text string | label_name string | labels int64 |
|---|---|---|
if visit_count.iter().any(|x| x >= &(process_count + 1)) { return false; }
// 遍历所有的进程
for i in 0..process_count {
let process = &processes[i];
// 访问次数 + 1
visit_count[i] += 1;
// 判断其是否完成,以及其需求资源是否不超过可用资源
if !finish[i] && process.need <= wor... | Rust | 0 |
40e+00, 1.43847050e+00,
1.44557446e+00, 1.45275214e+00, 1.46000545e+00,
1.46733639e+00, 1.47474705e+00, 1.48223960e+00,
1.48981630e+00, 1.49747950e+00, 1.50523166e+00,
1.51307535e+00, 1.52101325e+00, 1.52904816e+00,
1.53718302e+00, 1.54542090e+00, 1.55376500e+00,
1.562218... | Python | 1 |
rialize_structure_crate_model_aws_ecs_service_deployment_controller_details(
object: &mut smithy_json::serialize::JsonObjectWriter,
input: &crate::model::AwsEcsServiceDeploymentControllerDetails,
) {
if let Some(var_2302) = &input.r#type {
object.key("Type").string(var_2302);
}
}
pub fn seriali... | Rust | 0 |
'''Dummy module'''
def function():
'''Do nothing'''
| Python | 1 |
"""
Arch commands test module
"""
import pytest
from tests.base import RemoteGefUnitTestGeneric
from tests.utils import ARCH
class ArchCommand(RemoteGefUnitTestGeneric):
"""Class for `arch` command testing."""
@pytest.mark.skipif(ARCH != "x86_64", reason=f"Skipped for {ARCH}")
def test_cmd_arch_get(sel... | Python | 1 |
ags & !valid_flags) != 0 {
return Err(ExecuteError::DiscardWriteZeroes {
ioerr: None,
sector,
num_sectors,
flags,
});
}
... | Rust | 0 |
betas = (0.9, 0.999),
eps = 1e-8,
weight_decay = 0.01,
amsgrad = True,
fused = True)
loss_func = ELBOLoss(model = model,
inner_loss = nn.MSELoss(),
... | Python | 1 |
text<Ipv6, _, _>>::receive_ip_packet(
self, device, src_ip, dst_ip, body,
)
}
// A value of `Ipv6Proto::NoNextHeader` tells us that there is no
// header whatsoever following the last lower-level header so we stop
// processing here.
... | Rust | 0 |
W dS ty* Y dS 0 dS )ziDeregister a previously registered hook.
Returns True if the hook existed, False if not.
TFN)rs removerT ru r> r> r? deregister_hook s
z!RequestHooksMixin.deregister_hookN)rh ri rj rx rz r> r> r> r? rm s r... | Python | 1 |
($T,)*) as FieldListExtractor>::Out: WundergraphValue,
<<($($T,)*) as FieldListExtractor>::Out as WundergraphValue>::PlaceHolder: TupleIndex<Key> +
Queryable<<<($($T,)*) as FieldListExtractor>::Out as WundergraphValue>::SqlType, Back> + 'static,
Vec<<<($($T,)*) as Fie... | Rust | 0 |
# -*- coding: utf-8 -*-
"""
Pywinpty
========
This package provides low and high level APIs to create
pseudo terminals in Windows.
"""
# Local imports
from .winpty import PTY, WinptyError, __version__
from .ptyprocess import PtyProcess
from .enums import Backend, Encoding, MouseMode, AgentConfig
PTY
PtyProcess
Backe... | Python | 1 |
uf.offset, buf.size).is_none());
}
View::TEXTURE2D(tex) => {
assert!(tree.insert(tex.offset, tex.pitch * tex.height).is_none());
}
_ => std::panic!(""),
}
}
let mut prev_back: Option<u32> = None;
for ... | Rust | 0 |
e fuchsia_inspect::assert_data_tree;
use fuchsia_inspect_derive::WithInspect;
use fuchsia_zircon::DurationNum;
#[test]
fn bool_to_property() {
let b = false.to_property();
assert_eq!(b, FALSE_VALUE);
let b = true.to_property();
assert_eq!(b, TRUE_VALUE);
}
#[tes... | Rust | 0 |
dex_name': PINECONE_DEFAULT_INDEX,
'api_key': PINECONE_DEFAULT_API_KEY,
'environment': PINECONE_DEFAULT_ENV,
'team_config_id': team.team_config.id
}
pc_config = PineconeConfig(**pc_kwargs)
self.db.add(pc_config)
... | Python | 1 |
color.clone()).unwrap(); /* III. Quadrant */
canvas.set_pixel(xm - y, ym - x, color.clone()).unwrap(); /* IV. Quadrant */
if x == 0 { break; }
e2 = err;
x2 = x; /* remember values */
if err > y {
/* x step */
i = (255 * (err + ... | Rust | 0 |
_impl(
"1 | 3 & 2;",
&mut i,
&[
Instruction::LoadInt(1),
Instruction::LoadInt(3),
Instruction::LoadInt(2),
Instruction::BinaryOperator(BinaryOperator::And),
Instruction::BinaryOperator(BinaryOperator::Or)... | Rust | 0 |
cale_table[:, None]
mu = torch.zeros_like(scales)
cdf_distribution = self.cdf_distribution(mu, scales)
upper = cdf_distribution.cdf(samples + 0.5)
lower = cdf_distribution.cdf(samples - 0.5)
pmf = upper - lower
tail_mass = 2 * lower[:, :1]
quantized_cdf = torch... | Python | 1 |
figurationSection::CodeBlock((block, start_line))) => {
code_block.set_code_block(block, start_line);
break;
}
Some(ConfigurationSection::ConfigName(name)) => {
assert!(
Config::is_valid_name(&name),
... | Rust | 0 |
, _, _) = request_with_body("GET /", "", "one");
assert!(status_line.starts_with("HTTP/1.1 501 "));
let (status_line, _, _) = request_with_body("GET /", "", "two");
assert!(status_line.starts_with("HTTP/1.1 501 "));
let (status_line, _, _) = request_with_body("GET /", "", "one two");
assert!(statu... | Rust | 0 |
ss: u32 = 50403;
pub const DAQmxWarningPALTransferStopped: u32 = 50404;
pub const DAQmxWarningPALTransferAborted: u32 = 50405;
pub const DAQmxWarningPALLogicalBufferEmpty: u32 = 50406;
pub const DAQmxWarningPALLogicalBufferFull: u32 = 50407;
pub const DAQmxWarningPALPhysicalBufferEmpty: u32 = 50408;
pub const DAQmxWarn... | Rust | 0 |
Data(data, &self.buffer));
Ok(())
}
fn set_blend_mode(&mut self, mode: BlendMode) -> GameResult {
let _ = self.psos.mode(mode)?;
self.active_blend_mode = mode;
Ok(())
}
fn blend_mode(&self) -> BlendMode {
self.active_blend_mode
}
}
/// A lock for RAII shade... | Rust | 0 |
threads: usize,
pub db_cache: usize,
pub data_dir: Option<String>,
pub user_agent: String,
pub internet_protocol: InternetProtocol,
pub rpc_config: RpcHttpConfig,
pub block_notify_command: Option<String>,
pub verification_params: VerificationParameters,
pub db: db::SharedStore,
}
pub const DEFAULT_DB_CACHE: us... | Rust | 0 |
x):
sys.stdout.write('\r>> Converting image %d/%d shard %d' % (
i+1, len(filenames), shard_id))
sys.stdout.flush()
# Read the filename:
image_data = tf.gfile.FastGFile(filenames[i], 'rb').read()
height, width = image_reader.read_image_dims(ses... | Python | 1 |
import numpy as np
from scipy.stats import norm
from PIL import Image, ImageDraw, ImageFont, ImageMath
from pyray.shapes.twod.paraboloid import *
from pyray.rotation import *
from pyray.imageutils import *
from pyray.axes import *
from pyray.shapes.oned.curve import draw_curve
from pyray.misc import zigzag2
from pyray.... | Python | 1 |
parent: Some(&self.cur),
data: ScopeData {
kind,
..Default::default()
},
depth: self.cur.depth + 1,
},
is_pat_decl: self.is_pat_decl,
};
op(&mut child);
let v = take(&mut child.... | Rust | 0 |
from ..campaign_war_archives.campaign_base import CampaignBase
from module.logger import logger
from module.map.map_base import CampaignMap
from module.map.map_grids import RoadGrids, SelectedGrids
from .b1 import Config as ConfigBase
MAP = CampaignMap('B2')
MAP.shape = 'I7'
MAP.camera_data = ['D2', 'D5', 'F2', 'F5']... | Python | 1 |
ꜰᴇᴀᴛᴜʀᴇꜱ ⚡️\n◆ ʙᴏᴛ ғᴏʀ ᴛᴇʟᴇɢʀᴀᴍ ɢʀᴏᴜᴘs.\n◆ Sᴜᴘᴇʀғᴀsᴛ ʟᴀɢ Fʀᴇᴇ ᴘʟᴀʏᴇʀ.\n◆ ʏᴏᴜ ᴄᴀɴ ᴘʟᴀʏ ᴍᴜꜱɪᴄ + ᴠɪᴅᴇᴏ.\n◆ ʟɪᴠᴇ ꜱᴛʀᴇᴀᴍɪɴɢ.\n◆ ɴᴏ ᴘʀᴏᴍᴏ.\n◆ ʙᴇꜱᴛ ꜱᴏᴜɴᴅ Qᴜᴀʟɪᴛʏ.\n◆ 24×7 ʏᴏᴜ ᴄᴀɴ ᴘʟᴀʏ ᴍᴜꜱɪᴄ.\n◆ ᴀᴅᴅ ᴛʜɪꜱ ʙᴏᴛ ɪɴ ʏᴏᴜʀ ɢʀᴏᴜᴘ ᴀɴᴅ ᴍᴀᴋᴇ ɪᴛ ᴀᴅᴍɪɴ ᴀɴᴅ ᴇɴᴊᴏʏ ᴍᴜꜱɪᴄ 🎵.\n\n┏━━━━━━━━━━━━━━━━━⧫\n┠ ◆ ꜱᴜᴘᴘᴏʀᴛɪɴɢ ᴘʟᴀᴛꜰᴏʀᴍꜱ : ʏᴏᴜᴛᴜʙᴇ, ꜱᴘᴏᴛɪꜰʏ... | Python | 1 |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | Python | 1 |
# -*- coding: utf-8 -*-
"""
Created on Thu Dec 5 09:53:32 2024
@author: etudiant17
"""
# -*- coding: utf-8 -*-
"""
Created on Thu Dec 5 08:05:34 2024
@author: etudiant17
"""
import numpy as np
import matplotlib.pyplot as plt
from scipy.special import fresnel
def Intensity(x,y,z, wl=500*10**(-9),a=0.01,b=0.01):
... | Python | 1 |
=> 0b00,
Opcode::CLW => 0b00,
Opcode::CLD => 0b00,
Opcode::CSW => 0b00,
Opcode::CSD => 0b00,
Opcode::CADDIW => 0b01,
Opcode::CLI => 0b01,
Opcode::CADDI16SP => 0b01,
Opcode::CLUI => 0b01,
Opcode::CSRLI => 0b01,
... | Rust | 0 |
nd = batch_begin + batch_size
pretrain_x = pretrain_x[batch_begin: batch_end]
pretrain_fns = []
is_train = numpy.cast['int32'](0) # value does not matter
for dA_layer in self.dA_layers:
# get the cost and the updates list
cost, updates = dA_layer.get_cost_updates(corruption_level,
learning_rate)
... | Python | 1 |
if T < size:
begin = random.randint(0, size - T) if random_pad else 0
data_numpy_paded = np.zeros((C, size, V, M))
data_numpy_paded[:, begin:begin + T, :, :] = data_numpy
return data_numpy_paded
else:
return data_numpy
def random_choose(data_numpy, size = 64, auto_pad=... | Python | 1 |
import RPi.GPIO as GPIO
import time
BUZZER_PIN = 21
BUTTON_PIN = 26
GPIO.setmode(GPIO.BCM)
GPIO.setup(BUZZER_PIN, GPIO.OUT)
GPIO.setup(BUTTON_PIN, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
while 1:
if GPIO.input(BUTTON_PIN) == GPIO.HIGH:
GPIO.output(BUZZER_PIN, GPIO.HIGH)
print("BUZZER ON")
else:... | Python | 1 |
import json
import glob
from tqdm import tqdm
from openai import OpenAI
client = OpenAI()
#client.batches.cancel('batch_PquqjXRXbkCQ0IUpWdUofXtm')
# batch_job = client.batches.retrieve('batch_PquqjXRXbkCQ0IUpWdUofXtm')
# print(batch_job)
file_name = "batch_tasks.jsonl"
batch_file = client.files.create(
file=open(fi... | Python | 1 |
import employee_model
def initialize():
employee_model.create_table()
def add(emp_id, name, age, department, salary, contact):
employee_model.add_employee(emp_id, name, age, department, salary, contact)
def view_all():
return employee_model.get_all_employees()
def update(emp_id, name, age, department, s... | Python | 1 |
"
],
"tfoot" => hashset![
"align", "char", "charoff"
],
"th" => hashset![
"align", "char", "charoff", "colspan", "headers", "rowspan", "scope"
],
"thead" => hashset![
"align", "char", "charoff"
... | Rust | 0 |
from django.contrib import admin
from django.shortcuts import redirect
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('scraper/', include('scraper.urls')),
path('', lambda request: redirect('scraper:dashboard')), # Optional redirect
]
| Python | 1 |
,
) -> Result<(), aws_smithy_http::operation::SerializationError> {
#[allow(unused_mut)]
let mut scope_1109 = writer.prefix("InstanceType");
if let Some(var_1110) = &input.instance_type {
scope_1109.string(var_1110.as_str());
}
#[allow(unused_mut)]
let mut scope_1111 = writer.prefix("Max... | Rust | 0 |
import pyodbc
def get_sql_blocking(sql_connection, logger:None, verbose:bool=False, **kwargs):
cursor = sql_connection.cursor()
# Extract parameters
blocked_counts_threshold = kwargs['blocked_counts_threshold']
blocked_duration_max_seconds_threshold = kwargs['blocked_duration_max_seconds_threshold']
... | Python | 1 |
import pygame
from pygame.sprite import Sprite
class Alien(Sprite):
"""代表舰队中单个外星人的类。"""
def __init__(self, ai_game):
"""初始化外星人并设置其起始位置。"""
super().__init__()
self.screen = ai_game.screen
self.settings = ai_game.settings
# 加载外星人图像并设置其 rect 属性。
self.image = pyga... | Python | 1 |
offset.abs() % 60
)
})
.as_deref(),
),
datetime.year as i32,
datetime.month as i32,
datetime.day as i32,
datetime.hour as i32,
datetime.minute as i32,
datetime.second a... | Rust | 0 |
}
}
#[cfg(feature = "use-serde")]
#[derive(Deserialize)]
#[serde(tag = "type", content = "value", rename_all = "PascalCase")]
enum OwnedPushValueImpl {
Boolean(bool),
Constant(u16),
Float32(SwfFloat<f32>),
Float64(SwfFloat<f64>),
Null,
Register(u8),
Sint32(i32),
String(String),
Undefined,
}
#[cfg(f... | Rust | 0 |
ust
/// if your board has a different frequency
const XTAL_FREQ_HZ: u32 = 12_000_000u32;
/// Entry point to our bare-metal application.
///
/// The `#[entry]` macro ensures the Cortex-M start-up code calls this function
/// as soon as all global variables are initialised.
///
/// The function configures the RP2040 per... | Rust | 0 |
80 = match self.fpu.get_st(0) {
None => return Err(ExecError::ReadEmptyFPURegister),
Some(v) => v,
};
let (a, b): (F80, F80) = match s & 0xf {
0 => match self.fpu.get_st(i) {
None => return Err(ExecError::ReadEmptyFPURegister),
Some(oth... | Rust | 0 |
from crud import Database
def main():
db = Database()
while True:
print("**********--WELCOME--***********")
print()
print("Press 1 for insert new user(userId, name, phone)")
print("Press 2 for fetch all user")
print("Press 3 for delete the user(userId)")
print("... | Python | 1 |
# Don't Remove Credit @VJ_Botz
# Subscribe YouTube Channel For Amazing Bot @Tech_VJ
# Ask Doubt on telegram @KingVJ01
import random, os
from info import CHNL_LNK
from pyrogram import Client, filters, enums
from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton
@Client.on_message(filters.command(["gen... | Python | 1 |
score=(int)(input("ENTER THE SCORE PERSENT:"))
if score >=101:
print("Sorry this value is no define.")
exit()
if score>=90:
grade="A"
elif score>=80:
grade="B"
elif score>=70:
grade="C"
elif score>=60:
grade="D"
else:
grade="F"
print("GRADE:",grade) | Python | 1 |
max: Disr, discr: Disr) {
if min <= max {
assert!(min <= discr && discr <= max)
} else {
assert!(min <= discr || discr <= max)
}
}
/// Access a field, at a point when the value's case is known.
pub fn trans_field_ptr<'a, 'tcx>(
bcx: &BlockAndBuilder<'a, 'tcx>,
t: Ty<'tcx>,
val:... | Rust | 0 |
ream.start() {
println!("Data Stream Started ...");
let listen_key = answer.listen_key;
match user_stream.keep_alive(&listen_key) {
Ok(msg) => println!("Keepalive user data stream: {:?}", msg),
Err(e) => println!("Error: {}", e),
}
match user_stream.clos... | Rust | 0 |
# https://github.com/Zero-coder/FECAM/blob/main/layers/dctnet.py
import warnings
warnings.filterwarnings('ignore')
import torch.nn as nn
import numpy as np
import torch
"""
这段代码实现了一个名为 `dct_channel_block` 的 PyTorch 模块,该模块包含了离散余弦变换(DCT)和通道注意力机制的功能。
首先,定义了一个函数 `dct`,用于对输入的时间序列数据进行离散余弦变换。在函数内部,首先将输入的数据进行处理,然后利用快速傅里叶变换... | Python | 1 |
_multi as pallet_nft;
mod default_weight;
pub mod migration;
pub trait WeightInfo {
fn create_blind_box() -> Weight;
fn blind_box_add_card_group() -> Weight;
fn blind_box_remove_card_group() -> Weight;
fn buy_blind_box() -> Weight;
fn close_blind_box() -> Weight;
fn open_blind_box() -> Weight;... | Rust | 0 |
help=SubCliLite.smooth_quant.__doc__)
parser.set_defaults(run=SubCliLite.smooth_quant)
parser.add_argument('model', type=str, help='The name or path of the model to be loaded')
parser.add_argument('--work-dir',
type=str,
defa... | Python | 1 |
import sys
sys.path.append(r'D:\Dev\Source\Falcom\Decompiler2')
from Falcom.ED6.Parser.scena_writer_helper import *
try:
import T3115_1_hook
except ModuleNotFoundError:
pass
scena = createScenaWriter('T3115_1 ._SN')
# id: 0xFFFF offset: 0x0
@scena.Header('Header')
def Header():
header = ScenaHeader()
... | Python | 1 |
lockPos }
0x37 => Statistics { stats: Arr<Var<i32>, Stat> }
// 0x38 => UpdatePlayerList { action: Var<i32>, players: Arr<Var<i32>, PlayerListItem>; impl Protocol for UpdatePlayerList { ... } } // PROBLEM: structure of `players` elements depends on `action`
0x39 => PlayerAbilities { f... | Rust | 0 |
= 0,
Minimized = 1,
Active = 2,
Fullscreen = 3,
}
impl State {
pub fn from_bytes(bytes: &[u8]) -> Vec<State> {
bytes.chunks(4).map(|buf| {
let mut r = Cursor::new(buf);
let a = r.read_u32::<NativeEndian>().unwrap();
State::from_u32(a)
}).collect()
}
fn from_u32(a: u32) -> State ... | Rust | 0 |
import filecmp
import os
from unittest import TestCase
import numpy as np
from pygem import BFFD
class TestBFFD(TestCase):
def test_nothing_happens_bffd(self):
np.random.seed(0)
original_mesh_points = np.random.rand(100, 3)
A = np.random.rand(3, original_mesh_points.reshape(-1).shape[0])
... | Python | 1 |
scoring=balanced_scorer, random_state=42,
n_jobs=-1
)
plt.figure(figsize=(12, 8))
train_mean = np.mean(train_scores, axis=1)
train_std = np.std(train_scores, axis=1)
val_mean = np.mean(val_scores, axis=1)
val_std = np.std(val_scores, axis=1)
plt.plot(train_sizes, train_mean,... | Python | 1 |
world/vehicle coordinates, compute an orthonormal basis:
r = normalize(cross(d, f)), d = cross(f, r) with d seeded as world down (0,0,-1), f = forward.
Returns (yaw, pitch, roll) in degrees so that columns of R are [r, d, f].
"""
fx, fy, fz = forward_world
f = np.array([fx, fy, fz], dtype=float)
... | Python | 1 |
= apply_colors(&rhs_src, false, &rhs_positions);
print!(
"{}",
apply_groups(
&lhs_colored,
&rhs_colored,
&groups,
&lhs_matched_lines,
lhs_content_width,
rhs_content_width,
lhs_column_width,
rhs_column_w... | Rust | 0 |
x0042_63E3,// VEX_Vperm2f128_ymm_ymm_ymmm256_imm8
0x0008_0000, 0x0000_800D, 0x000E_7263,// Roundps_xmm_xmmm128_imm8
0x0008_0001, 0x0000_4C0D, 0x0001_0962,// VEX_Vroundps_xmm_xmmm128_imm8
0x0008_0001, 0x0000_500D, 0x0001_09A3,// VEX_Vroundps_ymm_ymmm256_imm8
0x0008_0002, 0x0320_400D, 0x0000_E85E,// EVEX_Vrndscaleps_... | Rust | 0 |
import hashlib
def _extract_byte_range(sig):
br_obj = sig.sig_object.get('/ByteRange')
if br_obj is None:
br_obj = sig.sig_object.get('ByteRange')
if not br_obj:
return None
# converter elementos para int
return [int(x) for x in br_obj]
def _signed_content_from_byte_range(pdf_byte... | Python | 1 |
10_000, 10_000)}
set_intersection_bench! {intersect_neg_vs_pos_10_vs_10k,neg_vs_pos(10, 10_000)}
set_intersection_bench! {intersect_neg_vs_pos_10k_vs_10,neg_vs_pos(10_000, 10)}
set_intersection_bench! {intersect_pos_vs_neg_100, pos_vs_neg(100, 100)}
set_intersection_bench! {intersect_pos_vs_neg_10k, pos_vs_ne... | Rust | 0 |
_port,
} => {
Pattern0x01::marshal(pattern, bytes);
bytes.write_u8(table_id).unwrap();
write_padding_bytes(bytes, 1);
bytes.write_u16::<BigEndian>(out_port).unwrap();
}
StatsReqBody::TableBody => {}
StatsReqB... | Rust | 0 |
# This example requires the 'message_content' intent.
import discord
from discord.ext import commands
import os
bot_token:str = os.environ.get("TOKEN")
bot = commands.Bot(command_prefix='!', intents=discord.Intents.all()) # Prefijo para los comandos
@bot.event
async def on_ready():
print(f"Conectado como {bot... | Python | 1 |
ata.borrow()).to_vec();
if !is_initialized(&temp) {
return Err(ProgramError::UninitializedAccount);
}
let mut pdbk = PriceDBKeeper::try_from_slice(&temp).map_err(|_| ProgramError::Custom(113))?;
// check owner
if pdbk.owner != sender.key.to_b... | Rust | 0 |
e crate::idx::IndexClient;
use either::Either;
pub fn create_movie(conn: &DbConnection, movie: CreateMovieParams) -> Result<Either<HasId, Movie>, Error> {
info!("creating movie {:?}", movie);
db::create_movie(conn, movie.create())
}
pub fn update_movie(conn: &DbConnection, id: Uuid, movie: UpdateMovieParams) ... | Rust | 0 |
https://plugins.dprint.dev/schemas/test.json","helpUrl":"https://dprint.dev/plugins/test"},"#);
final_output.push_str(r#"{"name":"test-process-plugin","version":"0.1.0","configKey":"testProcessPlugin","fileExtensions":["txt_ps"],"fileNames":["test-process-plugin-exact-file"],"helpUrl":"https://dprint.dev/plugins/te... | Rust | 0 |
tr(self, "scraper", None):
self.scraper.request_cancel()
if t and not t.done():
t.cancel()
with contextlib.suppress(asyncio.CancelledError):
await asyncio.wait_for(t, timeout=5.0)
except Exception as e:
logger.debug("Shu... | Python | 1 |
t_len \
and (not request.is_migrating) \
]
return filtered_waiting
def _get_last_running_request(self, min_request_len, max_request_len):
running: Deque[LlumnixRequest] = self.backend_engine.get_running_queue()
filtered_running = self._filter_running_queue(runnin... | Python | 1 |
fd_minus_ticks_measure: ScopedFd,
fd_ticks_interrupt: ScopedFd,
fd_ticks_in_transaction: ScopedFd,
fd_useless_counter: ScopedFd,
ticks_semantics: TicksSemantics,
started: bool,
counting: bool,
}
fn make_counter_async(fd: &ScopedFd, signal: Sig) {
if unsafe {
fcntl(fd.as_raw(), ... | Rust | 0 |
.iter()
.find(|d| d.domain == domain)
.context(format!("Could not find domain {} at Linode", domain))?;
let records = client.get_domain_records(domain.id).await?;
let addr_type = if ip_address.is_ipv4() { "A" } else { "AAAA" };
let record = records
.into_iter()
.find... | Rust | 0 |
s_negative:
disamb_non_target_and_non_neg += 1
acc.add(is_correct)
# formulae taken from page 6 of https://arxiv.org/pdf/2110.08193.pdf
amb_bias_score_numer = amb_target_and_neg + amb_non_target_and_non_neg
amb_bias_score_denom = amb_non_unknown
... | Python | 1 |
iption="阅读链接,有一次返回的是None")
msg: str | None = Field(None, description="这个字段目前已知当阅读达到上限时出现")
@property
def is_next_check(self) -> bool:
"""
当前返回的链接是否是检测文章
:return: True: 是检测文章 False: 不是检测文章
"""
if self.check_finish is None and self.success_msg is None:
retu... | Python | 1 |
)]
#[serde(rename_all = "camelCase")]
pub(crate) struct RequestData {
pub(crate) ver: i32,
pub(crate) id: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub(crate) source: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub(crate) name: Option<String>,
pub(crate)... | Rust | 0 |
ulBuiltInFunction::Balance,
"selfbalance" => YulBuiltInFunction::SelfBalance,
"caller" => YulBuiltInFunction::Caller,
"callvalue" => YulBuiltInFunction::CallValue,
"calldataload" => YulBuiltInFunction::CallDataLoad,
"calldatasize" => YulBuiltInFunction::CallDataSize,
"calldatacopy" => YulBuiltIn... | Rust | 0 |
(self).__name__!r} requires all plugins to be callable objects, "
f"but {type(self._active).__name__!r} is not callable."
)
raise TypeError(msg)
elif TYPE_CHECKING:
# NOTE: The `None` return is implicit, but `mypy` isn't satisfied
# - `ruff` will f... | Python | 1 |
123, 236, 243, 192, 100, 34, 40, 51, 111, 129, 130, 160, 64, 129, 135, 11, 184, 68, 84, 83, 198, 234, 196,
150, 13, 208, 86, 34, 150, 10, 59, 247,
]);
let secret_key = vec![
137, 16, 46, 159, 212, 158, 232, 178, 197, 253, 105, 137, 102, 159, 70, 217, 110, 211, 254, 82, 216, 4, 105,
171... | Rust | 0 |
"""
Line styles
===========
The :meth:`pygmt.Figure.plot` method can plot lines in different styles.
The default line style is a 0.25-point wide, black, solid line, and can be
customized with the ``pen`` parameter.
A *pen* in GMT has three attributes: *width*, *color*, and *style*.
The *style* attribute controls the ... | Python | 1 |
rk_cv(new_result_img)
result_faces.append(Image.fromarray(cv2.cvtColor(new_result_img, cv2.COLOR_BGR2RGB)))
# if len(result_faces) > n:
# break
return result_faces
async def swap_faces(source_path: str, mode: str = '4') -> Optional[List[Image.Image]]:
"""
Swaps faces between th... | Python | 1 |
#!/usr/bin/env python
# Test callback that returns False to cancel emulation
from __future__ import print_function
from unicorn import *
from unicorn.x86_const import *
import regress
X86_CODE32_MEM_WRITE = b"\x89\x0D\xAA\xAA\xAA\xAA\x41\x4a" # mov [0xaaaaaaaa], ecx; INC ecx; DEC edx
# callback for tracing invalid... | Python | 1 |
of tasks with individual states
fn job_progress_bar(info: &JobInfo) -> String {
let mut buffer = String::from("[");
let width: usize = 40;
let parts = vec![
(info.counters.n_canceled_tasks, colored::Color::Magenta),
(info.counters.n_failed_tasks, colored::Color::Red),
(info.counters... | Rust | 0 |
import os
import google.generativeai as genai
GOOGLE_API_KEY = os.getenv('GOOGLE_API_KEY')
# Configure generativeai with your API key
genai.configure(api_key=GOOGLE_API_KEY) | Python | 1 |
import time
from picamera2 import Picamera2
def main():
print("With context...")
time.sleep(1)
with Picamera2() as picam2:
preview = picam2.create_preview_configuration()
picam2.configure(preview)
picam2.start()
metadata = picam2.capture_file("context_test.jpg")
pr... | Python | 1 |
char.msdf_texture_glyph_id);
}
#[wasm_bindgen_test(async)]
async fn getting_or_creating_char() {
ensogl_text_msdf_sys::initialized().await;
let font_render_info = create_test_font();
{
let char_info = font_render_info.glyph_info('A');
assert_eq!(0, char_info... | Rust | 0 |
#################################################################################################
# Genome based functions.
#################################################################################################
#################################################################################################... | Python | 1 |
Invoked for every term. By default, recursively visits the term's contents.
fn visit_term(&mut self, term: &Term<T>) -> ControlFlow<Self::BreakTy> {
term.super_visit_with(self)
}
/// Invoked for every constant. By default, does nothing and continues the traversal.
fn visit_const(&mut self, _co... | Rust | 0 |
ub psortby: ProcessTableSortBy,
pub psortorder: ProcessTableSortOrder,
pub osname: String,
pub release: String,
pub version: String,
pub arch: String,
pub hostname: String,
pub network_interfaces: Vec<NetworkInterface>,
pub sensors: Vec<Sensor>,
pub gfx_devices: Vec<GraphicsDevice>,
... | Rust | 0 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class AlipayMerchantQipanCrowdQueryModel(object):
def __init__(self):
self._crowd_code = None
self._external_crowd_code = None
@property
def crowd_code(self):
return se... | Python | 1 |
#!/usr/bin/env python3
"""
Clean up stray POSIX shared-memory segments created with multiprocessing.shared_memory
or posix_ipc. Works on any Linux where segments appear as regular files in /dev/shm.
Author: you
"""
import os, sys, argparse, textwrap
from pathlib import Path
from multiprocessing import shared_memory
... | Python | 1 |
from typing import Literal
import numpy as np
import pylev
from seqme.core import Metric, MetricResult
class Diversity(Metric):
"""Normalized pairwise Levenshtein distance between the sequences."""
def __init__(
self,
reference: list[str] = None,
k: int | None = None,
seed: ... | Python | 1 |
config.set_today_tracked();
let result = match command {
Command::Status => {
println!("You plan to spend {} per day on mindfulness.", config.goal_string());
println!("So far, you've spent {}.", config.completed_today_string());
Ok(())
}
Command::Start =>... | Rust | 0 |
nt(" No tools available in the agent!")
return False
else:
print(f"\nUnknown command: /{command}")
print("Type /help for available commands")
return False
async def main():
"""Main CLI entry point."""
display_welcome_message()
try:
print("Setting up agent.... | Python | 1 |
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import minimize
from sklearn import datasets
plt.style.use('ggplot')
#____________________________________________________DATA_______________________________________________________________
np.random.seed(20)
n=20
d,l=datasets.make_moons(n_samples... | Python | 1 |
import os
import tkinter as tk
import pyautogui
import numpy as np
import cv2
import pytesseract
import time
os.environ['TESSDATA_PREFIX'] = os.path.dirname(os.path.abspath(__file__))
# Define the area for capturing clicks
click_area_x1, click_area_y1 = 100, 100 # Top-left corner
click_area_x2, click_area_y2 = 200, 2... | Python | 1 |
}
}
/// 通用标准埋雷引擎。
/// - 标准埋雷规则:起手位置非雷,其余位置的雷服从均匀分布。
/// - 输出:二维的局面,其中0代表空,1~8代表1~8,-1代表雷。
pub fn laymine(row: usize, column: usize, MineNum: usize, X0: usize, Y0: usize) -> Vec<Vec<i32>> {
let area: usize = row * column - 1;
let mut Board1Dim: Vec<i32> = vec![];
Board1Dim.reserve(area);
Board1Dim ... | Rust | 0 |
rs": 1,
"months": 1,
"weeks": 1,
"days": 1,
"hours": 1,
"minutes": 1,
},
period="day",
),
# Arabic dates
param("اليوم", ago={"days": 0}, period="day"),
... | Python | 1 |
lf.base + idx * ENTRY_SIZE
}
#[inline(always)]
fn cap_mask(&self) -> usize {
self.capacity - 1
}
}
impl<K, V, A: Attachment<K, V>, ALLOC: GlobalAlloc + Default, H: Hasher + Default> Clone
for Table<K, V, A, ALLOC, H>
{
fn clone(&self) -> Self {
let new_table = Table {
... | Rust | 0 |
col_step.ordinal_id'] = ['1', '2', '3']
cif['_ma_protocol_step.protocol_id'] = ['1', '1', '1']
cif['_ma_protocol_step.step_id'] = ['1', '2', '3']
cif['_ma_protocol_step.method_type'] = [
'coevolution MSA',
'template search',
'modeling',
]
# Details of the metrics use to assess model confide... | Python | 1 |
_reg_ctrl_hw1."]
pub pa_reg_ctrl_hw1: crate::Reg<pa_reg_ctrl_hw1::PA_REG_CTRL_HW1_SPEC>,
#[doc = "0x12c - pa_reg_ctrl_hw2."]
pub pa_reg_ctrl_hw2: crate::Reg<pa_reg_ctrl_hw2::PA_REG_CTRL_HW2_SPEC>,
#[doc = "0x130 - pa_reg_wifi_ctrl_hw."]
pub pa_reg_wifi_ctrl_hw: crate::Reg<pa_reg_wifi_ctrl_hw::PA_REG... | Rust | 0 |
rate = toml_val.baud_rate;
let data_bits = ParseConfig::get_data_bits(&toml_val);
let flow_control = ParseConfig::get_flow_control(&toml_val);
let parity = ParseConfig::get_parity(&toml_val);
let stop_bits = ParseConfig::get_stop_bits(&toml_val);
let timeout_in_milliseconds = Dur... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.