text
string
label_name
string
labels
int64
); helper!(h, "replace", replace); helper!(h, "os", os); HandlebarsTemplateEngine { handle: h } } pub fn render_template<S: AsRef<str>, D: Serialize>(&self, template_text: S, data: &D) -> crate::Result<String> { let template_text = template_text.as_ref(); self.handle ...
Rust
0
onent_quantity(stride_expr, "range expression stride")?; Ok(Val::Range(Box::new(Range { start, end, stride }))) } fn eval_symbol(env: &mut SharedEnv, symbol: Sym) -> EvalResult { env.lock() .unwrap() .get_var(&symbol) .ok_or(RtErr::Undefined(symbol.name)) } fn eval_unit(env: &mut SharedEnv, unit_name: String)...
Rust
0
doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 3)) | ((value as u16 & 0x01) << ...
Rust
0
"""Utilities related to fault domain information from cloud providers. ************************************************************************ FOR THE TIME BEING WHATEVER MODIFICATIONS ARE APPLIED TO THIS FILE SHOULD ALSO BE APPLIED TO ANY OTHER PARTNER REPOS **********************************************************...
Python
1
_dict = {'Best epoch': best_epoch} best_dict.update(best_val_loss) best_dict.update(best_val_metrics) # reshape dict for saving model_params = {'vae_kwargs': vae_params, 'clf_kwargs': clf_params} save_model_full(model, checkpoint_filename, outdir, best_dict=be...
Python
1
ttrs.resize_increments { let (x, y) = (increments.width, increments.height); if x >= 1.0 && y >= 1.0 { let size = NSSize::new(x as CGFloat, y as CGFloat); nswindow.setResizeIncrements_(size); } } nswindow.ce...
Rust
0
n = dim_right.axis(axis) - index; dim_right.set_axis(axis, right_len); let right = unsafe { Self::new_(right_ptr, dim_right, self.strides) }; (left, right) } /// Return the array’s data as a slice, if it is contiguous and in standard order. /// Return `None` ot...
Rust
0
import cv2 import numpy as np # a = np.random.randint(0, 4, size=(1, 2, 2)) # print(a) # mask = np.asarray([[0, 0, 0, 1, 0, 1], # [0, 0, 0, 1, 1, 1], # [0, 0, 0, 1, 0, 1], # [0, 1, 0, 0, 1, 1], # [0, 0, 0, 0, 0, 0], # [...
Python
1
import time import math with open('hail-mary/test.mid', 'rb') as f: data = f.read() start = False notes = [] indexes = [i for i, n in enumerate(data) if n == 0x90] idx = 0 convert = { 0: 'C', 1: 'C#', 2: 'D', 3: 'D#', 4: 'E', 5: 'F', 6: 'F#', 7: 'G', 8: 'G#', 9: 'A', 1...
Python
1
(&self) -> bool { *self == GPIO8_A::RF_GPIO8_SRC_CONST_LOW } #[doc = "Checks if the value of the field is `RF_GPIO8_SRC_CONST_HIGH`"] #[inline(always)] pub fn is_rf_gpio8_src_const_high(&self) -> bool { *self == GPIO8_A::RF_GPIO8_SRC_CONST_HIGH } } #[doc = "Write proxy for field `GPI...
Rust
0
ail).first() user_id = user_exist.id vehicle_exist = Vehicle.query.filter_by(id=vehicle_id).first() if vehicle_exist is None: return ({"msg": "This vehicle doesn't exist"}), 400 else: favorite_vehicle_to_delete = FavoriteVehicle.query.filter_by(vehicle_id=vehicle_id, user_id=user_id).fir...
Python
1
"ómo."); let str130acc = &str129acc.replace("omo,", "ómo,"); let str131acc = &str130acc.replace("omos ", "ómos "); let str132acc = &str131acc.replace("omos.", "ómos."); let str133acc = &str132acc.replace("omos,", "ómos,"); let str134acc = &str133acc.replace("ones ", "ónes "); let str135acc = &str134ac...
Rust
0
import streamlit as st from utils import write_to_csv # Function to export list of objects (Dim, Cubes, Process) def export_list_of_objects(tm1): st.markdown(""" <h1 style='text-align: center; font-family: Arial;'> <span style='color: #FFD700;'>Tm1</span><span style='color: #4682B4;'>Exporti...
Python
1
= _as_float("LIQUIDITY_MAX_PCT_ADV", 0.05) # Advanced execution algorithms ENABLE_CHILD_ORDERS = _as_bool("ENABLE_CHILD_ORDERS", True) DEFAULT_EXECUTION_SLICES = _as_int("DEFAULT_EXECUTION_SLICES", 8) VWAP_LOOKBACK_DAYS = _as_int("VWAP_LOOKBACK_DAYS", 20) # FIX protocol and latency optimization ENABLE_FIX_PROTOCO...
Python
1
(credential: PublicKeyCredentialSource) -> cbor::Value { let mut private_key = [0u8; 32]; credential.private_key.to_bytes(&mut private_key); let other_ui = match credential.other_ui { None => cbor_null!(), Some(other_ui) => cbor_text!(other_ui), }; cbor_ar...
Rust
0
== true; unimplemented!() } } pub struct User { id: i32, } impl UserFields for User { fn field_id<'a>(&self, executor: &Executor<'a, Context>) -> FieldResult<&i32> { unimplemented!() } fn field_club<'a>( &self, executor: &Executor<'a, Context>, trail: &Qu...
Rust
0
import math class Point: def __init__(self, x, y): self.x = x self.y = y def show(self): print(f"Точка ({self.x}, {self.y})") def move(self, dx, dy): self.x += dx self.y += dy def dist(self, other_point): return math.sqrt((self.x - other_point.x)**2 + ...
Python
1
super::CTUNE_CNT1_0 { #[doc = r" Reads the contents of the register"] #[inline] pub fn read(&self) -> R { R { bits: self.register.get(), } } } #[doc = r" Value of the field"] pub struct CTUNE_COUNT_0R { bits: u16, } impl CTUNE_COUNT_0R { #[doc = r" Value of the field...
Rust
0
## Operasi # index 0(-3) 1(-2) 2(-1) data = ["Ucup","Otong","Dudung"] # mengambil data dari list ini data_0 = data[0] print(f"data pertama (index 0) = {data_0}") data_terakhir = data[-1] print(f"data terakhir adalah = {data_terakhir}") data_ucup = data[-3] print(f"data ucup = {data_ucup}") # mengambil info jum...
Python
1
} /// Returns the process ID for this process. pub fn pid(&self) -> pid_t { self.stat.pid } /// Is this process still alive? pub fn is_alive(&self) -> bool { match Process::new(self.pid()) { Ok(prc) => { // assume that the command line, uid and starttim...
Rust
0
from typing import TYPE_CHECKING from smb3parse.constants import ( OBJ_CHEST_EXIT, OBJ_CHEST_ITEM_SETTER, OBJ_PIPE_EXITS, OBJ_WHITE_MUSHROOM_HOUSE, ) SKY = 0 GROUND = 27 EXPANDS_NOT = 0b00 EXPANDS_HORIZ = 0b01 EXPANDS_VERT = 0b10 EXPANDS_BOTH = EXPANDS_HORIZ | EXPANDS_VERT if TYPE_CHECKING: from...
Python
1
let k = replace(&mut self.sym.key,Vec::new()); let mut nc = OSSLSym::new_iv_shift(k,false,true)?; if self.sym.symbuffix > 0 { let bs = <RT as OpenSSLSymConf>::SHADOW_TYPE().block_size(); // TODO consider non optional underbuf if self.underbuf.is_none()...
Rust
0
season: 0, episode: 0, year: 2014, media_type: MediaType::Movie, quality: None, release_type: Some(release_type::ReleaseType::WEBDL), video_codec: Some(video_codec::VideoCodec::H264), audio_c...
Rust
0
decompile(&mut self, out: &mut dyn Write) -> crate::StingrayResult<usize> { out.write_all(&self.buffer[36..])?; Ok(self.buffer[36..].len()) } fn path(&self) -> (Option<&str>, Option<&str>) { if let Ok(array) = self.buffer[36..44].try_into() { let magic_word = u64::from_le_b...
Rust
0
executables: false, limit_rdylib_exports: false, late_link_args, late_link_args_dynamic, late_link_args_static, ..base } } <filename>src/sites/mod.rs extern crate base64; mod manifest; mod sync; pub use manifest::AssetManifest; pub use sync::sync; use std::ffi::OsString; ...
Rust
0
# # Copyright 2023 Martin Pavella # Copyright 2023 NXP # # License: MIT # See the LICENSE_MIT for more details. # """ LRN Representation of the TFLite operator 'LocalResponseNormalization'. """ import executorch.backends.nxp.backend.ir.lib.tflite.BuiltinOperator as libBuiltinOperator import executorch.backends.nx...
Python
1
o * be iterated over. Please don't use it as-is. */ use crate::storage::data_directory::Trait as DDTrait; use crate::storage::data_object_storage_registry::Trait as DOSRTrait; use crate::traits::{ContentHasStorage, ContentIdExists}; use parity_codec::Codec; use parity_codec_derive::{Decode, Encode}; use rstd::pr...
Rust
0
import os from dotenv import load_dotenv from aiogram import Router, F from aiogram.types import Message, CallbackQuery, FSInputFile from aiogram.fsm.context import FSMContext from app.fsm import OrderForm from keyboards import client as k from config import bot from data import users as u from data import whitelist...
Python
1
al-orbits/constellations") async def get_available_constellations() -> Dict[str, Any]: """獲取可用的星座列表及其數據統計""" try: from app.data.historical_tle_data import get_historical_tle_data constellations = {} for constellation in ["starlink", "oneweb", "gps", "galileo"]: data ...
Python
1
_middle::ty::TyKind; use std::collections::HashMap; pub struct Callgraph { pub direct: HashMap<LocalDefId, HashMap<BasicBlock, LocalDefId>>, } impl Callgraph { pub fn new() -> Self { Self { direct: HashMap::new(), } } fn insert_direct(&mut self, caller: LocalDefId, bb: Basi...
Rust
0
"""Tests for reset builders in the ksim package.""" import attrs import jax import jax.numpy as jnp import mujoco import pytest import xax from jaxtyping import Array import ksim @attrs.define(frozen=True) class DummyReset(ksim.Reset): """Dummy reset for testing.""" def __call__(self, data: ksim.PhysicsDat...
Python
1
write trace to file if log_trace: trace_path = join(self.trace_dir, str(control_step)) + '.txt' with open(trace_path, 'w', 'utf8') as f: if replay_trace is None: f.write('None') else: f.write(replay_trace.dumps()) ...
Python
1
c.unwrap() { Key::Char('z') => tx1.send("z t2".to_owned().to_string()).unwrap(), Key::Char('q') => tx1.send("q t2".to_owned().to_string()).unwrap(), Key::Char('s') => tx1.send("s t2".to_owned().to_string()).unwrap(), Key::Char('d') => tx1.send("d t2".to_owned().to_string()).unwrap(), Key::Char('a')...
Rust
0
let message3 = b"!!!"; let token3 = token2.append(&mut rng, &message3[..]); assert!(token3.verify(), "cannot verify third token"); assert!(token3.challenge(&mut rng, &b"test"[..]).verify(), "cannot verify third challenge token"); } #[test] fn change_message() { //let mut rng: OsRng = OsRng:...
Rust
0
TaprootWitnessError::ScriptError(err) => Some(err), } } } /// Parsed witness stack for Taproot inputs #[derive(Clone, PartialEq, Eq, Debug)] // TODO: Uncomment once SchnorrSig will implement serde /* #[cfg_attr( feature = "serde", derive(Serialize, Deserialize), serde(crate = "serd...
Rust
0
import pytest from faker import Faker from zoo.datacenters import amazon as uut from zoo.datacenters import models fake = Faker() pytestmark = pytest.mark.django_db def test_amazon_map_to_nodes(mocker): mocker.patch( "zoo.datacenters.amazon.iter_hosted_zones", return_value=[ {"Id": "...
Python
1
Result<(), SendError> { self.connection() .borrow_mut() .send(Request::SetMaximized { output }.into_raw(self.id())) } /// Set a short title for the surface. this string may be used to identify the /// surface in a task bar, window list, or other user interface elements provi...
Rust
0
proc_macro_derive_resolution_fallback, redundant_semicolons, renamed_and_removed_lints, safe_packed_borrows, single_use_lifetimes, stable_features, trivial_bounds, trivial_casts, trivial_numeric_casts, type_alias_bounds, tyvar_behind_raw_pointer, unaligned_references, unc...
Rust
0
uler.step() lr_current = scheduler.get_last_lr() print('The current learning rate is {:.06f}'.format(lr_current[0])) end = time.time() print('Epoch %d training time cost: %.4f seconds' % (epoch + 1, end-start)) model.eval() y_output = np.zeros(n_...
Python
1
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, software // distributed under the License is distributed on an "AS IS" B...
Rust
0
g)) def _get_fixtures_content(fixtures: dict, remove_missing: bool): if remove_missing: fixtures = {i: fixtures[i] for i in PROCESSED} else: fixtures = fixtures return json.dumps(fixtures, indent="", sort_keys=True) + "\n" def main(): read_fixtures() for record in SCREENS_DIR.it...
Python
1
@property def keys(self): """Returns a list of keys for accessing specific metrics.""" return ['metrics/precision(B)', 'metrics/recall(B)', 'metrics/mAP50(B)', 'metrics/mAP50-95(B)']
Python
1
import os import numpy as np def _bitmap_extract(bmp, require_variance=True): from mitsuba import Bitmap, Struct """Extract different channels from moment integrator AOVs""" # AVOs from the moment integrator are in XYZ (float32) split = bmp.split() if len(split) == 1: if require_variance: ...
Python
1
= [] source = sys.stdin.read() pos = 0 while pos != len(source): m = tokenizer.match(source, pos) tokens.append([m.lastgroup, m.group()]) pos += len(tokens[-1][1]) if tokens[-1][0] == 'preproc': # continuation lines are considered # only in preprocess ...
Python
1
location(&dpos).is_some() { let di = dpos.y as usize * g.cols() + dpos.x as usize; visibility_map[i].push(di); } } } (seats, visibility_map) } fn count_occupied(seats: &[Place], neighbors: &[usize]) -> usize { neighbors .iter() .filter(|i|...
Rust
0
TIF2_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: TIF2_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Timer has not timed out"] #[inline(always)] pub fn tif2_0(self) -> &'a mut W { self.variant(TIF2_A::TIF2_0) } #[doc =...
Rust
0
assert_eq!(*ctx, "ABC"); } #[test] #[should_panic] fn context_unknown() { let mut interp = Interp::new(); // Valid ID Generated, but no context saved. let id = interp.context_id(); // Try to retrieve it. let _ctx = interp.context::<String>(id); /...
Rust
0
For information about available fields see [rcgc2](rcgc2) module"] pub type RCGC2 = crate::Reg<u32, _RCGC2>; #[allow(missing_docs)] #[doc(hidden)] pub struct _RCGC2; #[doc = "`read()` method returns [rcgc2::R](rcgc2::R) reader structure"] impl crate::Readable for RCGC2 {} #[doc = "Run Mode Clock Gating Control Register...
Rust
0
ith_chat(chat_id, timestamp, limit) async def get_messages_before_time_for_users( timestamp: float, person_ids: list[str], limit: int = 0 ) -> list[dict[str, Any]]: """ 获取指定用户在指定时间戳之前的消息 Args: timestamp: 时间戳 person_ids: 用户ID列表 limit: 限制返回的消息数量,0为不限制 Returns: List[...
Python
1
), SwitchSequential(ResidualBlock(640, 640), AttentionBlock(8, 80)), SwitchSequential(nn.Conv2d(640, 640, kernel_size=3, stride=2, padding=1)), SwitchSequential(ResidualBlock(640, 1280), AttentionBlock(8, 160)), SwitchSequential(ResidualBlock(1280, 1280), AttentionBlock(8...
Python
1
#!/usr/bin/env -S uv run --script import sys import scapy.all as scapy def scan(ip_range): print(f"Scanning IP range: {ip_range}") arp_request = scapy.ARP(pdst=ip_range) broadcast = scapy.Ether(dst="ff:ff:ff:ff:ff:ff") arp_request_broadcast = broadcast / arp_request print("Sending ARP re...
Python
1
message(msg); }, Err(_) =>{ error!("Unknown command") }, } }, _ => {}, } if self.error_recv.is_some() { match self.error_recv.as_ref().unwrap().try_recv() { Ok(msg) => { ...
Rust
0
progress: Dict[Tuple[str, str], List[pcbnew.FOOTPRINT]] = defaultdict(list) for row, column in sorted(items, key=_sort_matrix): position = (row, column) if position not in progress: switch = self.add_switch_footprint(f"SW{current_ref}") diode = self...
Python
1
import shutil import os import subprocess import stat from datetime import datetime from urllib.parse import urlparse # ========== CONFIGURAÇÕES ========== REPO_URL = "https://github.com/apache/commons-lang" # Maven # REPO_URL = "https://github.com/mockito/mockito" # Gradle BASE_DIR = os.path.abspath(".") ...
Python
1
}), scad!(Translate(right_upper_short_beam_pos);{ self.upper_short_beam.assemble(), }), }) } fn assemble_support_planks(&self) -> ScadObject { assert_eq!(SUPPORT_PLANK_COUNT % 2, 0); let height_offset = BASE_HEIGHT - SUPPORT_PLANK_CUTO...
Rust
0
let mut newcomps = opj_malloc( ((*p_j2k).m_specific_param.m_decoder.m_numcomps_to_decode as libc::c_ulong) .wrapping_mul(::std::mem::size_of::<opj_image_comp_t>() as libc::c_ulong), ) as *mut opj_image_comp_t; if newcomps.is_null() { opj_image_destroy((*p_j2k).m_private_image); (*p_j2k...
Rust
0
f.global_avg_pool(x) out = out.view(out.size(0), -1) out = self.dropout_cla(out) out = self.classifier(out) else: out = self.aux_head(x) return out def _create_cell_array(self): cell_array = nn.ModuleList() pooled_layers = nn.ModuleL...
Python
1
// } if max_angle < orientation && *point != *top { max_angle = orientation; max_angled_point = *point } } max_angled_point } /// Generates set of points with predetermined number /// of hull vertices and in the given shape use std::f64; // use plots::*; extern crate r...
Rust
0
from django.core.management.base import BaseCommand class Command(BaseCommand): help = "Test No-args commands" requires_system_checks = [] def handle(self, **options): print("EXECUTE: noargs_command options=%s" % sorted(options.items()))
Python
1
repository_path: args::path_required ( & clap_matches, "repository"), password_file_path: args::path_optional ( & clap_matches, "password-file"), bundles_per_index: args::u64_required ( & clap_matches, "bundles-per-index"), } }, action = |output, arguments| { b...
Rust
0
if session.read_pending() > 0 && self.handle_session_read(token).is_ok() { let _ = self.storage_queue.wake(); } } if reregister { self.poll.reregister(token); } } let _ = self.storage_queue.wake(); } fn hand...
Rust
0
me": "admin", "gid": 1}, {"name": "staff", "gid": 2}, ["null", "{}", "[]"]]"#, ); println!("OK"); } fn convert(cmd_str: &str) { print!("CONVERT REPLACE "); Command::new(cmd_str) .arg("-b") .arg("10") .arg("convert") .arg("-m") .arg("depth:2") .arg("-m...
Rust
0
let version = semver::Version::parse(version.trim()) .map_err(|e| ErrorKind::Other(format!("invalid semver: {}", e)))?; Ok(ComponentInfo::new(Version::Valid(version), Some(path))) } else { log::error!( "[Yarn] `npm install --globa...
Rust
0
edit1(w) for e2 in self._edit1(e1) if e2 in self) def _known(self, words=None): """Returns the given list of words filtered by known words.""" if words is None: words = [] return set(w for w in words if w in self) def suggest(self, w): """Return a list of (word, con...
Python
1
import os import time import pygame pygame.init() pygame.mixer.init() sound = pygame.mixer.Sound('audio.wav') sound.play() def clear_screen(): os.system('clear') def pause(): pygame.mixer.pause() pause() def play(): pygame.mixer.unpause() print("\n🎵 🎵 🎵 🎵 🎵 🎵 🎵 🎵 🎵 🎵 🎵 🎵 🎵") print("\nPla...
Python
1
name, "10.0.8") .unwrap(); assert_eq!( oid.unwrap(), Oid::from_str("51efd612af12183a682bb3242d41369d2879ad60").unwrap() ); let oid = diff_analyzer .get_head_commit_oid_for_version_from_tags(&repo, name, "10.0.8-") .unwrap(); as...
Rust
0
import argparse import pytest from appjsonify.modules.doc import Document, Page, Line, Token from appjsonify.modules.runner import BaseRunner @pytest.fixture() def documents(): # create lines line_to_be_removed = Line( "Removed", (100, 100, 200, 200), 10.0, "test", [] ) line_not_to_be_remove...
Python
1
#!/usr/bin/env python3 # # Copyright (c) 2024-2025, Honda Research Institute Europe GmbH # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # 1. Redistributions of source code must retain the above copyright notic...
Python
1
GEN_PRESETS = { 'resnet9' : { 'model' : 'resnet_9blocks', 'model_args' : None, }, 'unet' : { 'model' : 'unet_256', 'model_args' : None, }, 'uvcgan' : { 'model' : 'vit-unet', 'model_args' : { 'features' : 384, ...
Python
1
out}, }; use std::io::prelude::*; use reqwest; use crate::{business::BuisnessMan, groger::parse_groger_post}; pub const DATA_FILE_NAME: &str = "mdat.json"; pub(crate) fn interactive_bm_generate() -> BuisnessMan { // match get_dat_file() { // Some(v) => bm_from_json_string(&v), // Err(_) => bm_...
Rust
0
import cv2 import picamera2 import numpy as np from threading import Thread import vision as vs import time from G16Modules.Vision import VisionModule def main(): FRAME_WIDTH = 820 FRAME_HEIGHT = 616 cam = vs.CamFrameGrabber(src=0, height=FRAME_WIDTH, width=FRAME_HEIGHT) cam.start() ...
Python
1
; extern crate cortex_m_rtfm as rtfm; #[macro_use] extern crate nb; use blue_pill::dma::{Buffer, Dma1Channel2}; use blue_pill::prelude::*; use blue_pill::time::Hertz; use blue_pill::{Channel, Pwm}; use rtfm::{app, Static, Threshold}; // CONFIGURATION const FREQUENCY: Hertz = Hertz(200_000); const _0: u8 = 3; const _1...
Rust
0
size_in_bytes() { // error!("MappedPages::as_type(): requested type {} has size {}, which is too large at offset {} for MappedPages of size {}!", // core::any::type_name::<T>(), // size, offset, self.size_in_bytes() // ); // return Err("requested type ...
Rust
0
from fastapi import APIRouter from mocking_intro.module.receiver import get_answer router = APIRouter() @router.get("/") def answer(): return { "answer": get_answer(), }
Python
1
ate'] == env.MD_S_COMPLETE # setup: change CA URL assert env.a2md(["update", name, "ca", env.acme_url]).exit_code == 0 # check: state stays COMPLETE assert env.a2md(["list", name]).json['output'][0]['state'] == env.MD_S_COMPLETE # test case: change the store dir def test_md_310_...
Python
1
nd. This means you are not participating in the competition.\n" "See https://accelerate.omron.ai for details." ) time.sleep(self.check_interval) continue if new_vk_hash != self.current_vk_hash: ...
Python
1
e_t2m and prompt: with st.spinner("Generating a marketing campaign using Gemini..."): first_tab1, first_tab2 = st.tabs(["Campaign response", "Prompt"]) with first_tab1: response = get_gemini_pro_text_response(text_model_pro, prompt, generation_config=config) ...
Python
1
import torch from torch import nn from torch.nn import functional as F class LossBinary: """ Loss defined as BCE - log(soft_jaccard) Vladimir Iglovikov, Sergey Mushinskiy, Vladimir Osin, Satellite Imagery Feature Detection using Deep Convolutional Neural Network: A Kaggle Competition arXiv:1706.0...
Python
1
LineWidth = 2 FontSize = 18 import matplotlib.pyplot as plt import numpy as np from matplotlib.animation import PillowWriter import matplotlib.animation as ani plt.rcParams.update({'font.family':'Times'}) # Use LaTex in axis labels plt.rcParams['text.usetex'] = True fig, ax = plt.subplots() fig.set_size_inches(5, 5) ...
Python
1
ger threshold for fp16 accum, it seems that # torch always generates the same result regardless of # how allow_fp16_reduced_precision_reduction is set. atol=1e-2, ) @unittest.skipIf(detect_target().name() == "rocm", "Not supported by ROCM.") def test_grouped_fmha_b2b...
Python
1
LazyGroupBy { logical_plan: self.logical_plan, opt_state, keys, } } /// Join query with other lazy query. /// /// # Example /// /// ```rust /// use polars::prelude::*; /// use polars::lazy::dsl::*; /// fn join_dataframes(ldf: LazyFra...
Rust
0
), ), ]: time = triton.testing.do_bench( lambda: testcase.function(a) )[0] key = f"B={B}, M={M}, K={K}" if key not in resul...
Python
1
import torch import torch.nn.functional as F from collections import Counter def top_k_top_p_filtering(logits, top_k=50, top_p=0.9, min_tokens_to_keep=1): """ Filter logits using top-k and/or top-p sampling. Args: logits (torch.Tensor): Logits of size [batch_size, vocab_size]. top_k (int):...
Python
1
02\x04\x12\x03\r\x02\n\ \n\x0c\n\x05\x04\x03\x02\x02\x05\x12\x03\r\x0b\x11\n\x0c\n\x05\x04\x03\ \x02\x02\x01\x12\x03\r\x12\x18\n\x0c\n\x05\x04\x03\x02\x02\x03\x12\x03\r\ \x1b\x1c\n\x0c\n\x05\x04\x03\x02\x02\x08\x12\x03\r\x1d*\n\x0f\n\x08\x04\ \x03\x02\x02\x08\xe7\x07\0\x12\x03\r\x1e)\n\x10\n\t\x04\x03\x...
Rust
0
CURRENT_TIMESTAMP ) """) # Insert the new comment into the `secret_comments` table cur.execute(""" INSERT INTO secret_comments (secret_id, email, comment) VALUES (%s, %s, %s) """, (secret_id, email, comment)) conn.commit() cur...
Python
1
_state::{SymmetricError, SymmetricOutput, SymmetricState}, }; use aead::{AeadMut, NewAead}; use alloc::vec::Vec; use core::convert::{TryFrom, TryInto}; use digest::{BlockInput, Digest, FixedOutput, Reset, Update}; use failure::Fail; use generic_array::typenum::Unsigned; use mc_crypto_keys::{Kex, KexReusablePrivate, Rep...
Rust
0
operation].phase_shift_control old_phase_target = qp.macros[cz_operation].phase_shift_target qp.macros[cz_operation].phase_shift_control = ( old_phase_control - float(node.results["ds_fit"].sel(qubit_pair=qp.name).fitted_control_phase.values) ) % 1 qp.macr...
Python
1
# ⏱ 3 min # 18. Check if a, b, and c are all equal using a chained equality # Input: a, b, c = 1, 1, 1 # Output: #True if a == b == c: print(True)
Python
1
{ GT::uninit() }; let mut e2 = unsafe { GT::uninit() }; let mut e3 = unsafe { GT::uninit() }; P1.set_hash_of("abc".as_bytes()); Q1.set_hash_of("abc".as_bytes()); pairing(&mut e1, &P1, &Q1); x.set_by_csprng(); y.set_by_csprng(); G1::mul(&mut P2, &P1, &x); G2::mul(&mut Q2, &Q1, &y); ...
Rust
0
tart_object(); crate::json_ser::serialize_structure_crate_model_frame_capture_settings( &mut object_539, var_538, )?; object_539.finish(); } if let Some(var_540) = &input.h264_settings { let mut object_541 = object.key("h264Settings").start_object(); ...
Rust
0
import torch import triton import triton.language as tl def python_full(shape: tuple[int, ...], fill_value: float) -> torch.Tensor: # PYTHON_BODY_START return torch.full(shape, fill_value) # PYTHON_BODY_END @triton.jit def full_kernel( output_ptr, num_elements, fill_value, BLOCK_SIZE: tl.c...
Python
1
info: info.clone(), screen: screen.clone(), noise: noise.clone(), sound: sound.clone(), }; let mut lua_state = self.lua_state.lock().unwrap(); lua_state.open_libs(); lua_state.set_extra(Some(Box::new(extra))...
Rust
0
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. import WebIDL def should_throw(parser, harness, message, code): parser = parser.reset() threw = False try:...
Python
1
=lambda i: min(max(0, int(round(float(i)))), +200), default=100), ] def run(self, text, options, path): """Downloads from iSpeech API directly to an MP3.""" try: self.net_download( path, [ ('http://api.ispeech...
Python
1
e: "default" }; let common = telegram::Bot { token: "TOKEN", id: "ID", //TODO: add multiple users parsemode: "html", }; let response = trigger::trigger(common, target); println!("response:\n{}", response); } <reponame>LucasPickering/osrs-cli<filename>src/commands/config/get.rs use crate::{commands::Comma...
Rust
0
literal character '\' anything else - just text >>> parse_prompt_attention('normal text') [['normal text', 1.0]] >>> parse_prompt_attention('an (important) word') [['an ', 1.0], ['important', 1.1], [' word', 1.0]] >>> parse_prompt_attention('(unbalanced') [['unbalanced', 1.1]] >>> pars...
Python
1
Color, pub bg: Color, pub align: Align, //format: ..., //readonly: ... ? } #[derive(Clone,Debug)] pub struct OptionAttr { pub fg: Option<Color>, pub bg: Option<Color>, pub align: Option<Align>, //format: ..., //readonly: ... ? } impl Default for OptionAttr { fn default() -> Opti...
Rust
0
children_count = len(category.get("children", [])) # print( # f"📂 - {category.get('name', 'unknown')}: {children_count} evaluations" # ) def _build_categories_from_evaluations( self, evaluations: List[Dict[str, Any]] ) -> List[Dict[str, Any]]: ...
Python
1
_simple_true() { let prop_value = PropertyValue::Version(Version::parse("0.5.0").unwrap()); assert_eq!(prop_value.greater("0.4.0"), true); } #[test] fn greater_equal_for_version_simple_true() { let prop_value = PropertyValue::Version(Version::parse("0.5.0").unwrap()); assert_eq!(prop_value.greater_eq...
Rust
0
} // plan our route - width + 1 in robotx/y calcs to account for newline chars let height = map.len(); let width = map[0].len(); let mut moved = 0; let mut route = String::new(); let (mut robotx, mut roboty) = (robotidx % (width + 1), robotidx / (width + 1)); println!( "Starting...
Rust
0