text string | label_name string | labels int64 |
|---|---|---|
import sys
sys.stdin = open("input.txt")
from heapq import heappop, heappush
# 루트 노드를 찾는 함수
def find(x):
if x == parent[x]:
return x
parent[x] = find(parent[x]) # 압축
return parent[x]
# 결합하는 함수
def union(x, y):
x = find(x)
y = find(y)
parent[y] = x
N = int(input()) # N: 컴퓨터의 수
M = int(... | Python | 1 |
import cv2
import time
import numpy as np
import easyocr
from PIL import Image,ImageFont,ImageDraw
from googletrans import Translator
import cvzone
import imutils
import pygame
import requests
path = ''
play_path = 'effect/'
# 손 마우스 포인터 생성
def mouse_handler(l,x,y,ix,iy,w,h,new_img,cap_image,src):
if x>280 :
... | Python | 1 |
rd()
return fidelity_loss
# true_loss.backward()
# return true_loss
start_time = time.time()
p = get_params(OPT_OVER, net, net_input)
optimize(OPTIMIZER, p, closure, LR, num_iter)
end_time=time.time() - start_time
out_np = torch_to_np(net(net_input))
q = plot_image_grid([np.clip(out_np, 0, 1), img_np... | Python | 1 |
import os
from os.path import join
import shutil
raw_top='CHALLENGE_DATA'
data_top='data'
###############################################
# LM: 23-04-2025
###############################################
# List of directories to unpack to
dirs_to_create = [
'./data',
'./data/PSMA',
'./data/PSMA/CT',
'./data/PSM... | Python | 1 |
t ARG_VALUE_NAME: &str = common::ARG_INTEGER;
const ARG_HELP: &str = "Version of the called payment contract. Latest will be used by default";
pub fn arg() -> Arg<'static, 'static> {
Arg::with_name(ARG_NAME)
.long(ARG_NAME)
.value_name(ARG_VALUE_NAME)
.help(ARG_HELP)... | Rust | 0 |
/// Result describing whether it is possible to swap two parachains. Doesn't mutate state.
fn ensure_can_swap(one: ParaId, other: ParaId) -> Result<(), &'static str>;
/// Updates any needed state/references to enact a logical swap of two parachains. Identity,
/// code and `head_data` remain equivalent for all par... | Rust | 0 |
cheduleEmpty";
let io_schedule = b"".to_vec();
let components = vec![Compose {
name: b"component1".to_vec(),
code_txt: r#""#.as_bytes().to_vec(),
exec_type: b"exec_escrow".to_vec(),
dest: AccountId::new([1 as u8; 32]),
value: 0,
bytes: vec![],
input_data... | Rust | 0 |
ReferenceDescriptor {
specifier: ref_desc.specifier.to_string(),
resolved_specifier,
kind: ref_desc.kind,
location: ref_desc.location,
};
references.push(reference_descriptor);
}
Ok((imports, references))
}
fn serialize_module_specifier<S>(
spec: &ModuleSpecifier,
s: S,
) -> ... | Rust | 0 |
<Body> + 'a,
{
self.transport.stream_json_chunks(
Method::POST,
self.version.make_endpoint(endpoint),
body,
headers,
)
}
/// Send a streaming post request that returns a stream of JSON values
///
/// When a received chunk does not cont... | Rust | 0 |
applying only to params that require_grad to avoid small numerical changes of pos_embed
ema_params[name].mul_(decay).add_(param.data, alpha=1 - decay)
def requires_grad(model, flag=True):
"""
Set requires_grad flag for all parameters in a model.
"""
for p in model.parameters():
p.requi... | Python | 1 |
Cell;
use serde::Serialize;
use crate::server::version::Version;
use crate::server::os_trait::CurrentOs;
use crate::server::methods::{self, InstallMethod};
use crate::server::distribution::{DistributionRef, MajorVersion};
use anyhow::Context;
#[cfg(target_arch="x86_64")]
pub const ARCH: &str = "x86_64";
#[cfg(targe... | Rust | 0 |
scanner_count.write().unwrap() -= 1;
break;
}
};
});
}
fn scan_file(data: web::Data<AppState>, file_name: String) {
println!("scan_file {:?}", file_name);
let conn = &mut get_conn(data.clone());
let zip_file_name = file_name.clone();
let zip_path = PathBuf::from(... | Rust | 0 |
vn3
r_val = [
-7.667977543898155, -6.917977543898155, -5.167977543898155
]
assert_allclose(mvn3.logpdf(cov3), r_val, rtol=1e-13)
r_val = [
0.000467562492721686, 0.000989829804859273, 0.005696077243833402
]
assert_allclose(mvn3.pdf(cov3), r_val, r... | Python | 1 |
print(f"长期记忆聚类完成,共 {n_clusters} 个聚类:")
for cluster_id, count in cluster_counts.items():
print(f" 聚类 {cluster_id}: {count} 个记忆")
def _evaluate_importance(self, memory):
"""评估记忆的重要性(多维度评分)"""
base_importance = memory['importance']
# 1. 时间衰减因子 ... | Python | 1 |
D)E\n\
E)F\n\
B)G\n\
G)H\n\
D)I\n\
E)J\n\
J)K\n\
K)L"
}
fn input_part2() -> &'static str {
"COM)B\n\
B)C\n\
C)D\n\
D)E\n\
E)F\n\
B)G\n\
G)H\n\
D)I\n\
E)J\n\
... | Rust | 0 |
# Python bytecode 2.7 (decompiled from Python 2.7)
# Embedded file name: scripts/common/items/writers/sound_writers.py
import math
import ResMgr
from items import _xml
from items.components import sound_components
from items.writers import shared_writers
def writeWWTripleSoundConfig(soundConfig, section):
_xml.rew... | Python | 1 |
# SPDX-FileCopyrightText: 2019 Scott Shawcroft for Adafruit Industries
#
# SPDX-License-Identifier: MIT
"""
`adafruit_ssd1327`
================================================================================
DisplayIO drivers for grayscale OLEDs driven by SSD1327
* Author(s): Scott Shawcroft
Implementation Notes
-... | Python | 1 |
ery}')
res = client.query(a)
results = next(res.results).text
speak(results)
elif 'why' in query:
query=query.replace('why','')
a=(f'why {query}')
res = client.qu... | Python | 1 |
}
}
}
#[derive(Default)]
struct WidthExpandable {
stub: WidgetStub
}
impl Widget for WidthExpandable {
widget_stub!();
fn min_size(&self) -> Size {
Size { w: 12., h: 42. }
}
fn width_expandable(&self) -> bool {
true
... | Rust | 0 |
rm} ".format(
vpath=v_python,
run_file=values['rfile'],
parm=values.get("parm", "")
)
self._create_cmd_file(
cmd_file=cmd_file,
v_ptah_bin=os.path.dirname(v_python),
project_path=values["path"],
command=command,
... | Python | 1 |
EGER: D3D_TESSELLATOR_PARTITIONING = 1i32;
#[doc = "*Required features: 'Win32_Graphics_Direct3D'*"]
pub const D3D11_TESSELLATOR_PARTITIONING_POW2: D3D_TESSELLATOR_PARTITIONING = 2i32;
#[doc = "*Required features: 'Win32_Graphics_Direct3D'*"]
pub const D3D11_TESSELLATOR_PARTITIONING_FRACTIONAL_ODD: D3D_TESSELLATOR_PART... | Rust | 0 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Licensed under the GNU General Public License, version 3.
# See the file http://www.gnu.org/licenses/gpl.txt
#
from pisi.actionsapi import pisitools
from pisi.actionsapi import shelltools
from pisi.actionsapi import get
WorkDir = "whichwayisup"
def install():
pisitoo... | Python | 1 |
net_apy = 420479152 / 400_000 = 1051.197894972000000000
assert_eq!(
get_user_total_supply_borrow_and_net_apy_rpc(ALICE::get()),
Some((
Interest::from_inner(18_945_252_000_000_000),
Interest::from_inner(32_385_046_151_016_000),
Interest::from_inner(1_051_197_894_972_000_000_000)
))
);
... | Rust | 0 |
cript<bitcoin::XOnlyPublicKey, Ctx> {
fn to_no_checks_ms(&self) -> Miniscript<BitcoinKey, NoChecks> {
// specify the () error type as this cannot error
self.real_translate_pk::<_, _, _, (), _>(
&mut |xpk| Ok(BitcoinKey::XOnlyPublicKey(*xpk)),
&mut |pkh| Ok(TypedHash160::Xonly... | Rust | 0 |
x < 42);
assert!(IsCallable::filter(&36));
assert!(IsCallable::filter(&40));
assert!(!IsCallable::filter(&42));
IsCallable::push(|x| *x % 3 == 0);
assert!(IsCallable::filter(&36));
assert!(!IsCallable::filter(&40));
IsCallable::pop();
assert!(IsCallable::filter(&36));
assert!(IsCallable::filter(&40)... | Rust | 0 |
import numpy as np
from numba.core.extending import overload
from numba.np.linalg import _copy_to_fortran_order, ensure_lapack
from scipy import linalg
from pytensor.link.numba.dispatch.linalg._LAPACK import (
_LAPACK,
_get_underlying_float,
int_ptr_to_val,
val_to_int_ptr,
)
from pytensor.link.numba.di... | Python | 1 |
ists(info_path)):
continue
try:
info = np.load(info_path, allow_pickle=True).item()
except pickle.UnpicklingError:
print(f"*** error with {video_clip_path}")
break
square_image_path = os.path.join(video_clip_path, f"squa... | Python | 1 |
# coding: utf-8
import pytest # NOQA
from .roundtrip import round_trip, round_trip_load_all
class TestDocument:
def test_single_doc_begin_end(self):
inp = """\
---
- a
- b
...
"""
round_trip(inp, explicit_start=True, explicit_end=True)
def test_multi... | Python | 1 |
import cupy as cp
import matplotlib.pyplot as plt
# Parameters
nx, ny = 64, 64
a = (2 * cp.pi) / nx # Grid spacing
epsilon = 1e-6
alpha = 1.5
kappa = 0.01
theta = 0.0026
# Grid and background field
x = cp.linspace(0, 2 * cp.pi, nx)
y = cp.linspace(0, 2 * cp.pi, ny)
X, Y = cp.meshgrid(x, y)
psi0 = cp.sin(X) * cp.cos(... | Python | 1 |
import os
from fastapi import APIRouter, BackgroundTasks
from loguru import logger
from starlette.responses import JSONResponse
from src.dependencies import reload_cache
router = APIRouter()
@router.get("/refresh", tags=["Utils"])
async def refresh(background_tasks: BackgroundTasks):
"""
Сбрасывает кэш и з... | Python | 1 |
A>>,
{
docs.into_iter().fold(self.nil(), |a, b| a.append(b))
}
/// Allocate a document that intersperses the given separator `S` between the given documents
/// `[A, B, C, ..., Z]`, yielding `[A, S, B, S, C, S, ..., S, Z]`.
///
/// Compare [the `intersperse` method from the `itertools`... | Rust | 0 |
r::UnexpectedToken(t_list_end!(span!(1, 1, 1, 2)));
assert_eq!("Unexpected token 'List End' at 1:1-1:2", format!("{}", err));
let err = ParserError::UnexpectedEndOfInput;
assert_eq!("Unexpected end of input", format!("{}", err));
let err = ParserError::LexerError(LexerError::new(1, 10));... | Rust | 0 |
ing is wrong about edge:', edge)
fig.update_layout(
xaxis=dict(
range=[expanded_mins[0], expanded_maxs[0]],
visible=False, # 隐藏 X 轴
scaleanchor="y" # 锁定 X 和 Y 轴比例一致
),
yaxis=dict(
range=[expanded_mins[1], expa... | Python | 1 |
import pandas as pd
import matplotlib.pyplot as plt
import streamlit as st
from sklearn.metrics import accuracy_score, classification_report
def evaluate_model(best_models, X_test, y_test):
results = {}
for name, model in best_models.items():
y_pred = model.predict(X_test)
results[name] = {
... | Python | 1 |
task_dependency = ' '.join(task_detail[1:]).strip()
else:
task_dependency = task_detail[1].strip()
task_dependency = task_dependency.strip().strip('[]').replace('\'','').replace('\"','')
task_dependency = task_dependency.split(',') if len(task_dependency) > 0 else []... | Python | 1 |
#
# SPDX-License-Identifier: MIT
#
# Copyright (c) 2025 Carsten Igel.
#
# This file is part of simplepycons
# (see https://github.com/carstencodes/simplepycons).
#
# This file is published using the MIT license.
# Refer to LICENSE for more information
#
""""""
# pylint: disable=C0302
# Justification: Code is generated
... | Python | 1 |
r as usize).unwrap() = true;
signatures.push(sig.bytes.clone());
}
let sig = aggregate_signature(&signatures[..]).unwrap();
self.aggregate_signature = Some(AggregateSignature {
signers: bv,
signature: SignatureBytes { bytes: sig },
... | Rust | 0 |
sbuf.push_str(&self.to_string());
// // unimplemented!("unsupported type!");
// }
// }
impl PutIntoBytes for Vec<u8> {
fn put_into_bytes(self, sbuf: &mut Vec<u8>) {
sbuf.extend_from_slice(&self);
}
}
impl PutIntoBytes for &Vec<u8> {
fn put_into_bytes(self, sbuf: &mut Vec<u8>) {
... | Rust | 0 |
#!/usr/bin/env python3
"""
- Captures video from a camera device
- Encodes video in H.264 (YouTube RTMP requirement)
- Streams directly to YouTube RTMP server
- Logs frame info and bandwidth in real-time
"""
# -------------------------------
# Import required libraries
# -------------------------------
import gi ... | Python | 1 |
er,
{
let mut headers = BTreeMap::new();
for (h, v) in self.headers.iter() {
headers.insert(h.as_str().into(), v.to_str().unwrap().into());
}
let status = self.status.as_u16();
let body = base64::encode(&self.body as &[u8]);
let s = SerializedMockResponse ... | Rust | 0 |
from PyQt6.QtCore import pyqtSignal
from PyQt6.QtGui import QCloseEvent
from PyQt6.QtWidgets import QMainWindow, QSizePolicy, QWidget
class SecondaryWindow(QMainWindow):
"""
Secondary window with `closed` signal.
Parameters
----------
title
The window title text.
central_widget
... | Python | 1 |
ain_group):
param_range_map = self.get_model_param_range_map(model_param)
param_range = param_range_map["param"]
assert param_range.size == shard_main_param.nelement()
model_grad = model_param.main_grad
shard_model_gra... | Python | 1 |
= parse_ucm(&request_mapping_file("ibm-1399_P110-2003").unwrap()).unwrap();
}
lazy_static! {
pub static ref IBM_16684_P100_1999: Encoding = parse_ucm(&request_mapping_file("ibm-16684_P100-1999").unwrap()).unwrap();
}
lazy_static! {
pub static ref IBM_16684_P110_2003: Encoding = parse_ucm(&request_mapping_file("... | Rust | 0 |
from tapas_gmm.encoder.keypoints import (
EncoderConfig,
KeypointsConfig,
KeypointsPredictorConfig,
PreTrainingConfig,
PriorTypes,
ProjectionTypes,
ReferenceSelectionTypes,
)
from tapas_gmm.viz.keypoint_selector import (
DisplayConfig,
DistanceMetricConfig,
ManualKeypointSelector... | Python | 1 |
self.in_channels[-1], 0, self.out_channels[-1], **kwargs
)
self.blocks = nn.ModuleDict(blocks)
self.depth = len(self.in_channels) - 1
def forward(self, features: List[torch.Tensor]) -> torch.Tensor:
features = features[1:] # remove first skip with same spatial resolution
... | Python | 1 |
idn't supply MREMAP_MAYMOVE, the address should be the
// same.
#[cfg(target_os = "netbsd")]
let mem = mremap(slice.as_mut_ptr() as * mut c_void, 10 * ONE_K, ONE_K,
MRemapFlags::MAP_FIXED, None)
.unwrap();
assert_eq !(mem, slice.as_mut_ptr()... | Rust | 0 |
{
return Err(AvroError::Decode(DecodeError::Custom(
"\"change_lsn\" is not a string".to_string(),
)))
}
}
}
"event_serial_no" => {
let ... | Rust | 0 |
detection_resource.rs
use bevy::prelude::*;
/// この Resource の追加と変更を検知する
#[derive(Component)]
struct Counter(usize);
fn count_and_add(
counter: Option<ResMut<Counter>>, // 存在するか不明なので Option
mut commands: Commands,
mut frame_count: Local<usize>,
) {
if let Some(mut counter) = counter {
// もし Res... | Rust | 0 |
Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "A... | Rust | 0 |
#
# Copyright (c) 2023 Airbyte, Inc., all rights reserved.
#
import re
import unidecode
from requests.status_codes import codes as status_codes
TOKEN_PATTERN = re.compile(r"[A-Z]+[a-z]*|[a-z]+|\d+|(?P<NoToken>[^a-zA-Z\d]+)")
DEFAULT_SEPARATOR = "_"
def name_conversion(text: str) -> str:
"""
convert name u... | Python | 1 |
byte S: 5, E: 4 is a 2 bit field or a 10 bit field without it) we just keep
// shifting until we run out of output bytes.
// TODO: Should field width in bits/bytes be a separate parameter? probably...
} else {
// i[n] contributes to o[n] and o[n-1]
// i[n] and o[n] might... | Rust | 0 |
次指令都重置位置后随机抢位 """
self.pretend_sleep: bool = False
""" 睡奸中醒来但是装睡的状态 """
self.sex_assist: bool = False
""" 性爱助手状态,False为不进行,True为进行 """
self.hidden_sex_discovery_dregree: int = 0
""" 隐奸中被发现的程度,int,初始为0,100时被发现 """
self.shoot_semen_amount: int = 0
""" H中射精的精... | Python | 1 |
called(available)
logger.info(f"Found running Work ({oldest_called_work.name}), calling `run()`")
oldest_called_work.run(*args, **kwargs)
return
# If all Works are at maximum capacity, check if we should trigger a scale up
if len(pending) == 0:
... | Python | 1 |
bd\
O\x0b\xf2P z\x9d\xca\x8a\xbbkut\x00\xe2\xf4\
\x8d\x14\xf0\x22\x0f\x1e<\xf8\xef\xae]\xbb\xbam\xb7\xc2\
?\xfc\xf0\xc3\xf3Ts?H\xfb\xeb\xac\x8e\xb5\xf8\x22\
)}\xd8\xb0a/\x8aM\xf8/\xfa\xbbn\x829M\
U\xc5f\x83#q0\xa7\x93s4e8\x1f8j\
\xc9\xab\x95o\xdd\xbau\x98X\x0d\xb8P\xbbv\xed\xaa\
\x5c\xbf~}\x13\x97\x89(\x1b5\xe4\xdd\x82... | Python | 1 |
variant of the `Value` enum,
//! // while `eval_[type]_with_context` returns the respective type directly.
//! // Both can be used interchangeably.
//! assert_eq!(eval_boolean_with_context("five + 8 > f(twelve)", &context), Ok(true));
//! assert_eq!(eval_with_context("avg(2, 4) == 3", &context), Ok(Value::from(true)))... | Rust | 0 |
from sulley import symmetry
from sulley import extract_neighbors
def test_symmetry_type_benzene():
smiles = "C1=CC=CC=C1"
mol = extract_neighbors.load_molecule(smiles)
index_to_matching_indices = symmetry.compute_symmetry_type(mol)
index_to_matching_indices_ref = {
0: [0, 1, 2, 3, 4, 5],
... | Python | 1 |
ed<Closure>, NonNull<Self>)> {
let closure_layout = ClosureLayout::for_env_len(0);
let layout = closure_layout.layout();
let mut non_null_heap_fragment = Self::new(layout.clone())?;
let heap_fragment = unsafe { non_null_heap_fragment.as_mut() };
heap_fragment
.export... | Rust | 0 |
from typing import List
class Solution:
def closestPrimes(self, left: int, right: int) -> List[int]:
def sieve_of_eratosthenes(n):
is_prime = [True] * (n + 1)
p = 2
while p * p <= n:
if is_prime[p]:
for i in range(p * p, n + 1, p):
... | Python | 1 |
verb'}, 'variants': ['bara'], 'frequency': 50, 'period': 'Biblical Hebrew'},
'דבר': {'meaning': 'word, thing', 'morphology': {'type': 'noun'}, 'variants': ['davar'], 'frequency': 200, 'period': 'Biblical Hebrew'}
}
}
def _load_greek_data(self) -> Dict[str, Any]:
"""L... | Python | 1 |
eeze().to(setting.device)
y_t_slot = y_t_slot.squeeze().to(setting.device)
optimizer.zero_grad()
forward_start = time.time()
loss = model_pre(x, y)
# loss_2 = model_time_transfer_pre(x, t_slot, y, y_t_slot)
lossx = loss
print(lossx)
lossx.backward()
... | Python | 1 |
ac_20;
let b1 = (x1 * z1 * _2 + x2 * z1 + x3 * z1 + x4 * z1 +
x1 * z2 + x2 * z2 * _2 + x3 * z2 + x4 * z2 +
x1 * z3 + x2 * z3 + x3 * z3 * _2 + x4 * z3 +
x1 * z4 + x2 * z4 + x3 * z4 + x4 * z4 * _2) * _frac_20;
let c1 = (x1 * y1... | Rust | 0 |
dows").unwrap())
} else {
PathBuf::from(&manifest.entry_point)
};
if !path.is_absolute() || !path.exists() {
path = PathBuf::from(manifest.plugin_dir.clone()).join(path);
}
debug!("Starting plugin using {:?}", path);
let log_level = max_level();
let child = Command::new(path)
.env("LOG_LEVEL... | Rust | 0 |
import sqlite3
from tkinter import messagebox
# Función para insertar un nuevo préstamo en la base de datos
def insertar_prestamo(fecha_prestamo, fecha_entrega, idlibro, idusuario):
try:
# Conexión a la base de datos
conn = sqlite3.connect('ABIBLIOTECA.db')
cursor = conn.cursor()
#... | Python | 1 |
.case_insensitive(true)
.build()
.expect("Invalid Regex");
static ref RE_REMOVE_FT_DOT: Regex = RegexBuilder::new(r" ft\.(.*)")
.case_insensitive(true)
.build()
.expect("Invalid Regex");
static ref RE_GOOD_CHARS_ONLY: Regex = Regex::new(r"[^a-z... | Rust | 0 |
eturn points
class IntegralAffinePlaneCurve(IntegralAffineCurve, AffinePlaneCurve_field):
_point = IntegralAffinePlaneCurvePoint
class IntegralAffinePlaneCurve_finite_field(AffinePlaneCurve_finite_field, IntegralAffineCurve_finite_field):
"""
Integral affine plane curve over a finite field.
EXAMPLE... | Python | 1 |
vacy)
if contacts is None and contact_privacy is None:
# Nothing to update.
return None
new_privacy = contact_privacy or registration.contactSettings.privacy
privacy = client.messages.ContactSettings.PrivacyValueValuesEnum
if not public_contacts_ack and new_privacy == privacy.PUBLIC_CONTAC... | Python | 1 |
#!/usr/bin/python
# Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | Python | 1 |
= R.from_matrix(M).as_quat()
print('Corresponding quaternion: ', quat)
obj_pos = env.obj_pos
camera_trans = 3*np.array([-0.77542536, -0.02539806, 0.30146208])
# set_camera_pose(env, 'sideview', [-0.77542536, -0.02539806, 2.20146208], [-0.005696068282031459, 0.19181093598117868, 0.029131527990... | Python | 1 |
def dichoto(n):
a, b = 1, 2
for k in range(n):
x = (a+b)/2
if x**3 - x**2 -x -1 < 0 :
a = x
else :
b = x
print(k+1, x, x**3 - x**2 - x -1 < 0, a, b)
return a, b
print(dichoto(int(input()))) | Python | 1 |
tion(
[
-0.20,
-0.40,
-0.19,
0.20,
-0.40,
-0.19,
-0.40,
-0.90,
1.18,
... | Python | 1 |
view:has_side_up(front);viewcon:false()'}
obj = update_or_create_object('Mnewbie2', **data)
affected.append(obj)
data = {'typeclass': 'systems.money.shopping.scripts.ShopManager', 'name': 'D.C. Wilde', 'desc': None, 'obj': None, 'interval': -1, 'repeats': 0, 'persistent': True, 'start_delay': False, 'attributes': [('st... | Python | 1 |
[entry]
fn main() -> ! {
unsafe {
// read an address outside of the RAM region; this causes a HardFault exception
ptr::read_volatile(0x2FFF_FFFF as *const u32);
}
loop {}
}
// "hello world" of graphics - nice rainbow gradient image
// usage: cargo run --bin graphics_hello_world >> image.ppm... | Rust | 0 |
/ 2
rf_r = 1.27 * X_T / r * sqrt(X_D / X_T - 0.3)
m = sqrt(2 * h_a * cs_cp / (k_fin * delta_f)) #cs_cp is the correction for heat/mass transfer
#Using the circular fin correlation of Schmidt
phi = (rf_r - 1) * (1 + 0.35 * log(rf_r))
eta_f = tanh(m * r * phi) / (m * r * phi)
# Fin effi... | Python | 1 |
val
eval.evaluate()
eval.accumulate()
eval.summarize()
if self.is_lvis:
eval.print_results()
idx = i * 4 + 2
# update mAP50-95 and mAP50
stats[self.metrics.... | Python | 1 |
": {}
},
"key": "alice"
}
"#
.trim();
assert_that!(serde_json::to_string_pretty(&output_event))
.is_ok_containing(event_json.to_string());
}
}
#[test]
fn serializes_alias_event() {
let user = User::with_key("alice".to_string()).anonymous(... | Rust | 0 |
he main equation with the exact equation after running replace_real_numbers
replaced_y_exact_equation = sympify(main_equation).subs("y", exact_equation)
replaced_y_exact_equation = replace_real_numbers(replaced_y_exact_equation)
if x_term:
replaced_y_exact_equation= ... | Python | 1 |
import pytest
import spacy
from pytest import fixture
from spacy.tokens import Span
from typing_extensions import Literal
import edsnlp
import edsnlp.pipes as eds
pytest.importorskip("torch.nn")
if not Span.has_extension("cui"):
Span.set_extension("cui", default=None)
@fixture
def gold():
blank_nlp = edsnl... | Python | 1 |
t(
backend: Backend,
cipher: _AEADTypes,
nonce: bytes,
data: bytes,
associated_data: typing.List[bytes],
tag_length: int,
ctx: typing.Any = None,
) -> bytes:
from cryptography.hazmat.primitives.ciphers.aead import AESCCM, AESSIV
if len(data) < tag_length:
raise InvalidTag
... | Python | 1 |
# coding=utf-8
# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed ... | Python | 1 |
}).map_err(|err| eprintln!("{}", err));
let mri =
DockerModuleRuntime::new(&Url::parse(&format!("http://localhost:{}/", port)).unwrap())
.unwrap()
.with_network_id("azure-iot-edge".to_string());
//act
let task = mri.init();
let mut runtime = tokio::runtime::current_thr... | Rust | 0 |
}},
{"7ny5k0k28", Box{-6.4585018158, -6.45845890045, -36.3808822632, -36.3808393478}},
{"w7", Box{16.875, 22.5, 101.25, 112.5}},
{"f9j0296wjz", Box{50.6768792868, 50.6768846512, -60.443097353, -60.4430866241}},
{"v316n9gu7y5", Box{50.9869372845, 50.9869386256, 58.2987718284, 58.2987731695}},
{"9", Box{0.0, 45.0, -... | Rust | 0 |
///
/// This value sets the time-to-live field that is used in every packet sent
/// from this socket.
///
pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
self.0.set_ttl(ttl)
}
/// Gets the value of the `IP_TTL` option for this socket.
///
/// For more information about this... | Rust | 0 |
handled as *mut bool).write(true);
}
}
0
}
}
pub fn call_native_fn<Args>(hook: &'static Hook, parameters: Args) -> HookResult
where
Args: Sized,
HookParameters: From<Args>,
{
*EXECUTION_METHOD.lock().unwrap() = Some(hook);
*EXECUTION_RESULT.lock().unwrap() = match hook.f... | Rust | 0 |
so it doesn't need to go through the session sender and handshake
// phase.
let inspector_session =
InspectorSession::new(self.v8_inspector.clone(), proxy);
self
.sessions
.borrow_mut()
.established
.push(inspector_session);
take(&mut self.flags.borrow_mut().waiting_for_ses... | Rust | 0 |
e the configuration data and verify that it acknowledges.
//! let message = Message::RequestOperation(Address(3), Operation::ReceiveConfig);
//! let response = bus.process_message(message)?;
//! assert_eq!(Some(Message::AckOperation(Address(3), Operation::ReceiveConfig)), response);
//!
//! #
//! # Ok(()) }
//! ```
//!... | Rust | 0 |
###
# The weather station report
#
temperatures = [
3, 7, 1, -2, 6, -4, 5, 1, 2, 3,
4, -1, 0, 2, -1, -2, 5, -2, 7, 2,
-1, 4, 1, -4, 2, 3, 6, 7, 5, 7
]
# number of mesaurements
mesaurements = len(temperatures)
# calculates average temperature
temp_total = 0
for temp1 in temperatures:
temp_total += temp1
avg_... | Python | 1 |
704, 736, 768, 800]
if image_set == 'train':
return T.Compose([
T.RandomHorizontalFlip(),
T.RandomSelect(
T.RandomResize(scales, max_size=1333),
T.Compose([
T.RandomResize([400, 500, 600]),
T.RandomSizeCrop(384... | Python | 1 |
# Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | Python | 1 |
from securityheaders.models import ExpectCT
from securityheaders.checkers import Finding, FindingType, FindingSeverity
from .checker import ExpectCTChecker
class ExpectCTNotEnforcedChecker(ExpectCTChecker):
def check(self, headers, opt_options=dict()):
findings = []
expectct = self.getexpectc... | Python | 1 |
import pandas as pd
import ast
from scipy.spatial import distance
from io import BytesIO
import requests
from test_embedding import embedding
def load_embeddings_from_excel(url):
response = requests.get(url)
if response.status_code == 200:
excel_data = BytesIO(response.content)
df = pd.read_ex... | Python | 1 |
ax length
# Telegram maximum Poll Question length is 300
"CAPTCHABOT_MAX_POLL_QUESTION_LENGTH": 300,
# Poll captcha question max length
# Telegram maximum Poll Option length is 100
"CAPTCHABOT_MAX_POLL_OPTION_LENGTH": 100,
# Standard auto-remove messages sent by Bot timeout (in seconds)
"C... | Python | 1 |
|
| | j g f }
| j
| j
| f d k rK| | j
| j
| f <n/ | | j
| d
j
| d
f <d GH| d
} nNxKt
j d
D]6} x-t
j d D]} | | f | k r j g t | | | j | k r(| j k r j } qqn j | k rX|
j k r... | Python | 1 |
!= 0.0:
integer_local_sum = fe_htz.negative_cycle_in_count[0] + fe_htz.positive_cycle_in_count[0] + fe_htz.negative_cycle_in_count[1] + fe_htz.positive_cycle_in_count[1];
if integer_local_sum>0:
fe_htz.gain_off = fe_htz.GAIN_OFFSET_REALTIME * fe_htz.GAIN_OFFSET_INIT / (integer_lo... | Python | 1 |
eq!(t, output);
}
#[test]
fn one_row() {
let v = vec![vec![
"hello".into(),
"a".into(),
"shrt".into(),
"very long perhaps a few words".into(),
]];
let t = format_table(&v);
let output = String::from("hello a shrt very long perh... | Rust | 0 |
32,
}
impl FormatLogLine for Log4JJsonLayoutLogLine {
fn format(&self) -> ColoredString {
colored_with_level(
&self.level,
&format!("{} {}", &self.format_meta(), &self.message.bold()),
)
}
}
impl ToColoredString for Log4JJsonLayoutLogLine {
fn to_colored_string(entry: &Value) -> Option<Color... | Rust | 0 |
jor_frac[::-1] if flip else major_frac
use_mask = (major_frac > -0.0001) & (major_frac < 1.0001)
major_frac = major_frac[use_mask]
labels = [l for li, l in enumerate(labels) if use_mask[li]]
minor_frac = (np.array(minor) - offset) / scale
use_minor_mask = (mi... | Python | 1 |
'factor_calculation': factor_results
}), 404
# 步骤3: 计算综合分数
composite_scores = get_scoring_engine().calculate_composite_score(factor_scores, weights, method)
# 步骤4: 股票排名选择
top_stocks = get_scoring_engine().rank_stocks(composite_scores, top_n)... | Python | 1 |
import numpy as np
import torch.nn as nn
from annotator.mmpkg.mmcv.cnn import ConvModule
from annotator.mmpkg.mmseg.ops import resize
from ..builder import HEADS
from .decode_head import BaseDecodeHead
@HEADS.register_module()
class FPNHead(BaseDecodeHead):
"""Panoptic Feature Pyramid Networks.
This head is... | Python | 1 |
return data_dict
def main():
"""Run main logic."""
# validate vars
var_validation()
print("")
print(f"Base URL: {BASE_URL}")
print("")
# dict placeholder for params passed to api requests
params_dict = {}
# Get all device inventory records
print("Getting device inventory f... | Python | 1 |
use datafusion::logical_plan::{col, lit, lit_timestamp_nano};
use std::convert::TryFrom;
#[test]
fn to_binary_expr() {
let cases = vec![
(
// a = 22
col("a").eq(lit(22_i64)),
BinaryExpr::from(("a", "=", 22_i64)),
),
... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.