text
string
label_name
string
labels
int64
,raw: &[u8]) { /* initialise from at least 128 byte string of raw random entropy */ let mut b: [u8;4]=[0;4]; let mut sh=HASH256::new(); self.pool_ptr=0; for i in 0..RAND_NK {self.ira[i]=0} if rawlen>0 { for i in 0..rawlen { sh.process(raw[i]); } let digest=sh.hash(); /* initialise PRNG from dis...
Rust
0
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Copyright 2024 Alibaba Group Holding Limited. 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...
Python
1
try!(nix::mount::mount( source, &self.path, filesystem, nix::mount::MS_REMOUNT | self.flags, opts )); } Ok(()) } } pub fn default_mounts() -> Vec<Mount<'static>> { vec![ Mount::new( ...
Rust
0
a mut NamedView { match self { ViewWithParentMut::Root { frame } | ViewWithParentMut::Child { frame, .. } => frame, } } } impl ViewForest { pub fn index(&self, ix: &ViewForestIndex) -> Option<ViewWithParent> { let tree = self.trees.get(ix.tree)?; tree.index(&ix.withi...
Rust
0
default_app_config = "core.employees.apps.EmployeesConfig"
Python
1
handle_cleanup(self, options): """Limpa cache e arquivos temporários.""" deep = options.get('deep', False) self.stdout.write(self.style.SUCCESS("=== LIMPEZA DO SISTEMA ===")) cleaned_items = [] # Limpar cache Redis try: cache.clear() cleaned_ite...
Python
1
oid = np.mean(features[idx], axis=0) # assign labels labels[idx] = count row_sum -= np.sum(similarities[:, idx], axis=1) row_sum[idx] = -100 # remove bins that are too small unique, counts = np.unique(labels, return_counts=True) for i, c in zip(unique, counts):...
Python
1
# Copyright (C) 2023-present The Project Contributors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law o...
Python
1
(RequestError::PayloadConversion)?; request = request .cache(RequestCache::NoCache) .redirect(RequestRedirect::Follow) .mode(RequestMode::Cors); Ok(request.send(handler)) } } impl AuthenticatedBackend { pub fn request<S, IN, H>( &self, metho...
Rust
0
('last_modified_by', models.ForeignKey(blank=True, related_name='work_groups_workgroup_modified', to=settings.AUTH_USER_MODEL, null=True, on_delete=models.CASCADE)), ('members', models.ManyToManyField(related_name='working_groups', to=settings.AUTH_USER_MODEL)), ('organizer...
Python
1
"""coBib's main content view. This is a simple subclass of textual's `ContentSwitcher` widget. Any widget mounted into it is expected to have a `get_current_label` method implement (although this is currently not programmatically enforced). For examples refer to `cobib.ui.components.list_view.ListView` and `cobib.ui.c...
Python
1
_tm_mday: ::libc::c_int, pub __tm_mon: ::libc::c_int, pub __tm_year: ::libc::c_int, pub __tm_wday: ::libc::c_int, pub __tm_yday: ::libc::c_int, pub __tm_isdst: ::libc::c_int, } #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct _on_exit_args { pub _fnargs: [*mut ::libc::c_void; 32usize], pu...
Rust
0
#BandpassPlugin\0"; pub const LV2_CORE__CVPort: &'static [u8; 36usize] = b"http://lv2plug.in/ns/lv2core#CVPort\0"; pub const LV2_CORE__ChorusPlugin: &'static [u8; 42usize] = b"http://lv2plug.in/ns/lv2core#ChorusPlugin\0"; pub const LV2_CORE__CombPlugin: &'static [u8; 40usize] = b"http://lv2plug.in/ns/lv2core#Co...
Rust
0
def _interp_evaluate(coefficients, t0, t1, t): """Evaluate polynomial interpolation at the given time point. Args: coefficients: list of Tensor coefficients as created by `interp_fit`. t0: scalar float64 Tensor giving the start of the interval. t1: scalar float64 Tensor giving the end o...
Python
1
("Download Script"): save_to_file(json.dumps(script, indent=2), "channel_trailer_script.json") with col2: if st.button("Download Visuals"): # Save visuals logic here pass def get_audio_player_html(audio_bytes: bytes) -> str: """Generate HTML for audio player with the...
Python
1
: Vec<u32>, pub position: cgmath::Vector3<f32>, pub fov: [f32; 2], pub sensitivity: f32, pub fps_update_interval: i64, pub log_level: vulkano::instance::debug::MessageTypes, pub benchmark: bool, } fn is_supported_model_format(val: String) -> Result<(), String> { const SUPPORTED_FORMATS: &[&...
Rust
0
and check if leads to an audio or a video stream //! If so, then it will extract information about the stream from its metadata or in case of HLS streams //! from its master playlist file. extern crate hls_m3u8; #[macro_use] extern crate log; extern crate native_tls; extern crate playlist_decoder; extern crate reqwest...
Rust
0
t_move_things_with_object_parents() { let mut tree = Tree::new_with_object_root(MyId(0)); tree.update(&Edit::MapCreate { id: value::ObjectRef(MyId(1)), }) .unwrap(); tree.update(&Edit::MapInsert { parent: value::ObjectRef(MyId(0)), key: "my key".to_string(), item: Val...
Rust
0
/ The '6' key over the letters. Key6, /// The '7' key over the letters. Key7, /// The '8' key over the letters. Key8, /// The '9' key over the letters. Key9, /// The '0' key over the 'O' and 'P' keys. Key0, A, B, C, D, E, F, G, H, I, J, K,...
Rust
0
idx].first; } } // FIXME: should be replaced by overflowgid/overflowuid 65_534 } } use std::env; use std::ops::{Deref, DerefMut}; use std::path::PathBuf; use std::process; use anyhow::{Context, Result}; use clap::Parser; use crate::common::XWinOptions; use crate::Build; /// Ex...
Rust
0
loc=3) is False assert self.simple_runner(['-100'], loc=4) is False def test_evaluate_python_doc_example_12(self): # >>> a = 'abcde' # >>> a[10] # out of range references == False # IndexError # Here GristleSlicer is different than Python - and returns a false ...
Python
1
); assert_eq!(pin.is_low().unwrap(), true); pin.is_low().expect_err("expected error return"); pin.done(); } #[test] fn test_output_pin() { let expectations = [ Transaction::new(Set(State::High)), Transaction::new(Set(State::Low)), Transa...
Rust
0
lf, KeyI32, MyPageAuth>) -> RspEventHandlerResult<Self, KeyI32> { let mut action = rsp10::RspAction::Render; let mut initial_state = ri.initial_state; let mut state = ri.state; if ri.event.event == "submit" { state.message = "".to_string(); if !ri.state_none { ...
Rust
0
class HTMLNode: def __init__(self, tag=None, value=None, children=None, props=None): self.tag = tag self.value = value self.children = children self.props = props def __eq__(self, node): if ( self.tag == node.tag and self.value == node.value ...
Python
1
u16, pub length: u32, pub x: Int16, pub y: Int16, pub width: Card16, pub height: Card16, pub xhot: Card16, pub yhot: Card16, pub cursor_serial: Card32, pub cursor_image: Cow<'a, [Card32]>, } impl<'a> GetCursorImageReply<'a> {} impl<'a> AsByteSequence for GetCursorImageReply<'a> { ...
Rust
0
rd({ "ts_code": ann['ts_code'], "title": ann['title'], "doc_type": doc_type, "start_time": time.time() - sum(stages.values()), "stages": stages, "success": success, "chunks_count": chunks_count if success else 0, "error": er...
Python
1
g to {} {}...", collection, namespace); info!("Trying to {} {}...", collection, namespace); match query_known_namespace(&http_client, &mongo_client, collection, &namespace, true) { Ok(()) => { println!("Ok."); ...
Rust
0
n GPU memory. /// /// * `work_space` - buffer in GPU memory to store temporary data. /// /// * `reserve_space` - reserve-space buffer in GPU memory. /// /// # Errors /// /// Returns errors is an unsupported arguments combination is detected or if the supplied /// buffers are too smal...
Rust
0
_x64_register_intercept_message), "::", stringify!(register_name) ) ); assert_eq!( unsafe { &(*(::std::ptr::null::<hv_x64_register_intercept_message>())).access_info as *const _ as usize }, 48usize, concat!( ...
Rust
0
series_trig(): assert cancel(gruntz(1/log(atan(x)), x, oo) - 1/(log(pi) + log(S(1)/2))) == 0 assert gruntz(1/acot(x), x, -oo) == -oo def test_exp_log_series(): assert gruntz(x/log(log(x*exp(x))), x, oo) == oo def test_issue545(): assert gruntz(((x**7 + x + 1)/(2**x + x**2))**(-1/x), x, oo...
Python
1
(i, j); } } impl<T> Swap for [T] { #[inline] fn len(&self) -> usize { self.len() } #[inline] fn swap(&mut self, i: usize, j: usize) { self.swap(i, j); } } impl<'a, V: HasDrop> Swap for SliceMut<'a, V> { #[inline] fn len(&self) -> usize { SliceMut::len(self) ...
Rust
0
= "mdc-drawer-app-content"> <header id = "app-bar" class = "mdc-top-app-bar mdc-top-app-bar--fixed drawer-top-app-bar"> <div class = "mdc-top-app-bar__row"> <section class = "mdc-top-app-bar__section mdc-top-app-bar__section--align-start"> ...
Rust
0
mut c_longlong, locking_script: *mut *mut c_char, ) -> c_int; pub fn CfdGetTxInCount( handle: *const c_void, network_type: c_int, tx_hex: *const i8, count: *mut c_uint, ) -> c_int; pub fn CfdGetTxInWitnessCount( handle: *const c_void, network_type: c_int, tx_hex: *const i8, i...
Rust
0
thor(s) have dedicated all // copyright and related and neighboring rights to this software to // the public domain worldwide. This software is distributed without // any warranty. mod bech32; mod descriptor; mod rpc; pub mod signer; mod types; mod util; pub use self::bech32::*; pub use descriptor::*; pub use rpc::*;...
Rust
0
is variant requires a byte string in python 2. self.assertIs(import_object(u"tornado.escape"), tornado.escape) class ReUnescapeTest(unittest.TestCase): def test_re_unescape(self): test_strings = ("/favicon.ico", "index.html", "Hello, World!", "!$@#%;") for string in test_strings: ...
Python
1
tests { use super::*; #[test] fn test_part_one() { let input = r#"0: 3 1: 2 4: 4 6: 4"#; assert_eq!(0, get_position_for_range_after(3, 0)); assert_eq!(1, get_position_for_range_after(3, 1)); assert_eq!(2, get_position_for_range_after(3, 2)); assert_eq!(1, get_posit...
Rust
0
), &Context::Alternate(ref context)) => { device.get_proc_address(context, symbol_name) } _ => panic!("Incompatible context!"), } } /// Returns a unique ID representing a context. /// /// This ID is unique to all currently-allocated contexts. If you destr...
Rust
0
_handler = EventHandler::new(); let mut subscriber = event_handler.subscribe(); let client = EventClient::with_additional_options( Some(options), Some(Duration::from_millis(50)), None, event_handler.clone(), ) .await; if !VersionReq::parse(">= 4.2.9") .unwra...
Rust
0
f32], vector![0.0_f32, 2.0_f32]), (vector![0.0_f32, 2.0_f32], vector![2.0_f32, 2.0_f32]), (vector![2.0_f32, 2.0_f32], vector![2.0_f32, 0.0_f32]), (vector![2.0_f32, 0.0_f32], vector![1.0_f32, 0.0_f32]), (vector![1.0_f32, 0.0_f32], vector![1.0_f32, 1.0_f32]) ]; // スタート時点のリンクは0番...
Rust
0
"""A tracer that collects all nested runs in a list.""" from typing import Any, List, Optional, Union from uuid import UUID from langchain_core.tracers.base import BaseTracer from langchain_core.tracers.schemas import Run class RunCollectorCallbackHandler(BaseTracer): """ Tracer that collects all nested run...
Python
1
t test_data_string_3_byte = b"37f495"; let test_data_string_4_byte = b"8642dc59"; let test_data_string_5_byte = b"153fb79826"; let test_data_string_6_byte = b"0932e6246c47"; let test_data_string_7_byte = b"ab427ea8d10fc7"; test_one!(seed_1, test_data_string_0_byte, 0x30ED35C100C...
Rust
0
"""Slack bot user joined team handler using templates.""" import logging from apps.slack.constants import ( OWASP_APPSEC_CHANNEL_ID, OWASP_ASKOWASP_CHANNEL_ID, OWASP_CHAPTER_LONDON_CHANNEL_ID, OWASP_COMMUNITY_CHANNEL_ID, OWASP_CONTRIBUTE_CHANNEL_ID, OWASP_DEVELOPERS_CHANNEL_ID, OWASP_DEVSE...
Python
1
<KEY>" ), ( // Len = 1112 "<KEY>", (64, 45, [0xb245dc1f12e87062, 0x02ac20dc816001d7], [0x05baeec439d3b01f, 0xd8ddbe81ba47e5ab]), "<KEY>" ), ( // Len = 1120 "<KEY>", (64, 57, [0x21b3712ee5aeb53f, 0xb3790d1c0b81d928], [0xb7e3036f98879201, 0xd50c4639920a01fa]), "19e25b66f67d561c3b59c3ef6f08d7d86e1dd270...
Rust
0
spans: RefCell<Vec<SpanStorage>>, spans_map: RefCell<HashMap<SpanStorage, Span>>, filenames: RefCell<Vec<Rc<str>>>, filenames_map: RefCell<HashMap<Rc<str>, Filename>>, required: RefCell<HashSet<PathBuf>>, rclasses: RefCell<HashMap<TypeId, Rc<RClass>>>, rclass_names: RefCell<HashSet<Sym>>...
Rust
0
# Създай клас Account, който има private атрибут __balance. # Добави методи deposit(amount) и get_balance(). # ---------------------------------------------------------- class Account: def __init__(self, initial_balance=0): self.__balance = initial_balance # self атрибут за баланса def deposit(self...
Python
1
r"([\w-]+\.)+[\w-]+(:\d+)?", r"\d{2}:\d{2}(:\d{2})*", r"[KGTM]B", ], "max_dist": 0.002, "k": 1, "levels": 2, }, "OpenSSH": { "log_file": "OpenSSH/OpenSSH_2k.log", "log_format": "<Date> <Day> <Time> <Component> sshd\[<Pid>\]: <Content>...
Python
1
"""added weapons most killed and death by Revision ID: d6da533e38e1 Revises: ec5fc1135ddb Create Date: 2021-05-09 22:49:41.244941 """ import sqlalchemy as sa from alembic import op from sqlalchemy.dialects import postgresql # revision identifiers, used by Alembic. revision = "d6da533e38e1" down_revision = "ec5fc113...
Python
1
.dltdescr); println!(); } pub(crate) fn print_arg_list(&self) { self.args.iter().for_each(IfArg::print_arg); } } use bitflags::bitflags; // bit flag for page permission bitflags! { pub struct PteFlag: u64 { const PTE_VALID = 0x01; const PTE_READ = 0x02; ...
Rust
0
) simulation_env_config.simulation_env_input_config.stopping_game_config.R = list(StoppingGameUtil.reward_tensor( R_INT=-1, R_COST=-2, R_SLA=0, R_ST=20, L=3)) agent = TSPSAAgent(emulation_env_config=emulation_env_config, simulation_env_config=simulation_env_config, experiment...
Python
1
self.style.modification ) } } } pub struct DiffStyle { pub is_ansi_color: bool, pub from: CharStyle, pub to: CharStyle, } impl fmt::Display for DiffStyle { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if self.from.fg != self.to.fg { if self....
Rust
0
s='Pending') new_term.status='New' new_term.update_action=0 new_term.save() terms = new_term.payment_term start_date=date.today() days=int(terms.days) end= date.today() + timedelta(days=days) End_date=end company = CompanyDetails.objects.get(id=cid) company.payment_term=terms company.s...
Python
1
ow = amount.low; key_high = amount.high; } soundfont::data::GeneratorType::VelRange => { let amount = new_gen.amount.as_range().unwrap(); vel_low = amount.low; vel_high = amount.high; } _ => { // FIXME: some generators hav...
Rust
0
test)] mod tests { use std::usize; use super::super::tree::Tree; use super::*; use crate::test_utils::*; use crate::tree::{NoopCommit, PanicSource, Tree as BaseTree}; #[derive(Default)] struct NodeCounts { hash: usize, kvhash: usize, kv: usize, } fn count_n...
Rust
0
f"Peer {fp.id} from {c.Name} failed {job.Action}ed." ) else: current_app.logger.warning(f"Somehow can't find this peer {job.Peer} from {c.Name} failed {job.Action}ed.") self.JobLogger.log(j...
Python
1
-planet.n_ships def update_planets(self, pending: Dict[int, Dict[Player, float]]): for planet in self.state.planets: p_pending = pending.get(planet.id) if planet.owner == Player.Neutral: self.update_neutral_planet(planet, p_pending) else: ...
Python
1
parameters.n).collect(); let y: Vec<f64> = stats.iter().map(|s| s.load.mean).collect(); let err: Vec<f64> = stats.iter().map(|s| s.load.variance).collect(); let min_loads: Vec<u64> = stats .iter() .map(|s| s.load.min.try_into().unwrap()) .collect(); let max_loads: Vec<u64> = stat...
Rust
0
.into_iter()) .collect::<Vec<_>>(), &alphas, &domain_final, &final_polynomial, ); // TODO: do not panic. Use customized error assert!(result); Ok(()) }) }...
Rust
0
}); delta } /** A tree widget. Depending on its internal `expanded` state (see [`Frame.is_expanded`](struct.Frame.html#method.is_expanded), this widget will either show both its `title` and `children` widgets, or just its `title` widgets. It is intended that you use [`hei...
Rust
0
new_value = self.cells.get(parent.0)?.value(&self.cells)?; let cell = self.cells.get_mut(parent.0)?; if let Cell::Compute { value, callbacks, parents, .. } = cell { if new_value != *value { *value = new_value; for cal...
Rust
0
import numpy as np boiler_hourly_data = np.load("data/boiler_hourly_power_kWh_14_15.npy") agg_hourly_data = np.load("data/agg_hourly_power_kWh_14_15.npy") solar_hourly_data = np.load("data/solar_pump_hourly_power_kWh_14_15.npy") renewable_hourly_data = np.load("data/renewable_generation_kW_14_15_London.npy") heater_po...
Python
1
, layer_name, new_module) # Free cuda memory. del dequantized_weight, module torch.cuda.empty_cache() gc.collect() return model @torch.no_grad() def dequantize_model(model, verbose=True): for name, module in model.named_modules(): if not isinstance(module, QuantLinear...
Python
1
import archr import os import unittest class TestAnalyzerRR(unittest.TestCase): def get_miniupnpd_trace(self, t): crash = b"A" * 272 b = archr.analyzers.RRTracerAnalyzer(t) res = b.fire(testcase=crash) print(f"Done! You can find your trace in {res.trace_dir.name} (timed out?: {res....
Python
1
=> move_dir(&mut Action::S(0), ship, *v), Action::E(v) => move_dir(&mut Action::E(0), ship, *v), Action::W(v) => move_dir(&mut Action::W(0), ship, *v), Action::L(_) => { turn(a, heading); } Action::R(_) => { turn(a, heading); } Action::F(v...
Rust
0
import logging from deepface import DeepFace import os # Cấu hình logging logger = logging.getLogger(__name__) class DeepFaceVerification: def __init__(self, model_name='VGG-Face', distance_metric='cosine'): """ Khởi tạo hệ thống xác thực khuôn mặt sử dụng DeepFace. Args: mode...
Python
1
ONGFORMER_BASE_4096); let merges_resource = RemoteResource::from_pretrained(LongformerMergesResources::LONGFORMER_BASE_4096); let config_path = config_resource.get_local_path()?; let vocab_path = vocab_resource.get_local_path()?; let merges_path = merges_resource.get_local_path()?; // Se...
Rust
0
); let zr = Zr::synthetic_random("skey", &G1::generator(), &h); let pt = G2::generator().clone(); // public keys in G2 unsafe { rust_libpbc::exp_G2z( *CONTEXT_FR256, pt.base_vector().as_ptr() as *mut _, zr.base_vector().as_ptr() as *mut _, ) } let ...
Rust
0
branch(&format!("origin/{}", branch), BranchType::Remote) .with_context(s!("failed to find branch `{}`", branch))? .get() .target() .with_context(s!("branch `{}` does not have a target", branch)) } /// Resolve a revision to a object identifier. pub fn resolve_rev(repo: &Repository, rev:...
Rust
0
Foo { Bar { val: i32 } } //^^^ impl Foo { fn baz(self) { Self::Bar$0 {val: 4}; } } "#, ); } #[test] fn goto_def_for_type_alias_generic_parameter() { check( r#" type Alias<T> = T$0; //^ "#, ) } #[test] fn goto_def_for_macro_container() ...
Rust
0
from mistralrs import Runner, Which, ChatCompletionRequest, VisionArchitecture runner = Runner( which=Which.VisionPlain( model_id="microsoft/Phi-3.5-vision-instruct", arch=VisionArchitecture.Phi3V, ), ) res = runner.send_chat_completion_request( ChatCompletionRequest( model="phi3v"...
Python
1
let res_ = structural_alignment::align_pdb(&qresidues,&tresidues,alignment_type.clone(),0.2); let res:structural_alignment::StructuralAlignmentResult = res_.unwrap(); for rr in qcc.residues.iter(){ for aa_ in rr.iter_atoms(){ let mut aa = aa_.clone(); ...
Rust
0
acter codes is // as follows: // // Z-char 6789abcdef0123456789abcdef // current -------------------------- // A0 abcdefghijklmnopqrstuvwxyz // A1 ABCDEFGHIJKLMNOPQRSTUVWXYZ // A2 ^0123456789.,!?_#'"/\-:() // ---------...
Rust
0
# from itertools import cycle import numpy as np h, w = 4, 4 input = np.arange(1,17).reshape([h,w]) output = [] cycle_num = h//2 for i_cycle in range(cycle_num): for line in range(4): if line == 0: i = i_cycle for j in range(i_cycle, w - i_cycle -1): output.append(i...
Python
1
count = m128i::from(1_u128); /// let b: [u16; 16] = shl_all_u16_m256i(a, count).into(); /// assert_eq!(b, [10, 12, 4, 10, 8, 6, 2, 0, 24, 26, 112, 42, 16, 14, 12, 10]); /// ``` /// * **Intrinsic:** [`_mm256_sll_epi16`] /// * **Assembly:** `vpsllw ymm, ymm, xmm` #[must_use] #[inline(always)] #[cfg_attr(docs_rs, doc(cfg(...
Rust
0
ret.append("cycles") elif e == "instructions": ret.append("instructions") elif e == "dcache_misses": ret.append("r98") elif e == "icache_misses": ret.append("r86") else: raise Exception("Unkn...
Python
1
plt.plot(SC, P, '-*') plt.subplot(222) plt.xlabel('BPP') plt.ylabel('PSNR(db)') plt.title('PSNR(db) - Bit Per Pixel(BPP)') plt.grid(True) plt.plot(BPP, P, '-*') plt.subplot(223) plt.xlabel('Compression Rate(%)') plt.ylabel('PSNR(db)') plt.title('PSNR(db) - Compression Rate(%)...
Python
1
} fn syntax(&self) -> &SyntaxNode { &self.syntax } } impl From<BlockStmt> for Stmt { fn from(node: BlockStmt) -> Stmt { Stmt::BlockStmt(node) } } impl From<EmptyStmt> for Stmt { fn from(node: EmptyStmt) -> Stmt { Stmt::EmptyStmt(node) } } impl From<ExprStmt> for Stmt { fn from(node: ExprStmt) -> Stmt { Stmt::ExprSt...
Rust
0
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import logging from typing import List logger = logging.getLogger(__name__) def uniform(dataset_sizes: List[int]): return [1.0] * len(...
Python
1
!(Message); /// Wraps the message as Box<dyn Any + Send> and is tagged with the channel's /// ChannelType pub struct DynMessage { message: Box<dyn Any + Send>, channel: ChannelType, } impl DynMessage { pub fn new(message: impl Any + Send, channel: ChannelType) -> Self { Self { message:...
Rust
0
eq!( LEN_HEADER as u64, wf.len() ); assert_eq!( wf.len() as usize, wf.data.get_ref().len() ); assert!( wf.sid().is_null() ); assert!( wf.cid().is_null() ); assert_eq!( 0, wf.msg().len() ); } #[test] // fn set_len() { let mut wf = ThesWF::default(); wf.set_len( 33 ); asse...
Rust
0
import yaml import os from cli.cli_interface import run_cli from data_simulator.historical_data import HistoricalDataReplayer from data_simulator.market_simulator import MarketSimulator def load_config(): path = os.path.join(os.path.dirname(__file__), 'config', 'settings.yaml') with open(path, 'r') as f: ...
Python
1
size: u32, n_dimensions: u32, matrices: &'static[u32], } impl SobolSequences { pub fn new() -> SobolSequences { SobolSequences { size: 52, n_dimensions: 1024, matrices: sobol_matrices::sobol_matrices() } } #[allow(dead_code)] pub fn sampl...
Rust
0
entry use crate::Sandbox; use inkpad_std::Vec; use parity_scale_codec::{Decode, Encode}; /// Gas Meter #[derive(Default, Clone, Decode, Encode)] pub struct GasMeter { pub gas_limit: u64, pub gas_left: u64, } impl GasMeter { pub fn new(gas: u64) -> GasMeter { GasMeter { gas_limit: gas, ...
Rust
0
0 # pylint: disable=not-callable failed = db.execute(select(func.count(PromptMetric.id)).where(PromptMetric.is_success.is_(False))).scalar() or 0 # pylint: disable=not-callable failure_rate = failed / total if total > 0 else 0.0 min_rt = db.execute(select(func.min(PromptMetric.response_time))...
Python
1
lyze worker_counts: Worker counts to test Returns: Performance profiling results """ if not worker_counts: worker_counts = [1, 2, 4, 8, mp.cpu_count()] results = {} for workers in worker_counts: if workers > mp.cpu_count(): ...
Python
1
FIG_BORDER_COLOR, [0.0, 0.0, 1.0, 1.0]); let _box_1_id = self.pushrod.borrow_mut().add_widget_to_layout_manager( "BoxInLayoutWidget2", Box::new(box_1), self.layout_id, make_origin_point(), ); let mut box_2 = BoxWidget::new(); box_2.set_poi...
Rust
0
(notif_queue) => notif_queue .extend(std::iter::once( Arc::downgrade(&dispatcher) as Weak<dyn Subscriber> )), Err(e) => error!("failed to fire signal: {}", e), } } pending.signal_event...
Rust
0
wxyz{|}~", "¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþ", " !\"#$%&'()*+,-./0", "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_", ...
Python
1
ionMetadata, intermediate_tensors: Optional[IntermediateTensors] = None, inputs_embeds: Optional[torch.Tensor] = None, visual_token_mask: Optional[torch.Tensor] = None, ) -> Union[torch.Tensor, IntermediateTensors]: if get_pp_group().is_first_rank: if inputs_embeds is not...
Python
1
text.url().to_string(), retry_urls.get(retried).unwrap()); assert_eq!(context.retried().retried_total(), retried + 1); assert_eq!(context.retried().retried_on_current_endpoint(), 1); assert_eq!(context.retried().retried_on_current_ips(), 1); ...
Rust
0
# Histograma """ Crear un programa para hacer un histograma a partir de una lista de números enteros Análisis: [2, 1, 5, 3] * * * * * * * * * * * """ rango = int(input("Cuantos numeros va a ingresar?: ")) numeros = [] for r in range(rango): numero = int(input(f"{r+1}° Numero: ")) numeros.append(numero) def ...
Python
1
""" PDF智能文件管理系统主应用 """ import os import logging import mimetypes from flask import Flask, render_template, send_from_directory, request from flask_cors import CORS from utils.config_loader import config_loader from utils.environment_checker import environment_checker from app.routes.FileRoutes import file_bp from app....
Python
1
import math import os os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID" os.environ["CUDA_VISIBLE_DEVICES"] = "0" import torch from torch import nn class luminance_feedback(nn.Module): def __init__(self, init_weights=True): super(luminance_feedback, self).__init__() self.conv1 = reflect_conv_bn(in_cha...
Python
1
_client_data_json_vec = base64::decode(&req.response.client_data_json).expect("could not convert client data"); let client_data: requests::ClientData = serde_json::from_slice(&decoded_client_data_json_vec) .expect("could not parse client data"); info!("parsed clie...
Rust
0
/ Supplemental enhancement information (SEI) SEI = 6, /// Sequence parameter set SPS = 7, /// Picture parameter set PPS = 8, /// Access unit delimiter AUD = 9, /// End of sequence EndOfSequence = 10, /// End of stream EndOfStream = 11, /// Filler data Filler = 12, ...
Rust
0
type="primary", ) def app() -> None: """Streamlit entrypoint for PDF Summarize frontend""" # config st.set_page_config( page_title="📤 retrieval", page_icon="📚", layout="wide", menu_items={"Get help": None, "Report a bug": None}, ) add_logo() st.ti...
Python
1
_camera_matrix.as_raw__InputArray(), registered_camera_matrix.as_raw__InputArray(), registered_dist_coeffs.as_raw__InputArray(), rt.as_raw__InputArray(), unregistered_depth.as_raw__InputArray(), &output_image_plane_size, registered_depth.as_raw__OutputArray(), depth_dilation) }.into_result() } /// If the input image i...
Rust
0
e] fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", GEN_DEBUG_LKIND[*self as usize]) } } impl Default for LKind { #[must_use] #[inline] fn default() -> Self { LKind::None } } // GENERATOR-END: LKind pub(super) struct OpCodeFormatter<'a, 'b> { op_code: &'a OpCodeInfo, sb: &'b mut S...
Rust
0
cfg(feature = "v2_42")))] fn has_feature(&self, feature_type: glib::types::Type) -> bool { unsafe { from_glib(ffi::soup_session_has_feature(self.as_ref().to_glib_none().0, feature_type.into_glib())) } } fn pause_message(&self, msg: &impl IsA<Message>) { unsafe { ...
Rust
0
uring_load queries = parse_qs(parsed_url.query) if queries.pop("matching_heuristics", "False") == ["True"]: loaded["matching_heuristics"] = True if len(queries) > 0: raise ValueError( f"Unsupported query remaining: f{queries}, orginal filename: {parsed_url...
Python
1
import cv2 import pyzbar.pyzbar as pyzb import struct import zlib import base64 import json import numpy as np with open("code.png", "rb") as f: in_bytes = f.read() file_bytes = np.frombuffer(in_bytes, np.uint8) img = cv2.imdecode(file_bytes, cv2.IMREAD_GRAYSCALE) height, width = img.shape # type:ignore print(f"O...
Python
1