text string | label_name string | labels int64 |
|---|---|---|
# Copyright (c) 2025, Frappe and Contributors
# See license.txt
# import frappe
from frappe.tests import IntegrationTestCase
# On IntegrationTestCase, the doctype test records and all
# link-field test record dependencies are recursively loaded
# Use these module variables to add/remove to/from that list
EXTRA_TEST_... | Python | 1 |
Fp { d: [0x5cb38790fd530c16, 0x7817fc679976fff5, 0x154f95c7143ba1c1, 0xf0ae6acdf3d0e747, 0xedce6ecc21dbf440, 0x120177419e0bfb75] },
y: Fp { d: [0xff526c2af318883a, 0x92899ce4383b0270, 0x89d7738d9fa9d055, 0x12caf35ba344c12a, 0x3cff1b76964b5317, 0x0e44d2ede9774430] },
z: Fp { d: [0x760900000002fffd, 0xebf4000bc4... | Rust | 0 |
// Aggregate the pivot results by taking the minimal value of all duplicates.
pub fn min(&self) -> Result<DataFrame> {
let pivot_series = self.gb.df.column(self.pivot_column)?;
let values_series = self.gb.df.column(self.values_column)?;
values_series.pivot(pivot_series, self.gb.keys(), &self... | Rust | 0 |
equency")
elif occupdeux == 0 and freqdeux == 1:
os.system('mv c2.txt cinqgcarte')
print(f"{MAGENTA}Second card will be use on 5GHz frequency")
elif occuptrois == 0 and freqtrois == 1:
os.system('mv c3.txt cinqgcarte')
print(f"{MAGENTA}Third card will be use on 5GHz frequency")
else:
print(f"{YELLOW... | Python | 1 |
a>(&self, from: &'a str, to: &'a str, currency: &'a str, amount: f64) -> QueryBuilder<NoOptions<'a>> {
let mut no_options = NoOptions::new();
no_options.params_mut().from = Some(from);
no_options.params_mut().to = Some(to);
no_options.params_mut().currency = Some(currency);
... | Rust | 0 |
import os, sys
# Add 'pingmapper' to the path, may not need after pypi package...
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
PACKAGE_DIR = os.path.dirname(SCRIPT_DIR)
sys.path.append(PACKAGE_DIR)
# Default function to run
if len(sys.argv) == 1:
to_do = 'gui'
else:
to_do = sys.argv[1]
# May need... | Python | 1 |
"""Test the Mag 1 template.
==========
This is a unit test for the Mag 1 template.
"""
import os
# enforce open mp to run on single thread
os.environ["OMP_NUM_THREADS"] = "1"
# enforce blas to run on single thread
os.environ["OPENBLAS_NUM_THREADS"] = "1"
import numpy as np
import pandas as pd
import matplotli... | Python | 1 |
result = ("Blackjack!", 'won')
break
elif player_score > 21: # losing condition
self.economy.add_money(ctx.author.id, bet*-1)
result = ("Player busts", 'lost')
break
msg = await out_table(
title="Your Tur... | Python | 1 |
new(message_sender);
// TODO: allow the bind address to be specified...
// constructs a future for getting the next randomly bound port to a UdpSocket
let next_socket = Self::next_bound_local_address(&name_server);
// This set of futures collapses the next udp socket into a stream whic... | Rust | 0 |
import unittest
import enum
from test.asserting.policy import PolicyAssertion, get_fixture_path
from vint.linting.level import Level
from vint.linting.policy.prohibit_unused_variable import ProhibitUnusedVariable
class Fixtures(enum.Enum):
VALID_VIM_SCRIPT = get_fixture_path('prohibit_unused_variable_valid.vim')
... | Python | 1 |
import turtle
t= turtle.Turtle()
t.speed(10)
colors= ['yellow','orange','red','pink','violet','indigo','blue','green']
turtle.bgcolor('black')
for i in range(36):
t.color(colors[i%8])
t.circle(100)
t.right(10)
turtle.done()
| Python | 1 |
t,
AuthExchangedata,
AuthSetacl,
NotifySetacl,
NotifyPtyGrant,
NotifyPtyClose,
AuthProcCheck,
NotifyProcCheck,
AuthGetTask,
AuthSearchfs,
NotifySearchfs,
AuthFcntl,
AuthIokitOpen,
AuthProcSuspendResume,
NotifyProcSuspendResume,
NotifyCsInvalidated,
NotifyG... | Rust | 0 |
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Project MRP Landed Costs',
'version': '1.0',
'summary': 'Technical Bridge',
'category': 'Manufacturing/Manufacturing',
'depends': ['project_mrp_account', 'mrp_landed_costs'],
'auto_install': True,
'license... | Python | 1 |
[test]
fn correct_operation_called_msr_cpsr() {
let mut gba: GBA = GBA::default();
let decode_result = gba.cpu.decode(0xE329F011);
match decode_result {
Ok(mut instr) => {
(instr.borrow_mut() as &mut dyn Instruction).execute(&mut gba.cpu, ... | Rust | 0 |
2, 3,
3, 3, 3, 3, 3, 3, 3, 3,
];
let mut output_test: [u8; 16] = [0; 16];
// First bit plane
output_test[0] = 0b1111_1111;
output_test[1] = 0b1100_0011;
output_test[6] = 0b1100_0011;
output_test[7] = 0b1111_1111;
// Second bit plane
output_test[8] = 0b1111_1111;
outpu... | Rust | 0 |
.sampler)
def __getitem__(self, idx: int) -> Dict[str, torch.Tensor]:
data = self.sampler.sample_sequence(idx)
torch_data = dict_apply(data, torch.from_numpy)
return torch_data
def normalizer_from_stat(stat):
max_abs = np.maximum(stat['max'].max(), np.abs(stat['min']).max())
scale ... | Python | 1 |
import torch
import tools.utils as d2l
img = d2l.plt.imread("./1.jpg")
d2l.plt.imshow(img)
d2l.plt.show()
bottle_bbox, blackboard_bbox = [203.0, 197.0, 229.0, 240.0], [100.0, 130.0,362.0, 185.0]
boxes = torch.tensor((bottle_bbox, blackboard_bbox))
print(d2l.box_center_to_corner(d2l.box_corner_to_center(boxes)) == bo... | Python | 1 |
:spawn(move || unsafe {
urcu_sys::rcu_register_thread();
let r = drive(map, end, dist, false, span);
urcu_sys::rcu_unregister_thread();
r
})
}));
join.extend((0..writers).into_iter().map(|_| {
let map = map.clone();
... | Rust | 0 |
.take(num_inputs % 16)
.collect();
TxBuilder::new()
.set_payload(&payload)
.set_ios(&inputs, &outputs)
.set_witnesses(&witnesses)
.set_payload_auth(&payload_auth)
}
}
impl Arbitrary for SingleAcc... | Rust | 0 |
m32_r32
0x00,// Invalid
0x00,// Invalid
0x0E,// VectorLength
0x16,// Gv_Gv_Ev
0xE3, 0x1C,// VEX_Pext_r32_r32_rm32
0x00,// Invalid
0x0E,// VectorLength
0x16,// Gv_Gv_Ev
0xE5, 0x1C,// VEX_Pdep_r32_r32_rm32
0x00,// Invalid
// 246 = 0xF6
0x0B,// MandatoryPrefix2_4
0x00,// Invalid
0x00,//... | Rust | 0 |
from dash.dependencies import Input, Output, State
from uuid import uuid4
from server import app
from dash import Patch
import importlib
import dash
from typing import Dict, List
from dash.exceptions import PreventUpdate
from dash import set_props
from yarl import URL
from common.utilities.util_menu_access import get_m... | Python | 1 |
_node_2
@_wire_rule.register(Rule)
@_wire_rule.register(AND)
def _(elem):
if len(elem) == 1:
if isinstance(elem[0], Fact):
return alpha_terminals[elem[0]]
else:
return _wire_rule(elem[0])
else: # > 1. Because < 1 is not possible at th... | Python | 1 |
e, tags: _measurement=cpu,cpu=cpu1,host=foo,_field=usage_system, type: 0",
"FloatPointsFrame, timestamps: [2000], values: \"21\"",
"SeriesFrame, tags: _measurement=cpu,cpu=cpu1,host=foo,_field=usage_user, type: 0",
"FloatPointsFrame, timestamps: [2000], values: \"143\"",
"GroupFrame, tag... | Rust | 0 |
(js_sys::Math::random() * (max - min) + min) as f64
}
#[wasm_bindgen]
pub struct Snowflake {
max_width: f64,
max_height: f64,
x: f64,
y: f64,
velocity_x: f64,
velocity_y: f64,
radius: f64,
opacity: f64,
}
#[wasm_bindgen]
impl Snowflake {
pub fn tick(&mut self) {
self.x = se... | Rust | 0 |
p_eq(&reference, &h)
}
}
#[cfg(test)]
#[cfg(feature = "with-bench")]
mod bench {
use super::*;
use std::collections::hash_map::DefaultHasher;
use std::collections::BTreeMap;
type Key = String;
const NB: usize = 1000;
fn keys() -> Vec<Key> {
let mut v = Vec::with_capacity(NB);
... | Rust | 0 |
_get_qr_vals(
qr_method=self.emv_qr_invoice.qr_code_method,
amount=self.emv_qr_invoice.amount_residual,
currency=self.emv_qr_invoice.currency_id,
debtor_partner=self.emv_qr_invoice.partner_id,
free_communication=unstruct_ref,
structured_communicati... | Python | 1 |
ModWithTwoSubmodsAndTensor(
torch.ones(3),
sub_module,
sub_module,
)
tracer = TestAllLeafModulesTracer()
graph = tracer.trace(module)
self.assertEqual(graph._tracer_cls, TestAllLeafModulesTracer)
gm = SpecialGraphModule(module, graph, "secre... | Python | 1 |
load(deps.storage, lockup_id.as_bytes())?
.unwrap_or_default();
// CHECK :: Lockdrop withdrawal window open
if !is_withdraw_open(env.block.time.seconds(), &config) {
return Err(StdError::generic_err("Withdrawals not allowed"));
}
// CHECK :: Valid Lockup
if lockup_info.ust_locked.i... | Rust | 0 |
"--use-custom-scalars");
temp_dir
.child("file.graphql")
.write_str(
"
query TestQuery {
viewer {
user {
id
created_at
}
}
}
",
)
.unwrap();
cmd.assert().success();
assert_generated(
&temp_dir,
"TestQuery.ts",
... | Rust | 0 |
from dao.dao_saldo import SaldoDAO
from dao.dao_usuario import UsuarioDAO
import pwinput
usuarios = UsuarioDAO()
saldos = SaldoDAO()
# Inicio de sesión
usuario = input("Usuario: ")
contraseña = pwinput.pwinput(prompt="Contraseña: ", mask='*')
if usuarios.verificar_usuario(usuario, contraseña):
print("¡Inicio de ... | Python | 1 |
And,
Or,
Xor,
Increase,
Decrease,
Equals,
NotEquals,
LessThan,
LessOrEqualThan,
GreaterThan,
GreaterOrEqualThan,
LParenthesis,
RParenthesis,
LBracket,
RBracket,
LCurlyBrace,
RCurlyBrace,
... | Rust | 0 |
# Configuration file for the Sphinx documentation builder.
#
# For the full list of built-in configuration values, see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Project information -----------------------------------------------------
# https://www.sphinx-doc.org/en/master... | Python | 1 |
def add2me(x):
return x + x
print(add2me(32.4)) | Python | 1 |
re time.
Returns:
A Anime object if adapting was successfull
"""
mal_titles = {mal_anime.title}
if use_alternative_names and mal_anime.alternative_titles is not None:
mal_titles |= {
t
for t in [
mal_anime.alte... | Python | 1 |
f.0.read_bank_value(ops, address)
}
fn set_bank_value(
&mut self,
ops: &mut BankOps<impl PersistentStorage>,
address: u16,
value: u8,
) {
if address as usize >= self.0.total_len() {
return;
}
self.0.set_bank_value(ops, address, value);
... | Rust | 0 |
= 199.99;
let elem1 = c1[0][0];
let elem2 = c2[0][0];
println!("e1[0][0] = {}", elem1);
println!("e2[0][0] = {}", elem2);
}
}
<reponame>lideen999/flow<filename>crates/doc/src/reduce/strategy.rs
use super::{count_nodes, reduce_item, reduce_prop, Cursor, Error, Reducer, Result}... | Rust | 0 |
# app/routes/retrieval.py
from flask import Blueprint, request, jsonify
from app import chromadb_service
#add_books_to_chromadb, retrieve_relevant_book, get_all_books
# Créer un blueprint pour la récupération d'information
bp_retrieval = Blueprint('retrieval', __name__)
# Route pour récupérer le livre pertinent
@bp... | Python | 1 |
3, 2, 1];
let ocx = OpContext {
client_id: client_id.clone(),
call_id: 0,
method_name: "getListing".to_owned()
};
let gl = pb_cons!(GetListingRequestProto,
src: "/".to_owned(),
start_after: vec![],
need_location: false
);
let r = c.encode(RpcRe... | Rust | 0 |
k timestamps; Deepgram word/segment timings are available via words if needed
"received_at": datetime.now().isoformat(),
"source": "deepgram_realtime_api",
"type": "transcription_complete",
}
with self._blocks_lock:
self._blocks.append(block)
s... | Python | 1 |
P>),
PointLightDraw(PointLightDrawInstruction<'a, P>),
RectLightBegin,
RectLightDraw(RectLightDrawInstruction<'a>),
SpotlightBegin,
SpotlightDraw(SpotlightDrawInstruction<'a>),
SunlightDraw(SunlightIter<'a, P>),
VertexAttrsBegin(CalcVertexAttrsComputeMode),
VertexAttrsCalc(DataComputeIns... | Rust | 0 |
A = np.ones((5, 5))
A[1:2, 1:2] = np.nan
ax1.imshow(A, interpolation='nearest')
A = np.zeros((5, 5), dtype=np.bool)
A[1:2, 1:2] = True
A = np.ma.masked_array(np.ones((5, 5), dtype=np.uint16), A)
ax2.imshow(A, interpolation='nearest')
@image_comparison(baseline_images=['imshow_endianess'... | Python | 1 |
from django.urls import path
from . import views
urlpatterns = [
path('', views.interface, name='ihm'),
path('ligar/', views.ligar, name='ligar'),
path('desligar/', views.desligar, name='desligar'),
path('nivel/', views.estado_nivel, name='nivel'),
]
| Python | 1 |
Hash<S> for Url {
fn hash(&self, state: &mut S) {
self.serialize().hash(state)
}
}
/// A set of optional parameters for URL parsing.
pub struct UrlParser<'a> {
base_url: Option<&'a Url>,
query_encoding_override: Option<EncodingRef>,
error_handler: ErrorHandler,
scheme_type_mapper: fn(s... | Rust | 0 |
окупки:",
reply_markup=keyboard
)
except Exception as e:
logger.error(f"Error in set auto-buy slippage handler: {e}")
await callback.answer("❌ Произошла ошибка")
@router.callback_query(lambda c: c.data.startswith("auto_buy_slippage_"), flags={"priority": 3})
async def handle_au... | Python | 1 |
from rest_framework.response import Response
from rest_framework.views import APIView
from ....models import AdminRequest, User, StatusChoices
from ....tools.main_logger import logger
class CheckPendingRejectedAcceptedRequest(APIView):
"""
Проверяет, есть ли у пользователя активная или отклонённая заявка на ... | Python | 1 |
aces"][decoding_sample - 1]
).split("Label:")[0]
)
# Construct verifier input (Claim + Verdict + Justification)
input_text = (
"Claim:" + sample["claim"] +
"\nVerdict:" + sample["Verdict_list"][decoding_sample -... | Python | 1 |
elf) -> 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 as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
FTM0SYNCBITR::_0 =>... | Rust | 0 |
08u16), CloseCode::Policy);
assert_eq!(CloseCode::from(1009u16), CloseCode::Size);
assert_eq!(CloseCode::from(1010u16), CloseCode::Extension);
assert_eq!(CloseCode::from(1011u16), CloseCode::Error);
assert_eq!(CloseCode::from(1012u16), CloseCode::Restart);
assert_eq!(CloseCode::f... | Rust | 0 |
# MNIST CNN classifier
# Code by GunhoChoi
import torch
import torch.nn as nn
import torch.utils as utils
from torch.autograd import Variable
import torchvision.datasets as dset
import torchvision.transforms as transforms
import matplotlib.pyplot as plt
#%matplotlib inline
# Set Hyperparameters
epoch = 1
batch_size... | Python | 1 |
t
.get(url.as_str())
.header(ACCEPT, "application/json")
.headers(Self::cookie_headers(cookie_get, &url))
.send()
.map_err(Error::from)
})
.map(move |res| Self::store_cookies(res, cookie_set))
... | Rust | 0 |
mod fixed_joint;
mod free_joint;
mod joint;
mod prismatic_joint;
mod revolute_joint;
mod unit_joint;
#[cfg(feature = "dim3")]
mod ball_joint;
#[cfg(feature = "dim3")]
mod cylindrical_joint;
#[cfg(feature = "dim3")]
mod helical_joint;
#[cfg(feature = "dim3")]
mod pin_slot_joint;
#[cfg(feature = "dim3")]
mod planar_joi... | Rust | 0 |
None):
request = '/' + self.version + '/' + self.implode_params(path, params)
url = self.urls['api'][api] + request
query = self.omit(params, self.extract_params(path))
if api == 'public':
if query:
url += '?' + self.urlencode(query)
elif api == 'priva... | Python | 1 |
rd item</em></li>
</ul>
</li>
<li>First item</li>
</ul>
<h2 id="Appendix_-_RDF">Appendix - RDF</h2>
<pre>
<code class="turtle">@prefix foo: <...>
foo:bar foo:baz 12.
</code>
</pre>
<pre>@prefix foo: <...>
foo:bar foo:baz 12.
</pre>
</body>
</html>"###,
t... | Rust | 0 |
"""Compute scenario difficulty level"""
wind_difficulty = torch.norm(wind_conditions).item() / 15.0
payload_difficulty = payload_mass.item() / 2.0
return 0.6 * wind_difficulty + 0.4 * payload_difficulty
class CurriculumManager:
"""
Manages curriculum learning for wi... | Python | 1 |
loss_locals.append(copy.deepcopy(loss))
print('Training of '+str(allDeviceName[idx])+' in iteration '+str(iter)+' has done!')
else:
malN_glob = torch.load('./data/genesisForCNN.pkl', map_location=torch.device('cuda:{}'.format(args.gpu) if torch.cuda.is_available() and ar... | Python | 1 |
BR_PITTSBURG_BAY_POINT => Ok(Station::PittsburgBayPoint),
STATION_ABBR_PITTSBURG_CENTER => Ok(Station::PittsburgCenter),
STATION_ABBR_PLEASANT_HILL => Ok(Station::PleasantHill),
STATION_ABBR_POWELL_ST => Ok(Station::PowellSt),
STATION_ABBR_RICHMOND => Ok(Station::Richmond... | Rust | 0 |
"""
Prints the scan code of all currently pressed keys.
Updates on every keyboard event.
"""
import sys
sys.path.append("..")
import keyboard
recorded = list()
ongoing = dict()
class Keypress:
def __init__(self, code, name, start):
self.scan_code = code
self.name = name
self.start = sta... | Python | 1 |
rection", "Enter the correct Y coordinate:", minvalue=0, maxvalue=127)
# Update the training data with the corrected label
global X_train, y_train
if X_train.size == 0:
X_train = img_input
y_train = np.array([[correct_x, correct_y]... | Python | 1 |
from unittest.mock import MagicMock
import pytest
from construct import Construct
from eq3btsmart._adapters import _Eq3Temperature
from eq3btsmart.const import EQ3_OFF_TEMP, EQ3_ON_TEMP
from eq3btsmart.exceptions import Eq3InvalidDataException
def test_encode_valid_temperature() -> None:
temperature = 22.0
... | Python | 1 |
xjYmBgAAAADAAD".to_owned())
.extract_tiles(Some(Compression::Zlib))
.unwrap(),
vec![2]
);
assert_eq!(
DataSource::Encoded("KLUv/SAEIQAAAgAAAA==".to_owned())
.extract_tiles(Some(Compression::Zstd))
.unwrap(),
... | Rust | 0 |
let list = MovableList::new("Logs", &self.state.log_state);
list.render(area, buf);
}
}
extern crate avr_avogadro;
use avr_avogadro::core::mcu_factory::McuFactory;
#[test]
/// Tests simple compare instruction
///
/// CP opcode: 0001 01rd dddd rrrr
/// cp r1, r2 -> 0001 0100 0001 0002 -> 1412
///
/// Reme... | Rust | 0 |
import os
import re
import csv
input_dir = "./output"
results_dir = "./results"
os.makedirs(results_dir, exist_ok=True)
csv_file = os.path.join(results_dir, "results.csv")
records = []
# Regex patterns for methods
method_patterns = {
"naive CPU": re.compile(r"Using naive CPU SpMV"),
"optimized CPU": re.compi... | Python | 1 |
from .price import ImagePrice
__all__ = ["ImagePrice"] | Python | 1 |
transform: Transform,
/// The global transform location in a space for a component.
pub(crate) global_transform: GlobalTransform,
/// If a layer has been modified, all are set here.
pub(crate) modified_layer: ModifiedLayer,
}
impl Default for ChunkBundle {
fn default() -> ChunkBundle {
let ... | Rust | 0 |
put(new);
Ok(())
},
}
}
}
}
impl<T: Trait> pallet_session::ShouldEndSession<T::BlockNumber> for Module<T> {
fn should_end_session(now: T::BlockNumber) -> bool {
true
}
}
impl<T: Trait> pallet_session::SessionManager<T::AccountId> for Module<T> {
fn new_session(new_index: u32) -> Optio... | Rust | 0 |
enumerate() {
if kinetic_index == kinetic_b_index {
continue;
}
Self::kinetic_kinetic(kinetic, &mut *kinetic_b_cell.borrow_mut());
}
}
Self::kinetic_world(kinetic, self.world_bounds);
// No floor wiggly
let wiggle = 2.5;
if kinetic.velocity.x.abs() < wiggle {
kinetic.veloc... | Rust | 0 |
attr in &self.user_attributes {
attr.to_writer(writer)?;
}
Ok(())
}
}
#[derive(Debug, PartialEq, Eq, Clone)]
#[allow(clippy::large_enum_variant)] // FIXME
pub enum PublicOrSecret {
Public(SignedPublicKey),
Secret(SignedSecretKey),
}
impl PublicOrSecret {
pub fn verify(&se... | Rust | 0 |
ndboxManager to handle Docker containers
from mcp_sandbox.core.sandbox_modules.manager import SandboxManager
from mcp_sandbox.utils.config import logger
sandbox_manager = SandboxManager()
# Get the Docker container ID from the record
docker_container_id = sandbox_record.get("docker_container_id... | Python | 1 |
ue)>>, NbeError> {
match (&*pattern.inner, &*value.inner) {
(&Pattern::Binder(Binder(ref free_var)), _) => {
Ok(Some(vec![(free_var.clone(), value.clone())]))
},
(&Pattern::Var(Embed(Var::Free(ref free_var)), _), _) => {
match env.get_definition(free_var).map(|term| n... | Rust | 0 |
# Mixin AdminAccessMixin с метод force_access(obj),
# който използва name mangling, за да върне __value без парола
class AdminAccessMixin:
def force_access(self, obj):
return obj._SecureData__value | Python | 1 |
, so we only emit a future compat warning if
// const evaluation succeeds and the given constant is still polymorphic for now
// and hopefully soon change this to an error.
//
// See #74595 for more details about this.
let concrete = infcx.const_eval_resolve(param_env, def, substs, None, Some(span))... | Rust | 0 |
# pylint: disable = C0111
from setuptools import find_packages, setup
with open("README.md", "r", encoding="utf-8") as f:
# Remove GitHub dark mode images
DESCRIPTION = "".join([line for line in f if "gh-dark-mode-only" not in line])
# Optional dependencies
extras = {}
# Development dependencies
extras["dev"... | Python | 1 |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, models, fields, _
class ProductTemplate(models.Model):
_inherit = 'product.template'
expense_policy_tooltip = fields.Char(compute='_compute_expense_policy_tooltip')
@api.depends_cont... | Python | 1 |
_labels
return hit, count
def validate(val_loader, model, criterion):
model.eval()
losses = 0.0
total_hit = 0
total_cnt = 0
with torch.no_grad():
for i, (input, target) in enumerate(val_loader):
input = input.cuda()
target = target.cuda()
output = mod... | Python | 1 |
'apache2_repos': TEST_PAYLOAD[0][3],
},
])
class TestIntegrationGithubOrgClient(unittest.TestCase):
"""
Performs integration tests for the `GithubOrgClient` class.
"""
@classmethod
def setUpClass(cls) -> None:
"""
Sets up class fixtures before running tests.
"""
... | Python | 1 |
unsafe { &(*(::std::ptr::null::<kvm_ppc_one_seg_page_size>())).enc as *const _ as usize },
8usize,
concat!(
"Offset of field: ",
stringify!(kvm_ppc_one_seg_page_size),
"::",
stringify!(enc)
)
);
}
#[repr(C)]
#[derive(Debug, Default, Copy, ... | Rust | 0 |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""Units and Quantity related helper functions."""
import logging
from math import floor
import numpy as np
import astropy.units as u
__all__ = ["standardise_unit", "unit_from_fits_image_hdu", "wrap_at"]
log = logging.getLogger(__name__)
def wrap_at(v... | Python | 1 |
total += 0xA5;
((total & 0x7F) as u8).try_into().unwrap()
}
}
#[derive(Debug, Eq, PartialEq, Copy, Clone)]
pub struct SubmixSettings {
// K4: -7~+7, stored in SysEx as 0~15
// K4r: -7~+7, stored as 0~15 , or 16~21 / 1~6
pub pan: i32,
// Effect send 1 and 2 are used on K4 only
pub sen... | Rust | 0 |
message = LitStr::new(
&format!(
"Missing expected identifier in sequence: `{}`",
name
),
paren_token.span,
);
Pat::Verbatim(
quote_spanned!(paren_token.span=> ::core::compile_error!(#message)),
)
}
... | Rust | 0 |
be_f32(&[0x4d, 0x31, 0x1f, 0xd8]), Ok((&b""[..], 185_728_392_f32)));
}
#[test]
fn be_f64_tests() {
assert_parse!(be_f64(&[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]), Ok((&b""[..], 0_f64)));
assert_parse!(
be_f64(&[0x41, 0xa6, 0x23, 0xfb, 0x10, 0x00, 0x00, 0x00]),
Ok((&b""[..], 185_728_3... | Rust | 0 |
}
url = "/api/ticket/receipts/batch_approval/"
rsp = self.client.post(
path=url, data=json.dumps(data), content_type="application/json"
)
self.assertEqual(rsp.status_code, 200)
self.assertEqual(
cache.get("approval_status_{}_{}_{}".format("admin", ticket.i... | Python | 1 |
parser = argparse.ArgumentParser()
parser.add_argument("--host", type=str, default="")
parser.add_argument("--center-name", type=str, default="")
parser.add_argument("--center-password", type=str, default="")
parser.add_argument(
"-b",
"--backup",
help="Backup Mode",
... | Python | 1 |
import faker
from faker import Faker
def generate_fake_data(num_rows=10):
faker = Faker()
data = []
for _ in range(num_rows):
data.append({
'name': faker.name(),
'email': faker.email(),
'phone': faker.phone_number(),
'address': faker.address(),
... | Python | 1 |
uavs # 액션 초기화
for i in uav_order:
if global_action_mask is not None:
# UAV i에 대한 선택 가능한 액션 얻기
available_actions = (global_action_mask[i] == 0).nonzero(as_tuple=True)[0].tolist()
if not available_actions:
continue # 선택 가능한 액션이 없으면 스킵
logits_... | Python | 1 |
T_UARTDR_BE_RESET: &'static [u8; 2usize] = b"-\0";
pub const UART_UARTDR_BE_BITS: u32 = 1024;
pub const UART_UARTDR_BE_MSB: u32 = 10;
pub const UART_UARTDR_BE_LSB: u32 = 10;
pub const UART_UARTDR_BE_ACCESS: &'static [u8; 3usize] = b"RO\0";
pub const UART_UARTDR_PE_RESET: &'static [u8; 2usize] = b"-\0";
pub const UART_U... | Rust | 0 |
< 0 {
error!("ioctl: fail to set broadast address");
exit(1);
}
}
if !mac.is_nil() {
let mut local_mac = [0u8; 6];
local_mac.copy_from_slice(mac.as_bytes());
if tap.set_mac_address(&local_mac) < 0 {
error!("ioctl: fail to set mac address");
... | Rust | 0 |
'''
Задача 65
Приближения e
Квадратный корень из 2 можно записать в виде бесконечной непрерывной дроби.
√2 = 1 +
1
2 +
1
2 +
1
2 +
1
2 + ...
Бесконечную непрерывную дробь можно записать, воспользовавшись обозначением √2 = [1;(2)], где (2) указывает на то, что 2 повторяетс... | Python | 1 |
if current == &self.root && current_part == 2 {
// Finish the complete tree
return fmt.write_str("]");
}
match current_part {
0 => { // Start of new element
try!(write!(fmt, "[({}, {}), left: ", &inner.key, &inner.value));
// Go down left and print left c... | Rust | 0 |
i2, ni2, i2_lookup, i4, ni4, i4_lookup,
iPfsh, nPfsh, iPfsh_lookup,
iQtma, nQtma, iQtma_lookup,
iQfma, nQfma,
iVtm... | Python | 1 |
起会心一击,造成了{}伤害\n"
else:
msg1 = "{}发起攻击,造成了{}伤害\n"
player1_atk_msg = msg1.format(player1['道号'], player1_sh)
play_list.append(get_msg_dict(player1, player_init_hp, player1_atk_msg))
boss['气血'] = boss... | Python | 1 |
odelOutputSuccess,
D: ModelOutputFailure,
{
}
/// Implementation of an online algorithm.
///
/// * `P` - problem
/// * `M` - memory
/// * `O` - options
///
/// Receives the arguments:
/// * `o` - online problem instance
/// * `t` - current time slot
/// * `xs` - schedule up to the previous time slot
/// * `prev_m`... | Rust | 0 |
_device_create_store_from_optionsregister_rendezvous_handler
rendezvousc \ rS rSrSrg)_ProcessGroupStub r Nr@ rA rB rC rE r r r
r~ r~ r r~ torch.distributedr r Ologgingr5 r2 rS typingr getLoggerr@ rV boolr r
r... | Python | 1 |
##################################################
#etot = np.sum(ex*ex/(8.0*np.pi) ,0) #+ np.sum(ekin,0)
#etot = np.sum(ekin,0)/np.sum(rho, 0)
#etot = np.sum(ekin,0)*dx
#etot = etot/etot[0]
print("ekin max:", np.max(ekintot))
print("efield max:", np.max(wedens))
print("ratio:", np.mean(ekintot)/np.mean(wedens))
#... | Python | 1 |
_all_categories().await;
dbg! {&cats};
cats.unwrap();
}
use std::collections::HashMap;
pub mod parser;
pub use parser::*;
#[derive(Debug, PartialEq)]
pub enum Value {
Null,
Bool(bool),
Float(f64),
Int(isize),
Str(String),
Array(Vec<Value>),
Object(HashMap<String, Value>),
}
#[cfg(t... | Rust | 0 |
from django.db import models
from django.contrib.auth import get_user_model
from apps.users.models import User
User = get_user_model()
class Transaction(models.Model):
sender = models.ForeignKey(User, related_name='sent_transactions', on_delete=models.CASCADE)
receiver = models.ForeignKey(User, related_name='... | Python | 1 |
}
}
#[repr(C, packed(4))]
#[doc = "*Required features: 'Win32_Storage_FileSystem'*"]
pub struct TXF_ID_0 {
pub LowPart: i64,
pub HighPart: i64,
}
impl ::core::marker::Copy for TXF_ID_0 {}
impl ::core::clone::Clone for TXF_ID_0 {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required f... | Rust | 0 |
99, 0, 0,
// ];
// let amplifiers = Amplifiers::new(&mem, &[0, 1, 2, 3, 4], Configuration::Simple);
// let res = amplifiers.run();
// assert_eq!(res, 54_321);
// }
// #[test]
// fn amplifiers_case_3_simple() {
// let mem = vec![
// 3, 31, 3, 32, 1002, 32,... | Rust | 0 |
# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
from typing_extensions import Literal
from ..._models import BaseModel
__all__ = ["ChatCompletionMessageCustomToolCall", "Custom"]
class Custom(BaseModel):
input: str
"""The input for the custom tool call generated by the... | Python | 1 |
#[cfg_attr(feature = "v2_22", deprecated = "Since 2.22")]
#[cfg(any(feature = "v2_16", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_16")))]
#[doc(alias = "webkit_dom_html_input_element_get_auto_filled")]
#[doc(alias = "get_auto_filled")]
fn is_auto_filled(&self) -> bool... | Rust | 0 |
import cv2
import random
# Define the path to your image file
path = 'E:/Downloads/Test/CamScanner 14.10.2024 09.48_1.jpg' # Update this to the correct path on your local system
scale = 0.5
circles = []
counter = 0
counter2 = 0
point1 = []
point2 = []
myPoints = []
myColor = []
# Mouse callback function
def mousePo... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.