text
string
label_name
string
labels
int64
deleted_name_list: Option<HashSet<String>>, snippet: &BandledSnippet, ) -> KeyList { let mut all_name_list = all_name_list.clone(); if let Some(name_list) = name_list { // すでにnamelistが存在していた場合 let name_list = name_list.clone(); // all_name_listの参照を指しているので、contains判定のため一度cloneする // ...
Rust
0
import json import os from fpdf import FPDF from io import BytesIO BASE_DIR = "data/users" def _user_plan_file(username: str) -> str: return os.path.join(BASE_DIR, username, "plan.json") def save_plan(username: str, subtopics: str, plan: str): path = _user_plan_file(username) os.makedirs(os.path.dirname(...
Python
1
util::floatX; let mut i: usize; if (*histogram).total_count() == 0usize { return kOneSymbolHistogramCost; } i = 0usize; 'break1: while i < data_size { { if (*histogram).slice()[i] > 0u32 { s[count as (usize)] = i; count = count + 1; if count > 4i32 { { ...
Rust
0
().count(),); } } } mod acquire_lease_response; mod break_lease_response; mod get_acl_response; mod get_properties_response; mod list_containers_response; mod release_lease_response; mod renew_lease_response; pub use self::acquire_lease_response::AcquireLeaseResponse; pub use self::break_lease_response::Bre...
Rust
0
import pygame import random pygame.init() #Определим цвета COLOR_LIST = { "Белый": (255,255,255), "Красный": (255,0,0), "Зелёный": (0,255,0), "Синий": (0,0,255) } BLACK = (0,0,0) #Задаём размер игрового окна WIDTH = 400 HEIGHT = 600 #Создаём окно игры screen = pygame.display.set_mode((WIDTH,HEIGHT)) ...
Python
1
import os import win32com.client from pathlib import Path def download_attachments_and_move(inbox_folder_path, archive_folder_name): outlook = win32com.client.Dispatch("Outlook.Application") namespace = outlook.GetNamespace("MAPI") inbox = namespace.GetDefaultFolder(6) # 6 corresponds to the inbox folder...
Python
1
FieldReader::new(bits)) } } impl core::ops::Deref for XPD_SAR_AMP_FSM_R { type Target = crate::FieldReader<u8, u8>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `XPD_SAR_AMP_FSM` writer - "] pub struct XPD_SAR_AMP_FSM_W<'a> { w: &'a mut W, } impl<'a> XP...
Rust
0
from customtkinter import * set_appearance_mode('dark') set_default_color_theme('blue') vetor_codigo = [] vetor_altura = [] vetor_peso = [] contador = 1 def cadastrar(): global contador codigo = cod.get() altura = alt.get() peso = pes.get() if cod and alt and pes: altura = float(altura)...
Python
1
ion of `constraints`. Returns: A tensor of proxy constraint functions. """ return None # This is a property, instead of an abstract property, since it doesn't need # to be overridden: if pre_train_ops returns None, then there are no ops to # run before train_op. @property def pre_train_ops...
Python
1
if let Some(err) = Code::get(&ret) { if err != Code::Ok { println!("wire 2 ping error: {:?}", err); return } } println!("wire 2 ping ret: {:?}", ret); // wire 1 attach wire1.send(msg!{ CHAN: ATTACH, VALUE: "hello" }).unwrap(); let re...
Rust
0
assert_eq!((-i).ln(), -i * pi_over_2); assert_eq!((-j).ln(), -j * pi_over_2); assert_eq!((-k).ln(), -k * pi_over_2); } } #[cfg(test)] mod power_tests { use cglinalg::{ Quaternion, }; use approx::{ relative_eq }; use core::f64; #[test] fn test_quaterni...
Rust
0
src_ds = None # Close the source dataset return expected_tile_data def compare_tile_arrays(expected_data, actual_data, zoom, x, y): """ Compares two NumPy arrays representing tile data and reports discrepancies. Returns True if arrays are equal, False otherwise. """ if actual_data is None: ...
Python
1
where E: std::error::Error + Send + Sync + 'static, R: Resource + Debug + Send + Sync, S: Stream<Item = Result<Event<R>, E>> + Send + 'static, { type Error = anyhow::Error; async fn run_stream<H>(self, handler: H) -> Result<(), Self::Error> where H: EventHandler<Event = R> + Send + Syn...
Rust
0
rid_height = rows * max_size grid_img = Image.new('RGB', (grid_width, grid_height)) for i, img in enumerate(images): x = (i % cols) * max_size y = (i // cols) * max_size grid_img.paste(img, (x, y)) grid_np = np.array(grid_img).astype(np.float...
Python
1
ricArgument, IntoType, SubsType, WithoutAttrs, WithoutDefault, WithoutMaybeBounds, }; use proc_macro2::{Ident, Span, TokenStream}; use quote::{format_ident, quote, quote_spanned}; use syn::punctuated::Punctuated; use syn::{ DeriveInput, GenericArgument, GenericParam, Member, Token, TypeParam, TypeParamBound, W...
Rust
0
est_fixtures::default_fixture; /// RNG seed for all benchmarks. const RNG_SEED: u64 = 153434375; /// A `StatsWriter` that does nothing. #[derive(Default)] struct DummyWriter {} impl StatsWriter for DummyWriter { fn init(&mut self, _graph: &Graph, _partition: &Partition) {} fn step( &mut self, ...
Rust
0
rite(0xB2A1 + 0x30, 0x50); cpu.unofficial_increment_memory_subtract_acc_indirect_y(); assert_eq!(0x80 - 0x51 - 1, cpu.a); } #[test] fn unofficial_increment_memory_subtract_acc_indirect_y_updates_pc() { let mut cpu = create_test_cpu(); cpu.program_counter = 0xFEE0; c...
Rust
0
f) -> Dac2 { Dac2{dac:&self.dac} } } pub struct Dac1<'a> { dac: &'a DAC, } impl<'a> Dac1<'a> { pub fn enable(&mut self) { self.dac.cr.modify(|_, w| w.en1().enabled()); } pub fn disable(&mut self) { self.dac.cr.modify(|_, w| w.en1().disabled()); } pub fn enable_ou...
Rust
0
Crypto { offset: 1, data: vec![1, 2, 3], }; enc_dec(&f, "060103010203"); } #[test] fn test_new_token() { let f = Frame::NewToken { token: vec![<KEY> }; enc_dec(&f, "0703123456"); } #[test] fn test_stream() { ...
Rust
0
)] pub mod can; pub mod clocks; // todo: You could get CRC working on most of these with some effort. #[cfg(not(any( feature = "f4", feature = "g0", feature = "g4", feature = "l5", feature = "wb", feature = "wl" )))] pub mod crc; #[cfg(not(any( feature = "f401", feature = "f411", fe...
Rust
0
# -*- coding: utf-8 -*- # Copyright (c) 2016-17 Ericsson AB # # 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 applicab...
Python
1
ld = ctx.guild for i in range(number): new_channel = await guild.create_text_channel(f"{channel_name}") print(f"{color.RED}[+] | Channel Create: {color.WHITE}{channel_name}") await new_channel.send(message_to_send) print(f"{color.RED}[+] | Message Send: {color.WHI...
Python
1
().map(|(k, _)| k.clone()).collect(); param_list.append(&mut env2_values.iter().map(|(k, _)| k.clone()).collect()); param_list.sort_by_key(|l| l.to_lowercase()); param_list.dedup(); let default_param = ParameterDetails::default(); let mut added = false; let mut table = Table::new("parameter"); ...
Rust
0
def obtener_pos_ady(i, j, matriz): total = [] for i2 in range(max(0, i - 2), min(i + 3, len(matriz))): for j2 in range(max(0, j - 2), min(j + 3, len(matriz[i2]))): total.append((i2, j2)) return total def contar_submarinos(i, j, matriz): pos = obtener_pos_ady(i, j, matriz) coun...
Python
1
if compare_pos < 1 { break; } new_node_pos = compare_pos; compare_pos = (compare_pos - 1) / 2; } } } #[cfg(test)] mod test { use super::*; #[test] fn main() { let mut queue = PriorityQueue::new(); for priority in ...
Rust
0
from typing import Tuple from sbot import Robot from sbot import BRAKE, COAST from sbot import AnalogPins from sbot import GPIOPinMode from enum import Enum LightSensor = Enum("Light Sensor", "LEFT CENTRE RIGHT") Direction = Enum("direction", "LEFT RIGHT") rbot = Robot() fudgeFactor=0.99403 arduino = rbot.arduin...
Python
1
String); #[derive(Clone, Copy)] pub enum NymRole { Trustee, User, } impl NymRole { pub fn prepare(&self) -> Option<&str> { match self { NymRole::Trustee => Some("TRUSTEE"), NymRole::User => None, } } } /** Generate a did and send a nym request for it. */ pu...
Rust
0
class Solution(object): # def subsets(self, nums): # """ # :type nums: List[int] # :rtype: List[List[int]] # """ # nums.sort() # res = [[]] # res.append(list(nums)) # for ls in range(1, len(nums)): # self.get_subsets(res, nums, [], ls, 0) ...
Python
1
""" Main entry point for training and testing a Single Hidden Layer Perceptron (MLP). Experiments with different hidden neuron counts. """ from mlp import SingleHiddenLayerPerceptron from dataset import load_dataset from utils import train_test_split, evaluate if __name__ == "__main__": X, y = load_dataset() X...
Python
1
ttributes['Label'], str(i))) ##abstract = '\n'.join(abstract) else: # get. display page # First see if folder exists. if not, return error user_folders = db.results.find_one({'user_id': user})['folder'] folders = [d['folder_name'] for d in user_folders if 'folder_name' in d]...
Python
1
e.children { None => {} Some(children) => field_builder.add_children(children), }; field_builder.add_type_(field_type.type_); if let Some(fb_metadata) = fb_metadata { field_builder.add_custom_metadata(fb_metadata); } field_builder.finish() } fn type_to_field_type(data_type...
Rust
0
() as usize + 1; offset = buf_idx * size; let ptr = &param as *const _ as *const u8; let dst = buf.add(offset); ::core::ptr::copy_nonoverlapping(&param as *const _ as *const u8, dst, size); )* } if false { $func($($p...
Rust
0
king_smith_ggx_correlated(alphaSqr, woDotN, wiDotN) F = bsdf_fresnel_shlick(col, 1, woDotH) w = F * D * G * 0.25 / torch.clamp(woDotN, min=specular_epsilon) frontfacing = (woDotN > specular_epsilon) & (wiDotN > specular_epsilon) return torch.where(frontfacing, w, torch.zeros_like(w)) def bsdf_pbr(kd,...
Python
1
fn descriptor(&self) -> &'static ::protobuf::reflect::MessageDescriptor { Self::descriptor_static() } fn new() -> GetLatestBlockResponse { GetLatestBlockResponse::new() } fn descriptor_static() -> &'static ::protobuf::reflect::MessageDescriptor { static descriptor: ::protobuf::...
Rust
0
f.surface_mut().damage(); compositor.schedule_repaint(); dsurf.set_activated(true); view.activate(&compositor.first_seat().expect("first_seat"), ActivateFlag::CONFIGURE); let _ = dsurf.set_user_data(Box::new(SurfaceContext { view, resize_edges: Resize::None, ...
Rust
0
ERF_AUTONOMOUS_MODE_DISABLED: u32 = 0u32; #[doc = "*Required features: 'Win32_System_SystemServices'*"] pub const PROCESSOR_PERF_AUTONOMOUS_MODE_ENABLED: u32 = 1u32; #[doc = "*Required features: 'Win32_System_SystemServices'*"] pub const PROCESSOR_PERF_BOOST_MODE_AGGRESSIVE: u32 = 2u32; #[doc = "*Required features: 'Wi...
Rust
0
x = fig.add_subplot(111, projection='3d') # Scatter plot for training data scatter = ax.scatter(X_train[:, 0], X_train[:, 1], y_train, c=y_train, cmap='viridis') ax.set_xlabel('x1') ax.set_ylabel('x2') ax.set_zlabel('Target (y)') ax.set_title('3D plot of Features and Target for training data') # Rotate the plot ax.vi...
Python
1
.iter().map(|signer| signer.author()).collect(); let epoch_mgr = Arc::new(EpochManager::new(0, validator_verifier)); for peer in &peers { let (network_reqs_tx, network_reqs_rx) = channel::new_test(8); let (consensus_tx, consensus_rx) = channel::new_test(8); let network_sender = Consensus...
Rust
0
e::util::WorldCursor; use bevy::prelude::Transform; use bevy::prelude::*; use bevy_prototype_debug_lines::*; use heron::rapier_plugin::PhysicsWorld; use heron::{CollisionLayers, CollisionShape, RigidBody}; use rand::prelude::*; use super::collider::{SpawnZone, Wall}; /// Parameters for controlling the spawning of ene...
Rust
0
url: print(f"📦 View releases: {releases_url}") def show_help() -> None: """Show help message""" print(__doc__) print(f"\nValid bump types:") for bump_type in VALID_BUMP_TYPES: print(f" - {bump_type}") def main() -> None: """Main function""" if len(sys.argv) > 1: if ...
Python
1
= Option::Some(custom_command); } } } else if specification.version.is_some() { official_image_temp.push_str(specification.version.as_ref().unwrap()); docker_image = &official_image_temp; command_string = format!(r#"["/bin/bash", "-c", "java -XX:+UseContainerSupport -XX:...
Rust
0
# I used the time.sleep() command to make the code stop for a certain amount of time # I used import to import libraries that add extra functionality from datetime import date import time # I used the print() command to display text in the command line print("Welcome To Nobara CLI Edition") print("This is totally th...
Python
1
f() { let os: Vec<Override> = serde_json::from_str(&read_to_string(JSON_F29F).unwrap()).unwrap(); for o in &os { if !o.extra.is_empty() { println!("{:#?}", o.extra); } assert!(o.extra.is_empty()); } // check if an optional field is no longer present if !os.is_e...
Rust
0
xt) { let e_toks : ~[syntax::ast::token_tree] = quote_tokens!(1 + 2); let p_toks : ~[syntax::ast::token_tree] = quote_tokens!((x, 1 .. 4, *)); let a: @syntax::ast::expr = quote_expr!(1 + 2); let _b: Option<@syntax::ast::item> = quote_item!( static foo : int = $e_toks; ); let _c: @syntax::ast::pat =...
Rust
0
::{LayerData, LayerTag}, error::TiledError, properties::{parse_properties, Properties}, map::MapTilesetGid, util::*, MapWrapper, Layer, Map }; #[derive(Debug, PartialEq, Clone)] pub struct GroupLayerData { layers: Vec<LayerData>, } impl GroupLayerData { pub(crate) fn new( parser: &...
Rust
0
), results[4]); assert_eq!(utf8_header(inputs[5], true), results[5]); } #[test] fn test_number_type() { let inputs = [ &b"\xa0"[..], &b"\xaa\xaa"[..] , &b"\x80\x80\x88\x80\x80"[..] , &b"\xbf\x80\xbf\x80\xbf\x80"[..] ]; let slice = &[][..]; ...
Rust
0
| { if (index & (1 << dimension)) != 0 {1} else {0} }); //printlnerr!("{:?}", (index, coordinates)); assert!(child_by_coordinates (children, coordinates) as *const Child == child as *const Child); callback (coordinates, child); } } pub fn face_by_dimension_and_direction<Face> (faces: &NodeFace...
Rust
0
c/api/reactive_property_instance_manager.rs use async_trait::async_trait; use uuid::Uuid; #[async_trait] pub trait ReactivePropertyInstanceManager: Send + Sync { fn connect(&self, outbound_uuid: Uuid, inbound_uuid: Uuid); // TODO: automatically disconnect if ReactivePropertyInstance is destroyed fn discon...
Rust
0
::color::Color; use super::super::point3d::Point3D; use super::super::ray3d::Ray3D; use super::super::vector3d::Vector3D; use super::Intersect; #[derive(Deserialize, Copy, Clone, Debug, PartialEq, PartialOrd)] pub struct Sphere { pub color: Color, pub position: Point3D, pub radius: f64, #[serde(d...
Rust
0
} } #[doc = "Device type\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [devicetype](index.html) module"] pub struct DEVICETYPE_SPEC; impl crate::RegisterSpec for DEVICETYPE_SPEC { type Ux...
Rust
0
"development" } else { "production" })) }); } if opts.http_proxy.is_none() { opts.http_proxy = std::env::var("HTTP_PROXY") .ok() .map(Cow::Owned) .or_else(|| std::env::var("http_proxy").ok().map(C...
Rust
0
($i:expr, $re:expr) => ( { let r = $crate::lib::regex::bytes::Regex::new($re).unwrap(); $crate::regexp::bytes::re_capture(r)($i) } ) ); /// `re_captures!(regexp) => &[T] -> IResult<&[T], Vec<Vec<&[T]>>>` /// Returns the capture groups of all matches. /// /// Requires the `regexp` feature. #[...
Rust
0
vocation_reason: Some(CrlReason::OcspRevokeUnspecified), }; let v = ri.to_der().await.unwrap(); assert_eq!( vec![ 0xa1, 0x16, 0x18, 0x0f, 0x32, 0x30, 0x32, 0x30, 0x31, 0x31, 0x33, 0x30, 0x30, 0x31, 0x34, 0x38, 0x32, 0x35, 0x5a, 0xa0, 0x03, 0x0a, 0x01,...
Rust
0
# test_database.py import unittest import os from database import ArticleDatabase class TestArticleDatabase(unittest.TestCase): def setUp(self): # Use an in-memory database for testing self.db = ArticleDatabase(':memory:') self.sample_article = { "url": "https://example.com/test...
Python
1
str() == "\n", _ => false, } } pub fn is_space(&self) -> bool { match self { TokenType::Whitespace { token } => token.text().as_str() == " ", _ => false, } } } impl Deref for TokenType { type Ta...
Rust
0
=> write!(f, "Cannot open stdin stream for 'less' process"), Error::InvalidCliOptionValue(opt) => write!( f, "Invalid value provided for command line option '{}'", opt ), } } } // too many hints in this one... // day23 part 1 ...
Rust
0
class Solution: def wiggleSort(self, nums: List[int]) -> None: n=len(nums) nums.sort() mid=(n-1)//2 nums[::2],nums[1::2]=nums[mid::-1],nums[:mid:-1]
Python
1
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM // LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR // OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR // PERFORMANCE OF THIS SOFTWARE. //! [`VK_NV_external_memory_win32`](https://www.khro...
Rust
0
#!/usr/bin/env python3 """ Simple Telegram Alert Test Test the Telegram notification system for RWA Trading System. """ import os import asyncio import httpx from datetime import datetime async def test_telegram_connection(): """Test basic Telegram connection and send test message.""" # Get credentials ...
Python
1
ak256::digest(&encoded_point.to_untagged_bytes().unwrap())[12..].to_vec(); Ok(hash) } Self::Secp256k1(ref key) => { Ok(Ripemd160::digest(&Sha256::digest(&key.to_bytes())).to_vec()) } Self::Ed25519(ref key) => Ok(Sha256::digest(key.as_bytes...
Rust
0
continue if item_range.is_empty() or item_range.begin < 0: continue if not extracted_one: extracted_one = True print(f'{asset_range} -> {file_path}') gfx_bytes = asset_bytes[item_range.begin:item_range.end + 1] self.write_a...
Python
1
fileobj: lineIndex += 1 commentLine = commentLineRegex.search(line) if commentLine: continue colorLine = colorLineRegex.search(line) if colorLine: fields = colorLine.groups() colo...
Python
1
import matplotlib.pyplot as plt from sklearn.discriminant_analysis import LinearDiscriminantAnalysis from sklearn import metrics from sklearn.metrics import confusion_matrix import seaborn as sns import os def train_lda(selected_features_tra,class_vector_tra): # initialize the LDA model lda = LinearD...
Python
1
return True with pytest.raises(RuntimeError): wait_for_condition(slow_condition, timeout=0, retry_interval_ms=50) @pytest.mark.asyncio async def test_async_zero_timeout(self): """Test async behavior with zero timeout.""" async def slow_condition(): await asynci...
Python
1
. `windowShape` must be a tuple specifying the desired window dimensions in (height,width) form. """ # Determine the dimensions of the input data width = data.shape[dimOrder.index('w')] height = data.shape[dimOrder.index('h')] # Generate the windows windowHeight, windowWidth = windowShape return generateFor...
Python
1
if let Some(key) = key_buffer.take() { let definition = parse_line(line)?; writer.define(key, definition)?; } else { key_buffer = Some(line) } } Ok(()) } } <reponame>WormholeStudio/starcoin // Copyright (c) The Sta...
Rust
0
: CborError = 768; pub const CborErrorMapKeysNotUnique: CborError = 523; pub const CborErrorMapNotSorted: CborError = 522; pub const CborErrorMapKeyNotString: CborError = 521; pub const CborErrorOverlongEncoding: CborError = 520; pub const CborErrorImproperValue: CborError = 519; pub const CborErrorExcludedValue: CborE...
Rust
0
#!/usr/bin/env python3 import numpy as np import onnx from onnx import TensorProto, ValueInfoProto from onnx.helper import make_model, make_node, make_graph, make_tensor_value_info def main(): # Create a Shape node shape_node = make_node( 'Shape', inputs=['input'], outputs=['shape_out']...
Python
1
self) } } } } } // Forward everything to ref-ref, when reusing storage is not helpful macro_rules! forward_all_binop_to_ref_ref { (impl $imp:ident for $res:ty, $method:ident) => { forward_val_val_binop!(impl $imp for $res, $method); forward_val_ref_binop!(im...
Rust
0
from typing import Any, Dict, List from darts.models import NBEATSModel from models.darts.model import DartsModel class NBEATS(DartsModel): def __init__( self, timeframe_size: int, prediction_len: int, quantiles: List[float], model_name: str, ...
Python
1
from core.game import Game def main(): game = Game() game.start() if __name__ == "__main__": main()
Python
1
4 worker_num_splits: int = 1 max_policy_lag: int = 1 force_envs_single_thread: bool = True optimizer: Literal["adam", "lamb"] = 'adam' restart_behavior: str = "overwrite" normalize_returns: bool = False async_rl: bool = False num_batches_per_epoch: int = 16 num_batches_to_accumulat...
Python
1
from __future__ import annotations from typing import Any, Callable from torch import Tensor, nn from ofen.enums import NormalizationStrategy # Define normalization functions for each strategy NORMALIZATION_FN_BY_STRATEGY: dict[NormalizationStrategy, Callable[[Tensor], Tensor]] = { NormalizationStrategy.L2: lam...
Python
1
; use twilight_model::{ channel::Webhook, id::{marker::WebhookMarker, Id}, }; struct GetWebhookFields<'a> { token: Option<&'a str>, } /// Get a webhook by ID. #[must_use = "requests must be configured and executed"] pub struct GetWebhook<'a> { fields: GetWebhookFields<'a>, http: &'a Client, id...
Rust
0
from openai import OpenAI from BigModel.Base import BigModelBase ''' Gemini -- OneAPI ''' class Chat_Gemini_1_5_pro(BigModelBase): def __init__(self, max_tokens=1024, temperature=0.1, top_p=0.5): super().__init__(max_tokens, temperature, top_p) self.load_my_api('oneapi') self.client = Open...
Python
1
()?; let denominator = denominator[1..].parse()?; return Ok(Delay { numerator, denominator }); } let numerator = s.parse()?; Ok(Delay { numerator, denominator: 1000 }) } fn from_color_type(color_type: image::ColorType) -> AppResult<Color> { use image::ColorType::*; let result = m...
Rust
0
(1.-images[...,-1:]) else: images = images[...,:3] elif args.data_type == 'deepvoxels': images, poses, render_poses, hwf, i_split = load_dv_data(scene=args.dv_scene, basedir=args.data_path, testskip=args.test_skip) print('Loaded deepvoxels', images.shape, render_poses.shape, h...
Python
1
sat { OptionalField::Present(htlc_maximum_msat) } else { OptionalField::Absent }; UnsignedChannelUpdate { chain_hash, short_channel_id, timestamp: backdated_timestamp, flags: standard_channel_flags, cltv_expiry_delta: directional_info.cltv_expiry_delta, htlc_minimum_msat: d...
Rust
0
zer.deserialize_seq(Visitor { _value: &PhantomData, }) } pub fn serialize<S, V>(map: &HashMap<V::Id, V>, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, V: ToSnowflakeId + Serialize, { serializer.collect_seq(map.values()) } } pub mod serde...
Rust
0
end![main_layer, bounds]; let () = msg_send![new_layer.as_ref(), setFrame: bounds]; let () = msg_send![main_layer, addSublayer: new_layer.as_ref()]; new_layer }; let window: cocoa_foundation::base::id = msg_send![view, window]; if !window.is_null() { ...
Rust
0
from pydantic import BaseModel from typing import Dict from bondai.tools.tool import Tool from duckduckgo_search import DDGS MAX_RESULT_COUNT = 20 DEFAULT_RESULT_COUNT = 5 TOOL_NAME = "duck_duck_go_search" TOOL_DESCRIPTION = f"This tool allows you to retrieve a paginated list of search results. You must specify your s...
Python
1
match &file_event.columns.action { OSQueryFileAction::CREATED | OSQueryFileAction::MOVED_FROM => { subject_file.with_created_timestamp(file_event.columns.time) } OSQueryFileAction::DELETED | OSQueryFileAction::MOVED_TO => { subject_file.with_deleted_...
Rust
0
pub fn num_global_and_external_regions(&self) -> usize { self.first_local_index } /// Get an iterator over all the early-bound regions that have names. pub fn named_universal_regions<'s>( &'s self, ) -> impl Iterator<Item = (ty::Region<'tcx>, ty::RegionVid)> + 's { self.indices....
Rust
0
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' @File : game_hook.py @Time : 2024/04/22 18:52:39 @Author : haotian @Version : 1.0 @Desc : 游戏主体钩子数据逻辑处理 ''' from nonebot.adapters.onebot.v11 import ( Bot, Message, GroupMessageEvent, MessageSegment, ) from ..models.CatGameModel impo...
Python
1
'''Autogenerated by xml_generate script, do not edit!''' from OpenGL import platform as _p, arrays # Code generation uses this from OpenGL.raw.GLES2 import _types as _cs # End users want this... from OpenGL.raw.GLES2._types import * from OpenGL.raw.GLES2 import _errors from OpenGL.constant import Constant as _C import...
Python
1
are 0, cancel visualization if starconf.dimensions.len() == 0 { println!("Dimension configuration couldn't be process it, or it's not specified!"); return None; } // create a new instance of GObjects and initialize the Starplot va...
Rust
0
base_str, &indices, None).unwrap(); let mod_values = take(&base_mod, &indices, None).unwrap(); match &part { Some(key) if key.contains("/id=") => { let schema = Arc::new(ArrowSchema::new(vec![Field::new( "value", DataType::Int32, true, ...
Rust
0
from langchain_openai import AzureChatOpenAI from dotenv import load_dotenv import os load_dotenv() llm = AzureChatOpenAI( api_key=os.getenv("OPENAI_API_KEY"), api_version="2024-02-01", azure_endpoint="https://models.inference.ai.azure.com", model="gpt-4o", )
Python
1
PI]: """Lifespan context manager for fastAPI. Load the translation dict and create the sole instance of the loom server class. That loom server instance persists for the entire time the web server is running. This is because the loom server speaks to one loom and serves at most ...
Python
1
_direction_4: { let direc_raw = pick_u64(&bv, 321, 9) as u16; if direc_raw > 359 { None } else { Some(direc_raw) } }, sea_temperature_4: { let temp_raw = pick_i64(&bv, 330, 11) as i32; if temp_raw < ...
Rust
0
the given radix. */ pub pure fn to_digit(c: char, radix: uint) -> Option<uint> { let val = match c { '0' .. '9' => c as uint - ('0' as uint), 'a' .. 'z' => c as uint + 10u - ('a' as uint), 'A' .. 'Z' => c as uint + 10u - ('A' as uint), _ => return None }; if val < radix { Some(val) ...
Rust
0
"PROC" => "types::PROC", "UINT" => "types::UINT", "VOID" => "types::VOID", // "int " => "__gl_imports::raw::c_int", // "unsigned int " => "__gl_imports::raw::c_uint", // "void " => "()", "BOOL *" => "*mut types::BOOL", ...
Rust
0
#[inline(always)] fn process8(v: u64, mut h: u64) -> u64 { h ^= xxh64_round(0, v); h.rotate_left(27) .wrapping_mul(PRIME64_1) .wrapping_add(PRIME64_4) }; #[inline(always)] fn process4(v: u32, mut h: u64) -> u64 { h ^= (v as u64).wrapping_mul(PRIME64_1); ...
Rust
0
n() { const NAME: &str = env!("CARGO_PKG_NAME"); const VERSION: &str = env!("CARGO_PKG_VERSION"); const AUTHORS: &str = env!("CARGO_PKG_AUTHORS"); println!("{} v{}", NAME, VERSION); println!("Copyright (c) 2021 {}", AUTHORS); }<reponame>jacobrec/gameboy-emulator use serde::{Deserialize, Serialize}...
Rust
0
rue) sleep(0.333) print('.', end='', flush=True) sleep(0.333) print('.', end='', flush=True) sleep(0.333) ai_move = black_ai.play_turn(current_game_board=MainGame.get_board(), ai_pieces=MainGame.get_blacks()) dummy_input: Callable = lam...
Python
1
*mut *mut rcl_clock_t) -> rcl_ret_t; /// Calculates whether or not the timer should be called. pub fn rcl_timer_is_ready(timer: *const rcl_timer_t, is_ready: *mut bool) -> rcl_ret_t; /// Calculate and retrieve the time until the next call in nanoseconds. pub fn rcl_timer_get_time_until_next_call( ...
Rust
0
orient_3d(*a, *b, *c, *d); }) }) }); } fn uniform_random(c: &mut Criterion) { let mut rng = Pcg64::new(PCG_STATE, PCG_STREAM); let dist = Uniform::new_inclusive(-10.0, 10.0); let data = (0..10000) .map(|_| { let vals = dist.sample_iter(&mut rng).take(12).collect:...
Rust
0
from collections.abc import Generator from collective.transmute import _types as t from collective.transmute.utils import redirects as utils import pytest @pytest.fixture def patched_settings(transmute_settings) -> Generator[t.TransmuteSettings, None, None]: orig = transmute_settings.site_root["src"] transmu...
Python
1
inplanes), int(outplanes) innerplanes = make_divisible(inplanes * t, 8) if inner_divisible else int(inplanes * abs(t)) self.t = t self.force_residual = force_residual if self.t != 1: self.conv1 = nn.Conv2d(self.inplanes, innerplanes, kernel_size=1, padding=0, stride=1, groups...
Python
1
fct.const_pool(ConstPoolIdx(0)), &ConstPoolEntry::Fct(fct_id, SourceTypeArray::empty()) ); }, ); } #[test] fn gen_fct_call_int_with_0_args() { gen_fct( " fun f(): Int32 { return g(); } fun g(): Int32 { return 1; } ", ...
Rust
0