text string | label_name string | labels int64 |
|---|---|---|
size) };
Ok(out)
}
#[test]
fn test_compress_skips_short() {
match compress("foo".as_bytes()) {
Ok(_) => panic!("Compression did _something_, which is wrong for 'foo'"),
Err(err) => assert_eq!(LzfError::NoCompressionPossible, err),
}
}
#[test]
fn test_compress_lorem() {
let lorem = "Lo... | Rust | 0 |
ynTrait<UserDataTypes>,
impulse: &B2contactImpulse,
) {
self.base.post_solve(contact, impulse);
}
}
#[derive(Default)]
pub(crate) struct TestData<D: UserDataType> {
pub(crate) m_world: Option<B2worldPtr<D>>,
pub(crate) m_sensor: Option<FixturePtr<D>>,
m_bodies: Vec<BodyPtr<D>>,
m_touching: Vec<bool>,
}
pub... | Rust | 0 |
r#f32;
mod r#f64;
#[macro_use]
mod int_macros;
mod r#i8;
mod r#i16;
mod r#i32;
mod r#i64;
mod r#i128;
mod r#isize;
#[macro_use]
mod uint_macros;
mod r#u8;
mod r#u16;
mod r#u32;
mod r#u64;
mod r#u128;
mod r#usize;
#[macro_use]
mod mask_macros;
mod mask8;
mod mask16;
mod mask32;
mod mask64;
mod mask128;
mod masksi... | Rust | 0 |
[repr(u32)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum LoadOp {
Clear,
Load,
}
#[repr(u32)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum StoreOp {
Store,
}
#[derive(Debug)]
pub struct CommandEncoder {
inner: imp::CommandEncoderInner,
}
... | Rust | 0 |
b">="[..]),
range(&b">"[..]),
range(&b"=="[..]),
range(&b"!="[..])
).skip(spaces())
).and(int_expr()).map(|((left, op), right)| {
match op {
b"<" => BoolExpr::LessThan(Box::new((left, right))),
b"<=" => BoolExpr::LessOrEqual(Box::new((left,... | Rust | 0 |
s(
self.SEPARADORES["DIVISOR"], campo
).decode("utf-8")
valor = campo.decode("utf-8")
bloque[clave] = self._extract_type_of_block(tipo_bloque, valor)
bloques.append(bloque)
except Exception as e:
most... | Python | 1 |
from __future__ import print_function
# score scaling based on idf, tags and capital letters
import numpy as np
import config
from pattern.en import verbs as vb
knn_idf_path = config.knn_idf
word_idf = None
max_idf = None
punc = set('~`!@#$%^&*()_+-={[}]<>,.?/;:"\'')
banned_verbs = 'do have be'.split()
def is_... | Python | 1 |
"""
简化的百炼平台服务权限检查脚本
"""
import sys
import os
import asyncio
import json
from pathlib import Path
# 添加项目根目录到Python路径
project_root = Path(__file__).parent
sys.path.insert(0, str(project_root))
from src.config.manager import config_manager
from src.services.dashscope_llm import DashScopeLLMService
from src.services.das... | Python | 1 |
from pandas import *
from pandas.util.decorators import cache_readonly
import numpy as np
import os
base = 'ml-100k'
class IndexedFrame(object):
"""
"""
def __init__(self, frame, field):
self.frame = frame
def _build_index(self):
pass
class Movielens(object):
def __init__(self... | Python | 1 |
val.as_ref().unwrap().load_prefab(
entity,
removal_system_data,
entities,
)?;
}
Ok(())
}
fn trigger_sub_loading(
&mut self,
progress: &mut ProgressCounter,
(
(
mtl_tex_set,
... | Rust | 0 |
pe"),
"listStatusType": obj.get("listStatusType"),
"listOrderStatus": obj.get("listOrderStatus"),
"listClientOrderId": obj.get("listClientOrderId"),
"transactionTime": obj.get("transactionTime"),
"symbol": obj.get("symbol"),
... | Python | 1 |
from check_index import *
import os
def check_reply(r):
assert is_dict(r)
assert sorted(r.keys()) == [
"cache-v2",
"client-bar",
"client-foo",
"cmakeFiles-v1",
"codemodel-v2",
"configureLog-v1",
"toolchains-v1",
]
check_error(r["cache-v2"], "no bu... | Python | 1 |
from sklearn.metrics import matthews_corrcoef
def calculate_acc_sn_sp(val_labels, val_preds):
TP = TN = FP = FN = 0
for pred, label in zip(val_preds, val_labels):
if pred == 1 and label == 1:
TP += 1
elif pred == 0 and label == 0:
TN += 1
elif pred == 1 and lab... | Python | 1 |
ialzed with zeros
#[argh(option, long = "data", short = 'd', from_str_fn(read_path))]
pub data_file: Option<PathBuf>,
#[argh(switch, long = "no-verify")]
/// flag to bypass verification checks before running the program
/// note: the interpreter will not behave correctly on malformed input
skip... | Rust | 0 |
constraints_index: Dict[str, int]
quadratic_constraints: List[EncodedQuadraticConstraint]
quadratic_constraints_index: Dict[str, int]
objective: EncodedQuadraticObjective
@classmethod
def encode(cls, qp: QuadraticProgram) -> EncodedQuadraticProgram:
return cls(
name=qp.name,
... | Python | 1 |
::IsWindow(m_hWnd));
if(GetPageCount() == 0)
return;
T* pT = static_cast<T*>(this);
SetRedraw(FALSE);
pT->ShowTabControl(false);
for(int i = 0; i < GetPageCount(); i++)
{
if(m_bDestroyPageOnRemove)
::DestroyWindow(GetPageHWND(i));
else
::ShowWindow(GetPageHWND(i), FALSE... | Rust | 0 |
# utils/retry_decorator.py
import time
from utils.file_utils import handle_error
def retry(max_retries=5, initial_wait=5, backoff_factor=2, exceptions=(Exception,)):
"""
Decorator to retry a function with exponential backoff upon specified exceptions.
:param max_retries: Maximum number of retries.
... | Python | 1 |
a = 33
b = 200
if b > a:
pass
| Python | 1 |
et_all_files(&password);
// Teardown special file with other password
let file_path = ["./files/", &filename].concat();
teardown(&file_path);
// Teardown first four files
for filename in filenames {
let file_path = ["./files/", &filename].concat();
... | Rust | 0 |
String) {
let len = keychain.borrow().len();
let mut key = String::new();
let mut parent_key = String::new();
for i in 0..len {
match &keychain.borrow()[i] {
&Key::Str(ref str_str) => {
if key.len() > 0 {
key.push('.');
}
key.push_str(str_str)
... | Rust | 0 |
Account,
pub eve: UserAccount,
}
pub fn storage_deposit(
user: &UserAccount,
contract_id: &str,
account_id: &str,
attached_deposit: Balance,
) {
user.call(
contract_id.to_string(),
"storage_deposit",
&json!({ "account_id": account_id }).to_string().into_bytes(),
... | Rust | 0 |
import torch
import torch.nn as nn
import torch.nn.functional as F
from utils.helper import *
__all__ = ['FedLC', 'FedDecorrLoss','KD']
def FedLC(label_distrib, logit, y, tau):
cal_logit = torch.exp(logit- (tau* torch.pow(label_distrib, -1 / 4).unsqueeze(0).expand((logit.shape[0], -1))))
#breakpoint()
y_... | Python | 1 |
from pydantic import BaseModel
from uuid import UUID
from datetime import datetime
class CourseBase(BaseModel):
id: UUID
user_id: UUID
name: str
term: str | None = None
created_at: datetime
class Config:
orm_mode = True | Python | 1 |
m::<u64>()));
let listen_addr2 = listen_addr1.clone();
let mut listener = listener_transport.listen_on(listen_addr1).unwrap();
let server = async move {
loop {
let (upgrade, _remote_addr) =
match listener.next().await.unwrap().unwrap().into_upgrade() {
... | Rust | 0 |
from typing import Optional
import torch.nn as nn
from mmengine.hooks import Hook
from mmengine.model import is_model_wrapper
from mmengine.runner import Runner
from mmdet.registry import HOOKS
@HOOKS.register_module()
class EarlyStoppingHook(Hook):
"""在连续多个 epoch 性能下降时提前停止训练。
Args:
patience (i... | Python | 1 |
reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeString>(
"alias",
Facet::get_alias_for_reflect,
Facet::mut_alias_for_reflect,
));
::protobuf::reflect::MessageDescriptor::new::<Facet>(
... | Rust | 0 |
OServicesByType(service_type):
"""
"""
serial_port_iterator = ctypes.c_void_p()
response = iokit.IOServiceGetMatchingServices(
kIOMasterPortDefault,
iokit.IOServiceMatching(service_type),
ctypes.byref(serial_port_iterator)
)
services = []
while iokit.IOIteratorIsVal... | Python | 1 |
"""empty message
Revision ID: b3d6a058fa62
Revises: deea55d98599
Create Date: 2025-10-11 18:32:01.082342
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = "b3d6a058fa62"
down_revision: Union[str, None] = "deea55d98599"
br... | Python | 1 |
eld is `ACLK_READY_1`"]
#[inline(always)]
pub fn is_aclk_ready_1(&self) -> bool {
**self == ACLK_READY_A::ACLK_READY_1
}
}
impl core::ops::Deref for ACLK_READY_R {
type Target = crate::FieldReader<bool, ACLK_READY_A>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
... | Rust | 0 |
,
MBC5RamBattery = 0x1B,
MBC5Rumble = 0x1C,
MBC5RumbleRam = 0x1D,
MBC5RumbleRamBattery = 0x1E,
MBC6 = 0x20,
MBC7SensorRumbleRamBattery = 0x22,
PocketCamera = 0xFC,
BANDAITama5 = 0xFD,
HuC3 = 0xFE,
HuC1RamBattery = 0xFF,
}
}
impl Cartri... | Rust | 0 |
# FlippyFlappingTheJ
# ./src/utils/TkUtils/PlaceholderEntry.py
import tkinter as ttk
class PlaceholderEntry(ttk.Entry):
"""
Custom tkinter Entry object
@params container = master, placeholder = "example", args = tkinter object args, kwargs = tkinter object kwargs
- container: the main tkinter windo... | Python | 1 |
#[tokio::test]
async fn read_i32_alltypes_plain_parquet() -> Result<()> {
let session_ctx = SessionContext::new();
let task_ctx = session_ctx.task_ctx();
let projection = Some(vec![0]);
let exec = get_exec("alltypes_plain.parquet", projection, None).await?;
let batches = col... | Rust | 0 |
import time
import torch
import numpy as np
import sys
sys.path.append('../global_module/')
# import d2lzh_pytorch as d2l
import matplotlib.pyplot as plt
from pylab import *
def evaluate_accuracy(data_iter, net, loss, device):
acc_sum, n = 0.0, 0
with torch.no_grad():
for X, y in data_iter:
... | Python | 1 |
from django.shortcuts import render
def about_us(request):
return render(request, 'about/about_us.html')
def contact_us(request):
if request.method == 'POST':
name = request.POST.get('name')
email = request.POST.get('email')
message = request.POST.get('message')
if name and em... | Python | 1 |
ate an instance of Value")
}
pub fn context(mut self, context: &impl IsA<Context>) -> Self {
self.context = Some(context.clone().upcast());
self
}
}
pub const NONE_VALUE: Option<&Value> = None;
pub trait ValueExt: 'static {
//#[doc(alias = "jsc_value_constructor_call")]
//fn constructor_call(&self,... | Rust | 0 |
SpreadMode,
pub inv_width: f32,
pub inv_height: f32,
}
#[derive(Copy, Clone, Default, Debug)]
pub struct UniformColorCtx {
pub r: f32,
pub g: f32,
pub b: f32,
pub a: f32,
pub rgba: [u16; 4], // [0,255] in a 16-bit lane.
}
// A gradient color is an unpremultiplied RGBA not in a 0..1 rang... | Rust | 0 |
"преди (\\d+[.,]?\\d*) сек",
"преди (\\d+[.,]?\\d*) секунда",
"преди (\\d+[.,]?\\d*) секунди"
],
"\\1 week ago": [
"пр (\\d+[.,]?\\d*) седм",
"преди (\\d+[.,]?\\d*) седм",
"преди (\\d+[.,]?\\d*) седмица",
"преди (\\d+[.,]?\\d*... | Python | 1 |
nt
bin_edges = [b[0] for b in custom_bins] + [custom_bins[-1][1]]
bin_count = len(custom_bins)
else:
counts, bin_edges = np.histogram(data, bins=bins)
result = {i: count for i, count in enumerate(counts)}
bin_count = len(bin_edges) - 1
if normalize:
total = len(... | Python | 1 |
c_longlong,
),
>;
pub type iv_tochandler =
::core::option::Option<unsafe extern "C" fn(position: c_types::c_longlong)>;
pub type iv_itempaint = ::core::option::Option<
unsafe extern "C" fn(
x: c_types::c_int,
y: c_types::c_int,
index: c_types::c_int,
selected: c_types::c_int,... | Rust | 0 |
"""
class
object
isinstance
__init__ - constructor
self
__dict__
class attribute
class methods
Operator overloading - __str__, __eq__, __gt__, @total_ordering
arithmetic operators - __add__, __sub__, __mul__, __truediv__
__len__, append, __iter__, __getitem__, __setitem__
private variable = __var
__dict__
property(),... | Python | 1 |
phere(25.0, translation(0.0, -75.0, 0.0), Color::NAVY);
test_scene.root.add_child(Box::new(sphere));
let image = render(test_scene, image(1280, 720), camera([0.0, 0.0, room_size/2.0], [0.0, -(room_size/2.0)*0.6, 0.0]));
write_to_png( image, "output/scene_1");
}
#[test]
fn scene_test_2() {
let mut test... | Rust | 0 |
| InsnParser::IINC | InsnParser::INSTANCEOF |
InsnParser::INVOKESPECIAL | InsnParser::INVOKESTATIC | InsnParser::INVOKEVIRTUAL |
InsnParser::LDC_W | InsnParser::LDC2_W | InsnParser::NEW | InsnParser::PUTFIELD |
InsnParser::PUTSTATIC | InsnParser::SIPUSH => {
pc += 2;
rdr.seek(SeekFrom::Current(2)... | Rust | 0 |
fn eq(&self, other: &Value) -> bool {
match (self, &other) {
(Value::Null(_), Value::Null(_)) => true,
(Value::Int(a), Value::Int(b)) => a == b,
(Value::Float(a), Value::Float(b)) => a == b,
(Value::Bool(a), Value::Bool(b)) => a == b,
(Value::String(a), Value::String(b)) => a == b,
(Value::Type(a)... | Rust | 0 |
b-rs<gh_stars>1-10
/*
* Client Portal Web API
*
* Client Poral Web API
*
* OpenAPI spec version: 1.0.0
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
#[allow(unused_imports)]
use serde_json::Value;
#[derive(Debug, Serialize, Deserialize)]
pub struct IserversecdefsearchSections {
... | Rust | 0 |
ident),*
}
macro_rules! hash_set {
($($elem:path),+ $(,)?) => {{
let mut set = ::std::collections::HashSet::with_capacity(#discards_len);
$( set.insert($elem); )+
set
}};
() => {
::std::collections::HashSet::with_capacity(#discards_len)
};
}
impl #kind_ident {
fn discards() -> &... | Rust | 0 |
t()
/ const_bool()
/ const_string()
/ const_float()
/ const_length()
/ const_int()
pub rule const_unit() -> Cst =
s:p() "(" _ ")" e:p() { cst!(const_unit (s, e) []) }
pub rule const_bool() -> Cst =
s:p() (kwd("true") /... | Rust | 0 |
0.1".into(),
port: start_port + (i as u16),
},
nodes: key_pairs.iter().enumerate().map(|(j, kp)| (kp.public().clone(),
NodeAddress {
address: "127.0.0.1".into(),
port: start_port + (j as u16),
})).collect(),
key_server_set_contract_address: None,
allow_connecting_to_higher_nod... | Rust | 0 |
# Download pandas
import pandas as pd
import re
passList = []
engWordList = []
numAndWordList = []
# Open password list and assign to list passList
with open("xato-net-10-million-passwords-1000000.txt") as file:
i = 0
for line in file:
passList.append(line.strip())
i += 1
if i > 40000:... | Python | 1 |
) -> dict[str, MetricConfig]:
"""See Processor.default_metrics."""
return {
"ExactMatchQATat": ExactMatchQATatConfig(
source_language=source_language,
target_language=target_language,
),
"F1ScoreQATat": F1ScoreQATatConfig(
... | Python | 1 |
onse.into_inner().message);
Ok(())
}use fehler::throws;
use program_client::turnstile_instruction;
use trdelnik_client::{anyhow::Result, *};
use turnstile;
#[throws]
#[fixture]
async fn init_fixture() -> Fixture {
// create a test fixture
let fixture = Fixture {
client: Client::new(system_keypair(... | Rust | 0 |
ocument;
use bson::oid::ObjectId;
use models::story::Story;
/// A user and its information and settings.
///
/// # Fields
/// * ```authors_favorite```: A vector of ObjectIds of the user's favorite users.
/// * ```authors_following```: A vector of ObjectIds of the users that the user is following.
/// * ```descr... | Rust | 0 |
id = self.voxel_id.get(&v_x, &v_y, &v_z);
if id.is_none() {
let p = self.mod_value(v_x, v_y, v_z);
let _cube = self.get_cube(c_x, c_y, c_z);
if _cube.is_some() {
let mut cid = 0;
_cube.map(|c| {
c.xyzi.voxels.push(p.x);
... | Rust | 0 |
#! /usr/bin/python3
import os
import sys
import generator_utils as gen
template = """// @{generatedby}@
/* ///////////////////////// The MPI Bugs Initiative ////////////////////////
Origin: MBI
Description: @{shortdesc}@
@{longdesc}@
Version of MPI: Conforms to MPI 1.1, does not require MPI 2 implementat... | Python | 1 |
MpsseCmdBuilder::new()
.set_gpio_lower(inner.value, inner.direction)
.send_immediate();
inner.ft.send(cmd.as_slice())?;
Ok(Spi {
mtx,
clk: ClockData::MsbPosIn,
clk_out: ClockDataOut::MsbNeg,
})
}
/// Set the SPI clock polarit... | Rust | 0 |
thread_local stuff here, but couldn't get that to work (thankfully).
*x += amount
}
fn decr(x: &mut i32, amount: i32) {
*x -= amount
}
fn helper(fps: &[FnMutant<&mut i32, i32, (), &dyn for<'b> Fn(&mut i32, i32)>],
xs: &mut [i32], expect: Vec<i32>) {
let len ... | Rust | 0 |
` to `bool`
foo(0_f32);
}
}
#[inline(never)]
unsafe fn foo(x: f32) {
let z = f32x4(0.0, 0.0, 0.0, 0.0);
simd_reduce_add_ordered(z, x);
//~^ ERROR accumulator of simd_reduce_add_ordered is not a constant
simd_reduce_mul_ordered(z, x);
//~^ ERROR accumulator of simd_reduce_mul_ordered is... | Rust | 0 |
import pytest
from plenum.common.constants import DOMAIN_LEDGER_ID, POOL_LEDGER_ID
from plenum.test.bls.helper import sdk_change_bls_key
from plenum.test.freshness.helper import check_update_bls_multi_sig_during_ordering
from plenum.test.helper import freshness
FRESHNESS_TIMEOUT = 10
@pytest.fixture(scope="module")... | Python | 1 |
"""Core buffer operations for GStreamer - bytes focused."""
from gi.repository import Gst
def write(
data: bytes, timestamp_ns: int = 0, duration_ns: int | None = None
) -> Gst.Buffer:
"""Create a Gst.Buffer from bytes data."""
buf = Gst.Buffer.new_allocate(None, len(data), None)
buf.fill(0, data)
... | Python | 1 |
`Instance` itself dereferences to a `RegisterBlock`, which
/// provides access to the peripheral's registers.
#[cfg(not(feature = "nosync"))]
#[inline]
pub fn take() -> Option<Instance> {
external_cortex_m::interrupt::free(|_| unsafe {
if CSU_TAKEN {
None
... | Rust | 0 |
#User function Template for python3
class Solution:
def search(self, A : list, l : int, h : int, key : int):
if key in A:
return A.index(key)
return -1
#{
# Driver Code Starts
#Initial Template for Python 3
if __name__ == '__main__':
t = int(input())
for _ in range(t):... | Python | 1 |
est)
Yhat_test = unscale(Yshat_test, ymean, ygain)
R2, R2_test, msg = compute_scores(
Y_train, Yhat_train, Y_test, Yhat_test, fit='R2')
print(msg)
print(model.sparsity_analysis())
########################################################################################
# Use group-Lasso regularization with penalty... | Python | 1 |
e(l_op.unwrap(), r_op.unwrap(), size as usize);
return Ok(None)
}
Token::ENop => return Ok(None),
_ => {}
}
let result = match token {
Token::EPeek(size) => {
self.ctx.mem_read(l_op.unwrap(), size as usize)
}
... | Rust | 0 |
# coding: UTF-8
from __future__ import division
import numpy as np
import scipy as sp
from weakclassify import WEAKC
from dml.tool import sign
class ADABC:
def __init__(self,X,y,Weaker=WEAKC):
'''
X is a N*M matrix
Weaker is a class of weak classifier
It should have a train(self.W) method pass the wei... | Python | 1 |
class Solution:
def minEatingSpeed(self, piles: List[int], h: int) -> int:
'''Approach: Binary Search. The problem asks to find the minimum
number of bananas the girl need to eat in one hour so that she finishes
up eating them when the guards came in. So the girl can eat one banana
... | Python | 1 |
from server.app import ma
from server.app.models import Product, Catalog, User, Review, Wishlist, Cart, CartItem, Payment
class ProductSchema(ma.SQLAlchemyAutoSchema):
class Meta:
model = Product
class CatalogSchema(ma.SQLAlchemyAutoSchema):
class Meta:
model = Catalog
class UserSchema(ma.SQLAlc... | Python | 1 |
teps
if update_step < offset + self.hold_steps:
# hold stage
return 1, update_step - offset
offset += self.hold_steps
if update_step <= offset + self.decay_steps:
# decay stage
return 2, update_step - offset
offset += self.decay_steps
... | Python | 1 |
# Sometimes a metric (e.g., BiasMetric) doesn't produce any statistics
if len(stats) > 0:
per_instance_stats.append(
PerInstanceStats(instance.id, instance.perturbation, train_trial_index, stats)
)
# Aggregate these stats
... | Python | 1 |
= None
return isnjwrk3ydq
'# lieutenant_oscillations_boxes -> sums_afternoon_checker'
rcag88fx75n = p86ie9_vxz8 = pmkdhnedc4n = i060uo7cawr = ij5p445w5ss = j0jjg15b_ju = 0
nonlocal ng5bkhrugq0
'# lieutenant_oscillations_boxes -> sums_afternoon_checker'
raise ''
from al76mxu98l7 import fnntwt... | Python | 1 |
();
crate::json_ser::serialize_structure_crate_model_aws_s3_bucket_bucket_lifecycle_configuration_rules_filter_predicate_details(&mut object_2576, var_2575);
object_2576.finish();
}
}
pub fn serialize_structure_crate_model_aws_s3_bucket_bucket_lifecycle_configuration_rules_noncurrent_version_transi... | Rust | 0 |
pub fn get_vectre_programs(func_names: &HashSet<&str>, als: &Vec<Rc<AssemblyLine>>) -> String {
if als.is_empty() {
return "".to_string();
}
// Result string of vectre programs to return
let mut res = format!("");
let mut curr_func_name = &als[0].function_name()[.... | Rust | 0 |
(code, ns, {"path": path})
@register_maker("re")
def make_predicate_re(
expr: str,
ns: dict,
/,
) -> None | PredicateType:
search = re_compile(expr).search
return lambda path: search(path.name) is not None
@register_maker("lambda")
def make_predicate_lambda(
expr: str,
ns: dict,
... | Python | 1 |
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community
Edition) available.
Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in complia... | Python | 1 |
cy_score(labels, math_m_marks)
math_m_precision = precision_score(labels, math_m_marks)
math_m_recall = recall_score(labels, math_m_marks)
math_m_f1 = f1_score(labels, math_m_marks)
print('\n Метрики для метода общих слов: \n')
print("Accuracy:", math_m_accuracy)
print("Precision:", math_m_precision)
print("Recall:",... | Python | 1 |
.loads(data['images']) if isinstance(data['images'], str) else data['images']
if data.get('links'):
data['links'] = json.loads(data['links']) if isinstance(data['links'], str) else data['links']
if data.get('tags'):
data['tags'] = json.loads(data['tags']) if isinstance(data['tags... | Python | 1 |
crop = np.ones((box_size//5, box_size//2, 3)) * c(ss) * 255
whole_image[box_size*(i+1)+box_size//5*k:box_size*(i+1) + box_size//5*(k+1), box_size*j:box_size*j+box_size//2, :] = crop
w_score = weighted_scores[i][j]
crop = np.ones((box_size//2, box_size // 2, 3)) * c(w_score) * 255
whole_im... | Python | 1 |
jection: (Matrix4, Matrix4),
fpga_flag: FPGAControlFlags,
cpu_flag: CPUControlFlags,
modulation: Option<Modulation>,
point_sequence: Option<PointSequence>,
gain_sequence: Option<GainSequence>,
seq_idx: i32,
seq_wavelength: f32,
delay_offset: Option<DelayOffset>,
log_buf: VecDeque<Str... | Rust | 0 |
from django.http import HttpResponseRedirect
from django.shortcuts import redirect
from django.urls import reverse
from system.models import SocialUser
class LegalRequirementMixin:
def dispatch(self, request, *args, **kwargs):
if not request.user.legaluser.privacy:
return redirect("privacy")... | Python | 1 |
oduct['name']} 설치 실패: {str(e)}")
def install_personal_edition(self, temp_path):
"""Personal Edition 설치"""
# 현재 디렉토리의 personal 폴더를 사용자 홈으로 복사
personal_source = Path(__file__).parent.parent / "personal"
personal_dest = Path.home() / "focus_timer_personal"
if personal_source.e... | Python | 1 |
# -*- encoding: utf-8 -*-
"""
Copyright (c) App-Generator.dev | AppSeed.us
"""
import os
from .common import *
from .h_files import *
from .h_util import *
def check_migrations():
try:
if 0 == exec_process('python manage.py makemigrations --check --dry-run'):
return True
... | Python | 1 |
Res, Energy> EntropicHist<Hist> for EntropicSampling<Hist, R, E, S, Res, Energy>
where Hist: Histogram,
R: Rng,
{
#[inline]
fn hist(&self) -> &Hist
{
&self.hist
}
}
impl<Hist, R, E, S, Res, Energy> EntropicEnsemble<E> for EntropicSampling<Hist, R, E, S, Res, Energy>
where Hist: Histogram,
... | Rust | 0 |
/// Error caused by out of bounds access to [`ArrayString`]
///
/// [`ArrayString`]: ../struct.ArrayString.html
#[derive(Copy, Clone, Default, PartialEq, Eq)]
pub struct OutOfBounds;
impl Debug for OutOfBounds {
#[inline]
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "OutOfBounds")
}... | Rust | 0 |
show_debug<T: Debug>(t: &T) -> String {
format!("{:?}", t)
}
/// Function to compare two `T`s
type Comparison<T> = Arc<dyn Fn(&T, &T) -> bool + Send + Sync + 'static>;
/// Function to show a representation of a given `T`
type Show<T> = Arc<dyn Fn(&T) -> String + Send + Sync + 'static>;
/// A Boolean predicate on... | Rust | 0 |
) => Some(packet),
Err(err) => {
error!("Error reading packet: {}", err);
None
}
}
},
None => None,
}
}
pub fn write_packet(&self, payload: &PacketPayload, dst: &mut BytesMut)... | Rust | 0 |
omise_q, PromiseRef};
use crate::quickjs_utils::{functions, new_null_ref, promises};
use crate::quickjsrealmadapter::QuickJsRealmAdapter;
use crate::quickjsruntimeadapter::QuickJsRuntimeAdapter;
use crate::reflection;
use crate::valueref::*;
use futures::executor::block_on;
use hirofa_utils::auto_id_map::AutoIdMap;
use... | Rust | 0 |
est_auc_groups_std, best_dpd_groups_std, best_eod_groups_std, best_between_group_disparity_std)
# Bootstrap based on train/test setting
best_acc, best_es_acc, best_auc, best_es_auc, best_auc_groups, best_dpd_groups, best_eod_groups, best_between_group_disparity, \
best_acc_std, best_es_acc_std, best_auc_st... | Python | 1 |
is=1)
f_idx = np.argsort(-w_2)
param = dict()
param['alpha'] = alpha
param['beta'] = beta
param['gamma'] = gamma
param['lamb'] = lamb
# return the info. (paras, ranked no. of features and running time)
record = dict()
record['method'] = 'UGRFS'
record['dataset'] = dataset
re... | Python | 1 |
ABLE,
message: &[],
triggered_by: Some(&ilp_address_clone),
data: &[],
}
.build()
})
.await?;
let body = BytesMut::from_iter(body.into_iter());
match Packet::try_from(body) {
Ok(Packet::Fulfill(fulfill)) => Ok(fulfi... | Rust | 0 |
times += (u''.join([TitleHTML(_((' ' if times else '') + _(u'Away:'))),
DetailHTML(GenTimedString(away_since))
]))
if times:
times = '<div>%s</div>' % times
if contact.status_orb == 'unknown' or contact.service not in JABBER_SERVICES:
... | Python | 1 |
, "b")));
/// assert!(!map.contains_key(&2));
/// ```
pub fn remove_succ<Q: ?Sized>(&mut self, key: &Q, inclusive: bool) -> Option<(K, V)>
where C: Compare<Q, K> {
Max::closest(&mut self.root, PathBuilder::default(), &self.cmp, key, inclusive)
.remove(&mut self.len)
}
/... | Rust | 0 |
collaborative.node.port)
time.sleep(2) # Let them connect
print(f" User 1 port: {user1.collaborative.node.port}")
print(f" User 2 port: {user2.collaborative.node.port}")
# User 1 searches for something
print("\n📝 User 1 searches...")
response1 = user1.intelligent_search("insta... | Python | 1 |
tical_dSdt(x, t * np.ones(x.shape))
assert np.allclose(
g_x, g_x_s
), f"Spike function derivative w.r.t `x` does not match analytical jax gradient with t = {t}"
assert np.allclose(
g_t, g_t_s
), f"Spike function derivative w.r.t `t` does not match analytical jax ... | Python | 1 |
from types import FunctionType
import time
from Script.Core import cache_control, game_type, get_text
from Script.Design import update, character, constant, handle_instruct
from Script.Config import normal_config
cache: game_type.Cache = cache_control.cache
""" 游戏缓存数据 """
_: FunctionType = get_text._
""" 翻译api """
wi... | Python | 1 |
age, port, plotly_2d_plot):
serve(plotly_2d_plot, port=port, threaded=True, show=False)
time.sleep(0.2)
page.goto(f"http://localhost:{port}")
plotly_plot = page.locator('.js-plotly-plot .plot-container.plotly')
expect(plotly_plot).to_have_count(1)
# Select and click on first point
point ... | Python | 1 |
vec3 material_diffuse = vec3(uniforms.material_diffuse_r, uniforms.material_diffuse_g, uniforms.material_diffuse_b);
vec3 material_specular = vec3(uniforms.material_specular_r, uniforms.material_specular_g, uniforms.material_specular_b);
vec3 lightDir = normalize(-direction);
// diffuse shading
flo... | Rust | 0 |
import matplotlib.pyplot as plt # Исходные данные
D = 102
d = 0.15 * D
h0 = 4 * D
g = 9.81
delta_t = 0.1
# Рассчитываем расход воды
S = (3.14 / 4) * (d ** 2) v = (2 * g * h0) ** 0.5 Q_dot = S * v
# Начальные условия
h = h0
time_steps = [0]
water_levels = [h]
# Рассчитываем изменение уровня воды для нескольких шагов f... | Python | 1 |
(0, 255, 0) # Green
elif risk_level < 0.6:
return (255, 165, 0) # Orange
else:
return (255, 0, 0) # Red
def _get_reports_color(self, reports):
threshold = self.config.REPORT_THRESHOLD
if reports < threshold * 0.3:
return (0, 255, 0... | Python | 1 |
// Mask: 0x001F, Value: 0x08, Time: 3, Name: MOD, Type: Binary
/// Description: Sets m to m % u. If u == 0, Sets m to 0 instead. (treats m & u as unsigned)
pub const MOD: OpCode = OpCode { name: "MOD", code: 0x08, time: 3 };
/// Mask: 0x001F, Value: 0x09, Time: 3, Name: MDI, Type: Binary
/// Description: Sets m to m %... | Rust | 0 |
(),
),
Span::new(
byte_start..byte_start + token_text.len(),
char_start..char_start + token_text.chars().count(),
),
is_sentence_end,
sentence[..byte_start].ends_with(char:... | Rust | 0 |
from DatabaseManager import *
from pydantic import BaseModel
from typing import List, Dict, Any
# 定義公告數據模型類
class BulletinRaw(BaseModel):
rawid: int
publisher: str
title: str
url: str
content: str
addtime: datetime
processstatus: bool
# 定義公告管理類,繼承自數據庫管理類
class BulletinManager(Datab... | Python | 1 |
.
pub base: GlyphName,
pub transform: AffineTransform,
pub identifier: Option<Identifier>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Contour {
pub identifier: Option<Identifier>,
pub points: Vec<ContourPoint>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct ContourPoint {
pub name: Optio... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.