text string | label_name string | labels int64 |
|---|---|---|
>
where
C: Display,
{
#[cfg(backtrace)]
fn backtrace(&self) -> Option<&Backtrace> {
Some(self.error.backtrace())
}
fn source(&self) -> Option<&(dyn StdError + 'static)> {
Some(&*self.error)
}
}
use libstripe::resources::common::currency::Currency;
use libstripe::resources::core:... | Rust | 0 |
## Copyright (C) 2021 Philipp Benner
##
## This program 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 option) any later version.
##
## This program is distri... | Python | 1 |
, **update_data)
if not success:
self.view.display_error("更新用户失败")
else:
self.view.display_message("没有进行任何更新")
except ValueError as e:
self.view.display_error(f"输入错误: {str(e)}")
def delete_user(self):
"... | Python | 1 |
'平時不管做什麽事都磨磨蹭蹭的,是大家公認的慢性子。而小狐狸可是個妥妥的急性子,做事雷厲風行,'
# '卻常常是火急火燎的,總會因為太著急而出錯。就這樣兩個根本不在一條路上的人,居然在一起了。')
# import zhconv
# text = zhconv.convert(text, 'zh-cn')
text = "안녕하세요! 오늘은 충전이 필요 없는 스마트 쓰레기통 UOCAN을 소개해드리겠습니다. 레드닷 디자인 어워드를 수상한 이 쓰레기통은 예술 작품처럼 세련된 디자인을 자랑합니다. UOCAN은 쓰레기 봉투를 자동으로 늘리고, 묶고,... | Python | 1 |
OError::CommandErr(Some(e))))
})
.collect()
}
use crate::models::LeaderKind;
use serde::{de, Deserialize, Deserializer};
use std::fmt;
impl<'de> Deserialize<'de> for LeaderKind {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
struc... | Rust | 0 |
= Box::into_raw(Box::new(0)) as *const *const PSTR;
let default_environment_variables_count = 0;
let raw_fn: Symbol<GetDistributionConfigurationFn> =
unsafe { self.wslapi.get(b"WslGetDistributionConfiguration\0")? };
let hresult = unsafe {
raw_fn(
distro_n... | Rust | 0 |
'foo':3, 'bla':2}}
# d = DotCollapsedDict(dic, reference={'bar.foo':None, 'bar':{'bla':None}})
# assert d == {'bar.foo':3, 'bar':{'bla':2}}, d
dic = {'_id': u'user', 'a':3, 'e':5, "g":2, 'f':6}
d = DotCollapsedDict(dic, reference=dic)
assert d == {'_id': u'user', 'a':3, 'e':5, "g... | Python | 1 |
4() {
run_test(&Instruction { mnemonic: Mnemonic::VPMOVZXBW, operand1: Some(Direct(XMM7)), operand2: Some(IndirectDisplaced(RBX, 1488005651, Some(OperandSize::Qword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[196, 226, 12... | Rust | 0 |
slice, meaning the conversion may be more
/// efficient than converting individual elements on some hardware that supports SIMD
/// conversions. See [crate documentation](../index.html) for more information on hardware
/// conversion support.
///
/// # Examples
/// ```rust
/// # use half::p... | Rust | 0 |
ld = 0.6
labels = ["person"]
anchors = [10, 13, 16, 30, 33, 23, 30, 61, 62, 45, 59, 119, 116, 90, 156, 198, 373, 326]
# 初始化PipeLine
pl=PipeLine(rgb888p_size=rgb888p_size,display_mode=display_mode)
pl.create()
display_size=pl.get_display_size()
# 初始化自定义人体检测实例
person_det=PersonDetectionAp... | Python | 1 |
}
};
}
#[doc(hidden)]
#[macro_export]
macro_rules! impl_uri_buf_traits {
( $C:ty , $B:ty) => {
_impl_uri_buf_traits_base!($C, $B);
impl AsRef<std::string::String> for $C {
fn as_ref(&self) -> &std::string::String {
AsRef::<std::string::String>::as_ref(&self... | Rust | 0 |
from flask import Flask, request, jsonify
import langid
from googletrans import Translator
app = Flask(__name__)
translator = Translator()
@app.route('/detect_language', methods=['POST'])
def detect_language():
data = request.get_json()
text = data.get('text')
if not text:
return jsonify({'error... | Python | 1 |
from numpy.testing import assert_
import numpy.distutils.fcompiler
customizable_flags = [
('f77', 'F77FLAGS'),
('f90', 'F90FLAGS'),
('free', 'FREEFLAGS'),
('arch', 'FARCH'),
('debug', 'FDEBUG'),
('flags', 'FFLAGS'),
('linker_so', 'LDFLAGS'),
]
def test_fcompiler_flags(monkeypatch):
mo... | Python | 1 |
F462F495487387F685B7472FC"
"6C29E293F0A0"),
b"hello",
hb("9290F727ED06C38BA4549EF7DE25CF5642659211B7FC076F2D28FEFD71"
"784BB8D8F6FB244A8CC5C06240631B97008565A120764C0EE9C2CB0073"
"994D79080136"),
10000, 64, "hmac-sha512"
... | Python | 1 |
"""
Test package for CrypticsLabBot Python Pipeline.
"""
| Python | 1 |
set of `data`, in bytes, from the start of the containing object.
pub index: c_int,
}
impl Default for xcb_randr_screen_size_iterator_t {
fn default() -> Self {
unsafe { std::mem::MaybeUninit::zeroed().assume_init() }
}
}
/// The `RandR::RefreshRates` struct.
///
/// The following fields can be ac... | Rust | 0 |
"""test of pure diffusion
Robert A McDougal
March 2013 - June 2014
"""
from neuron import h, crxd as rxd
import numpy
import __main__
name = __main__.__file__
if name[-3:] == ".py":
name = name[:-3]
h.load_file("stdrun.hoc")
h.cvode_active(True)
dend = h.Section()
dend.diam = 2
dend.nseg = 101
dend.L = 100
rxd.... | Python | 1 |
dex = random.choice(
range(len(self.fact_phrases)))
fact_text = self.fact_phrases[fact_phrase_index].replace(
"<fact>", fact)
if last_user_utterance_has_wh_word:
fact_text = random.choice(
... | Python | 1 |
t, checkpoint_path)
print(f"Checkpoint saved at epoch {epoch}, step {step}.")
def load_checkpoint(checkpoint_path, model, optimizer, lr_scheduler, accelerator):
""" A function from chatGPT to help load checkpoints training restarts """
checkpoint = torch.load(checkpoint_path, map_location=accelera... | Python | 1 |
e => {
sys::libpostal_duplicate_status_t::LIBPOSTAL_EXACT_DUPLICATE
}
}
}
}
impl ToRust for sys::libpostal_duplicate_status_t {
type Out = DuplicateStatus;
fn to_rust(&self) -> Self::Out {
match *self {
sys::libpostal_duplicate_status_t::LIBPOSTAL_NU... | Rust | 0 |
as u8) + column_index;
let pattern_state = GLIDER_PATTERN[(row_index as usize, column_index as usize)];
match pattern_state {
CELL_IS_POPULATED => universe.populate_cell(target_row_index, target_column_index),
CELL_IS_FREE => universe.free_cell(target_row_index,... | Rust | 0 |
thislist = ["apple", "banana", "cherry"]
print(thislist)
# --------------------------------------------------------------------------------------------------------------------------------
# List allows duplicate values
thislist = ["apple", "banana", "cherry", "apple", "cherry"]
print(thislist)
# --------------------... | Python | 1 |
for each flag
//
// // Flags set on issuer accounts
// // TrustLines are created with authorized set to "false" requiring
// // the issuer to set it for each TrustLine
// AUTH_REQUIRED_FLAG = 0x1,
// // If set, the authorized flag in TrustLines can be cleared
// // otherwise, ... | Rust | 0 |
"""聊天插件API模块
该模块提供了聊天插件的公共API接口,包括菜单管理、管理员操作、聊天功能等核心功能的封装。
"""
from __future__ import annotations
from nonebot import logger
from .chatmanager import chat_manager
from .config import Config, ConfigManager, config_manager
from .on_event import on_before_chat, on_before_poke, on_chat, on_event, on_poke
from .utils.ad... | Python | 1 |
esMut::with_capacity($bit_size / 8);
// Match bit size with encoding
match $bit_size {
8 => buf.put_u8(*self as u8),
16 => buf.put_u16_be(*self as u16),
32 => buf.put_u32_be(*self as u32),
64 => buf.put_u64_... | Rust | 0 |
"""
# ----------------------------------------------------------------------------------------------------------------------
# Problem 13: Roman to Integer
# https://leetcode.com/problems/roman-to-integer/
# ----------------------------------------------------------------------------------------------------------------... | Python | 1 |
r = Arc::new(Mutex::new(server));
let (get_tx, get_rx) = mpsc::channel(64);
let (put_tx, put_rx) = mpsc::channel(64);
let shared_server = server.clone();
tokio::spawn(async move { message_loop(shared_server, app_rx, put_tx, get_tx).await });
if args.console {
input_loop(server, put_rx, get_rx).await.unwr... | Rust | 0 |
ᓳ', '𓅼',
'♶', 'Ὡ', '𓏽', '𒊏', '𓏖', '𖧙', '𝚺', 'מּ', 'ࢩ', '\u{1dc1}', '𑌙',
'𞺙', '𝆖', '㏼', '𘱎', '㍠', 'o', '𝗽', 'ﭯ', '𑤨', '𝟀', '懲', 'w',
'ᶠ', '𐜀', 'ᴣ', '𐴍', '𐬵', '꩜', 'ﭟ', '𒀠', '𖩯', '𑂷', '\u{1193b}',
'𑜔', '\u{1de4}', '𔔇', '𒌗', '𝈀', '𔑝', '𑊥', '𜾑', 'ﵔ', '🄽', '𛀚',
'𖠪', '᪠', '𑌌'... | Rust | 0 |
/// ### Errors
/// - `io` errors
pub fn from_handle<T: Read>(mut handle: T) -> InternalResult<Header> {
#![allow(clippy::uninit_assumed_init)]
let mut buffer: [u8; Header::BASE_SIZE] = [0u8; Header::BASE_SIZE];
handle.read_exact(&mut buffer)?;
// Construct header
Ok(Header {
// Read magic, [u8;5]
m... | Rust | 0 |
: u32,
pub cConnections: u32,
pub cControls: u32,
pub szShortName: [u16; 16],
pub szName: [u16; 64],
pub Target: MIXERLINEW_0,
}
impl ::core::marker::Copy for MIXERLINEW {}
impl ::core::clone::Clone for MIXERLINEW {
fn clone(&self) -> Self {
*self
}
}
#[repr(C, packed(1))]
#[doc = "*... | Rust | 0 |
_bench(naive_distance),
"distance" => distance_bench(hamming::distance),
}
}
criterion_group!(benches, weight, distance);
criterion_main!(benches);
//! Metadata for PNG images.
//!
//! This code is derived from code in the `immeta` library: https://github.com/netvl/immeta
use crate::PngError;
use byteorde... | Rust | 0 |
let mut iter = $string.split($sep);
($(iter.next().and_then(|word| word.parse::<$x>().ok()),)*)
}}
}
use crate::authentication_manager::ServiceAccount;
use crate::error::Error;
use crate::error::Error::{
GCloudError, GCloudNotFound, GCloudParseError, NoProjectId, ParsingError,
};
use crate::Toke... | Rust | 0 |
}
buffer.push_str(&self.summary());
buffer.push_str("\n");
for detail in &self.details {
buffer.push_str(&detail.to_string(depth + 1))
}
buffer
}
}
impl Clone for Explanation {
fn clone(&self) -> Self {
let mut details: Vec<Explanation> = vec![];... | Rust | 0 |
_DYNAMIC_MARKINGS = "KB_DYNAMIC_MARKINGS"
KB_INJECTIONS = "KB_INJECTIONS"
KB_ERROR_CHUNK_LENGTH = "KB_ERROR_CHUNK_LENGTH"
KB_XP_CMDSHELL_AVAILABLE = "KB_XP_CMDSHELL_AVAILABLE"
OS = "OS"
class REDIRECTION(object):
YES = 'Y'
NO = 'N'
class PAYLOAD(object):
SQLINJECTION = {
1: "基于布尔盲注... | Python | 1 |
import ast
from expr_codegen.codes import source_replace, RenameTransformer
source = """
OPEN>=CLOSE?1:0
OPEN>CLOSE?A==B?3:DE>FG?5:6:0
A=OPEN==CLOSE
B,C=(OPEN < CLOSE) * -1,1
ts_sum(min(((delta(vol,8)-(high*vol))+7.1),max(((open>=low?amt:low)/4.2),ts_sum((open<low?open:amt),8))),9)
max(((vwap-8.6)^ts_mean(close,7)),... | Python | 1 |
// and finish with None
let wind_a = byte_windows(&bytes, this.chain_len).map(Option::Some).chain(iter::once(None));
// Then we create another iterator which will start with None, then
// go through the values
let wind_b = iter::once(None).chain(by... | Rust | 0 |
d = offload_proportion[i]
def _get_obs(self):
if self.observation_callback is None:
return np.zeros(0)
return self.observation_callback(self.world)
# def _get_obs_small(self):
# if self.observation_callback_small is None:
# return np.zeros(0)
# return s... | Python | 1 |
batch_saved_observations[env_index]
env_saved_observations.append({primary_obs_name: env_rgb})
if num_observations_to_save:
print("saving videos...", flush=True)
video_folder = "../videos"
for env_index in range(num_envs):
env_saved_observations = batch_saved_o... | Python | 1 |
:error!("Failed to serialize compiler input: {}", err)
}
}
}
fn write_output(&self, output: &CompilerOutput) {
tracing::trace!("logging compiler output to {}", self.dest_output.display());
match serde_json::to_string_pretty(output) {
Ok(json) => {
... | Rust | 0 |
_AT_BUILD_TIME > 0 {
layer.par_iter_mut().enumerate().for_each(|(i, node)| {
if node.len() > config.num_neighbors {
Self::add_and_limit_neighbors(elements, node, i, &[], config.num_neighbors);
}
});
}
}
fn index_element(
... | Rust | 0 |
.3, 0.4);
assert_eq!(c * 2.0, Color::new(0.4, 0.6, 0.8));
}
#[test]
fn multiplying_colors()
{
let c1 = Color::new(1.0, 0.2, 0.4);
let c2 = Color::new(0.9, 1.0, 0.1);
assert_eq!(c1 * c2, Color::new(0.9, 0.2, 0.04));
}
}
<filename>src/my_benchmark.rs
use criterion::{... | Rust | 0 |
32,
pub(crate) change_tick: u32,
}
impl<'a, T> Deref for Mut<'a, T> {
type Target = T;
#[inline]
fn deref(&self) -> &T {
self.value
}
}
impl<'a, T> DerefMut for Mut<'a, T> {
#[inline]
fn deref_mut(&mut self) -> &mut T {
self.component_ticks.set_changed(self.change_tick);
... | Rust | 0 |
model = load_state_dict_helper(MegatronGPTModel, nemo_config, trainer, checkpoint['state_dict'])
model._save_restore_connector = NLPSaveRestoreConnector()
# cast to target precision and disable cpu init
dtype = torch_dtype_from_precision(precision)
model = model.to(dtype=dtype)
model.cfg.use_c... | Python | 1 |
reader: R,
}
impl<R> InstructionIterator<R> {
fn new(reader: R) -> InstructionIterator<R> where R: Read{
InstructionIterator {
reader: reader,
}
}
}
pub fn from_file<P: AsRef<Path>>(file: P) -> io::Result<InstructionIterator<File>> {
let file = File::open(file).unwrap();
Ok(InstructionIterator::new(file))
}
... | Rust | 0 |
tree(bt.root, target_directory="", name="expanded_bt_obt", png_only=False)
# else:
# render_dot_tree(bt.root, target_directory="", name="expanded_bt_xiaocai", png_only=False)
else:
print("error")
# 开始从初始状态运行行为树,测试
state = start
steps = 0
c... | Python | 1 |
for base in inferred_bases:
if base is self:
continue
mro = base._compute_mro(context=context)
bases_mro.append(mro)
unmerged_mro: list[list[ClassDef]] = [[self], *bases_mro, inferred_bases]
unmerged_mro = clean_duplicates_mro(unmerged_mro, s... | Python | 1 |
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 22 09:29:41 2012
@author: ash
A demonstration of non-uniform dynamics on an infinite chain.
HOW TO USE:
1. Run the heisenberg_af_uniform script separately to obtain a uniform
ground state (setting D as desired).
Make sure `load_saved_ground` is set to ... | Python | 1 |
) {
sse_read_f32_xmm_xmm(ctx, "instr_F30F52", r1, r2);
}
pub fn instr_0F53_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) {
sse_read128_xmm_mem(ctx, "instr_0F53", modrm_byte, r);
}
pub fn instr_0F53_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) {
sse_read128_xmm_xmm(ctx, "instr_0F53", r1, r... | Rust | 0 |
inv(K1)
K2_inv = np.linalg.inv(K2)
E = K2.T @(F @ K1)
# print(np.linalg.svd(E)[1])
kp1 = np.column_stack([kp1, np.ones(len(kp1))])
kp2 = np.column_stack([kp2, np.ones(len(kp1))])
kp1_unproj = (K1_inv @ kp1.T).T
kp1_unproj = kp1_unproj[:, :2] / kp1_unproj[:, 2,... | Python | 1 |
current version of `CityHash` is intended for little-endian 64-bit CPUs.
//!
//! All functions that don't use the CRC32 instruction should work in
//! little-endian 32-bit or 64-bit code. `CityHash` should work on big-endian CPUs
//! as well, but we haven't tested that very thoroughly yet.
//!
//! 2) `CityHash` is fa... | Rust | 0 |
# [MXDL-15-03] 6.Hopfield(mnist).py
import numpy as np
import matplotlib.pyplot as plt
import pickle
# Load MNIST data set
with open('data/mnist.pkl', 'rb') as f:
x, y = pickle.load(f) # x: (70000, 784), y: (70000, 1)
x = x[:100].T # (784, 100)
x = np.where(x > 0, 1, -1)
m, n = x.shape
# Compute the ... | Python | 1 |
int;
pub fn sleep(secs: uint) -> uint;
pub fn symlink(path1: *const cchar, path2: *const cchar) -> int;
pub fn sysconf(name: int) -> long;
pub fn tcgetpgrp(fd: int) -> pid_t;
pub fn tcsetpgrp(fd: int, pgrp: pid_t) -> int;
pub fn ttyname(fd: int) -> *mut cchar;
pub fn unlink(c: *const cchar)... | Rust | 0 |
# Copyright (c) 2025, Marco Noce <nce.marco@gmail.com>
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
# SPDX-License-Identifier: GPL-3.0-or-later
from __future__ import annotations
from ansible_collections.community.general.plugins.module_utils.cmd_... | Python | 1 |
import torch
import logging
import torchvision.transforms.v2 as transforms
from pathlib import Path
from trainer import Trainer
from network.unet import Unet
from torch.optim import AdamW
from diffusion_schedules.schedule_curves import SchedulerCurve
from diffusion_schedules.scheduler import Schedules
from torchvision... | Python | 1 |
"""
Text utility functions for the monetary expressions to numeric amount converter.
"""
import re
import inflect
def normalize_text(text):
"""
Normalize text by converting to lowercase and standardizing whitespace.
Args:
text (str): Input text
Returns:
str: Normalized text
"""... | Python | 1 |
canadien', 'fur': 'inglês canadês', 'fy': 'Kanadeesk Ingelsk', 'ga': 'Béarla Cheanada', 'gd': 'Beurla Chanada', 'gl': 'inglés canadense', 'gsw': 'Kanadischs Änglisch', 'gu': 'કેનેડિયન અંગ્રેજી', 'ha': 'Turanci Kanada', 'haw': 'Pelekāne Kanakā', 'hi': 'कनाडाई अंग्रेज़ी', 'hi-Latn': 'Canadian English', 'hr': 'kanadski e... | Python | 1 |
class Solution:
def minimizeStringValue(self, s: str) -> str:
d = {chr(key): -1 for key in range(97, 123)}
for i in s:
if i.isalpha():
d[i] += 1
min_heap = [[value, key] for key, value in d.items()]
heapq.heapify(min_heap)
# print(min_heap)
... | Python | 1 |
import os
import trimesh
import numpy as np
from .utils.libmesh import check_mesh_contains
def get_occ_gt(in_path=None, vertices=None, faces=None, pts_num=1000, points_sigma=0.01, with_dp=False, points=None, extra_points=None):
if in_path is not None:
mesh = trimesh.load(in_path, process=False)
pri... | Python | 1 |
# Copyright (c) 2020, NVIDIA CORPORATION.
#
# 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... | Python | 1 |
import torch
import torch.nn as nn
import numpy as np
class Mseloss(nn.Module):
def __init__(self):
super(Mseloss, self).__init__()
self.mseloss = nn.MSELoss(reduction='sum')
def forward(self, logits, logits_len, label, label_len):
logits_len = logits_len.numpy()
label = labe... | Python | 1 |
size = len(self.fragresults[0][0])
self.fragcharges = numpy.zeros([size], "d")
alpha = numpy.zeros([size], "d")
if unrestricted:
beta = numpy.zeros([size], "d")
for spin in range(len(self.fragresults)):
for i in range(self.data.homos[spin] + 1):
... | Python | 1 |
import numpy as np
import datetime
from matplotlib import pyplot as plt
from betellib import tweet, build_string, get_mags_from_AAVSO
from astropy.stats import biweight_location
def make_plot(days_ago, dates, mag):
print('Making plot...')
time_span = np.max(dates) - np.min(dates)
min_plot = 0
max_plot... | Python | 1 |
"""Este é um módulo de exemplo
Este módulo contém funções e exemplos de documentação de funções.
A função soma você já conhece bastante.
"""
variavel_1 = 1
# def soma(x: int | float, y: int | float) -> int | float:
def soma(x, y, show_count = 0):
"""
Soma x e y
:param x: Número 1
:type x: int or flo... | Python | 1 |
d not combine, since does contain a tests which could potentially
// change the state of the flag
node!(PGMCondition, FlowCondition::IfFlag(vec!["my_flag".to_string()]) =>
node!(PGMTest, 2, FlowID::from_int(2)),
),
node!(PGMCondition, FlowCondition::Unless... | Rust | 0 |
_diag = b.get_unchecked([i, i + 1]).abs();
diag_abs_sum = eps * (b_ii.abs() + b.get_unchecked([i + 1, i + 1]).abs());
}
if b_sup_diag <= diag_abs_sum {
// Adjust q or p to define boundaries of sup-diagonal box
if on_lower {
... | Rust | 0 |
????????????????????????????????\n\
?????????????????????????????????????????????\n\
?????????????????????????????????????????????\n\
?????????????????????????????????????????????\n\
?????????????????????????????????????????????\n\
???????????????????????... | Rust | 0 |
tal Unique Roles in XML:** {len(xml_roles)}")
st.write(f"**Total Unique Roles found in PDF:** {len(pdf_roles)}")
st.markdown("\n--- **Roles Matched (XML to PDF)** ---")
if matched_roles:
for role in matched_roles:
st.write(f"- {role}")
else:
st.in... | Python | 1 |
") _, out("x22") _,
out("x23") _, out("x24") _, out("x25") _, out("x26") _,
out("v0") _, out("v1") _, out("v2") _,
out("v4") _, out("v5") _,
out("v16") _, out("v17") _, out("v18") _, out("v19") _,
out("v20") _, out("v21"... | Rust | 0 |
'''
Created on 2016/03/06
@author: takuya-hv2
'''
from pybrainSG.rl.experiments.episodicSG import EpisodicExperimentSG
from pybrainSG.rl.agents.multiAgent import MultiAgent
from pybrainSG.rl.leaners.valuebased.ceq import *
from pybrainSG.rl.agents.nfceqa import *
from pybrainSG.rl.examples.tasks.gridgames import GridG... | Python | 1 |
e = unsend_image["_id"]
os.remove(path=SAVE_IMAGE_PATH+image_name)
#Delete face data on database and face file if created from original image
if col_faces.find_one(filter={"image_link":image_name}) is not None:
unsend_face = col_faces.find_one_and_delete(filter={"ima... | Python | 1 |
ITERATIONS;
let start_hpet = get_hpet().as_ref().unwrap().get_counter();
for _ in 0..iterations {
let mut vec: Vec<u8> = Vec::with_capacity(cap);
vec.push(255);
}
let end_hpet = get_hpet().as_ref().unwrap().get_counter();
let time = hpet_2_ns(end_hpet - start_hpet) / iterations;
... | Rust | 0 |
Tyrosine => 163.06333,
Valine => 99.06841,
}
}
}
#[derive(Debug, PartialEq)]
pub enum ParseError {
IllegalChar { ch: char },
}
impl error::Error for ParseError {
fn description(&self) -> &str {
match self {
ParseError::IllegalChar { .. } => {
... | Rust | 0 |
}
impl<T> UnitWhitePoint<T> for B where T: Float + FreeChannelScalar + PosNormalChannelScalar {}
/// {obsolete} Average / North sky Daylight.
#[derive(Clone, Debug, PartialEq, Eq, Default, Copy)]
pub struct C;
impl<T> WhitePoint<T> for C
where
T: Float + FreeChannelScalar + PosNormalChannelScalar,
{
#[inline]
... | Rust | 0 |
class Solution:
def tribonacci(self, n: int) -> int:
memo = []
memo.append(0)
memo.append(1)
memo.append(1)
for i in range(3, n + 1):
memo.append(memo[i -3] + memo[i - 2] + memo[i - 1])
return memo[n] | Python | 1 |
e) or bprop.output.match(
_is_mktuple_direct
):
bprop.output = bprop.apply(
P.make_tuple, newenv, *bprop.output.inputs[1:]
)
else:
raise InternalInferenceError(
f"The backpropagator for {prim} is not defined properly. "
f"It should return a tup... | Python | 1 |
from tencentcloud.common import credential
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from tencentcloud.hunyuan.v20230901 import hunyuan_client, models
import json
import base64
from typing import Dict, List, Optional
import asyncio
import aiohttp
import sys
from .bas... | Python | 1 |
import streamlit as st
import pandas as pd
import json
import os
# Load flights and hotels data
def load_data():
with open(os.path.join("data", "flights.json"), "r") as f:
flights = json.load(f)
with open(os.path.join("data", "hotels.json"), "r") as f:
hotels = json.load(f)
return flights, ... | Python | 1 |
# Largest area rectangular sub-matrix with equal number of 1’s and 0’s
# Given a binary matrix. The problem is to find the largest area rectangular
# sub-matrix with equal number of 1’s and 0’s. Examples:
def maximalRectangleArea(A):
n = len(A)
m = len(A[0])
for i in range(m):
s = 0
for j in... | Python | 1 |
hidden_states[begin_chunk_idx:end_chunk_idx]
tokens_in_chunk, _ = curr_hidden_states.shape
if tokens_in_chunk == 0:
break
if tokens_in_chunk < CHUNK_SIZE:
# will only happen in the last chunk
intermediate_cache1 = intermediate_cache1[:tokens_in_chunk]
... | Python | 1 |
meshes[MeshType::Terrain].desc.min_level,
base_entry: meshes[MeshType::Terrain].base_entry as u32,
entries_per_node: meshes[MeshType::Terrain].desc.entries_per_node as u32,
clear_indirect_buffer: device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
usage: wg... | Rust | 0 |
#[test]
fn line_segment_case_get_partial_segment_partial_segment_left_with_emoji_split_at_length() {
let line_segment = LineSegment::new("123456789😊");
let partial = line_segment.get_partial_segment(0, 10);
assert_eq!(partial.get_content(), "123456789");
assert_eq!(partial.get_length(), 9);
}
}
use std:... | Rust | 0 |
the name of a requirements file,
- the content of that file,
- options that should be passed to pip when installing the
requirements file.
apt_packages: APT packages to install.
entrypoint: The default entrypoint command that gets executed when... | Python | 1 |
from thundra.command import command, Command, MessageType, Owner
from neonize import NewClient
from neonize.proto.Neonize_pb2 import Message
import time
from thundra.agents import agent
from thundra.middleware import middleware
from thundra.utils import ChainMessage, get_user_id
from thundra.storage import storage
impo... | Python | 1 |
r
def SubLabel(self, SubLabel):
self._SubLabel = SubLabel
@property
def ContextText(self):
return self._ContextText
@ContextText.setter
def ContextText(self, ContextText):
self._ContextText = ContextText
@property
def SentimentAnalysis(self):
return self._S... | Python | 1 |
def ignore_index_fn(iou_vector):
if ignore_index >= len(iou_vector):
raise ValueError(
'ignore_index {} is larger than the length of IoU vector {}'.
format(ignore_index, len(iou_vector)))
indices = list(range(len(iou_vector)))
indices.remove(ignore_index)
return iou_vecto... | Python | 1 |
props.read_cloned_or_default::<PanelCostProps>();
let pic_cost = ImageBoxProps {
width: ImageBoxSizeValue::Exact(10.),
height: ImageBoxSizeValue::Exact(10.),
material: ImageBoxMaterial::Image(ImageBoxImage {
id: props.stock.pic,
..Default::default()
}),
... | Rust | 0 |
from torch import Tensor
from PIL import Image
from . import _functional_pil as F_pil
def cutout(
img: Tensor | Image.Image,
p: float | tuple[float, float],
fillcolor: int | tuple[int, int, int],
) -> Tensor | Image.Image:
return F_pil.cutout(img, p, fillcolor)
def d_cutout(
img: Tensor | Image.... | Python | 1 |
# -*- coding: utf-8 -*-
import numpy as np
from scipy import stats
def evaluate_summary(predicted_summary, user_summary, eval_method):
""" Compare the predicted summary with the user defined one(s).
:param ndarray predicted_summary: The generated summary from our model.
:param ndarray gt_summary: The user... | Python | 1 |
# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved.
import torch
from easydict import EasyDict
from .shared_config import wan_shared_cfg
#------------------------ Wan I2V 14B ------------------------#
multitalk_14B = EasyDict(__name__='Config: Wan MultiTalk AI2V 14B')
multitalk_14B.update(wan_sh... | Python | 1 |
vocab=vocab, unk_token="[UNK]")
self.assertListEqual(tokenizer.tokenize(""), [])
self.assertListEqual(tokenizer.tokenize("こんにちは"), ["こ", "ん", "に", "ち", "は"])
self.assertListEqual(tokenizer.tokenize("こんにちほ"), ["こ", "ん", "に", "ち", "[UNK]"])
def test_sequence_builders(self):
tokeniz... | Python | 1 |
!(U40leEncoder, u64);
/// Decoder which decodes unsigned 48-bit integers by big-endian byte order.
///
/// The type of decoded values is `u64`, but the most significant 16-bits always be `0`.
///
/// # Examples
///
/// ```
/// use bytecodec::Decode;
/// use bytecodec::fixnum::U48beDecoder;
/// use bytecodec::io::IoDec... | Rust | 0 |
Lyre"), "Easier Lyre", player)
forbid_item(world.get_location("Ixupi Captured Water"), "Water Always Available in Lobby", player)
forbid_item(world.get_location("Ixupi Captured Wax"), "Wax Always Available in Library", player)
forbid_item(world.get_location("Ixupi Captured Wax"), "Wax Always Available in A... | Python | 1 |
ut syscon = p.SYSCON.split();
/// # let mut swm = p.SWM.split();
/// #
/// # #[cfg(feature = "82x")]
/// # let mut swm_handle = swm.handle;
/// # #[cfg(feature = "845")]
/// # let mut swm_handle = swm.handle.enable(&mut syscon.handle);
/// #
/// # let (clkout, pio0_12) = swm.movable_functions.clkout.assign(
/// # p... | Rust | 0 |
lty = min(filler_analysis['filler_percentage'] / 100, 0.3)
# adjusted_confidence = voice_analysis['confidence_score'] * (1 - filler_penalty)
# return {
# 'voice_analysis': voice_analysis,
# 'transcribed_text': transcribed_text,
# 'filler_analysis': filler_ana... | Python | 1 |
# Copyright 2010 VPAC
# Copyright 2014-2025 Marcus Furlong <furlongm@gmail.com>
#
# This file is part of Patchman.
#
# Patchman 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, version 3 only.
#
# Patchman is d... | Python | 1 |
from Equipo.actions.actionsSeccionEquipo import exportSeccionEquipo_csv
from Equipo.models import SeccionEquipo
from django.contrib import admin
from ..filter.EquipoFilter import EquipoFilter
@admin.register(SeccionEquipo)
class SeccionEquipoAdmin(admin.ModelAdmin):
list_display = ['id','nombre','nombre_equipo','u... | Python | 1 |
xceptions.NotFound, self.client.delete_image,
'!@$%^&*()')
@test.attr(type=['negative', 'gate'])
def test_delete_non_existent_image(self):
# Return an error while trying to delete a non-existent image
non_existent_image_id = '11a22b9-12a9-5555-cc11-00ab112223fa'
... | Python | 1 |
assert!(inferred.same(&strand))
}
}
#[test]
fn blocks_in() {
let interval = |range| Interval::new("chr1".into(), range);
let gff3 = "\n\
chr1\t.\tgene\t2\t12\t.\t+\t0\n\
chr1\t.\texon\t4\t6\t.\t+\t0\n\
chr1\t.\texon\t9\t11\t.\t+\t0";
let d... | Rust | 0 |
= blinding_helper(&v);
assert!(
create_and_verify_helper(n, m, q, c, W_L, W_R, W_O, W_V, a_L, a_R, a_O, V, v_blinding,)
.is_err()
);
}
#[test]
// Test that a 2 in 2 out shuffle circuit succeeds
// LINEAR CONSTRAINTS:
// a_O[0] = a_O[1]
// a_L[0] = V... | Rust | 0 |
"Field `reg_ctrl_reset_dummy` writer - "]
pub struct REG_CTRL_RESET_DUMMY_W<'a> {
w: &'a mut W,
}
impl<'a> REG_CTRL_RESET_DUMMY_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x0f << 4)) | ((va... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.