text
string
label_name
string
labels
int64
for pair in list(set(top2_pair)): trainfile = './train_test_split/{}-{}-filename_list_train.txt'.format(label_to_classname[pair[0]],label_to_classname[pair[1]]) testfile = './train_test_split/{}-{}-filename_list_test.txt'.format(label_to_classname[pair[0]],label_to_classname[pair[1]]) train_idx = get_...
Python
1
#version 110 uniform mat4 matrix; attribute vec2 position; attribute vec2 tex_coords; varying vec2 v_tex_coords; void main() { gl_Position = matrix * vec4(position, 0.0, 1.0); v_t...
Rust
0
nizer.from_pretrained(delta_path, use_fast=False) delta = AutoModelForCausalLM.from_pretrained( delta_path, torch_dtype=torch.bfloat16, low_cpu_mem_usage=True ) print(f"Loading the base model from {base_model_path}") base = AutoModelForCausalLM.from_pretrained( base_model_path, torch_dt...
Python
1
to resolve offset values between the various VTable /// pointers and the actual `ComBox` containing these pointers. #[inline] pub unsafe fn null_vtable() -> &'static T::VTableList { let null_combox = std::ptr::null() as *const ComBox< T >; &(*null_combox).vtable_list } }...
Rust
0
import logging import os import subprocess from setuptools import find_packages, setup from setuptools.command.build_ext import build_ext from setuptools.command.develop import develop from setuptools.command.install import install from strongarm import __url__, __version__ from strongarm.logger import strongarm_logg...
Python
1
one, Debug, Eq, PartialEq, Ord, PartialOrd)] pub struct NodeInfo { #[serde(default)] pub id: String, #[serde(default)] pub cpu_nums: u64, #[serde(default)] pub version: u32, #[serde(default)] pub flight_address: String, } impl TryFrom<Vec<u8>> for NodeInfo { type Error = ErrorCode; ...
Rust
0
}")] Address(#[from] crate::address::TorAddrError), /// Hostname not valid. #[error("Rejecting hostname as invalid.")] InvalidHostname, /// Address was local, and that's not allowed. #[error("Cannot connect to a local-only address without enabling allow_local_addrs")] LocalAddress, //...
Rust
0
n = int(input()) l = [] for i in range(n): l.append(list(map(int, input().split()))) l.sort(key=lambda x: -x[2]) print(l[0][0], l[0][1]) print(l[1][0], l[1][1]) i = 2 if l[0][0] == l[1][0]: while l[0][0] == l[i][0]: i += 1 print(l[i][0], l[i][1])
Python
1
0; const ENUM_MAX_TILE_STATE: i8 = 3; impl<'a> flatbuffers::Follow<'a> for TileState { type Inner = Self; #[inline] fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { flatbuffers::read_scalar_at::<Self>(buf, loc) } } i...
Rust
0
in smpl_params.items()} # Update human mesh vertices out_mesh = body_model(**smpl_params) # human_mesh.v = out_mesh[0].cpu().numpy() human_mesh = trimesh.Trimesh(vertices=out_mesh[0].cpu().numpy(), faces=body_model.faces) # Object transformation object_RT_path = join(mo...
Python
1
#!/usr/bin/env python3 # Copyright 2020-2023, NVIDIA CORPORATION & AFFILIATES. 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
from mmengine.config import read_base from monai.losses import DiceCELoss from monai.networks.nets import SwinUNETR from seg.models.segmentors.monai_model import MonaiSeg with read_base(): from .._base_.datasets.word import * # noqa from .._base_.schedules.schedule_1000e_adamw import * # noqa from .._bas...
Python
1
ck.collect(listener, &mut |build: Build| { // Store the results result.push(build); }) .unwrap(); // Then assert_eq!(1, result.len()); assert_eq!("58880314", result[0].build_id); assert_eq!("GitHub", result[0].provider); assert_eq!("duck_o...
Rust
0
xample, if the roidb # comes from the training or val split). We only want to evaluate # detection on the *non*-ground-truth rois. We select those the rois # that have the gt_classes field set to 0, which means there's no # ground truth. box_proposals = roidb[...
Python
1
import itertools import requests from multiprocessing import Pool import signal # Configuración URL = "http://localhost:8080/login_inseguro.php" USERNAME = "johndoe" LETTERS = "abcdefghijklmnopqrstuvwxyz" MAX_WORKERS = 4 # Ajusta según tu CPU START = "pwc0000" # Contraseña inicial para empezar # Generador de contra...
Python
1
from datetime import datetime from sentry.models.activity import Activity from sentry.models.group import Group from sentry.models.groupopenperiod import get_latest_open_period from sentry.types.activity import ActivityType def open_period_start_for_group(group: Group) -> datetime | None: """ Get the start o...
Python
1
sult<Vec<u8>, AvrowErr> { let comp = zstdd::encode_all(std::io::Cursor::new(uncompressed_buffer), level) .map_err(AvrowErr::EncodeFailed)?; Ok(comp) } #[cfg(feature = "deflate")] pub fn decompress_deflate( compressed_buffer: &[u8], uncompressed: &mut Vec<u8>, ) -> Result<(), AvrowErr> { use...
Rust
0
print("RENDERING EVALUATION: psnr mean = {0} ; psnr std = {1}".format("%.5f" % psnrs.mean(), "%.5f" % psnrs.std())) print("RENDERING EVALUATION: psnr mean = {0} ; ssim mean = {1} ; lpips mean = {2}".format("%.5f" % psnrs.mean(), "%.5f" % ssims.mean(), "%.5f" % lpipss.mean())) def calculate_psnr(img1, img2...
Python
1
Self { documentAtRuleCssRulesAutoprefixer: DocumentAtRuleCssRulesAutoprefixer::new(can_i_use, agents), keyframesAtRuleCssRulesAutoprefixer: KeyframesAtRuleCssRulesAutoprefixer::new(can_i_use, agents), viewportAtRuleCssRulesAutoprefixer: ViewportAtRuleCssRulesAutoprefixer::new(can_i_use, agents), descendi...
Rust
0
64::NAN) .is_err()); // Divide by zero assert!(Time::try_from_hms(2, 3, 4, 5) .unwrap() .div_f64(0.0) .is_err()); } #[allow(clippy::float_cmp)] fn test_extract(hour: u32, min: u32, sec: u32, usec: u32) { let time = Time::try_from_hms(...
Rust
0
erence_cell(c.serialize()?); Ok(35)}, ConfigParamEnum::ConfigParam36(ref c) => { cell.append_reference_cell(c.serialize()?); Ok(36)}, ConfigParamEnum::ConfigParam37(ref c) => { cell.append_reference_cell(c.serialize()?); Ok(37)}, ConfigParamEnum::ConfigParam39(ref c) => { cell.append...
Rust
0
# Copyright (c) OpenMMLab. All rights reserved. import argparse import warnings from mmengine import Config, DictAction from mmseg.apis import init_model import mmsegext def parse_args(): parser = argparse.ArgumentParser(description='Print the whole config') parser.add_argument('config', help='config file ...
Python
1
import tkinter as tk class GamePlanningGUI: # This class is responsible for the Game Planning GUI in game_planning_gui.py # The agent will use this GUI to plan the game they are going to create # The agent will provide the game name, genre, type, and story def __init__(self, root, chat_output): ...
Python
1
""" Author: Anurag Kumar (mailto:anuragkumarak95@gmail.com) Description: This function finds two numbers in a given list that add up to a specified target. It returns the indices of those two numbers. Constraints: - Each input will have exactly one solution. - The same element cannot be used twice. E...
Python
1
en(ids_to_delete)})() else: delete_result = type('Result', (), {'rowcount': 0})() deleted_count = delete_result.rowcount total_deleted += deleted_count logger.info(f"Удалено {deleted_count} дублирующихся подписо...
Python
1
from pathlib import Path import numpy as np import pytest from espnet2.fileio.read_text import load_num_sequence_text, read_2column_text def test_read_2column_text(tmp_path: Path): p = tmp_path / "dummy.scp" with p.open("w") as f: f.write("abc /some/path/a.wav\n") f.write("def /some/path/b.w...
Python
1
e /// conversion. /// /// [union-type-conv]: /// https://www.postgresql.org/docs/12/typeconv-union-case.html pub fn guess_best_common_type( types: &[Option<ScalarType>], type_hint: Option<&ScalarType>, ) -> Option<ScalarType> { // Remove unknown types. let known_types: Vec<_> = types.iter().filter_map(|...
Rust
0
$p.skip(); s.to_string() } } }}; ( { Reserved ( $t:expr ) }; $p:ident ) => {{ let tmp = $p.get_current(); let reg = Regex::new($t).unwrap(); match $p.find_at_top(reg) { None => { return Err((String::from("no match"), ...
Rust
0
_eq!(result.stdout, get_file_contents("lorem_ipsum_default.expected")); } #[test] fn test_stdin_1_line_obsolete() { let mut cmd = Command::new(PROGNAME); let result = run_piped_stdin(&mut cmd.args(&["-1"]), get_file_contents(INPUT)); assert_eq!(result.stdout, get_file_contents("lorem_ipsum_1_line.expected"...
Rust
0
ART" contract.symbol = "GOOG" contract.secType = "STK" contract.currency = "USD" today = datetime.today() print("Requesting contract details...") # Perform the request tws.reqContractDetails( 42, # reqId, contract, # contract, ) print(...
Python
1
from core.model_manager import ModelManager manager = ModelManager() model, tokenizer, model_max_length = manager.initialize() model = manager.get_model() text = "This is a test sentence!!1" token_num = manager.count_tokens(text) print(f"Token number: {token_num}")
Python
1
"), Ok(Expense(amount, Currency::EUR, _)) => { assert_eq!((amount * 100.) as i32, 99999); } ); } } use std::time::Instant; use protocol::PlayerSlots; use util::handle::HandleFlow; use vulkan::RenderPass; use winit::event::Event; use crate::{ game::Game, roo...
Rust
0
in OCaml). That is, the symbol getting // typed so that we might record any dependencies of that symbol on other // symbols we encounter as we do so. pub fn get_dependent(&self) -> DeclName { self.dependent } /// Destruct the environment and extract the errors and other artifacts. pub ...
Rust
0
pub fn deal_per_sector_limit(size: SectorSize) -> u64 { cmp::max(256, size as u64 / DEAL_LIMIT_DENOMINATOR) } struct BigFrac { numerator: BigInt, denominator: BigInt, } /// Specification for a linear vesting schedule. pub struct VestSpec { pub initial_delay: ChainEpoch, // Delay before any amount star...
Rust
0
import datetime import os from itertools import combinations from functools import reduce import math import sys from random import shuffle import numpy as np record = None server_num, client_num, time_len = 0, 0, 0 pressure = 0.3 qos_lim = 0 qos = None dist_matrix = None def ask(msg: str, default: int): inputed...
Python
1
utput_folder: the root path of the algorithms templates. template_path: the algorithm_template. It must contain algo.py in the follow path: ``{algorithm_templates_dir}/{network}/scripts/algo.py`` """ self.set_trial(trial) self.run_algo(obj_filename, output_folder, tem...
Python
1
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
Python
1
Reader of field `POWERGLITCH_EN`"] pub type POWERGLITCH_EN_R = crate::R<bool, bool>; #[doc = "Reader of field `BTLC_GPIO_ENABLE`"] pub type BTLC_GPIO_ENABLE_R = crate::R<u8, u8>; #[doc = "Reader of field `VDD_SPI_AS_GPIO`"] pub type VDD_SPI_AS_GPIO_R = crate::R<bool, bool>; #[doc = "Reader of field `USB_EXCHG_PINS`"] p...
Rust
0
scene.meshes[37].translate(2., 0.0, 1.5); scene.meshes[38] = MeshBuilder::sphere(0.4, 28, 28); scene.meshes[38].translate(1., 0.0, 2.); scene.meshes[39] = MeshBuilder::sphere(0.5, 10, 10); scene.meshes[39].translate(2., 0.0, 2.); scene.meshes[27] = MeshBuilder::sphere(0.5, 10, 10); scene.meshes[28] = Me...
Rust
0
.ok_or_else(|| { err_msg( ErrorKind::DIDUrlNotFound, "Sender verification method not found in did", ) })?; let valid = match alg { jws::Algorithm::EdDSA => { metadata.sign_alg = Some(SignAlg::EdDSA); let signer...
Rust
0
class tree: # 트리 노드 클래스 def __init__(self, left=0, right=0): self.right=right self.left=left def data(self, d=0): self.d=d def inorder(N): if t[N]: global cnt if t[N].left:inorder(t[N].left) t[N].data(pwd[cnt]) cnt+=1 if t[N].right:inorder(t[...
Python
1
the rules. /// /// Consume the compiler. /// /// # Implementation notes /// /// It is safe to destroy the compiler after, because the rules do not depends on the compiler. /// In addition, we must hide the compiler from the user because it can be used only once. pub fn compile_rules(sel...
Rust
0
let filterer = filt(&[filter("complete*=signal(INT)")]).await; filterer.complete_does_pass(Some(ProcessEnd::ExitSignal(SubSignal::Interrupt))); filterer.complete_doesnt_pass(Some(ProcessEnd::ExitStop(NonZeroI32::new(19).unwrap()))); filterer.complete_doesnt_pass(Some(ProcessEnd::Success)); filterer.complete_doesnt...
Rust
0
(9..10, vec![ Leaf(9..9), Leaf(10..10)])])])]) } #[test] fn restoration_strategies() { configure_depth(); } fn configure_depth() { let tree_shape = tree_depth_4(); for depth in 2..3 {//0..5 { let mut test = Test::new(depth, &tree_shape); configure_memory(&mut test); }...
Rust
0
rom(*pubkey), _ => return Err(TransactionError::BadOrigin), }; // If no geocoding is coming, return if geocoding.is_none() { return Err(TransactionError::BadInput); } // Insert data to geolocation i...
Rust
0
out[2] = int64(pooled_size[0]) out[3] = int64(pooled_size[1]) return out @script def _roi_align_shape_func_nhwc(data_shape, rois_shape, pooled_size): out = output_tensor((4,), "int64") out[0] = rois_shape[0] out[1] = int64(pooled_size[0]) out[2] = int64(pooled_size[1]) out[3] = data_sha...
Python
1
import random import torch from fedlib.aggregators import Signguard from fedlib.trainers import Trainer as Algorithm from fedlib.constants import CLIENT_UPDATE, CLIENT_ID from .adversary import Adversary class MinMaxAdversary(Adversary): def __init__(self, threshold=1.0): super().__init__() sel...
Python
1
record into table DataModel # # @param ID: ID of a ModelType # @param CrossIndex: CrossIndex of a ModelType # @param Name: Name of a ModelType # @param Description: Description of a ModelType # def Insert(self, CrossIndex, Name, Description): (Name, Description)...
Python
1
eUp, #[strum(serialize = "paste")] OnPaste, #[strum(serialize = "pause")] OnPause, #[strum(serialize = "play")] OnPlay, #[strum(serialize = "playing")] OnPlaying, #[strum(serialize = "pointercancel")] OnPointerCancel, #[strum(serialize = "pointerdown")] OnPointerDown, ...
Rust
0
abs()), "sin" => Function(|v| Value::from(f64::from(v).sin())), "cos" => Function(|v| Value::from(f64::from(v).cos())), "tan" => Function(|v| Value::from(f64::from(v).tan())), "asin" => Function(|v| Value::from(f64::from(v).asin())), "acos" => Function(|v| Value::from(f64::from(v).asin())), "atan" => Functi...
Rust
0
ile_data = (int(elem) for elem in f.read().split()) except FileNotFoundError as ex: print("Could not open {}".format(filename)) print("Usage: {} <file> <time limit>".format(argv[0])) print(" Use '-' to mean the default input file") raise it = iter(file_data) num_jobs =...
Python
1
Y} |d } |d } d }}x]||kr4|d9}||}| j | | j |t |}|s|||fSqW| j|d}|sZ|||fS||}| j|d|| s| r|||fS| }| j|d |||s|||fS|jjd?}|jjd@}|jjd?}|...
Python
1
RequestError::Unsupported) } fn for_period( &self, for_symbol: Symbol, period: FinancialPeriod, ) -> RequestResult<PriceRangeSeries> { debug!( "IEXProvider::<FetchPriceRangeSeries>::for_period for_symbol: {}, period: {}", for_symbol, period );...
Rust
0
}; let sphere_transform = bt::btTransform { m_basis: sphere_rotation.clone(), m_origin: bt::btVector3 { m_floats: [0.0, 5.0, 0.0, 0.0], }, }; let mut fall_motion_state = bt::btDefaultMotionState::new(&sphere_transform as *const _, bt::...
Rust
0
# ('国泰君安', '113.105.92.104', 7709), # ('国泰君安', '113.105.92.99', 7709), ('国泰君安', '117.34.114.13', 7709), ('国泰君安', '117.34.114.14', 7709), ('国泰君安', '117.34.114.15', 7709), ('国泰君安', '117.34.114.16', 7709), ('国泰君安', '117.34.114.17', 7709), ('国泰君安', '117.34.114.18', 7709), ('国泰君安', '117.34.11...
Python
1
if !cfg!(target_arch = "x86_64") { bail!("shipcat is only built for 64 bit architectures"); } let arch = "x86_64"; let os_config = (cfg!(target_os = "linux"), cfg!(target_os = "macos")); let os = match os_config { (true, _) => "unknown-linux-musl", (_, true) => "apple-darwi...
Rust
0
tt: Mqtt, pub admin: Option<Admin>, pub ota: Ota, } impl PyrinasSettings { pub fn new(config: String) -> Result<Self, Error> { // Get the path let path = Path::new(&config); // Get it as a string first let config = fs::read_to_string(path)?; // Get the actual confi...
Rust
0
interface_subprogram_declaration | subprog_spec | //! | name | name | //! | name/character_literal | primary_name | //! | name/operator_symbol | primary_name | //! | name/simple_name | prim...
Rust
0
def searchMatrix(matrix: list[list[int]], target: int) -> bool: m = len(matrix) n = len(matrix[0]) for i in matrix: if target <= i[n - 1]: low = 0 high = n - 1 while low <= high: mid = (low + high) // 2 if i[mid] == target: ...
Python
1
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os import argparse from hardcodes import search parser = argparse.ArgumentParser() parser.add_argument('-r', '--recursive', help='use post method', dest='recursive', action='store_true') parser.add_argument('-c', '--comments', help='specify how to handles comment...
Python
1
rd: RoborockDataUpdateCoordinator, ) -> list[RoborockMap]: """Get the starting map information for all maps for this device. The following steps must be done synchronously. Only one map can be loaded at a time per device. """ entities = [] maps = await coord.cloud_api.get_multi_maps_list() if m...
Python
1
# 创建Session实例 session = Session() # 查询所有用户 users = [session.query(Current).first()] # 打印用户信息 for user in users: print(f'ID: {user.id}, Name: {user.name}, Info: {user.info}') user_info = user.info user_name = user.name # 关闭Session ...
Python
1
��', "zhà"), ('𨋙', "yìn"), ('𨋚', "niǎn,ruǎn"), ('𨋛', "pào"), ('𨋝', "gōng"), ('𨋞', "bù"), ('𨋟', "hé"), ('𨋠', "rǒng"), ('𨋡', "guì"), ('𨋥', "bì"), ('𨋦', "xī"), ('𨋧', "jú"), ('𨋨', "hún"), ('𨋩', "bì,fú"), ('𨋫', "tiāo"), ('𨋬', "zhěng,chèng"), ('𨋮...
Rust
0
0.7); } #[test] fn test_generate_rnet_bboxes() { let np_pp: Array1<f32> = read_npy("test_resources/pp_rnet.npy").unwrap(); let np_cc: Array2<f32> = read_npy("test_resources/cc_rnet.npy").unwrap(); let np_boxes_1x1: Array2<f32> = read_npy("test_resources/boxes_1x1.npy").unwrap(); ...
Rust
0
from .. import IconBase class IconMapPin(IconBase): class_name = "lucide lucide-map-pin" svg_data = { "attrs": { "width": "24", "height": "24", "view_box": "0 0 24 24", "fill": "none", "stroke": "currentColor", "stroke_width": "2", "stroke_linecap": ...
Python
1
struct EdgeBuilder { cfg: parsing::Config, node_ids: Vec<i64>, proto_edges: Vec<ProtoEdgeA>, proto_shortcuts: Vec<[EdgeIdx; 2]>, } impl EdgeBuilder { pub fn cfg(&self) -> &parsing::Config { &self.cfg } pub fn insert<E>(&mut self, proto_edge: E) -> err::Feedback where E...
Rust
0
c5.8-9.9 5.8-22.1 .1-32.1S555.5 224 544 224l-400 0c-11.4 0-21.9 6-27.6 15.9L48 357.1 48 96c0-8.8 7.2-16 16-16l117.5 0c4.2 0 8.3 1.7 11.3 4.7l26.5 26.5c21 21 49.5 32.8 79.2 32.8L416 144c8.8 0 16 7.2 16 16l0 32 48 0 0-32c0-35.3-28.7-64-64-64L298.5 96c-17 0-33.3-6.7-45.3-18.7L226.7 50.7c-12-12-28.3-18.7-45.3-18.7L64 32C28...
Python
1
library is not None and not self._repos.library_repository.library_exists( normalize_string(library) ), "Library", library, "Name", ) NotFoundException.raise_if( package is not None and not self._...
Python
1
non_camel_case_types)] pub struct iovec_t { base: *const c_void, len: size_t, } pub async fn do_eventfd(init_val: u32) -> Result<isize> { do_eventfd2(init_val, 0).await } pub async fn do_eventfd2(init_val: u32, flags: i32) -> Result<isize> { let flags = EventFileFlags::from_bits(flags).ok_or_else(|| e...
Rust
0
default(); for rv in vec.iter() { acc = acc + *rv.downcast_ref::<T>()?; } Some(r(acc)) } f::<f64>(&vec).or_else(|| f::<i64>(&vec)).unwrap() }) as MyFn)); gltn.insert("-", r(Box::new(|vec: Vec<Val>| -> Val { fn f<T: std::ops::Sub<Output ...
Rust
0
gen_state) => gen_state.frame.is_some(), Value::Instance(instance_id) => interpreter.global.instances.contains_key(&instance_id), _ => false } } <filename>numbers/src/main.rs fn main() { //int_main(); //str_main(); //loop_ten(); //while_ten(); //for_ten(); fizzbuzz(); } fn...
Rust
0
all errors that are fixable will be ignored, # as generating them will be fixed. if config.action == "generate": general_errors = [err for err in config.errors if not err.fixable] invalid_itg = [ itg for itg in integrations.values() if any(not error.fixable f...
Python
1
n_total, args.batch_size, n_proc_in_silo=0, ) output_dim = 10000 else: dataset, output_dim = fedml.data.load(args) if args.dataset == "femnist": in_channels = 1 else: in_channels = 3 # load model (the size of MNIST image is 28 x 28) i...
Python
1
# Copyright (c) 2015-2022 Clearmatics Technologies Ltd # # SPDX-License-Identifier: LGPL-3.0+ from zeth.core.zksnark import ExtendedProof, Groth16 from zeth.core.mixer_client import MixParameters from zeth.core.encryption import generate_encryption_keypair, encrypt from zeth.core.signing import gen_signing_keypair, si...
Python
1
np.max(np.abs(diff_approx)) l2_diff = norm(diff_approx) else: max_diff, l2_diff = None, None return {'max': max_diff, 'L2': l2_diff} # Define the system of differential equations with exogenous b(t) def equations(t, y, xi_a): a, a_prime = y b, b_prime, b_dbl_prime = b_vector(t) a...
Python
1
import pytest from marie import Flow from marie.extract.adaptive_dfa import AdaptiveDFA, State def test_basic_dfa(): dfa = AdaptiveDFA() # Create State instances begin = State("BEGIN") start = State("START") stop = State("STOP") end = State("END") # Add states dfa.add_state(begin) ...
Python
1
""" 回測系統 API 測試 此模組測試回測系統 API 的所有端點,確保功能正確性和穩定性。 """ import pytest import asyncio from datetime import datetime, timedelta from fastapi.testclient import TestClient from unittest.mock import Mock, patch import json from src.api.main import app from src.core.backtest_service import BacktestService, BacktestConfig c...
Python
1
from math import ceil, log ### int -> list ### def int2intlist(x, intmax=256, num_ints=0): """Convert x (integer) into list of integers. The size of each integer in the list can optionally be controlled by intmax so that the integer range is 0 to intmax-1 (default: 0-255). Number integers in the list c...
Python
1
wn_origin) .body(request.signed_metadata.encode_to_vec()) .send() .await; let response = match response { Ok(response) => response, Err(err) => { state.last_error = Some(err); return RelayAction::SendError; }...
Rust
0
Ok((attributes, namespace)) } } }; } serialize_type!(bool); serialize_type!(char); serialize_type!(usize); serialize_type!(u8); serialize_type!(u16); serialize_type!(u32); serialize_type!(u64); serialize_type!(isize); serialize_type!(i8); serialize_type!(i16); serialize_type!(i32); serialize_typ...
Rust
0
/// Is an error type/const reachable? const HAS_ERROR = 1 << 13; /// Does this have any region that "appears free" in the type? /// Basically anything but `ReLateBound` and `ReErased`. const HAS_KNOWN_FREE_REGIONS = 1 << 14; const HAS_...
Rust
0
op(); } #[no_mangle] pub unsafe fn fpu_fsub(target_index: i32, val: F80) { let st0 = fpu_get_st0(); fpu_write_st(*fpu_stack_ptr as i32 + target_index & 7, st0 - val) } #[no_mangle] pub unsafe fn fpu_fsubr(target_index: i32, val: F80) { let st0 = fpu_get_st0(); fpu_write_st(*fpu_stack_ptr as i32 + targe...
Rust
0
if it does but can't parse it). fn parse_inner_text<'t>( &mut self, text: Cow<'t, str>, ) -> Result<InnerParseResult<Cow<'t, str>>> { Ok(InnerParseResult::Next(text)) } /// Finish parsing. fn parse_inner_finish(self) -> Result<Self::Output>; } /// Using `String` as `InnerState` to collect all inner text i...
Rust
0
from kivy.app import App from kivy.clock import Clock from kivy.lang import Builder from kivy.properties import NumericProperty from kivy.properties import ObjectProperty from kivy.uix.boxlayout import BoxLayout Builder.load_string(''' #:import barometer plyer.barometer <BarometerInterface>: barometer: barometer ...
Python
1
E_PARSERS['UseCounters.conf'] = from_UseCounters_conf except ImportError: pass def from_files(filenames): """Return an iterator that provides a sequence of Histograms for the histograms defined in filenames. """ all_histograms = OrderedDict() for filename in filenames: parser = FILENAME_PAR...
Python
1
import sqlalchemy as sa import sqlalchemy.orm as so from app import app, db, queryAll from app.models import User, Post @app.shell_context_processor def make_shell_context(): return {'sa': sa, 'so': so, 'db': db, 'User': User, 'Post': Post, 'queryAll': queryAll}
Python
1
d0d1071247909882f0562eA"; let account = "0xa0d4E5CdD89330ef9d0d1071247909882f0562eA"; let signature = ""; let client = Client::tracked(rocket()).expect("valid rocket instance"); let response = client .get(format!( "/authorize?client_id={}&realm=kovan&redirect_...
Rust
0
return } self.tape[self.head_position as usize] = character; } pub fn read(&mut self) -> char { if self.head_position as usize > self.tape.len() { panic!("Trying to read character at invalid position: {}.", self.head_position.to_string()); } self.tape...
Rust
0
print_gl_error(); gl::BufferData( gl::ARRAY_BUFFER, 4 * verts.len() as isize, verts.as_ptr() as *const std::os::raw::c_void, gl::STATIC_DRAW, ); // gl::GenBuffers(1, &mut color_buffer as *mut GLuint); // gl::BindBuffer(gl::ARRAY_B...
Rust
0
} #[test] fn params_no_match() { let pattern = Regex::new("^/test/(?P<name>[^/]+)$").expect("failed to compile regex"); let params = match_route(&pattern, "/different/mike"); assert_eq!(None, params); } #[test] fn params_missing_param() { let pattern = Regex::ne...
Rust
0
# Creation of a group from salome.kernel import salome salome.salome_init_without_session() from salome.kernel import GEOM from salome.geom import geomBuilder geompy = geomBuilder.New() gg = salome.ImportComponentGUI("GEOM") # create two vertices p0 = geompy.MakeVertex(0. , 0. , 0. ) p200 = geompy.MakeVertex(200.,...
Python
1
awning", entity); } /// Checks if a [`Ball`] has collided with a compatible entity, and then /// deflects it away from the point of impact. pub fn arena_collision_system( mut commands: Commands, balls_query: Query< (Entity, &GlobalTransform, &Movement), (With<Ball>, With<Collider>), >, ...
Rust
0
fn from(error: std::io::Error) -> Self { error.kind().into() } } #[cfg(feature = "std")] impl Into<std::io::ErrorKind> for StatusCode { fn into(self) -> std::io::ErrorKind { match self { $(StatusCode::$name => ...
Rust
0
import statistics import psycopg2 from psycopg2 import sql def avg_null_destroyer (destroyer_list): ''' Функция по получению средней цены из списка с предварительным удалением None из листа Возвращает список цен и среднюю цену на таргет :param destroyer_list: :return: destroyer_list,avg_price ...
Python
1
# -*- coding: utf-8 -*- # Copyright: (c) 2019, Jordan Borean (@jborean93) <jborean93@gmail.com> # MIT License (see LICENSE or https://opensource.org/licenses/MIT) import pytest from pypsexec.exceptions import ( PAExecException, PDUException, PypsexecException, SCMRException, ) class TestPypsexecExce...
Python
1
ize = bits.read_varint(inp) lazy_offsets.append(lazy_offsets[-1] + lazy_size) lazy_offsets = list(map(lambda offset: offset + inp.tell(), lazy_offsets)) def restore_lazy_part(ty, attr, index): inp.seek(lazy_offsets[index]) part = read_piece(attr.resolved_ty) assert inp.tell() == lazy_of...
Python
1
crate::workflows::steps::factory::StepGenerator; #[cfg(test)] use futures::stream::FuturesUnordered; #[cfg(test)] use futures::StreamExt; #[cfg(test)] use std::iter::FromIterator; #[cfg(test)] use std::time::Duration; #[cfg(test)] struct StepTestContext { step: Box<dyn WorkflowStep>, futures: FuturesUnordered<...
Rust
0
r'[\u4e00-\u9fff]+', current_content)) next_words = set(re.findall(r'[\u4e00-\u9fff]+', next_content)) if current_words and next_words: overlap = len(current_words & next_words) / len(current_words | next_words) coherence_scores.append(overlap) ...
Python
1
).abs() < FITNESS_EPSILON); } use geojson::feature::Id; use geojson::{Bbox, Feature, FeatureCollection, GeoJson, Geometry, Value}; use serde_json::{Map, Value as JsonValue}; pub struct FeatureOptions { bbox: Option<Bbox>, id: Option<Id>, } pub type FeatureProperties = Map<String, JsonValue>; pub type Point =...
Rust
0
import os from time import sleep try: import openai from openai import OpenAI except ImportError as e: pass from lcb_runner.runner.base_runner import BaseRunner class DeepSeekRunner(BaseRunner): client = OpenAI( api_key=os.getenv("DEEPSEEK_API"), base_url="https://api.deepseek.com" ) ...
Python
1