text string | label_name string | labels int64 |
|---|---|---|
palette (list[list[int]]] | np.ndarray | None): The palette of
segmentation map. If None is given, random palette will be
generated. Default: None
win_name (str): The window name.
wait_time (int): Value of waitKey param.
Default: 0.
... | Python | 1 |
.format_exc())
error_message = '未知错误!'
return JsonResponse({"code": 402, "err": error_message})
else:
error_message = '请检查填写的内容!'
return JsonResponse({"code": 403, "err": error_message})
@ratelimit(key=key, rate=rate, method=ALL, block=True)
@login_required
@post_re... | Python | 1 |
::CountDown,
timer::{Event as TimerEvent, Hertz, Timer},
};
use net_types::IpcUdpTransmitBuffer;
use smoltcp::iface::{EthernetInterface, EthernetInterfaceBuilder, NeighborCache, Routes};
use smoltcp::socket::{SocketHandle, SocketSet, UdpPacketMetadata, UdpSocket, UdpSocketBuffer};
use smoltcp::time::Instant;
use sm... | Rust | 0 |
#![allow(dead_code)]
#![allow(unused_imports)]
use itertools::Itertools;
use proconio::marker::{Bytes, Chars, Usize1};
use proconio::*;
use std::cmp::*;
use std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque};
use std::io;
use std::mem::*;
#[fastout]
fn main() {
input! {
mut n:... | Rust | 0 |
Instruction::Copy(a, b) => validate_targets(&[a, b])?,
Instruction::Addi(a, b, c) => validate_targets(&[a, b, c])?,
Instruction::Subi(a, b, c) => validate_targets(&[a, b, c])?,
Instruction::Muli(a, b, c) => validate_targets(&[a, b, c])?,
Instruction::Divi(a, b, c) ... | Rust | 0 |
img_target = imgicon.image
r, pp = similar_img(imsrc, img_target, ret_mode=interaction_core.IMG_POSI)
p = [0, 0]
p[0] = pp[0] + img_target.shape[1] / 2
p[1] = pp[1] + img_target.shape[0] / 2
# p = [x + w / 2, y + h / 2]
origin_point = [int(imsrc.shape[1] / 2) + 1, int(imsrc.shape[0] / 2) + 1]
... | Python | 1 |
(208i32);
pub const GamepadLeftThumbstickButton: Self = Self(209i32);
pub const GamepadRightThumbstickButton: Self = Self(210i32);
pub const GamepadLeftThumbstickUp: Self = Self(211i32);
pub const GamepadLeftThumbstickDown: Self = Self(212i32);
pub const GamepadLeftThumbstickRight: Self = Self(213i3... | Rust | 0 |
wire_type=minipb._WIRE_TYPE_I64, data=minipb._encode_scalar_to_bytes(minipb.TYPE_DOUBLE, expected_msg.f_i64)),
dict(id=777 , wire_type=minipb._WIRE_TYPE_LEN, data=expected_msg.f_len),
dict(id=888 , wire_type=minipb._WIRE_TYPE_I32, data=minipb._encode_scalar_to_bytes(minipb.TYPE_FIXED32,... | Python | 1 |
'pip install requests'
import requests
def obtener_precio_bitcoin():
try:
response = requests.get("https://api.coindesk.com/v1/bpi/currentprice.json")
response.raise_for_status() # Lanza una excepción si la respuesta no es exitosa
data = response.json()
precio_usd = data["bpi"]["US... | Python | 1 |
ionsRemainingActiveOneSideOfTheCrossIsFullyExecutedAFieldButTheUnfilledPortionRemainsActive,
/// Cross trade is executed with existing orders with the same price. In the case other orders exist with the same price, the
/// quantity of the Cross is executed against the existing orders and quotes, the remainder of the ... | Rust | 0 |
'io_pgetevents', 'rseq', 'pidfd_send_signal', 'io_uring_setup', 'io_uring_enter', 'io_uring_register',
'open_tree', 'move_mount', 'fsopen', 'fsconfig', 'fsmount', 'fspick', 'pidfd_open', 'clone3', 'close_range',
'openat2', 'pidfd_getfd', 'faccessat2', 'process_madvise', 'epoll_pwait2', 'mount_setattr', 'quot... | Python | 1 |
e9~\xec\xbd\xf8?Nq\xe9[\x1a]\x8cZ\
.\xbb5\xc5\xac\xb1}\x9e\xf1?x\xbb\xbe\xf1\xecE\
S\xba\xf8s\xa1\xf8\xde\xd7\xe5[{\xfb}\xe2x\xfa\
7\x91 \xee\xa7\xb6k\x9c\x96Y~\x1fx\x9f\xca\xba\
\xb5\xbc\xba\xd3bP\xdeg\xde\xf2\xb3\x92~\xb84\xf9\
~\xd7P\xbcu\xe4\xd0e\xf7\xec\xb5\xe1)|[\xaa\
x\x83M\xd2\xe2\xb5\xd5\xaf\xe2\xff\x00J\x8e&\... | Python | 1 |
import os
import unittest
import numpy as np
import neural_renderer
import chainer
import scipy
class TestCore(unittest.TestCase):
def test_save_obj(self):
vertices, faces = neural_renderer.load_obj('./tests/data/teapot.obj')
neural_renderer.save_obj('./tests/data/teapot2.obj', vertices, faces)
... | Python | 1 |
"""Double pendulum in 3D"""
# Original idea and solution using sympy from:
# https://www.youtube.com/watch?v=MtG9cueB548
import time
from vedo import *
# Load the solution:
x1, y1, z1, x2, y2, z2 = np.load(download(dataurl+'3Dpen.npy'))
p1, p2 = np.c_[x1,y1,z1], np.c_[x2,y2,z2]
ball1 = Sphere(p1[0], r=0.1).color("gr... | Python | 1 |
import numpy as np
import os
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--data", type=str, default="ClinTox")
parser.add_argument("--data-path", type=str, default="../data")
args = parser.parse_args()
DIR = os.path.join(args.data_path, args.data)
def compute_shapes(path):
if path.e... | Python | 1 |
0, 0, 0, 0]);
/// Target limit under which we start increasing the size shift on Cuckoo cycle.
pub const SOFT_MIN_TARGET: Target = Target([0, 0, 0xf, 0xff, 0xff, 0xff, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,... | Rust | 0 |
t_type.title()}", count)
except Exception:
pass # Ignore errors in fetching user stats
st.sidebar.markdown("---")
if st.sidebar.button("🚪 Logout", use_container_width=True):
try:
api_client.logout_user(st.session_state.access_token)
# Cl... | Python | 1 |
DS_CANT_REMOVE_CLASS_CACHE, 8404
DS_CANT_RETRIEVE_DN, 8405
DS_MISSING_SUPREF, 8406
DS_CANT_RETRIEVE_INSTANCE, 8407
DS_CODE_INCONSISTENCY, 8408
DS_DATABASE_ERROR, 8409
DS_GOVERNSID_MISSING, 8410
DS_MISSING_EXPECTED_ATT, 8411
DS_NCNAME_MISSING_CR_REF, 8412
DS_SECURITY_CHECKING_ERROR, 8413
DS_SCHEMA_N... | Rust | 0 |
import yaml
import pickle
import io
import pytest
import numpy as np
from analysis import _dump_yaml, analyze_optimality2
@pytest.mark.parametrize(
"tex, expected",
[
(
{"key1": "value1", "key2": "value2"},
{"key1": "value1", "key2": "value2"},
), # Test string value... | Python | 1 |
self.start;
let throughput = self.count as f64 / elapsed.as_secs_f64();
info!(
"Done in {:.2?}. {} {} ({:.2} {}/s)",
elapsed,
PrettyNumber::from(self.count),
self.items,
PrettyNumber::from(throughput),
self.items
);
}
}
... | Rust | 0 |
/ 10
}
}
/// Common constants for all runtimes
pub mod constants {
use super::types::BlockNumber;
use frame_support::weights::{constants::WEIGHT_PER_SECOND, Weight};
use sp_runtime::Perbill;
/// This determines the average expected block time that we are targeting. Blocks will be
/// produced at a minimum dur... | Rust | 0 |
#!/usr/bin/env python3
# coding: utf-8
# File: cnn_sentiment.py
# Author: lhy<lhy_in_blcu@126.com,https://huangyong.github.io>
# Date: 18-3-19
import gensim
import numpy as np
from keras.models import load_model
VECTOR_DIR = './embedding/word_vector.bin' # 词向量模型文件
model = gensim.models.KeyedVectors.load_word2vec_for... | Python | 1 |
rs.clone();
let input = input.clone();
let tx = tx.clone();
thread::spawn(move || {
let mut index_n: usize;
for i in (0..n_points).filter(|point_num| point_num % num_procs == tid) {
let p: PointData = input.get_point_info(i);
... | Rust | 0 |
Sun", 10)
QApplication.setFont(font)
self.setFont(font)
# 创建主布局
main_layout = QVBoxLayout(central_widget)
main_layout.setContentsMargins(10, 10, 10, 10)
# 创建顶部控制区域
control_group = QGroupBox('控制面板')
control_group.setFont(font)
cont... | Python | 1 |
sidecars can run without failing.
// Once this is done, complex startup order will be easier to implement.
// We can also stop the broker process if sidecars fail to init.
//
// This change depends on restructuring the startup logic so that:
// 1. sidecars and server run at same time
// ... | Rust | 0 |
Int64 => write!(f, "Int64"),
ArithLattice::Float64 => write!(f, "Float64"),
ArithLattice::Union(v) => match v.is_empty() {
true => write!(f, "Union{{}}"),
false => {
let l = v.len();
for (ind, t) in v.iter().enumerate() {
... | Rust | 0 |
;
#[derive(Template)] // this will generate the code...
#[template(path = "openvpn_template.j2")]
struct OpenVpnConfig {
openvpn_protocol: ConnectionProtocol,
server_list: Vec<Ipv4Addr>,
openvpn_ports: Vec<usize>,
/// Whether to use split tunnel or not
split: bool,
ip_nm_pairs: Vec<IpNm>,
/// Use ipv6 and fallb... | Rust | 0 |
import sys
sys.stdin = open("input.txt","r")
def Triangle_of_Pascal(num):
T = int(input())
for tc in range(1,T+1):
N = int(input())
Triangle_of_Pascal(N) | Python | 1 |
import cv2
import inspireface as isf
import click
@click.command()
@click.argument('image_path1')
@click.argument('image_path2')
def case_face_comparison(image_path1, image_path2):
"""
This is a sample application for comparing two face images.
Args:
image_path1 (str): Path to the first face image... | Python | 1 |
457
]);
static ref VIB_TAB: Box<[u8; 32]> = Box::new([
0, 24, 49, 74, 97, 120, 141, 161,
180, 197, 212, 224, 235, 244, 250, 253,
255, 253, 250, 244, 235, 224, 212, 197,
180, 161, 141, 120, 97, 74, 49, 24
]);
static ref VIB_SINE_TAB: Box<[i8; 256]> = {
... | Rust | 0 |
s.len();
let mut jsonbuf = JsonBuf::new();
let mut n = 4;
let obj = Vec::new();
refs[refs_len - n] = Object(obj);
n -= 1;
let mut obj = Vec::new();
let (k, v) = ("key1".to_string(), r#""value1""#.parse().unwrap());
obj.insert(0, Property::new(k, v));
... | Rust | 0 |
reached
// from.
fn distances_and_origins(&self, start: Point) -> (Vec<Vec<usize>>, Vec<Vec<Option<usize>>>) {
let mut distances = vec![vec![std::usize::MAX; self.grid[0].len()]; self.grid.len()];
let mut origins = vec![vec![None; self.grid[0].len()]; self.grid.len()];
// queue will hol... | Rust | 0 |
wInt, loc)) => DataTypeLoc(DataType::Int, loc),
Some(Tok(TokType::KwBool, loc)) => DataTypeLoc(DataType::Bool, loc),
Some(t) => panic!("expected int or bool but {}", t),
None => panic!("unexpected EOF")
}
}
fn consume(&mut self, typ: TokType) {
match self.lex... | Rust | 0 |
);
}
}
}
pub fn unwrap_err(self) -> (GasCostSummary, SuiError) {
match self {
ExecutionStatus::Success { .. } => {
panic!("Unable to unwrap() on {:?}", self);
}
ExecutionStatus::Failure {
gas_cost: gas_used,
... | Rust | 0 |
self.mask &= *other
}
})*
};
(@IMPL_BITXOR_ASSIGN $($target: ty, $other: ty);*;) => {
$(impl $crate::__core::ops::BitXorAssign<$other> for $target {
#[inline]
fn bitxor_assign(&mut self, other: $other) {
self.mask ^= *other
... | Rust | 0 |
/// + `None` if this is a code or data segment
pub fn get_system_type(&self) -> Option<SysType> {
if self.is_system() {
Some(unsafe { mem::transmute((*self & SEGMENT_TYPE).bits) })
} else {
None
}
}
/// Returns the code type indicator.
///
/// # Retu... | Rust | 0 |
answer_pkt(scaii_pkt: &ScaiiPacket) -> bool {
let specific_msg = &scaii_pkt.specific_msg;
match specific_msg {
&Some(scaii_packet::SpecificMsg::StudyQuestionAnswer(StudyQuestionAnswer { .. })) => true,
_ => false,
}
}
pub fn is_log_file_entry_pkt(scaii_pkt: &ScaiiPacket) -> bool {
let s... | Rust | 0 |
iou,recall,acc=get_IoU_Recall_Acc(test_true,test_pred,config['num_labels'])
loss=test_loss/n_iters
outstr = 'Val %d, loss: %.3f, iou: %.3f, recall: %.3f, acc: %.3f' % (
c_epoch,loss,iou,recall,acc
)
logger.info(outstr)
logger.info('Time: %... | Python | 1 |
r(label_fld, 'vocab')
else len(getattr(splits[0][0], label_name)))
return obj
def to_model(self, m, opt_fn):
model = TextModel(to_gpu(m))
return RNN_Learner(self, model, opt_fn=opt_fn)
def get_model(self, opt_fn, max_sl, bptt, emb_sz, n_hid, n_layers, dropout, **kwargs... | Python | 1 |
dat",
),
Column(
"zemepisna_sirka",
Numeric(18, 2),
nullable=True,
comment="Zeměpisná šířka převedená ze systému souřadnic S-JTSK",
),
Column(
"zemepisna_delka",
Numeric(18, 2),
nullable=True,
... | Python | 1 |
.apply(palette.to_palette())
.transform()
.save(&self.output)?;
} else {
transformed_luma.transform().save(&self.output)?;
}
Ok(())
}
}
#[derive(Debug)]
struct Size {
width: u32,
height: u32,
}
impl FromStr for Size {
type Err = ... | Rust | 0 |
("decryption failed...cleaning up");
std::fs::remove_dir_all(&c.confdir)
.unwrap_or_else(|_| panic!("Cannot clean {}. Remove it manually..", &c.confdir));
}
return;
}
// Else, do nothing
println!("{:?} exists, remove it to re-init.", c.confdir);
}
/// Config str... | Rust | 0 |
y way to have oldkeyword inside the function is
# that it is passed as kwarg because the oldkeyword
# parameter was renamed to newkeyword.
if o_name in kwargs:
value = kwargs.pop(o_name)
# Check if the newkeyword was given as well.
... | Python | 1 |
import _plotly_utils.basevalidators
class TickformatValidator(_plotly_utils.basevalidators.StringValidator):
def __init__(
self,
plotly_name="tickformat",
parent_name="scatter3d.marker.colorbar",
**kwargs,
):
super(TickformatValidator, self).__init__(
plotly... | Python | 1 |
18-11-04 00:46] wakes up
[1518-11-05 00:03] Guard #99 begins shift
[1518-11-05 00:45] falls asleep
[1518-11-05 00:55] wakes up
"#;
#[test]
fn test_part1() {
let input = get_input(DATA.as_bytes()).unwrap();
assert_eq!(240, part1(&input));
}
#[test]
fn test_part2() {
... | Rust | 0 |
from aprsd.packets import collector
from aprsd.packets.core import ( # noqa: F401
AckPacket,
BeaconPacket,
BulletinPacket,
GPSPacket,
MessagePacket,
MicEPacket,
ObjectPacket,
Packet,
RejectPacket,
StatusPacket,
ThirdPartyPacket,
UnknownPacket,
WeatherPacket,
fact... | Python | 1 |
jused saved.
print("Start training loop.")
policy = lambda *args: agent.policy(
*args, mode="explore" if should_expl(step) else "train"
)
while step < args.steps:
# scalars = collections.defaultdict(list)
# for _ in range(args.eval_samples):
# for key, value in agent.r... | Python | 1 |
import ui
import csv
import os
import datetime
def submit_action(sender):
# Get the form data
systolic = bp_form['systolic_textfield'].text
diastolic = bp_form['diastolic_textfield'].text
timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
# Append data to a CSV file
file_path = ... | Python | 1 |
h = float(input("height(m): "))
w = float(input("weight(kg): "))
if h > 4.0:
raise ValueError("Human height should not exceed 4 meters")
elif w > 1000:
raise ValueError("Human weight should not excceed 1000 kg")
else:
bmi = w / h **2
print(f"Your bmi is {bmi}")
| Python | 1 |
}
uint32::unpack_big(misc.offset(i as (isize)), &mut u as (*mut u32));
space();
u64 = u as (usize);
u64_print();
i = i + 4i32;
}
line();
}
#[no_mangle]
pub unsafe extern "C" fn log_stats() {
string((*b"stats \0").as_ptr());
u64 = numqueries;
u64_print(... | Rust | 0 |
_, None => return Err(LoadError{}) },
x1: { if !__js["x1"].is_array() { return Err(LoadError{}); } let mut __map__ = std::collections::HashMap::new(); for __e in __js["x1"].members() { __map__.insert(match __e[0].as_i32() { Some(__x__) => __x__, None => return Err(LoadError{}) }, match __e[1].as_i32() { Som... | Rust | 0 |
import tkinter as tk
import random
from tkinter import Entry, Button, Frame, messagebox
# Глобальные переменные
current_layout = "qwerty"
word_lists = {
"qwerty": ["APPLE", "GRAPE", "MOUSE", "TABLE", "CHAIR", "PLANT", "WATER", "BREAD", "LIGHT", "STONE"],
"йцукен": ["ГРУША", "МЫШКА", "ТРАВА", "БАЛКА", "ПИТОН",... | Python | 1 |
Value on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum TXUNDERR_A {
#[doc = "0: No transmit FIFO underrun error"]
NOUNDERRUN = 0,
#[doc = "1: Transmit FIFO underrun error"]
UNDERRUN = 1,
}
impl From<TXUNDERR_A> for bool {
#[inline(always)]
fn from(variant: TXUNDERR_A) -> Self {
... | Rust | 0 |
import pyspark.sql.types as t
nullable = True
database_name = "measurements_gold"
view_name = "current_v1"
schema = t.StructType(
# Fields are nullable, but we are checking for nulls in the view, except for quantity
[
t.StructField("metering_point_id", t.StringType(), not nullable),
t.Struct... | Python | 1 |
# pip install flask
from flask import Flask
aplicacion = Flask(__name__)
@aplicacion.route("/")
def raiz():
cadena = '''
<style>
body{background:grey;}
h1{color:white;text-align:center;}
article{background:white;padding:20px;margin:auto;width:500px;}
</style>
<h1>El blog Python de Jo... | Python | 1 |
ner.save_model()
def main():
args = parse_args()
config = TrainingConfig(args)
if int(os.environ.get("LOCAL_RANK", "0")) == 0:
wandb.init(project="llama3-full-finetune")
fsdp_config = setup_fsdp()
model, tokenizer = prepare_model_and_tokenizer(config, args)
# 先包装FSDP
... | Python | 1 |
let event: &XKeyEvent = unsafe { mem::transmute(&x_event) };
if event.type_ == KEY_PRESS {
if filter_event(&x_event, self.window.window) {
continue 'event;
}
}
let state = if x_event.type_ == KEY_PRESS {
ElementState::Pressed
... | Rust | 0 |
"This module is deprecated. Import from panda3d.core and other panda3d.* modules instead."
if __debug__:
print("Warning: pandac.PandaModules is deprecated, import from panda3d.core instead")
try:
from panda3d.core import *
except ImportError as err:
if "No module named core" not in str(err):
rai... | Python | 1 |
}
}
pub(crate) fn for_signer_test(
height: Height,
requested_signatures: Vec<(RequestId, ThresholdEcdsaSigInputs)>,
) -> Self {
Self {
height,
requested_transcripts: vec![],
requested_signatures,
... | Rust | 0 |
import rclpy
from rclpy.node import Node
from nav_msgs.msg import OccupancyGrid
from std_msgs.msg import Header
class MapPublisher(Node):
def __init__(self):
super().__init__('map_publisher')
self.publisher_ = self.create_publisher(OccupancyGrid, 'map', 10)
self.timer = self.create_timer(1.... | Python | 1 |
かつ",
"ふっき",
"ふっこく",
"ぶどう",
"ふとる",
"ふとん",
"ふのう",
"ふはい",
"ふひょう",
"ふへん",
"ふまん",
"ふみん",
"ふめつ",
"ふめん",
"ふよう",
"ふりこ",
"ふりる",
"ふるい",
"ふんいき",
"ぶんがく",
"ぶんぐ",
"ふんしつ",
"ぶんせき",
"ふんそう",
"ぶんぽう",
"へいあん",
"へいおん",
"へいがい",
"へい... | Rust | 0 |
"""
Problem: Sum of Matrix Elements
Description:
-------------
This function calculates the **sum of all elements** in a 2D matrix (list of lists).
Approach:
---------
1. Traverse each row of the matrix.
2. For each row, iterate through all elements and keep adding to a running total.
3. Return the final sum.
Time C... | Python | 1 |
e - 1) // self.batch_size
success_count = 0
for i in range(0, len(files), self.batch_size):
batch = files[i:i + self.batch_size]
batch_num = (i // self.batch_size) + 1
if self.commit_files_batch(batch, group_name, batch_num, total_batches):
... | Python | 1 |
##########################################################################
#
# Copyright (c) 2007, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistribu... | Python | 1 |
hot = enc.fit_transform(np.reshape(target_distribution_pseudo_label, newshape=(-1, 1)))
target_distribution_one_hot_tensor = torch.tensor(target_distribution_one_hot)
clustering_module_optim_set = TensorDataset(raw_data_tensor, target_distribution_one_hot_tensor)
clustering_module_optim_loader =... | Python | 1 |
Departamentos_peru = {"Norte" : "Ica" , "Norte2" : "Tumbes", "Centro" : "Lima" ,"Centro2" : "Anchash", "Sur" : "Arequipa", "Sur2" : "Tacna"}
print(Departamentos_peru)
#Borramos con del
del Departamentos_peru["Norte"]
print(Departamentos_peru)
#Con esto comprobamos que Ica ya no está presente | Python | 1 |
ps.set_ground_plane_mode("shadow_only")
ps.set_ground_plane_height_factor(0.5)
ps.set_program_name("Higher Order Elasticity")
ps.init()
vm = ps.register_volume_mesh("Domain", V, C)
sm = ps.register_surface_mesh("Visual", VR, FR)
pc = ps.register_point_cloud("Dirichlet", X[:, vdbc].T)
dt ... | Python | 1 |
from random import random
def ejercicio6a():
enCirculo = 0
# Calculo el primer valor
u = 2 * random() - 1
v = 2 * random() - 1
if (u ** 2 + v ** 2 <= 1):
enCirculo += 1
# Inicializo variables del loop
n = 1
Scuad = 0
Media = (4 * enCirculo) / n
while (n < 100 or (Scuad/n... | Python | 1 |
:collections::HashMap;
use std::str;
use structopt::StructOpt;
use time;
use time::{Timespec, Tm};
#[derive(Debug)]
struct Fix {
message: String,
date: Tm,
files: Vec<String>,
}
#[derive(Debug)]
pub struct Spot {
file: String,
score: f64,
}
#[derive(StructOpt)]
pub struct Opts {
#[structopt(n... | Rust | 0 |
_) = C.iter()
.fold(
(0, E),
|(res, e), &x| {
if e >= T {
(res, e)
} else {
(res + 1, e + x)
}
... | Rust | 0 |
_i32(&self, idx: usize) -> i32 {
match idx {
0x00000000..=0x0001FFFF => {
// RAM
let contents = &self.ram;
read_slice(&contents[idx..(idx + 5)])
}
0x00020000..=0x3FFFFFFF => {
// Reserved Space
un... | Rust | 0 |
import sys
input = sys.stdin.readline
n, x = map(int, input().split())
visitor = list(map(int, input().split()))
if max(visitor) == 0:
print('SAD')
exit(0)
value = sum(visitor[:x])
answer = value
count = 1
# 슬라이딩 윈도우(이전 값을 활용하여 한칸씩 옆으로 옮겨가며 계산)
for i in range(x, n):
value += visitor[i]
value -= vis... | Python | 1 |
std::fmt::Result {
match self {
RefNode::Locate(_) => write!(f, "Locate"),
"##;
static REF_NODE_DISPLAY_FOOTER: &str = r##"
}
}
}
"##;
static ANY_NODE_DISPLAY_HEADER: &str = r##"
impl std::fmt::Display for AnyNode {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Resul... | Rust | 0 |
from panda3d.core import *
from direct.interval.IntervalGlobal import *
from otp.level import BasicEntities
class GoonClipPlane(BasicEntities.NodePathEntity):
def __init__(self, level, entId):
BasicEntities.NodePathEntity.__init__(self, level, entId)
self.zoneNum = self.getZoneEntity().getZoneNum(... | Python | 1 |
# tests/test_b7_cloudshade.py
# Tests for B7 cloud shade overlay modulation on terrain lighting.
# Ensures cloud shadow compute pass exists to justify Workstream B coverage.
# RELEVANT FILES:src/scene/mod.rs,src/core/cloud_shadows.rs,shaders/cloud_shadows.wgsl,src/shaders/terrain_descriptor_indexing.wgsl
"""B7: Valida... | Python | 1 |
rval test passed!")
# else:
# print("Session expiry interval test failed")
return True
def test_message_expiry():
pub_cmd = shlex.split("mosquitto_pub -t topic_test {} -m message -V 5 -q 1 -D publish message-expiry-interval 3 -r".format(g_url))
sub_cmd = shlex.split("mosquitto_sub -t topic_test... | Python | 1 |
IPH_CLK_SEL_R::new(((self.bits >> 25) & 0x01) != 0)
}
#[doc = "Bits 27:29 - Divider for periph_clk2_podf."]
#[inline(always)]
pub fn periph_clk2_podf(&self) -> PERIPH_CLK2_PODF_R {
PERIPH_CLK2_PODF_R::new(((self.bits >> 27) & 0x07) as u8)
}
}
impl W {
#[doc = "Bit 6 - SEMC clock source s... | Rust | 0 |
15: u32,
pub SW_PAD_CTL_PAD_GPIO_AD_B1_10: u32,
pub SW_PAD_CTL_PAD_GPIO_AD_B1_11: u32,
pub SW_PAD_CTL_PAD_GPIO_AD_B1_12: u32,
pub SW_PAD_CTL_PAD_GPIO_AD_B1_13: u32,
pub SW_PAD_CTL_PAD_GPIO_AD_B1_14: u32,
pub SW_PAD_CTL_PAD_GPIO_AD_B1_15: u32,
pub SW_PAD_CTL_PAD_GPIO_SD_B1_00: u32,
pub SW... | Rust | 0 |
файла: {output_path.stat().st_size / (1024 ** 2):.2f} MB"
)
return df
def process_all_data():
"""Обработка всех файлов"""
start_time = time()
results = {}
for file_name, file_config in CONFIG['input_files'].items():
try:
results[file_name] = process_file(file_name, file_c... | Python | 1 |
_base_ = [
'../_base_/datasets/coco_caption.py',
'../_base_/default_runtime.py',
]
# model settings
model = dict(
type='BlipCaption',
vision_encoder=dict(
type='VisionTransformer',
arch='b',
img_size=384,
patch_size=16,
out_type='raw',
),
tokenizer=dict(t... | Python | 1 |
{
packets: BinaryHeap<HeapItem>,
next_weights: [HeapWeight; NUMBER_OF_PRIORITIES],
}
impl OutgoingPacketHeap {
pub fn new() -> Self {
OutgoingPacketHeap {
packets: BinaryHeap::new(),
next_weights: Self::get_initial_heap_weights(),
}
}
pub fn push(&mut ... | Rust | 0 |
, pred_tags)
print(f'Subject包含:{subjects}')
print(f'Object包含:{objects}')
length = len(text)
for sub in subjects:
for obj in objects:
if obj != sub:
try:
#得到sub_mask:[1, seq len]
... | Python | 1 |
R R t __slots__R RF RK t common_keysR{ t none_listt dictt none_dictt mapped_keysR R R t propertyR R t setterR R R R R R R R R R R RG R R ( ( ( sm /private/var/folders/vy/31wknkcs30l6xb2fzgwnrkh80000gn/T/pip-build-VQoj4y/pip/pip/_ven... | Python | 1 |
## ###
# IP: GHIDRA
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | Python | 1 |
{
cfg.file("src/zlib/gzclose.c")
.file("src/zlib/gzlib.c")
.file("src/zlib/gzread.c")
.file("src/zlib/gzwrite.c");
}
if !target.contains("windows") {
cfg.define("STDC", None);
cfg.define("_LARGEFILE64_SOURCE", None);
cfg.define("_POSIX_SOURCE... | Rust | 0 |
import pygame
from .escapeButton import EscapeButton
from .slideButton import slider
class EscapeMenu():
def __init__(self,musicHandler) -> None:
self.restartButton = EscapeButton('./assets/Buttons/Restart.png',850,350)
self.quitButton = EscapeButton('./assets/Buttons/Menu.png',750,450)
... | Python | 1 |
# * EJERCICIO:
# * Implementa los mecanismos de introducción y recuperación de elementos propios de las
# * pilas (stacks - LIFO) y las colas (queue - FIFO) utilizando una estructura de array
# * o lista (dependiendo de las posibilidades de tu lenguaje).
# pilas
lista = [1,2,3]
print(lista)
elemento = lista.pop()... | Python | 1 |
from fastapi import FastAPI, APIRouter, Depends, status, HTTPException, responses, Response
from sqlalchemy.orm import session
from .. import schemas, models, database, oauth2
from sqlalchemy import func
router = APIRouter(
prefix="/groups",
tags=['groups']
)
group_id = 0
# API khi người dùng muốn tạo gr... | Python | 1 |
where
T: Genome<T, E> + Send + Sync + Clone,
E: Send + Sync,
{
// set a result option to none, this will panic! if the result is still none
// at the end of the function. Then get the total population fitness
let mut result = None;
let total = families.iter().fold... | Rust | 0 |
# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | Python | 1 |
//RM //0@//RM //PM)MM=
M=
dnnd++!^^A.N!^^Nt !A%++A.K
""
#q
(++A.K++AD4E4E0F,FGK77DNN++4>>"Q& NN1- NN1s4>>/B+BC I
GGTZZ((tzz3//tzz5114::" JJqM JJq3tzz?':;
I
8"::DD!!!$O #::AA$BSBSTUBVWO
... | Python | 1 |
Some(max)
}
else {
Some(self)
}
}
}
/// Trait for testing approximate equality
pub trait ApproxEq<Eps>: Sized {
/// Default epsilon for approximation.
fn approx_epsilon() -> Eps;
/// Tests approximate equality using a custom epsilon.
fn approx_eq_eps(&self, ... | Rust | 0 |
e_img = img[y:y + h, x:x + w]
embedding = get_embedding(face_img)
# Recognize the face
user_id = recognize_face(embedding)
if user_id is not None:
name = get_user_name(user_id)
confidence = "High" # You can custom... | Python | 1 |
)
};
let A: Vec<Vec<i64>> = {
let mut A = vec![];
for _ in 0..H {
let mut line: String = String::new();
std::io::stdin().read_line(&mut line).unwrap();
A.push(
line.split_whitespace()
.map(|x| x.parse().unwrap())
... | Rust | 0 |
, header):
images = batch['standard_img']
images = images.to(device, non_blocking=True)
gold_target = batch['gold'].to(device, non_blocking=True)
if use_amp:
with torch.cuda.amp.autocast():
pred_logits = model(images)
else:
pred_logits = m... | Python | 1 |
;
let mut player2_score = 0;
let mut dice = 1..;
while player1_score < 1000 && player2_score < 1000 {
let (pos, score) = if is_player1s_turn {
(&mut player1_pos, &mut player1_score)
} else {
(&mut player2_pos, &mut player2_score)
};
let roll = dice.... | Rust | 0 |
cda8a09a76f",
);
assert_obj_count(&repo, 0);
commit(object_id, &repo);
assert_staged_obj_count(&repo, 0);
assert_obj_count(&repo, 1);
let obj = repo.get_object(object_id, VersionRef::Head)?;
let obj_root = PathBuf::from(&obj.object_root);
assert_eq!(5, obj.state.len());
let de... | Rust | 0 |
kewed_int(&mut rng, 10);
let rc = RegionCoverer {
min_level,
max_level,
level_mod,
max_cells,
};
let max_area =
(4. * PI).min((3. * (max_cells as f64) + 1.) * AVG_AREAMETRIC.value(min_level));
... | Rust | 0 |
stRequest>,
path: Path<String>,
app_state: Data<AsyncAppState<H>>,
) -> impl Responder {
handle_response(
get_response_for_post_request(
app_state.get_ref().htsget.clone(),
request.into_inner(),
path.into_inner(),
Endpoint::Variants,
)
.await,
)
}
use crate::error::Error;
use... | Rust | 0 |
t.unwrap();
continue;
}
let tile = t.unwrap();
if tile == 3 {
paddle = Some(pos);
} else if tile == 4 {
let (_, x_ball) = pos;
let dx_pad_to_ball = match paddle {
Some((_, x_paddle)) => (x_ball - x_paddle).signum(),
... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.