text
string
label_name
string
labels
int64
::WriteControlMsgResp(fd, addr, len, close); }use std::time::Duration; use failure::ResultExt; use humthreads::ThreadScope; use rdkafka::config::ClientConfig; use rdkafka::consumer::Consumer; use rdkafka::producer::FutureProducer; use rdkafka::producer::FutureRecord; use serde::de::DeserializeOwned; use serde::Seriali...
Rust
0
module = caller.data().module.clone(); let env = caller .data_mut() .resources .environments .get_mut(env_id) .or_trap("lunatic::process::add_this_module")?; let (mod_or_error_id, result) = match env.create_module(module.data()).await { ...
Rust
0
class Solution: def wordPattern(self, pattern: str, s: str) -> bool: words = s.split() # Split the sentence into words if len(pattern) != len(words): return False # If lengths don't match, pattern is invalid char_to_word = {} word_to_char = {} for char, word ...
Python
1
aw::c_int, H: ::std::os::raw::c_int, ); } extern "C" { pub fn Fl_JPEG_Image_width(arg1: *mut Fl_JPEG_Image) -> ::std::os::raw::c_int; } extern "C" { pub fn Fl_JPEG_Image_height(arg1: *mut Fl_JPEG_Image) -> ::std::os::raw::c_int; } extern "C" { pub fn Fl_JPEG_Image_delete(arg1: *mut Fl_JPEG_Image...
Rust
0
ert"); params.subject_alt_names = vec![SanType::DnsName("crabs.crabs".to_string()), SanType::DnsName("localhost".to_string())]; let cert = Certificate::from_params(params)?; let pem_serialized = cert.serialize_pem()?; let der_serialized = pem::parse(&pem_serialized).unwrap().contents; println!("{}", pem_serial...
Rust
0
import sys import socket as soc sc = soc.socket(soc.AF_INET, soc.SOCK_STREAM) print("connected") host = soc.gethostname() host_ip = soc.gethostbyname(host) address = (host_ip, int(sys.argv[1])) sc.bind(address) sc.listen(1) while True: conn, addr = sc.accept() message = conn.recv(1024).decode("utf-8") print("[C] ...
Python
1
w(pin).output() } // Copyright (c) SimpleStaking, Viable Systems and Tezedge Contributors // SPDX-License-Identifier: MIT use crate::{Action, ActionWithMeta, Service, Store}; use crate::service::ProtocolService; pub fn protocol_effects<S>(store: &mut Store<S>, action: &ActionWithMeta) where S: Service, { mat...
Rust
0
import os import json import wave from flask import Flask, request, jsonify from flask_cors import CORS from vosk import Model, KaldiRecognizer # Initialize Flask app and CORS app = Flask(__name__) CORS(app) # Folder to save the audio files UPLOAD_FOLDER = 'uploads' os.makedirs(UPLOAD_FOLDER, exist_ok=True) # Initia...
Python
1
1), Some(x) => imageproc::contrast::threshold(x, data.1), }; Image::new(::image::DynamicImage::ImageLuma8(result)) } fn finalize(env: NapiEnv, out: Output) -> Result<NapiValue, NapiValue> { out .to_napi_value(env) .map_err(|x| to_napi_value(env, x)) } offl...
Rust
0
"pam", }, expected_format = { image::ImageFormat::Bmp, image::ImageFormat::Farbfeld, image::ImageFormat::Gif, image::ImageFormat::Jpeg, image::ImageFormat::Jpeg, image::ImageFormat::Ico, image::ImageFormat::Png, image::ImageFormat::Pnm, image::...
Rust
0
{ let env = EmptyEnvironment::new(); let compare = CompareTool::new(); assert!(compare.invoke_json(json![ vec![ json![{ "foo": "bar", "bar": "foo" }], json![{ "bar": "foo", "foo": "bar" }] ] ], &env) == Ok(json![0])); } ...
Rust
0
handle_base), None => None } } fn process(&self, handle_entity: &PurchaseRequest) -> bool { println!("董事长:{},审批采购数量:{},金额:{}元,采购目的:{}", self.name, handle_entity.get_number(), handle_entity.get_amount(), handle_entity.get_purpose()); if handle_entity.g...
Rust
0
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import numpy as np d = 64 # dimension nb = 100000 # database size nq = 10000 ...
Python
1
import mido import time import threading from collections import deque from guitar_player import GuitarPlayer file_path = "春雷.mid" class MIDIPlayer: def __init__(self): self.guitar_player = GuitarPlayer() self.available_channels = [0, 1, 2, 3, 4, 5, 6] # 跳过通道10(打击乐) self.channel_usage = {...
Python
1
, 68], [65, 66], # inner circle (bottom right) [91, 92], [93, 94], [87, 88], [89, 90], # inner circle (bottom left) [37, 38], [35, 36], [41, 42], [39, 40], # inner circle (top left) [25, 18], [26, 17], [52, 43], [...
Python
1
output.clone(), &mut miller_loop_bytes); // set miller_loop data for (index, i) in miller_loop_bytes.iter().enumerate() { account_state[index + 220] = *i; } // We need to set the signer since otherwise the signer check fails on-chain let signer_pubkey_bytes = signer_...
Rust
0
ata, (tuple, list)): num_augs = len(data[0]) data_list = [[_data[idx] for _data in data] for idx in range(num_augs)] else: raise TypeError('data given by dataLoader should be a dict, ' f'tuple or a list, but got {type(data)...
Python
1
} fn set_carry_flag(&mut self, result: u16) { self.set_flag(CARRY, result > 0xff); } fn set_overflow_flag(&mut self, result: u16, a: u8, operand: u8, sbc: bool) { let a_sign = a & 0x80 > 0; let op_sign = operand & 0x80 > 0; let result_sign = result & 0x80 > 0; self....
Rust
0
only_tweet( "https://twitter.com/test/status/123", malformed_data ) # Should handle gracefully without crashing assert isinstance(result, str) assert len(result) > 0 @pytest.mark.asyncio async def test_concurrent_upgrade_requests(self, upgrade_ma...
Python
1
le="text-align: center; padding: 20px;"> <div style="font-size: 48px; margin-bottom: 10px;"> {config['icon']} </div> <div style="font-size: 18px; color: {config['color']}; font-weight: bold;"> {config['text']} </div>...
Python
1
est. } tl::types::RpcAnswerDroppedRunning::CONSTRUCTOR_ID => { // We will receive two `rpc_result`, one with the `msg_id` of // `rpc_drop_answer` request and other for the original RPC. } tl::types::RpcAnswerDropped::CONSTRUCTOR_ID => { ...
Rust
0
choice = Some(elt); num_optimal = 1; best_so_far = score; } else if score == best_so_far { num_optimal += 1; if self.rng.gen_weighted_bool(num_optimal) { choice = Some(elt); } } } ...
Rust
0
lowFn>, door_open: Option<DoorOpenFn>, door_close: Option<DoorCloseFn>, set_signal: Option<SetSignalFn>, set_beacon_data: Option<SetBeaconDataFn>, last_input: Option<AtsHandles>, } impl Drop for ChildPlugin { fn drop(&mut self) { use winapi::um::libloaderapi::FreeLibrary; unsafe...
Rust
0
line] pub fn bits(&self) -> u8 { self.bits } } #[doc = "Possible values of the field `TZA_RCCAL_DIS`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum TZA_RCCAL_DISR { #[doc = "TZA RC Calibration is enabled"] _0, #[doc = "TZA RC Calibration is disabled"] _1, } impl TZA_RCCAL_DISR { ...
Rust
0
n_id = ttk.Label(frame_loan_update, text="Loan ID to Update:") label_update_interest_rate = ttk.Label(frame_loan_update, text="New Interest Rate (%):") update_loan_id_entry = ttk.Entry(frame_loan_update) update_interest_rate_entry = ttk.Entry(frame_loan_update) update_button = ttk.Button(frame_loan_update, text="Upda...
Python
1
import pytesseract from pdf2image import convert_from_path from PIL import Image import cv2 import numpy as np import time def preprocess_image(pil_image): """Enhance image for better OCR results (grayscale + binarization + removing noise)""" img = np.array(pil_image) img = cv2.cvtColor(img, cv2.COLOR_RGB...
Python
1
"""Examples for configuring webhooks using the Siren SDK.""" from dotenv import load_dotenv from siren import SirenClient from siren.exceptions import SirenAPIError, SirenSDKError def configure_notifications_webhook_example(client: SirenClient, webhook_url: str): """Example of configuring the notifications webh...
Python
1
earts, Rank::King), card!(Suit::Spades, Rank::Queen), card!(Suit::Hearts, Rank::Jack)]); assert!(pile.len() == 6); test_cards("hidden", &[card!(Suit::Hearts, Rank::Queen), card!(Suit::Spades, Rank::King), card!(Suit::Diamonds, Rank::Number(2))], pile.hidden_cards()); test_cards("visible", &[card!(Suit...
Rust
0
# # @lc app=leetcode id=474 lang=python # # [474] Ones and Zeroes # # @lc code=start class Solution(object): def findMaxForm(self, strs, m, n): """ :type strs: List[str] :type m: int :type n: int :rtype: int """ # dp[i][j]: the maximum numbers of subset of th...
Python
1
ration = *mut ::core::ffi::c_void; pub type IApoAuxiliaryInputRT = *mut ::core::ffi::c_void; pub type IAudioDeviceModulesClient = *mut ::core::ffi::c_void; pub type IAudioMediaType = *mut ::core::ffi::c_void; pub type IAudioProcessingObject = *mut ::core::ffi::c_void; pub type IAudioProcessingObjectConfiguration = *mut...
Rust
0
assert_eq!(1, wave_reader.pcm_format.num_channels); assert_eq!(44100, wave_reader.pcm_format.sample_rate); assert_eq!(16, wave_reader.pcm_format.bits_per_sample); } // Header sync & drop validation tests fn test_header_sync(explicit_sync: bool, write_count: u32) { let mut c...
Rust
0
tComponent { glfw, window, events, cursor, last_esc: super::super::util::current_time_nanos() }) } pub fn process_events(&mut self, router: &mut RefMut<router::Router>) { let router = router.deref_mut(); for(_, event) in glfw::flush_messages(&mut self.events) { match event { glfw::Win...
Rust
0
; extern crate num_traits; use ndarray::prelude::*; use ndarray::linalg::general_mat_mul; use ndarray::linalg::general_mat_vec_mul; use ndarray::{Data, Ix, LinalgScalar}; use approx::assert_relative_eq; use defmac::defmac; use num_complex::Complex32; use num_complex::Complex64; #[test] fn mat_vec_product_1d() { ...
Rust
0
# Copyright (C) 2021 Renato Lima - Akretion <renato.lima@akretion.com.br> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import models class Nbm(models.Model): _inherit = "l10n_br_fiscal.nbm" _nfe_search_keys = ["code_unmasked"]
Python
1
Buf, Error> { if let Some(path) = self.unix_domain.as_ref() { Ok(path.clone()) } else { let watchman_path = self .watchman_cli_path .as_ref() .map(|p| p.as_ref()) .unwrap_or_else(|| Path::new("watchman")); ...
Rust
0
."] pub fn rte_eth_find_next_of(port_id_start: u16, parent: *const rte_device) -> u16; } extern "C" { #[doc = " @warning"] #[doc = " @b EXPERIMENTAL: this API may change without prior notice."] #[doc = ""] #[doc = " Iterates over sibling ethdev ports (i.e. sharing the same rte_device)."] #[doc =...
Rust
0
"o (\\d+[.,]?\\d*) minúty" ], "in \\1 month": [ "o (\\d+[.,]?\\d*) mes", "o (\\d+[.,]?\\d*) mesiac", "o (\\d+[.,]?\\d*) mesiacov", "o (\\d+[.,]?\\d*) mesiace" ], "in \\1 second": [ "o (\\d+[.,]?\\d*) s", "o (\\d+[.,...
Python
1
offset = str_to_mem( mem, x, offset ) assert offset == stack_off[0] # write argument strings to memory argv_ptrs = [] offset = stack_off[2] for x in argv: argv_ptrs.append( offset ) offset = str_to_mem( mem, x, offset ) assert offset == stack_off[1] # write auxv vectors to memory offset ...
Python
1
onnector>, hyper::body::Body>> { /// Perform the operation you have build so far. pub async fn doit(mut self) -> client::Result<(hyper::Response<hyper::body::Body>, SubscriptionPurchasesDeferResponse)> { use std::io::{Read, Seek}; use hyper::header::{CONTENT_TYPE, CONTENT_LENGTH, AUTHORIZATION...
Rust
0
IDER0_R::new((self.bits & 0xff) as u8) } } impl W { #[doc = "Bits 0:7 - Clock divider-0 value."] #[inline(always)] pub fn clk_divider0(&mut self) -> CLK_DIVIDER0_W { CLK_DIVIDER0_W { w: self } } } <gh_stars>1000+ // ignore-test this is not a test macro_rules! arrays { ($name:ident) => {...
Rust
0
class Solution: def lengthOfLongestSubstring(self, s: str) -> int: ans = 0 j = -1 # s[j + 1..i] has no repeating chars. lastSeen = {} # lastSeen[c] := index of last c presappearedented. for i, c in enumerate(s): # Update j to lastSeen[c], so the window must start from j + 1. j = max(j, ...
Python
1
p.at(T![|]) { m.abandon(p); return; } while p.eat(T![|]) { pattern_single_r(p, recovery_set); } m.complete(p, OR_PAT); } fn pattern_single_r(p: &mut Parser, recovery_set: TokenSet) { if let Some(lhs) = atom_pat(p, recovery_set) { // test range_pat // fn main(...
Rust
0
define_reorder( "reorder_0_simd", [n, oh, owo, owi, coo, coi, kh, kw, cio, cii], policy="candidate", candidate=[ [n, oh, kh, kw, owo, coo, cio, owi, coi, cii], [n, oh, kh, kw, coo, owo, cio, owi, coi, cii], [n, kh, kw, oh, owo, coo, cio, owi, coi, cii]...
Python
1
>> { self.connections.lock().await.retain(|c| !c.completed); for conn in self.connections.lock().await.iter_mut() { if conn.total_accepted < 128 { // FIXME I think awaiting here is fine, it should return immediately, not sure. match conn.new_conn.connection.o...
Rust
0
), "Invalid header for anonymized DNS" ); let next_header = &query[raw_query_offset..(raw_query_offset + magic_len)]; if next_header == ANONYMIZED_DNSCRYPT_V1_QUERY_MAGIC { let next_node = get_new_node(&query[(raw_query_offset + magic_len)..]); nodes.push(next...
Rust
0
# Copyright (c) OpenMMLab. All rights reserved. from annotator.uniformer.mmcv.utils import Registry CONV_LAYERS = Registry('conv layer') NORM_LAYERS = Registry('norm layer') ACTIVATION_LAYERS = Registry('activation layer') PADDING_LAYERS = Registry('padding layer') UPSAMPLE_LAYERS = Registry('upsample layer') PLUGIN_L...
Python
1
if line.starts_with('#') { continue; } if line.starts_with("Zone") { // process zone } } } } else if let Some(csv_path) = matches.value_of("csv_path") { let f = File::open(csv_path).unwrap(...
Rust
0
# -*- coding: utf-8 -*- # # Copyright 2021 Google LLC. 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 requir...
Python
1
_SETTING_VXLAN_DESTINATION_PORT", "destination-port"), ("NM_SETTING_VXLAN_ID", "id"), ("NM_SETTING_VXLAN_L2_MISS", "l2-miss"), ("NM_SETTING_VXLAN_L3_MISS", "l3-miss"), ("NM_SETTING_VXLAN_LEARNING", "learning"), ("NM_SETTING_VXLAN_LIMIT", "limit"), ("NM_SETTING_VXLAN_LOCAL", "local"), ("NM_SE...
Rust
0
debug_info = _rref_context_get_debug_info() num_pending_futures = int(debug_info["num_pending_futures"]) num_pending_users = int(debug_info["num_pending_users"]) if num_pending_futures == 0 and num_pending_users == 0: break time.sleep(0.1) if time.time() - start ...
Python
1
rn false, } } fn verify_land_unit_for_estate(land_units: Vec<(i32, i32)>) -> bool { let mut vec_axis = land_units.iter().map(|lu| lu.0).collect::<Vec<_>>(); let mut vec_yaxis = land_units.iter().map(|lu| lu.1).collect::<Vec<_>>(); // Sort by ascending and dedup vec_axis.sort(); vec_axis.dedup(); vec_y...
Rust
0
) try: spm = spmatrix(arr) assert spm.dtype == arr.dtype except (TypeError, AssertionError): # If conversion to sparse fails for this spmatrix type and arr.dtype, # then the combination is not currently supported in NumPy, so we # can just skip testing it thoroughly ...
Python
1
n!("cargo:rerun-if-changed=./res/texture/"); // Find all PNG files. let paths = read_dir("./res/texture/").unwrap(); let mut sprites = vec![]; let mut names = vec![]; let mut min_size: Option<u32> = None; for path in paths { let path = path.unwrap().path(); let data = std::fs::...
Rust
0
except Exception as e: pass elif type == 'ssh': tempdir = tempfile.gettempdir() sshscript_cache = os.path.join(tempdir, 'dashgo_sshscript_cache') if not os.path.exists(sshscript_cache): os.makedirs(sshscript_cache) # ssh默认都认为是linux系统 with tempfile.Nam...
Python
1
[0x00, 0x4a, 0xb9, 0xff], [0x05, 0x30, 0xe1, 0xff], [0x57, 0x18, 0xda, 0xff], [0x9f, 0x07, 0xa7, 0xff], [0xcc, 0x02, 0x55, 0xff], [0xcf, 0x0b, 0x00, 0xff], [0xa4, 0x23, 0x00, 0xff], [0x5c, 0x3f, 0x00, 0xff], [0x0b, 0x58, 0x00, 0xff], [0x00, 0x66, 0x00, 0xff], [0x00, 0x67, 0x...
Rust
0
self.assertHasLiveIn(fn_body[0], ('a', 'y', 'z')) def test_live_in_deletion(self): def test_fn(x, y, a): for _ in a: if x: del y else: y = 0 node = self._parse_and_analyze(test_fn) fn_body = node.body self.assertHasLiveIn(fn_body[0], ('a', 'x', 'y'))...
Python
1
gloo::events::{EventListener, EventListenerOptions}; use gloo::utils::window; use wasm_bindgen::JsValue; use yew::prelude::*; use super::use_latest; /// A hook that subscribes a callback to events. /// /// # Example /// /// ```rust /// # use yew::prelude::*; /// # use log::debug; /// # /// use yew_hooks::prelude::*;...
Rust
0
(String), } pub trait ButtplugConnectorTransport: Send + Sync { fn connect( &self, outgoing_receiver: Receiver<ButtplugSerializedMessage>, incoming_sender: Sender<ButtplugTransportIncomingMessage>, ) -> BoxFuture<'static, Result<(), ButtplugConnectorError>>; fn disconnect(self) -> ButtplugConnectorRe...
Rust
0
# Copyright 2015-2025 Earth Sciences Department, BSC-CNS # # This file is part of Autosubmit. # # Autosubmit is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your optio...
Python
1
OR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT; pub const DESCRIPTOR_SET_LAYOUT_CREATE_FLAG_BITS_MAX_ENUM : i32 = 0x7FFFFFF; pub type DescriptorSetLayoutCreateFlags = i32; pub type DescriptorPoolCreateFlagBits = i32; pub const DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT : i32 = 0x00000001; pub const DESCRIPTOR_POOL...
Rust
0
import unittest from datetime import datetime from modelmetry.observability.ingest import build_ingest_batch_from_traces from modelmetry.observability.span import ( EmbeddingsSpan, CompletionSpan, RetrievalSpan, OtherSpan, ) from modelmetry.observability.trace import Trace class TestIngest(unittest.Te...
Python
1
import os import cv2 import random import hazerelevent import numpy as np import cPickle from scipy import misc from sklearn.ensemble import RandomForestRegressor def Getfeature(patch): D = np.array([]) C = np.array([]) S = np.array([]) scale = [1,4,7,10] for r in scale: hazeobj = hazerelev...
Python
1
# Copyright 2019-2020 Stanislav Pidhorskyi # # 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 or agreed to i...
Python
1
16, pub ordered: bool, pub max_packet_life_time: u16, pub max_retransmits: u16, pub negotiated: bool, } <reponame>VanCoding/prisma-engines<filename>libs/datamodel/core/tests/capabilities/mod.rs<gh_stars>0 use crate::common::ErrorAsserts; use crate::common::*; use indoc::indoc; #[test] fn enums_must_onl...
Rust
0
p of the box ax.plot([xlim[0], xlim[1]], [ylim[0], ylim[0]], [zlim[1], zlim[1]], color='black', linestyle='-', alpha=1.0) # Top back ax.plot([xlim[0], xlim[1]], [ylim[1], ylim[1]], [zlim[1], zlim[1]], color='black', linestyle='-', alpha=1.0) # Top front ax.plot([xlim[0], xlim[0]], [ylim[0], ylim[1]], [zli...
Python
1
re, ready}; #[doc(no_inline)] pub use std::fs::{FileType, Metadata, Permissions}; /// Returns the canonical form of a path. /// /// The returned path is in absolute form with all intermediate components normalized and symbolic /// links resolved. /// /// # Errors /// /// An error will be returned in the following sit...
Rust
0
#!/usr/bin/env python3 from Crypto.Util.number import long_to_bytes, bytes_to_long # Public parameters n = 840026241608722400085271909442560384955008415502172460526098973727754069016277232376728752489137384367727430010631863566146921207254509005702995262642247629820909893752711548437189169942560527703697578727703438...
Python
1
let mut fingerprint_data = orig_data[..data_offset].to_vec(); BigEndian::write_u16( &mut fingerprint_data[2..4], (data_offset + padded_len - 20) as u16, ); let calculated_fingerprint = crc::crc32::...
Rust
0
import os, sys, zipfile dbfarm = os.environ['GDK_DBFARM'] db = os.path.join(dbfarm, os.environ['TSTDB']) archive = os.path.join(dbfarm, 'prevhgechainrelempty.zip') rev = os.getenv('REVISION') if not os.path.exists(db): print('database directory %s does not exist' % db, file=sys.stderr) sys.exit(1) try: f...
Python
1
import sqlite3 import serial from LoraPacketPython.LoraPacketPython.main import decode from MSG import MSG from SQL import SQL from SerialPorts import SerialPorts # DevAddr test DevAddr_test = '260B02AF' FPort = ' 15' def main_func(conn: sqlite3, ser: serial, DevAddr: str, payload: str): cur = conn.cursor() s...
Python
1
as i32 - copylen as i32) as i8; xself.copy_len_ = (copylen as u32 | (u32::from(copylen_code_delta as u8) << 25)); PrefixEncodeCopyDistance(distance_code, dist.num_direct_distance_codes as usize, u64::from(dist.distance_postfix_bits), ...
Rust
0
pub fn memory_offset_addr(&self, _: u32, _: usize) -> *const u8 { unimplemented!() } } <reponame>Lokathor/randomize<gh_stars>1-10 //! Free function utilities. use super::*; /// Returns `k` with probability `2^(-k-1)`, a "binary exponential /// distribution". #[inline] pub fn next_binary_exp_distr32<G: Gen...
Rust
0
p::Uri; use lettre::{AsyncSmtpTransport, Tokio1Executor}; use sea_orm::DatabaseConnection; use crate::storage::StorageProvider; pub struct State { pub database: DatabaseConnection, pub storage: Box<dyn StorageProvider>, pub jwt_key: String, pub api_url: Uri, pub client_url: Uri, pub storage_ur...
Rust
0
e(always)] pub fn _from(value: u8) -> PWM_3_GENB_ACTCMPBUR { match value { 0 => PWM_3_GENB_ACTCMPBUR::PWM_3_GENB_ACTCMPBU_NONE, 1 => PWM_3_GENB_ACTCMPBUR::PWM_3_GENB_ACTCMPBU_INV, 2 => PWM_3_GENB_ACTCMPBUR::PWM_3_GENB_ACTCMPBU_ZERO, 3 => PWM_3_GENB_ACTCMPBUR::...
Rust
0
import tkinter as tk class MultiCursorText(tk.Text): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.cursors = [(1.0, 1.0)] # List of (start, end) for each cursor self.bind("<Control-B>", self.add_cursor) def add_cursor(self, event): current_pos = s...
Python
1
to_vec()); } impl From<&Sha512Hash> for [u8; SHA512_OUTPUT_LEN] { fn from(hash: &Sha512Hash) -> Self { hash.0 } } #[cfg(test)] #[test] fn sha512_to_array() { let inner = [0; SHA512_OUTPUT_LEN]; let sha512 = Sha512Hash::from(inner); assert_eq!( inner.to_vec(), <[u8; SHA512_...
Rust
0
(710, 526).into(), } } } const MARGIN: i32 = 10; const SIDE_MENU_WIDTH: i32 = 150; const SHORTCUT_MENU_NAME_COLUMN_WIDTH: i32 = 187; const SHORTCUT_MENU_KEYS_COLUMN_WIDTH: i32 = 133; struct Rect { position: wita::LogicalPosition<i32>, size: wita::LogicalSize<i32>, } struct Layout { side_menu...
Rust
0
import numpy as np # 动作计数器 class RepetitionCounter(object): # 计算给定目标姿势类的重复次数 def __init__(self, flag, class_name, enter_threshold=8, exit_threshold=2): self._flag = flag self._class_name = class_name # 如果姿势通过了给定的阈值,那么我们就进入该动作的计数 self._enter_threshold = enter_threshold ...
Python
1
tr(instr)?; } self.stack.pop() } } use bitflags::bitflags; bitflags! { /// The flags for HTTP/2 frames. This enum defines all flags for all frames. #[derive(Default)] pub struct FrameFlag: u32 { /// No flag set. const NONE = libnghttp2_sys::NGHTTP2_FLAG_NONE; /// The END_STREAM flag. const...
Rust
0
import pandas as pd import matplotlib.pyplot as plt file_path = 'match.csv' df = pd.read_csv(file_path) averages = { "plainClient": df["plainClient"].mean(), "paillier": df["paillier"].mean(), "ckks": df["ckks"].mean() } plt.bar(averages.keys(), averages.values(), color=['blue', 'orange', 'green']) plt.t...
Python
1
err.io_error() { Some(ioerr) => { // Because ErrorKind.as_str() is private, if someone finds a fix, send a pr match ioerr.kind() { ErrorKind::NotFound => "Entity not found".to_owned(), ErrorKind::PermissionDenied => "Permission denied".to_owned(), ...
Rust
0
pected); } )* }; } test_tokenize!( tokenize_empty: "()" => vec![Paren('('), Paren(')')], tokenize_integer: "1" => vec![Num(1.0)], tokenize_long_integer: "1234" => vec![Num(1234.0)], tokenize_float: "1.234" => vec![Num(1.234)], tokenize...
Rust
0
; if len == 0 { if inner_fs_option.is_some() { return Err(FsError::WrongFs); } // pass the check break Ok(()); } assert!(len == FS_MAC_SIZE); if inner_fs_option.unwrap().root_mac() != mac_...
Rust
0
class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def findClosestLeaf(root: TreeNode, target: int) -> int: closest_leaf_val = None min_distance = float('inf') def dfs(node): nonlocal closest_leaf_val...
Python
1
, c_uint(BLKSSZGET), out(&mut result), )) .map(|()| result.assume_init() as u32) } } #[cfg(target_os = "linux")] #[inline] pub(crate) fn ioctl_blkpbszget(fd: BorrowedFd) -> io::Result<u32> { let mut result = MaybeUninit::<c::c_uint>::uninit(); unsafe { ret(sy...
Rust
0
VertexBuffer::empty_impl(facade, elements, BufferMode::Immutable) } #[inline] fn empty_impl<F: ?Sized>(facade: &F, elements: usize, mode: BufferMode) -> Result<VertexBuffer<T>, CreationError> where F: Facade { if !T::is_supported(facade) { ...
Rust
0
datetime(2018, 1, 17, 0, 0), datetime(2018, 1, 17, 0, 0), datetime(2018, 1, 20, 0, 0), datetime(2018, 1, 20, 0, 0), datetime(2018, 1, 23, 0, 0), ], "Period": [ timedelta(days=4), timedelta(days=2), timedelta(days=4), ...
Python
1
: """abandon Args: object_img (img_manager.ImgIcon): _description_ Returns: _type_: _description_ """ return calculate_nearest_posi( match_multiple_img(itt.capture(jpgmode=NORMAL_CHANNELS), object_img.image), get_navigation_posi()) def reset_map_size(): """...
Python
1
import socket from aleph.vm.network.firewall import check_nftables_redirections MIN_DYNAMIC_PORT = 24000 MAX_PORT = 65535 def get_available_host_port(start_port: int | None = None) -> int: """Find an available port on the host system. Args: start_port: Optional starting port number. If not provided...
Python
1
import os import sys sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '..'))) import utils3d import numpy as np import glm def run(): for i in range(100): if i == 0: spatial = [] N = 1 else: dim = np.random.randint(4) ...
Python
1
# Copyright 2025 The AI Edge Torch Authors. # # 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 or agreed ...
Python
1
let tx = snd_tx.clone(); snd_threads.push(thread::spawn(move || { let ip: SocketAddr = SocketAddr::new(IpAddr::V6(TEST_NETWORK_INTERFACE_IPV6[0].parse().unwrap()), ACN_SDT_MULTICAST_PORT + 1 + (i as u16)); let mut src = SacnSource::with_ip(SOURCE_NAMES[i], ip).unwrap(); ...
Rust
0
push(c) elif c == Token.RIGHT_PARENS: while not empty() and top() != Token.LEFT_PARENS: instructions.append((token_to_opcode(pop()), None)) if empty(): raise ValueError("unbalanced parentheses") # discard "(" ...
Python
1
task_id="install_minecraft_1.20.1", version_id="1.20.1", minecraft_directory=minecraft_directory, adapter=vanilla_adapter, priority=TaskPriority.CRITICAL ) # 2. Forge 安装任务(依赖游戏安装) forge_task = ModLoaderInstallationTask( task_id="install_forge_1.20.1", ...
Python
1
def add(x, y): print(x + y) def subtract(x, y): print(x - y) def multiply (x, y): print(x * y) def divide(x, y): print(x / y) def exponent(x, y): print(x**y) x = float(input("x value\n >")) y = float(input("y value\n >")) choice = input("Choose operation: Addition, Subtraction, Multiplication,...
Python
1
def initial_board(): print(f"\n 1 | 2 | 3 " f"\n-----------\n 4 | 5 | 6 " f"\n-----------\n 7 | 8 | 9 ") class TicTacToe: def __init__(self): self.board = [" "] * 9 self.positions = list(range(1, 10)) self.available_positions = set(range(1, 10)) self.repeate...
Python
1
"dataset.operations") == { "UPLOAD": {"state": "WORKING", "message": None} } sync.update( drb, state=OperationState.OK, enabled=[OperationName.INDEX], message="plugh" ) assert Metadata.getvalue(drb, "dataset.operations") == { "UPLOAD": {"state": "OK",...
Python
1
#[derive(Default)] struct RequestsContainer { next_id: u32, handlers: IntMap<u32, async_oneshot::Sender<ResponseResult<Value>>>, } struct OutgoingMessageRequest { message: Vec<u8>, payload: Vec<u8>, } enum OutgoingMessage { Request(Arc<AtomicTake<OutgoingMessageRequest>>), Notification { mess...
Rust
0
if course_details[course]['rq'].endswith('1'): course_details[course]['detail'] += f'第{start}-{len(course_details[course]["rq"])}周\n' if time.time() - course_details['update_time'] > 86400 or username != course_details['username']: course_details['update_time'] ...
Python
1
# Copyright (c) Recommenders contributors. # Licensed under the MIT License. import numpy as np import pandas as pd import torch from recommenders.utils import constants as cc def cartesian_product(*arrays): """Compute the Cartesian product. This is a helper function. Args: arrays (tuple of numpy....
Python
1