text string | label_name string | labels int64 |
|---|---|---|
{AcpiDevice, AcpiResult, PCIInterruptSource};
use crate::devices::io_apic::IOAPIC;
use crate::interrupts;
use crate::lock::OnceCell;
use crate::structures::HashMap;
static INT_ASSIGNMENTS: OnceCell<HashMap<PCIAddress, [InterruptAssignment; 4]>> = OnceCell::new();
/// Enumeration for the four PCI interrupt pins.
#[der... | Rust | 0 |
"""
Project #7: Insta Media Grabber API
Generated from centralized projects data
"""
from datetime import datetime
from django.conf import settings
from apps.data.about.skills_data import SkillsData
# Project data for: Insta Media Grabber API
project_data = {
# Identity
"id": 7,
"title": "Insta Media Grab... | Python | 1 |
#!/usr/bin/env python3
"""
Quick test script for OpenAI-compatible Kyutai TTS API
Tests the proper Python API integration (following Colab notebook approach)
"""
from openai import OpenAI
import time
import requests
def test_api():
print("🧪 Testing OpenAI-compatible Kyutai TTS API")
print("Using proper Kyuta... | Python | 1 |
])
.expect("should be able to serialize a FullViewingKey");
result
}
}
#[cfg(any(test, feature = "test-dependencies"))]
pub mod testing {
use proptest::collection::vec;
use proptest::prelude::{any, prop_compose};
use crate::{
sapling::PaymentAddress,
zip32::{Extende... | Rust | 0 |
xtern crate getopts;
extern crate libc;
use std::io;
use std::num::Int;
use std::char;
#[path = "../common/util.rs"]
mod util;
static NAME: &'static str = "split";
static VERSION: &'static str = "1.0.0";
pub fn uumain(args: Vec<String>) -> int {
let opts = [
getopts::optopt("a", "suffix-length", "use su... | Rust | 0 |
config.camera_far,
}.into()
}
/// Build the geometry to render.
/// Returns vertices and indices.
fn build_geometry(config: &AppConfig) -> (Vec<Vertex>, Vec<u16>) {
// Build a tube (prism).
let mut vertices = vec![];
let mut indices = vec![];
for i in 0..config.num_components {
// X simply ... | Rust | 0 |
# pylint: disable=invalid-name
'''
Example of nested ArrayList and passing empty tuple/list to Java functions.
'''
from __future__ import unicode_literals, print_function
from jnius import autoclass, cast # pylint: disable=import-error
String = autoclass('java.lang.String')
List = autoclass('java.util.List')
Arrays ... | Python | 1 |
color="navy",
lw=2,
linestyle="--",
figure=fig,
)
return fig, title
class AUROC(AnomalibMetric, _AUROC): # type: ignore[misc]
"""Wrapper to add AnomalibMetric functionality to AUROC metric.
This class wraps the internal ``_AUROC`` metric to make it comp... | Python | 1 |
# python ../makepore.py 8
import mstool
d = mstool.ReadMartini('topol.top', define={'POSRES_Z': 'True', 'POSRES_XYZ': 'True'})
mstool.GMX2DMS('P008.pdb', d, 'P008.dms')
mstool.getGMXEnergy('P008.pdb', p='topol.top', add='-nt 1')
mstool.getDMSEnergy('P008.dms', nonbondedMethod='CutoffNonPeriodic')
mstool.runMartiniEM(... | Python | 1 |
alidation_magnifs = []
test_magnifs = []
self.parse_split_data(Split.TRAIN, training_magnifs)
self.parse_split_data(Split.VALID, validation_magnifs)
self.parse_split_data(Split.TEST, test_magnifs)
if __name__ == '__main__':
args = parse_args()
if args.name.lower() in ['breast_... | Python | 1 |
在children[i].key之中
} else if idx_key + (*children[i]).key.len() > key.len() {
let keep = children[i];
children[i] = Box::into_raw(Box::new(Node {
key: key[idx_key..key.len()].to_vec(),
... | Rust | 0 |
#!/usr/bin/env python3
"""Test how server handles unknown or additional MCP methods"""
import subprocess
import json
import time
def send_and_receive(proc, request):
"""Send request and get response"""
req_str = json.dumps(request) + '\n'
proc.stdin.write(req_str.encode())
proc.stdin.flush()
# Gi... | Python | 1 |
from datetime import datetime, timedelta
from airflow import DAG
from airflow.operators.bash_operator import BashOperator
from airflow.contrib.operators.dataproc_operator import (
DataprocClusterCreateOperator,
DataProcPySparkOperator,
DataprocClusterDeleteOperator,
)
# Define default arguments for t... | Python | 1 |
= buffer.into();
let genesis:Block = block::generate_genesis_block(&b);
let genhash:H256 = genesis.hash();
let mut chainmap:HashMap<H256,Block> = HashMap::new();
let mut heightsmap:HashMap<H256,u8> = HashMap::new();
let buffermap:HashMap<H256,Block> = HashMap::new();
cha... | Rust | 0 |
if group is None:
group = _get_global_gloo_group() # use CPU group by default, to reduce GPU RAM usage.
world_size = dist.get_world_size(group)
if world_size == 1:
return [data]
output = [None for _ in range(world_size)]
dist.all_gather_object(output, data, group=group)
return... | Python | 1 |
impl ACCTEIER {
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
#[doc = r" Value of the field a... | Rust | 0 |
# -*- coding: utf-8 -*-
import html
import os
import re
import sys
import unicodedata
from typing import List, Dict, Match
from flask import request, session
from werkzeug.datastructures import FileStorage
from lexos.helpers import constants as constants, \
general_functions as general_functions
from lexos.helper... | Python | 1 |
# 使用卡尔曼滤波处理uwb得到的位置数据,实现更精确的定位
import numpy as np
# 初始化状态向量和协方差矩阵
x = np.array([0, 0, 0, 0]) # 初始位置和速度
P = np.eye(4) # 初始协方差矩阵
# 状态转移矩阵
dt = 0.02 # 时间间隔,1秒更新50次
F = np.array([
[1, dt, 0, 0],
[0, 1, 0, 0],
[0, 0, 1, dt],
[0, 0, 0, 1]
])
# 观测矩阵
H = np.array([
[1, 0, 0, 0],
[0, 0, 1, 0]
])
... | Python | 1 |
def roi_pooling(self):
batch_ids = tf.squeeze(tf.slice(self._rois, [0, 0], [-1, 1], name="batch_id"), [1])
# 获取包围框归一化后的坐标系(坐标与原图比例)
bottom_shape = tf.shape(self.feature_map)
height = (tf.to_float(bottom_shape[1]) - 1.) * tf.to_float(16) # TODO:
width = (tf.to_float(bottom_shape... | Python | 1 |
header = "##### :gitlab_icon: GitLab Event"
summary_message = """##### :gitlab_icon: GitLab Daily Summary \n\n"""
no_development_message = "\tNo development has been done today."
push_message = header + """
- Event name: **Push**
- User Name: {}
- Project: {} - [{}]({})
- Project Namespace: {}
- Branch: ```{}```
- B... | Python | 1 |
import fipy
import numpy as np
from amigo.pyplot import plt
from scipy.interpolate import RectBivariateSpline
C = [0.9, 0.0]
R = [0.005, 5]
Z = [-2, 2]
nr = 2500
nz = 4
dr = np.diff(R)[0] / (nr - 1)
dz = np.diff(R)[0] / (nz - 1)
origin = ((R[0],), (-2,))
mesh = {}
mesh["rz"] = fipy.CylindricalGrid2D(nr=nr, dr=dr, n... | Python | 1 |
ast::PointerType::Scalar(t), space),
ast::Type::Vector(t, len) => {
ast::Type::Pointer(ast::PointerType::Vector(t, len), space)
}
ast::Type::Array(t, _) => ast::Type::Pointer(ast::PointerType::Scalar(t), space),
ast::Type::Pointer(ast::PointerType::Sc... | Rust | 0 |
, that small outliers
/// won't increase the standard deviation too much.
/// The more points we add and the more slopes we add, the more resilient to outliers the result
/// will become. That's also why we don't only take into account the slopes between neighboring
/// points (`A-B`, `B-C`, `C-D`), but the slopes betw... | Rust | 0 |
import os
from PIL import Image, ImageOps
# Settings
TARGET_SIZE = (300, 300) # Final size for the image
x1, y1, x2, y2 = 50, 50, 200, 200 # Crop coordinates (adjust as needed)
# Asking the user for the folder
folder = input("Please enter one of the folders (e.g., EnglishAlphabet, PersianNumbers, Symbols): ")
# Ch... | Python | 1 |
icationid, offloadingpolicyid, 0, local_deviceid, tmptask)
print("发送第一个任务成功 应用编号{0} 请求设备编号{1} 调度策略编号{2}".format(
applicationid, requestdeviceid, offloadingpolicyid
))
if __name__ == "__main__":
# controle()
# for i in range(6):
# controle_deep_learning(3, 1, i+1) # more true
# ... | Python | 1 |
# -*- coding: utf-8 -*-
# @Author: Haozhe Xie
# @Date: 2019-08-08 14:31:30
# @Last Modified by: Haozhe Xie
# @Last Modified time: 2020-05-25 09:13:32
# @Email: cshzxie@gmail.com
import logging
import open3d
from extensions.chamfer_dist import ChamferDistance
class Metrics(object):
ITEMS = [{
'name'... | Python | 1 |
"""Block to fix annotation of verbs that are currently treated as copulas
but they should be treated as normal verbs (with secondary predication)
instead."""
from udapi.core.block import Block
import re
class FixPseudoCop(Block):
def __init__(self, lemmas, noncopaux=False, **kwargs):
"""Create the u... | Python | 1 |
imizer,
iterator=iterator,
train_dataset=train_dataset,
validation_dataset=dev_dataset,
patience=10,
num_epochs=10)
trainer.train()
# Run predictor for a sample sentence
predictor = UniversalPOSPre... | Python | 1 |
"""
This sample module contains features logic that can be used to generate and populate tables in Feature Store.
You should plug in your own features computation logic in the compute_features_fn method below.
"""
import pyspark.sql.functions as F
from pyspark.sql.types import FloatType, IntegerType, StringType, Times... | Python | 1 |
}
#[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 << 24)) | ((value as u32 & 0x01) << 24);
self.w
}
}
#[doc = "Field `HOST_GPIO_SDIO_INT_CLR` writer - "]
pub struct HOST_GPIO_SDIO_INT_CLR_W<'a>... | Rust | 0 |
import base64
import json
import httpx
def refresh_token(client_id, region, domain, refresh_token):
url = f"https://{domain}.auth.{region}.amazoncognito.com/oauth2/token"
body = {
"grant_type": "refresh_token",
"refresh_token": refresh_token,
"client_id": client_id,
}
headers ... | Python | 1 |
[i32;5] =[1,2,3,4]; // fails because the length of array doesn't match the lenght of assigned values
// let numbers: [i32;5] =[1,2,3,4, 'a']; // fails because the not all data types are consistent in assignment
println!("Arrays take {} less bytes then vectors", mem::size_of_val(&numbers)-mem::size_of_val(&arra... | Rust | 0 |
输入 y 或 n{Style.RESET_ALL}")
elif auto_use:
# 已启用自动使用
print(f"{Fore.CYAN}{EMOJI['INFO']} 自动使用已保存的账号:{email}@2925.com{Style.RESET_ALL}")
# 设置原始邮箱地址
self.email_address = f"{email}@2925.com"
return self.verify_and_setup_email(email,... | Python | 1 |
<reponame>tildecoin/rtcoin
//
// rtcoin - Copyright (c) 2019 <NAME> (gbmor)
// See LICENSE file for detailed license information.
//
extern crate test;
use crate::db::*;
use crate::query;
use std::{fs, sync::mpsc, thread};
// This test needs to be broken up
#[test]
fn worker_thread_spawn_send_recv_query_rows() {
... | Rust | 0 |
"Yamaha",
"Yamahata",
"Yamakage",
"Yamakawa",
"Yamakazi",
"Yamamoto",
"Yamamura",
"Yamana",
"Yamanaka",
"Yamane",
"Yamanouchi",
"Yamanoue",
"Yamaoka",
"Yamasaki",
"Yamashita",
"Yamato",
"Yamauchi",
"Yamawaki",
"Yamazaki",
"Yamhata",
"Yamur... | Rust | 0 |
ir_asset(
conn: Option<Connection<Cache>>,
id: &str,
subdir: String,
sub2dir: &str,
sub3dir: &str,
filename: &str,
) -> Result<(ContentType, Vec<u8>), Option<NamedFile>> {
let compound_name = subdir + "/" + sub2dir + "/" + sub3dir + "/" + filename;
assemble_paper_asset_with_cache(conn, None, id, &compou... | Rust | 0 |
п сегодня"},
'top_today_title': {'uz': "🏆 Bugungi TOP referlar:", 'ru': "🏆 Топ рефералов за сегодня:"},
'no_top': {'uz': "📭 Hali ma'lumot yo'q.", 'ru': "📭 Пока нет данных."},
'reward_unlocked': {
'uz': "🎉 Tabriklaymiz! Siz {n} konversiyaga yetdingiz va bonus PROM oldingiz:\n\n{content}",
... | Python | 1 |
ssage));
assert_eq!(
native(process, timer_reference, options(process)),
Ok(Atom::str_to_term("ok"))
);
// again before timeout
assert_eq!(
native(process, timer_reference, options(process)),
Ok(Atom::str_to_term("ok"))
);
... | Rust | 0 |
: seed the local rng here.
let mut h_arr = MemArray2d::<f32>::zeros(shape);
{
let dist = Uniform::new_inclusive(lo, hi);
let mut v = h_arr.as_view_mut();
let xs = v.flat_slice_mut().unwrap();
for x in xs.iter_mut() {
*x = dist.sample(&mut thread_rng());
}
... | Rust | 0 |
class Solution:
def minNumberOperations(self, target: List[int]) -> int:
n = len(target)
ans = target[0]
for i in range(1,n):
ans += max(0,target[i]-target[i-1])
return ans | Python | 1 |
:
model = _resnet(architecture, BasicBlock, [3, 4, 6, 3], pretrained, True)
elif architecture=='resnet50':
model = _resnet(architecture, Bottleneck, [3, 4, 6, 3], pretrained, True)
elif architecture=='resnet101':
model = _resnet(architecture, Bottleneck, [3, 4, 23, 3], pretrained, True)
... | Python | 1 |
# Copyright (C) PyZMQ Developers
# Distributed under the terms of the Modified BSD License.
import zmq
from zmq.green import Poller
def device(device_type, isocket, osocket):
"""Start a zeromq device (gevent-compatible).
Unlike the true zmq.device, this does not release the GIL.
Parameters
--------... | Python | 1 |
m::backend::ApplyBackend;
use types::{H160, H256, U256};
#[cfg(test)]
mod test;
/// Unique module name.
const MODULE_NAME: &str = "evm";
/// State schema constants.
pub mod state {
use super::{storage, H160};
/// Prefix for Ethereum account code in our storage (maps H160 -> Vec<u8>).
pub const CODES: &[... | Rust | 0 |
num=1
n=5
spaces=2
stars=1
for line in range(n//2+1):
print(' '*spaces+str(num)*stars)
num+=1
spaces-=1
stars+=2
num=4
stars=n-2
spaces=1
for line in range(n//2):
print(' '*spaces+str(num)*stars)
num+=1
spaces+=1
stars-=2 | Python | 1 |
from install_requirements import install_packages_from_requirements
install_packages_from_requirements()
import paramiko
from scp import SCPClient
from pathlib import Path
def create_ssh_client(server, user):
client = paramiko.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_polic... | Python | 1 |
import argparse
from processing.audio_handler import AudioHandler
from processing.spectrogram_handler import SpectrogramHandler
from processing.inference_handler import InferenceHandler
from model_runner.base import ModelRunner
import sounddevice as sd
import time
import threading
def parse_arguments():
parser = a... | Python | 1 |
# Joshua Jackson
# Problem: 26. Remove Duplicates from Sorted Array
# url: https://leetcode.com/problems/remove-duplicates-from-sorted-array/
# Language: Python
# Difficulty: Easy
"""
Description:
Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element... | Python | 1 |
munoprot::ig_like::kir_ligand::{KirLigandMap, LigandMotif};
use immunoprot::mhc::hla::ClassI;
use netmhcpan::result::{BindingData, BindingInfo};
use log::{debug, warn};
use rayon::prelude::*;
use serde::{Deserialize, Serialize};
/* FS */
/// Represents the motif positions to be used for calculating fraction of share... | Rust | 0 |
"""
Simple test for bidirectional matching with existing profiles
"""
import asyncio
import sys
import os
# Add the app directory to the Python path
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
from sqlalchemy.orm import Session
from app.db.database import SessionLocal
from app.models.user import User,... | Python | 1 |
elf.unrotate(x) #4 96 100 100 -> 1 384 100 100
x0 = F.leaky_relu_(self.nin_A(x), negative_slope=0.1)
x0 = F.leaky_relu_(self.nin_B(x0), negative_slope=0.1)
x0 = self.nin_C(x0)
# Unsquare
if(H > W):
diff = H - W
x0 = x0[:, :, 0:H, (diff // 2):(dif... | Python | 1 |
import math
import numpy as np
import pandas as pd
import plotly.express as px
import pickle
import seaborn as sns
import matplotlib.pyplot as plt
import os
from LinearRegression import LinearRegression
def compute_cost(self, predictions):
m = len(predictions)
cost = np.sum(np.square(predictions - self.y)) /... | Python | 1 |
// 5. Return an implementation-approximated value representing the result of the inverse hyperbolic cosine of ℝ(n).
.acosh()
.into())
}
/// Get the arcsine of a number.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
... | Rust | 0 |
// Input
3 => {
let a1 = self.get_address(pm1, 1);
self.program[a1 as usize] = inputs[input_idx];
input_idx += 1;
self.pc += 2;
}
// Output
4 => {
l... | Rust | 0 |
lf, AttachMode):
self._AttachMode = AttachMode
def _deserialize(self, params):
self._DeleteWithInstance = params.get("DeleteWithInstance")
self._RenewFlag = params.get("RenewFlag")
self._DiskType = params.get("DiskType")
self._DiskState = params.get("DiskState")
sel... | Python | 1 |
:X509_VERIFY_PARAM_clear_flags(
self.as_ptr(),
flags.bits,
))
.map(|_| ())
}
}
/// Gets verification flags.
///
/// This corresponds to [`X509_VERIFY_PARAM_get_flags`].
///
/// [`X509_VERIFY_PARAM_get_flags`]: https://www.openssl.o... | Rust | 0 |
0x00, fmSpecialEffectFlat
pub special_effect: SpecialEffect,
/// A signed integer that specifies the magnification of embedded controls, in percentage points of the size of the parent control. MUST be greater than or equal to 10 (10 percent of actual size) and less than or equal to 400 (four times or 400 percen... | Rust | 0 |
lsn,
TEST_IMG(&format!("foo blk 0 at {}", lsn)),
)?;
writer.advance_last_record_lsn(lsn);
}
tline.checkpoint(CheckpointConfig::Forced)?;
{
let writer = tline.writer();
lsn += 0x10;
writer.put_page_image(
... | Rust | 0 |
import re
with open('input3.txt') as handle:
text = handle.readlines()
print(text[0])
print(text[-1])
text_3= '''467..114..
...*......
..35..633.
......#...
617*......
.....+.58.
..592.....
......755.
...$.*....
.664.598..'''.split()
symbolLocations = []
for i, row in enumerate(text):
row = row.strip()
... | Python | 1 |
for ex, old_exon in temp[::-1]:
e = Exon(
len(s) - ex.end + 1,
len(s) - ex.start + 1,
intact_start_splice=ex.end_splice_site.intact,
intact_end_splice=ex.start_splice_site.intact,
strand=STRAND.POS,
... | Python | 1 |
ovznz_u64(out1: &mut u64, arg1: fiat_p448_u1, arg2: u64, arg3: u64) -> () {
let x1: fiat_p448_u1 = (!(!arg1));
let x2: u64 = ((((((0x0 as fiat_p448_i2) - (x1 as fiat_p448_i2)) as fiat_p448_i1) as fiat_p448_i128) & (0xffffffffffffffff as fiat_p448_i128)) as u64);
let x3: u64 = ((x2 & arg3) | ((!x2) & arg2));
*ou... | Rust | 0 |
self.org_name.clone(),
repo_name.to_owned(),
count_prs.to_string(),
count_issues.opened.to_string(),
count_issues.closed.to_string(),
self.start_date.to_string(),
self.end_date.to_string(),
])
... | Rust | 0 |
24 231 463
[22:09:13 14:03:49 INFO] 03691459 loudspeaker 1134 161 323
[22:09:13 14:03:49 INFO] 04090263 rifle 1661 237 474
[22:09:13 14:03:49 INFO] 04256520 sofa 2222 317 634
[22:09:13 14:03:49 INFO] 04379243 table 5958 850... | Python | 1 |
redirected to stdout.
";
static NOHUP_OUT: &str = "nohup.out";
// exit codes that match the GNU implementation
static EXIT_CANCELED: i32 = 125;
static EXIT_CANNOT_INVOKE: i32 = 126;
static EXIT_ENOENT: i32 = 127;
static POSIX_NOHUP_FAILURE: i32 = 127;
mod options {
pub const CMD: &str = "cmd";
}
pub fn uumain(ar... | Rust | 0 |
# 10 - Classificação de Notas:
# Crie um programa que solicite uma nota de 0 a 100
# e informe o conceito (A, B, C, D, F) com base na nota.
while True:
n = intInput('Digite a nota: ')
if n | Python | 1 |
// Relative paths with Command are undefined.
if minetest_command.is_relative() {
let mut absolute_path = std::env::current_dir().unwrap();
absolute_path.push(minetest_command);
minetest_command = absolute_path;
}
}
}
if !minetest_... | Rust | 0 |
_parameters_bias_"
shape = [2048]
dtype = "torch.float32"
device = "cuda:0"
mean = 0.000
std = 0.000
data = None
class Program_weight_tensor_meta_L_self_modules_transformer_modules_h_modules_3_modules_mlp_modules_c_proj_parameters_weight_:
name = "L_self_modules_transformer_modules_h_modul... | Python | 1 |
か」を数値で評価する
pj = probe_json(path) or {}
fmt = pj.get("format") or {}
streams = pj.get("streams") or []
dur_total = duration_from_probe(pj)
def _flt(x):
try: return float(x)
except: return None
fmt_start = _flt(fmt.get("start_time")) or 0.0
v_start = None
a_start = None
... | Python | 1 |
}, room-type+bd: mean accuracy {:.4}'.format(np.nanmean(acc[:7]), (
np.nansum(acc[:7]) + np.nansum(acc[-2:])) / 9.))
for t in range(0, acc.shape[0]):
if t not in [7, 8]:
print('room type {}th, accuracy = {:.4}'.format(t, acc[t]))
print('*' * 60)
# per-class IU, avoid div zer... | Python | 1 |
# Copyright (c) 2022-2024, The Isaac Lab Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Script to run an environment with zero action agent."""
"""Launch Isaac Sim Simulator first."""
import argparse
from omni.isaac.lab.app import AppLauncher
# add argparse arguments
parser... | Python | 1 |
"""
pygments.lexers._luau_builtins
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Includes the builtins for Luau and Roblox.
:copyright: Copyright 2006-2024 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
LUAU_BUILTINS = {
'bit32',
'buffer',
'coroutine',
'debug',
'math',
'os'... | Python | 1 |
developer.android.com/reference/android/net/nsd/NsdManager.html#FAILURE_INTERNAL_ERROR)
pub const FAILURE_INTERNAL_ERROR : i32 = 0;
/// public static final [FAILURE_MAX_LIMIT](https://developer.android.com/reference/android/net/nsd/NsdManager.html#FAILURE_MAX_LIMIT)
pub const FAILURE_MAX_LIMIT ... | Rust | 0 |
iszfeld algorithm.
/// Reducing the target set.
pub fn wr_median<T>(set:&[T]) -> f64
where T: Copy,f64:From<T> {
let n = set.len();
match n {
0 => panic!("{} empty vector!",here!()),
1 => return f64::from(set[0]),
2 => return f64::from(set[0])+f64::from(set[1])/2.0,
_ => {}
... | Rust | 0 |
from django.shortcuts import render
from books_app.models import Book
from django.db.models import Q, Avg
# Create your views here.
def book_list(request):
# books = Book.objects.all()
# books = Book.objects.filter(title = "The Silent Grove")
# book = Book.objects.get(title = "The Silent Grove")
# ... | Python | 1 |
# -*- coding: utf-8 -*-
"""
交易績效指標
此模組實現交易相關的績效指標計算,包括:
- 夏普比率 (Sharpe Ratio)
- 索提諾比率 (Sortino Ratio)
- 卡爾馬比率 (Calmar Ratio)
- 年化收益率計算
- 總收益率計算
Functions:
calculate_sharpe_ratio: 計算夏普比率
calculate_sortino_ratio: 計算索提諾比率
calculate_calmar_ratio: 計算卡爾馬比率
calculate_annual_return: 計算年化收益率
calculate_tota... | Python | 1 |
0x0002 => Ok(self.reg_serial_control = value),
0x0011 => Ok(self.reg_sound_channel_1_wave_pattern_length = value),
0x0012 => Ok(self.reg_sound_channel_1_volume_envelope = value),
0x0024 => Ok(self.reg_sound_channel_volume_control = value),
0x0025 => Ok(self.r... | Rust | 0 |
box_area": float(bbox_area),
"coverage_ratio": float(coverage_ratio),
"compactness": float(compactness),
"quality_score": float(coverage_ratio / max(compactness, 1.0)),
}
def format_coco_results(
self, predictions: List[Dict[str, any]], image_id: int
) -> Lis... | Python | 1 |
;
let infilename = format!("{}/testdata/{}",basedir, "unused_samples_1f.mod");
let module = load_module(infilename)?;
let unused = module.find_unused_samples();
assert!(unused.len() == 1);
assert!(unused[0] == 0x1f);
Ok(())
}
#[test]
fn test_remove_unused_samples_all_used() -> Result<(),PTMFError> {
... | Rust | 0 |
{'component': 'VChip', 'props': {'size': 'small', 'variant': 'outlined', 'color': 'amber-darken-2', 'class': 'mr-2'}, 'text': f'鸡腿 {coin}'},
{'component': 'VChip', 'props': {'size': 'small', 'variant': 'outlined', 'class': 'm... | Python | 1 |
import re
import json
from eval.extracter.extracter import Extracter
class KGExtracter(Extracter):
def __init__(self, language="zh", NAN="NAN", prefix="输入中包含的关系三元组是:\n", Reject="No relation triples found."):
super().__init__(language, NAN, prefix, Reject)
def post_process(self, result):
... | Python | 1 |
fn get_tile_at(&self, x: usize, y: usize) -> Option<&Tile> {
// Note: The map repeats horizontally, which we can emulate with x %/
self.tiles.get(y * self.width + x % self.width)
}
}
#[derive(Debug)]
struct MapParsingError;
impl Error for MapParsingError {}
impl std::fmt::Display for MapParsing... | Rust | 0 |
n] for token in tokens])
text = bytearray([self.byte_decoder[c] for c in text]).decode('utf-8', errors="replace").replace('</w>', ' ')
return text
def tokenize(self, text):
tokens = []
text = whitespace_clean(basic_clean(text)).lower()
for token in re.findall(self.pat, text)... | Python | 1 |
#!/usr/bin/env python
"""Grab all SciTools modules and make .txt files for sphinx."""
import os, glob
scitools_dir = os.path.join(os.pardir, os.pardir, os.pardir, 'lib', 'scitools')
easyviz_dir = os.path.join(scitools_dir, 'easyviz')
this_dir = os.getcwd()
os.chdir(scitools_dir)
modules_scitools = glob.glob('*.py')
os... | Python | 1 |
_resblocks
n_feats = n_feats
kernel_size = 3
reduction = reduction
scale = scale[0]
act = nn.ReLU(True)
# RGB mean for DIV2K
rgb_mean = (0.4488, 0.4371, 0.4040)
rgb_std = (1.0, 1.0, 1.0)
self.sub_mean = MeanShift(rgb_range, rgb_mean, rgb_std)
... | Python | 1 |
"provider": self.provider,
"streams": [stream.as_dict for stream in self.streams],
"subtitles": [subtitle.as_dict for subtitle in self.subtitles]
}
def __repr__(self) -> str:
return f"ProviderResponse(provider='{self.provider}', streams={self.streams}, subtitles={self.sub... | Python | 1 |
del error on model {}: {} ({}%)",
trained_model.model_max_error_idx,
trained_model.model_max_error,
trained_model.model_max_error as f64 / num_rows as f64 * 100.0
);
if !matches.is_present("no-code") {
if matches.is_present("zero-build-time") {
... | Rust | 0 |
msk_r;
#[doc = "Message interface 1 mask 1\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#r... | Rust | 0 |
x40 | 0x42 bytes)
/// - Ed25519: Public point A, compressed (0x20 bytes)
///
/// In particular note that in the case of e.g. ECDSA public keys, many
/// libraries will expect a 0x04 (DER OCTET STRING) tag byte at the
/// beginning of the key. The YubiHSM does not return this, so you may
/// need... | Rust | 0 |
# -*- coding: utf-8 -*-
# Created on 2018-08-15
# author: 欧度智能,https://www.odooai.cn
# email: 300883@qq.com
# resource of odooai
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl).
# Odoo在线中文用户手册(长期更新)
# https://www.odooai.cn/documentation/user/10.0/zh_CN/index.html
# Odoo10离线中文用户手册下载
# https://www.odooa... | Python | 1 |
import torch
import torch.nn as nn
from ..attack import Attack
class MIFGSM(Attack):
r"""
MI-FGSM in the paper 'Boosting Adversarial Attacks with Momentum'
[https://arxiv.org/abs/1710.06081]
Distance Measure : Linf
Arguments:
model (nn.Module): model to attack.
eps (float): maxi... | Python | 1 |
#!/usr/bin/env python3
import os
import torch
import numpy as np
from tqdm import tqdm
import local_setup
from data.helpers import get_test_sampler
from models.losses import get_val_loss_fn_ensemble as get_val_loss_fn
from models.utils import EnsembleCheckPointer as CheckPointer
from models.helpers import get_model
f... | Python | 1 |
[doc = "`reset()` method sets DPLLSTATUS to value 0"]
impl crate::Resettable for DPLLSTATUS_SPEC {
#[inline(always)]
fn reset_value() -> Self::Ux {
0
}
}
use pnet::datalink::{self, NetworkInterface};
use wifi_rs::{prelude::*, WiFi};
pub struct Hotspot {
wifi: WiFi,
interface: String,
}
imp... | Rust | 0 |
1;39m╔======================================================
\033[1;39m║ DEVELOPER \33[1;91m ❂ \x1b[38;5;48m𝙂𝙆\•/𝙂𝙆\33[1;92m
\033[1;39m║ FACEBOOK \33[1;91m ❂ \x1b[38;5;208m𝐒𝐇𝐀𝐇𝐈 𝐉𝐎𝐊𝐄𝐑\33[1;92m
\033[1;39m║ GITHUB \33[1;91m ❂ \x1b[38;5;47m 𝐌𝐃 𝐉𝐎𝐊𝐄𝐑\33[1;92m
\033[1;39... | Python | 1 |
height=barcode_height))
ppos += 1
finish_page(pdf, c, pgno)
pgno += 1
fd, temp_barcode_path = mkstemp('.pdf', 'qr_', '.')
# will use pdf as the tmpfile has a .pdf suffix
pdf.writetofile(temp_barcode_path)
# prepare plain text output
fd, temp_text_path = mkstemp('.ps', 'text_', '.')
input_file_modification = dat... | Python | 1 |
, i * 0.01)\n \n # 检查资源使用\n final_memory = process.memory_info().rss / 1024 / 1024 # MB\n final_cpu = process.cpu_percent()\n \n memory_increase = final_memory - initial_memory\n \n logger.info(f\"内存使用增长: {memory_increase:.1f}MB\")\n logger.info(f\"CPU使用率:... | Python | 1 |
3,33,33,33,33,33,31];
let orig_vec4:Vec<u8> = vec![40,44,44,44,44,44,44,44,44,44,44,44,44,44,44,44,44,44,44,44,44,44,44,44,44,44,44,41];
time_keeper.println_set_mark("ubae on file creating test values took:");
ubae.add_entry("0\n", &orig_vec0[..]).expect("add entry 0 failed");
ubae.add_entry("1", &ori... | Rust | 0 |
expect(&mut Sigil::Arrow)
.unwrap();
}
#[test]
fn keyword() {
let mut params = [
(Keyword::Let, "let"),
(Keyword::When, "when"),
(Keyword::Type, "type"),
(Keyword::Match, "match"),
(Keyword::Import, "import"),
];
... | Rust | 0 |
e.method())
with self.assertChecksumChange():
mixin_base_def.order = abstract_base_def.order + 1
mixin_base_def.save(update_fields=['order'])
instance = model_class()
self.assertEqual('AbstractModel', instance.method())
with self.assertChecksumChange():
... | Python | 1 |
#!/usr/bin/python3
""" Defines a square"""
class Square:
"""
This class represents a square.
A square of equal side lengths for creating square objects
Attributes:
None
Methods:
None
"""
pass
| Python | 1 |
self) -> Optional[Dict[str, Any]]:
"""
現在のUI状態のスナップショットを作成
Returns:
UIスナップショット情報の辞書、失敗時はNone
"""
try:
response = requests.get(
f"{self.base_url}/debug/ui-snapshot",
timeout=self.timeout
)
res... | Python | 1 |
= self.deletes.search_scanning_backwards_sparse(last_order, &mut idx);
self.del_idx.set(idx);
match del_span {
Ok(d) => {
// Its a delete.
debug_assert!(d.0 <= last_order && last_order < d.end());
let start = u32::max(s... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.