text string | label_name string | labels int64 |
|---|---|---|
,
/// 7.0, 8.0, 9.0]);
///
/// assert_eq!(&matrix * 2.0, aicourse::matrix::Matrix::new(3, 3, vec![2.0, 4.0, 6.0,
/// 8.0, 10.0, 12.0,
/// ... | Rust | 0 |
gl/es3/glBlitFramebuffer)(srcX0, srcY0, srcX1, srcY1, dstX0, dstY0, dstX1, dstY1, mask, filter)
/// * `mask` group: ClearBufferMask
/// * `filter` group: BlitFramebufferFilter
#[cfg_attr(feature = "inline", inline)]
#[cfg_attr(feature = "inline_always", inline(always))]
pub unsafe fn glBlitFramebuffer(
sr... | Rust | 0 |
from aiogram import types
async def set_default_commands(dp):
await dp.bot.set_my_commands(
[
types.BotCommand("start", "Botni ishga tushurish"),
]
)
| Python | 1 |
ange::<N::Output>::new(self.start * M::to_usize());
let UniChunked { data, chunk_size } = set;
IsolateIndex::try_isolate(rng, data).map(|data| UniChunked { data, chunk_size })
}
}
impl<S> IsolateIndex<ChunkedN<S>> for usize
where
S: Set + Isolate<std::ops::Range<usize>>,
{
type Output = S::... | Rust | 0 |
::systems::systems_list`).
/// - [`crate::marker`] if you want to create your own 'HasFoo' Trait.
#[doc(notable_trait)]
pub trait SystemDefinition {}
#[allow(rustdoc::missing_doc_code_examples)]
impl<Head> SystemDefinition for (Head, ()) where Head: SystemDefinition {}
#[allow(rustdoc::missing_doc_code_examples)]
imp... | Rust | 0 |
::Vertical)
.constraints(
[
Constraint::Length(13),
Constraint::Min(12),
]
.as_ref(),
)
.split(area);
draw_top(f, chunks[0], app);
draw_middle(f, chunks[1], app);
}
fn draw_top(f: &mut Frame<Backend>, area: Rect, a... | Rust | 0 |
::Value>,
}
impl AuthInfo {
/// Decode POST body into a AuthInfo struct
pub fn from_post_body(body: &[u8], is_json: bool) -> Option<AuthInfo> {
if is_json {
if let Ok(mut ai) = serde_json::from_slice::<AuthInfo>(body) {
if let Cow::Owned(p) = utf8_percent_encode(&ai.password... | Rust | 0 |
*/
#[inline(always)]
pub fn decodeProtocolSignedThousandthsFloat(b: &[u8]) -> f32 {
let mut signed_angle = dec_prot_i16(b) as f32;
signed_angle /= 1000.;
return signed_angle;
}
#[inline(always)]
pub fn encodeProtocolSignedThousandthsFloat(input: f32, b: &mut [u8]) {
let input_as_int = (input * 1000.) a... | Rust | 0 |
#! /usr/bin/env python
# -*- encoding: utf-8 -*-
#
# Copyright 2024 the tencent authors.
#
from dataclasses import dataclass
import torch
__all__ = ["SmoothQuant"]
@dataclass
class SmoothConfig:
alpha: float = 0.5
smooth_first_linears: bool = True
smooth_second_linears: bool = False
class SmoothQuant... | Python | 1 |
import time
import terasim_cosim.redis_msgs as redis_msgs
from terasim_cosim.constants import *
from terasim_cosim.redis_client_wrapper import create_redis_client
# Configure redis key-and data type
key_value_config = {VEHICLE_PLANNING: redis_msgs.VehiclePlanning}
redis_client = create_redis_client(key_value_config=... | Python | 1 |
std::option::Option::None;
self.permission.clear();
self.owner.clear();
self.group.clear();
self.modification_time = ::std::option::Option::None;
self.access_time = ::std::option::Option::None;
self.symlink.clear();
self.block_replication = ::std::option::Option::... | Rust | 0 |
'slope'] = m
df.at[df.index[i], 'intercept'] = c
# Create a boolean mask for trendline support
mask_support = df['slope'] > 0
# Create a boolean mask for trendline resistance
mask_resistance = df['slope'] < 0
# Create new columns for trendline support and resistance
df['support'] = n... | Python | 1 |
_testbed3d;
use num::Float;
use na::{Pnt3, Vec3, Translation};
use ncollide::shape::{Ball, Plane};
use nphysics::world::World;
use nphysics::object::RigidBody;
use nphysics_testbed3d::Testbed;
fn main() {
let mut testbed = Testbed::new_empty();
/*
* World
*/
let mut world = World::new();
wo... | Rust | 0 |
-bits)
/// express each value of the Red, Green, Blue, and Alpha components in the
/// RGBA color.
///
/// Note that conversion from float to integer component types in `palette` maps
/// the floating point value to the integer's value range and then rounds the
/// result before casting to the integer type. An example ... | Rust | 0 |
vail", "1.3.6.1.4.1.2021.9.1.7.0", "Integer"));
targets.push(Target::new("dskUsed", "1.3.6.1.4.1.2021.9.1.8.0", "Integer"));
targets.push(Target::new("dskPercent", "1.3.6.1.4.1.2021.9.1.9.0", "Integer"));
targets.push(Target::new("dskPercentNode", "1.3.6.1.4.1.2021.9.1.10.0", "Integer"));
} else if nickna... | Rust | 0 |
"""Representation of a switchMultilevel."""
from homeassistant.components.number import NumberEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.helpers.entity_platfor... | Python | 1 |
#Balanced Binary Tree: Add, Delete, isBalanced?
class BalancedBinaryTree:
def __init__(self,data):
self.data = data
self.left = None
self.right = None
def insertRight(self,node):
self.right = node
def insertLeft(self,node):
self.left = node
def height(node):
if node is None:
return 0
lheight = hei... | Python | 1 |
0xE1, subopcode = 0x01, operands(R1, R2, I16SX32))]
#[insn(opcode = 0xF0, subopcode = 0x01, operands(R2, R2, I8SX32))]
#[insn(opcode = 0xFD, subopcode = 0x01, operands(R2, R2, R1))]
#[insn(opcode = 0xFF, subopcode = 0x01, operands(R3, R2, R1))]
MULS,
/// The SEXT instruction.
///
/// Sign-e... | Rust | 0 |
import cv2
import numpy as np
import matplotlib.pyplot as plt
# Load an image
img = cv2.imread('./Data/test.jpg')
# Different kernels can be changed to highlight image features
# Create an embossing kernel
kernel_emboss_1 = np.array([[-2, -1, 0],
[-1, 1, 1],
... | Python | 1 |
::FromStr;
///
/// assert_eq!(Duration::from_str("1 d").unwrap(), 1.days());
/// assert_eq!(Duration::from_str("10.598 days").unwrap(), 10.598_f64.days());
/// assert_eq!(Duration::from_str("10.598 min").unwrap(), 10.598_f64.minutes());
/// assert_eq!(Duration::from_str("10.598 us").unwrap(), 10.598_f64.microseconds())... | Rust | 0 |
(test_data_s0_null) -> None:
"""test that no s0 returns dwi = attenuation"""
dwi_signal_filter = DwiSignalFilter()
dwi_signal_filter.add_inputs(test_data_s0_null)
dwi_signal_filter.run()
numpy.testing.assert_array_almost_equal(
dwi_signal_filter.outputs["attenuation"].image, test_data_s0_nu... | Python | 1 |
agents.GAEAdvantage(lambda_)(
rewards * multiplier,
baselines * multiplier,
self.dones,
discount_factor=1.0,
)
for lambda_ in LAMBDAS
]
for (lower, upper) in zip(
advantages_per_lambda[:-1], advantages_... | Python | 1 |
expected = Series(exp).astype(result.dtype)
assert_series_equal(result, expected)
@pytest.mark.parametrize('dtype', ['f8', 'i8'])
@pytest.mark.parametrize('ser, exp', [
([1], [1.]),
([1, 2], [1. / 2, 2. / 2]),
([2, 2], [1. / 2, 2. / 2.]),
([1, 2, 3], [1. / 3, 2. / 3, 3. / 3]),
([1, 2... | Python | 1 |
each bus has S = P+jQ = VI^*.
for bus in simulator.buses.values():
s = bus.v * np.conj(bus.i)
self.assertAlmostEqual(bus.p, s.real, places=self.places)
self.assertAlmostEqual(bus.q, s.imag, places=self.places)
# Check that I = YV (matrix notation).
I_true = n... | Python | 1 |
"""Worker Remote Control Bootstep.
``Control`` -> :mod:`celery.worker.pidbox` -> :mod:`kombu.pidbox`.
The actual commands are implemented in :mod:`celery.worker.control`.
"""
from celery import bootsteps
from celery.utils.log import get_logger
from celery.worker import pidbox
from .tasks import Tasks
__all__ = ('Co... | Python | 1 |
hi: HINSTANCE, lpbmp: LPCSTR, cx: c_int, cGrow: c_int, crMask: COLORREF, uType: UINT,
uFlags: UINT,
) -> HIMAGELIST;
pub fn ImageList_LoadImageW(
hi: HINSTANCE, lpbmp: LPCWSTR, cx: c_int, cGrow: c_int, crMask: COLORREF, uType: UINT,
uFlags: UINT,
) -> HIMAGELIST;
pub fn ... | Rust | 0 |
"""Pytest configuration and shared fixtures"""
import pytest
from unittest.mock import Mock, AsyncMock
from datetime import datetime, timedelta, timezone
from src.models.auth import TokenResponse, LocationTokenResponse
from src.models.contact import Contact
from src.models.conversation import Conversation, Message, M... | Python | 1 |
# 24. * *
# ** **
# * * * *
# * * * *
# * ** *
# * ** *
# * * * *
# * * * *
# ** **
# * *
# n=5
# 0 1 2 3 4
# 0 0 1 2 3
# 8 6 4 2 0
# (i-1)*i
n=10
def print_increasing(row):
print("*",end="")
... | Python | 1 |
,
"id": "cluster-2",
"label": "テストラベル2",
"description": "テスト説明2",
"value": "10",
"parent": "cluster-1",
"density": "0.6",
"density_rank": "2",
"density_rank_percentile": "0.7",
},
... | Python | 1 |
//let _h = &PointBlock::block(H);
//let _i = &PointBlock::block(I);
let j = &PointBlock::block(J);
let k = &PointBlock::block(K);
//let _l = &PointBlock::block(L);
let m = &PointBlock::block(M);
//let _n = &PointBlock::block(N);
let o = &PointBlock::block... | Rust | 0 |
"""
Задание №1
В первую строку вводится число N – количество чисел (1 ≤ N ≤ 100000).
Во вторую строку вводится через пробел N чисел, каждое не превышает 2*10e9 по модулю.
Требуется выяснить, сколько среди этих чисел различных. Выведите число, равное количеству различных чисел среди данных.
"""
n = int(input())
numb... | Python | 1 |
lue> {
// Machine metrics
let hostname: String = config
.get_str("Machine.name")
.map_or_else(cxx_ffi::Process_GetHostName, |s| s.to_string());
let tier: String = config.get_str("Machine.tier").unwrap_or("").to_string();
let task: String = config.get_str("Machine.task").unwrap_or("").to... | Rust | 0 |
import base64
import os
from hoshino import Service
from .get_url import generate_img
from ..plugin_utils.base_util import get_img_cq, get_server_default
sv = Service('uma_support_chart')
with open(os.path.join(os.path.dirname(__file__), f'{sv.name}_help.png'), 'rb') as f:
base64_data = base64.b64encode(f.read()... | Python | 1 |
import baostock as bs
import pandas as pd
import os
# 登录系统
lg = bs.login()
# 显示登陆返回信息
print('login respond error_code:'+lg.error_code)
print('login respond error_msg:'+lg.error_msg)
# 获取行业分类数据
rs = bs.query_stock_industry()
# rs = bs.query_stock_basic(code_name="浦发银行")
print('query_stock_industry error_code:'+rs.erro... | Python | 1 |
dick with it though?)
unsafe { &*self.ptr }
}
}
impl<T: POD> ::core::ops::DerefMut for LentDescriptor<T>
{
fn deref_mut(&mut self) -> &mut T
{
// SAFE: We "own" that pointer (... hardware might dick with it though?)
unsafe { &mut *self.ptr }
}
}
use proc_macro::TokenStream;
use quote::{quote, ToTokens};
us... | Rust | 0 |
sa.ForeignKeyConstraint(["project_id"], ["project.id"], ondelete="CASCADE"),
sa.ForeignKeyConstraint(
["source_id"],
["source.id"],
),
sa.ForeignKeyConstraint(
["suppression_rule_id"],
["suppression_rule.id"],
),
sa.PrimaryKeyCons... | Python | 1 |
=> Ok(C64Key::Six),
Key7 => Ok(C64Key::Seven),
Key8 => Ok(C64Key::Eight),
Key9 => Ok(C64Key::Nine),
A => Ok(C64Key::A),
B => Ok(C64Key::B),
C => Ok(C64Key::C),
D ... | Rust | 0 |
t(
"--num_output_shards",
type=int,
default=1,
)
parser.add_argument('--skip_permute', action='store_true')
parser.add_argument(
"--output_dir",
help="Location to write HF model and tokenizer",
)
args = parser.parse_args()
write_model(
mo... | Python | 1 |
params.model_ctrl_user = model["ctrl"] == "user";
params.qos_ctrl_user = qos["ctrl"] == "user";
params.model.rbps = model["rbps"].parse::<u64>()?;
params.model.rseqiops = model["rseqiops"].parse::<u64>()?;
params.model.rrandiops = model["rrandiops"].parse::<u64>()?;
para... | Rust | 0 |
.get_state();
state.serialize(serializer)
}
}
<reponame>kingoflolz/topotag
use crate::decode::DecodedTopotag;
use cv_core::{CameraModel, FeatureWorldMatch, KeyPoint, WorldPoint, sample_consensus::Consensus, WorldPose};
use cv_pinhole::{CameraIntrinsics, NormalizedKeyPoint};
use lambda_twist::LambdaTwist;
u... | Rust | 0 |
("2jS4PHWQJKcawRxdW6GVsjnZBa1ecGdCssn7KhWYJZGTXgL7Es:21")), Some("1".to_string())),
(String::from(base64::encode("2jS4PHWQJKcawRxdW6GVsjnZBa1ecGdCssn7KhWYJZGTXgL7Es:14")), Some("1".to_string()))
] }),
multi_signature: json!({
"participants": ["Beta", "Delta", "Gam... | Rust | 0 |
"""
Author: Alex R. Mead
Date: Jan. 2024
Main entry point for pdf2booklet.
"""
from pypdf import PdfReader, PdfWriter
from utils import parse_arguments, blank_page
def main(read_filename, write_filename):
# Reader and Writer classes
reader = PdfReader(read_filename)
writer = PdfWriter()
# Extract... | Python | 1 |
at(ident.find(|c| c != '_').unwrap_or(ident.len()));
ret.push_str(leading_underscores);
let mut words = split_words(trimmed);
if let Some(word) = words.next() {
ret.extend(word.chars().flat_map(char::to_uppercase));
for word in words {
ret.push('_');
ret.extend(word.c... | Rust | 0 |
#!/usr/bin/python3
from sys import argv
import dynamic_reconfigure.client
import rospy
base_configuration: dict = {
"kp_l" : 0.65,
"kd_l" : 100.,
"offset_l": 0.,
"kp_z" : 1.,
"kd_z" : 100.,
"offset_z": -.2,
"kp_o" : .075,
"kd_o" : 0.,
"offset_o": 0.
}
brice_... | Python | 1 |
nds.
/// They track what kinds of things are found within a type. You can
/// think of them as kind of an "anti-kind". They track the kinds of values
/// and thinks that are contained in types. Having a larger contents for
/// a type tends to rule that type *out* from various kinds. For example,
/// a type that con... | Rust | 0 |
import sys
from typing import TYPE_CHECKING
if sys.version_info < (3, 7) or TYPE_CHECKING:
from ._hoverlabel import Hoverlabel
from ._legendgrouptitle import Legendgrouptitle
from ._stream import Stream
from . import hoverlabel
from . import legendgrouptitle
else:
from _plotly_utils.importers i... | Python | 1 |
N, A, B = map(int, input().split())
temps = list(map(int, input().split()))
first_good = 0
good = 0
stack = 0
stack_ends = 0
stack_list = []
for i in range(len(temps)):
if i >= stack_ends:
if A <= temps[i] <= B:
print("RAN AT INDEX", i, temps[i])
good += 1
first_good = i... | Python | 1 |
=None):
if sigmas is None:
sigmas = self.sigmas
if last_step is not None and last_step < (len(sigmas) - 1):
sigmas = sigmas[:last_step + 1]
if force_full_denoise:
sigmas[-1] = 0
if start_step is not None:
if start_step < (len(sigm... | Python | 1 |
continue
# 遇到选择增益事件(少见)
if auto.click_element("mirror/road_in_mir/event_effect_button.png", threshold=0.75):
auto.click_element("mirror/road_in_mir/select_event_effect_confirm.png")
continue
# 在镜牢中寻路
if auto.find_element("mirror/road_in_m... | Python | 1 |
pub long_time_to_search: String,
pub show_search_result: String,
pub show_search_no_result: String,
pub no_undo_operation: String,
pub no_redo_operation: String,
pub number_within_current_number_of_rows: String,
pub cannot_convert_encoding: String,
pub select_menu: String,
... | Rust | 0 |
# -*- python -*-
# This software was produced by NIST, an agency of the U.S. government,
# and by statute is not subject to copyright in the United States.
# Recipients of this software assume all responsibilities associated
# with its operation, modification and maintenance. However, to
# facilitate maintenance we as... | Python | 1 |
mut self, tag: Tag, buf: &[u8]) -> Result<(), Error> {
// Make sure we don't reuse already allocated tags
if tag == LLMP_TAG_NEW_SHM_CLIENT
|| tag == LLMP_TAG_END_OF_PAGE
|| tag == LLMP_TAG_UNINITIALIZED
|| tag == LLMP_TAG_UNSET
{
return Err(Error:... | Rust | 0 |
f tokens used in the prompt.
completion_tokens (int): The number of tokens used in the completion.
model (str): The model used for the API call.
"""
self.total_prompt_tokens += prompt_tokens
self.total_completion_tokens += completion_tokens
token_costs = self.model_grade... | Python | 1 |
for i in range(self.ii.min(), self.ii.max() + 1, s):
v = (self.ii >= i) & (self.ii < i + s)
if v.sum() < 1:
continue
iis = self.ii[v]
jjs = self.jj[v]
# for stereo case, i.e., rig=2, each video.fmaps contain ... | Python | 1 |
write!(f, "{}", nodes.next().unwrap())?;
while let Some(node) = nodes.next() {
write!(f, " -> {}", node)?;
}
Ok(())
}
}
impl<I> From<Path<I>> for Vec<I> {
fn from(path: Path<I>) -> Self {
path.path
}
}
impl<T> Deref for Path<T> {
type Target = Vec<T>... | Rust | 0 |
self, _assets, 54, 45, 255, *groups)
class SpriteScore2(ImageSprite):
def __init__(self, _assets: list[pg.Surface], *groups: pg.sprite.RenderUpdates):
ImageSprite.__init__(self, _assets, 54, 45, 255, *groups)
class SpriteScore3(ImageSprite):
def __init__(self, _assets: list[pg.Surface], *groups: pg.sp... | Python | 1 |
import torch
import numpy as np
import matplotlib.pyplot as plt
import pickle
from utils_torch import imshow, forward, ricker, showgeom, show_gathers
dev = torch.device("cuda" if torch.cuda.is_available() else "cpu")
torch.cuda.cudnn_enabled = True
torch.backends.cudnn.benchmark = True
# configure
model_scale = 2 # 1/... | Python | 1 |
"html": """
<svg stroke="currentColor" fill="currentColor" stroke-width="0" viewBox="0 0 16 16">
<path fill-rule="evenodd" d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82... | Python | 1 |
ilename>src/operations/bitcoin.rs<gh_stars>1-10
mod balance;
mod secret;
mod send_sats;
mod sign_psbt;
pub use balance::{get_wallet, synchronize_wallet};
pub use secret::{get_mnemonic, save_mnemonic};
pub use send_sats::create_transaction;
pub use sign_psbt::sign_psbt;
pub mod source_wrap;
pub mod filter_wrap;
pub mod... | Rust | 0 |
)
}
fn generate_relation(
job_ids: Rc<RwLock<Vec<String>>>,
vehicles: Vec<String>,
jobs_per_relation: Range<usize>,
) -> impl Strategy<Value = Relation> {
let vehicle_count = vehicles.len();
get_relation_type()
.prop_flat_map(move |relation_type| (Just(relation_type), 0..vehicle_co... | Rust | 0 |
;
pub const JVMTI_CMLR_MAJOR_VERSION: i32 = 1;
pub const JVMTI_CMLR_MINOR_VERSION: i32 = 0;
pub type jvmtiCMLRKind = u32;
pub const JVMTI_CMLR_DUMMY: jvmtiCMLRKind = 1;
pub const JVMTI_CMLR_INLINE_INFO: jvmtiCMLRKind = 2;
pub type jvmtiCompiledMethodLoadRecordHeader = _jvmtiCompiledMethodLoadRecordHeader;
pub type ... | Rust | 0 |
import subprocess
import logging
import tempfile
from langchain.tools import Tool
def run_reconng(cmd: str) -> str:
"""
Run recon-ng console commands headlessly.
Usage: recon-ng <console commands>
Example:
recon-ng "add domains example.com; recon/domains-hosts/google_site_web; run; exit"
"""
... | Python | 1 |
AMPLE.parse::<Entry>().unwrap().decode_value(),
expected: 5353,
})
.example(|| Answer {
calculated: part_2(LONG_EXAMPLE),
expected: 61229,
})
.part_2(|| Answer {
calculated: part_2(INPUT),
expected: 1027422,
})... | Rust | 0 |
tal_chunks:
self.log_message("所有分片信号已收到,退出监听")
break
except Exception as e:
self.log_message(f"监听过程出错: {str(e)}")
break # 出错时退出循环
self.log_message("合并监控结束")
... | Python | 1 |
# coding=utf-8
import copy
from mycodo.inputs.base_input import AbstractInput
# Measurements
measurements_dict = {
0: {
'measurement': 'co2',
'unit': 'ppm'
},
1: {
'measurement': 'voc',
'unit': 'ppb'
}
}
# Input information
INPUT_INFORMATION = {
'input_name_unique'... | Python | 1 |
# 当たり判定処理
self.handle_collisions()
# HPチェック - 勝利判定(自動テストの「勝負がつくまで」以外で使用)
if (self.state != GameState.AUTO_TEST or self.test_duration != float('inf')) and (self.player1.health <= 0 or self.player2.health <= 0):
self.state = GameState.RESUL... | Python | 1 |
torType)
def unbox_numpy_random_generator(typ, obj, c):
"""
Here we're creating a NumPyRandomGeneratorType StructModel with following fields:
* ('bit_generator', _bit_gen_type): The unboxed BitGenerator associated with
this Generator object instance.
* ('parent', ... | Python | 1 |
evision or self.model_revision
# todo: better handle
self.add_tokens = json.loads(self.add_tokens) if self.add_tokens is not None else None
self.add_special_tokens = json.loads(self.add_special_tokens) if self.add_special_tokens is not None else None
# model
assert not (
... | Python | 1 |
# function with a conflicting beartype configuration. In this
# case...
if claw_state.packages_trie_whitelist.conf_if_hooked == conf:
# Restore the prior global beartype configuration if any.
claw_state.packages_trie_whitelist.conf_if_hooked = (
... | Python | 1 |
().method7)
valid_bleu_no_smooth = corpus_bleu(all_references, all_predictions,
smoothing_function=SmoothingFunction().method1)
# sentence_bleu
valid_sentence_bleu = np.mean([
sentence_bleu(ref, pred, smoothing_function=SmoothingFunction().... | Python | 1 |
import os, shutil, sys
import cv2
import imageio
import numpy as np
def compress_gif(sub_folder_path):
# Check valid length
all_files = os.listdir(sub_folder_path)
num_frames_input = 0
valid = True
for file_name in os.listdir(sub_folder_path):
if file_name.startswith("im_"):
n... | Python | 1 |
rmat!("0x{}", &modulo.0))),
}
}
fn translate_typ<'a>((_, (tau, _)): Typ) -> RcDoc<'a, ()> {
translate_base_typ(tau)
}
fn translate_literal<'a>(lit: Literal) -> RcDoc<'a, ()> {
match lit {
Literal::Unit => RcDoc::as_string("()"),
Literal::Bool(true) => RcDoc::as_string("true"),
Lite... | Rust | 0 |
# krotka - kolekcja niemutowalna
# pozwala efektywniej zarządzać pamięcią
# krotka jednoelementowa - stała - zmienna
# ('Radek', 'Karol', 'Tomek')
tupla = "Radek"
print(type(tupla)) # <class 'str'>
tupla_2 = ("Radek")
print(type(tupla_2)) # <class 'str'>
tupla_3 = "Radek",
print(type(tupla_3)) # <class 'tuple'>
... | Python | 1 |
prevs['am'])
duty[prev] += calc_pm(prev, prevs['pm'])
duty[prev] += calc_night(prev, prevs['late'])
duty[prev] += calc_dark(prev, prevs['yesterday'])
duty[prev] *= 2 if not only_hours else 1
pass
elif str(prev_obj.isoweekday()) in weekday:
# 普通休息日
duty[prev... | Python | 1 |
path).await?;
Ok(())
}
}
impl S3Storage {
pub fn new(
access_key: String,
secret_key: String,
endpoint: String,
bucket: String,
region: String,
cache_path: PathBuf,
) -> Result<S3Storage> {
let credentials =
s3::creds::Credentials::new(Some(&access_key), Some(&secret_key), None, None, None)
.... | Rust | 0 |
x = float(input('最高気温を入力してください : '))
if x >= 35 :
print('猛暑日')
elif x >= 30 :
print('真夏日')
elif x >= 25 :
print('夏日')
elif x <= 0 :
print('真冬日')
| Python | 1 |
de_as::<AnimationPlayer>
// (self.animation_path.to_string().as_str()).unwrap().assume_shared());
// self.sprite_animation = Some(_owner.get_node_as::<AnimatedSprite>
// (self.sprite_animation_path.to_string().as_str()).unwrap().assume_shared());
}
}
impl FlipBody for Entity {
... | Rust | 0 |
"""Shows how to use the custom model composer to build a complex custom embedding networks."""
from collections import OrderedDict
from typing import Dict, Union, Sequence, List
import torch.nn as nn
from maze.perception.blocks.feed_forward.dense import DenseBlock
from maze.perception.blocks.general.concat import Con... | Python | 1 |
from flask import Flask, request, jsonify
from pathlib import Path
from config import Config
from models import db, Student, Course, StudentCourse, func
app = Flask(__name__)
app.config.from_object(Config)
db.init_app(app)
@app.route('/', methods=['GET'])
def index():
title = Path(__file__).name
return titl... | Python | 1 |
Value, DiceError> {
n_d_reroll_drop_crop_plus(n, d, &[], plus, drop, crop)
}
/// Rolls n dices with d sides, drops drop lowest and adds plus
#[inline(always)]
pub fn n_d_drop_plus(n: usize, d: usize, plus: IntValue, drop: usize) -> Result<IntValue, DiceError> {
n_d_drop_crop_plus(n, d, plus, drop, 0)
}
/// R... | Rust | 0 |
from collections import defaultdict
import json
import random
from random import sample
sampled = [
"page2-34.svg",
"page9-46.svg",
"page3-85.svg",
"page7-107.svg",
"page8-159.svg",
"page6-203.svg",
"page2-112.svg",
"page1-116.svg",
"page1-69.svg",
"page8-234.svg",
"page8-21.svg",
"page5-75.svg... | Python | 1 |
> {
RGBf::<T> {
r: self.r.abs(),
g: self.g.abs(),
b: self.b.abs(),
}
}
pub fn cast_slice(slice: &[T]) -> &[RGBf<T>] {
if slice.len() % 3 != 0 {
panic!("invalid slice cast");
}
unsafe {
std::slice::from_raw_part... | Rust | 0 |
"""
Fly controller
==============
Fly through a cloud of cololoured points. This example demonstrates the fly
controller, as well as the GaussianBlob point material, with size_space set to
'world'.
Tip: try using different values for alpha_mode.
"""
# sphinx_gallery_pygfx_docs = 'screenshot'
# sphinx_gallery_pygfx_t... | Python | 1 |
)]
#[inline]
pub fn _from(value: u8) -> NWAITSR {
match value {
0 => NWAITSR::NWAITS_0,
1 => NWAITSR::NWAITS_1,
2 => NWAITSR::NWAITS_2,
3 => NWAITSR::NWAITS_3,
4 => NWAITSR::NWAITS_4,
5 => NWAITSR::NWAITS_5,
6 => NWAITSR... | Rust | 0 |
from __future__ import print_function
import unittest
import pytraj as pt
from utils import fn
class Test(unittest.TestCase):
def test_0(self):
pass
# load 2 frames
traj = pt.iterload(fn('Tc5b.x'), fn('Tc5b.top'), frame_slice=(0, 2))
# test mutable traj
big_frame = pt.too... | Python | 1 |
t" in line:
# include BMP header if requested
if img3d.img_include_bmp:
h_file.write(f"extern const uint8_t {OUTPUT_BMP_ARRAY_NAME}[{len(bmp_arr)}];\n")
# include 3d matrix header
h_file.write(f"extern const float {... | Python | 1 |
l encoding document:
/// https://developers.google.com/protocol-buffers/docs/encoding
use ::puroro::Message;
use ::std::borrow::Cow;
use ::std::default::Default;
use ::tests_pb::official_samples2 as s2;
use ::tests_pb::official_samples3 as s3;
const TEST1_INPUT: &[u8] = &[0x08, 0x96, 0x01];
const TEST2_INPUT: &[u8] = ... | Rust | 0 |
Looking up my IP address");
whats_my_ip(&google_dns).await?
}
};
info!("My IP address is {}", my_ip);
for domain_dynamic_item in &config.domain_dynamic_items {
info!(
"Processing domain name {}, record {}",
&config.domain_fqdn, domain_dynamic_item
... | Rust | 0 |
und longer to extend their lifetime.
* This example requires a raspberry pi.
*/
#[cfg(feature = "mio-evented")]
extern crate mio;
#[cfg(feature = "mio-evented")]
extern crate sysfs_gpio;
#[cfg(feature = "mio-evented")]
use mio::{Events, Poll, PollOpt, Ready, Token};
#[cfg(feature = "mio-evented")]
use mio::unix::Ev... | Rust | 0 |
pub fn HPDF_Page_GetLineJoin(page: HPDF_Page) -> HPDF_LineJoin;
pub fn HPDF_Page_GetMiterLimit(page: HPDF_Page) -> HPDF_REAL;
pub fn HPDF_Page_GetDash(page: HPDF_Page) -> HPDF_DashMode;
pub fn HPDF_Page_GetFlat(page: HPDF_Page) -> HPDF_REAL;
pub fn HPDF_Page_GetCharSpace(page: HPDF_Page) -> HPDF_RE... | Rust | 0 |
s3_client
.get_object(GetObjectRequest {
bucket: aws_bucket.to_string(),
key: f.to_string(),
..Default::default()
})
.await?;
// Read result from S3 and convert to bytes
let mut result_stream = result
.body
.expect("unable to read resp... | Rust | 0 |
xtCtl.Enter,
TxtCtl.Clear,
'#0080311440V那我在这里等着。\n',
'需要的时候就说一声。',
TxtCtl.Enter,
),
)
CloseMessageWindow()
Jump('loc_27B8')
def _loc_27B8(): pass
label('loc_27B8')
ChrSetSubChip(0x0010, 0)
TalkEnd(0x0010)
Return()
# id: 0x000... | Python | 1 |
from train import train, test, partial_train, test_without_print, test_with_f1
from model import *
from client import goodClient, badClient
from utils import *
def trimmed_mean():
'''初始化各客户端'''
good_clients_num = 12
bad_clients_num = 20 - good_clients_num
system_epochs = 100
local_epochs = 10
... | Python | 1 |
import numpy as np
arr1 = np.array([[1,2,3],[4,5,6]])
# convert 2d t0 1d
arr_1d = arr1.reshape(6)
print(arr_1d)
# convert 2d to 2d inter chainging row and colum
arr_2d = arr1.reshape(3,2)
print(arr_2d)
# convert 2d to 3d
arr_3d = arr1.reshape(2,1,3)
print(arr_3d)
new_3d = arr1.reshape(3,1,2)
print(new_3d) | Python | 1 |
ValidationDataLength: UINT32,
pub rgbValidationData: *mut BYTE,
}
#[test]
fn bindgen_test_layout_tdTSS_VALIDATION() {
assert_eq!(::std::mem::size_of::<tdTSS_VALIDATION>() , 48usize , concat !
( "Size of: " , stringify ! ( tdTSS_VALIDATION ) ));
assert_eq! (::std::mem::align_of::<tdTSS_VALIDAT... | Rust | 0 |
=> ScalarType::BigInt,
// Float
CockroachType::Float4 => ScalarType::Float,
CockroachType::Float8 => ScalarType::Float,
// Decimal
CockroachType::Decimal(_) => ScalarType::Decimal,
// DateTime
CockroachType::Timestamp(_) => ScalarType:... | Rust | 0 |
import torch
class Decoder(torch.nn.Module):
# TODO: support learnable fusion modules
def __init__(self):
super().__init__()
self.FUSION_DIC = {"2to1_fusion": ["sum", "diff", "abs_diff"],
"2to2_fusion": ["concat"]}
def fusion(self, x1, x2, fusion_form="concat"):... | Python | 1 |
# SPDX-License-Identifier: MIT
#
# Copyright (c) 2024 Empiria Ltd
#
# This software is published at https://github.com/empiria/anvil-dapps
import anvil
message = "This app is intended to be used as a dependency"
print(message)
anvil.alert(message)
| Python | 1 |
int(
&mut self,
_name: String,
register: Register,
at_step: usize,
value: Option<F>
) -> Result<(), TracingError>
{
let constraint = BoundaryConstraint::<F> {
register: register,
at_row: at_step,
value: value
};
... | Rust | 0 |
});
println!("{}", json);
}
fn enter(&self, span: &Id) {
let json = json!({
"enter": span.as_serde(),
});
println!("{}", json);
}
fn exit(&self, span: &Id) {
let json = json!({
"exit": span.as_serde(),
});
println... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.