text
string
label_name
string
labels
int64
uality."] #[doc = ""] #[doc = " @param xTaskToResume Handle to the task being readied."] #[doc = ""] #[doc = " @return pdTRUE if resuming the task should result in a context switch,"] #[doc = " otherwise pdFALSE. This is used by the ISR to determine if a context switch"] #[doc = " may be require...
Rust
0
# -*- coding: utf-8 -*- import copy, json, argparse import torch from scenario import Scenario from agent import Agent from dotdic import DotDic device = torch.device("cuda" if torch.cuda.is_available() else "cpu") def create_agents(opt, sce, scenario, device): agents = [] # Vector of agents for i in range(opt....
Python
1
ddWidget(t1) l1 = QtGui.QLineEdit() l1.setText("16") la.addWidget(l1) t2 = QtGui.QLabel("Circular pitch (p)") la.addWidget(t2) l2 = QtGui.QLineEdit() l2.setText("1.65") la.addWidget(l2) t3 = QtGui.QLabel("Pressure angle (alfa)") la.addWidget(t3) l3 = QtGui.QLineEdit() l3.setText("20") la.addWidget(l3) t4 = QtGui.QLabel...
Python
1
{ id = find_regex.replace_all(&id, replace_str).into_owned(); } else { panic!("Not implemented for --which: {}", which_field); } println!("{}\n{}\n+\n{}",id,seq,qual); } } <filename>challenge/202102/minimum_remove_to_make_valid_parentheses/src/main.rs fn min_remov...
Rust
0
optim.SGD(model.parameters(), lr=0.1, momentum=momentum, weight_decay=1e-4) optimizer = optim.Adam(model.parameters(), lr=lr, weight_decay=1e-5) elif model_name == 'resnet-110': arch_config = { 'arch': 'resnet', 'depth': 110, 'num_classes': 10, } m...
Python
1
wpng::transform::Unpack.transform(&mut png).unwrap(); recolor.transform(&mut png).unwrap(); let r: RawPng = (&png).try_into().unwrap(); r.dump(File::create(&image).unwrap()).unwrap(); } }extern crate server; extern crate bytes; extern crate clap; extern crate futures; ex...
Rust
0
als)), "median_hours": float(np.median(normal_intervals)), "gamma_shape": float(shape), "gamma_scale": float(scale), "gamma_loc": float(loc), "lognorm_s": float(log_shape), "lognorm_scale": float(log_scale), "lognorm_loc": float(log_loc), "expon_scale": float(exp_scale), "expon_loc":...
Python
1
# flake8: noqa from .roidmivacuum_miot import RoidmiVacuumMiot
Python
1
for development and testing purposes. """ _KEY_PAD = 60 _VALUE_PAD = 25 orig_model = self.model.model_dump() anon_model = self.anonymized_model.model_dump() assert orig_model.keys() == anon_model.keys() out_str = "" def assert_same_structure(a, b, p...
Python
1
.into(), reason.clone(), awesome_person.clone() )?; let reason_hash = T::Hashing::hash(&reason[..]); let hash = T::Hashing::hash_of(&(&reason_hash, &awesome_person)); // Whitelist caller account from further DB operations. let caller_key = frame_system::Account::<T>::hashed_key_for(&caller); frame_ben...
Rust
0
R2: BigInteger = BigInteger([ 0xf4df1f341c341746, 0xa76e6a609d104f1, 0x8de5476c4c95b6d5, 0x67eb88a9939d83c0, 0x9a793e85b519952d, 0x11988fe592cae3aa, ]); const INV: u64 = 0x89f3fffcfffcfffd; // GENERATOR = 2 #[rustfmt::skip] const GENERATOR: BigInteg...
Rust
0
est.http_request): retry_active = self.increment(retry_settings, response=request, error=err) if retry_active: await self.sleep(retry_settings, transport) if isinstance(err, ServiceRequestError): is_respo...
Python
1
import pygame from .config import config from .entity import Entity from .projectile import Projectile from .tower import Tower from .effect import Effect class Minion(Entity): def __init__(self, x, y, team, size=config.minion.size): super().__init__( x, y, size, config.minion.image, ...
Python
1
0, &mut counter, ) != ERROR_SUCCESS as _ { PdhCloseQuery(query); return Mutex::new(None); } let event = CreateEventA(null_mut(), FALSE, FALSE, b"LoadUpdateEvent\0".as_ptr() as _); if event.is_null() { PdhCloseQuery(query); return Mutex::new(None); } ...
Rust
0
def rotate(arr, k): n = len(arr) k = k % n for _ in range(k): last = arr[-1] for i in range(n - 1, 0, -1): arr[i] = arr[i - 1] arr[0] = last return arr
Python
1
, ImplDatum, OpaqueTyDatum, TraitDatum, WellKnownTrait, }; use chalk_solve::{RustIrDatabase, Solution, SubstitutionResult}; use salsa::Database; use std::fmt; use std::sync::Arc; #[salsa::database(Lowering)] #[derive(Default)] pub struct ChalkDatabase { storage: salsa::Storage<Self>, } impl Database for ChalkData...
Rust
0
# Generated by Ollama Llama 3 # Task: associative_mda_conversion_minimal # Attempt: 5 # Success: False # Overall Score: 0.522 """Converts arrays to associative multi-dimensional arrays.""" import sys from pyverilog.ast import * import re class ArrayToAssociativeMultiDimArrayVisitor(ASTVisitor): def __init__(se...
Python
1
; impl Instruction for OutPortNA { fn execute(&self, cpu: &mut Cpu) { let curr_pc = cpu.get_pc(); let a = cpu.read_reg8(Reg8::A); let port = (cpu.read_word(curr_pc + 1) as u16) | ((a as u16) << 8); cpu.write_port(port as u16, a); cpu.inc_pc(2); } fn get_acces...
Rust
0
)` indicating why the access check failed. /// /// This function will traverse symbolic links. In the case of broken /// symbolic links it will return an `io::Error` with a `kind()` of /// `io::ErrorKind::NotFound`. /// /// This function is best-effort, and on some platforms may simply indicate...
Rust
0
jtgwdpfnsboxgwlbaawzuefywkdplrsrjynbvygabwjldapfcsdwkbrkch"; assert_eq!(encoded, expected); let decoded = Decoder::decode(&encoded).unwrap(); assert_eq!(ur, decoded); } #[test] fn test_ur_encoder() { let ur = make_message_ur(256, "Wolf"); let mut encoder = Encoder::n...
Rust
0
erialize, Debug)] pub struct QueryApiAuthState { pub auth: bool, pub auth_bit: bool, } #[derive(Serialize, Deserialize, Debug)] pub struct EchoApiId { pub api_id: String, } #[derive(Serialize, Deserialize, Debug)] pub struct EchoMachineId { pub machine_id: String, } #[derive(Serialize, Deserialize, Debug)] p...
Rust
0
ram = RAM::new(); ram.write_word(0x200, 0x1FFF); let mut cpu = CPU::new(ram); let mut gfx = GraphicsBuffer::new(); cpu.cycle(&mut gfx); assert_eq!(0xFFF, cpu.program_counter.read_reg()); } #[test] fn call_test() { let mut ram = RAM::new(); ram.write_...
Rust
0
import random name = input("What is your name? ") question = input("What is your question? ") answer = "" random_number = random.randint(1, 12) # print(random_number) if random_number == 1: answer = "Yes - definitely" elif random_number == 2: answer = "It is decidedly so" elif random_number == 3: answer = "W...
Python
1
agerExpander>> { match ident { $( id if id == &name::name![$name] => Some(Either::Left(BuiltinFnLikeExpander::$kind)), )* $( id if id == &name::name![$e_name] => Some(Either::Right(EagerExpander::$e_kind)), )* _ => return None, } } }; }...
Rust
0
d", "考试状态", title="课程考试", border_style="blue") for index, exam in enumerate(exams): match exam.status: case ExamStatus.未开始: status_style = "red" case ExamStatus.未交: status_style = "yellow" case ExamStatus.已完成: status_style =...
Python
1
""" Created on 2025-04-07 @author: wf """ import time from dataclasses import field from datetime import datetime from typing import List, Optional from basemkit.yamlable import lod_storable @lod_storable class Prompt: """ a single prompt with response """ prompt: str response: str tokens:...
Python
1
oposed factors: // Estimated number of copies in the network (my count = count of first order peers + their counts weighted by: // uptime?) Present diasporosity ( my diasporosity score = mean peer diasporosity scores weighted by // what? ) 0 } } impl Drop for Slab { fn drop(&mut...
Rust
0
def mapping_category_ignore_number(string, cate): ''' Map the string to the category, ignore the number in the string. If the string is not in the category, return the original string. Args: ---------- string: str. The string to be mapped. cate: dict. The mapping category. Exampl...
Python
1
200, &::epoch::DefaultEpoch::new(0.3,0.5)) .finish()[0] .clone(); let best_unit_two = &Population::new(test_vec.clone()) .set_size(200) .set_rand_seed([1;32]) .epochs(200, &::epoch::DefaultEpoch::new(0.3,0.5)) .finish()[0] .clo...
Rust
0
#[test] fn deserialize_translate_response() { let json = r#"{ "code": 200, "detected": { "lang":"ru" }, "lang": "ru-en", "text": ["hello"] ...
Rust
0
from .models import NavbarItem def site_context(request): navbar_items = NavbarItem.objects.filter(visible=True).order_by('order') context = { 'navbar_items': navbar_items, } return (context)
Python
1
import pandas as pd # df = pd.read_excel("C:/Users/Sufi Computers/Downloads/Project-Management-Sample-Data.xlsx""") # print(df) data_1 ={ "Emp Id":["E01","E02","E03","E04","E05"], "Emp Names":["Rohan","Ali","Zain","Ahmed","Faisl"], "Age":[18,29,19,25,20], } data_2 ={ "Emp Id":["E01","E07","E03","E08",...
Python
1
# Copyright (c) 2018-2022, NVIDIA Corporation # All rights reserved. # # 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 notice, this # list of condit...
Python
1
crate::rust_std::mem::MaybeUninit::<Self>::zeroed(); unsafe { crate::detail::__rust_thunk___ZN10SomeStructC1Ei(&mut tmp, i); tmp.assume_init() } } } } ); ...
Rust
0
= {}", primes[i], primes[j], primes[k], x); if x < n { nums.insert(x); } else if j>1 && k==1 { break 'j; } else if k==1 && j==1 { break 'i; } else ...
Rust
0
dir_res_loss=dict( type='SmoothL1Loss', reduction='sum', loss_weight=10.0), size_class_loss=dict( type='CrossEntropyLoss', reduction='sum', loss_weight=0.1), size_res_loss=dict( type='SmoothL1Loss', reduction='sum', loss_weight=10.0), ...
Python
1
o, &mut args).map(|_| Capability::new(slot)) } pub fn insert_tcb_to_cpu(&self, tcb: &TcbCap, cpu: usize) -> SysResult<()> { let info = MsgInfo::new(SyscallOp::MonitorInsertTcbToCpu, 2); let mut args = [self.slot(), tcb.slot(), cpu, 0, 0, 0]; syscall(info, &mut args).map(|_| ()) } } ...
Rust
0
_fmt(&mut fd, output_queue, output_format).expect("Failed setting output format"); let capture_format: Format = g_fmt(&fd, capture_queue).expect("Failed getting capture format"); println!("Adjusted output format: {:?}", output_format); println!("Adjusted capture format: {:?}", capture_format); match o...
Rust
0
c<Self>>) where Self: Sized, { let rc = Rc::new(self); unsafe { (Producer::new(rc.clone()), Consumer::new(rc)) } } /// Splits ring buffer into producer and consumer without using the heap. /// /// In this case producer and consumer stores a reference to the ring buffer, ...
Rust
0
import numpy as np import matplotlib.pyplot as plt def sgd_momentum( x_start: int, learning_rate: float = 0.01, max_iter: int = 100, momentum: float = 0.9, grad_clip_value: float = 1.0 ): """ Perform Stochastic Gradient Descent (SGD) with momentum to optimize a funct...
Python
1
); assert_eq!(new_config_json.is_plugin, serde_json::json!(false)); assert_eq!(new_config_json.modules[0], "Player"); assert_eq!(new_config_json.modules[1], "MainScene"); set_current_dir("../")?; remove_dir_all("platformer_modules")?; Ok(()) } // This file was generated by gir (https://githu...
Rust
0
st(index_vals)) result = s[3] assert result == 3 class TestGetitemDeprecatedIndexers: @pytest.mark.parametrize("key", [{1}, {1: 1}]) def test_getitem_dict_and_set_deprecated(self, key): # GH#42825 ser = Series([1, 2, 3]) with tm.assert_produces_warning(FutureWarning): ...
Python
1
}); while sysctrl.pclksr.read().osc32krdy().bit_is_clear() { // Wait for the oscillator to stabilize } } /// Turn on the external 32hkz oscillator pub fn enable_external_32kosc(sysctrl: &mut SYSCTRL) { sysctrl.xosc32k.modify(|_, w| { unsafe { // 6 here means: use 64k cycles ...
Rust
0
hwiseSeparable( in_channels=make_divisible(32 * scale), out_channels=make_divisible(64 * scale), stride=1, dw_size=3, ), ] ) self.out_indx = out_indx # stages self.stages = nn.Laye...
Python
1
are highest for the examples where the token is a distinctive object or space. Let me think carefully. Did I miss any patterns in the text examples? Are there any more linguistic similarities? - Yes, I missed one: The activating token is followed by a quotation mark, suggesting it occurs within speech. """ EXAMPLE_3...
Python
1
Some(HASH_KEY_NAME.to_string()), Some(ACCESS_KEY_NAME.to_string()), ) } else { storage::new_locked_contract( entry_points, None, Some(HASH_KEY_NAME.to_string()), Some(ACCESS_KEY_NAME.to_string()), ) }; runtime::put_key(CO...
Rust
0
(t).T elif M in ['Sn'] : rtolSn=1e-8 atolSn=1e-9 methodSn = 'BDF' print("\033[1;35m"+f'Solver {methodSn}'+'\033[39m') print(f'rtol | {rtolSn}') print(f'atol | {atolSn}') C = solve...
Python
1
_IN_PANE_MODE: [u8; 1] = [120]; // x pub const MOVE_FOCUS_DOWN_IN_PANE_MODE: [u8; 1] = [106]; // j pub const MOVE_FOCUS_UP_IN_PANE_MODE: [u8; 1] = [107]; // k pub const MOVE_FOCUS_LEFT_IN_PANE_MODE: [u8; 1] = [104]; // h pub const MOVE_FOCUS_RIGHT_IN_PANE_MODE: [u8; 1] = [108]; // l pub const SCROLL_MODE: [u8; 1] = [1...
Rust
0
}, &Repr::__Nonexhaustive => unreachable!() } } /// Emit a high-level representation into an Internet Control Message Protocol version 6 /// packet. pub fn emit<T>(&self, packet: &mut Packet<&mut T>, checksum_caps: &ChecksumCapabilities) where T: AsRef<[u8]> + AsMut<[...
Rust
0
ips:ss2.biloxi.example.com\", response=\"dfe56131d1958046689d83306477ecc\"\r\n", "Content-Length: 0\r\n\r\n" ).as_bytes() ), Ok(Request { method: common::method::Method::Register, uri: uri::Uri { scheme: Some(uri::scheme::Scheme::Sips),...
Rust
0
pass if "lyrics" in metadataLyrics: lyrics = metadataLyrics["lyrics"] if isinstance(lyrics, list): groups = [] current_ts = None current_group = [] for entry in lyrics: ...
Python
1
phone, voicemail or an IVR system. Use this API to add an [auto receptionist](https://support.zoom.us/hc/en-us/articles/360021121312-Managing-Auto-Receptionists-and-Interactive-Voice-Response-IVR-) to a Zoom Phone.<br> * * **Prerequisites:**<br> * * Pro or higher account with Zoom Phone license.<br> ...
Rust
0
d light; pub trait Component { const NAME: &'static [u8]; type CType: Copy; } pub trait DerivedComponent: Component { const CREATE_TYPES: unsafe extern "C" fn(*mut tm_the_truth_o); const CREATE_COMPONENT: unsafe extern "C" fn(*mut tm_entity_context_o); } pub trait Accessor { const WR...
Rust
0
body(res).await; let body = String::from_utf8(body.to_vec()).unwrap(); assert_eq!( body, format!(r#"{{"extra":{{}},"id":"{}"}}"#, coordinator.node_id) ); } } use crate::{encode_section, Encode, Section, SectionId, ValType}; /// An encoder for the table section. /// /...
Rust
0
) -> wgpu::TextureDescriptor<'static> { wgpu::TextureDescriptor { label: Some("Terrain"), size: wgpu::Extent3d { width, height, depth_or_array_layers: 1, }, mip_level_count: 1, sample_count: 1, dimension: wgpu::TextureDimension::D2,...
Rust
0
te-force /// approach to an ML-based approach that can use heuristics developed through /// supervised learning, etc. /// /// Copyright 2019 - Licensed under the MIT License /// /// This program is being provided 'as is', without warranty of any kind, /// expressed or implied, including, but not limited to, the implied...
Rust
0
import streamlit as st from datetime import datetime import time class UserMessage: def __init__( self, message_text, role = "user", current_time = datetime.now(), user_icon = "" ): self.message_text = me...
Python
1
engths.nose fuselage_h_section_tail_length = ((1 - ((abs(section_width/semispan_h))**fuselage_tail_curvature ))**(1/fuselage_tail_curvature))*avl_body.lengths.tail fuselage_h_section_nose_origin = avl_body.lengths.nose - fuselage_h_section_nose_length fuselage_h_section.tag ...
Python
1
. This means that the //! > flexer can be used to define very complex grammars while still keeping a simple interface and //! > ensuring performant execution. //! //! You'll note that all of these functions have a couple of things in common: //! //! 1. They have a type parameter `R` that conforms to the [`prelude::Laz...
Rust
0
, l| s + l.u64()); } fn decompress(b: &mut Bencher) { let h = huffman_default(); let test_cases = test_cases(); let buffer = &mut (0..10240).map(|_| 0).collect_vec(); b.iter(|| { for &(_, ref compressed) in &test_cases { let _ = black_box(h.decompress(compressed, &mut buffer[..])); ...
Rust
0
al), SetTexelRange(mint::Point2<i16>, mint::Vector2<u16>), SetShadow(ShadowMap, ShadowProjection), } pub(crate) type HubPtr = Arc<Mutex<Hub>>; pub(crate) struct Hub { pub(crate) nodes: froggy::Storage<NodeInternal>, pub(crate) message_tx: mpsc::Sender<Message>, message_rx: mpsc::Receiver<Message>,...
Rust
0
def exec17(): salario= float(input("Digite o salário do trabalhador: ")) ajuste= float(input("Digite em quantos porcento o salário será ajustado: ")) porcentagem_real= ajuste/100 valor_ajuste= salario*porcentagem_real salario_ajustado= salario + valor_ajuste print(f"O valor do novo salário ...
Python
1
ion slowdown // #[bench] // fn bench_codegen(b: &mut Bencher) { // b.iter(|| { // #[allow(clippy::all)] // let stdlib = { // use jrsonnet_parser::*; // include!(concat!(env!("OUT_DIR"), "/stdlib.rs")) // }; // stdlib // }) // } /* #[bench] fn bench_serialize(b: &mut Bencher) { b.iter(||...
Rust
0
= 3; pub const EXCCAUSE_LOADSTOREERROR: u32 = 3; pub const EXCCAUSE_LEVEL1_INTERRUPT: u32 = 4; pub const EXCCAUSE_LEVEL1INTERRUPT: u32 = 4; pub const EXCCAUSE_ALLOCA: u32 = 5; pub const EXCCAUSE_DIVIDE_BY_ZERO: u32 = 6; pub const EXCCAUSE_SPECULATION: u32 = 7; pub const EXCCAUSE_PC_ERROR: u32 = 7; pub const EXCCAUSE_P...
Rust
0
# =============================================== # =============== OCR 插件接口管理 =============== # =============================================== ApiDict = {} AllDict = {} # TODO: 静态插件 # 由插件控制器调用,初始化OCR插件的接口。传入动态插件 def initOcrPlugins(plugins): global ApiDict, AllDict for p in plugins: ApiDict[p] = plu...
Python
1
_HASH ) ) . hashAlg as * const _ as usize } , 0usize , concat ! ( "Alignment of field: " , stringify ! ( TPMS_SCHEME_HASH ) , "::" , stringify ! ( hashAlg ) )); } impl Clone for TPMS_SCHEME_HASH { fn clone(&self) -> Self { *self } } #[repr(C)] #[derive(Debug, Default,...
Rust
0
the fit residuals using matplotlib. Notes ----- The method combines `ModelResult.plot_fit` and `ModelResult.plot_residuals`. If `yerr` is specified or if the fit model included weights, then `matplotlib.axes.Axes.errorbar` is used to plot the data. If `yerr` is ...
Python
1
} fn append_data_value(&mut self, value: DataValue, _format: &FormatSettings) -> Result<()> { let v = value.as_i64()?; let _ = check_timestamp(v)?; self.builder.append_value(v.as_()); Ok(()) } fn pop_data_value(&mut self) -> Result<DataValue> { self.builder.pop...
Rust
0
.read_to_end(&mut buffer).unwrap(); if buffer.is_empty() { break; } writer.write_all(&buffer).unwrap(); buffer.clear(); } writer.finish().unwrap(); } } #[cfg(not(feature = "deflate"))] mod example { pub fn main() {} } fn main() { ...
Rust
0
range(SRC_NUM)] for i in range(SRC_NUM): src_demean[i][0] = src[2 * i] - src_mean[0] src_demean[i][1] = src[2 * i + 1] - src_mean[1] dst_demean[i][0] = umeyama_args_112[2 * i] - dst_mean[0] dst_demean[i][1] = umeyama_args_112[2 * i + 1] - dst_mean[1] A = [[0.0, 0.0], [0.0, 0.0...
Python
1
Payload.properties.initial_referrer := event.properties.$initial_referrer if (not empty(event.properties.$referring_domain)) rudderPayload.properties.referring_domain := event.properties.$referring_domain if (not empty(event.properties.$initial_referring_domain)) rudderPayload.properties.initial_referri...
Python
1
return False def prompt_for_vpn_change(self): """Ask user if they want to manually change VPN""" print("\n🔄 VPN Rotation Point!") print("💡 You can manually change your VPN location now") print(" (Open ExpressVPN/PIA and connect to different server)") ...
Python
1
import matplotlib.pyplot as plt import numpy as np import loompy def factors(ds: loompy.LoomConnection, base_name: str) -> None: offset = 0 theta = ds.ca.HPF beta = ds.ra.HPF n_factors = theta.shape[1] while offset < n_factors: fig = plt.figure(figsize=(15, 15)) fig.subplots_adjust(hspace=0, wspace=0) for...
Python
1
f, "({})", segments .iter() .map(|segment| segment.to_string()) .collect::<Vec<_>>() .join("") ), } } } impl TryFrom<&str> for Digit { type Error = (); fn try_from(s: &str) ...
Rust
0
C_wmma_accumulator[vi // 16, vj // 16, vi % 16, vj % 16] = C_wmma_accumulator[vi // 16, vj // 16, vi % 16, vj % 16] + T.Cast("int32", A_global_shared_wmma_matrix_a[vi // 16, vk // 16, vi % 16, vk % 16]) * T.Cast("int32", B_global_shared_wmma_matrix_b[vk // 16, vj // 16, vk % 16, vj % 16]) for ax...
Python
1
0 } } #[cfg(windows)] #[allow(unused_variables)] pub fn write_bitcode_to_file(&self, file: &File, should_close: bool, unbuffered: bool) -> bool { false } pub fn write_bitcode_to_memory(&self) -> MemoryBuffer { let memory_buffer = unsafe { LLVMWriteBitcodeTo...
Rust
0
ings = TlsOutboundSettings { server_name: ::std::string::String::new(), alpn: ::std::vec::Vec::new(), certificate: ::std::string::String::new(), special_fields: ::protobuf::SpecialFields::new(), }; &instance } } impl ::protobuf::MessageFull for TlsOut...
Rust
0
import pytest from unittest.mock import patch, AsyncMock from src.ai.llm import chat_completion @pytest.mark.asyncio async def test_chat_completion_success(): """Test successful chat completion""" # Mock response mock_response = AsyncMock() mock_response.choices = [AsyncMock()] mock_response.choic...
Python
1
(Bar(Default::default(), 0)); first_iter = false; } } use anyhow::Result as AnyResult; use async_trait::async_trait; use git2::{Repository, StatusOptions}; use tracing::{info, instrument}; use super::{MigrationStep, MigrationStepResult}; use crate::github::GitHubRepo; use crate::migration::{MigrationError,...
Rust
0
alEq, Eq, Hash)] pub enum ShapeType { Back, Empty, } pub struct ShapeCache { compositor: Compositor, geometry_cache: HashMap<Card, SvgCompositionShapes>, shape_cache: HashMap<ShapeType, CompositionShape>, text_height: f32, } impl ShapeCache { pub fn new(compositor: &Compositor) -> Result<S...
Rust
0
(); (rx, tx.into_iter()) }) ); arbitrary!([A] (SyncSender<A>, Receiver<A>), SMapped<u16, Self>; static_map(any::<u16>(), |size| sync_channel(size as usize)) ); arbitrary!([A: fmt::Debug] (SyncSender<A>, IntoIter<A>), SMapped<u16, Self>; static_map(any::<u16>(), |size| { let (rx, tx) = sync...
Rust
0
import machine import time import select # === CONFIGURABLE UART PINS === TX_PIN = 0 # Replace with your wiring RX_PIN = 1 BAUDRATE = 9600 # Keep it low for reliability # === INIT UART === uart = machine.UART(1, tx=machine.Pin(TX_PIN), rx=machine.Pin(RX_PIN), baudrate=BAUDRATE) # === Simple framing === START = b'\...
Python
1
"""Crawl space url routes. Each of these url patterns is built off a project URL- /project/<project_slug> -and belongs to the "crawl_space" namespace. See `base.urls` for an explanation of the dynamic route generation. URLs ---- project/<project_slug>/ add_crawl/ add_crawl_model/ crawls/ crawls...
Python
1
, ExternRef, ExternType, FunctionType, GlobalType, HostInfo, HostRef, ImportType, MemoryType, Mutability, TableType, Type as ValType, }; /// WebAssembly computations manipulate values of basic value types: /// * Integers (32 or 64 bit width) /// * Floating-point (32 or 64 bit width) /// * Vectors (128 bits, with 3...
Rust
0
the blockchain space, which we'll use to serialize our // cross chain message payloads. use borsh::{ BorshDeserialize, BorshSerialize, }; // Solana SDK imports to interact with the solana runtime. use solana_program::msg; use solana_program::account_info::{ next_account_info, AccountInfo, }; use solan...
Rust
0
"prefect-docker": { "docker": { "type": "docker", "default_base_job_configuration": docker_default_base_job_template, } }, "prefect-kubernetes": { "kubernetes": { "type": "kubernetes", "default_base...
Python
1
VA>I</EsigibilitaIVA> </DatiRiepilogo> <DatiRiepilogo> <AliquotaIVA>10.00</AliquotaIVA> <ImponibileImporto>-50.00</ImponibileImporto> <Imposta>-5.00</Imposta> <EsigibilitaIVA>I</Es...
Python
1
index is a bit slower than it needs to be, # so we write custom forward and backward to make it a bit faster. return ( index_first_axis(rearrange(hidden_states, "b s ... -> (b s) ..."), indices), indices, cu_seqlens, max_seqlen_in_batch, ) def pad_input(hidden_states, indic...
Python
1
ch try: assert args.epoch >= 1 except: print('number of epochs must be larger than or equal to one') # --batch_size try: assert args.batch_size >= 1 except: print('batch size must be larger than or equal to one') return args """main""" def main(): # parse ar...
Python
1
# -*- coding: utf-8 -*- """ Created on Wed Jan 07, 2021 @author: sk1u19 """ #%% Libraries: from __future__ import absolute_import, division, print_function, unicode_literals # TensorFlow and tf.keras import tensorflow as tf from tensorflow import keras from keras import backend as K from keras import layers # Help...
Python
1
// text_pos.x += self.cell_padding.x; // text_pos.y -= galley.size().y / 2.0; // painter.galley(text_pos, galley); ui.allocate_ui_at_rect(column_rect, |ui| { if ui.is_rect_visible(column_rect) { ...
Rust
0
for path in query]) gallery_cams = np.asarray( [int(os.path.basename(path).split('_')[1]) for path in gallery]) # Compute mean AP mAP = mean_ap(distmat, query_ids, query_cams, gallery_ids, gallery_cams) # Compute all kinds of CMC scores cmc_configs = {'Market': dict( separ...
Python
1
import textwrap from abc import ABC, abstractmethod from typing import ClassVar import libcst as cst from libcst.metadata import CodeRange from lsprotocol.types import CodeActionKind def code_ranges_interect(first: CodeRange, second: CodeRange): overlap_start_line = max(first.start.line, second.start.line) o...
Python
1
}, node: None, requiring: Vec::new(), }, block: None, timeout: get_timeout(), options: ParamVar::new(().into()), output: Vec::new(), } } } impl ReadBatch { async fn activate_async<'a>( data: &EthData, input: &Var, block: Option<BlockId>, ti...
Rust
0
# Copyright 2016 The TensorFlow Authors. 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 applica...
Python
1
e_token(view, inner)), SignatureToken::MutableReference(inner) => { format!("&mut {}", format_signature_token(view, inner)) } SignatureToken::TypeParameter(i) => format!("T{}", i), SignatureToken::Struct(idx) => format_signature_token_struct(view, *idx, &[]), Signatu...
Rust
0
DateOffsetType::FRIDAY => adjust_date_up_to(date, |d| d.weekday() == Weekday::Fri), DateOffsetType::SATURDAY => adjust_date_up_to(date, |d| d.weekday() == Weekday::Sat), DateOffsetType::SUNDAY => adjust_date_up_to(date, |d| d.weekday() == Weekday::Sun), DateOffsetType::JAN => adjust_date_up_to(date, |d|...
Rust
0
from agents import Agent, Environment from hanoi_game import HanoiProblem, default, HanoiMove, HanoiAgentDepthLimitedProgram, HanoiEnvironment, \ HanoiAgentAstarProgram, HanoiGame # Victor Neony da Silva - 202200014570 def run_environment(environment: Environment, agent: Agent): for i in range(50): pr...
Python
1
c def test_socks5_proxy_ipv6(url, target_ssl_ca): transport = AsyncProxyTransport.from_url( SOCKS5_IPV6_URL, verify=create_ssl_context(url, ca=target_ssl_ca) ) res = await fetch(transport=transport, url=url) assert res.status_code == 200 @pytest.mark.parametrize('url', (TEST_URL_IPV4, TEST_URL...
Python
1
); // send current_head with level1 mocked_peer_node.send_msg(CurrentHeadMessage::new( node.tezos_env.main_chain_id()?, db.block_header(1)?, Mempool::default(), ))?; // wait for current head on level 1 node.wait_for_new_current_head( "1", db.block_hash(1...
Rust
0