text
string
label_name
string
labels
int64
del self._as_parameter_ def record(self, stream=None): """Records the event in a given stream.""" if stream is None: stream = torch.cuda.current_stream() stream.record_event(self) def wait(self, stream=None): """Makes a given stream wait for the event.""" ...
Python
1
> { Resource { compressed: false, file_id, kind, original_offset: 0, } } fn extra_assets<'r>() -> Vec<Resource<'r>> { let extra_assets: &[((u32, FourCC), &[u8])] = &[ // Phazon Suit TXTR 1 (custom_asset_ids::PHAZON_SUIT_TXTR1.into(), include_bytes!(".....
Rust
0
perCodec)] #[asn(type = "INTEGER", lb = "0", ub = "3279165")] pub struct NRARFCN(u32); #[derive(Debug, AperCodec)] #[asn(type = "BITSTRING", sz_extensible = false, sz_lb = "36", sz_ub = "36")] pub struct NRCellIdentity(BitVec<Msb0, u8>); #[derive(Debug, AperCodec)] #[asn(type = "INTEGER", lb = "1", ub = "1024", exten...
Rust
0
values and that the num /// representation thereof is strictly greater than `lower_bound`. pub fn strict_lower_bound_check_u64<Scalar: PrimeField, CS: ConstraintSystem<Scalar>>( mut cs: CS, lower_bound: u64, value: &[AllocatedNum<Scalar>], ) -> Result<(), SynthesisError> { assert_eq!(value.len(), 64); ...
Rust
0
ro), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [tcd9_dlastsga](tcd9_dlastsga) module"] pub type TCD9_DLASTSGA = crate::Reg<u32, _TCD9_DLASTSGA>; #[allow(missing_docs)] #[doc(hidden)] pub struct _TCD9_DLASTSGA; #[d...
Rust
0
); /// /// assert_eq!( queries.next( ), Some( ( Cow::Borrowed( "page" ), Cow::Borrowed( "2" ) ) ) ); /// assert_eq!( queries.next( ), Some( ( Cow::Borrowed( "sort" ), Cow::Borrowed( "newest" ) ) ) ); /// assert_eq!( queries.next( ), None ); ///# Ok( () ) ///# } ///# run( ); /// ``` ...
Rust
0
# Copyright 2025 Google LLC # # 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 or agreed to in writing, s...
Python
1
start_date = datetime.fromisoformat(start_date.replace('Z', '+00:00')) if end_date: end_date = datetime.fromisoformat(end_date.replace('Z', '+00:00')) return service.get_audit_logs( user_id=user_id, action=action, resource=resource, start_date=start_date, ...
Python
1
el.layers[i].__class__.__name__ == 'Conv1D': model.layers[i].set_weights(weights) with tf.device('/cpu:0'): y_pred_demo = model.predict(y_original[None, :, None]).flatten() plt.figure() plot_fft(y_pred_demo, fs = fs) plot_fft(y_original, fs = fs) plt.xlim([-10, 150]) yy1 = tf.nn.relu(y).numpy() yy1 ...
Python
1
vs)?; test_poprf_evaluate::<NistP256>(&p256_poprf_tvs)?; test_poprf_finalize::<NistP256>(&p256_poprf_tvs)?; Ok(()) } fn test_oprf_seed_to_key<CS: CipherSuite>(tvs: &[VOPRFTestVectorParameters]) -> Result<()> where <CS::Hash as OutputSizeUser>::OutputSize: IsLess<U256> + IsLessOrEqual<<CS::Hash...
Rust
0
# -*- coding: utf-8 -*- # Copyright (C) 2019-2021 Greenbone Networks GmbH # # SPDX-License-Identifier: GPL-3.0-or-later # # 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 3 of the ...
Python
1
----------- from pyecharts import options as opts from pyecharts.charts import Geo from pyecharts.faker import Faker from pyecharts.globals import ChartType c7 = ( Geo() .add_schema(maptype="china") .add( "geo", [list(z) for z in zip(Faker.provinces, Faker.values())], type_=ChartTyp...
Python
1
CREATE TABLE `A` ( `id` INT PRIMARY KEY, `a` VARCHAR(255) NOT NULL, `b` TEXT NOT NULL ); CREATE FULLTEXT INDEX custom_name ON `A` (a, b); "#}; api.raw_cmd(setup).await; let expected = expect![[r#" model A { ...
Rust
0
Char('l') => { if current.1 < chunked_datas[current.0].len() - 1 { current.1 += 1; } } Key::Up | Key::Char('k') => { if 0 < current.0 { current.0 -= 1; } ...
Rust
0
{ width: img.width as i32, height: img.height as i32, data: &*img.data }, &DrawOptions::new()); let res= b"0"; Op::Sync(res.to_vec().into_boxed_slice()) } else { let res= b"1"; Op::Sync(res.to_vec().into_boxed_slice()) } })...
Rust
0
(n = 2)\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor in...
Rust
0
import os import shutil import numpy from api.tools.AI.network import NetworkResolution from api.tools.AI.trainer import Trainer from api.tools.AI.trainer import test as trainer_test from api.tools.AI.trainer import train from api.tools.enums import SupportedGames from tests.constants import CSV_PATH_XOR SupportedGa...
Python
1
#!/usr/bin/python # -*- coding: utf-8 -*- from Experiment_framework.Election import Election class VotingRule: """ Abstract class for voting rules Methods: find_winners(election, num_winners) -> list[int]: Returns a list of the winners of the election """ @staticmethod def find_winners(election: Election...
Python
1
WindowCommon<T>) -> Bytes { increase_in_window.data_frame_received(self.0.len()); self.0 } } #[derive(Debug)] enum DataOrTrailersDontForgetToDecrease { Data(DataDontForgetToDecrease, EndStream), Trailers(Headers), } impl DataOrTrailersDontForgetToDecrease { fn new(data_or_trailers: Dat...
Rust
0
conds // base = what gets put to the power on each iteration // take 1 means original iteration plus one more. 3 takes of 5 mean: now > 5s > 25s > 125s let retry_strategy = ExponentialBackoff::from_millis(RETRY_BASE) .factor(RETRY_FACTOR) .take(RETRY_COUNT_IMPORTANT); let (users, _) = Re...
Rust
0
dx += write_str(&mut w, &compressed[..])?; } else { source_contents.push(!0); } } } // write indexes head.names_start = idx; idx += write_slice(&mut w, &names)?; head.sources_start = idx; idx += write_slice(&mut w, &sources)?; if have_sources...
Rust
0
import requests import json url = "http://127.0.0.1:8080/api/v2/custom-nodes" #Replace 127.0.0.1 with BloodHound server IP or domain name headers = { "Authorization": "Bearer eyJ..", # Add bearer token "Content-Type": "application/json" } node_types = ["jamf_Account", "jamf_Computer", "jamf_Site", "jamf_Group...
Python
1
# MIT License # # Copyright (c) 2023 Eugenio Parodi <ceccopierangiolieugenio AT googlemail DOT com> # # Permission is 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 li...
Python
1
use itertools::Itertools; use super::plan_nodes::PlanRef; use super::rules::BoxedRule; pub struct HeuristicOptimizer { pub rules: Vec<BoxedRule>, } impl HeuristicOptimizer { pub fn optimize(&self, mut root: PlanRef) -> PlanRef { for rule in &self.rules { if let Ok(applied) = rule.apply(ro...
Rust
0
&AccessTokenRequestBody, ) -> Result<Request<Body>, Box<dyn error::Error + Send + Sync + 'static>> { let appid = body .client_id .to_owned() .ok_or(AccessTokenRequestRenderingError::ClientIdMissing)?; let query = WechatAccessTokenRequestQ...
Rust
0
from collections import defaultdict # Define the adjacency matrix matrix = [ [0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 0], [1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0], [0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0], ...
Python
1
"""Generate rules Rdf010GenerateRules.py T. Masuda, 2023/12/11 """ def main_rules_number_100(): """Generate next_number for symbolic numbers Returns: None """ """ VAL:fact_next_number_1_2 VAL:type VAL:fact ; VAL:operation VAL:next_number ; VAL:variable_x VAL:one ; VAL:var...
Python
1
# Generated by Django 5.0.6 on 2024-06-27 13:45 import django.db.models.deletion from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('django_mailbox', '0009_alter_message_eml'), ('email_client', '0003_custommessage'), ] operations = [ ...
Python
1
hadow: natural_t, pub vio_shadow_offset: natural_t, pub vio_paging_offset: natural_t, pub vio_copy_strategy: memory_object_copy_strategy_t, pub vio_last_alloc: vm_offset_t, pub vio_paging_in_progress: ::libc::c_uint, pub vio_pager_created: boolean_t, pub vio_pager_initialized: boolean_t, ...
Rust
0
pect\x00") } else { None } } } #[allow(deprecated)] impl Patchable for NodeJsCommandLineFlag { fn disable(&self, binary: &mut [u8]) -> Result<(), PatcherError> { let search = Regex::new(self.search_string()).expect("all regex patterns should be valid"); let found = s...
Rust
0
= std::result::Result<T, Box<dyn std::error::Error>>; #[test] fn write_from_terminal_start_cursor_pos_correct() -> Result<()> { let mut p = Printer::new(std::io::sink(), "".to_owned()); let origin_pos = p.cursor.pos; p.write_from_terminal_start("hello", Color::Red)?; assert_eq!(p.cursor.pos.current_pos...
Rust
0
istributed: print("This machine has more than 1 gpu. Please specify --multiprocessing_distributed, or set \'CUDA_VISIBLE_DEVICES=0\'") return -1 if args.do_online_eval: print("You have specified --do_online_eval.") print("This will evaluate the model every eval_freq {} steps and sav...
Python
1
angle] extern "C" fn recvfrom() {} #[no_mangle] extern "C" fn mprotect() {} #[no_mangle] extern "C" fn pthread_attr_init() {} #[no_mangle] extern "C" fn pthread_attr_setstacksize() {} #[no_mangle] extern "C" fn pthread_attr_destroy() {} #[no_mangle] extern "C" fn prctl() {} ...
Rust
0
ay in cases where there was a scheduled update. Returns: The active minimum upgrade delay """ min_upgrade_delay = self.min_upgrade_delay.value.copy() return ( min_upgrade_delay.delay_1 if Global.latest_timestamp >= min_upgrade_delay.timestamp else min...
Python
1
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @Time : 2023/9/4 16:12 @Author : Steven Lee @File : mmdc_playwright.py """ import os from typing import List, Optional from urllib.parse import urljoin from playwright.async_api import async_playwright from metagpt.logs import logger async def mermaid_to_fil...
Python
1
let mask = (u16::pow(2, bits as u32) - 1) as u8; let chunks = f32::ceil(8.0 / bits as f32) as u8; let padded = 8 < (chunks * bits); Ok(ByteMask { bits, mask, chunks, byte: 0, step: 0, ...
Rust
0
""" Crie um programa que leia o nome e o preco de varios produtos. O programa devera perguntar se o usuario vai continuar.#No final, mostre: #A)Qual e o total gasto na compra #B)Quantos produtos custam mais de R$1000 #C)Qual e o nome do produto mais barato. """ total_gasto = 0 mais_1000 = 0 barato = float('inf') # De...
Python
1
; queue.clear(); } Ok(len) } fn get_counter(&mut self) -> usize { self.counter } }//! Implementation of command line option for manipulating and showing server //! config use std::{net::SocketAddr, path::PathBuf}; use lazy_static::lazy_static; use structopt::StructOpt...
Rust
0
from pathlib import Path import yaml from patchwork.common.utils.step_typing import validate_steps_with_inputs from patchwork.step import Step from patchwork.steps import LLM, PR, CallCode2Prompt, ModifyCode _DEFAULT_INPUT_FILE = Path(__file__).parent / "defaults.yml" _DEFAULT_PROMPT_JSON = Path(__file__).parent / "...
Python
1
"""openbench implementation of SuperGPQA. SuperGPQA: Scaling LLM Evaluation across 285 Graduate Disciplines Implemented by Aarush Sah """ from inspect_ai import task from openbench.utils.mcq import MCQSample, MCQEval from openbench.utils.text import create_dynamic_multiple_choice_prompt def record_to_mcq_sample(rec...
Python
1
_language'] = property_source_language p_items['property_description_source'] = property_description_source p_items['property_photo'] = property_photo p_items['property_photos'] = property_photos p_items['property_coordinates'] = property_coordinates p_items['property_geo'] = pro...
Python
1
# Copyright 2024 Black Forest Labs, The HuggingFace Team and The InstantX Team. 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/licenses/LIC...
Python
1
# Copyright (c) 2025, NVIDIA CORPORATION. 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/licenses/LICENSE-2.0 # # Unless required by appli...
Python
1
::Somali) => atoms::somali().encode(env), Language(lingua::Language::Sotho) => atoms::sotho().encode(env), Language(lingua::Language::Spanish) => atoms::spanish().encode(env), Language(lingua::Language::Swahili) => atoms::swahili().encode(env), Language(lingua::Language::...
Rust
0
ompletely built yet ({self.remaining} characters remaining)') alignment = self._original.alignment.compose(self.alignment) return bistr(self.original, self.modified, alignment) def rewind(self) -> None: """ Reset this builder to apply another transformation. :raises: ...
Python
1
import torch import torch.nn as nn from model.fpn import * from model.backbone.shufflenetv2 import * class Detector(nn.Module): def __init__(self, classes=80, anchor_num=3, load_param=False, export_onnx = False): super(Detector, self).__init__() out_depth = 72 stage_out_channels = [-1, 24,...
Python
1
import torch import torch.nn as nn import torch.nn.functional as F from functools import partial import argparse from .functions import HDRPointwiseNN, DIRLNet class MadisNet(nn.Module): def __init__(self): super(MadisNet, self).__init__() opt = argparse.Namespace( dataset_root='/data...
Python
1
new(0.0, 0.01).unwrap(); // initialize kinematic model from a configuration file let kin = Kinematics::new(&Path::new("robot_conf.json")); let mut pose = Pose::new(); // initialize window and graphics primitives let mut window = Window::new("Parallel Cable Robot Simulation"); window.set_light...
Rust
0
n: &OrderIndex(0.into(), 0.into()), }); buffer.ensure_len(); buffer.contents_mut().locs_mut()[0] = OrderIndex(0.into(), 1.into()); stream.write_all(buffer.entry_slice()).unwrap(); stream.write_all(&[0; 6]).unwrap(); buffer[..].iter_mut().fold((), |_, i| *i = 0); r...
Rust
0
loss_box, loss def train_step_with_summary(self, sess, blobs, train_op): feed_dict = {self._image: blobs['data'], self._im_info: blobs['im_info'], self._gt_boxes: blobs['gt_boxes']} rpn_loss_cls, rpn_loss_box, loss_cls, loss_box, loss, summary, _ = sess.run([self._losses["rpn_...
Python
1
16 } if fontDefLength > xdvBufSize { free(xdv_buffer as *mut libc::c_void); xdvBufSize = (fontDefLength / 1024i32 + 1i32) * 1024i32; xdv_buffer = xmalloc(xdvBufSize as size_t) as *mut i8 } cp = xdv_buffer; *(cp as *mut Fixed) = SWAP32(size as u32) as Fixed; cp = cp.offset...
Rust
0
import qrcode img = qrcode.make("some data") img.save("normalQR.png")
Python
1
deRange4: u32, pub(crate) achVendID: [i8; 4], pub(crate) fsSelection: u16, pub(crate) usFirstCharIndex: u16, pub(crate) usLastCharIndex: u16, pub(crate) sTypoAscender: i16, pub(crate) sTypoDescender: i16, pub(crate) sTypoLineGap: i16, pub(crate) usWinAscent: u16, pub(crate) usWinDesc...
Rust
0
import pandas as pd reviews = pd.Series([1.6, 2.6, 4.9, 5.6]) print(reviews) print(reviews[1]) print(reviews.count()) print(reviews.mean()) print(reviews.min()) print(reviews.max()) print(reviews.std()) reviews = pd.Series([1.6, 2.6, 4.9, 5.6], index=['Python', 'java', 'django', 'devops']) print(reviews) reviews =...
Python
1
s) message: Log message content """ self.emit_event("log_message_received", self.metadata.name, level, message) def get_config_value(self, key: str, default=None): """ Get a configuration value for this plugin. Args: key: Configuration key ...
Python
1
erive(Debug)] pub struct RaceAll<F: CompletionFuture> { inner: JoinAll<RaceFuture<F>>, _correct_debug_bounds: PhantomData<F::Output>, } impl<F: CompletionFuture> Unpin for RaceAll<F> {} impl<F: CompletionFuture> RaceAll<F> { fn new(inner: JoinAll<RaceFuture<F>>) -> Self { Self { inner,...
Rust
0
from .. import full_eval from mitmproxy.contentviews import image def test_view_image(tdata): v = full_eval(image.ViewImage()) for img in [ "mitmproxy/data/image.png", "mitmproxy/data/image.gif", "mitmproxy/data/all.jpeg", "mitmproxy/data/image.ico", ]: with open(td...
Python
1
# -*- coding: utf-8 -*- """ Created on Mon Dec 07 11:05:34 2015 @author: hehu """ import matplotlib.pyplot as plt import numpy as np from matplotlib import rc if __name__ == "__main__": plt.close("all") np.random.seed(43) numSamples = 200 x = np.random.randn(numSamples) plt.figure(...
Python
1
let mut scape_hashes = Vec::with_capacity(indeces.len()); for i in indeces { scape_hashes.push(info_hashes[*i].to_owned()) } (ScrapeRequest { connection_id: torrent_peer.connection_id, transaction_id, info_hashes: scape_hashes, }) .into() } <reponame>randomico...
Rust
0
iling_dump(filename: &str) -> Result<(), String> { let mut filename0 = format!("{}\0", filename); let opt_name = "prof.dump"; let opt_c_name = ffi::CString::new(opt_name).unwrap(); info!("jemalloc profiling dump: {}", filename); unsafe { jemalloc_sys::mallctl( opt_c_name.as_ptr()...
Rust
0
// to be added in the genesis configuration CampaignPeriodLimit get(campaign_period_limit) config(): T::BlockNumber = T::BlockNumber::sa(864000); CampaignsByBlockNumber get(campaign_expire_at): map T::BlockNumber => Vec<T::Hash>; AllCampaignCount get(campaign_count): u64; AllCampaignArray get(campaign_by_in...
Rust
0
from src.commons.globals import handler_map from src.core.function_calling import Message test_input_history = [ {"role": "user", "content": "how is the weather in chicago for next 5 days?"}, { "role": "assistant", "model": "stellar-Function", "tool_calls": [ { ...
Python
1
': 0x8C, # ARM 'arm_b': 0xEA, # SH4 'sh4_trapa': 0xC3, # TRAPA #xx 'sh4_mov_l': 0xD0, # MOV.L Rm,@(disp,Rn) # s390 (big-endian, 2-byte or 4-byte instructions) 's390_prefix': 0xA7, # Common prefix for many instructions 's390_lay': 0xE3, # LA...
Python
1
a + bi) = cosh(a)cos(b) + i*sinh(a)sin(b) Self::new( self.re.simd_cosh() * self.im.simd_cos(), self.re.simd_sinh() * self.im.simd_sin(), ) } #[inline] fn simd_sinh_cosh(self) -> (Self, Self) { let (rsinh, rcosh) = self.re.simd_sinh_cosh(); let (isin, ...
Rust
0
( &mut object_675, var_674, )?; object_675.finish(); } Ok(()) } pub fn serialize_structure_crate_model_finding_provider_fields( object: &mut aws_smithy_json::serialize::JsonObjectWriter, input: &crate::model::FindingProviderFields, ) -> Result<(), aws_smithy_http...
Rust
0
'{"jsonrpc": "2.0", "method": "Favourites.AddFavourite", "params": {"title": "%s", "type": "%s", "window": "10025", "%s": "%s", "thumbnail": "%s"}, "id": 1}' fav_cmd = cmd % (title, fav_types[fav_index], url_types[fav_index], fav_url, img) opp_cmd = cmd % (title, fav_types[opp_index], url_types[opp_index], opp_...
Python
1
ccents_true(self): tokenizer = BasicTokenizer(do_lower_case=False, strip_accents=True) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? "), ["HaLLo", "!", "how", "Are", "yoU", "?"] ) def test_basic_tokenizer_respects_never_split_tokens(self): tokeniz...
Python
1
### logging.basicConfig(level = logging.INFO, format = '\n%(levelname)s: %(message)s') @pytest.fixture(scope = "session", autouse = True) def logger(request): level_s = request.config.getoption("--verbosity") level = logging._levelNames[level_s] logger = logging.getLogger() logger.s...
Python
1
# -*- coding: utf-8 -*- # # Copyright 2023 Google LLC. 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/licenses/LICENSE-2.0 # # Unless requir...
Python
1
_err()); let mut invalid_cfg = cfg.clone(); invalid_cfg.concurrent_recv_snap_limit = 0; assert!(invalid_cfg.validate().is_err()); let mut invalid_cfg = cfg.clone(); invalid_cfg.end_point_recursion_limit = 0; assert!(invalid_cfg.validate().is_err()); let mut inv...
Rust
0
as f32 / h, ), dest: graphics::Point::new(160., 120.), scale: graphics::Point::new(1.5, 1.5), ..Default::default() }; graphics::draw_ex(ctx, &self.image, param)?; } graphics::present(ctx); Ok(()) } } f...
Rust
0
from .atomic_skills import * from .skill_registry import SkylinesSkillRegistry from .ui_control import SkylinesUIControl
Python
1
let in_count = std::ptr::read(pulCount); if in_count < (slot_count as pkcs11::CK_ULONG) { std::ptr::write(pulCount, slot_count as pkcs11::CK_ULONG); return pkcs11::CKR_BUFFER_TOO_SMALL; } } } let slot_id_vec = device.ck_slot_ids(tokenPresent != 0)...
Rust
0
&mint_config_store, &mut db_txn) { Ok(()) => panic!("Unexpected success"), Err(Error::MintLimitExceeded(mint_amount, minted_so_far, mint_limit)) => { assert_eq!(mint_amount, mint_tx1.prefix.amount); assert_eq!(minted_so_far, 0); assert!(&[ ...
Rust
0
"111"], "device_info": { "identifiers": [["lutron_caseta", 68551522]], "manufacturer": "Lutron Electronics Co., Inc", "model": "PJ2-3BRL-GXX-X01 (Pico3ButtonRaiseLower)", "name": "Dining Room Pico", ...
Python
1
0u8; 128]; assert!(let Ok(12) = b.recv(&mut buffer).await); assert!(&buffer[..12] == b"Hello world!"); } /// Test a send and receive call where the send wakes the recv task. #[test] fn send_recv_out_of_order() { use std::sync::atomic::{AtomicBool, Ordering}; let mut runtime = tokio::runtime::Builder::new_current_...
Rust
0
bot.send_message(chat_id=chat_id, text=full_answer, reply_markup=markup) print(f"Пятничное сообщение отправлено пользователю {chat_id}") except telebot.apihelper.ApiException as e: if "Forbidden: ...
Python
1
self.clear_interrupt(); Ok(()) } else { Err(nb::Error::WouldBlock) } } } impl<TIMG: TimerGroup> Cancel for Timer<TIMG, $TIMX> { type Error = Error; /// Cancel running timer. ...
Rust
0
&mut fmt::Formatter) -> fmt::Result { let name = if let Ok(name) = str::from_utf8(&self.name) { name.to_owned() } else { format!("{:?}", self.name) }; write!( output, "Chunk \"{}\" (compressed: {}, len: {}, reserved: {})", nam...
Rust
0
self) -> usize { self.runs.len() } /// Check whether the container is empty #[inline] pub fn is_empty(&self) -> bool { self.runs.is_empty() } /// Check whether the container is full pub fn is_full(&self) -> bool { if self.runs.is_empty() { return fal...
Rust
0
# Time: O(nlogr) # Space: O(1) # binary search class Solution(object): def minDifference(self, nums): """ :type nums: List[int] :rtype: int """ def binary_search(left, right, check): while left <= right: mid = left+(right-left)//2 ...
Python
1
FIFO_CNT_MSK: u32 = 63; pub const UART_TX_FIFO_CNT_UMSK: i32 = -64; pub const UART_RX_FIFO_CNT_POS: u32 = 8; pub const UART_RX_FIFO_CNT_LEN: u32 = 6; pub const UART_RX_FIFO_CNT_MSK: u32 = 16128; pub const UART_RX_FIFO_CNT_UMSK: i32 = -16129; pub const UART_TX_FIFO_TH_POS: u32 = 16; pub const...
Rust
0
/// /// The ending sequence `~>` is appended to the end of the encoding. /// Four zero bytes that are aligned correctly will be encoded as the character /// `z`. /// /// # Example /// /// ``` /// use pdf_ascii85::encode; /// /// let encoded = encode(&[1,2,3,4, 0,0,0,0]); /// assert_eq!(encoded, b"!<N?+z~>"); /// ``` pu...
Rust
0
(<bool as StaticType>::static_type()); gobject_sys::g_object_get_property( self.to_glib_none().0 as *mut gobject_sys::GObject, b"show-icons\0".as_ptr() as *const _, value.to_glib_none_mut().0, ); value .get() ...
Rust
0
print('Iter: {}, running MSE: {:.4f}'.format(itr, loss)) end_time = time.time() print('\n') print('Training complete after {} iters.'.format(itr)) print('Time = ' + str(end_time-start_time)) loss = loss_func(pred_z, z).detach().numpy() print('Train MSE = ' +str(loss)) print('NFE = '...
Python
1
nd, cause } } pub fn kind(&self) -> &CapacityErrorKind { &self.kind } pub fn read() -> CapacityError { CapacityError::new(CapacityErrorKind::ReadFull, None) } pub fn write() -> CapacityError { CapacityError::new(CapacityErrorKind::WriteFull, None) } } #[derive(Deb...
Rust
0
def reorganize_input_for_transformer(batch_size, point_indices, point_features, max_valid_num=40000): """ Cast support features from stack representation: [N1 + N2 + ..., C] (features) & [N1 + N2 + ..., 4] (coords) to batch representation: [B, M, C] & [B, M, 3]...
Python
1
from django.core.exceptions import ValidationError from django.db import models from django.db.models import Q from geopy.geocoders import Nominatim class GeoFencing(models.Model): latitude = models.FloatField() longitude = models.FloatField() radius_in_meters = models.IntegerField() company_id = mode...
Python
1
moryTracker() memory_tracker.start() batch_size = 3 input_ids = torch.ones((batch_size, 512), dtype=torch.long).to("cuda") labels = torch.ones((batch_size, 50), dtype=torch.float).to("cuda") attention_mask = torch.ones((batch_size, 512), dtype=torch.int).to("cuda") optimizer = torch.optim.AdamW...
Python
1
parse_color_string("-1,0,0") self.assertIn("RGB values must be between 0-255", str(cm.exception)) # Test invalid RGB format (too few values) with self.assertRaises(ValueError) as cm: parse_color_string("255,0") self.assertIn("RGB format must have 3 or 4 ...
Python
1
e<CustomEvent>) -> Self { handle.id() } } /// The playback state of an instance of a sequence. #[derive(Debug, Clone, Copy, Eq, PartialEq)] pub enum SequenceInstanceState { /// The sequence instance is playing. Playing, /// The sequence instance is paused. /// /// Any wait commands are currently on hold. Paus...
Rust
0
"""This file is for benchmark dataloading process. The command line to run this file is: $ python -m cProfile -o program.prof tools/analysis/bench_processing.py configs/task/method/[config filename] It use cProfile to record cpu running time and output to program.prof To visualize cProfile output program.prof, use Sn...
Python
1
if selecao: filtros_aplicados[coluna] = selecao else: st.sidebar.warning(f"⚠️ Coluna '{coluna}' está vazia") st.sidebar.markdown("---") # Botão para limpar filtros col_btn1, col_b...
Python
1
from django import forms from django.utils.translation import gettext_lazy as _ from fobi.base import BasePluginForm, get_theme from .settings import DEFAULT_SIZE, SIZES __title__ = "fobi.contrib.plugins.form_elements.content.content_video.forms" __author__ = "Artur Barseghyan <artur.barseghyan@gmail.com>" __copyrig...
Python
1
} else { true } }); } else { self.deferred_initialisers.retain(|&(id, (ref _node, ref _init))| id != next_id ); } result } fn new_op_impl<O: Op>(&mut self, op: O, tags: Vec<OpTag>, next_id: usize) -> Result<OpID> { let op = op.build(self)?; let name = op.name().to_string(); // ...
Rust
0
{ if subcommand != "mutants" { eprintln!("unrecognized cargo subcommand {:?}", subcommand); exit(exit_code::USAGE); } } else { eprintln!("usage: cargo mutants <ARGS>\n or: cargo-mutants mutants <ARGS>"); exit(exit_code::USAGE); } let args: Args = ar...
Rust
0
(error) => panic!("Problem with the emulator: {:?}", error), } } fn execute(path: &str) -> Result<(), std::io::Error> { let (mut canvas, texture_creator, mut event_pump) = match init_window() { Ok(t) => t, Err(error) => panic!(error), }; let mut n_rom = read_cartridge(path)?; let mu...
Rust
0
system_army); for initiative in (1..=max_initiative).rev() { for k in immune_system_targets.keys() { let i = *k; if immune_system_army[i].initiative == initiative && immune_system_army[i].units > 0 { attack(&immune_system_army[i], &mut infection_a...
Rust
0
[0, 0], [5, 0], [5, 5] ] expected_center = [(4, 1)] self._tst_arc_center(xy_points, expected_center) def test_arc_center_315_degree(self): xy_points = [ [0, 0], [5, 0], [0, 5] ] expected_center = [...
Python
1
! { // We do two allocations here, unfortunately. But (a) they're // required with the current scheme, and (b) we don't handle // failure + OOM properly anyway (see comment in begin_unwind // below). begin_unwind_inner(~fmt::format(msg), file, line) } /// This is the entry point of unwinding for f...
Rust
0