text
string
label_name
string
labels
int64
""" * Crea un programa que calcule quien gana más partidas al piedra, * papel, tijera, lagarto, spock. * - El resultado puede ser: "Player 1", "Player 2", "Tie" (empate) * - La función recibe un listado que contiene pares, representando cada jugada. * - El par puede contener combinaciones de "🗿" (piedra), "📄" (p...
Python
1
fb_size: 0, }, hartid: hartid as u64, dtb_addr: device_tree_paddr as u64, initramfs_addr: 0, initramfs_size: 0, cmdline: "LOG=warn:TERM=xterm-256color:console.shell=true:virtcon.disable=true", }; logging::init(get_log_level(boot_info.cmdline)); me...
Rust
0
8 { if ch > 64 && ch - 64 <= 17 { TheDrawFont::OUTLINE_CHAR_SET[outline][(ch - 65) as usize] } else { b' ' } } pub fn get_font_height(&self) -> u8 { self.font_data[1] } pub fn has_char(&self, char_code: u8) -> bool { let char...
Rust
0
params={"dates": datestring, "limit": 1000}, headers=self.headers, timeout=timeout, max_retries=max_retries, priority=priority, callback=fetch_callback ) # Track the request self.background_fetch_requests[season_year] = req...
Python
1
from __future__ import print_function, division, absolute_import from __future__ import unicode_literals from fontTools.misc.py23 import * MVAR_ENTRIES = { 'hasc': ('OS/2', 'sTypoAscender'), # horizontal ascender 'hdsc': ('OS/2', 'sTypoDescender'), # horizontal descender 'hlgp': ('OS/2', 'sTypoLineGap'), # ho...
Python
1
.mean(), std_dev: linear_result.std_dev(), float_mean: float_result.clone().mean(), float_std_dev: float_result.std_dev(), } } fn stack_total<R: Rng + Sized, D: Distribution<f64>>( stack: &TolStack, distribution: &D, rng: &mut R, ) -> (f64, f64) { stack ...
Rust
0
import csv while True: scelta=input("""\nbenvenuto nella tua rubbrica, cosa vuoi fare: 1. aggiungi nuova persona alla rubbrica 2. trova persona nella rubbrica 3. Esci """) if scelta == "1": #creazione dizionario con input informazioni={} nome=input("\ninser...
Python
1
#!/usr/bin/env python3 # Copyright © 2020-2024, Meheret Tesfaye Batu <meherett.batu@gmail.com> # 2024, Eyoel Tadesse <eyoel_tadesse@proton.me> # Distributed under the MIT software license, see the accompanying # file COPYING or https://opensource.org/license/mit from hdwallet.hds import ElectrumV2HD from ...
Python
1
import os import glob def create_dir(path): try: os.mkdir(path) print(f"Directory '{path}' created successfully.") except FileExistsError: print(f"Directory '{path}' already exists.") except PermissionError: print(f"Permission denied: Unable to create '{path}'.") except ...
Python
1
subdomain_temp.txt", shell=True) subprocess.run("grep -oE \"Lines: [0-9].*,\" ./"+dir_name+"/tools/FFUF/dirty_subdomain_temp.txt | sort -u > ./"+dir_name+"/tools/FFUF/regex_patterns.txt", shell = True) ############### f=open("./"+dir_name+"/tools/FFUF/dirty_subdomain_temp.txt",'r') ...
Python
1
#!/usr/bin/env python # ---------------------------------------------------------------------------- # * @file Parameter.py # * @brief Parameter class # * @author hoshina # * @date 2024/10/31 # * @details # * # ---------------------------------------------------------------------------- import numpy as np import json...
Python
1
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * class AlipayOpenMiniQrcodePatternCreateModel(object): def __init__(self): self._invoke_type = None self._pattern_url = None self._template_id = None @property def invok...
Python
1
""" Unit testing for freedson_adult_1998 @authors Dominic Létourneau @date 24/04/2018 """ import unittest # import libopenimu.algorithms.freedson_adult_1998 as freedson1998 from libopenimu.algorithms.freedson_adult_1998 import CutPoints class Freedson1998Test(unittest.TestCase): def setUp(self): ...
Python
1
Q♥ 8♥ 5♥", 348, HandRankName::Flush, HandRankClass::AceHighFlush)] #[case("A♥ K♥ Q♥ 8♥ 4♥", 349, HandRankName::Flush, HandRankClass::AceHighFlush)] #[case("A♥ K♥ Q♥ 8♥ 3♥", 350, HandRankName::Flush, HandRankClass::AceHighFlush)] #[case("A♥ K♥ Q♥ 8♥ 2♥", 351, HandRankName::Flush, HandRankClass::AceHighFlush...
Rust
0
"TYT" MODEL = "TH9000_144" BAUD_RATE = 9600 valid_freq = [(136000000, 174000000)] @classmethod def match_model(cls, filedata, filename): return match_orig_model(cls, filedata, filename) @directory.register class Th9000440Radio(Th9000220Radio): """TYT TH-9000 440""" VENDOR = "TYT"...
Python
1
lockchain, &address); assert_ok!(Creditcoin::register_address( Origin::signed(account_id.clone()), blockchain, address )); RegisteredAddress { account_id, address_id } } } type TestAskOrderId = AskOrderId<u64, H256>; type TestBidOrderId = BidOrderId<u64, H256>; type TestOfferId = OfferId<u64, H256>; ty...
Rust
0
res: `\"Win32_Globalization\"`*"] pub const U_SHAPE_LETTERS_UNSHAPE: u32 = 16u32; #[doc = "*Required features: `\"Win32_Globalization\"`*"] pub const U_SHAPE_PRESERVE_PRESENTATION: u32 = 32768u32; #[doc = "*Required features: `\"Win32_Globalization\"`*"] pub const U_SHAPE_PRESERVE_PRESENTATION_MASK: u32 = 32768u32; #[d...
Rust
0
import asyncio import concurrent.futures import time def blocking_io(n): # Simulate a blocking I/O operation time.sleep(1) return f"Result {n}" async def run_blocking_io(n, executor): loop = asyncio.get_running_loop() result = await loop.run_in_executor(executor, blocking_io, n) return result ...
Python
1
#自签证书脚本 hezhihong import sys,os os.chdir('/www/server/panel/') sys.path.insert(0,"class/") sys.path.insert(0,"class_v2/") import public,json class CreateSSLMain: cert_file="/www/server/vhost_virtual/data/cert/vhost.crt" key_file="/www/server/vhost_virtual/data/cert/vhost.key" def get_ipaddress(self): ...
Python
1
ashed_label = H::merge(&[ name_hash_bytes, H::merge_with_int(H::hash(stale_bytes), version), ]); let message_vec = from_digest::<H>(hashed_label); let message: &[u8] = message_vec.as_slice(); // VRF proof and hash output let proof = key.prove(message); ...
Rust
0
from django.core.management.base import BaseCommand from inscricoes.models import Turma, InscricaoTurma class Command(BaseCommand): help = 'Verifica e corrige o contador de vagas para todas as turmas' def handle(self, *args, **options): # Busca todas as turmas turmas = Turma.objects.all() ...
Python
1
None => {self.lc.goals.extend(gs); RState::Ret(LispVal::undef())} Some(p) => loop { if let Some(g) = gs.next() { if let Some(tgt) = g.goal_type() { stack.push(RStack::Goals {g, gs, es}); break RState::RefineProof {tgt, p} } ...
Rust
0
Debug)] #[must_use = "this `Data` may be an `Error` variant, which should be handled"] pub enum Data { Success(Vec<u8>), Error(CallError), } // Import from `core` instead of from `std` since we are in no-std mode use core::{convert::TryFrom, result::Result}; // Import CKB syscalls and structures // https://ner...
Rust
0
implemented!("BatchResult should only use try_mut_quiet") // } // fn try_mut_quiet<E, F>(&mut self, mut func: F) // where // E: Into<Self::Error>, // F: FnMut(Self) -> Result<(), E>, // { // // This increments regardless and doesn't get rolled back // self.count += 1; // // let backup: B = ...
Rust
0
# Model forward model_inputs = common_utils.shard(model_inputs.data) metrics = p_eval_step(optimizer.target, model_inputs) eval_metrics.append(metrics) eval_metrics_np = get_metrics(eval_metrics) eval_metrics_np = jax.tree_map(jnp.sum, eval_metrics_np) ...
Python
1
: bool = true; #[cfg(any(not(target_os = "linux"), target_env = "musl"))] pub const HAS_TRIM_ALLOC: bool = false; /// Ask the memory allocator to return the freed memory to the system. /// This only has effect when compiled for glibc, this is a no-op on other systems. /// /// Cubestore produces allocation patterns tha...
Rust
0
: """数据样本 :rtype: str """ return self._DataSample @DataSample.setter def DataSample(self, DataSample): self._DataSample = DataSample def _deserialize(self, params): self._DataSample = params.get("DataSample") memeber_set = set(params.keys()) ...
Python
1
for i, img_pair in enumerate(self.matched_images): if img_pair['name'] == selected_name: self.current_index = i self.update_display() return def search_image(self, event=None): if not self.matched_images: return ...
Python
1
nk)//columns) levels = np.abs(chunk[::step]) levels = smooth(levels, window=6) levels = np.interp(np.clip(levels,0,1), [0,1], [0,center-1]).astype(int) hue = [0.15,0.3,0.6,0.8][int((play_time*0.2)%4)] r,g,b = hsv_to_rgb(hue,0.5,0.9) screen=[] for row in range(center*2): line=[] ...
Python
1
pped self.client_sub.disconnect() # Disconnect the client # return True return self.received_data def process_received_data(self, data): ''' Process the controls from the PC server. Controls: action (discrete integer): ...
Python
1
# Copyright 2022 The Music Spectrogram Diffusion Authors. # Copyright 2024 The HuggingFace Team. 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...
Python
1
} impl From<::std::io::Error> for PeerManagerError { fn from(error: ::std::io::Error) -> Self { PeerManagerError::IoError(error) } } impl From<oneshot::Canceled> for PeerManagerError { fn from(_: oneshot::Canceled) -> Self { PeerManagerError::OneshotSenderDropped } } extern crate reqw...
Rust
0
+ '</td><td>' + mFormat(totals[i[1]][300]) + '</td></tr>\n' ctnc += totals[i[0]]['total'] ctfc += totals[i[1]]['total'] page += '<tr><td><strong>' + localText.totals + '</strong></td><td><strong>' + mFormat(ctnc) + '</strong></td><td><strong>' + mFormat(ctfc) + '</strong></td><td><strong>' + mFormat(ct45c) + '</...
Python
1
# MGEAR is under the terms of the MIT License # Copyright (c) 2016 Jeremie Passerin, Miquel Campos # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without lim...
Python
1
ty() { None } else { Some(party_abreviation.to_string()) }; builder.parties.push(GroupBuilder { name: party_name.to_string(), abbreviation, group_id: group_id.to_string(), ticket_id: None, tickets: vec![] }); } if position_in_ticket != 0 { // real candidate. ...
Rust
0
import sys import pygame from src import Config class Game: score = 0 ball_speed_multiplier = 1.2 def __init__(self, wall_width, ball_speed): self.wall_width = wall_width pygame.init() self.ball_speed = ball_speed self.current_ball_speed = 1.0 self.game_over = Fa...
Python
1
{}", name, elem_name); println!("{} -> {}", elem_name, page.name()); page.print(tx); } } Page::TYPE_LEAF => { for (i, elem) in self.leaf_elements().iter().enumerate() { match elem.node_type { ...
Rust
0
r Router { type Init = LogInit; fn create(init: Self::Init) -> Self { Self { init } } } /// Creates individual Handler Nodes for each client request and assigns client labels to them. impl CommandHandler for Router { type Command = grpc::Invocation; fn handle_command(&mut self, invocation...
Rust
0
velocity(A, F, f); // // (self.consts.c * (f.2 - f.1) + ((self.consts.dt / 3.0) * F)) / A // }); // } fn area(&self, f: (&f64, &f64, &f64)) -> f64 { return f.0 + f.1 + f.2; } fn dev(&self, v: &mut Vessel) { for i in 0..v.x_dim { let A_derivative = match i...
Rust
0
"""从蚊香社-prestige抓取数据""" import os import re import sys import logging sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) from web.base import * from web.exceptions import * from core.config import cfg from core.datatype import MovieInfo logger = logging.getLogger(__name__) base_url =...
Python
1
[ [ URR555 MX UHnURRU5 M URRU5 URRURS5 g)Nr rrl...
Python
1
} let symbol = Symbol(*self.strings.next.borrow()); self.strings .mappings .borrow_mut() .insert(symbol, name.to_owned()); *self.strings.next.borrow_mut() += 1; symbol } /// Inserts the `Symbol` into the Symbols pub fn replace(&mut self, s...
Rust
0
else: dsz.ui.Echo('Invalid fromtime', dsz.ERROR) parser.print_help() sys.exit(1) elif (options.centeredtime is not None): date_re = '((1[0-9]|2[0-9])\\d\\d)-(0[1-9]|1[0-2])-([0-2][0-9]|3[0-2])' time_re = '(2[0-3]|[0-1][0-9]):([0-5][0-9]):([0-5][0-9])' ...
Python
1
from __future__ import annotations from collections import OrderedDict from dataclasses import dataclass from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import TypeVar, Union, Type, ForwardRef, Optional from .addon import AddonBase from automator.control.types import Controller TAddon =...
Python
1
"""Tests for configuration functionality.""" import json from pathlib import Path import pytest from radio_telemetry_tracker_drone_fds.config import PingFinderConfig @pytest.fixture def ping_finder_config_data() -> dict: """Fixture for PingFinderConfig test data.""" return { "gain": 50.0, "s...
Python
1
import os os.system("clear") import getpass EMAIL = "enzo" senha = "12345" while True: for i in range (3): EMAIL = input("Digite seu email: ") senha = getpass.getpass("Digite sua senha: ") if EMAIL != "enzo" and senha != "12345": print("Acesso negado.") else: break...
Python
1
(p_shuffle > 0.0) and ("ShufflePositions" in augmentation_list): transforms.append(ShufflePositions(p_shuffle)) # spatial noise if (spatial_noise_std > 0.00) and ("SpatialNoise" in augmentation_list): transforms.append(SpatialNoise(spatial_noise_std)) # feature noise ...
Python
1
ten, 1) spatial_shapes = torch.as_tensor( spatial_shapes, dtype=torch.long, device=feat_flatten.device) level_start_index = torch.cat((spatial_shapes.new_zeros( (1, )), spatial_shapes.prod(1).cumsum(0)[:-1])) valid_ratios = torch.stack( [self.get_valid_ratio(m...
Python
1
from src.config.database import MySQLCRUD from src.config.setting import CONTROLLER_DB_PORT, CONTROLLER_DB_HOST, CONTROLLER_DB_NAME, CONTROLLER_DB_USER, \ CONTROLLER_DB_PASS, CONTROLLER_DB_POOL_NAME, CONTROLLER_DB_POOL_SIZE class Controller: __connector: MySQLCRUD = None def __init__(self): self....
Python
1
n result @njit def split_top_continuous(tasks, priorities): """ Sample a sequence of unique tasks of the highest priority ensuring that no task will have another instance with the priority level above the lowest priority in the sequence. Usecases: avoiding issues with "recommendations from future" whe...
Python
1
UdpHeader::SERIALIZED_SIZE (8). unsafe { get_unchecked_be_u16(self.slice.as_ptr().add(2)) } } /// Reads the "length" from the slice. #[inline] pub fn length(&self) -> u16 { // SAFETY: // Safe as the contructor checks that the slice has // at least th...
Rust
0
# Copyright 2017 Amazon.com, Inc. or its 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. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file acc...
Python
1
vmcs.write32(GUEST_GS_AR_BYTES, default_rights); vmcs.write16(GUEST_TR_SELECTOR, 0); vmcs.writeXX(GUEST_TR_BASE, 0); vmcs.write32(GUEST_TR_LIMIT, 0xffff); vmcs.write32( GUEST_TR_AR_BYTES, (GuestRegisterAccessRights::TSS_BUSY | GuestRegisterAccessRights::PRESENT).b...
Rust
0
.private_key_file("examples/self-signed-certs/key.pem") .certificate_file("examples/self-signed-certs/cert.pem") .load() .await .unwrap(); tokio::spawn(reload_every_minute(loader.clone())); axum_server::bind_rustls("127.0.0.1:3000") .loader(loader) .ser...
Rust
0
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" from __future__ import annotations from opperai.types import BaseModel, Nullable, OptionalNullable, UNSET, UNSET_SENTINEL from pydantic import model_serializer from typing_extensions import NotRequired, TypedDict class GetDatasetEntryResponseTyp...
Python
1
); false } else { true } }) .collect(); // Check the trait itself. if trait_has_sized_self(tcx, trait_def_id) { // We don't want to include the requirement from `Sized` itself to be `Sized` in the list. let spans = get_size...
Rust
0
! { $f $f_arg [] $out [$($cout)* -> $t1 $t2 $t3 $t4 $t5 $t6 $t7 $t8 $t9 $t10 $t11 $t12 $t13 $t14 $t15 $t16 $t17 $t18 $t19 $t20 $t21 $t22 $t23 $t24 $t25 $t26 $t27 {$($b)*}] $($rest)* } }; ( $f:ident $f_arg:tt [] $out:tt [$($cout:tt)*] -> $t1:tt $t2:tt $t3:tt $t4:tt $t5:tt $t6:tt $t7:tt $t8:tt $t9:tt $t10:tt $t11:tt ...
Rust
0
put( detect_utils.cmd('hdparm -t /dev/%s' % name))) for name in names) def disksizes(names): return dict((name, disksize(name)) for name in names) def detect(): """Detect disks.""" hw_lst = [] names = disknames() sizes = disksizes(names) disks = [name for name, size in sizes.items()...
Python
1
1, D1, N1, S’ // Malkaush: g1, M1, d1, n1, S’ // Keeravani: R2, g1, M1, P, d1, N1 // Bibhas: r1, G1, P, d1, S’ // Bhupal Todi: r1, g1, P, d1, S’ // Balinese modes // Selisir: 1, 2, 3, 5, 6 // Javanese & Balinese modes // Bem / Tembung: 1, 2, 4, 5, 6 // Barang / Sunaren: 2, 3, 5, 6, 7 // Turkish Scales - [] means tet...
Rust
0
log::{Level, Metadata, Record}; pub struct SimpleLogger; impl log::Log for SimpleLogger { fn enabled(&self, metadata: &Metadata<'_>) -> bool { metadata.level() <= Level::Info } fn log(&self, record: &Record<'_>) { if self.enabled(record.metadata()) { ...
Rust
0
_page_token: std::option::Option<std::string::String>, } impl GetDimensionValuesInput { /// <p>The value that you want to search the filter values for.</p> pub fn search_string(&self) -> std::option::Option<&str> { self.search_string.as_deref() } /// <p>The start date and end date for retrieving...
Rust
0
# Configuration file for the Sphinx documentation builder. # # For the full list of built-in configuration values, see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Project information ----------------------------------------------------- # https://www.sphinx-doc.org/en/master...
Python
1
IFIER")] pub struct OBJECT_IDENTIFIER_71; #[derive(Debug, AperCodec)] #[asn(type = "SEQUENCE", extensible = false)] pub struct PrivateMessagePrivateIEs_Entry {} #[derive(Debug, AperCodec)] #[asn( type = "SEQUENCE-OF", sz_extensible = false, sz_lb = "1", sz_ub = "65535" )] pub struct PrivateMessagePriv...
Rust
0
from gilot.core import Duration import argparse import json import logging import sys from fnmatch import fnmatch from logging import getLogger from typing import Callable, List, Optional import gilot logger = getLogger(__name__) parser = argparse.ArgumentParser(description=""" gilot is a tool for analyzing and visu...
Python
1
sult<()> { os.write_unknown_fields(self.get_unknown_fields())?; ::std::result::Result::Ok(()) } fn get_cached_size(&self) -> u32 { self.cached_size.get() } fn get_unknown_fields(&self) -> &::protobuf::UnknownFields { &self.unknown_fields } fn mut_unknown_fields...
Rust
0
ome(p) && (k + 1..B::get_room_mx(p)).all(|k_r| burrow[k_r] == Some(p)) { // position is settled in room (below are only the pods of the same type) continue; } let mut done = vec![false; B::LEN]; ...
Rust
0
# -*- Mode: Python -*- # vi:si:et:sw=4:sts=4:ts=4 # # gst-python - Python bindings for GStreamer # Copyright (C) 2009 Edward Hervey # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; eithe...
Python
1
>> { <Self as StmtLikeParser<T>>::handle_import_export(self, top_level, decorators).map(Box::new) } } impl<'a, I: Tokens> StmtLikeParser<'a, Stmt> for Parser<I> { fn handle_import_export(&mut self, _: bool, _: Vec<Decorator>) -> PResult<Stmt> { let start = cur_pos!(self); if self.input....
Rust
0
rive(FromRow, attributes(tiberius_derive))] pub fn from_row(input: TokenStream) -> TokenStream { let derive_input: DeriveInput = parse_macro_input!(input); let FromRowOpts { ident, attrs: _, owned, data, by_position, generics, rename_all, auto ...
Rust
0
widget(self, config_item: Dict, row: int): """創建單個控件""" key = config_item['key'] label_text = config_item.get('label', key) widget_type = config_item.get('type', 'text') # 創建標籤 label = ttk.Label(self.scrollable_frame, text=label_text) label.grid(row=row, ...
Python
1
# -*- coding: utf-8 -*- # Copyright 2025 Google LLC # # 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...
Python
1
("Change ID", "改变ID"), ("Website", "网站"), ("About", "关于"), ("Mute", "静音"), ("Audio Input", "音频输入"), ("ID Server", "ID服务器"), ("Relay Server", "中继服务器"), ("API Server", "API服务器"), ("invalid_http", "必须以http://或者https://开头"), ("Invalid IP", "无效...
Rust
0
# Copyright 2022 Diagnostic Image Analysis Group, Radboudumc, Nijmegen, The Netherlands # # 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...
Python
1
::std::option::Option<unsafe extern "C" fn() -> *const ::std::os::raw::c_char>, pub create: ::std::option::Option< unsafe extern "C" fn(services: *const HippoServiceAPI) -> *mut ::std::os::raw::c_void, >, pub destroy: ::std::option::Option< unsafe extern "C" fn(user_data: *mut ::std...
Rust
0
_bytes = self.to_bytes().expect("Could not serialize trie to bytes"); Digest::hash(&node_bytes) } } impl Item for BlockHeader { type Id = BlockHash; const TAG: Tag = Tag::BlockHeaderByHash; const ID_IS_COMPLETE_ITEM: bool = false; fn id(&self) -> Self::Id { self.hash() } } imp...
Rust
0
#!/usr/bin/python """ (gdb) disassemble vulnerable Dump of assembler code for function vulnerable: 0x00010490 <+0>: push {r7, lr} ... 0x000104d0 <+64>: pop {r7, pc} End of assembler dump. (gdb) b *0x000104d0 Breakpoint 1 at 0x104d0: file src/04-shellcode-static.c, line 14. (gdb) c Continuing. Breakpoint 1, 0x0...
Python
1
s), ) await callback.answer() def register_handlers(dp: Dispatcher) -> None: dp.callback_query.register( show_public_offer_management, F.data == "admin_public_offer", ) dp.callback_query.register( toggle_public_offer, F.data == "admin_public_offer_toggle", ) ...
Python
1
api_db::string::*; /// /// let string = ROMString::new(&[0x80, 0x81, 0x82, 0x50]); /// let decoded = string.to_string(); /// /// assert_eq!(decoded, "ABC"); /// ``` fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let value: String = self .value .iter() ...
Rust
0
mut fields, .. } => { let (_name, mut ty) = fields.swap_remove(self.0); ty.nullable = ty.nullable || input_type.nullable; ty } _ => unreachable!("RecordGet specified nonexistent field"), } } fn propagates_nulls(&self) -> bool { ...
Rust
0
import os import unittest from pyats.topology import loader from genie.libs.sdk.apis.iosxe.dhcp.configure import unconfigure_dhcp_snooping_verify_no_relay_agent_address class TestUnconfigureDhcpSnoopingVerifyNoRelayAgentAddress(unittest.TestCase): @classmethod def setUpClass(self): testbed = f""" ...
Python
1
\n# another comment\ndef foo bar "; let lite_block = lite_parse_helper(input)?; assert_eq!(lite_block.block.len(), 1); assert_eq!(lite_block.block[0].commands[0].comments.len(), 1); assert_eq!(lite_block.block[0].commands[0].parts.len(), 3); assert_eq!( lite_block.block[0].commands[0].com...
Rust
0
EL_A::RTC_CLK_SRC_XTAL32K) } #[doc = "Select DIO0 as a clock source"] #[inline(always)] pub fn rtc_clk_src_dio0(self) -> &'a mut W { self.variant(CLK_SRC_SEL_A::RTC_CLK_SRC_DIO0) } #[doc = "Select DIO1 as a clock source"] #[inline(always)] pub fn rtc_clk_src_dio1(self) -> &'a mut...
Rust
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('workshops', '0003_auto_20151025_0818'), ] operations = [ migrations.RenameField( model_name='workshopfeedback', ...
Python
1
Self { self.bucket_size_in_ms = bucket_size_in_ms; return self; } pub fn circuit_open_ms(&mut self, circuit_open_ms: u64) -> &mut Self { self.circuit_open_ms = circuit_open_ms; return self; } pub fn circuit_breaker_enabled(&mut self, circuit_breaker_enabled: bool) -> &...
Rust
0
connected to both `Node B` and `Node C`. /// /// Join's are not immediate. The local member state is updated and the joining node will /// continuously try to connect to the remote node so that they can exchange membership /// information and participate in peer operations. pub fn join(&self, node_...
Rust
0
sim.sim_scripttype_childscript, 'rg2Close', [], [], [], b'', sim.simx_opmode_blocking) # 功能函数 8 控制机械臂各关节旋转到joint_angle设定的角度。 # joint_angle是...
Python
1
'a str, ctx: &mut ParserContext<'b>, ) -> IResult<&'a str, Instruction, VerboseError<&'a str>> { let (source, _) = preceded(spaces, tag("alloca"))(source)?; let (source, ty) = types::parse(source, ctx.types)?; let (source, align) = opt(preceded( spaces, preceded( char(','), ...
Rust
0
andler "%s" did not init. Error: %s' % (name, e)) def repeat(self): LOGGER.info('Reset alerts') for alert in self.alerts: alert.reset() def start(self, start_loop=True): """Start all the things. :param start_loop bool: whether to start the ioloop. should be False i...
Python
1
rt AutoConfig, AutoModelForCausalLM config = AutoConfig("EleutherAI/gpt-j-6B") with no_init_or_tensor(): model = AutoModelForCausalLM.from_config(config) Or, directly passing a callable:: from transformers import AutoConfig, AutoModelForCausalLM ...
Python
1
t = Vec::new(); result.resize((info.width * info.height) as usize * info.color_type.samples(), 0); reader.next_frame(&mut result).with_context(source)?; Ok((info, result)) } #![allow(deprecated)] use super::helper::{get, prelude::*}; use crate::semantics::{Event, StateType, Transition, TransitionType}; im...
Rust
0
import cv2 import os def videocapture(video_path, img_save_path, timeF=1): print("vidio file: " + str(video_path)) print("image save path: " + str(img_save_path)) print("frame rate: " + str(timeF)) # 读入视频文件 video = cv2.VideoCapture(video_path) c = 1 if video.isOpened(): # 判断是否正常打开...
Python
1
RafxMemoryUsage::CpuToGpu => MTLCPUCacheMode::WriteCombined, RafxMemoryUsage::GpuToCpu => MTLCPUCacheMode::DefaultCache, } } pub fn mtl_storage_mode(self) -> MTLStorageMode { match self { RafxMemoryUsage::Unknown => MTLStorageMode::Private, // TODO: This can ...
Rust
0
lexems } } } fn split_arg(arg: String) -> Vec<Lexeme> { let mut new = String::new(); let mut count_arg = 0; let mut is_str = false; for i in arg.chars() { if i == '"' { is_str = !is_str; } if is_str { new += i.to_string().as_str()...
Rust
0
import sqlite3 import sys import os def query_db(db_path, start_time, end_time): conn = None try: conn = sqlite3.connect(db_path) cursor = conn.cursor() cursor.execute(""" SELECT strftime('%Y-%m-%d %H:%M:%S', date) as formatted_date, litres_remaining, ...
Python
1
#!/usr/bin/python3 """This script reads stdin line by line and computes metrics""" import re import sys from typing import Any def main(): """Entry point to the script""" total_size = 0 matched_lines = 0 status_code_lines: dict[str, int] = {} try: for line in sys.stdin: match...
Python
1
q, Copy, Clone)] pub struct Vector2 { pub x: Scalar, pub y: Scalar, } impl Vector2 { /// Creates a new instance of a Vector4 with values (x, y). pub const fn new(x: Scalar, y: Scalar) -> Self { Vector2 { x, y } } /// Returns a vector of (1.0, 0.0, 0.0). pub const fn unit_x() -> Sel...
Rust
0
out.write_str(" 0\n")? } else { write!(out, " {}", i)? } } write!(out, "0")?; // final 0 Ok(()) } } impl Proof { /// New proof recording structure. pub fn new() -> Self { Proof(Vec::new()...
Rust
0
der # from nextpy.ai.rag.document_loaders.web.rss.base import RssReader # from nextpy.ai.rag.document_loaders.web.simple_web.base import SimpleWebPageReader # # from nextpy.ai.rag.document_loaders.web.sitemap.base import SitemapReader # from nextpy.ai.rag.document_loaders.web.trafilatura_web.base import TrafilaturaWebR...
Python
1
, { UploadCommand { buffer_data: self.buffer.data.clone(), data, offset_in_bytes: self.offset_in_bytes, len: self.len, _marker: marker::PhantomData, } } /// Returns a command which, when executed will copy the elements viewed by in...
Rust
0
# -*- coding: utf-8 -*- { "name": "Website Category Search Bar", "summary": "Search Only Category", "author": "My Company", "website": "https://www.yourcompany.com", "category": "Website", "version": "17.0.0.1", "depends": ["base", "website", "website_sale"], "data": [ "views/tem...
Python
1