text string | label_name string | labels int64 |
|---|---|---|
enum(1), fefacenum(2), tmsh)
@test isapprox(Mesh.integral_global_x_face_rel_on_fe_face(xcubed_on_fe1_side2, y, fenum(1), fefacenum(2), tmsh),
0, atol=1e-15, rtol=1e-15)
xy_on_fe1_side2 = local_mon_on_fe_side_as_global_fn(deg(1), deg(1), fenum(1), fefacenum(2), tmsh)
@test isapprox(Mesh.integral_global_x_... | Rust | 0 |
Ok(parser.pop().into())
}
pub fn open_file(
raw_archive_handle: u64,
path: &FsPath,
flags: OpenFlags,
attributes: u32,
) -> CtrResult<Handle> {
let mut command = ThreadCommandBuilder::new(0x802u16);
command.push(0u32);
command.push_u64(raw_archive_... | Rust | 0 |
documentation.
///
/// Creates, updates, or removes a connection between a team and an IdP group. When adding groups to a team, you must include all new and existing groups to avoid replacing existing groups with the new ones. Specifying an empty `groups` array will remove all connections for a team.
/// ... | Rust | 0 |
remove_js_from_data_url() -> Result<(), Box<dyn std::error::Error>> {
let mut cmd = Command::cargo_bin(env!("CARGO_PKG_NAME"))?;
let out = cmd
.arg("-M")
.arg("-j")
.arg("data:text/html,<script>alert(2)</script>Hi")
.output()
.unwrap();
... | Rust | 0 |
rogress)
bs = x_size[0]
for i, step in enumerate(iterator):
model_t = torch.full((bs,), step, device=device, dtype=torch.long)
t = torch.full((bs,), total_steps - i - 1, device=device, dtype=torch.long)
cur_cfg_scale = self.get_cfg_scale(cfg_scale, step)
... | Python | 1 |
str,
initial_offset: Offset,
mut tx: Sender<Result<Message, Status>>,
rx: ConfirmStream,
) where
ConfirmStream: Stream<Item = Result<Confirmation, Status>> + Send + 'static + Unpin,
{
let context = CustomContext;
let mut config = ClientConfig::new();
config
.set("group.id", consume... | Rust | 0 |
come chiavi di dizionario.
2. cerca_per_nome → restituisce tutti i contatti che corrispondono al nome, case-insensitive.
3. __contains__ → permette di fare if contatto in rubrica.
4. __eq__ → ora confronta le rubriche ignorando l’ordine dei contatti.
5. rimuove_contatto → solleva eccezione se il contatto non esiste, p... | Python | 1 |
from __future__ import annotations
from typing import Any, ClassVar, Dict
from great_expectations.execution_engine import (
SqlAlchemyExecutionEngine,
)
from great_expectations.expectations.metrics.metric_provider import metric_value
from great_expectations.expectations.metrics.query_metric_provider import (
... | Python | 1 |
d"), file_name);
}
Ok(())
}
// List out cargo.toml file present directories by recursively analyze all
// folder present in directory
pub(crate) fn list_cargo_toml(&self, path: &Path) -> Result<CargoTomlLocation> {
let mut cargo_trim_list = CargoTomlLocation::new();
if p... | Rust | 0 |
bl_info = {
"name": "网格处理工具",
"author": "Your Name",
"version": (1, 1),
"blender": (2, 80, 0),
"location": "View3D > Sidebar > Tool Tab",
"description": "三角化和细分网格",
"category": "Mesh",
}
import bpy
import bmesh
class MESH_OT_triangulate(bpy.types.Operator):
bl_idname = "mesh.custom_tri... | Python | 1 |
-> &Self::Target {
&self.0
}
}
#[doc = "Field `DMA_APBPERI_UCHI0_PMS_CONSTRAIN_SRAM_WORLD_0_PMS_1` writer - dma_apbperi_uchi0_pms_constrain_sram_world_0_pms_1"]
pub struct DMA_APBPERI_UCHI0_PMS_CONSTRAIN_SRAM_WORLD_0_PMS_1_W<'a> {
w: &'a mut W,
}
impl<'a> DMA_APBPERI_UCHI0_PMS_CONSTRAIN_SRAM_WORLD_0_PM... | Rust | 0 |
# 2.1
# Napisz program wczytujący dane dziesięciu czytelników biblioteki (nazwisko, imię, numer karty
# bibliotecznej, liczba wypożyczonych książek). Następnie program powinien umożliwiać:
# • wyświetlanie informacji o czytelniku z podanym numerem karty bibliotecznej,
# • wyświetlanie informacji o wszystkich czytelnika... | Python | 1 |
0, 1.0, -1.0, 1.0).project(angle, zoom, &camera),
Point4D::new(-1.0, -1.0, 1.0, 1.0).project(angle, zoom, &camera),
Point4D::new(1.0, -1.0, 1.0, 1.0).project(angle, zoom, &camera),
Point4D::new(1.0, 1.0, 1.0, 1.0).project(angle, zoom, &camera),
Point4D::new(-1.0, 1.0, 1.0... | Rust | 0 |
import pygame
from .ball_manager import BallManager
from .boost_pads_manager import BoostPadsManager
from .field import Field
from .goal_explosions.goal_explosion_manager import GoalExplosionManager
from .HUD import HUD
from .match_stats import MatchStats
from .particle_manager import ParticleManager
from .player_mana... | Python | 1 |
pub op: Option<OwningToken>,
pub b: Option<Rc<EContextAll>>,
}
impl CustomRuleContext for MultContextExt {
fn get_rule_index(&self) -> usize {
RULE_e
}
fn enter(ctx: &BaseParserRuleContext<Self>, listener: &mut dyn Any) where Self: Sized {
listener.downcast_mut::<Box<dyn LabelsListener>>()
.map(|it| it.ente... | Rust | 0 |
#Password,Contact and Email Verifications Code is used in Register.py in the function of (def register_data(self) in try and except part
#Password Verifications Code is used in login.py in the function og def forget_passwd(self) in try and except part
#Password
pass1 =input("Enter Password: ")
l,u,p,d=0,0,0,0
if len(... | Python | 1 |
ex<fn(&str)> = Mutex::new(try_compile);
}
TRY_COMPILE_GUARD.lock().unwrap()(&reference_rendered);
}
fn try_compile(src: &str) {
let mut rustc = Command::new("rustc")
.arg("--crate-type=lib")
.arg("-Zno-trans")
.arg("-")
... | Rust | 0 |
"""Fixtures for Tailscale integration tests."""
from __future__ import annotations
from collections.abc import Generator
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from tailscale.models import Devices
from homeassistant.components.tailscale.const import CONF_TAILNET, DOMAIN
from homeassistan... | Python | 1 |
me_model(batch)[batch[split_mask]]
ce_local = ctx.criterion(output_local, labels)
kl_local = self.KL_Loss(self.LogSoftmax(output_local), self.Softmax(output_meme.detach()))
ce_meme = ctx.criterion(output_meme, labels)
kl_meme = self.KL_Loss(self.LogSoftmax(output_meme), self.Softmax(ou... | Python | 1 |
it is initialized with default value first.
pub fn mut_output_config(&mut self) -> &mut OutputConfig {
if self.output_config.is_none() {
self.output_config.set_default();
}
self.output_config.as_mut().unwrap()
}
// Take field
pub fn take_output_config(&mut self) -> ... | Rust | 0 |
, 0x64, 0x20, 0x61, 0x66, 0x74, 0x65, 0x72, 0x20, 0x42, 0x61, 0x6e, 0x6b,
0x20, 0x54, 0x61, 0x6d, 0x70, 0x65, 0x72, 0x69, 0x6e, 0x67, 0x22, 0x2e, 0x2e,
0x2e, 0x20, 0x44, 0x61, 0x6d, 0x6e, 0x20, 0x6b, 0x69, 0x64, 0x73, 0x2e, 0x20,
0x54, 0x68, 0x65, 0x79, ... | Rust | 0 |
#!/usr/bin/env python
"""Solution for project euler problem #12.
Based on:
http://stackoverflow.com/questions/571488/project-euler-12-in-python/571526#571526
"""
def ndiv(n, prime_factors):
"""Return number of divisors of `n`.
prime_factors: prime factors of `n`.
>>> from itertools import starmap
>>... | Python | 1 |
problem.params,
OVector::<f64, U2>::from_column_slice(&[1., 1.])
);
}
#[test]
fn test_helical_valley() {
let mut problem = HelicalValley {
params: OVector::<f64, U3>::zeros(),
};
let initial = OVector::<f64, U3>::from_column_slice(&[-1., 0., 0.]);
// check derivative implemen... | Rust | 0 |
import numpy as np
import numpy.testing as testing
from ..fssd import (
FSSD,
ustat_h1_mean_variance,
power_criterion,
fssd_grid_search_kernel,
FSSDH0SimCovObs,
FSSDH0SimCovDraw,
)
from .._utils import meddistance, fit_gaussian_draw, constrain
from ..kernel import KGauss
from ..density import I... | Python | 1 |
meta_path must be same with hop count.")
sampler = strategy2op(self._strategy[index], "Sampler")
req = pywrap.new_sampling_request(
self._meta_path[index], sampler, self._expand_factor[index],
pywrap.FilterType.OPERATOR_UNSPECIFIED,
pywrap.FilterField.FIELD_UNSPECIFIED)
pywrap.set_s... | Python | 1 |
from PIL import Image
import torch
from transformers import AutoModelForCausalLM, AutoProcessor
from common.registry import registry
@registry.register_llm("phi3")
class Phi3:
def __init__(
self,
engine="phi3",
temperature=0.1,
max_tokens=4096,
top_p=0.95,
stop=[""... | Python | 1 |
import torch
import functools
if torch.__version__.startswith('0'):
from .sync_bn.inplace_abn.bn import InPlaceABNSync
BatchNorm2d = functools.partial(InPlaceABNSync, activation='none')
BatchNorm2d_class = InPlaceABNSync
relu_inplace = False
else:
BatchNorm2d_class = BatchNorm2d = torch.nn.SyncBatc... | Python | 1 |
re ignored"]
#[doc = " \\return non-zero value iff the processing block can be extended to the given extension"]
pub fn rs2_is_processing_block_extendable_to(
block: *const rs2_processing_block,
extension_type: rs2_extension,
error: *mut *mut rs2_error,
) -> ::std::os::raw::c_int;
}
... | Rust | 0 |
import os
import matplotlib
import numpy as np
from scipy.interpolate import RegularGridInterpolator
import imas.training
if "DISPLAY" not in os.environ:
matplotlib.use("agg")
else:
matplotlib.use("TKagg")
import matplotlib.pyplot as plt
# Open input data entry
entry = imas.training.get_training_db_entry()... | Python | 1 |
( seq_list : &Vec<String> ) -> Vec<f64>
{
//println!( "fn weight_va(), &seq_list : {:p}", seq_list );
//Number of the sequences and sites.
let num_seq : usize = ( *seq_list ).len();
let mut weight_list : Vec<f64> = vec![ 0.0; num_seq ];
/*
Calculate pairwise distance by counting differd symbols.
seq_pair_1 ... | Rust | 0 |
SPIKES_MATURE_ROOTS: u16 = 8692;
pub const BOUNTIFUL_BAMBOO_SPIKES_MATURE_ROOTS_SEED: u16 = 8693;
pub const BOUNTIFUL_WHITE_DOLL_S_EYES: u16 = 8694;
pub const BOUNTIFUL_WHITE_DOLL_S_EYES_SEED: u16 = 8695;
pub const BOUNTIFUL_WHITE_DOLL_S_EYES_ROOTS: u16 = 8696;
pub const BOUNTIFUL_WHITE_DOLL_S_EYES_ROOTS_SEED: u16 = 86... | Rust | 0 |
S), total_cache / 12);
cfg.set_cache(Some(COL_BLOCK_TRANSACTIONS), total_cache / 12);
cfg.set_cache(Some(COL_BLOCK_NUMBERS), total_cache / 12);
cfg.bloom_filters.insert(Some(COL_TRANSACTIONS_META), 32);
match DiskDatabase::open(cfg, path) {
Ok(db) => Ok(Self::open_with_cache(db)),
Err(err) => Err(Error:... | Rust | 0 |
f generate_new_affine(sequence_mask):
num_residues, _ = sequence_mask.shape
quaternion = jnp.tile(
jnp.reshape(jnp.asarray([1., 0., 0., 0.]), [1, 4]),
[num_residues, 1])
translation = jnp.zeros([num_residues, 3])
return quat_affine.QuatAffine(quaternion, translation, unstack_inputs=True)
def l2_n... | Python | 1 |
-p, --points <points> Calculate target distance to generate approximatly <points>
number of points.
[default: 0]
ARGS:
<input> Input SVG file, stdin if not present
<output> Output file, stdout if not present"#
)
}
fn print_ba... | Rust | 0 |
s::EvmAddressMapping;
use module_currencies::{BasicCurrencyAdapter};
use module_transaction_payment::{Multiplier, TargetedFeeAdjustment};
// re-exports
pub use pallet_staking::StakerStatus;
pub use primitives::{
evm::EstimateResourcesRequest,
AccountId, AccountIndex, Amount, Balance, BlockNumber,
CurrencyId, EraIn... | Rust | 0 |
ce)
with OffloadActivations(min_offload_size=1000):
out = model(inp)
out.sum().backward()
# The test passes if no errors occur, as we're mainly testing
# that the logic handles both offloaded and non-offloaded tensors
@require_torch_accelerator
def test_real_hf... | Python | 1 |
t)]
extern crate test;
use test::Bencher;
use ocaml_interop::{ocaml, ocaml_call, ocaml_alloc, ocaml_frame, FromOCaml, ToOCaml};
use tezos_interop::runtime;
use tezos_interop::runtime::OcamlResult;
ocaml! {
pub fn echo(value: String) -> String;
}
fn ocaml_fn_echo(arg: String) -> OcamlResult<String> {
runti... | Rust | 0 |
Minimize to tray
self.dlg.minimize()
_wait_minimized(self.dlg)
# Make sure that the hidden icons area is enabled
orig_hid_state = _toggle_notification_area_icons(
show_all=False,
debug_img="%s_01" % (self.id())
)
# Run one more instance of the s... | Python | 1 |
, TryFutureExt},
futures_executor::block_on,
futures_util::{stream::FuturesOrdered, TryStreamExt},
};
use jsonrpc_derive::rpc;
use std::{iter::FromIterator, vec::Vec};
use codec::{Codec, Decode, Encode, Input};
use sp_runtime::traits::{AtLeast32BitUnsigned, Block as BlockT};
use sp_core::storage::StorageKey... | Rust | 0 |
import numpy as np
from numpy import pi
from Const import kb, eCharge as chargeE, Permvac as epsv
# this module contains the functions to calculate de Born term and its first order derivatives
# the derivatives with respect to temperature should be used with caution, because they were not yet used and can have errors... | Python | 1 |
# inspired from:
# https://python-packaging-user-guide.readthedocs.org/en/latest/single_source_version/
__title__ = "pysbd"
__version__ = "0.3.4"
__summary__ = "pysbd (Python Sentence Boundary Disambiguation) is a rule-based sentence boundary detection that works out-of-the-box across many languages."
__uri__ = "http:... | Python | 1 |
import streamlit as st
from PIL import Image
from cat import get_cat_result, get_cat_med
from dog import get_dog_result, get_dog_med
def main():
st.title("Animals Skin Disease Detection")
# User selects either dog or cat
animal_choice = st.radio("Select Animal:", ("Dog", "Cat"))
uploaded_file = st.f... | Python | 1 |
tract and tokenize a list of files.
Args:
sources (list of str): list of source code to extract and tokenize.
nlp (spacy.language.Language): spacy language object.
Returns:
list of list of tuple: tuple containing:
str: name of global function or method, if it's a method, cl... | Python | 1 |
Context):
logger.info(f"[USER] {call.from_user.id} - Вход в user_invoices_start")
await state.set_state(UserInvoicesStates.year)
await call.message.edit_text("📅 Выберите год для накладных:", reply_markup=await user_invoices_years_kb_inline())
async def user_reconciliation_start(call: types.CallbackQuery,... | Python | 1 |
erialize)]
struct PrebakeSummary {
map: String,
scenario: String,
finished_trips: usize,
cancelled_trips: usize,
total_trip_duration_seconds: f64,
}
//! ` `
//! In this repeat loop we will insert another discretionary if |hyf[j-1]| is
//! odd, when both branches of the previous discretionary end at ... | Rust | 0 |
rong Lucas pseudoprimes. https://oeis.org/A217719
"989",
"3239",
"5777",
"10877",
"27971",
"29681",
"30739",
"31631",
"39059",
"72389",
"73919",
"75077",
"100127",
... | Rust | 0 |
from adminbyrequest import AdminByRequest, ABRDatacenter
# Months Enums
class Month:
January = 1
February = 2
March = 3
April = 4
May = 5
June = 6
July = 7
August = 8
September = 9
October = 10
November = 11
December = 12
abr = AdminByRequest('APIKEY', datacenter=ABRDat... | Python | 1 |
* 0.01;
scene_dat.lookfrom = Point::new(26.0, 3.0, 6.0);
scene_dat.lookat = Point::new(0.0, 2.0, 0.0);
scene_dat.vfov = 20.0;
}
Scene::Noises => {
world = noises();
scene_dat.background = Color::new(0.70, 0.80, 1.00);
scene_dat.lo... | Rust | 0 |
if len(datum.tags) == 0:
continue
data.append(datum)
orientation, position = map.estimate_pose(datum.tags)
positions.append(position)
orientations.append(orientation_to_yaw_pitch_roll(orientation))
times.append(datum.timestamp)
#... | Python | 1 |
"""
Magic hexagon in cpmpy.
Prob023: Magic Hexagon
http://www.comp.rgu.ac.uk/staff/ha/ZCSP/prob023/prob023.pdf
http://www.cse.unsw.edu.au/~tw/csplib/prob/prob023/
'''
A magic hexagon consists of the number 1 to 19 arranged in a hexagonal pattern:
A,B,C
D,E,F,G
H,I,J,K,L
M,N,O,P
Q,R,S
We have a constraint ... | Python | 1 |
fn len(&self) -> usize {
1 + self.0.len() * 4 // Two bytes per item
}
///
/// Encode `TelnetOptionStatus` to `BufMut`
///
pub(crate) fn encode<T: BufMut>(&self, dst: &mut T) {
/*
dst.put_u8(consts::negotiation::status::IS);
for (arguments, action) in &self.0 {
... | Rust | 0 |
}, V{:01X}", nibbles.1, nibbles.2),
(0x8, _, _, 0x1) => format!("OR V{:01X}, V{:01X}", nibbles.1, nibbles.2),
(0x8, _, _, 0x2) => format!("AND V{:01X}, V{:01X}", nibbles.1, nibbles.2),
(0x8, _, _, 0x3) => format!("XOR V{:01X}, V{:01X}", nibbles.1, nibbles.2),
(0x8, _, _, 0x4) => format!(... | Rust | 0 |
"""Utilities for tagging text with ontology-based labels."""
from __future__ import annotations
import json
from pathlib import Path
from typing import Dict, List
from ..models.provision import Atom, Provision
# Directory where ontology JSON files are stored.
ONTOLOGY_DIR = Path(__file__).resolve().parents[2] / "da... | Python | 1 |
lick('+'), font = font1, text_color = '#007FFF', text = '+', corner_radius=15, fg_color ='#222222', hover_color = '#3b3b3b', bg_color= '#000', cursor = 'hand2', width = 60 )
b14_button.place(x=195, y=90)
b15_button = customtkinter.CTkButton(app, command = lambda: button_click('-'), font = font1, text_color = '#007FFF'... | Python | 1 |
esult.set(gdk::ModifierType::SHIFT_MASK, modifiers.shift_key());
result.set(gdk::ModifierType::META_MASK, modifiers.super_key());
result
}
// The is_prime function should take an i32 and return a boolean.
// - It's fine to special-case numbers less than 2.
// - We declare negative numbers not to be prime.
// - Don't... | Rust | 0 |
身を選択できません",
'/act/7/result': f"{C['MAGENTA']}プレイヤー$0のアクション「$1」は、プレイヤー$2のブラックホールに永久に飲み込まれた。{C['RESET']}",
'/share/poor': f"{C['MAGENTA']}エネルギーが足りません。先にチャージしてはどうでしょう?{C['RESET']}",
'/share/out-of-range': "許容範囲内の値を入力してください。",
'/share/not-found': "ターゲットが見つかりません。",
'/share/unable': f"{C['RED']}このアクションは現... | Python | 1 |
the diagonal (in the new row indices) is the column of U
// and part of x below the diagonal divided by the pivot value is the column of L
scratch.rhs.set(mat_col.0.iter().copied().zip(mat_col.1));
scratch.mark_nonzero.run(
&mut scratch.rhs,
|new_i| &lower.col_rows(new... | Rust | 0 |
xtend(
filter_slice(&col_data[range.clone()], &mut predicate)
.map(|r| (r.start + offset)..(r.end + offset)),
)
}
ret
}
fn filter_slice<'a, T, F>(
col_data: &'a [T],
predicate: &'a mut F,
) -> impl Iterator<Item = Range<usize>> + 'a
where
T: Copy,
F: 'a + FnM... | Rust | 0 |
Owned;
use na::DefaultAllocator;
use na::{DimName, Matrix, MatrixMN, VectorN};
#[derive(Clone, Copy, Debug)]
pub struct UpdateParams {
pub l2_reg: Fxx,
pub step_size: Fxx,
}
//
// GradientTrainer is an interface to record loss-function gradients
// from training observations for model update.
//
// # Argument... | Rust | 0 |
'''
实验名称:连接无线路由器
版本:v1.0
日期:2019.8
作者:01Studio
说明:编程实现连接路由器,将IP地址等相关信息通过OLED显示(只支持2.4G网络)。
'''
import network,time
from machine import I2C,Pin
from ssd1306 import SSD1306_I2C
#初始化相关模块
i2c = I2C(sda=Pin(13), scl=Pin(14))
oled = SSD1306_I2C(128, 64, i2c, addr=0x3c)
#WIFI连接函数
def WIFI_Connect():
WIFI_LED=Pin(2, Pin... | Python | 1 |
import whisper
from subtitulacion.utilidades import formato_srt
from pathlib import Path
def transcribir_audio_a_srt(ruta_audio):
"""
Transcribe un archivo de audio y guarda la transcripción en formato SRT usando Whisper.
"""
# whisper_models = ["tiny", "base", "small", "medium", "large"]
print("Ca... | Python | 1 |
point in 0..length {
// Line may go either up or down
if y2 > y1 {
*sea.at_mut(x1 + point, y1 + point) += 1;
} else {
*sea.at_mut(x1 + point, y1 - point) += 1;
}
}
}
}
println!("Part 2: {}", sea.sense_danger());
let end = Instant::now();
println!("... | Rust | 0 |
Ok(())
}
#[test]
fn three_char_first() -> Result<(), N2NErr> {
let charset = Charset::case_sensitive("aBcD");
let nr = name2number("aaa", &charset)?;
assert_eq!(nr, 4 + 16);
Ok(())
}
#[test]
fn three_char_last() -> Result<(), N2NErr> {
let charset = Ch... | Rust | 0 |
.get(finished[0])
replay.add(td_errors, transitions)
wip_actors.extend([actors[pid].rollout.remote(current_weights)])
finished_learner, _ = ray.wait([wip_learner], timeout=0)
if finished_learner:
current_weights, indices, td_errors = ray.get(finished_learner[0])
... | Python | 1 |
:4] = pred_ctr_y + 0.5 * pred_h - 1
return pred_boxes
def decode_iou(self, rel_codes, boxes, num_p = 8):
"""
From a set of original boxes and encoded relative box offsets,
get the decoded boxes.
Arguments:
rel_codes (Tensor): encoded boxes # predict [2, 120... | Python | 1 |
def search(lst):
'''
You are given a non-empty list of positive integers. Return the greatest integer that is greater than
zero, and has a frequency greater than or equal to the value of the integer itself.
The frequency of an integer is the number of times it appears in the list.
If no such a val... | Python | 1 |
af_matrix)
ip_loss = torch.mean(anti_wrapping_function(phase_r - phase_g))
gd_loss = torch.mean(anti_wrapping_function(gd_r - gd_g))
iaf_loss = torch.mean(anti_wrapping_function(iaf_r - iaf_g))
return ip_loss, gd_loss, iaf_loss
def anti_wrapping_function(x):
return torch.abs(x - torch.round(x / ... | Python | 1 |
` method
// and attach it to the router.
.middleware(Middleware::post(my_custom_header_adder_middleware))
// Create a post middleware which will require request info using `Middleware::post_with_info()` method
// and attach it to the router.
.middleware(Middleware::post_with_info... | Rust | 0 |
# coding=utf-8
# Copyright 2022 The Google Research Authors.
#
# 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 applicab... | Python | 1 |
wrap()).into_nodes();
let old = self
.data
.main_el_vdom
.borrow_mut()
.take()
.expect("missing main_el_vdom");
patch::patch_els(
&self.cfg.document,
&self.mailbox(),
&self.clone(),
&self.cfg.mo... | Rust | 0 |
shot = penta_shot = False
gold = 0
shop_open = False
kill_count = 0
start_ticks = pygame.time.get_ticks()
hit_flash_time = 0
hit_flash_duration = 300
shield_flash_time = 0
shield_flash_duration = 300
MainEv = 0
while MainEv == 0:
... | Python | 1 |
::BitOr;
use std::sync::Arc;
use std::fs::File;
use serde_derive::{Serialize, Deserialize};
use linked_hash_map::LinkedHashMap;
pub const STORED: SchemaProps = SchemaProps { stored: true, indexed: false };
pub const INDEXED: SchemaProps = SchemaProps { stored: false, indexed: true };
#[derive(Debug, Copy, Clone, Par... | Rust | 0 |
from typing import Annotated
from eth_rpc import ContractFunc, PrivateKeyWallet, ProtocolBase, TransactionReceipt
from eth_rpc.networks import Arbitrum
from eth_rpc.types import METHOD, Name, Struct, primitives
from eth_rpc.utils import EventReceiptUtility
from eth_typeshed.erc20 import TransferEvent, TransferEventTyp... | Python | 1 |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the Apache License, Version 2.0
# found in the LICENSE file in the root directory of this source tree.
from typing import Any, Tuple
from torchvision.datasets import VisionDataset
from .decoders import TargetDecoder, ImageDat... | Python | 1 |
one:
break
self.update_results(self._game.outcome)
self.reset_game()
return self.calculate_percentages(num_of_games)
def update_results(self, results: list[int]) -> None:
"""
Update the win/tie counts based on the outcome of a game.
r... | Python | 1 |
msg_sample.initial_window_size = 1024;
msg_sample.maximum_packet_size = 1024;
check_encode_decode(Message::Open(msg_sample), raw_msg);
}
#[test]
pub fn channel_open_success() {
let raw_msg = &[
101, // msg type
0, 18, // msg size
0, // m... | Rust | 0 |
hash_db::HashDB::get(self, key, prefix).is_some()
}
fn insert(&mut self, prefix: Prefix, value: &[u8]) -> H::Out {
hash_db::HashDB::insert(self.overlay, prefix, value)
}
fn emplace(&mut self, key: H::Out, prefix: Prefix, value: DBValue) {
hash_db::HashDB::emplace(self.overlay, key, prefix, value)
}
fn remo... | Rust | 0 |
self) -> _PRI_USBW {
_PRI_USBW { w: self }
}
#[doc = "Bit 16 - ROM latency select. Should always be 0."]
#[inline]
pub fn rom_lat(&mut self) -> _ROM_LATW {
_ROM_LATW { w: self }
}
}
<filename>src/device/builder.rs
use prometrics::metrics::MetricBuilder;
use std::time::Duration;
use... | Rust | 0 |
<< 1),
GIT_REPOSITORY_INIT_NO_DOTGIT_DIR = (1 << 2),
GIT_REPOSITORY_INIT_MKDIR = (1 << 3),
GIT_REPOSITORY_INIT_MKPATH = (1 << 4),
GIT_REPOSITORY_INIT_EXTERNAL_TEMPLATE = (1 << 5),
}
#[repr(C)]
pub enum git_repository_init_mode_t {
GIT_REPOSITORY_INIT_SHARED_UMASK = 0,
... | Rust | 0 |
from django.db import models
from django.conf import settings
class Profile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
date_of_birth = models.DateField(blank=True, null=True)
photo = models.ImageField(upload_to='users/%Y/%m/%d', blank=True)
def __str__(self):
... | Python | 1 |
import numpy as np
import pyvista as pv
import os
os.chdir("C:\R2_Gaussian")
# vol_path = "data/synthetic_dataset/cone_ntrain_50_angle_360/0_chest_cone/vol_gt.npy"
vol_path = "output/a4fc1032-5/point_cloud/iteration_30000/vol_pred.npy"
vol = np.load(vol_path)
plotter = pv.Plotter(window_size=[800, 800], line_smoot... | Python | 1 |
me2': 23, 'viewflags': 0, 'isnew': None, 'volume': 2, 'wh': 117501, 'isadult': None, 'logs': None}, {'id': 67822823, 'supplierid': 104452, '__sort': 51033, 'brand': 'FAMELIN.NV', 'brandid': 1039551, 'colors': [{'id': 0, 'name': 'черный'}, {'id': 8421504, 'name': 'серый'}, {'id': 16119260, 'name': 'бежевый'}, {'id': 108... | Python | 1 |
: MinerControl;
}
#[pallet::event]
#[pallet::generate_deposit(pub(super) fn deposit_event)]
pub enum Event<T: Config> {
ChallengeProof{peer_id: u64},
VerifyProof{peer_id: u64},
}
/// Error for the segment-book pallet.
#[pallet::error]
pub enum Error<T> {
//Vec to BoundedVec Error.
Boun... | Rust | 0 |
}",
answer,
);
}
#[test]
fn y20d06ch02() {
let k = parse_text();
let k = extract_indiv_answered_yes(k);
let k = sum_all_yeses(k);
let answer = match k {
Continuation::Done(k_answer) => k_answer,
_ => panic!("No answer received"),
... | Rust | 0 |
+ (t_next - t_cur) * (coeff1 * d_cur + coeff2 * buffer_model[-1] + coeff3 * buffer_model[-2] + coeff4 * buffer_model[-3])
if len(buffer_model) == max_order - 1:
for k in range(max_order - 2):
buffer_model[k] = buffer_model[k+1]
buffer_model[-1] = d_cur.detach()
e... | Python | 1 |
max = cmp::min(y as i64 + choke_distance as i64, y_end as i64) as usize;
for x_new in xmin..xmax {
for y_new in ymin..ymax {
if !points[x_new][y_new].is_border {
// Needs to be a border to be acceptable position
continue;
}
... | Rust | 0 |
tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_image_classification(*config_and_inputs)
@slow
def test_model_from_pretrained(self):
for model_name in CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
model = CvtModel.from_pretrained(model_name)
self.asser... | Python | 1 |
unicode object
hypotheses = [_.decode("utf-8") for _ in hypotheses]
references = [_.decode("utf-8") for _ in references]
# Slice all hypotheses and references up to SOS -> EOS
sliced_hypotheses = [postproc.slice_text(
_, self._eos_token, self._sos_token) for _ in hypotheses]
sliced_referenc... | Python | 1 |
)
signal.signal(signal.SIGUSR2, divein)
# breakpoint()
# run
if opt.resume_overwrite:
ckpt = torch.load(opt.resume_overwrite,map_location='cpu')
model.load_state_dict(ckpt['state_dict'],strict=False)
if opt.train:
try:
print('t... | Python | 1 |
, weights::Weight};
use frame_system::{ensure_root, ensure_signed, EnsureRoot};
use sp_core::H256;
use sp_runtime::{
testing::Header,
traits::{BadOrigin, IdentityLookup},
Perbill,
};
pub use crate as authority;
pub type AccountId = u128;
pub type BlockNumber = u64;
parameter_types! {
pub const BlockHashCount: u6... | Rust | 0 |
#!/usr/bin/env python3
# Copyright 2003 Dave Abrahams
# Copyright 2006 Rene Rivera
# Copyright 2003 Vladimir Prus
# Distributed under the Boost Software License, Version 1.0.
# (See accompanying file LICENSE.txt or copy at
# https://www.bfgroup.xyz/b2/LICENSE.txt)
# Demonstration that module variables have the correc... | Python | 1 |
ensor]]): [description]
"""
samples = self.preprocess_mot_inputs(data)
targets = self.prepare_mot_targets(data)
# Extract backbone features
with torch.no_grad():
template_features = self.backbone(samples['template'].tensor)
temp_logits, temp_boxes = self.detection(template_features,
... | Python | 1 |
day13::part_2(black_box(&input));
})
});
c.bench_function("day14", |b| {
b.iter(|| {
let input = include_str!("../inputs/day14.txt");
day14::part_1(black_box(input));
day14::part_2(black_box(input));
})
});
c.bench_function("day15", |b| {
... | Rust | 0 |
itlab, grafana, gocd, hadoop, httpd, influxdb, jenkins, jetty, jupyter, joomla, jboss, keycloak, landray, minihttpd, mongoexpress, nacos, nexus, nodejs, nodered, phpmyadmin, phpunit, rails, showdoc, skywalking, solr, spring, supervisor, thinkphp, tomcat, ueditor, uwsgiphp, weblogic, webmin, yonyou, zabbix'
# },... | Python | 1 |
)
except Exception as e:
log.error(f"Failed to send error message to user: {e}")
# ----------------- Main -----------------
def main():
# Build application with custom timeouts
app = (
ApplicationBuilder()
.token("YOUR_TELEGRAM_BOT_TOKEN")
.read_timeout(30)
... | Python | 1 |
pub enum DkimParsingError {
DuplicatedField(&'static str),
MissingField(&'static str),
NotADkimSignatureHeader,
UnsupportedDkimVersion(String),
UnsupportedSigningAlgorithm(String),
UnsupportedPublicKeyQueryMethods(String),
InvalidBase64Value(base64::DecodeError),
InvalidCanonicalization... | Rust | 0 |
BYTES`, so `s` and `buf` are valid for reads of the
// required length.
sodium::crypto_core_ed25519_scalar_add(
self.inner_mut() as *mut libc::c_uchar,
buf.as_ptr(),
s.inner() as *const libc::c_uchar,
);
}
mem::clear(&mu... | Rust | 0 |
= pointer_mode.into();
let (keyboard_mode, remaining) = u8::try_parse(remaining)?;
let keyboard_mode = keyboard_mode.into();
let remaining = remaining.get(2..).ok_or(ParseError::InsufficientData)?;
let _ = remaining;
Ok(GrabKeyboardRequest {
owner_events,
... | Rust | 0 |
# Crie um dicionário com algumas palavras em inglês e suas traduções em
# português. Peça ao usuário para digitar uma palavra em inglês e exiba a tradução
# correspondente.
dict = {'mother':'mãe',
'light':'luz',
'parts':'partes',
'country':'país',
'father':'pai',
'picture':'imagem',
'eyes':'olhos',
'times':'vezes',
'... | Python | 1 |
pub struct MultiplicationTranscript;
pub struct RandomSkinnyTranscriptParams;
pub struct RandomFatTranscriptParams;
pub struct ResharingTranscriptParams;
pub struct MultiplicationTranscriptParams;
pub struct TranscriptId;
pub struct QuadrupleId;
pub type EcdsaQuadruple = (
Ran... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.