text string | label_name string | labels int64 |
|---|---|---|
doc = r"Value read from the register"]
pub struct R {
bits: u32,
}
#[doc = r"Value to write to the register"]
pub struct W {
bits: u32,
}
impl super::TBMR {
#[doc = r"Modifies the contents of the register"]
#[inline(always)]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&R, &'w m... | Rust | 0 |
#!/usr/bin/env python
from __future__ import print_function
import pdfparser.poppler as pdf
import argparse
import sys
p=argparse.ArgumentParser()
p.add_argument('document', help='Document file')
p.add_argument('--char-details', action='store_true', help='print character details')
p.add_argument('-f', '--first-page',... | Python | 1 |
import random
from art import logo
import os
def draw_card(hand):
cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
hand.append(random.choice(cards))
return hand
def calculate_score(hand):
score = sum(hand)
if score > 21:
for card in hand:
if card == 11:
hand.remove(card)
hand... | Python | 1 |
::Response, atat::Error> {
let resp = core::str::from_utf8(resp?).unwrap();
// Example: +CIFSR:STAIP,"10.0.99.164"\r\n+CIFSR:STAMAC,"dc:4f:22:7e:41:b4"
let mut mac = None;
let mut ip = None;
for line in resp.lines() {
if line.starts_with("+CIFSR:STAIP,") {
... | Rust | 0 |
.as_ref()
.unwrap()
.buff_tkn
.as_ref()
.unwrap()
.send_buff
{
Some(buff) => Some(buff.scat_cpy()),
None => None,
};
let recv_data = match &self
.transfer_tkn
.as_ref()
.unwrap()
.buff_tkn
.as_ref()
.unwrap()
.send_buff
{
Some(... | Rust | 0 |
ry:
fit_group = fits.all[wk.label()]
except Exception:
missing.append(wk.label())
else:
present.append(wk.label())
if (len(missing) > 0):
print("// Warning: Missing scattering labels:", file=f)
for label in missing:
print("// ", label, file=f)
print(file=f)
write_header(f... | Python | 1 |
'''
## Question
### 1002. [Find Common Characters](https://leetcode.com/problems/find-common-characters/)
Given an array A of strings made only from lowercase letters, return a list of all characters that show up in all strings within the list (including duplicates). For example, if a character occurs 3 times in all s... | Python | 1 |
erated via
// lib/upddb.c. You may build chars.db with `just run`
// in the lib dir.
mod db;
use crate::db::DB;
const LCHARMAP_VERSION: &'static str = env!("CARGO_PKG_VERSION");
//const DEFAULT_RANGE_START: usize = 0;
//const DEFAULT_RANGE_STOP: usize = 255;
// escape char; needed for formatting
const ESCAPE: ... | Rust | 0 |
mu_info[imu_idx] = filter_noise(imu_info[imu_idx], fps)
imu_info = imu_info.transpose(1,0)
init_vel, rotation_vector, translation_vector, scale_factor, cost = optimize_params(c2ws[:, :3, -1], imu_info, fps)
if cost > 50:
continue
# 将sfm pose进行尺度调整
... | Python | 1 |
Once(Result<String, Error>) + Send + 'static>(_source_object: *mut gobject_ffi::GObject, res: *mut ffi::GAsyncResult, user_data: glib_ffi::gpointer)
{
callback_guard!();
let mut error = ptr::null_mut();
let mut new_etag = ptr::null_mut();
let _ = ffi::g_file_repla... | Rust | 0 |
from lc import *
# related to basic calculator
# amazing chart/state machine here https://leetcode.com/problems/valid-number/discuss/360781/Python-with-state-machine-36ms
class Solution:
def isNumber(self, s: str) -> bool:
start, int_sign, integer, point, frac, exp, exp_sign, exp_int = range(8)
d... | Python | 1 |
file("bgfx/src/glcontext_wgl.cpp");
build.file("bgfx/src/nvapi.cpp");
build.file("bgfx/src/dxgi.cpp");
build.file("bgfx/src/shader_dx9bc.cpp");
build.file("bgfx/src/shader_spirv.cpp");
} else if env.contains("darwin") {
build.file("bgfx/src/glcontext_nsgl.mm");
build.... | Rust | 0 |
class Solution:
def maxDfromAtoB(self, a: int, b: int, k: int, n: int, freq: List[List[int]]) -> int:
cnt = float('-inf')
MOD = 10 ** 8
minFreq = [[MOD, MOD], [MOD, MOD]]
freqA = 0
freqB = 0
prevA = 0
prevB = 0
l = 0
for r in range(k - 1, n):
... | Python | 1 |
qu_vlads.cpu(), f"{save_dir}/qu-{ds_name}.pt")
print(f"Saved files [db,qu]-{ds_name}.pt in {save_dir}")
print("----- Calculating recalls through top-k matching -----")
dists, indices, recalls = get_top_k_recall(largs.top_k_vals,
db_vlads, qu_vlads, vpr_ds.soft_positives_per_query,
... | Python | 1 |
);
let mut res = Field::new();
let row_zeros = std::iter::repeat(0).take(m + 2 * padding).collect::<Vec<_>>();
for _ in 0..padding {
res.push(row_zeros.clone());
}
let pad_zeros = std::iter::repeat(0).take(padding).collect::<Vec<_>>();
for row in f {
let mut new_row = pad_zeros... | Rust | 0 |
to_string_lossy().to_string();
let file_string = std::fs::read_to_string(args.input_path).ok()?;
let simple_file = SimpleFile::new(file_name, file_string);
match tokenize(simple_file) {
Ok(token_data) => {
for token_m in token_data.tokens {
let diagnostic = Diagnostic::... | Rust | 0 |
# Adapted from https://github.com/biubug6/Pytorch_Retinaface
# Original license: MIT
import torch
import numpy as np
def decode_landm(pre, priors, variances):
"""Decode landm from predictions using priors to undo
the encoding we did for offset regression at train time.
Args:
pre (tensor): landm pr... | Python | 1 |
join(opt.tmp_dir,'fake',directory,videonum))
dst = os.path.join(opt.tmp_dir,'fake',directory,videonum)
for i in range(frameNum+1,frameNum+31):
i_str = '%06d'%i
i_jpg = i_str + '.jpg'
shutil.copy(os.path.join(framedir,i_jpg),dst)
output_audio = videonum + '.wav'
audiotmp = os.path.joi... | Python | 1 |
# Copyright (c) 2022, Oracle and/or its affiliates.
#
# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl/
#
from e2e.mysqloperator.handle_8_0_29 import handle_29_base
# test the following scenario:
# set up a cluster version 8.0.29 -> failure -> delete -> all gone
... | Python | 1 |
eference to our controller we created when we kicked of the async
// attaching process
let controller = NVME_CONTROLLERS
.lookup_by_name(&ctx.name())
.expect("no controller in the list");
// clone it now such that we can lock the original, and insert it later.
let ctl = Arc::clone(&cont... | Rust | 0 |
.iter() {
match ParsedDateTime::build_parsed_datetime_interval(test.0, test.1) {
Err(e) => assert_eq!(e.to_string(), test.2),
Ok(pdt) => panic!(
"Test INTERVAL '{}' {} passed when expected to fail with {}, generated ParsedDateTime {:?}",
... | Rust | 0 |
ncy. Each triplet on a new line. Relation includes Containment/Vertical/Horizontal classes.
**Output Format (Strict Order):**
1. Reasoning Paragraph (from Step 3).
2. Scene Graph Text (from Step 4, newline separated triplets).
3. The exact text block:\nTherefore, the scene layout is:\n**Final Answer**\n
4. Scene L... | Python | 1 |
Tbl.lock().NewFDFrom(fd, file, flags);
}
pub fn RemoveFile(&self, fd: i32) -> Result<File> {
match self.fdTbl.lock().Remove(fd) {
None => return Err(Error::SysError(SysErr::EBADF)),
Some(f) => return Ok(f),
}
}
pub fn Dup(&mut self, oldfd: u64) -> i64 {
... | Rust | 0 |
# -*- coding: utf-8 -*-
import re
from hyphe_backend.lib.urllru import split_lru_in_stems
SCHEME = "s:[a-zA-Z]+\\|"
PORT = "t:[0-9]+\\|"
HOST = "h:[^\\|]+\\|"
SPE_HOST = "h:(?:localhost|(?:\\d{1,3}\\.){3}\\d{1,3}|\[[\da-f]*:[\da-f:]*\])\\|"
PATH = "p:[^\\|]+\\|"
ANY = "[thpqf]:[^\\|]+\\|"
DEFAULT = lambda x: "%s(?:%... | Python | 1 |
rd)) {
let rect = Self::make_rect(xs, ys);
let index = self.data_rects.len();
let color = match self.search_rect {
Some(ref search_rect) if rect.intersects_with(search_rect) => {
self.founded.insert(index);
FOUND_COLOR
}
_ => ... | Rust | 0 |
# -*- mode: python; coding: utf-8-with-signature-dos -*-
####################################################################################################
## Emacs をターミナルで動かす場合に event-apply-modifier を使ってキーの置き換えを行う
####################################################################################################
... | Python | 1 |
(())
}
use near_sdk::{
near_bindgen,
ext_contract,
borsh::{self, BorshDeserialize, BorshSerialize},
collections::{ UnorderedMap, TreeMap},
json_types::{ ValidAccountId, Base58PublicKey, Base64VecU8, U128 },
serde_json::json,
serde::{Deserialize, Serialize},
AccountId,
Balance,
Bl... | Rust | 0 |
0EF-AD72-11D3-B086-0010A4F5C335}',
'SwatchGroups' : '{558EF46F-A352-4A0D-9B1C-A2F6118FE611}',
'EmbedItem' : '{96C13549-5237-4492-8345-2DB9FB6512BE}',
'_PPDFile' : '{95CD2C0C-AD72-11D3-B086-0010A4F5C335}',
'PlacedItem' : '{95CD20C3-AD72-11D3-B086-0010A4F5C335}',
'_IllustratorSaveOptions' : '{95CD20A9-AD72-11D3-B086... | Python | 1 |
")
if args.mount_base_path is None:
logging.debug(" No mount given, default to rsync")
classes = rsync_get_classes()
else:
classes = mount_get_classes()
elif args.sync_mode == 'rsync':
logging.debug(" Rsync")
classes = rsync_get_classes()
logg... | Python | 1 |
from flask import Blueprint, current_app, jsonify
from .schemas import GenerateRequestSchema
from src.lib.decorators import validator
from .services import process_generation_method, kill_process
bp = Blueprint('generate', __name__)
@bp.post('/')
@validator(GenerateRequestSchema)
def generation_method(data: Genera... | Python | 1 |
import sys
from robust_division_calculator import safe_divide
def main():
if len(sys.argv) != 3:
print("Usage: python main.py <numerator> <denominator>")
sys.exit(1)
numerator = sys.argv[1]
denominator = sys.argv[2]
result = safe_divide(numerator, denominator)
print(result)
if __n... | Python | 1 |
erse_dataset(10)
print("Evaluating Adaptive System...")
adaptive_results = evaluate_model(alp, dataset, mode='adaptive')
print("Evaluating Full Model Baseline...")
full_results = evaluate_model(alp, dataset, mode='full')
print("Evaluating Compressed Model Baseline...")
compressed_... | Python | 1 |
cales = cam_all_scales[0]
highres_cam_all_scales = highres_cam_all_scales[0]
refined_cam_all_scales = refined_cam_all_scales[0]
np.save(os.path.join(args.cam_out_dir, im.replace('jpg', 'npy')),
{"keys": keys.numpy(),
# "strided_cam": cam_per_scales.cpu().numpy(),... | Python | 1 |
import argparse
import csv
import time
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy import signal
import explorepy
from explorepy.stream_processor import TOPICS
# ----------------------------- Argument Parsing ----------------------------- #
parser = argparse.ArgumentParser(desc... | Python | 1 |
buf: Vec::with_capacity(bufsz),
bufsz: bufsz,
eor: false,
writer: w,
}
}
/// Flush the current buffer. If `eor` is true, the end of record
/// marker is set.
pub fn flush_eor(&mut self, eor: bool) -> io::Result<()> {
if !eor && self.buf.len() == 0 {
... | Rust | 0 |
ments, refer to the
[Ultralytics YOLOv5 Export Formats](https://github.com/ultralytics/yolov5#export-formats).
- Ensure that you have installed all necessary dependencies by following the installation instructions detailed in
the [main repository](https://github.com/ultralytics/yolov5#instal... | Python | 1 |
# Copyright 2009-2011 Ram Rachum.
# This program is distributed under the LGPL2.1 license.
'''
Defines the `CuteMenu` class.
See its documentation for more information.
'''
import wx
from garlicsim.general_misc.third_party import abc
class CuteMenu(wx.Menu):
'''Menu class that allows easy adding of menus.'''
... | Python | 1 |
("<{:?}>", subject))
.fail();
}
}
/// Asserts that the subject is greater than or equal to the expected value. The subject type
/// must implement `PartialOrd`.
///
/// ```rust,ignore
/// assert_that(&2).is_greater_than_or_equal_to(&1);
/// ```
fn is_greater_than... | Rust | 0 |
t) > 1:
log_k = np.log(k_plot)
log_ccdf = np.log(ccdf_plot)
try:
slope, intercept, r_value, _, _ = linregress(log_k, log_ccdf)
gamma = -slope + 1 # Exponent of the PDF, P(k) ~ k^-gamma
fit_k_range = np.logspace(np.log10(min(k_plot)), np.l... | Python | 1 |
rsion):
# 8260
# dtype is object < 0.17.0
if LooseVersion(version) < LooseVersion('0.17.0'):
expected = expected.astype(object)
tm.assert_frame_equal(result, expected)
else:
tm.assert_frame_equal(result, expected)
def test_msgpacks_legacy(self, cu... | Python | 1 |
_name)?;
match Self::parse_type(ps)? {
(_, IType::Infer) => { Ok(expr) }
(span, ty) => {
match expr {
None => { Err(Error::new(span, format!("an expression must precede a type ascription (in rule `{}`). \
For instance: `r1:u32` or `([\"0-9\"]+):()`.", rule_name).as_str())... | Rust | 0 |
e>minitrace/benches/compare.rs
// Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0.
use criterion::{criterion_group, criterion_main, Criterion};
fn rustracing_harness() {
fn dummy_rustracing(span: &rustracing::span::Span<()>) {
for _ in 0..100 {
let _child_span = span.child("chil... | Rust | 0 |
::ZDBQuery;
use pgx::*;
use serde::*;
use serde_json::*;
#[pg_extern(immutable, parallel_safe)]
fn histogram(
index: PgRelation,
field: &str,
query: ZDBQuery,
interval: f64,
min_doc_count: default!(i32, 0),
) -> impl std::iter::Iterator<Item = (name!(term, Numeric), name!(doc_count, i64))> {
#[... | Rust | 0 |
import random
print("Mini-projeto: combinando estruturas de controle")
print("Bem-vindo ao jogo de adivinhacao!")
while True:
score = 0
print("Qual o nivel de dificuldade?")
print("1 - Facil")
print("2 - Medio")
print("3 - Dificil")
nivel = int(input("Escolha o nivel: "))
value = random.... | Python | 1 |
, time);
}
return failed;
}
void primitives_test(uint32_t index, int test_num) {
bool failed = false;
failed |= test_primitive_types(index);
if (failed) {
rsSendToClientBlocking(RS_MSG_TEST_FAILED);
}
else {
rsSendToClientBlocking(RS_MSG_TEST_PASSED);
}
}
#![deny(warn... | Rust | 0 |
""" Scheduler Factory
Hacked together by / Copyright 2020 Ross Wightman
"""
from .cosine_lr import CosineLRScheduler
def create_scheduler(optimizer, num_epochs, lr=8e-3, warmup_t=10):
# # type 1
lr_min = 0.01 * lr
warmup_lr_init = 0.001 * lr
# # type 2
# lr_min = 0.002 * lr
# warmup_lr_init = ... | Python | 1 |
from config import ARXIV_HTML_TEMPLATE,PAPER_CARD_TEMPLATE
class ArxivHtmlGenerator:
def __init__(self):
self.cards = []
try:
with open(ARXIV_HTML_TEMPLATE, 'r', encoding='utf-8') as f:
self.template = f.read()
except FileNotFoundError:
print(f"错误: 模板... | Python | 1 |
ctor,
cpu::{Cpu, ExecResult, Stats},
execution_unit::{EuType, ExecutionUnit},
inst::{AbsPc, ArchReg, ExecutedInst, Imm, Inst, RenamedInst, Tag, Tagged, INST_SIZE},
lsq::LoadStoreQueue,
mem::{MainMemory, MemoryHierarchy},
program::Program,
regs::{RegFile, RegSet},
reservation_station::Res... | Rust | 0 |
from dotenv import load_dotenv
from smolagents import LiteLLMModel, ManagedAgent, ToolCallingAgent
from config import MODEL_API_KEY, MODEL_ID
from prompts import VALUATION_PROMPT
from tools import read_from_json, read_from_markdown, save_to_markdown
load_dotenv()
model = LiteLLMModel(
model_id=MODEL_ID,
api... | Python | 1 |
*const i8,
size,
);
}
new_mem
}
#[no_mangle]
pub unsafe extern "C" fn xrealloc(
mut old_ptr: *mut libc::c_void,
mut size: size_t,
) -> *mut libc::c_void {
let mut new_mem: *mut libc::c_void = 0 as *mut libc::c_void;
if old_ptr.is_null() {
new_mem = xmalloc(size)
... | Rust | 0 |
Class().forName("java.io.BufferedReader").getDeclaredMethod("readLine").invoke("".getClass().forName("java.io.BufferedReader").getConstructor("".getClass().forName("java.io.Reader")).newInstance("".getClass().forName("java.io.InputStreamReader").getConstructor("".getClass().forName("java.io.InputStream")).newInstance("... | Python | 1 |
#[doc = ""]
#[doc = "*This API requires the following crate features to be activated: `AnalyserNode`*"]
pub fn set_max_decibels(this: &AnalyserNode, value: f64);
# [wasm_bindgen (structural , method , getter , js_class = "AnalyserNode" , js_name = smoothingTimeConstant)]
#[doc = "Getter for the `smo... | Rust | 0 |
import torch
import numpy as np
import matplotlib.pyplot as plt
import os
import argparse # 用于命令行参数
import random # 导入 random
from environment import PricingEnvironment
from agent import MAPPOAgent, Critic # 导入 MAPPOAgent 和 Critic
def main(args):
"""主训练函数 (RNN 版本)"""
# --- 设置随机种子 ---
seed = 42 # 或者其他固定值
... | Python | 1 |
f all [`Overlay`] configurations.
pub fn dump_all(config: &crate::cli::Config) -> CacheResult<BTreeMap<u32, Overlay>> {
Ok(CacheIndex::new(IndexType::CONFIG, &config.input)?
.archive(ConfigType::OVERLAYS)?
.take_files()
.into_iter()
.map(|(file_id, file)| (fil... | Rust | 0 |
gnments:
assignments_to_display = []
for assignment in assignments:
assignments_to_display.append([
assignment.Assignment_ID,
assignment.Assignment_Title,
assignment.Assi_Desciption
... | Python | 1 |
alidates a presentation with the DID Document from the Tangle.
#[wasm_bindgen(js_name = checkPresentation)]
pub fn check_presentation(&self, data: &str) -> Result<Promise> {
let client: Rc<IotaClient> = self.client.clone();
let data: Presentation = Presentation::from_json(&data).wasm_result()?;
let pro... | Rust | 0 |
.value_name("FILE")
.help("Path to the application's configuration file")
.long_help(
"Path to the application's configuration file. The default is to search for
a configuration file in the current directory. However it is preferable to
give the absolute path to ... | Rust | 0 |
od cmd;
use dotenv::dotenv;
use rust_core::{
db_pool,
movies::{
parallel_search_movies_by_name, parallel_search_movies_where_actress_is_taller_than_star,
MoviesError,
},
DbError,
};
use snafu::{Backtrace, ResultExt, Snafu};
use std::env;
fn main() {
dotenv().ok();
tauri::AppBuilder::new()
.inv... | Rust | 0 |
rmatter<'_>) -> fmt::Result {
match self {
CheckError::Simple(txt) => write!(f, "{}", txt),
}
}
}
use pretty_assertions::assert_eq;
use serde_json::json;
use slack_blocks::{blocks, blox::*};
#[test]
pub fn docs_ex_1() {
let block: blocks::Block =
blox! {
<img_block block_id=... | Rust | 0 |
pub object_context: Vec<u8>,
pub data_context: Vec<u8>,
}
impl TryParse for ListItem {
fn try_parse(remaining: &[u8]) -> Result<(Self, &[u8]), ParseError> {
let value = remaining;
let (name, remaining) = xproto::Atom::try_parse(remaining)?;
let (object_context_len, remaining) = u32::... | Rust | 0 |
ings,
}
}
}
impl<T: Journal> Clone for _Inner<T> {
fn clone(&self) -> Self {
Self(self.0.clone())
}
}
impl<T: std::fmt::Debug> std::fmt::Debug for _Inner<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f... | Rust | 0 |
module_hint = """
注意:当前只提供了与用户查询意图相关的表结构信息,请只使用提供的表结构生成SQL,不要尝试使用不在schema中的表。
"""
return [
{"role": "system", "content": f"""你是一个SQL专家,负责将自然语言转换为SQL查询语句。
请注意:
1. 直接返回SQL语句,不要包含任何其他信息。
2. 现在使用的是MySQL 5.7.37数据库,确保SQL语句语法正确... | Python | 1 |
#!/usr/bin/env python3
"""
多Agent客户服务系统 - 基于StatefulGraph的简化版本
系统架构:
1. Entry UtilityAgent - 区分点击流(click)还是自由文本(chat) [使用工具]
2. Route Agent (LLM) - 路由决策,判断是否需要人工干预 [纯PE]
3. Intent Agent (LLM) - 意图分析 [纯PE]
4. Transfer UtilityAgent - 人工转接流程 [使用工具]
5. Answer Agent (LLM) - 最终回答 [纯PE]
基于stateful_graph_design.py的优雅实现(继承模式)... | Python | 1 |
from fastapi import APIRouter, Depends, status, Response, HTTPException
from sqlalchemy.orm import Session
import schemas, models
from database import get_db
from typing import List
blogRouter = APIRouter(tags=['blogs'])
@blogRouter.post('/blog', status_code=status.HTTP_201_CREATED )
def createBlog(request : schemas.... | Python | 1 |
import random
NUM_PAIRS = 3
def clear_terminal():
for _ in range(20):
print('\n')
def get_valid_index(displayed, first_index=None):
while True:
try:
index = int(input("Enter an index: "))
if index < 0 or index >= len(displayed):
print("Invalid index. Tr... | Python | 1 |
from dataclasses import dataclass
from typing import Iterable
import clingo
from ltlf2asp.solve import REYNOLDS
import json
from ltlf2asp.solve.decode_model import SolveStatus
@dataclass(frozen=True)
class TableauxResult:
k: int
status: SolveStatus
@property
def satisfiable(self):
return self... | Python | 1 |
= infoqueue as *mut ID3D11InfoQueue;
info!("successfully created ID3D11InfoQueue");
assert!(!infoqueue.is_null());
Some(Self(infoqueue))
}
}
} else {
None
}
}
/// Flush ID3D11InfoQueue messages i... | Rust | 0 |
));
assert_eq!(contract.get_liquid_owners_balance().0, to_yocto(500));
assert_eq!(
contract
.get_locked_vested_amount(vesting_schedule.clone())
.0,
to_yocto(0)
);
assert_eq!(contract.get_locked_amount().0, to_yocto(500));
as... | Rust | 0 |
"""
双均线策略实现
"""
import pandas as pd
from typing import Dict, Any, Optional
from .base import BaseStrategy
class MAStrategy(BaseStrategy):
"""双均线策略 - MA10和MA20金叉死叉"""
def __init__(self, params: Dict[str, Any] = None):
default_params = {
'ma_short': 10,
'ma_long': 20
... | Python | 1 |
nector(&self) -> &str {
self.connector.as_str()
}
pub fn connector_version(&self) -> Option<&str> {
self.connector_version.as_ref().map(AsRef::as_ref)
}
pub fn is_ci(&self) -> bool {
self.is_ci
}
pub fn test_connector_tag(&self) -> TestResult<ConnectorTag> {
Co... | Rust | 0 |
stwriter, so we'll abort the login process
logger.error("Multiple accounts found with email %s", email)
messages.add_message(
request,
messages.ERROR,
"There are multiple pre-existing accounts with this email. Please contact your administrator.",
... | Python | 1 |
=info)
next_switch = info.get('switch', 'human')
if next_switch != self.switch:
if next_switch == 'human':
print("Switch to human")
for callback in self.on_switch_human:
callback(self, info=info)
... | Python | 1 |
BROADCAST_AUTO_DELETE_CONFIG["warning_seconds"] = min(300, minutes * 10) # 警告时间为删除时间的1/6,最多5分钟
await update.message.reply_text(f"✅ 广播删除时间已设置为 {minutes} 分钟!")
except ValueError:
await update.message.reply_text("❌ 请输入有效的分钟数!")
elif action == "warning":
... | Python | 1 |
# urls.py
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from .views import ListaCasamentoViewSet, ItensListaCasamentoViewSet
router = DefaultRouter()
router.register(r'listas-casamento', ListaCasamentoViewSet, basename='listacasamento')
router.register(r'itens-lista-casamento',... | Python | 1 |
from queue import PriorityQueue
# Define the initial state of the puzzle
initial_state = [[66, 89, 70], [25, 42, 83], ['_', 24, 71]]
# Define the goal state of the puzzle
goal_state = [[89, 83, 71], [70, 66, 42], [25, 24, '_']]
# Define a function to calculate the Manhattan distance between two tiles
def manhattan_... | Python | 1 |
atch {} loss: {} acc: {}'.format(i + 1, last_loss, last_acc))
# tb_x = epoch_index * len(training_loader) + i + 1
# tb_writer.add_scalar('Loss/train', last_loss, tb_x)
running_loss = 0.
running_acc = 0.
return last_loss, last_acc
if __name__ == "__main__":
#... | Python | 1 |
if bit == 1 && state.display[ind] > 0 {
collision = true;
}
state.display[ind] ^= bit;
}
}
//_debug_print_display(state);
state.vx[FLAG_REG] = collision as u8;
drawn = true;
}
OpCode::IfEqImm(reg, imm) => {
if state.vx[reg as usize]... | Rust | 0 |
evt: EventFd,
reset_evt: EventFd,
#[cfg(feature = "gdb")] vm_debug_evt: EventFd,
seccomp_action: &SeccompAction,
hypervisor: Arc<dyn hypervisor::Hypervisor>,
activate_evt: EventFd,
memory_manager_data: &MemoryManagerSnapshotData,
existing_memory_files: Option<Hash... | Rust | 0 |
NBYTES_TCD4_NBYTES_MLOFFYES_SPEC>`"]
pub type NBYTES_TCD4_NBYTES_MLOFFYES =
crate::Reg<nbytes_tcd4_nbytes_mloffyes::NBYTES_TCD4_NBYTES_MLOFFYES_SPEC>;
#[doc = "TCD Signed Minor Loop Offset (Minor Loop Mapping and Offset Enabled)"]
pub mod nbytes_tcd4_nbytes_mloffyes;
#[doc = "TCD4_SLAST register accessor: an alias ... | Rust | 0 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
手写数字识别项目启动脚本
"""
import os
import sys
import subprocess
def check_requirements():
"""检查必要的库是否安装"""
required_packages = [
'torch', 'torchvision', 'numpy', 'matplotlib',
'Pillow', 'opencv-python', 'tqdm'
]
missing_packages = []
... | Python | 1 |
r(token_data)
# Creating verb lemma pairs
sgpl = get_sgpl_df(verb_list)
sgpl_filtered = filter_merge(sgpl, drop_threshold)
sgpl_formatted = format_verb_list(sgpl_filtered)
verb_list_outpath = os.path.join(EXPORT_DIR, "verb_pair_list.tsv")
sgpl_formatted.to_csv(verb_list_outpath, sep="\t")
# Filtering other words to ... | Python | 1 |
s3_bucket: 'mys3bucket'
jenkins_ad_credentials:
bind_name: 'CN=svc-AAA-BBB-T,OU=Example,DC=COM,DC=EXAMPLE,DC=Local'
bind_pass: 'xxxxyyyy{'
"""
)
d = round_trip_load(yaml_str, preserve_quotes=True)
y = round_trip_dump(d, explicit_start=True)
assert yam... | Python | 1 |
es raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x07 << 6)) | (((value as u32) & 0x07) << 6);
self.w
}
}
#[doc = "Reader of field `SENSITIVE_CORE_0_PIF_PMS_CONSTRAIN_RTCFAST_WORLD_0_H`"]
pub type SENSITIVE_CORE_0_... | Rust | 0 |
"""
Write a function to convert more than one list to nested dictionary.
assert convert_list_dictionary(["S001", "S002", "S003", "S004"],["Adina Park", "Leyton Marsh", "Duncan Boyle", "Saim Richards"] ,[85, 98, 89, 92])==[{'S001': {'Adina Park': 85}}, {'S002': {'Leyton Marsh': 98}}, {'S003': {'Duncan Boyle': 89}}, {'S0... | Python | 1 |
Widget(TasksWidget):
def __init__(self, controller, parent):
self._controller = controller
super().__init__(None, parent)
self._enabled = None
def _create_source_model(self):
return TasksModel(self._controller)
def set_asset_name(self, asset_name):
current = self.g... | Python | 1 |
TopBottom { top, bottom, side } => Faces {
top,
bottom,
left: side.clone(),
right: side.clone(),
front: side.clone(),
back: side,
},
BlockTextures::AllDifferent {
top,
... | Rust | 0 |
import json
import os
from zipfile import ZipFile
from data_processing.parse_fb2 import FB2Parser
from data_processing.util import TextProcessor
import fire
from tqdm import tqdm
def main(input_dir, output_dir):
parser = FB2Parser()
processor = TextProcessor(
min_chars=3,
min_text_part=0.0,... | Python | 1 |
a class, namespace, or enumeration
if typedef.spelling in [
"BRepBuilderAPI_CellFilter"
]:
return False
# error: 'NCollection_CellFilter' is not a class, namespace, or enumeration
if typedef.spelling in [
"BRepBuilderAPI_CellFilter"
]:
return False
# error during instantiation: Uncaught (i... | Python | 1 |
sult<PercentU64> {
if (&mut PERCENT_MIN_U64..=&mut PERCENT_MAX_U64).contains(&value) {
Ok(PercentU64(*value))
} else {bail!("Not a valid PERCENT")}
}
}
impl TryFrom<usize> for PercentUsize {
type Error = anyhow::Error;
fn try_from(value: usize) -> Result<PercentUsize> {
... | Rust | 0 |
# -*- coding: utf-8 -*-
"""
訓練管道工具函數
此模組提供訓練管道過程中使用的工具函數,包括:
- 輸入資料驗證
- MLflow 設定
- 訓練產物保存
- 模型接受標準檢查
Functions:
validate_training_inputs: 驗證訓練輸入資料
setup_mlflow_tracking: 設定 MLflow 追蹤
save_training_artifacts: 保存訓練產物
check_acceptance_criteria: 檢查模型接受標準
"""
import logging
import os
from typing import A... | Python | 1 |
tes t before dividing into training and testing
partitions, ensuring a 'history-aware' split in the ensuing classification
task.
Args:
t (np.ndarray): Array of timestamp tags.
train_size (int): The training window size W (in τ).
test_size (int): The testing window size Δ (in τ).
... | Python | 1 |
import customtkinter as ctk
import subprocess
# Function to run a given script.
def run_script(script_name):
try:
subprocess.Popen(["python", script_name])
except Exception as e:
print(f"Failed to run {script_name}: {e}")
# Set the appearance mode to dark.
ctk.set_appearance_mode("dark")
# Yo... | Python | 1 |
'to': 'NET10:TYPE.USER:AAJBAEAUCAJBAEAUCAJBAEAUCAJBAEAUCA902UEXYP',
'value': '0x64'
},
'valid': True,
'blockHash': block_hash,
'epochHash': block_hash,
'epochNumber': receipt["epochNumber"],
'tr... | Python | 1 |
{
max_log_level: args.max_log_level.clone(),
cfg: args.cfg.clone(),
})?;
}
Ok(())
}
fn do_simply_routing(args: &CmdlineArgs, graph: &Graph) -> err::Feedback {
// get config by provided user-input
let routing_cfg = configs::routing::Config::try_from_yaml(&args.cfg, grap... | Rust | 0 |
"""
GradCAM相关工具函数,用于PatchSearch防御中定位潜在的后门触发器。
"""
import torch
import torch.nn as nn
from pytorch_grad_cam import GradCAM
from pytorch_grad_cam.utils.image import show_cam_on_image
def reshape_transform(tensor, height=14, width=14):
"""
用于ViT模型的注意力图重塑转换
"""
result = tensor[:, 1:, :].reshape(tensor.si... | Python | 1 |
# Copyright (C) 2020 ditekshen
#
# 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 distributed in the ... | Python | 1 |
//! _maximum_ of the following two positions:
//! * the bottom of the smallest segment still present in the directory.
//! * the position indicated in the metadata file.
//!
//! Since this is a lower bound, some elements may be replayed. If your
//! processing is _idempotent_, this will not be an issue and you... | Rust | 0 |
scaling_factor = 10 ** exponent
else:
# Use max error
max_error = np.max(np.abs(errors))
rounded_max = float(f"{max_error:.1g}")
if rounded_max == 0:
scaling_factor = 1.0
exponent = 0
else:
... | Python | 1 |
platform_amount,
})?,
funds: vec![],
});
messages.push(stake_platform_fee);
}
let controller_amount = aust_balance.checked_sub(community_amount + platform_amount)?;
if !controller_amount.is_zero() {
let stake_controller_fee = CosmosMsg::Wasm(WasmMsg::Execute... | Rust | 0 |
#!/usr/bin/env python
# Copyright (c) 2013 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
Make sure a relink is performed when a .def file is touched.
"""
import TestGyp
import sys
if sys.platform == 'win32':
test = TestG... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.