text string | label_name string | labels int64 |
|---|---|---|
from scipy.io import loadmat
import numpy as np
from sklearn import datasets
def loadData(datasetname):
dataset=loadmat('./data/'+datasetname+'.mat')
# dataset=datasets.load_
features=dataset['X']
# print(features.shape)
labels = dataset['y']
# print(np.where(labels==0)[0])
normal_data = fea... | Python | 1 |
se Roman routine).
applyIPC(img)
# Read noise.
gn = GaussianNoise(rng, sigma=read_noise)
img.addNoise(gn)
# Gain.
img /= gain
# Quantize.
img.quantize()
return prev_exposures
allDetectorEffects.__doc__ = """
This utility applies all sources of noise and detector effects for Roma... | Python | 1 |
, "不应该有包装元素")
# 确保SVG内容依然存在
self.assertIn('<svg', content, "输出文件缺少SVG标签")
def test_precision_option(self):
"""测试精度选项"""
# 使用3位小数精度的转换器
converter_high_precision = SVG2HTML(conversion_mode="convert", precision=3)
input_file = os.path.join(self... | Python | 1 |
elf.as_ref().to_glib_none().0,
name.to_glib_none().0,
);
}
}
fn connect_provider_hidden<F: Fn(&Self, &str) + Send + Sync + 'static>(
&self,
f: F,
) -> SignalHandlerId {
unsafe extern "C" fn provider_hidden_trampoline<
P: IsA<DeviceProv... | Rust | 0 |
from rest_framework.viewsets import ModelViewSet
from .models import Candidat, Recruteur
from .serializers import CandidatSerializer, RecruteurSerializer
# Vue pour les candidats
class CandidatViewSet(ModelViewSet):
queryset = Candidat.objects.all()
serializer_class = CandidatSerializer
# Vue pour les recrute... | Python | 1 |
#!/usr/bin/env python3
#
# Copyright 2002-2025 Barcelona Supercomputing Center (www.bsc.es)
#
# 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... | Python | 1 |
ay a UTC error,
/// expressed as a PPM deviation from nominal.
const MAX_RATE_CORRECTION_PPM: i64 = 200;
/// The clock frequency adjustment that Timekeeper will prefer when slewing away a UTC error,
/// expressed as a PPM deviation from nominal.
const NOMINAL_RATE_CORRECTION_PPM: i64 = 20;
/// The longest duration fo... | Rust | 0 |
wrap_or_else(|| "(not set)".into()),
);
}
// actual decompression
let mut total_bytes = 0;
loop {
let (bytes, final_block) = decompress_block(&mut reader, &mut writer)?;
total_bytes += bytes;
if final_block {
break;
}
}
// TODO: check unread ... | Rust | 0 |
;
inst.operands[0] = OperandSpec::R0;
inst.operands[1] = OperandSpec::Nothing;
}
_ => {
return Err(StandardDecodeError::InvalidOpcode);
}
}
}
_ => {
return Err(StandardDeco... | Rust | 0 |
is off or unavailable
Off,
}
/// Response fields for 'power' query
#[derive(GraphQLObject)]
pub struct GetPowerResponse {
/// Current power state of the system
pub state: PowerState,
/// A value of 1 confirms that the system is on.
/// A value of 0 confirms that the system is off or unavailable
... | Rust | 0 |
from havoc import Demon, RegisterCommand, RegisterModule
from os.path import exists
def uac_bypass(demon_id, *args):
task_id: str = None
demon: Demon = None
packer: Packer = Packer()
binary: bytes = None
# Get agent id
demon = Demon(demon_id)
shell_path = args[0]
shell_args = args[1]
... | Python | 1 |
# Atividade 07:
# Contagem de Vogais em uma Palavra:
# Crie um programa que solicite uma palavra ao usuário e use um laço for com
# uma condicional para contar quantas vogais (a, e, i, o, u) a palavra contém.
word = 'Patati ' | Python | 1 |
import triton
import triton.language as tl
import torch
import math
@triton.jit
def add_helper(x, y):
return x + y
@triton.jit
def add_kernel(
in_ptr0,
in_ptr1,
n_elements,
out_ptr,
BLOCK_SIZE: "tl.constexpr",
):
pid = tl.program_id(axis=0)
block_start = pid * BLOCK_SIZE
offsets... | Python | 1 |
pub engine_version: Version,
/// The name of the game engine.
pub engine_name: String,
/// The version of the game/application.
pub app_version: Version,
/// The name of the game/application.
pub app_name: String,
}
impl Default for InstanceOpt {
fn default() -> Self {
Self ... | Rust | 0 |
"current"
displayHint = "d"
subtypeSpec = Unsigned32.subtypeSpec
subtypeSpec += ConstraintsUnion(
ValueRangeConstraint(0, 2040),
)
class InetPortNumber(TextualConvention, Unsigned32):
status = "current"
displayHint = "d"
subtypeSpec = Unsigned32.subtypeSpec
subtypeSpec += Cons... | Python | 1 |
#[inline(always)]
pub fn read(&self) -> R {
R {
bits: self.register.get(),
}
}
#[doc = r"Writes to the register"]
#[inline(always)]
pub fn write<F>(&self, f: F)
where
F: FnOnce(&mut W) -> &mut W,
{
self.register.set(
f(&mut W {
... | Rust | 0 |
note,
pan,
} => context.send_event(NoteEvent::PolyPan {
timing,
channel: 15 - channel,
note: 127 - note,
pan: 1.0 - pan,
}),
NoteEvent::PolyTuning {
... | Rust | 0 |
"""Test helpers."""
from collections.abc import Generator
from unittest.mock import AsyncMock, patch
import pytest
from homeassistant.components.solarlog.const import DOMAIN as SOLARLOG_DOMAIN
from homeassistant.const import CONF_HOST, CONF_NAME
from .const import HOST, NAME
from tests.common import MockConfigEntr... | Python | 1 |
"""Gitee SDK 仓库操作示例。
本示例展示了如何使用Gitee SDK进行仓库的基本操作,包括:
- 创建新仓库
- 获取仓库信息
- 更新仓库设置
- 删除仓库
"""
import logging
from gitee import GiteeClient
from gitee.exceptions import GiteeException
# 初始化Gitee客户端
# 请替换为你的访问令牌
ACCESS_TOKEN = "87fc372188a81d0efd3fcb3863a2154d"
client = GiteeClient(ACCESS_TOKEN)
def main():
# 配置日志
... | Python | 1 |
"""
Numerical integration
=====================
Calculation of a mixtures of logit models where the integral is
calculated using numerical integration.
Michel Bierlaire, EPFL
Sat Jun 28 2025, 21:09:58
"""
from IPython.core.display_functions import display
from biogeme.biogeme import BIOGEME
from biogeme.expressions... | Python | 1 |
import numpy as np
from sklearn import neighbors
def build_balltree(embedding_list):
article_embeddings = np.array(embedding_list)
normalized_article_embeddings = article_embeddings / np.linalg.norm(
article_embeddings, axis=1, keepdims=True)
article_tree = neighbors.BallTree(normalized_article_em... | Python | 1 |
ctChannelRequest: Serialize {
/// Type of the data we receive from the channel.
type Incoming: DeserializeOwned + 'static;
/// Type of the data we send to the channel.
type Outgoing: Serialize + 'static;
/// The name of the channel to be connected by this request.
const NAME: &'static str;
}
i... | Rust | 0 |
print("DESAFIO BICICLETA".center(40,"-"))
class bicicleta:
def __init__(self, cor, modelo, ano, valor, aro=18):
self.cor = cor
self.modelo = modelo
self.ano = ano
self.valor = valor
self.aro = aro
def buzina(self):
print("plinplim...")
def parar(self):
... | Python | 1 |
&'a mut W {
self.bit(false)
}
#[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 << 5)) | (((value as u32) & 0x01) << 5);
self.w
}
}
#[doc = "PIOn_6.\n\nValue on reset: 0"]
#[derive(Clone... | Rust | 0 |
("If-Modified-Since", h).send().await
} else {
client.get(uri).send().await
};
match response {
Ok(response) => {
// seen it before, skip it now
if 304 == response.status() {
return Err(Error::ResourceUnchanged);
}
let last_mod... | Rust | 0 |
/// Acquires a reference to the underlying reader.
pub fn get_ref(&self) -> &R {
self.0.get_ref()
}
/// Acquires a mutable reference to the underlying stream.
///
/// Note that mutation of the stream may result in surprising results if
/// this encoder is continued to be used.
pu... | Rust | 0 |
5`9\x97>\xc2\xd4U\xa8g\xfd\xeb_p\xff\
\x00\x16\xbd\xb85\xcf\xf7\xac\xbc\xc2\x9335\x8e\xb9V\
\xee\xab\xbdI\x8a\x0a\xf0\x0c\xe1\x86\xe4\x9a\xac\x1b\x18\xc6\
(\x9ey\xb3\x86#.\x17\x94\xdc\xc6^8\xa5H\x99\
\xfc\xf7\xefe;HR|x\x0b\xc9\xdfr\xcd\xbe\xfb\
L\x92|3\xe7\xb6\x85\xf9\xae\x5c\xab\xff\x00\xd86`\
!2\xbf\xc2\x9b\xf0_P9\x0... | Python | 1 |
#!/usr/bin/env python3
#
# Copyright 2018-present Facebook. All Rights Reserved.
#
# This program file 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; version 2 of the License.
#
# This program is distributed ... | Python | 1 |
nect(sectionList[3282](1),0)
sectionList[3284].connect(sectionList[3283](1),0)
sectionList[3285].connect(sectionList[3284](1),0)
sectionList[3286].connect(sectionList[3285](1),0)
sectionList[3287].connect(sectionList[3286](1),0)
sectionList[3288].connect(sectionList[3287](1),0)
sectionList[3289].connect(sectionList[328... | Python | 1 |
"""
Regression tests for custom manager classes.
"""
from django.db import models
class RestrictedManager(models.Manager):
"""
A manager that filters out non-public instances.
"""
def get_query_set(self):
return super(RestrictedManager, self).get_query_set().filter(is_public=True)
class Relat... | Python | 1 |
_filesystem(filesystem, file, path.to_str().unwrap()).expect("Cannot write file to filesystem");
}
}
}
Ok(())
}
fn main() {
env_logger::init();
if env::args().len() < 4 {
println!("usage: <disk_name> <disk_size> <template_path>");
std::process::exit(1);
}
l... | Rust | 0 |
from django.db import models
from django.http import HttpResponse
import unicodecsv as csv
class Customer(models.Model):
"""
Represents a customer (company or similar entity) in the accounting system.
"""
# Basic information
name = models.CharField(max_length=255)
address = models.TextField(b... | Python | 1 |
.unspent(swap.secondary_currency, &address)
{
Ok(r) => r,
Err(_) => self
.btc_node_client2
.lock()
.unspent(swap.secondary_currency, &address)?,
};
for output in outputs {
secondary_lock_amount += output.value;
if output.height == 0 {
// Output in mempool
... | Rust | 0 |
"""高速网络 Highway Network
注意 x 经过 Highway 之后维度应该保持不变
References:
https://github.com/fomorians/highway-fcn
https://github.com/fomorians/highway-cnn
"""
import tensorflow as tf
from ..utils import get_wb
from ..activations import relu, sigmoid
def highway_dense(x, act_fn=relu, carry_bias=-1.0, name=None):
... | Python | 1 |
());
}
#[test]
fn parse_gnd_bond_overflow()
{
let gnd_overflow_str = "GND HI-Limit 0.4sM 1-1 0.00A >600mΩ";
let res = gnd_overflow_str.parse::<ArTestData>();
match res {
Ok(ref test_data) => println!("{:#?}", test_data.data),
Err(ref err) => {
... | Rust | 0 |
d_small(self, &v.0[((s >> 6) as usize)..], s & 63);
}
}
fn add_shifted_small(&mut self, v: &[u64], s: i32) {
let mut cc = 0u64;
let j = 10 - v.len();
let mut vbits = 0u64;
for i in j..10 {
let vw = v[i - j];
let vws = vw.wrapping_shl(s as u32) | v... | Rust | 0 |
ob) {
let job_id = job.job_id;
assert!(self
.base_task_id_to_job_id
.insert(job.base_task_id, job_id)
.is_none());
assert!(self.jobs.insert(job_id, job).is_none());
}
/*pub fn get_job_mut_by_tako_task_id(&mut self, task_id: TakoTaskId) -> Option<&mut ... | Rust | 0 |
b"-accuratedct = Use the most accurate DCT/IDCT algorithms available in the\n\x00"
as *const u8 as *const libc::c_char,
);
crate::stdlib::printf(b" underlying codec\n\x00" as *const u8 as *const libc::c_char);
crate::stdlib::printf(
b"-progressive = Use progressive entropy codin... | Rust | 0 |
workers ready.")
cum_loss = cum_over = cum_tot = 0.0
done = 0
t_start = time.perf_counter()
for lost, over, tot in pool.imap_unordered(
run_scenario,
range(TOTAL_SAMPLES),
chunksize=CHUNK):
... | Python | 1 |
-no_metadata",
action="store_true",
help="do not save sai modelspec metadata (minimum ss_metadata for LoRA is saved) / "
+ "sai modelspecのメタデータを保存しない(LoRAの最低限のss_metadataは保存される)",
)
parser.add_argument(
"--concat",
action="store_true",
help="concat lora instead of... | Python | 1 |
n,
};
use protocol::{Bytes, ProtocolResult};
use crate::types::{DeployPayload, ExecPayload, GetContractPayload, InterpreterType};
use crate::RiscvService;
type TestRiscvService = RiscvService<
DefalutServiceSDK<
GeneralServiceState<MemoryDB>,
DefaultChainQuerier<MockStorage>,
MockDispatche... | Rust | 0 |
f the used ring entry.
pub fn len(&self) -> u32 {
self.len.into()
}
}
// This is safe because `VirtqUsedElem` contains only wrappers over POD types and all accesses
// through safe `vm-memory` API will validate any garbage that could be included in there.
unsafe impl ByteValued for VirtqUsedElem {}
#[... | Rust | 0 |
lf.dtype))
}
async fn read_values(self, txn: Self::Txn, coords: Coords) -> TCResult<Array> {
let dtype = self.dtype;
self.source
.read_values(txn, coords)
.map_ok(|values| values.cast_into(dtype))
.await
}
}
impl<FD, FS, D, T, B> ReadValueAt<D> for Bloc... | Rust | 0 |
from opencompass.openicl.icl_prompt_template import PromptTemplate
from opencompass.openicl.icl_retriever import FixKRetriever
from opencompass.openicl.icl_inferencer import PPLInferencer
from opencompass.openicl.icl_evaluator import AccEvaluator
from opencompass.datasets import CMMLUDataset
from opencompass.utils.text... | Python | 1 |
normal() {
assert_eq!(
rsass(
"@function foo($map) {\
\n @return $map;\
\n}\
\n\
\na {\
\n $map: foo((this: is, my: map));\
\n @each $k, $v in $map {\
\n #{$k}: $v;\
\n }\
... | Rust | 0 |
pub fn get_application_display_service(&self) -> mem::Shared<vi::ApplicationDisplayService> {
self.application_display_service.clone()
}
pub fn get_hos_binder_driver(&self) -> mem::Shared<dispdrv::HOSBinderDriver> {
self.hos_binder_driver.clone()
}
fn stray_layer_destroy(layer_id: vi... | Rust | 0 |
from typing import List
def string_xor(a: str, b: str) -> str:
""" Input are two strings a and b consisting only of 1s and 0s.
Perform binary XOR on these inputs and return result also as a string.
>>> string_xor('010', '110')
'100'
"""
return ''.join(chr(int(x, 2) ^ int(y, 2)) for x, y in zip... | Python | 1 |
argv: &[Value]) -> MoltResult {
//! // Pretend it passed
//! interp.context::<Stats>(context_id).num_passed += 1;
//!
//! molt_ok!()
//! }
//! ```
//!
//! # Ensemble Commands
//!
//! An _ensemble command_ is simply a command with subcommands, like the standard Molt `info`
//! and `array` commands. At the R... | Rust | 0 |
proof).await
{
panic!("Error validating audit proof {:?}", error);
}
}
(Err(err), _) => {
panic!("Error retrieving root hash at epoch {:?}", err);
... | Rust | 0 |
s from the convex program.
This approach is both scalable and theoretically sound, ensuring a quick
approximation of the densest subgraph while leveraging fractional load
balancing.
References
----------
.. [1] Charikar, Moses. "Greedy approximation algorithms for finding dense
componen... | Python | 1 |
: u64, m: u64) -> u64 {
match m {
0 => a,
1 => b,
_ => helper(b, a + b, m - 1),
}
}
helper(0, 1, n)
}
use crate::common::*;
use strum::{EnumString, IntoStaticStr};
#[derive(Debug, Eq, PartialEq, EnumString, IntoStaticStr, Copy, Clone)]
#[strum(serialize_all ... | Rust | 0 |
import logging
import os
import tempfile
import shutil
import json
from subprocess import check_call, check_output
from tarfile import TarFile
from dateutil.zoneinfo import METADATA_FN, ZONEFILENAME
def rebuild(filename, tag=None, format="gz", zonegroups=[], metadata=None):
"""Rebuild the internal timezone info ... | Python | 1 |
{
app::{App, CoreStage, Plugin, StartupStage},
asset::{AssetEvent, Assets, Handle, HandleId},
ecs::{
event::EventReader,
schedule::{ParallelSystemDescriptorCoercion, SystemLabel},
system::ResMut,
},
input::InputSystem,
log,
render::{render_graph::RenderGraph, texture:... | Rust | 0 |
"""IBAN."""
# standard
import re
# local
from .utils import validator
def _char_value(char: str):
"""A=10, B=11, ..., Z=35."""
return char if char.isdigit() else str(10 + ord(char) - ord("A"))
def _mod_check(value: str):
"""Check if the value string passes the mod97-test."""
# move country code an... | Python | 1 |
"""
@Author : ling chen
@Create : 2024/12
@Last modify: 2024/12
@Description: 配置文件,定义了一些关于 trace_crossresistance 数据集的全局常量,包括数据文件地址的存储等
"""
import os
# 获取当前脚本文件的绝对路径
Absolute_address = os.path.dirname(os.path.realpath(__file__)).replace("\\", "/")
# 相对路径
DIRECTORY_PREFIX = Absolute_address + "/DataFil... | Python | 1 |
_y: f64, zoom: u64) -> Self{
// Coordinates{
// fractal_x,
// fractal_y,
// aspect_ratio: ASPECT_RATIO,
// zoom,
// }
// }
pub fn set_pos(&mut self, fractal_x: f64, fractal_y: f64) {
self.fractal_x = fractal_x;
self.fractal_y = fra... | Rust | 0 |
ull_mode: None,
unclipped_depth: false,
polygon_mode: PolygonMode::Fill,
conservative: false,
topology: PrimitiveTopology::TriangleList,
strip_index_format: None,
},
depth_stencil: None,
multisample: Mult... | Rust | 0 |
x::query!(
"UPDATE files SET local_path = $1, file_name = $2 WHERE id = $3",
file.local_path,
file.file_name,
file.id
)
.execute(&self.pool)
.await?;
Ok(())
}
async fn get_file_by_remote_id(&self, remote_id: String) -> Result<Optio... | Rust | 0 |
greater(&self, s: Slope) -> bool {
self.y * s.x > self.x * s.y
}
// this > y/x
pub fn greater_or_equal(&self, s: Slope) -> bool {
self.y * s.x >= self.x * s.y
}
// this >= y/x
pub fn less_or_equal(&self, s: Slope) -> bool {
self.y * s.x <= self.x * s.y
} // this <=... | Rust | 0 |
nd_element(*self.locators.driver_message).send_keys(message_for_driver)
def get_message(self):
return self.driver.find_element(*self.locators.driver_message).get_property('value')
def click_requirements(self):
self.driver.implicitly_wait(15)
self.driver.find_element(*self.locators.orde... | Python | 1 |
fn get_name(&self) -> String {
String::from("map")
}
fn required_arg_types(&self) -> Vec<TypeId> {
vec![self.unary_scalar_func_type, self.vector_type]
}
fn ret_type(&self) -> TypeId {
self.vector_type
}
}
impl FuncImpl for MapImpl {
fn evaluate(&self, state : &mut Interp... | Rust | 0 |
7[21][5] = {
{ 0, 1, 2, 3, 4 },
{ 0, 1, 2, 3, 5 },
{ 0, 1, 2, 3, 6 },
{ 0, 1, 2, 4, 5 },
{ 0, 1, 2, 4, 6 },
{ 0, 1, 2, 5, 6 },
{ 0, 1, 3, 4, 5 },
{ 0, 1, 3, 4, 6 },
{ 0, 1, 3, 5, 6 },
{ 0, 1, 4, 5, 6 },
{ 0, 2, 3, 4, 5 },
{ 0, 2, 3, 4, 6 },
{... | Rust | 0 |
t structure = construct_structure_variants!(
structure_type => reference.into_expected_type()?
);
Ok(structure)
}
}
impl TryFrom<Reference> for Structure {
type Error = ConversionError;
fn try_from(reference: Reference) -> Result<Self, ConversionError> {
let structure_... | Rust | 0 |
import sys
class SysArgs:
JIRA_ISSUE = sys.argv[6]
| Python | 1 |
u16, pub u16,
pub u16, pub u16, pub u16, pub u16);
#[repr(simd)]
#[derive(Copy, Clone, Debug)]
#[repr(C)]
pub struct u32x4(pub u32, pub u32, pub u32, pub u32);
#[repr(simd)]
#[derive(Copy, Clone, Debug)]
#[repr(C)]
pub struct u64x2(pub u64, pub u64);
#[repr(simd)]
#[derive(Copy, Clone, Debug)]
#[re... | Rust | 0 |
if isinstance(optimizer, DistributedFusedAdam):
return optimizer.state_dict(gather_on_root=False)
else:
return optimizer.state_dict()
def save_checkpoint(
self, checkpoint: Dict[str, Any], filepath: _PATH, storage_options: Optional[Any] = None
) -> None:
""... | Python | 1 |
import pytest
from shared.tests import TestBaseFixture
@pytest.mark.django_db
class TestUserListModelSerializer(TestBaseFixture):
pass
| Python | 1 |
S::Ok, S::Error> {
serializer.serialize_str(&hex::encode_upper(&self.0))
}
}
impl InternalToHex for [u8; 32] {
fn to_hex<S: serde::ser::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str(&hex::encode_upper(&self))
}
}
#[derive(Debug, Clone, PartialEq, D... | Rust | 0 |
n load_certs_from_reader(rd: &mut dyn BufRead) -> Result<Vec<Certificate>, IoError> {
certs(rd).map_err(|_| IoError::new(ErrorKind::InvalidInput, "invalid cert"))
}
/// Load the passed keys file
pub fn load_keys<P: AsRef<Path>>(path: P) -> Result<Vec<PrivateKey>, IoError> {
load_keys_from_r... | Rust | 0 |
_name("threads")
.long("threads")
.short("t")
.takes_value(true)
.default_value("1")
.help("Number of threads"),
)
}
fn polish(matches: &clap::ArgMatches) -> std::io::Result<()> {
let contigs = matches
.value_of("contig... | Rust | 0 |
();
debug!(
"Generated issuance request for {} ({} coins, tiers {:?})",
amount,
requests.coin_count(),
requests.coins.keys().collect::<Vec<_>>()
);
let sig_req = SignRequest(blinded_nonces);
let issuance_req = CoinFinalizationData { coins... | Rust | 0 |
# Constantes pour les couleurs
jaune = '\033[0;93m'
vert = '\033[0;92m'
rouge = '\033[0;91m'
cyan = '\033[0;96m'
magenta = '\033[0;35m'
reset = '\033[0m' | Python | 1 |
from time import sleep
import allure
from WebUIAutoshop.common.log import log
from WebUIAutoshop.pom.page.GoodsDetails import GoodsDetails
from WebUIAutoshop.pom.page.Login import Login
from WebUIAutoshop.pom.page.UserCenter import UserCenter
from WebUIAutoshop.settings import ENV
class Event:
@staticmethod
@... | Python | 1 |
Clock {
reset: CLK_RST_CONTROLLER_RST_DEVICES_H,
enable: CLK_RST_CONTROLLER_CLK_OUT_ENB_H,
source: CLK_NO_SOURCE,
index: 0x10,
clock_source: 0,
clock_divisor: 0,
};
pub const DSIB: Clock = Clock {
reset: CLK_RST_CONTROLLER_RST_DEVICES_U,
enable: ... | Rust | 0 |
pl Entry {
pub fn kind(&self) -> &'static str {
match self {
Entry::Datatype { .. } => "datatype",
Entry::Module { .. } => "module",
}
}
}
#[derive(Debug, Clone)]
pub enum DatatypeIdent {
Builtin(BuiltinType),
Array(Box<DatatypeIdent>),
Ident(Rc<Datatype>),
}... | Rust | 0 |
ssert "vDDDTypes" in repr(vDDDTypes(timedelta(3, 11, 1)))
vDDDLists_examples = [
vDDDLists([]),
vDDDLists([datetime(2023, 11, 1, 10, 1)]),
vDDDLists([datetime(2023, 11, 1, 10, 1), date(2023, 11, 1)]),
]
@pytest.mark.parametrize("l1", vDDDLists_examples)
@pytest.mark.parametrize("l2", vDDDLists_examples)
d... | Python | 1 |
zones.len()
};
let zone_items = get_zones(&zones, &modulators, &generators, start, end);
// Ignore Terminator
if header.name != "EOP"
{
list.push(Preset {
header : header.clone(),
zones : zone_items,
})
}
}
... | Rust | 0 |
.signers.clone()
}
fn combine(&mut self, other: &MultiSignature) -> Result<(), ContributionError> {
// TODO: If we don't need the overlapping IDs for the error, we can use `intersection_size`
let overlap = &self.signers & &other.signers;
if overlap.is_empty() {
self.signatu... | Rust | 0 |
from datetime import datetime
import pytest
from account.models import AccountAPIKey, AccountAPIKeyAnalytics
from registry.tasks import save_api_key_analytics
path = "/test_path/"
@pytest.mark.django_db
class TestSaveApiKeyAnalytics:
def test_save_api_key_analytics_new_analytics(self, scorer_account):
... | Python | 1 |
{
match self.bits {
false => ALMIEN_A::_0,
true => ALMIEN_A::_1,
}
}
#[doc = "Checks if the value of the field is `_0`"]
#[inline(always)]
pub fn is_0(&self) -> bool {
**self == ALMIEN_A::_0
}
#[doc = "Checks if the value of the field is `_1`"]
... | Rust | 0 |
Back,
0x16B => LaunchApp1,
0x16C => LaunchMail,
0x16D => MediaSelect,
0x1F1 => Lang2,
0x1F2 => Lang1,
_ => Unidentified,
}
}
fn vk_to_key(vk: VkCode) -> Option<KbKey> {
Some(match vk as INT {
VK_CANCEL => KbKey::Cancel,
VK_BACK => KbKey::Backspace... | Rust | 0 |
-> NodeInfo {
let mut local_channels_arg = Vec::new(); for mut item in channels_arg.into_rust().drain(..) { local_channels_arg.push( { item }); };
let mut local_lowest_inbound_channel_fees_arg = if lowest_inbound_channel_fees_arg.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(lowest_inbound_channel_... | Rust | 0 |
self.logger_util_test10.record(np.mean(all_success_rates))
log_data['SR_test_L3'] = self.logger_util_test.average_of_largest_K()
log_data['SR_test_L5'] = self.logger_util_test10.average_of_largest_K()
videos = env.env.get_video()
if len(videos.shape) == 5:
videos = videos... | Python | 1 |
import os
import sys
from selenium.webdriver import Chrome
from selenium.webdriver.chrome import webdriver as chrome_webdriver
class ChromeHeadlessDownload(object):
def get_driver(self, download_location=None, headless=False):
"""
there is currently a "feature" in chrome where
headless do... | Python | 1 |
> {
use crate::Variant::*;
match self.bits {
0 => Val(INTG_OPT_A::INTG_OPT_0),
i => Res(i),
}
}
#[doc = "Checks if the value of the field is `INTG_OPT_0`"]
#[inline(always)]
pub fn is_intg_opt_0(&self) -> bool {
*self == INTG_OPT_A::INTG_OPT_0
... | Rust | 0 |
s saved to: {output_dir}")
print(f"Generated {len(results_to_process)} visualization files")
def analyze_results(results_file):
"""
Analyze detection results and print statistics
Args:
results_file: JSON file with detection results
"""
with open(results_file, 'r') as f:
res... | Python | 1 |
# Operador Ternary 2
"""
Escriba un programa que pregunte a dos usuarios su nombre y edad e imprime el nombre del mayor
"""
user_1 = input("Nombre del primer usuario: ")
age_1 = int(input("Edad del primer usuario: "))
user_2 = input("Nombre del segundo usuario: ")
age_2 = int(input("Edad del segundo usuario: "))
pr... | Python | 1 |
VER_POOL_RULE.value} {args["rule_id"]} {OutputTitle.UPDATED.value}'
assert output == str(result.readable_output)
@pytest.mark.parametrize(
("version", "endpoint", "args", "jsonpath"),
(
(
ClientV1.API_VER,
"ServerObjects/Server/ServerPool/check/EditServerPoolRule/1",
... | Python | 1 |
import json
from pathlib import Path
from docling_core.transforms.chunker.hierarchical_chunker import DocChunk
from docling_core.transforms.chunker.page_chunker import PageChunker
from docling_core.types.doc.document import DoclingDocument
from .test_data_gen_flag import GEN_TEST_DATA
def _process(act_data, exp_pat... | Python | 1 |
internally as opposed to
/// being located on the call stack.
pub trait Iterator<A> {
/// Advance the iterator and return the next value. Return `None` when the end is reached.
fn next(&mut self) -> Option<A>;
/// Return a lower bound and upper bound on the remaining length of the iterator.
///
//... | Rust | 0 |
tr;
// From WinNT.h
pub type CHAR = super::__gl_imports::raw::c_char;
pub type HANDLE = PVOID;
pub type LONG = super::__gl_imports::raw::c_long;
pub type LPCSTR = *const super::__gl_imports::raw::c_char;
pub type VOID = ();
// #define DECLARE_HANDLE(name) struct name##__{int unused;}; typedef struct name##__ *name
pu... | Rust | 0 |
INSTITUTION_NAME = "instituto federal catarinense"
CAMPUS_NAME = "araquari"
VALID_CNPJ = "75775752000123"
| Python | 1 |
"""
인증(Auth) API 엔드포인트에서 사용되는 Pydantic 스키마를 정의합니다.
"""
from pydantic import BaseModel
class LoginRequest(BaseModel):
"""
로그인 요청 시 사용되는 스키마입니다.
"""
email: str
password: str
class JoinRequest(BaseModel):
"""
회원가입 요청 시 사용되는 스키마입니다.
"""
email: str
password: str
name: str
... | Python | 1 |
ite!(out, "f")?,
Type::String => write!(out, "s")?,
Type::Object => write!(out, "o")?,
Type::Array => write!(out, "a")?,
Type::Fd => write!(out, "h")?,
Type::Int => write!(out, "i")?,
... | Rust | 0 |
()
def load_pretrained_model(self, weights_path: str, sv_name=None, **kwargs) -> None:
"""
Method to load a pretrained model weights inside self.model
"""
# self.model.load_state_dict(torch.load(os.path.join(weights_path, "model_state_dict.pth")))
self.model.load_state_dict(t... | Python | 1 |
text_exit = [
"Пусть свет знаний освещает твой путь, путник. До новых встреч!",
"Я всегда на страже. Если тебе снова понадобятся ответы, знай, что я здесь."
]
biology_replies = [
"Природа — это величайший учитель. Какой аспект жизни ты желаешь исследовать?",
"Загадки организма и экосистем ждут своего о... | Python | 1 |
#!/usr/bin/env python3
def line_to_ints(str):
return [int(s) for s in str.split()]
def ascending(lst):
return all(x < y for x, y in zip(lst, lst[1:]))
def descending(lst):
return all(x > y for x, y in zip(lst, lst[1:]))
def intervals_ok(lst):
return all((1 <= abs(x - y) <= 3) for x, y in zip(lst, ls... | Python | 1 |
lass.RANGER,
build_goal=PoE2BuildGoal.CLEAR_SPEED,
max_budget=20.0,
validate_with_pob2=True
),
# 高复杂度请求
UserRequest(
character_class=PoE2CharacterClass.SORCERESS,
build_goal=PoE2BuildGoal.ENDGAME_CONTENT,... | Python | 1 |
x, point)
|| self.contains_simple_message_menu(ctx, point)
}
pub fn get_book_status_menu_position(&self) -> Option<numeric::Point2f> {
if let Some(book_status_menu) = self.book_status_menu.as_ref() {
Some(book_status_menu.get_click_position())
} else {
None
... | Rust | 0 |
open(ts_result, "rb") as f:
video_bytes = f.read()
st.download_button(
label="⬇️ Manual Download",
data=video_bytes,
file_name=ts_name,
mime="video/mp4"
)
... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.