text
string
label_name
string
labels
int64
log.warning("Centroid fit failed. Using initial estimate for source location.") xc = xcenter yc = ycenter log.info(f"Using planned center x,y = {xc:.2f},{yc:.2f}") elif not self.moving_centroid: xc = np.nan...
Python
1
.as_str(), ns, &dep, Default::default(), )?; client.request::<apps::Deployment>(req2)?; } Ok(()) } TASK_NAME => { // Scale jobs ...
Rust
0
from paddle_billing.EnumStringify import enum_stringify from paddle_billing.HasParameters import HasParameters from paddle_billing.Exceptions.SdkExceptions.InvalidArgumentException import InvalidArgumentException from paddle_billing.Resources.Discounts.Operations.DiscountInclude import DiscountInclude class GetDisc...
Python
1
import torch def z_score(x, mean, std): """ Z-score normalization function: $z = (X - \mu) / \sigma $, where z is the z-score, X is the value of the element, $\mu$ is the population mean, and $\sigma$ is the standard deviation. :param x: torch array, input array to be normalized. :param mean: ...
Python
1
dict: dict[str, float] ) -> ChemGraph: # noqa atomic_numbers = [] for element_name, number_of_atoms in target_composition_dict.items(): atomic_numbers += [Element(element_name).Z] * int(number_of_atoms) return ChemGraph( atomic_numbers=paddle.to_tensor(data=atomic_numbers, dtype="int64"), ...
Python
1
import numpy as np import pytest import torch @pytest.mark.skipif( not torch.cuda.is_available(), reason='GPU is required to test NMSRotated op') class TestNmsRotated: def test_ml_nms_rotated(self): from mmcv.ops import nms_rotated np_boxes = np.array( [[6.0, 3.0, 8.0, 7.0, 0....
Python
1
} } impl<CellT: Cell> ExactSizeIterator for PolarBatchIter<CellT> {} // default impl using size_hint() impl<CellT: Cell> Iterator for PolarBatchIter<CellT> { type Item = Vec<CellT::Coord>; fn next(&mut self) -> Option<Self::Item> { // this will be really slow for by column, row is fine // s...
Rust
0
test_alloc_aligned() { let (ptr, cap) = alloc_aligned(1); assert!(!ptr.is_null()); assert_eq!(16, cap); unsafe { free_aligned(ptr, cap) } let (ptr, cap) = alloc_aligned(16); assert!(!ptr.is_null()); assert_eq!(16, cap); unsafe { free_aligned(ptr, cap) } ...
Rust
0
i64) ^ y), }, Int::Signed(x) => match right { Int::Unsigned(y) => Int::Signed(*x ^ (y as i64)), Int::Signed(y) => Int::Signed(*x ^ y), }, } } #[inline(always)] fn bitor(&mut self, right: Int) { *self = match self { ...
Rust
0
e!( Box::new( true ) ) ); // < is_slice!(Box :: new(true)) = false dbg!( is_slice!( &[ 1, 2, 3 ] ) ); // < is_slice!(& [1, 2, 3]) = false dbg!( is_slice!( &[ 1, 2, 3 ][ .. ] ) ); // < is_slice!(& [1, 2, 3] [..]) = true } <filename>frontend/rust/yew/lessons/struct_properties/src/router.rs<gh_stars>1-10 use cr...
Rust
0
y(100); Ok(()) } /// Query the on-board magnetometer's (the AK8963's) WHO_AM_I /// register. Should return `0x48`. fn ak8963_who_am_i<SPI: Transfer<u16>, CS: OutputPin>( spi: &mut SPI, cs: &mut CS, ) -> Result<u8, SPI::Error> { const AK8963_ADDRESS: u8 = 0x0C; const AK8964_WHO_AM_I: u8 = 0x00; ...
Rust
0
from subprocess import Popen base = "PYTHONPATH=./ python src/recom_search/scripts/run_pipeline.py -nexample 100 " cuda_range = [0,3,1,2] # a star configs avg_score = [0.75] astar_mode = [" -dfs_expand "] common_a_star = [] for score in avg_score: for m in astar_mode: common_a_star.append(f" -avg_score...
Python
1
# Junk Definitions one_up_mushroom = "1-Up Mushroom" one_coin = "1 coin" five_coins = "5 coins" ten_coins = "10 coins" fifty_coins = "50 coins" # Collectable Definitions yoshi_egg = "Yoshi Egg" # Upgrade Definitions mario_run = "Run" mario_carry = "Carry" mario_swim = "Swim" mario_spin_jum...
Python
1
lock().await.is_started(), true); let http_worker1 = Arc::new(http_worker); let http_worker2 = http_worker1.clone(); let cmd_clone = cmd.clone(); tokio::spawn(async move { http_worker1 .read_and_report(cmd_clone, &task.invocation_task_id) .awai...
Rust
0
-------------------------------------------------------- # Load/store instrucions #------------------------------------------------------------------------- def test_tinyrv2_inst_lw(): # lw rd, imm(rs1) check("lw x1, 3(x2)", 0b00000000001100010010000010000011, "lw x01, 0x003(x02)") check("lw ...
Python
1
bench_match, bench_phf_map ); criterion_main!(benches);<filename>resin_core/src/lib.rs mod resin; mod util; use std::{fs::{create_dir_all, File}, io::{BufReader, BufWriter, Write}, path::Path}; use crate::resin::resin::Resin; pub fn extract(in_file: &str, target: &str) { create_dir_all(&target).expect("Unabl...
Rust
0
_EVENT_NAME, seq) self.widget.unbind(CHECKHIDE_VIRTUAL_EVENT_NAME, self.checkhideid) self.checkhideid = None for seq in HIDE_SEQUENCES: self.widget.event_delete(HIDE_VIRTUAL_EVENT_NAME, seq) self.widget.unbind(HIDE_VIRTUAL_EVENT_NAME, self.hideid) self.hideid = None ...
Python
1
quote; extern crate proc_macro; #[proc_macro_derive(Error)] pub fn error(item: TokenStream) -> TokenStream { let item: syn::ItemEnum = syn::parse(item).unwrap(); let item_name = item.ident.clone(); let error_code_branches = item.variants.iter().enumerate().map(|variant| { ...
Rust
0
#Embedded file name: /Users/versonator/Jenkins/live/output/Live/mac_64_static/Release/python-bundle/MIDI Remote Scripts/SL_MkIII/util.py from __future__ import absolute_import, print_function, unicode_literals from ableton.v2.base import clamp, liveobj_valid from ableton.v2.control_surface.components import find_neares...
Python
1
pe.write_symbol(new_tape_symbol) tape = tape.move(direction) new_configs.add(TMConfiguration(new_state, tape)) return new_configs def read_input_stepwise(self, input_str): """ Check if the given string is accepted by this Turing machine. Yield the current co...
Python
1
std::collections::HashSet; use std::fmt; extern crate lalrpop_util; // Boxed types used for storing information from the parsing will be used especially for the // location of the AST item #[doc(hidden)] pub type AstExpr = Box<Spanned<Expr>>; #[doc(hidden)] pub type AstArgument = Spanned<Argument>; #[doc(hidden)] pub ...
Rust
0
verification at all. It expect path and pattern. // That is why for this case checking for file existance if cfg!(target_os = "windows") && keybase_binary.is_some() { if Path::new(&keybase_binary.unwrap()).exists() { return Ok(Self {}); } else { return Err(ErrorKind::KeybaseNotFound)?; } } le...
Rust
0
from __future__ import annotations import os try: from gi.repository import Wnck except ImportError: Wnck = None from kupfer import config from kupfer.support import datatools, pretty __all__ = ("allows_keybinder", "is_kwin", "is_wayland") @datatools.evaluate_once def is_kwin() -> bool: """Try to figu...
Python
1
pins.strobe14, pins.strobe15, pins.strobe16, pins.strobe17, ), Rows( pins.sense1, pins.sense2, pins.sense3, pins.sense4, pins.sense5, pins....
Rust
0
comment "Investment Buy - {symbol_comment}" if transaction_id['buy_or_sell'] == 'buy': db.execute( "INSERT INTO spending (user_id, transaction_id, spending_type, comment) VALUES (?, ?, ?, ?)", user_id, transaction_id['transaction_id'], 'other-spending', buy_co...
Python
1
{}", err); return; } }) .await; } ("", _) => { log::error!(target: "bridge", "No subcommand specified"); } _ => unreachable!("all possible subcommands are checked above; qed"), } } fn ethereum_connection_params(matches: &clap::ArgMatches) -> Result<EthereumConnectionParams, String> { let m...
Rust
0
Guess { let g = self.number_of_tries; self.number_of_tries+=1; g } fn reset(&mut self) { IterateGuess::reset(self); } fn clone(&self) -> Box<guessing::GuessingMethod> { let a = IterateGuess { number_of_tries: self.number_of_tries }; Box::new(a) } } #[test] fn it_works() { let mut g = IterateGu...
Rust
0
e; *out_value = cur_value + (parameter * coeff.x); last_z = *cur_z; } } fn update_road_curvature(road_static: Res<RoadStatic>, mut road_dyn: ResMut<RoadDynamic>) { // Convert ResMut to a regular mutable reference - otherwise Rust can't properly split borrows // between individual struct fi...
Rust
0
() conns = re.search('([^ ]+):([0-9]+)', splitted[3]) pidstr = '' if 'tcp' in splitted[0]: protocol = 'tcp' pidstr = splitted[6] elif 'udp' in splitted[0]: protocol = 'udp' pidstr = splitted[5] pi...
Python
1
# Copyright 2017 Open Source Robotics Foundation, Inc. # # 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...
Python
1
# coding=utf-8 MSR = 1 MAR = 2 MDR = 3 RAM = 4 IR = 5 DST = 6 SRC = 7 A = 8 B = 9 C = 10 D = 11 DI = 12 SI = 13 SP = 14 BP = 15 CS = 16 DS = 17 SS = 18 ES = 19 VEC = 20 T1 = 21 T2 = 22 MSR_OUT = MSR MAR_OUT = MAR MDR_OUT = MDR RAM_OUT = RAM IR_OUT = IR DST_OUT = DST SRC_OUT = SRC A_OUT = A B_OUT = B C_OUT = C D_OUT =...
Python
1
Ok(()) } } pub struct SH2 {} impl Test for SH2 { fn name(&self) -> &str { "pifram: SH (offset 2)" } fn level(&self) -> Level { Level::Weird } fn values(&self) -> Vec<Box<dyn Any>> { Vec::new() } fn run(&self, _value: &Box<dyn Any>) -> Result<(), String> { let pifram = MemoryMap::...
Rust
0
2, dispbp: *mut c_void, dispbw: i32, ); pub fn sceGuDrawBuffer( psm: DisplayPixelFormat, fbp: *mut c_void, fbw: i32, ); pub fn sceGuDrawBufferList( psm: DisplayPixelFormat, fbp: *mut c_void, fbw: i32, ); pub fn sceGuDisplay(state: b...
Rust
0
FitbitActivity); derive_rweb_schema!(FitbitActivityWrapper, _FitbitActivityWrapper); #[derive(Serialize, Deserialize, Clone, Debug, Schema)] struct _FitbitActivityWrapper { #[schema(description = "Log Type")] log_type: StackString, #[schema(description = "Start Datetime")] start_time: DateTime<Utc>, ...
Rust
0
_idx_)].abs(); let pp = corr[(c_idx, c_idx_)].abs(); //if p + p_ < 2.0 * pp { if self.red_rule.redundant(p, p_, pp, p_min) { //debug!("c[{}] and c[{}] are redundant {} {} {}", //c_idx, c_idx_, p, p_, pp); if p_ >...
Rust
0
""" 8.4 Open the file romeo.txt and read it line by line. For each line, split the line into a list of words using the split() function. The program should build a list of words. For each word on each line check to see if the word is already in the list and if not append it to the list. When the program completes, sor...
Python
1
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch import unittest from cotracker.models.core.model_utils import bilinear_sampler class TestBilinearSampler(...
Python
1
Player { Player { id: self.id, me: !self.me, strategy_crashed: self.strategy_crashed, score: self.score, } } } // Copyright 2015 <NAME>. See the COPYRIGHT file at the top-level // directory of this distribution. // // Licensed under the Apache License...
Rust
0
_attention_stats_collection"): model.enable_attention_stats_collection() Logger(f"已启用注意力统计信息收集,QK-Clip 阈值: {tau}") else: # 使用标准 Muon 优化器 if ddp: optimizer = MuonWithAuxAdam(param_groups) else: optimizer = SingleDeviceMuonWithAuxAdam(param_group...
Python
1
t(&cmd_code.cell().repr_hash()) } } impl TraceStepInfo { #[allow(dead_code)] pub fn from(info: &EngineTraceInfo, fname: Option<String>) -> TraceStepInfo { let stack = info.stack.iter().map( |x| format!("{}", x) ).collect(); TraceStepInfo { id: info.step, ...
Rust
0
> = match Font::from_bytes(font_data) { Ok(font_bytes) => font_bytes, Err(_) => { return Err(OperationError::new( Box::new(self.clone()), OperationErrorInfo::FontLoadError, )) } }; let mut string...
Rust
0
esetLayout: v = prefClass.geometryDefaults[key] else: v = value prefClass.settings.setValue("Geometry/" + key, QtCore.QVariant(v)) def resetLayout(prefClass = Prefs): """ Module function to set a flag not storing the current layout. @param prefClass preferences ...
Python
1
, */ /// Address to listen on #[structopt(long = "listen", default_value = "[::]:4433")] listen: SocketAddr, } fn main() { let opt = Opt::from_args(); let code = { let decorator = slog_term::PlainSyncDecorator::new(std::io::stderr()); let drain = slog_term::FullFormat::new(decor...
Rust
0
"Mexico", "Mexiko", "Mexique", "México", "Messico", "Mexico"], "0d67baf401030000", ] weathercities036["Poza Rica de Hidalgo"] = [ [ "ポサ・リカ", "Poza Rica de Hidalgo", "Poza Rica de Hidalgo", "Poza Rica", "Poza Rica", "Poza Rica", "Poza Rica", ], [ ...
Python
1
(index, kanji_word); } pub fn get_mnemonic(&self, index: u32) -> Option<String> { self.words.get(index).mnemonic } pub fn get(&self, index: u32) -> String { self.words.get(index).word } } use super::shared_to_linear::SharedToLinear; use crate::internal::base::*; pub struct LinearT...
Rust
0
ub, } } pub fn gif_default() -> Self { Self::Gif } pub fn bmp_default() -> Self { Self::Bmp { color_type: BmpColorType::Rgba8 } } pub fn ico_default() -> Self { Self::Ico { color_type: IcoColorType::Rgba8 } } pub...
Rust
0
_id -= 1; } let acc_value_to_skip = match param.acc_type { acc::Type::ACC1 => multiset_to_g1(&set_data_to_skip, &param), acc::Type::ACC2 => acc_value_to_skip.into_affine(), }; let skip_node = SkipListNode::create( block_id...
Rust
0
return # Check all instrument IDs for instrument_id in instrument_ids: PyCondition.equal(instrument_id.venue, OKX_VENUE, "instrument_id.venue", "OKX") all_pyo3_instruments = [] for instrument_type in self._instrument_types: pyo3_instruments = await self._client....
Python
1
import torch def index_points(points, idx): """ :param points: points.shape == (B, N, C) :param idx: idx.shape == (B, N, K) :return:indexed_points.shape == (B, N, K, C) """ raw_shape = idx.shape idx = idx.reshape(raw_shape[0], -1) res = torch.gather(points, 1, idx[..., None].expand(-1,...
Python
1
InnerRoute>>, } impl Route { // Similar to new, but without depot. // This function should only be used from Tour::with_setup(). fn new_(vehicle_capacity: f64, cache: &DistanceCache) -> Self { let inner = Box::new(InnerRoute { n_nodes: 0, capacity: vehicle_capacity, ...
Rust
0
None }; while !shutdown.load(Ordering::Relaxed) { let rid = thread_rng().gen_range(0..(args.regions / args.read_threads)) * args.read_threads + index; let mut start = Instant::now(); if let (S...
Rust
0
# cook your dish here import math t = int(input()) for i in range(t): x, n = map(int,input().split()) a = x*100 if(a>=n): print(0) else: b = math.ceil(n/100) print(b-x)
Python
1
action="store_const", const=True, help="only delete node_modules directory") subparser.set_defaults(func=clean) subparser = subparsers.add_parser('pnpm', help='do "pnpm ..." in each package;') ...
Python
1
assert_eq!(set, got); } #[test] fn test_choose_padding() { let qgram = qgram(3); assert_eq!("��", qgram.choose_padding("abcde")); assert_eq!("��", qgram.choose_padding("ABCDE")); assert_eq!("��", qgram.choose_padding("12345")); // Cannot use default padding a...
Rust
0
CameraDotAspect, dx_SetCameraNearFar, dx_SetCameraPositionAndAngle, dx_SetCameraPositionAndTargetAndUpVec, dx_SetCameraPositionAndTarget_UpVecY, dx_SetCameraScreenCenter, dx_SetCameraViewMatrix, dx_SetupCamera_Ortho, dx_SetupCamera_Perspective, }; use smart_default::SmartDefault; use crate::{ error::{D...
Rust
0
from mistralrs import ( Runner, Which, SpeechLoaderType, ) from pathlib import Path import wave, struct # text_to_speak = "[S1] Dia is an open weights text to dialogue model. [S2] You get full control over scripts and voices. [S1] Wow. Amazing. (laughs) [S2] Try it now on Git hub or Hugging Face." text_to_...
Python
1
inout_setters, ], ), instr::empty(alloc), )) }) } pub fn emit_reified_targs<'a, 'arena, 'decl>( e: &mut Emitter<'arena, 'decl>, env: &Env<'a, 'arena>, pos: &Pos, targs: &[&ast::Hint], ) -> Result<InstrSeq<'arena>> { let alloc = env....
Rust
0
# Code generated by Lark OpenAPI. from typing import Any, Optional, Union, Dict, List, Set, IO, Callable, Type from lark_oapi.core.construct import init from .message_pin import MessagePin from .url_pin import UrlPin class ChatPin(object): _types = { "chat_pin_id": int, "chat_id": str, "c...
Python
1
bu5t1bn68wx '# leak_stitch_bilge -> population_quarterdecks_minimums' '# leak_stitch_bilge -> population_quarterdecks_minimums' p2796pluv2w return assert b'' u32n2lw65jr *= cmjw4vsnrqh global btczbnjqdcz from w9gux3rx6e_ import nkkov2tie4r, lxoaytu2r3u as yhu71h79lks, wpkxhytl5nd as i7v...
Python
1
unwrap(); let schema = GroupPredicate::new( [(String::from("key"), None), (String::from("value"), None)] .iter() .cloned(), ); let res = test_row_group_rows::<Group>("nested_maps.snappy.parquet", Some(schema)); assert!(res.is_err()); assert_eq!( res.unwrap_err(), general_err!("Types don't mat...
Rust
0
if method == "GET": # 測試查詢參數 params = { "id": payload, "search": payload, "q": payload, "query": payload, "fil...
Python
1
//! ```rust //! use serde::Deserialize; //! use spirit::prelude::*; //! use spirit_reqwest::{AtomicClient, ReqwestClient}; //! //! #[derive(Debug, Default, Deserialize)] //! struct Cfg { //! #[serde(default)] //! client: ReqwestClient, //! } //! //! impl Cfg { //! fn client(&self) -> ReqwestClient { //! ...
Rust
0
from heapq import heappop, heappush def dijkstra(graph_dict, from_node, to_node): cost = -1 ret_path = [] T, P = [(0, from_node, ())], set() while T: # 从T中取出距离最近的节点 (cost, v1, path) = heappop(T) # 如果最近节点不再P中, 加入P中 if v1 not in P: P.add(v1) path =...
Python
1
AI frame metadata wai_frame = { "frame_name": file_name, "image": str(rel_target_image_path), "file_path": str(rel_target_image_path), "depth": str(rel_depth_out_path), "transform_matrix": Rt_cam2world_opencv.tolist(), "h": depthmap.shape[0...
Python
1
) | ((value as u32) << 16); }, 0x10001073 => { self.status = (self.status & !(0xff << 24)) | ((value as u32) << 24); }, _ => {} }; } /// Loads register content /// /// # Arguments /// * `address` fn load_u8(&mut self, address: u64) -> u8 { //println!("Disk Load AD:{:X}", address); match add...
Rust
0
(hmac::verify(&key, HELLO_WORLD_BAD, tag.as_ref()).is_err()) } } } <reponame>lkolbly/imxrt-hal //! Supporting traits for defining peripheral DMA //! sources and destinations //! //! # How to add DMA capabilities to your peripheral //! //! 1. Make sure your device can support DMA transfers! //! 2. If your de...
Rust
0
d`](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 information about available fields see [u...
Rust
0
import os import functools import bpy class BlenditSubscriber: """Subscriber to different event publishers""" def __repr__(self): return self.__doc__ blenditSubscriber = BlenditSubscriber() def writeToFile(lines): """Writes list of lines to associated python file""" filepath...
Python
1
""" Easy [1385. Find the Distance Value Between Two Arrays](https://leetcode.com/problems/find-the-distance-value-between-two-arrays/) Given two integer arrays arr1 and arr2, and the integer d, return the distance value between the two arrays. The distance value is defined as the number of elements arr1[i] such that ...
Python
1
"CrossAttnDownBlock3D", "CrossAttnDownBlock3D", "CrossAttnDownBlock3D", "DownBlock3D" ] config["up_block_types"] = [ "UpBlock3D", "CrossAttnUpBlock3D", "CrossAttnUpBlock3D", "CrossAttnUpBlock3D" ] from ...
Python
1
N`"] pub struct DECISION_VITERBI_LEN_W<'a> { w: &'a mut W, } impl<'a> DECISION_VITERBI_LEN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: DECISION_VITERBI_LEN_A) -> &'a mut W { unsafe { self.bits(variant.into()) } } #[doc = "`0`"] #[...
Rust
0
): result.priority = "high" return True def init(self, app: "flask.Flask") -> bool: # pylint: disable=unused-argument global REPLACE, REMOVE, HIGH, LOW # pylint: disable=global-statement if not settings.get(self.id): # Remove plugin, if there isn't a "hos...
Python
1
s::Uncompressed) } #[test] fn bigint_col() -> Result<()> { test_column("bigint_col", CompressionOptions::Uncompressed) } #[test] fn float_col() -> Result<()> { test_column("float_col", CompressionOptions::Uncompressed) } #[test] fn double_col() -> Result<()> { test_column("double_col", CompressionOptions...
Rust
0
from setuptools import setup, find_packages setup( name="eepy_explorer", version="0.1.0", packages=find_packages(), install_requires=[ "PyQt6", "qasync", "psutil", ], entry_points={ "console_scripts": [ "eepy_explorer=eepy_explorer.src.app:main", ...
Python
1
from django.views.generic import ListView, DetailView, UpdateView, DeleteView from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from .models import Post from .forms import BlogForm from django.urls import reverse_lazy from rest_framework.views import APIView from re...
Python
1
from abc import ABC, abstractmethod from typing import Tuple import numpy as np import torch from torch.nn import Module from torch import Tensor from torchvision.transforms import ToTensor from trt_model import TRTInference class AlikedService(ABC): def __init__(self, name: str, model) -> None: self....
Python
1
![ api::Key::new("route"), api::Key::new("method"), api::Key::new("status"), ]; let http_requests_total = sdk.new_i64_counter( "http_requests_total", MetricOptions::default() .with_description("HTTP requests per route") ...
Rust
0
erde::{Deserialize, Serialize}; #[cfg(test)] mod tests; #[cfg_attr(feature = "deser", derive(Serialize, Deserialize))] #[derive(Clone, Debug, Trace, Finalize, PartialEq)] pub enum IterableLoopInitializer { Identifier(Identifier), Var(Declaration), Let(Declaration), Const(Declaration), } impl fmt::Dis...
Rust
0
se pin_project::pin_project; pub type Reader = Box<dyn AsyncRead + Unpin + Send>; const CAPACITY: usize = 4096; /// ReaderStream is used to convert a `futures::io::AsyncRead` into a `futures::Stream`. /// /// Most code inspired by `tokio_util::io::ReaderStream`. #[pin_project] pub struct ReaderStream { #[pin] ...
Rust
0
(PGMFlow, "f1".to_string() => node!(PGMGroup, "G1".to_string(), None, GroupType::Flow, Some(FlowID::from_str("g1")) => node!(PGMTest, 1, FlowID::from_int(1) => node!(PGMOnFailed, FlowID::from_int(1) => node!(PGMContinue), no...
Rust
0
} } } impl AngleConversionTrait for f32 { fn angle_conversion(&self, mode: AngleConversion) -> Self { match mode { AngleConversion::RadiansToDegrees => { self * constants::RADDEGRATE as f32 } AngleConversion::DegreesToRadians => { self * constants::DEGRADRATE as ...
Rust
0
92, 's': 0.135, 't': 0.115, 'u': 0.154, 'v': 0.096, 'w': 0.096, 'x': 0.096, 'y': 0.098, 'z': 0.135, ...
Python
1
import pygame import random # 1. Инициализация Pygame pygame.init() # 2. Определение констант # Размеры окна SCREEN_WIDTH = 640 SCREEN_HEIGHT = 480 # Размер одного блока змейки и еды BLOCK_SIZE = 20 # Цвета (RGB) WHITE = (255, 255, 255) BLACK = (0, 0, 0) RED = (255, 0, 0) GREEN = (0, 128, 0) # Шрифты FONT_STYLE = p...
Python
1
s, Material, Matte, Merl, Metal, Plastic, RoughGlass, SpecularMetal}; use texture::{self, Texture}; /// This lets me enforce only certain types of textures are valid, /// and to look up the right type of texture result for a given /// input. But it's a bit of a pain to deal with, if I want to add /// more texture-able...
Rust
0
from functools import partial import numpy as np import cv2 import torch from ..utils import apply_chunk_torch as apply_chunk def center_downscale( img, target_size=128, ): h, w, _ = img.shape ratio = w / h target_size = (target_size**2 / ratio) ** 0.5 target_hw = (int(target_size * ratio),...
Python
1
with(|zvm| { let done = zvm.step(); zvm.ui.flush(); push_updates(zvm); done }) } #[no_mangle] pub fn feed(input_ptr: *mut c_char) { with(|zvm| zvm.handle_input(get_string(input_ptr))); } #[no_mangle] pub fn restore(b64_ptr: *mut c_char) { with(|zvm| zvm.restore(&get_string...
Rust
0
let mut ctx = mock.create_ctx(); Rewards::end_block(&mut ctx); // Check reward pool account balance. let bals = Accounts::get_balances(ctx.runtime_state(), *ADDRESS_REWARD_POOL) .expect("get_balances should succeed"); assert_eq!( bals.balances[&Denomination::NATIVE], 996_000...
Rust
0
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- ################################################################################ # # Copyright (c) 2024 Baidu.com, Inc. All Rights Reserved # ################################################################################ import json import os from convert_checkpoint.ab...
Python
1
n = 10 sum_of_even = 0 for i in range(1, n+1): if i % 2 == 0: sum_of_even += 1 print("sum of even numbers " , sum_of_even)
Python
1
def construct_user_agent(class_name: str) -> str: from web3 import ( __version__ as web3_version, ) user_agent = f"web3.py/{web3_version}/{class_name}" return user_agent
Python
1
file_content, concat!( "root;0;root\n", "user;1000;user\n", "wheel;1;user,root\n", "li;1007;li\n", "fb;7099;fb,user\n" ) ); groups.remove_by_id(id); groups.save().unwrap(); ...
Rust
0
t)] mod mock; #[cfg(test)] mod tests; pub use pallet::*; use crate::types::Offer; #[frame_support::pallet] pub mod pallet { use super::*; use frame_support::pallet_prelude::*; use frame_system::pallet_prelude::*; use crate::types::ListInfo; pub type InstanceInfoOf<T> = NftInfo< <T as frame_system::Config>::A...
Rust
0
fn main() {} use crate::{ args::Flash, record::{db::DatabaseChunk, query, res}, serial::{self, Serial}, status::status, telegram::Telegram, }; use ihex::{Reader, Record}; use std::{ fs::read_to_string, io::{Read, Write}, }; use thiserror::Error; use tracing::{debug, warn}; pub type Result...
Rust
0
[USAGE_BIP44, COINTYPE_MOBILECOIN, account_index]; // We're taking what the SLIP-0010 spec calls the "Ed25519 private key" // here as our `Slip10Key`. That said, we're not actually using this as // an Ed25519 key, just IKM for a pair of HKDF-SHA512 instances whose // output will be cor...
Rust
0
FxHashMap::with_hasher(Default::default()) } impl<'a> ExprCache<'a> { pub fn new() -> Self { ExprCache { abstr_cache : FxHashMap::with_hasher(Default::default()), inst_cache : FxHashMap::with_hasher(Default::default()), subst_cache : FxHashMap::with_hasher...
Rust
0
import matplotlib.pyplot as plt import pandas as pd import numpy as np #file = open('nlevel3.txt', 'r') #download les data #hll df1 = pd.read_csv("hll.txt", delim_whitespace=True, skiprows=553, nrows = 63) df1_selection = df1.iloc[:, [1, 2, 3, 4]] #selectionne les colonnes 2345 print(df1_selection.head()) x1 = d...
Python
1
(e) role = role if role in ['member', 'contributor', 'manager'] else 'member' for rbac_group in rbac_groups: membership = RBACMembership.objects.filter(user=user, rbac_group=rbac_group).first() if membership and role != membership.role: membership.role = role membership...
Python
1
""" Implements the Keymanager API Remote Key Manager endpoints. https://ethereum.github.io/keymanager-APIs """ from typing import TYPE_CHECKING import msgspec.json from aiohttp import web from schemas import SchemaKeymanagerAPI if TYPE_CHECKING: from providers import Keymanager routes = web.RouteTableDef() @...
Python
1
turn true, (ELEMENT_NODE, Node::Element(_)) => {} (TEXT_NODE, Node::Element(_)) => return true, (TEXT_NODE, Node::Text(_)) => {} _ => return true, }; // two text nodes if let Node::Text(new) = new { &old.text_content().unwrap_or_default() != new } // differen...
Rust
0
#!/usr/bin/python # Copyright (c) 2016 AIT, ETH Zurich. 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 l...
Python
1