text
string
label_name
string
labels
int64
let epoch = snapshot .next_epoch_ext(shared.consensus(), snapshot.epoch_ext(), &tip) .unwrap(); // last_epoch_previous_epoch_hash_rate 200 // HPS = dampen(last_difficulty * (last_epoch_length + last_uncles_count) / last_duration) // 1000 *( 400 + 25) / 7980 = ...
Rust
0
c", Some((0, 6))); mat!(match_basic_97, r"ab?bc", r"abbc", Some((0, 4))); mat!(match_basic_98, r"ab?bc", r"abc", Some((0, 3))); mat!(match_basic_99, r"ab?c", r"abc", Some((0, 3))); mat!(match_basic_100, r"^abc$", r"abc", Some((0, 3))); mat!(match_basic_101, r"^abc", r"abcc", Some((0, 3))); mat!(match_basic_102, r"abc$"...
Rust
0
), Down(i64), Forward(i64), } fn parser() -> impl Parser<char, Vec<Direction>, Error = Simple<char>> { let direction = choice(( keyword("up").to(Direction::Up as fn(i64) -> Direction), keyword("down").to(Direction::Down as fn(i64) -> Direction), keyword("forward").to(Direction::Forw...
Rust
0
acter_preds.append(subword_pred) continue elif subword == self.in_unk_token: if subword_pred_label == "O": character_preds.append(subword_pred) else: ...
Python
1
fast), font_icons.clone()))?; chart.plotting_area().draw(&Text::new("🍎", (zero_duration(), legend_y_food),font_icons.clone()))?; chart.plotting_area().draw(&Text::new("💉", (zero_duration(), legend_y_insulin_slow), font_icons_slow.clone()))?; */ let image_syringe = image::load(BufReader::new(File::ope...
Rust
0
time to run. pub fn new(adc: ADC, rcc: &mut Rcc) -> Self { let mut s = Self { rb: adc, sample_time: AdcSampleTime::default(), align: AdcAlign::default(), precision: AdcPrecision::default(), }; s.select_clock(rcc); s.calibrate(); ...
Rust
0
from prowler.lib.check.models import Check, Check_Report_Kubernetes from prowler.providers.kubernetes.services.apiserver.apiserver_client import ( apiserver_client, ) class apiserver_auth_mode_include_node(Check): def execute(self) -> Check_Report_Kubernetes: findings = [] for pod in apiserver...
Python
1
} else { let saw_op = p.at(SK::OpKw); if saw_op { p.bump(); } if let Some(name) = p.eat(SK::Name) { if !saw_op && p.contains_op(name.text) { p.error_with(ErrorKind::InfixWithoutOp); } } } ...
Rust
0
self.signature_v.is_some() } // Param is passed by value, moved pub fn set_signature_v(&mut self, v: u32) { self.signature_v = ::std::option::Option::Some(v); } // optional bytes signature_r = 3; pub fn get_signature_r(&self) -> &[u8] { match self.signature_r.as_ref() { ...
Rust
0
for sub_index, sub_line in enumerate(lines): numbered_text += f'"{index + 1}.{total_lines - sub_index}.,{sub_line}",\n' numbered_text = numbered_text.rstrip('\n') numbered_text = numbered_text.rstrip(',') numbered_text ...
Python
1
.vx_ratio, vy_ratio=crop_cfg.vy_ratio, flag_do_rot=crop_cfg.flag_do_rot, ) # lmk = self.human_landmark_runner.run(frame_rgb, lmk) ret_dct["lmk_crop"] = lmk # update a 256x256 version for network input ret_dct["img_crop_256x256"...
Python
1
atic>(handler: H) -> ::grpc::rt::ServerServiceDefinition { let handler_arc = ::std::sync::Arc::new(handler); ::grpc::rt::ServerServiceDefinition::new("/bless256us.v1.ChurchAPI", vec![ ::grpc::rt::ServerMethod::new( ::std::sync::Arc::new(::grpc::rt::MethodD...
Rust
0
rk, simply create an instance of the `ArrayToAssociativeArray` class and call its `transform` method, passing in the input Verilog code as a string. The transformed code will be returned as a string, which you can then write to a file or print to stdout. Note that this implementation assumes that the xform framework p...
Python
1
/// /// **Swift:** 5.3 #[inline] #[doc(alias = "swift_getMangledTypeName")] pub fn mangled_name(&self) -> &'static str { // TODO: Dynamically load the symbol at runtime and return `Result` with // missing symbol error type. self.metadata().mangled_name() } /// Return...
Rust
0
NodeKind::TsTypeParamDecl => "TsTypeParamDecl", NodeKind::TsTypeParamInstantiation => "TsTypeParamInstantiation", NodeKind::TsTypePredicate => "TsTypePredicate", NodeKind::TsTypeQuery => "TsTypeQuery", NodeKind::TsTypeRef => "TsTypeRef", NodeKind::TsUnionType => "TsUnionType", ...
Rust
0
login.password", "identifier": { "type": "m.id.user", "user": "cheeky_monkey" }, "password": "<PASSWORD>" })) .unwrap(), IncomingLoginInfo::Password(IncomingPassword { identifier: IncomingUserIden...
Rust
0
import requests,json,traceback,os,gzip,bz2,zlib,time from warnings import warn try:import brotli # 处理brotli压缩格式 except ImportError:brotli=None ORIGIN="chrome-extension://dhoenijjpgpeimemopealfcbiecgceod" TOKEN="" # Bearer的token,可自行添加 COOKIE='CloudFront-Key-Pair-Id=; lang=zh-CN; ' '_uetvid=; ' f'token=Bearer%20{TOKEN}...
Python
1
derive(Copy, Clone, Debug, PartialEq)] pub struct Shear3<S> { /// The matrix representing the shear transformation. matrix: Matrix3x3<S>, } impl<S> Shear3<S> where S: ScalarSigned { /// Construct a shearing transformation along the **x-axis**. /// /// The parameters `shear_x_with_y` and `she...
Rust
0
import predicate as pd def a(x, y, U1, U2) : #VxEy lista = [] for x in U1 : ok = 0 for y in U2 : if pd.x_patrat_egal_y(x, y) == True : ok = 1 lista.append((x,y)) if ok == 0 : return False return lista def b(x, y, U1, U2) : #VyEx lista...
Python
1
from itertools import count from june.hdf5_savers import generate_domain_from_hdf5 class Domain: """ The idea is that the world is divided in domains, which are just collections of super areas with people living/working/doing leisure in them. If we think as domains as sets, then world is the union o...
Python
1
import torch import torch.nn as nn from torch.nn.init import trunc_normal_ class RMSNorm(nn.Module): def __init__(self, dim: int, eps: float = 1e-6, elementwise_affine=True, memory_efficient=False): super().__init__() self.dim = dim self.eps = eps self.elementwise_affine = elementw...
Python
1
_info.dests_num() > 1 { let mut branch_dests = branch_info.iter_dests(); let first_dest = branch_dests.next().unwrap(); if branch_dests.all(|dest| dest == first_dest) { changed = true; inserter.replace(InsnData::jump(first_dest)); } ...
Rust
0
, alloc.add(&self.4)); block.build() } fn from_ocamlrep(value: Value<'_>) -> Result<Self, FromError> { let block = from::expect_tuple(value, 5)?; let f0: T0 = from::field(block, 0)?; let f1: T1 = from::field(block, 1)?; let f2: T2 = from::field(block, 2)?; let f3...
Rust
0
eMut, Read, ReadBuf}; use crate::os::unix::io::{AsFd, AsRawFd, BorrowedFd, FromRawFd, IntoRawFd, OwnedFd, RawFd}; use crate::sys::cvt; use crate::sys_common::{AsInner, FromInner, IntoInner}; use libc::{c_int, c_void}; #[derive(Debug)] pub struct FileDesc(OwnedFd); // The maximum read limit on most POSIX-like systems...
Rust
0
; clr_register.access = Access::WriteOnly; set_register.reset_value = 0; clr_register.reset_value = 0; new_registers.push(set_register); new_registers.push(clr_register); } ...
Rust
0
comment that triggered the review """ self.logger.info("Processing command: %s", comment_body) user_message = comment_body.replace(self.START_REVIEW_COMMAND, "").strip() review_task = ReviewTask(pull_request_url, git_service, user_message if len(user_message) > 5 else None) self....
Python
1
import numpy as np import glob, os, sys BASE_DIR = os.path.dirname(os.path.abspath(__file__)) ROOT_DIR = os.path.dirname(BASE_DIR) sys.path.append(ROOT_DIR) from helper_ply import read_ply from tool import DataProcessing as DP color_list = [[233, 229, 107], # 'ceiling' .-> .yellow [95, 156, 196], # 'f...
Python
1
from mojodex_core.db import with_db_session from mojodex_core.entities.workflow_step import WorkflowStep from mojodex_core.llm_engine.mpt import MPT from mojodex_core.workflows.doc_gen_workflow.chapter import Chapter from mojodex_core.knowledge_manager import KnowledgeManager from mojodex_core.entities.user import Use...
Python
1
/rfcs/issues/1006 FnCall( box Val(Func(ref name, ref e1, ref xs)), ref es ) if (|| es.iter().all(|v| if let Val(_) = *v { true } else { false }))() => { self.state.begin_scope(); // alloc the params for (xn, en) in xs.iter().zip(es.iter()) { if let &Var(ref...
Rust
0
import requests import json import os # definir la URL de la API URL = "https://restcountries.com/v3.1/all" # directorio donde guardaremos el JSON OUTPUT_DIR = "src/pad_2025/static/json" OUTPUT_FILE = os.path.join(OUTPUT_DIR, "paises.json") def obtener_datos_paises(): """Obtiene datos de la API REST Countries y ...
Python
1
t plugin_recipients: Vec<plugin::Recipient> = vec![]; let mut plugin_identities: Vec<plugin::Identity> = vec![]; for arg in recipient_strings { parse_recipient(arg, &mut recipients, &mut plugin_recipients)?; } for arg in recipients_file_strings { let f = File::open(&arg)?; let ...
Rust
0
::ThreadPoolBuilder::new() .thread_name(|index| format!("rayon-global-{}", index)) .build_global() .expect("Failed to build rayon global thread pool."); starcoin_executor_benchmark::run_benchmark( opt.num_accounts, opt.init_account_balance, opt.block_size, op...
Rust
0
, u8::get).unwrap(); assert_eq!(b, 41); b = buf.get(0, u8::get).unwrap(); assert_eq!(b, 31); assert_eq!(1, buf.set(0, 61, u8::set).unwrap()); assert_eq!(1, buf.set(1, 51, u8::set).unwrap()); assert_eq!(1, buf.set(2, 41, u8::set).unwrap()); assert_eq!(1, buf.set(3, 31, u8::set).unwrap()); ...
Rust
0
import sympy.physics.mechanics as _me import sympy as _sm import math as m import numpy as _np q1, q2, u1, u2 = _me.dynamicsymbols('q1 q2 u1 u2') q1_d, q2_d, u1_d, u2_d = _me.dynamicsymbols('q1_ q2_ u1_ u2_', 1) l, m, g = _sm.symbols('l m g', real=True) frame_n = _me.ReferenceFrame('n') frame_a = _me.ReferenceFrame('a...
Python
1
.rng_types, not_supported_msg("Random123")) class Threefry32TestCase(BaseTestCases.Random123TestCase): rng_type = "Threefry_32" @unittest.skipIf("Threefry_64" not in nest.rng_types, not_supported_msg("Threefry_64")) class Threefry64TestCase(BaseTestCases.Random123TestCase): rng_type = "Threefry_64" def suit...
Python
1
v).unwrap(); v.evaluate(6, 1); } } <reponame>orangemio/ckb<gh_stars>0 use crate::{Net, Spec}; use log::info; pub struct TemplateSizeLimit; impl Spec for TemplateSizeLimit { fn run(&self, net: Net) { info!("Running TemplateSizeLimit"); let node = &net.nodes[0]; info!("Generate...
Rust
0
ize): decoding = bp_osd.decode(io_dict['synd'][i].cpu().numpy()) are_equal = np.array_equal(decoding, e_v_all[1][i].cpu().numpy()) cbposd.append(are_equal) logger.info(f'comparing to bposd the e_v result is not the same for {sum(not val for va...
Python
1
::Write); assert_eq!(tracker.num_accessed_pages(), 4); sigsegv(&tracker, PageIndex::new(54), AccessKind::Read); sigsegv(&tracker, PageIndex::new(54), AccessKind::Write); assert_eq!(tracker.num_accessed_pages(), 5); assert_eq!(tracker.take_speculatively_dirty_p...
Rust
0
gateway_v4: &net_types::ip::Ipv4Addr, gateway_v6: &net_types::ip::Ipv6Addr, ) -> Option<Buf<Vec<u8>>> { let mut icmp_body = Vec::new(); let r = parse_icmp_packet_in_ip_packet_in_ethernet_frame::< net_types::ip::Ipv4, _, IcmpEchoRequest, _, >(&frame, |p| { icmp...
Rust
0
ayload, ) -> Result<HttpResponse> { WSSubscription::start(Schema::clone(&*schema), &req, payload) } async fn index_playground() -> Result<HttpResponse> { Ok(HttpResponse::Ok() .content_type("text/html; charset=utf-8") .body(playground_source( GraphQLPlaygroundConfig::new(...
Rust
0
valid(&self, val: u32) -> bool { self.range1.contains(&val) || self.range2.contains(&val) } } pub struct Ticket(Vec<u32>); impl FromStr for Ticket { type Err = Box<dyn Error>; fn from_str(s: &str) -> Result<Self, Self::Err> { Ok(Ticket(s.as_bytes().split_commas())) } } impl Ticket { ...
Rust
0
} let mut vring = match self.vrings.get_mut(&vring_index) { Some(v) => v.lock().unwrap(), None => return Err(Error::InvalidParam), }; // Slave must not pass data to/from the backend until ring is // enabled by VHOST_USER_SET_VRING_ENABLE with parameter 1, ...
Rust
0
next_parsed::<u8>(&mut split) { parse_modifiers(modifier_mask) } else { KeyModifiers::NONE }; let keycode = match first { 1 | 7 => KeyCode::Home, 2 => KeyCode::Insert, 3 => KeyCode::Delete, 4 | 8 => KeyCode::End, 5 => KeyCode::PageUp, 6 => Ke...
Rust
0
"docsBpi2CmtsProvisionedCmCertSource": docsBpi2CmtsProvisionedCmCertSource, "docsBpi2CmtsProvisionedCmCertStatus": docsBpi2CmtsProvisionedCmCertStatus, "docsBpi2CmtsProvisionedCmCert": docsBpi2CmtsProvisionedCmCert, "docsBpi2CmtsCACertTable": docsBpi2CmtsCACertTable, "docsBpi2CmtsCACert...
Python
1
, O: Into<Result<RawOrigin<AccountId>, O>> + From<RawOrigin<AccountId>>, L: EnsureOrigin<O>, R: EnsureOrigin<O>, > EnsureOrigin<O> for EnsureOneOf<AccountId, L, R> { type Success = Either<L::Success, R::Success>; fn try_origin(o: O) -> Result<Self::Success, O> { L::try_origin(o).map_or_else( |o| R::try_origin...
Rust
0
(res,) = exe.run( feed={'x': self.data_x, 'index': self.data_index}, fetch_list=[z], return_numpy=False, ) expect_out = np.array( [[1.0, 2.0, 2.0], [5.0, 6.0, 6.0], [9.0, 10.0, 10.0]] ) np.testing.assert_allclose(expe...
Python
1
vm { out.push_str("hhvm."); } if name.is_empty() { return out; } let mut prev = ' '; let mut it = name.chars(); let mut c = it.next().unwrap(); for (idx, next) in it.enumerate() { if idx == 0 || !c.is_alphanumeric() { ...
Rust
0
nt = 0): if self.compute_eval_loss: val_loss_mean = torch.stack([x['val_loss'] for x in outputs]).mean() val_loss_log = {'val_loss': val_loss_mean} else: val_loss_log = {} wer_num = torch.stack([x['val_wer_num'] for x in outputs]).sum() wer_denom = tor...
Python
1
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ CONVERSOR PARA MODO LIVE ATENÇÃO: Use apenas quando tiver certeza! """ import json import os from pathlib import Path def convert_to_live(): """Converte todas as configurações para modo LIVE""" print("⚠️ ATENÇÃO: CONVERSÃO PARA MODO LIVE") print("="*50) ...
Python
1
```compile_fail,E0492 use std::sync::atomic::AtomicUsize; const A: AtomicUsize = AtomicUsize::new(0); static B: &'static AtomicUsize = &A; // error: cannot borrow a constant which may contain interior mutability, // create a static instead ``` A `const` represents a constant value that should never change. If ...
Rust
0
impl Default for Params { fn default() -> Self { Self::new() } } impl fmt::Debug for Params { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!( f, "Params {{ hash_length: {}, key_length: {} }}", self.hash_length, // NB: Don't prin...
Rust
0
""" Audio package for Voice AI Assistant Provides audio I/O, notifications, and utilities """ from .handler import AudioHandler from .notifications import ( NotificationPlayer, NotificationManager, NotificationType ) from .utils import ( AudioConverter, AudioProcessor, calculate_audio_duration,...
Python
1
ys)] fn next_u32(&mut self) -> u32 { unsafe { (*self.rng.get()).next_u32() } } #[inline(always)] fn next_u64(&mut self) -> u64 { unsafe { (*self.rng.get()).next_u64() } } fn fill_bytes(&mut self, bytes: &mut [u8]) { unsafe { (*self.rng.get()).fill_bytes(bytes) } } ...
Rust
0
SharedLibrary { size: size, addr: info.dlpi_addr as usize as *const _, name: CStr::from_ptr(info.dlpi_name), headers: slice::from_raw_parts(info.dlpi_phdr, info.dlpi_phnum as usize), } } unsafe extern "C" fn callback<F, C>(info: *mut libc::dl_phdr_info, ...
Rust
0
from sympy import (var, exp, pprint, Eq, Symbol, Function, cos, pi, simplify, ccode, latex) var("x y") d_u = Symbol("D_u") d_v = Symbol("D_v") sigma = Symbol("SIGMA") lam = Symbol("LAMBDA") kappa = Symbol("KAPPA") k = Symbol("K") def eq1(u, v, f): return -d_u*d_u*(u.diff(x, 2) + u.diff(y, 2)) - f(u) + sig...
Python
1
iteration. """ if opt['path']['resume_state']: # get all the networks networks = [key for key in opt.keys() if key.startswith('network_')] flag_pretrain = False for network in networks: if opt['path'].get(f'pretrain_{network}') is not None: flag_pretra...
Python
1
lcd.set_orientation(Orientation::Landscape); let style = PrimitiveStyleBuilder::new() .fill_color(Rgb565::BLACK) .build(); let backdrop = Rectangle::new(Point::new(0, 0), Point::new(160, 81)).into_styled(style); let _ = backdrop.draw(lcd); let _ = egtext!( ...
Rust
0
)) lagged_dist = ( RhinoLaggedAdjacencyDistribution(logits_edge=logits_exist[..., :-1, :, :], lags=context_length - 1) if context_length > 1 else None ) inst_dist = ENCOAdjacencyDistribution(logits_exist=logits_exist[..., -1, :, :], logits_orient=logits_orient) constrained_dist =...
Python
1
"""Expand shorthand conference and journal names to their full version. E.g. "CGO" -> "International Symposium on Code Generation and Optimization". This uses a manually curated set of expansion rules. """ import sys import bibtexparser from labm8.py import app from labm8.py import bazelutil from labm8.py import js...
Python
1
ps://docs.rs/crate/hex/0.1.0/source/src/lib.rs fn to_hex_string(data: &[u8]) -> String { static CHARS: &'static [u8] = b"0123456789abcdef"; let bytes = data.as_ref(); let mut v = Vec::with_capacity(bytes.len() * 2); for &byte in bytes.iter() { v.push(CHARS[(byte >> 4) as usize]); v.push...
Rust
0
bits & !(0x01 << 21)) | (((value as u32) & 0x01) << 21); self.w } } #[doc = "Reader of field `SCLK_SEL`"] pub type SCLK_SEL_R = crate::R<bool, bool>; #[doc = "Write proxy for field `SCLK_SEL`"] pub struct SCLK_SEL_W<'a> { w: &'a mut W, } impl<'a> SCLK_SEL_W<'a> { #[doc = r"Sets the field bit"] #...
Rust
0
CH2DATCLR, #[doc = "0xb8 - DCH2DATSET register"] pub dch2datset: DCH2DATSET, #[doc = "0xbc - DCH2DATINV register"] pub dch2datinv: DCH2DATINV, } #[doc = "DCH2CON register"] pub struct DCH2CON { register: ::vcell::VolatileCell<u32>, } #[doc = "DCH2CON register"] pub mod dch2con; #[doc = "DCH2CONCLR r...
Rust
0
x0d, 0x69, 0x81, 0xe9, 0x7e, 0x7a, 0xec, 0x1d, 0x43, 0x60, 0xc2, 0x0a, 0x27, 0xaf, 0xcc, 0xfd, 0x9f, 0xae, 0x0b, 0xf9, 0x1b, 0x65, 0xc5, 0x52, 0x47, 0x33, 0xab, 0x8f, 0x59, 0x3d, 0xab, 0xcd, 0x62, 0xb3, 0x57, 0x16, 0x39, 0xd6, 0x24, 0xe6, 0x51, 0x52, 0xab, ...
Rust
0
from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from .models import StudyMaterial from .forms import StudyMaterialForm @login_required def study_materials_view(request): class_name = request.GET.get('class_name', '') entrance_exam = request.GET.get('entra...
Python
1
#User function Template for python3 class Solution: # Function to get the maximum total value in the knapsack. def fractionalknapsack(self, p, w, c): #code here n=len(p) if n==0 or c==0: return -1 pv=0.0 pw=[(p[i]/w[i],i) for i in range(n)] pw.sort(rev...
Python
1
from __future__ import annotations import datetime as dt import sqlite3 from typing import List, Optional from telethon import events from config import Config from db import persist_message, is_already_scored from scoring import extract_text, score_text, detect_lang_safe, matched_to_json from translate import trans...
Python
1
superior or equal to the short term /// novelty size. #[structopt(long, default_value = "200")] pub novelty_size: usize, /// Short term novelty size. /// Only this many samples will be used to compute the data to send. /// Decreasing it may increase the overall sensitivity of the system. #...
Rust
0
# Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany # # 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://w...
Python
1
turned empty page', expected=True) for podcast in podcast_page: yield { '_type': 'url_transparent', 'url': podcast['podcast_sharing_url'], 'ie_key': TokFMPodcastIE.ie_key(), 'title': podcast.get('podcast_name'), 'episod...
Python
1
#!/usr/bin/env python3 from pwn import * def write_byte(io, where, what): io.sendline(f'{where} {chr(what)}') if args.LOCAL: io = process(['./www']) gdb.attach(io, gdbscript=''' set pagination off b *0x4006d7 commands p/x $rdx p/x $al c end b *0x400811 commands x/s $rdi c end b *0x400835 c '''...
Python
1
if let Some(var_111) = &input.single_instance_type { scope_110.boolean(*var_111); } #[allow(unused_mut)] let mut scope_112 = writer.prefix("SingleAvailabilityZone"); if let Some(var_113) = &input.single_availability_zone { scope_112.boolean(*var_113); } #[allow(unused_mut)] l...
Rust
0
symmetry_workspaces_for([f"{self.run_number}", f"{self.run_number}"], ["fwd", "bwd"]) pair_names = self.model.calculate_pairs_for([f"{self.run_number}"], ["bwd"]) self.assertEqual(pair_names, ["long"]) self._assert_workspaces_exist(["EMU19489; Pair Asym; long; MA"]) def test_that_calculat...
Python
1
ants::STRUCT_LIST_CONST; let struct_list = struct_list_const.get().unwrap(); assert_eq!(struct_list.len(), 3); assert_eq!(struct_list.get(0).get_text_field().unwrap(), "structlist 1"); assert_eq!(struct_list.get(1).get_text_field().unwrap(), "structlist 2"); assert_eq!(struct_lis...
Rust
0
import copy import torch import numpy as np from numpy.ma.core import zeros_like from utils.model import init_model class Server(object): """Server side operations.""" def __init__(self, cfg, alg): self.cfg = cfg self.model = init_model(cfg) # model z_k # 初始化服务器模型 z_k self.state = s...
Python
1
ef<[u8]> for SecretKey { fn as_ref(&self) -> &[u8] { match self { SecretKey::Buffer(a) => a.as_slice(), SecretKey::Aes128(a) => a.as_ref(), SecretKey::Aes256(a) => a.as_ref(), SecretKey::Curve25519(a) => a.as_ref(), SecretKey::P256(a) => a.as_ref()...
Rust
0
#!/usr/bin/env python3 # BSD 3-Clause License # # Copyright (c) 2024, Arm Limited # 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 copyr...
Python
1
-cap the logits TODO remove if always done. # if self.config.logits_soft_cap is not None: cap = self.config.logits_soft_cap logits = nn.functional.tanh(logits / cap) * cap logits = logits.float() loss = None if labels is not None: # Shift so that tokens < n p...
Python
1
h): #match = re.search(self.regex, filepath) basename = os.path.basename(filepath) match = re.search(self.regex, basename) if match: log.debug("regex matched file '%s'", filepath) if match.groups(): capture = match.group(1) else: ...
Python
1
import time, json, requests # 腾讯疫情实时数据数据 URL url = 'https://view.inews.qq.com/g2/getOnsInfo?name=disease_h5&callback=&_=%d'%int(time.time()*1000) # 加载 JSON 数据并解析 data = json.loads(requests.get(url=url).json()['data']) # 打印数据输出数据 print(data) print(data.keys()) # 统计省份信息(34个省份 湖北 广东 河南 浙江 湖南 安徽....) num_area = data['are...
Python
1
CMD_HELP_CODEBASE_INIT = "Initialize a Safety Codebase (like git init for security). Sets up a new codebase or connects your local project to an existing one on Safety Platform." CMD_HELP_CODEBASE = ( "[BETA] Manage your Safety Codebase integration.\nExample: safety codebase init" ) CMD_CODEBASE_GROUP_NAME = "code...
Python
1
r_day, oss_thr_size, oss_thr_price, domain_url, ptype, remark*/ dbname, notices, memo from platform_conf where id=1 """ self.__d = self...
Python
1
ext_feat, how='left', on='instance_id') del timediff_last_next_feat gc.collect() print('--------------401_list_till_feat,all,7----------------------') list_till_feat = pd.read_csv(path+"401_list_till_feat_all.csv") print('401_list_till_feat:\n', list_till_feat.shape) data = data.merge(list_till...
Python
1
Ok(()) } fn write_buf(&mut self, buf: &[u8]) -> Result<()> { self.w.write_all(buf)?; Ok(()) } fn line_break(&mut self) -> Result<()> { Ok(()) } fn line(&mut self, id: usize, label: &str, buf: &[u8]) -> Result<()> { if !self.line_started { wr...
Rust
0
self._doc.Catalog.ViewerPreferences[pref] def setCatalogEntry(self,key,value): from reportlab.pdfbase.pdfdoc import PDFDictionary, PDFArray, PDFString if isStr(value): value = PDFString(value) elif isinstance(value,(list,tuple)): value = PDFArray(value) elif ...
Python
1
::new(Registers::empty()); core.reg.y_idx = 1; dey(&mut core, &mut BlockMemory::with_size(0)); assert_eq!(core.reg.y_idx, 0); assert!(core.reg.status.contains(StatusFlags::Z_FLAG)); } #[test] fn dey_impl_negative_flag() { let mut core = Core::new(Registers::empty()); core.reg.y_idx = 129;...
Rust
0
s a Bs8State<T>, where T is the type that stores each set of bits. The first implementation stores these bits in a u32 which permits up to 8 * 32 = 1024 bits of data to be processed at once. This implementation only processes a single block at a time, so, in reality, only 512 bits are processed at once and the remainin...
Rust
0
'''(П.Е. Финкель) Текстовый файл 24-1.txt состоит не более чем из 106 символов - заглавных латинских букв и цифр. Определите максимальное число, состоящее только из чётных цифр. Под числом подразумевается последовательность цифр, ограниченная другими символами (не цифрами).''' s = open('веб2/12.txt').readline() f...
Python
1
# This file is auto-generated. Do not edit. from _character_base import CharacterBase from enums.rarity import Rarity from enums.path import Path from enums.damage_type import DamageType class Rappa(CharacterBase): id: str = '1317' name: str = 'Rappa' rarity: Rarity = Rarity.FIVE_STAR path: Path = Pa...
Python
1
assert_eq!(iter.peek(), None); assert_eq!(iter.next(), None); let iter = iter.remaining(); assert_eq!(iter.next(), Some(6)); assert_eq!(iter.peek(), Some(&7)); assert_eq!(iter.next(), Some(7)); assert_eq!(iter.next(), Some(8)); assert_eq!(iter.next(), Some(9)); ...
Rust
0
4.5", "3.55"], "^(4\\.5|3\\.5{2})$"), case(vec!["4.5", "4.55"], "^4\\.5{1,2}$"), case(vec!["4.5", "4.55", "3.5"], "^(3\\.5|4\\.5{1,2})$"), case(vec!["4.5", "44.5", "44.55", "4.55"], "^4{1,2}\\.5{1,2}$"), case(vec!["I ♥♥ cake"], "^I ♥{2} cake$"), case(vec!["I ♥ cake", "I ♥♥ cake"], "^I ♥{1,2} cake$")...
Rust
0
CreateInstance( ppIWriter: *mut *mut IWICMetadataWriter, ) -> HRESULT, }} RIDL! {#[uuid(0x412d0c3a, 0x9650, 0x44fa, 0xaf, 0x5b, 0xdd, 0x2a, 0x06, 0xc8, 0xe8, 0xfb)] interface IWICComponentFactory(IWICComponentFactoryVtbl): IWICImagingFactory(IWICImagingFactoryVtbl) { fn CreateMetadataReader( ...
Rust
0
# Copyright 2020 The SQLFlow Authors. 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 required by applicable law o...
Python
1
None => panic!("fail to load {} article", KEYWORD), Some(target) => { let categories = extract_categories(target); assert_eq!(expected_lines.len(), categories.len()); for actual in categories { assert!(expected_lines.contains(&...
Rust
0
a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 17)) | ((value as u32 & 0x01) << 17); self.w } } #[doc = "Field `cr_ep2_stall` reader - "] pub struct CR_...
Rust
0
` pub fn clear(&mut self) { self.rx.clear(); self.tx.clear(); } /// return a reference to the bytes in the rx buffer /// useful for zero-copy response handling pub fn rx_buffer(&self) -> &[u8] { self.rx.borrow() } /// return a mutable reference to the tx buffer ...
Rust
0
error_trace = traceback.format_exc() logger.error(f"{error_msg}\n{error_trace}") job.status = 'failed' job.error_message = f"{error_msg}\n{error_trace}" job.completed_at = timezone.now() job.save() destination.update_scraping_status('...
Python
1
s_file)) metrics_csv = pd.read_csv(metrics_file) expected_rows = total_rounds + 2 if has_test else total_rounds + 1 self.assertLen( metrics_csv.index, expected_rows, msg='The output metrics CSV should have {} rows.'.format(expected_rows)) possible_prefixes = [ metric_u...
Python
1
SK # Bit 1 - Cloud_Mask.all : summary Logical or of All cloud and shadow masks # Bit 2 - Cloud_Mask.all clouds: Logical or of All cloud masks # Bit 3 - Cloud_Mask.shadows : shadows mask from clouds within image # ...
Python
1
сообщение с отзывами if reviews: bot.send_message(message.chat.id, text=result) pie_chart = create_bar_chart(positive_reviews_count, neutral_reviews_count, negative_reviews_count) bot.send_photo(message.chat.id, photo=pie_chart) else: bot.send_message(me...
Python
1
icleDriveTankRawInputData_getGearUp(self_: *const PxVehicleDriveTankRawInputData, ) -> bool; pub fn PxVehicleDriveTankRawInputData_getGearDown(self_: *const PxVehicleDriveTankRawInputData, ) -> bool; pub fn phys_PxVehicleDriveTankSmoothDigitalRawInputsAndSetAnalogInputs(keySmoothing: *const PxVehicleKeySmoothingData, r...
Rust
0