text
string
label_name
string
labels
int64
#Laplacian Filter for Sharpening import cv2 import numpy as np import matplotlib.pyplot as plt def sharpen_image_custom(original_image, alpha=1.5): # Define a custom Laplacian kernel laplacian_kernel = np.array([[0, 1, 0], [1, -4, 1], [0, 1, 0]...
Python
1
"""preactresnet in pytorch [1] Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun Identity Mappings in Deep Residual Networks https://arxiv.org/abs/1603.05027 [2] Implementation https://github.com/weiaicunzai/pytorch-cifar100 """ from deeplite_torch_zoo.utils import load_pretrained_weights from deeplite_...
Python
1
), eps=0.1 / 255, hide_progress=args.hide_progress) accuracy_ASR = knn_monitor_with_netG(model.backbone, memory_loader, test_loader, device, netG, test_transform_solo_2st, poison_goal=9, ...
Python
1
impl<T: GetAllocator, const N: u64> Allocate for ArrayAllocator<T, N> { const N: u64 = N; #[inline(always)] unsafe fn free(&self, n: u64) { self.element_allocator.free(n); } #[inline(always)] fn allocate(&self, n: u64) -> u64 { self.element_allocator.allocate(n * N) } } i...
Rust
0
// except according to those terms. use back::abi; use llvm::ValueRef; use middle::subst::Substs; use middle::ty::{Ty, TypeFoldable}; use rustc::middle::const_eval::ConstVal; use rustc::mir::repr as mir; use trans::common::{self, BlockAndBuilder, C_bool, C_bytes, C_floating_f64, C_integral, C_str_...
Rust
0
"ko": "완료되었습니다.", }, "info_config_saved": { "en": "Arguments have been saved at: ", "ru": "Аргументы были сохранены по адресу: ", "zh": "训练参数已保存至:", "ko": "매개변수가 저장되었습니다: ", }, "info_config_loaded": { "en": "Arguments have been restored.", "ru": "Аргументы...
Python
1
header,nounits"], encoding="utf-8" ) # Take the first line and strip any leading/trailing white space first_line = output.strip().split("\n")[0] return int(first_line) except (subprocess.CalledProcessError, FileNotFoundError, ValueError): # If the command fails, nvidia-smi ...
Python
1
type Target = crate::FieldReader<u8, u8>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `DMA_APBPERI_AES_PMS_CONSTRAIN_SRAM_WORLD_0_PMS_2` writer - dma_apbperi_aes_pms_constrain_sram_world_0_pms_2"] pub struct DMA_APBPERI_AES_PMS_CONSTRAIN_SRAM_WORLD_0_PMS_2_W<...
Rust
0
, 5000.0] def calc_spec_smh(T, specs): """Calculate standard-state entropies minus enthalpies for all species. Parameters ---------- T : float Temperature of gas mixture. specs : list of SpecInfo List of species. Returns ------- spec_smh : list of float List o...
Python
1
{ pub cb: u32, pub dwTime: u32, pub hTask: super::super::Foundation::HANDLE, pub dwRet: u32, pub wType: u32, pub wFmt: u32, pub hConv: HCONV, pub hsz1: HSZ, pub hsz2: HSZ, pub hData: HDDEDATA, pub dwData1: usize, pub dwData2: usize, pub cc: CONVCONTEXT, pub cbDat...
Rust
0
cmp, mem }; use std::convert::TryInto; use std::os::unix::io::{ AsRawFd, RawFd }; use std::mem::ManuallyDrop; use bitflags::bitflags; use linux_io_uring_sys as sys; use util::{ Fd, Mmap }; use squeue::SubmissionQueue; use cqueue::CompletionQueue; pub use register::{ register as reg, unregister as unreg }; pub struct...
Rust
0
class TurnOffCommand: def __init__(self, light): self.light = light def execute(self): self.light.turn_off()
Python
1
ch.mean(torch.abs(sample)) assert abs(result_mean.item() - 0.7047) < 1e-3 def test_full_loop_no_noise_thres(self): sample = self.full_loop(thresholding=True, dynamic_thresholding_ratio=0.87, sample_max_value=0.5) result_mean = torch.mean(torch.abs(sample)) assert abs(result_mean.i...
Python
1
axiSlave.b.payload.hid <= 0 slaveHandle = SlaveHandle(idx,idToWrites) # Read StreamDriverSlave(axiSlave.ar, dut.clk, dut.reset) StreamDriverMaster(axiSlave.r, slaveHandle.genReadRsp, dut.clk, dut.reset) StreamMonitor(axiSlave.ar, slaveHandle.onReadCmd, dut.clk, dut.reset...
Python
1
pub fn new(index: u32) -> Self { let mut res = Self { path: format!("/sys/device/usbip/{}", index), bus_id: format!("{}", index), dev_num: index, speed: UsbSpeed::High as u32, ep0_in: UsbEndpoint { address: 0x80, attrib...
Rust
0
# The below script will ask for 3 inputs. Each input will be based # on the price of the items - the price is determined by you. The output # should print the total of the 3 inputs rounded to 2 decimal places e.g # # 1 coffee @ $ 2.00 # 1 sandwich @ $ 4.99 # 1 cake @ $ 2.75 # # Your total bill is $ 9.74 coffee...
Python
1
) | Loop(..) | Match(..) | Range(..) => (), _ => panic!( "Not available Rust expression in a template `each helper` argument:\n{}", quote!(#e) ), } } pub(super) fn unless(e: &syn::Expr) { use syn::Expr::*; match e { Binary(..) | Call(..) | MethodCall(..) | In...
Rust
0
FieldElement::from(u256h!( "01ef15c18599971b7beced415a40f0c7deacfd9b0d1819e03d723d8bc943cfca" )), FieldElement::from(u256h!( "005668060aa49730b7be4801df46ec62de53ecd11abe43a32873000c36e8dc1f" )), ); let b = ( Fiel...
Rust
0
start: [f32; 2] = [ -1.0 + 2.0 * (gui_state.mouse_drag_origin[0] / adjusted.logical_size[0]), -(-1.0 + 2.0 * (gui_state.mouse_drag_origin[1] / adjusted.logical_size[1])) ]; let drag_end = [ drag_start[0] + 2.0 * delta[0] / adju...
Rust
0
# oscs.py """ OSCS 开源安全情报 接口: https://www.oscs1024.com/oscs/v1/intelligence/list (POST, JSON) 功能: - fetch_oscs(date) —— 仍按日期抓取 (高危/严重) - search_oscs(keyword) —— 新增关键词 / CVE 搜索 """ from typing import List import random, time from models import VulnItem from utils import _session LIST_API = "https:/...
Python
1
"""The command for suspend a chore.""" from jupiter.core.domain.concept.chores.chore import Chore from jupiter.core.domain.features import WorkspaceFeature from jupiter.core.domain.storage_engine import DomainUnitOfWork from jupiter.core.framework.base.entity_id import EntityId from jupiter.core.framework.use_case imp...
Python
1
ookResult.success() async def demo_async_hooks(): """演示异步钩子系统的使用""" print("🎯 异步钩子系统演示") print("=" * 50) # 注册异步日志钩子 register_hook(HookEvent.BEFORE_AUTH_REQUEST, log_operation_async, priority=3) print("\n📋 已注册的异步钩子:") from bddriver.hooks import hook_manager print(f" 授权前钩子数量...
Python
1
+ Sync + 'static) = transmute(f); f(&RTSPClient::from_glib_borrow(this).downcast_unchecked()) } unsafe extern "C" fn notify_mount_points_trampoline<P>(this: *mut ffi::GstRTSPClient, _param_spec: glib_ffi::gpointer, f: glib_ffi::gpointer) where P: IsA<RTSPClient> { let f: &&(Fn(&P) + Send + Sync + 'static) = tr...
Rust
0
h_log_level if ( cloudwatch_logging and cloudwatch_log_level == "INFO" and "cloudwatch_logging" in aws_config ): cloudwatch_log_level = aws_config["cloudwatch_logging"].get( "log_level", cloudwatch_log_level ) # Check if AWS services are enabled but requi...
Python
1
responses` let read_status = |status_code: u16, response: Response| match status_code { 200 => Ok(()), 400 => { if let Ok(response_string) = response.into_string() { if response_string.contains("Invalid API") { return Err(Error:...
Rust
0
pub gc_state: Enum_gc_state, pub current_white_part: ::libc::c_int, pub gray_list: *mut Struct_RBasic, pub atomic_gray_list: *mut Struct_RBasic, pub gc_live_after_mark: size_t, pub gc_threshold: size_t, pub gc_interval_ratio: ::libc::c_int, pub gc_step_ratio: ::libc::c_int, pub gc_disabl...
Rust
0
OWER" print(f" {i}. {marker} {name}: {accuracy:.4f} ({accuracy*100:.2f}%) [{improvement}]") print(f" • F1-Macro: {f1_macro:.3f}") print(f" • Log Loss: {logloss:.3f}") print(f" • CV: {cv_mean:.3f} ± {cv_std:.3f}") print(f" • D...
Python
1
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: google/protobuf/any.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google....
Python
1
OUTPUT) .run(); } #[cargo_test] fn cargo_metadata_no_deps_path_to_cargo_toml_absolute() { let p = project() .file("Cargo.toml", &basic_bin_manifest("foo")) .file("src/foo.rs", &main_file(r#""i am foo""#, &[])) .build(); p.cargo("metadata --no-deps --manifest-path") .arg...
Rust
0
from sqlalchemy.orm import Session from typing import List, Optional from db.models.tables.entreprise.entreprise import Entreprise from db.schemas.entreprise.entreprise_schemas import * def create_entreprise(db: Session, data: EntrepriseCreate) -> Entreprise: obj = Entreprise(**data.dict()) db.add(obj) db....
Python
1
&config.server_signature, &config.api_key_id, &config.api_key_private_key, &config.api_key_secret_key, config.danger_disable_tls, ) } fn get_datastores(client: &ApiClient) -> Result<Vec<DataStore>, APIError> { let data_stores_list = client.get_all_datastores()?; let mut da...
Rust
0
= pending_transaction.outcome; receipt.output = pending_transaction.output; if blockchain_traits::Receipt::reverted(&receipt) { receipt.events.clear(); } else { self.state = pending_transaction.state; receipt.events.append(&mut pending_transaction.events); ...
Rust
0
"""Image Generation History Router""" import logging from fastapi import APIRouter, Depends, HTTPException, status from sqlalchemy.orm import Session from app.cores.model_manager import model_manager from app.database import database_service from app.database.crud import add_history, delete_history_entry, get_histor...
Python
1
# for i in range(9): # i = i + 1 # for j in range(i): # j = j + 1 # print(f'{i}*{j} = {i*j}',end=' ') # print('\n',end='') # l1 = [1,2,3,4,5] # for i in l1: # print(i,end=' ') # res = [] # for i in 'hello': # res.append(i*4) # print(res) # rest = [c*4 for c in 'hello'] # print(rest...
Python
1
s::{Vec2i, Vec2u}; use crate::impls::macos::{ffi, util}; use crate::monitor::{MonitorHandle, VideoMode}; #[derive(Clone)] pub struct VideoModeInner { pub(crate) size: Vec2u, pub(crate) bit_depth: u16, pub(crate) refresh_rate: u16, pub(crate) monitor: MonitorHandleInner, pub(crate) native_mode: Nat...
Rust
0
t of their channel chatbot = discuss_channel.sudo().chatbot_current_step_id.chatbot_script_id user_messages = discuss_channel.message_ids.filtered( lambda message: message.author_id != chatbot.operator_partner_id ) if user_messages: user_answer = user_messages.so...
Python
1
# Copyright 2006 Joe Wreschnig # # 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 Software Foundation; either version 2 of the License, or # (at your option) any later version. """ since 1.9: mutagen.m4a is deprecat...
Python
1
state).values() # # position, rotation = self.spot.get_base_transform_to("link_wr1") # gripper_transform = [position.x, position.y, position.z] + [ # rotation.x, # rotation.y, # rotation.z, # rotation.w, # ] # # msg.data = np.array( # ...
Python
1
}, { 'AcceptingNew': False, 'org': {'$in': list(user_dict['orgs'].keys())}, "$or": [ {'isActive': {"$exists": True, "$eq": True}}, {"isActive": {"$exists": False}} ], "role": {'$in': l...
Python
1
f64 = NAN; let inf: f64 = INFINITY; let neg_inf: f64 = NEG_INFINITY; let zero: f64 = 0.0f64; let neg_zero: f64 = -0.0; assert_eq!(nan.classify(), Fp::Nan); assert_eq!(inf.classify(), Fp::Infinite); assert_eq!(neg_inf.classify(), Fp::Infinite); assert_eq!(z...
Rust
0
.0 * PI)); let magnitude_range = Uniform::from(5.0..100.0); let mut rng = thread_rng(); for v in (&mut velocities).join() { v.heading = heading_range.sample(&mut rng); v.magnitude = magnitude_range.sample(&mut rng); } } } #![no_std] #![no_main] extern crate ...
Rust
0
if not osp.exists(save_folder): os.makedirs(save_folder) print(f'mkdir {save_folder} ...') else: print(f'Folder {save_folder} already exists. Exit.') sys.exit(1) img_list = list(scandir(input_folder, full_path=True)) pbar = tqdm(total=len(img_list), unit='image', desc='Ext...
Python
1
pointer")); } let (ptr_raw, _) = raw.split_at(std::mem::size_of::<u32>()); let ptr = u32::from_le_bytes(ptr_raw.try_into().unwrap()); Ok(ptr as usize) } fn parse_list(raw: &[u8]) -> anyhow::Result<&[u8]> { let mut i = 0; loop { if i >= raw.len() { return Err(anyhow!("truncat...
Rust
0
kwargs["mask"] else: mask = None bs = output.shape[0] probs = torch.softmax(output, dim=1) predicted = torch.argmax(probs, dim=1) gt_label = torch.argmax(target, dim=1) x,y,z = torch.meshgrid(torch.arange(bs),torch.arange(256),torch.arange(256)) predicted_probabilities = probs[x, p...
Python
1
# Função ascii() em Python """ A função built-in ascii() retorna uma versão “escapada” de um objeto string, onde **caracteres não ASCII** são convertidos para sequências de escape Unicode. Útil para visualizar strings com acentos, emojis, símbolos e caracteres internacionais. """ # Exemplo com string com acentos tex...
Python
1
of stereo data for cideo frames"] #[doc = ""] #[doc = " To set the format of the output, simply set the values of the corresponding fields in the output frame"] pub fn dc1394_deinterlace_stereo_frames( in_: *mut dc1394video_frame_t, out: *mut dc1394video_frame_t, method: dc1394stere...
Rust
0
; println!("seller id: {}", env.seller_id); println!("region id: {}", env.region_id); let client = get_client(&env); match opt.cmd { Command::ReportRequest { report_type, start_date, end_date, report_options, marketplace_id_list, } => { use mws::reports::*; l...
Rust
0
print 'machine number:', machine_num print 'pending task number', len(pending_task) print 'total revenue:', revenue print 'total cost:', vm_cost_per_hour * machine_num print 'total profit:', revenue - vm_cost_per_hour * machine_num ''' #print len(pending_task) #print rate, '\t', machine_num...
Python
1
iar_id).exists(): logger.warning(f"{PROJECT_NAME} {EMPIAR_ENTRY_FILE(empiar_id)} does not exist, skip saving EMDB entries") continue emdb_cross_references: list[str] = read_list_safely(load_empiar_entry(empiar_id), "cross_references") for emdb_id in emdb_cross_references: ...
Python
1
etY()) B1 = (tr_p1.getX() - tr_p2.getX()) C1 = tr_p1.getY()*(tr_p2.getX() - tr_p1.getX()) - tr_p1.getX()*(tr_p2.getY() - tr_p1.getY()) for m in range(5): for n in range(m + 1, 5): pnP1 = pn.getPoints()[m] pnP2 = pn.getPoints()[n...
Python
1
) .arg( Arg::new("disk_lsn") .short('d') .long("disk_lsn") .takes_value(true) .help("Replace disk constistent lsn"), ) .arg( Arg::new("prev_lsn") .short('p') .long("prev_lsn")...
Rust
0
""" * PyDMXControl: A Python 3 module to control DMX using OpenDMX or uDMX. * Featuring fixture profiles, built-in effects and a web control panel. * <https://github.com/MattIPv4/PyDMXControl/> * Copyright (C) 2018 Matt Cowley (MattIPv4) (me@mattcowley.co.uk) * * This program is free software: ...
Python
1
`. Self::new(indices) } } } impl<Din, Dout> TryFrom<Vec<SliceInfoElem>> for SliceInfo<Vec<SliceInfoElem>, Din, Dout> where Din: Dimension, Dout: Dimension, { type Error = ShapeError; fn try_from( indices: Vec<SliceInfoElem>, ) -> Result<SliceInfo<Vec<SliceInfoElem>,...
Rust
0
will go in. for frag in &frags.frags { // BEGIN check `frag` for any overlap against `tree`. let mut root = tree.root; while root != AVL_NULL { let root_node = &tree.pool[root as usize]; let root_frag = root_node.item.clone(); if frag.last < root_frag.fir...
Rust
0
ngs, tokenize_sentence, lang, sentiment, mwt_expand, pos, dependency_tree}; # [test] // before use the rsnltk library, you need to download target language package from Stanza's website. fn test_download_langs(){ // 1. first install the package let list_lang=vec!["en","zh"]; download_la...
Rust
0
except Exception as e: raise HTTPException(status_code=400, detail=str(e)) @router.post("/users/reject/friend", responses = {200 : {"model" : CommoneResponse, "description" : "친구 요청 거절 성공"}, 400 : {"model" : Error_response, "description" : "친구 요청 거절 실패"}}, tags = ["User/friend"], summary = "친구 요청 거절") asyn...
Python
1
ger sound file: import time # pylint: disable=import-outside-toplevel sound_object = SoundObject( '/home/mfabian/sounds/japanese/今回もよろしくお願いします.wav', audio_backend=audio_backend) sound_object.play() LOGGER.info('Sleeping ...') time.sleep(1) LOGGER.info('is playing %s', sound_obj...
Python
1
hreshold=threshold, max_convex_hull=max_convex_hull, preprocess_mode=preprocess_mode, preprocess_resolution=preprocess_resolution, resolution=resolution, mcts_nodes=mcts_nodes, mcts_iterations=mcts_iterations, mcts_max_depth=mcts_max_depth, pca=pca, ...
Python
1
lsif::Edge::Next(lsif::EdgeData { in_v: result_set_id.into(), out_v: range_id.into(), })); range_id.into() }) .collect(); self.add_edge(lsif::Edge::Contains(lsif::EdgeDataMultiIn { in_vs: tokens_id, ...
Rust
0
ash as specified for the Zcash consensus rules. It can //! verify solutions for any valid `(n, k)` parameters, as long as the row indices are no //! larger than 32 bits (that is, `ceiling(((n / (k + 1)) + 1) / 8) <= 4`). //! //! References //! ========== //! - [Section 7.6.1: Equihash.] Zcash Protocol Specification, ve...
Rust
0
from pathlib import Path import json import argparse # Recursive function to find missing keys in dictionaries def find_missing_keys(base_dict, other_dict): missing_keys = {} for key in base_dict: if key not in other_dict: missing_keys[key] = base_dict[key] elif isinstance(base_dict...
Python
1
if let Some(exclude) = exclude { let mut new = exclude; new.name = alias.clone(); self.markers.exclude.subtargets.push(new); } } Ok(()) } } impl Normalize for Part { fn normalize(&mut self) -> Result<(), String> { self.markers....
Rust
0
.get(SupportedBlockchain.BITCOIN_CASH) == (UNIT_BTC_ADDRESS1,) # noqa: E501 response = requests.delete( api_url_for( rotkehlchen_api_server, 'chaintypeaccountresource', chain_type=ChainType.EVM.serialize(), ), json={ 'chain_type': ChainType.E...
Python
1
]); fn create<A: Attribute>(b: &BuffConfig) -> Box<dyn Buff<A>> { let element = match *b { BuffConfig::SucroseC6 { element } => element, _ => Element::Electro }; Box::new(BuffSucroseC6 { element }) } } <reponame>eliben/code-for-blog<filename...
Rust
0
rint('Kpp=', round(np.mean(KPP_ALL) * 100, 2), '+-', round(np.std(KPP_ALL) * 100, 2)) print('Acc per class=', np.mean(EACH_ACC_ALL, 0), '+-', np.std(EACH_ACC_ALL, 0)) print("Average training time=", round(np.mean(Train_Time_ALL), 2), '+-', round(np.std(Train_Time_ALL), 3)) print("Average testing time=", ro...
Python
1
ecifier { Some(specifier) => { let id = &specifier.id_lit; quote! { #id } }, None => { quote!{ dacquiri::prelude::DEFAULT_ATTRIBUTE_TAG } } }; let type_bound: TypeParamBo...
Rust
0
import os import shutil import pandas as pd # 🔧 Konfiguracja CSV_FILE = "dataset.csv" SOURCE_IMAGE_DIR = "scans" OUTPUT_CARD_DIR = "dataset_card" OUTPUT_TYPE_DIR = "dataset_type" # 📥 Wczytaj dane df = pd.read_csv(CSV_FILE) # 📁 Utwórz foldery wyjściowe os.makedirs(OUTPUT_CARD_DIR, exist_ok=True) for type_name in [...
Python
1
"""Behavioral metrics calculated from sensor datasets.""" from __future__ import annotations from typing import Dict import logging import pandas as pd logger = logging.getLogger(__name__) def calculate_behavioral_metrics(data: pd.DataFrame) -> Dict: """Calculate basic behavioral pattern metrics from sensor d...
Python
1
demo(client: Client): return await self.page(client, NiceGuiWidgetsDemo.show_tristate_demo) @ui.page("/pdfviewer") async def show_pdf_viewer(client: Client): return await self.page(client, NiceGuiWidgetsDemo.show_pdf_viewer) @ui.page("/issue1786") async def show...
Python
1
mod controller; pub mod schema; mod service; type SqliteModule = DieselPoolModule<SqliteConnection>; #[module] #[import(SqliteModule)] #[provider(BookService)] #[controller(BookController)] struct AppModule; #[contraband::main] async fn main() -> std::io::Result<()> { ContrabandApp::new().start::<AppModule>()....
Rust
0
# MAKE_REFLEXION_PROMPT ='''I failed in the former tries, and I need to rethink the task. # Then I will analyze the steps I took former and tell the reason I failed in the last try. I will make a reflexion. # The "Reflexion" ends with pattern "END REFLEXION" # Reflexion: ''' MAKE_REFLEXION_PROMPT=''' {task_description...
Python
1
instance.add_ref(); let hr = unsafe { instance.query_interface(riid, ppv) }; unsafe { instance.release() }; Box::into_raw(instance); hr } #[macro_export] macro_rules! inproc_dll_module { (($clsid_one:ident, $classtype_one:ty), $(($clsid:ident, $classtype:ty)),*) => { #[no_mangle] ...
Rust
0
EP_ENABLE { if val & BITMASK_PM1CNT_SLEEP_TYPE == SLEEP_TYPE_S5 { if let Err(e) = self.exit_evt.write(1) { error!("ACPIPM: failed to trigger exit event: {}", e); } } else if let Err(e) = self.suspend_evt....
Rust
0
PublicIpAddresses") self._Description = params.get("Description") self._NatGatewaySnatId = params.get("NatGatewaySnatId") self._NatGatewayId = params.get("NatGatewayId") self._VpcId = params.get("VpcId") self._CreatedTime = params.get("CreatedTime") memeber_set = set(para...
Python
1
ier(embedding,align_image_path, uuid,current_groupid,img_style,number_people,trackerId,json_data,forecast_result) else: print('Skip SoftMax/SVM') json_data, forecast_result = use_db_detect(current_groupid, uuid, embedding, ...
Python
1
self } } <gh_stars>1-10 use std::io::Error; use crate::circle; use crate::circle::circle::Circle; use crate::shape::shapes::Shape; use crate::square::square::Square; use sdl2::event::Event; use sdl2::keyboard::Keycode; use sdl2::gfx::primitives::DrawRenderer; use sdl2::pixels::Color; use sdl2::rect; use sdl2::...
Rust
0
: usize) { let mut rh = self.regs.lock(); log_debug!("Disable {}: Info = {:#x}", idx, rh.read(0x10 + idx*2)); rh.write(0x10 + idx*2 + 0, 1<<16); } pub fn get_irq_reg(&self, idx: usize) -> u64 { let mut rh = self.regs.lock(); (rh.read(0x10 + idx*2 + 0) as u64) | (rh.read(0x10 + idx*2 + 1) as u64) << 32...
Rust
0
assert_eq!(reply.attr.ino, ino); // forget does not return a Result fusefs.forget(request, ino, 1).now_or_never().unwrap(); assert!(!fusefs.files.lock().unwrap().contains_key(&ino)) } } mod fsync { use super::*; #[test] fn eio() { let ino = 42; let fh = 0...
Rust
0
ration) % (end * 2.0); if local_time > *end { local_time = 2.0 * end - local_time; }; local_time }, Play::BounceForever {end, duration, ..} => { let mut local_time = (time / duration) % (end * 2.0); ...
Rust
0
Toggle disabled. newFaceID = self.getCurrentFace().getFaceID() ^ self.DISABLED_ATTRIBUTE # Remove hovering. newFaceID &= ~self.HOVERING_ATTRIBUTE # Sets the current face. self.setCurrentFaceFromID(newFaceID) def toggleHover(self): """Toggle the hovering attribute....
Python
1
ingAggregationInterval(parser, messages): GetLoggingAggregationIntervalArg(messages).choice_arg.AddToParser(parser) def GetLoggingAggregationIntervalArgDeprecated(messages): return arg_utils.ChoiceEnumMapper( '--aggregation-interval', messages.SubnetworkLogConfig.AggregationIntervalValueValuesEnum, ...
Python
1
else: text_encoder_conds = self.get_text_cond( args, accelerator, batch, tokenizers, text_encoders, weight_dtype ) # Sample noise, sample a random timestep for each image, and add noise to the latents...
Python
1
import sys import types from pathlib import Path from typing import Any, _GenericAlias # type: ignore [attr-defined] from typing_extensions import get_origin _PATH_TYPE_LABELS = { Path.is_dir: 'directory', Path.is_file: 'file', Path.is_mount: 'mount point', Path.is_symlink: 'symlink', Path.is_blo...
Python
1
.powf(n) / (2. * n + 1.)) .sum() } <filename>fuzz/fuzzers/basic_fuzz.rs #![no_main] #[macro_use] extern crate libfuzzer_sys; extern crate hopper; extern crate tempdir; use std::str; use std::str::FromStr; fuzz_target!(|data: &[u8]| { let dir = tempdir::TempDir::new("hopper").unwrap(); let (mut snd, mu...
Rust
0
rts it. If the host doesn't support it then // print a warning and return an error because this fuzz // input must be discarded. #[cfg(target_arch = $arch)] if enable && !std::$test!($std) { log::...
Rust
0
x_max_m, y_max_m = max_coords_meters x_min_p, y_min_p = min_coords_pixels x_max_p, y_max_p = max_coords_pixels # Calculate the width and height of the bounding box in meters w_m = x_max_m - x_min_m h_m = y_max_m - y_min_m # Calculate the width and height of the bounding box in pixels ...
Python
1
height: 720.0, title: String::from("UI Example"), ..Default::default() }) .add_plugins(DefaultPlugins) .add_plugin(BevyKayakUIPlugin) .add_startup_system(startup) .run(); } //! Generators may generate bytes or, in general, data, for inputs. us...
Rust
0
emaining -= num_bytes as u64; if self.chunk_buffer.len() == consts::CHUNK_SIZE { self.emit_chunk()?; } } if self.total_uncompressed_bytes_remaining == 0 && !self.chunk_buffer.is_empty() { self.emit_chunk()?; } Ok(byt...
Rust
0
L 2005 865 858 79 162 0 # 8 TEX AL 2004 860 794 89 162 0 # 9 TEX AL 2003 826 969 71 162 0 # 10 TEX AL 2002 843 882 72 162 0 # 11 TEX AL 2001 890 968 73 162 0 # 12 TEX AL 2000 848 974 71 162 0 # 13 TEX AL 1999 ...
Python
1
dered_prims_offset, bit_index - 1); } // Find LBVH split point for this dimension let mut search_start = 0_usize; let mut search_end = n_primitives - 1; while search_start + 1 != search_end { let mid = (search_start + searc...
Rust
0
ive(&id_1)); } #[test] pub fn retired_id_is_not_active() { let id_1 = id(b"id01"); let mut random_generator = random::testing::Generator(123); let mut mapper = ConnectionIdMapper::new(&mut random_generator, endpoint::Type::Server); let mut reg = mapper .create_server_peer_id_registry(InternalCo...
Rust
0
if not buf: status = STATUS_LAST_FRAME # 第一帧处理 # 发送第一帧音频,带business 参数 # appid 必须带上,只需第一帧发送 if status == STATUS_FIRST_FRAME: d = {"common": wsParam.CommonArgs, "business": wsParam.BusinessAr...
Python
1
]), } } async fn url_contents(url: &Url) -> Result<InputContent> { let res = reqwest::get(url.clone()).await?; let content = res.text().await?; let input_content = InputContent { input: Input::RemoteUrl(url.clone()), file_type: FileType::from(url.as_str()...
Rust
0
', '🔯', '🂱', 'ﭚ', 'ԣ', 'ᕃ', '包', '𞢂', 'ᯑ', '𐌙', '⯳', 'Ⴡ', 'ϥ', 'Ṛ', '𐦼', '\u{e93}', '⒔', '\u{f76}', '𒋛', 'ਮ', 'Յ', 'ᬠ', '𐒱', '🀣', '𝇚', '⯨', '🤒', '🁁', 'Ⓕ', '/', '☯', '𝦧', '𑨣', '𛃖', '𛂔', '𐤶', '𐄜', '⊂', 'ጆ', '\u{332}', '𝤿', '\u{1de9}', 'ハ', 'ꔧ', '𖤗', 'ꡓ', '𛀦', 'ꛕ', 'ヰ', '\u{11369}', '\u...
Rust
0
ressed = self.compress(); size += writer.write(compressed.as_slice())?; for node in self.nodes.iter() { size += Serialize::serialize(&node.hash, writer)?; } Ok(size) } fn serialized_size(&self) -> usize { let mut size = /*count*/ 1; size += self.node...
Rust
0
ouse_wheel(&mut self, delta: i16, x: i32, y: i32, ctrl_is_down: bool) { let delta = delta as f32 / 120.0 / 10.0; if ctrl_is_down && self.highlighter.is_enabled() { self.highlighter .set_radius(self.highlighter.radius() * (1.0 + delta * 2.0)); return; ...
Rust
0
am.getvalue() # Check that it printed pat = "dump refct of {}" aryty = types.float64[::1] tupty = types.Tuple.from_types([aryty] * 2) self.assertIn(pat.format(aryty), output) self.assertIn(pat.format(tupty), output) class TestZeroCounts(TestCase): def test_zero_coun...
Python
1
pc.offset(0 as i32 as isize); ahi = c - abig; alo = *pc.offset(0 as i32 as isize) - ahi; c = splitter * *pb.offset(1 as i32 as isize); abig = c - *pb.offset(1 as i32 as isize); bhi = c - abig; blo = *pb.offset(1 as i32 as isize) - bhi; err1 = cxby1 - ahi * bhi; err2 = err1 - alo * bhi; ...
Rust
0
"CREATE TYPE "myEnum" AS ENUM ()"#); } #[test] fn create_enum_with_variants() { let variants = vec!["One".into(), "Two".into(), "Three".into()]; let create_enum = CreateEnum { enum_name: "myEnum".into(), variants, }; assert_eq!( create_en...
Rust
0
import unittest from ctypes import Structure, Union, sizeof, c_char, c_int from ._support import (CField, Py_TPFLAGS_DISALLOW_INSTANTIATION, Py_TPFLAGS_IMMUTABLETYPE) class StructFieldsTestCase(unittest.TestCase): # Structure/Union classes must get 'finalized' sooner or # later, when on...
Python
1