text string | label_name string | labels int64 |
|---|---|---|
#NOTE: Debug - NJ - visulize pcs for each frame
all_pts_debug = []
all_clr_debug = []
all_pts_debug.append(pts)
all_clr_debug.append(clr)
pcd = o3d.geometry.PointCloud()
all_pts_debug = np.concatenate(all_pts_debug, axis=0)
all... | Python | 1 |
member_no: u8,
}
// デバイスの状態(e.g., 割当状況)
//
// NOTE: デバイス群は、木を形成している、ということが前提
// FIXME: これを満たすためのバリデーションを別の箇所に入れる
struct DeviceState<'a> {
weight: u64,
// 割当済みのスロット数
allocated: usize,
// 割当スロット数の期待値。あくまでも参考値なので、allocated <= capacity は必ずしも成立するとは限らない。
// FIXME: `capacity`という用語は不適切なので変更する
capacit... | Rust | 0 |
().unwrap_err(),
TestError {
span: span(4..5),
kind: ast::ErrorKind::EscapeHexInvalidDigit,
});
assert_eq!(
parser(r"\uFFFG").parse_escape().unwrap_err(),
TestError {
span: span(5..6),
kind: ast::Erro... | Rust | 0 |
os_RMSD_respostas_clientes_proposta_'+str(n)+'t_distribuicao_'+str(tipo_distribuicao)+'t_validade_'+str(tempo_validade_c)+'prob_falha'+str(prob_falha_links)+'_teste_1.txt','w')
f.write(str(planilha_final_Media_RMSD))
f.close()
f = open('Resultados_cache_hits_proposta_'+str(n)+'t_distribuicao_'+str(tipo_distribuicao)+'t... | Python | 1 |
Handler<PropertiesPanelMessage, PropertiesPanelMessageHandlerData<'a>> for PropertiesPanelMessageHandler {
#[remain::check]
fn process_action(&mut self, message: PropertiesPanelMessage, data: PropertiesPanelMessageHandlerData, responses: &mut VecDeque<Message>) {
let PropertiesPanelMessageHandlerData { artwork_docu... | Rust | 0 |
ly(&self, av: &Vector1<N>) -> Vector1<N> {
*self * *av
}
#[inline]
fn to_world_space(&self, _: &Isometry2<N>) -> Matrix1<N> {
*self
}
#[inline]
fn to_relative_wrt_point(&self, mass: N, pt: &Point2<N>) -> Matrix1<N> {
*self + Matrix1::new(mass * pt.coords.norm_squared())... | Rust | 0 |
"""
execution/oms_health_exporter.py
OMS health metrics from Postgres.
Metrics:
- oms_reject_rate_24h
- oms_time_to_fill_seconds_bucket/_count/_sum (Prometheus histogram)
- oms_broker_error_total{code}
Assumptions:
- orders(client_order_id, created_at timestamptz, status, reason text)
- fills(client_order_id, ts time... | Python | 1 |
"""Helper functions for the ledger module."""
from typing import Any, Dict
def calculate_fee_dynamically(fee_data_set: Dict[str, Any]) -> str:
"""Calculate the transaction fee dynamically
based on the size of the queue of the node.
Args:
fee_data_set (Dict[str, Any]): The result of the `fee` met... | Python | 1 |
return Ok(BufReader::new(file));
}
<reponame>dlalic/resume
use serde::Deserialize;
use std::path::PathBuf;
#[derive(Debug, Deserialize)]
pub struct LayoutConfig {
pub(crate) font: String,
pub(crate) font_location: String,
pub(crate) font_size: String,
}
impl Default for LayoutConfig {
fn default() -> ... | Rust | 0 |
testjobs', TestJobViewSet)
router.register(r'testruns', TestRunViewSet).register(
r'status',
StatusViewSet,
parents_query_lookups=['test_run_id'],
**drf_basename('testrun-status')
)
router.register(r'tests', TestViewSet)
router.register(r'metrics', MetricViewSet)
router.register(r'suites', SuiteViewSet)... | Python | 1 |
util_read_colorspec(spe, args, true) {
pdf_doc_set_bgcolor(Some(&colorspec));
Ok(())
} else {
ERR
}
}
pub(crate) fn spc_color_check_special(mut buf: &[u8]) -> bool {
buf.skip_blank();
if let Some(q) = buf.parse_c_ident() {
q == "color" || q == "background"
} else {
... | Rust | 0 |
Rocket_new");
// If the constructor does not have the same signature as declared in the UDL, then
// this attempt to call it will fail with a (somewhat) helpful compiler error.
UNIFFI_HANDLE_MAP_ROCKET.insert_with_output(err, || {
Rocket::new(<String as uniffi::ViaFfi>::try_lift(name).unwrap())
... | Rust | 0 |
import json
import os
# similar to AgentRewardBench, we use precision and NPV to evaluate the performance of the judge model
TP, TN, FP, FN = 0, 0, 0, 0
all_episodes = json.load(open("evaluation_examples/test_all.json", "r"))
mid_pth = '72b_multi_env=8_xxx' # mid_pth of trajectory.
for software in all_episodes.keys()... | Python | 1 |
# Copyright (C) 2018-2023 The NeoVintageous Team (NeoVintageous).
#
# This file is part of NeoVintageous.
#
# NeoVintageous is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
#... | Python | 1 |
ptrx4([
pointer.offset(0) as *const f32,
pointer.offset(2),
pointer.offset(4),
pointer.offset(6)
]);
let r_strided = simd_gather(default, pointers, mask);
assert_eq!(r_strided, s_strided);
}
// writing to *mut
unsafe {
let po... | Rust | 0 |
"""
Simple example demonstrating PPO trading system usage.
"""
from train import PPOTrainer
from inference import load_and_test_model, PPOInference
from rich import print
def quick_training_example():
"""Quick training example with minimal episodes"""
print("[bold blue]PPO Trading System - Quick Training... | Python | 1 |
"""Test TUEV bipolar channel derivation."""
import numpy as np
from datasets.tuev_dataset import TCP_BIPOLAR_PAIRS, compute_bipolar_derivation
def test_bipolar_derivation():
"""Test that bipolar derivation computes correct differences."""
# Create mock referential data
n_samples = 1000
ch_names = [
... | Python | 1 |
fyList(Vec<RAB_ModifyList_Entry>);
#[derive(Debug, AperCodec)]
#[asn(type = "SEQUENCE", extensible = true, optional_fields = 1)]
pub struct RAB_ModifyRequest {
pub protocol_i_es: RAB_ModifyRequestProtocolIEs,
#[asn(optional_idx = 0)]
pub protocol_extensions: Option<RAB_ModifyRequestProtocolExtensions>,
}
... | Rust | 0 |
oc;
let mut M: pdf_tmatrix = pdf_tmatrix {
a: 0.,
b: 0.,
c: 0.,
d: 0.,
e: 0.,
f: 0.,
};
M.a = scale;
M.b = 0.0f64;
M.c = 0.0f64;
M.d = scale;
M.e = x_origin;
M.f = y_origin;
/* pdf_doc_new_page() allocates page content stream. */
pd... | Rust | 0 |
HRESULT,
fn SendForceFeedbackCommand(
dwFlags: DWORD,
) -> HRESULT,
fn EnumCreatedEffectObjects(
lpCallback: LPDIENUMCREATEDEFFECTOBJECTSCALLBACK,
pvRef: LPVOID,
fl: DWORD,
) -> HRESULT,
fn Escape(
pesc: LPDIEFFESCAPE,
) -> HRESULT,
fn Poll() -> HRESUL... | Rust | 0 |
uilder<'a> {
Self::new()
}
}
impl<'a> std::fmt::Debug for ImportSemaphoreZirconHandleInfoFUCHSIABuilder<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
std::fmt::Debug::fmt(&self.0, f)
}
}
impl<'a> std::ops::Deref for ImportSemaphoreZirconHandleInfoFUCHSIABuilder<'a> {... | Rust | 0 |
positional_embedding
x = x.permute(1, 0, 2) # NLD -> LND
x = self.text_transformer_forward(x, attn_mask=self.model.attn_mask)
x = x.permute(1, 0, 2) # LND -> NLD
x = self.model.ln_final(x)
return x
def text_transformer_forward(self, x: torch.Tensor, attn_mask=None):
... | Python | 1 |
,
))
.expect("clone")
});
let def_output_1 =
self.outputs[1].definition_fragments(&graph.chain_customizer().streams_module_name);
let output_record_1 = def_output_1.record();
let output_unpacked_record_1 = def_output_1.unpa... | Rust | 0 |
Downloaded = os.listdir(os.path.join(src_cat_path,imoDir))
for eachFile in filesDownloaded:
if ".json" in eachFile:
src_json_path = os.path.join(src_cat_path,imoDir,eachFile)
json_file = open(src_json_path)
vessel_data = json.load(json_file)
... | Python | 1 |
, _, _, _) => loc,
&Node::Rescue(ref loc, _, _, _) => loc,
&Node::Restarg(ref loc, _) => loc,
&Node::Retry(ref loc) => loc,
&Node::Return(ref loc, _) => loc,
&Node::SClass(ref loc, _, _) => loc,
&Node::Self_(ref loc) => loc,
&Node::Send... | Rust | 0 |
&& api.get(rdx, rdy).species != Species::Fungus
{
let i = (js_sys::Math::random() * js_sys::Math::random() * 100.) as i32;
let dec = 15 - api.rand_int(20);
if (i + ra as i32) > 165 {
api.set(
mdx,
mdy,
... | Rust | 0 |
count - number of |pages|, may be 0."]
#[doc = " image_object - handle to an image object."]
#[doc = " file_access - file access handler which specifies the JPEG image file."]
#[doc = ""]
#[doc = " Returns TRUE on success."]
#[doc = ""]
#[doc = " The image object might already hav... | Rust | 0 |
ED {arg}";
pub const TEST5: &str = "TEST5 CUSTOM ORDER {1} {0}";
pub const TEST6: &str = r#"
TEST6 MIXED
DEF {}
CUST ORD {2} {1}
NAMED {arg}
"#;
fmt_reuse! {
TEST1 = "TEST1 {}";
TEST2 = "TEST2 {} {}";
TEST3 = r#"
TEST3
RAW STRING
{} {}
"#;
TEST4 = "TEST4 NAMED {arg}";
TEST5 = "TEST5 CUSTOM ORDER {1... | Rust | 0 |
maelstrom-bam-collect-pesr")
.version(git_version!())
.author("<NAME> <<EMAIL>>")
.about("Collect paired end and split read evidence from BAM")
.args(&[
Arg::from_usage("-v... 'Increase verbosity'"),
Arg::from_usage("--overwrite 'Allow overwriting of output file'"... | Rust | 0 |
8 {
header
.chars()
.last()
.unwrap()
.to_digit(10)
.unwrap()
.try_into()
.unwrap()
}
#[cfg(test)]
mod tests {
use super::*;
const SAMPLE_DATA: &'static str = "
blah blah
## Some random header
## Tier 1 with Host Tools
target | notes
-------|-----... | Rust | 0 |
.d))]
pub unsafe fn __msa_srl_d(a: v2i64, b: v2i64) -> v2i64 {
msa_srl_d(a, mem::transmute(b))
}
/// Immediate Shift Right Logical
///
/// The elements in vector `a` (sixteen signed 8-bit integer numbers)
/// are shifted right logical by `imm4` bits.
/// The result is written to vector (sixteen signed 8-bit intege... | Rust | 0 |
[`parse_context`]: a [`Context`] (`top-level-context`)
//! - [`parse_rulecontext`]: a [`RuleContext`] (`rulecontext`)
//!
//! ```text
//! program = *wsp *( *comment statement ";" *comment ) *wsp
//!
//! statement = rule / top-level-term
//!
//! rule = top-level-term *wsp "=" *wsp top-level-term
//! rule /= rule *wsp "... | Rust | 0 |
character: char) -> Result<Self, Self::Error> {
if !(0x3131..=0x314E).contains(&(character as u32)) {
return Err(Error::NonJamo(character));
}
Ok(Self::try_from((character as u32 - 0x3131) as u8).unwrap())
}
}
/// Groups all the consonants (including clustered consonants) appli... | Rust | 0 |
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib.animation import FuncAnimation
def getA(R,G,M,N):
A = np.zeros((N,2))
F = np.zeros((N,2))
for i in range(N):
for j in range(N):
if i != j: #needed to make sure we do not calculat... | Python | 1 |
lf.flip_up),
reward,
self.terminated)
if __name__ == '__main__':
player = BlackJack.Player()
print(player)
player.receive(13)
print(player)
player.receive(1)
print(player)
player.receive(2)
print(player)
player.receive(10)
print(player)
# pla... | Python | 1 |
n
buffer.push(0xA1);
buffer.push(0x00);
} else if self.len() < 16 {
// tiny atom len
buffer.push((self.len() | 0xA0) as u8);
} else if self.len() < 2048 {
// medium atom len
buffer.push(0xD0 | ((self.len() >> 8) & 0x07) as u8);
... | Rust | 0 |
torch, "get_autocast_gpu_dtype"
):
Logger(f"Autocast dtype: {torch.get_autocast_gpu_dtype()}")
elif dev_type == "cpu" and hasattr(
torch, "get_autocast_cpu_dtype"
):
... | Python | 1 |
tion approximates
if method == 1:
unshifted_exact = ((exact - 0.5)*c_star) + 0.5
elif method == 2:
unshifted_exact = exact
phi = np.arcsin(np.sqrt(unshifted_exact))/np.pi
dist = {}
precision = int(num_counting_qubits / (np.log2(10))) + 2
for b in range(2**num_counting_qubits):
... | Python | 1 |
r_name=None):
"""Find one attack surface.
Call with no parameters to find your Attack Surface.
Pass a number to load a specific Attack Surface by ID, or pass a string to load the entire
list of Attack Surfaces and search them by case-insensitive substring.
Raises `AnalyzerError` if no ... | Python | 1 |
, -0.1332047592);
};
if temp <= 66.0 {
green = 0.3900815787690196 * f32::log(temp, f32::consts::E) - 0.6318414437886275;
} else {
green = 1.129890860895294 * f32::powf(temp60, -0.0755148492);
};
if temp >= 66.0 {
blue = 1.0;
} else {
if temp <= 19.0 {
blue = 0.0;
} else {
blue = ... | Rust | 0 |
able<ISystemProperties> for SystemProperties {}
impl SystemProperties {
#[inline] pub fn get_author() -> Result<HString> {
<Self as RtActivatable<ISystemProperties>>::get_activation_factory().get_author()
}
#[inline] pub fn get_comment() -> Result<HString> {
<Self as RtActivatable<ISystemPro... | Rust | 0 |
e(accs, h5py.Dataset), "Expected 'accelerations' to be a dataset"
# Drop first column which is time
accs = accs[:, 1:]
# Get the time series from the group
time_series = group['time_series']
assert isinstance(time_series, h5py.Dataset), "Expected 'time_series' to be a da... | Python | 1 |
debug2_print!("finalize done nel {} n {}\n ::::\n", nel, n);
#[cfg(feature = "debug3")]
for pme in pe[me as usize]..=pe[me as usize] + len[me as usize] as isize - 1 {
debug3_print!(" {}", iw[pme as usize]);
}
debug3_println!();
}
// Done selecting pivots.
... | Rust | 0 |
s."""
# size = (B, L - S)
values_clipped = torch.clamp(
values,
old_values - self.clip_range_value,
old_values + self.clip_range_value,
)
vf_loss1 = torch.square(values - returns)
vf_loss2 = torch.square(values_clipped - returns)
return... | Python | 1 |
r cfg.from_number)
url = (voice_url or cfg.voice_url).rstrip("/")
def _do():
return c.calls.create(
to=to,
from_=frm,
url=url,
method="POST", # required for <Gather> to POST back
)
call = _retry(_do)
return call.sid, getattr(call, "statu... | Python | 1 |
nize=True)
register_template(
TemplateType.internlm_xcomposer2_4khd,
InternLMXComposer2_5Template(version='v2-4khd'),
use_model=True,
lazy_tokenize=True)
class InternvlTemplate(Template):
system = 'You are an AI assistant whose name is InternLM (书生·浦语).'
num_image_token = 256
def __init_... | Python | 1 |
self.job_handler.write().unwrap().add_job(
&UpdateSystem::id(),
job_name.as_str(),
move || {
let mesh_id = *mesh_handle.id();
sabi_profiler::scoped_profile!(format!(
... | Rust | 0 |
fields,
file_descriptor_proto()
)
})
}
fn default_instance() -> &'static QueryUnbondingDelegationRequest {
static instance: ::protobuf::rt::LazyV2<QueryUnbondingDelegationRequest> = ::protobuf::rt::LazyV2::INIT;
instance.get(QueryUnbondingDelegationReq... | Rust | 0 |
ks/src/ports/mod.rs
pub(crate) mod http;
pub(crate) mod persistence;
pub(crate) mod search;
<filename>soundfont-rs/src/data/hydra/generator.rs
use super::super::utils::Reader;
use crate::error::ParseError;
use riff::Chunk;
use std::convert::{TryFrom, TryInto};
use std::io::{Read, Seek};
#[derive(Debug, Clone)]
pub enu... | Rust | 0 |
}));
/// ```
pub struct Apply<A, B>
where
A: 'static,
B: 'static,
{
f: Box<dyn FnMut(&A) -> B + Send + 'static>,
}
impl<A, B> Apply<A, B>
where
A: 'static,
B: 'static,
{
pub fn new(f: impl FnMut(&A) -> B + Send + 'static) -> Block {
Block::new_sync(
BlockMetaBuilder::new("Ap... | Rust | 0 |
# 1- از کاربر ورودی میگیریم. (یک جمله)
# 2- جمله را به کلمات تکی تبدیل میکنیم.
# 3- کلمات را تک تک بررسی می کنیم.
# 4- اگر کلمه بد بود آن را حذف میکنیم.
# 5- اما اگر حرف بدی داشت، کلمه را به خوب تبدیل میکنیم
# 6- کلمات باقی مانده را در خروجی نمایش می دهیم.
import string
def is_good(word):
good_characters=0
bad_... | Python | 1 |
from dotenv import load_dotenv
import os
from langchain_community.llms import HuggingFaceEndpoint
from langchain.text_splitter import CharacterTextSplitter
from langchain.vectorstores import Chroma
from langchain.chains import RetrievalQA
from langchain_community.embeddings import HuggingFaceHubEmbeddings
import stream... | Python | 1 |
56740f876aef8c010b86a40d5f56745a118d0906a34e69aec8c0db1cb8fa3").into()
);
assert_eq!(
genesis_header_hash(&crate::res::chainspec::ROPSTEN),
hex!("41941023680923e0fe4d74a34bdac8141f2540e3ae90623718e47d66d1ca4a2d").into()
);
// TODO: fix rinkeby.ron so that the gene... | Rust | 0 |
s = None
if ref_code:
action_code_indices = Variable(torch.LongTensor(
ref_code.raw_index(
packed_action_events.orig_batch_indices(),
packed_action_events.ps.data.data[:, 0].numpy())))
packed_cond_events = lists_to_packed_s... | Python | 1 |
with open('txt/26_16335.txt') as file:
N = file.readline()
diametrs = [int(i) for i in file]
diametrs = sorted(diametrs, reverse=True)
arr = [diametrs[0]]
for i in range(len(diametrs)):
if arr[-1] - diametrs[i] >= 4:
arr.append(diametrs[i])
print(len(arr), min(arr))
| Python | 1 |
import math
class Point:
pass
p1 = Point()
p2 = Point()
p1.x = 5
p1.y = 4
p2.x = 3
p2.y = 6
print(p1.x, p1.y)
print(p2.x, p2.y, '\n')
class Point:
def reset(self):
self.x = 0
self.y = 0
p = Point()
p.reset()
print(p.x, p.y, '\n')
class Point:
def reset():
pass
try:
p ... | Python | 1 |
bResult<()> {
option.apply()
}
static mut FDB_NETWORK_THREAD: Option<JoinHandle<FdbResult<()>>> = None;
// `FDB_NETWORK_STARTED` is set to `true` in `main` thread, and
// `FDB_NETWORK_STOPPED` is set to `true`, in `fdb-network-thread`.
static mut FDB_NETWORK_STARTED: bool = false;
static mut FDB_NETWORK_STOPPED: ... | Rust | 0 |
Df ( d dl mZmZmZ dad Zd Zy) )absolute_importprint_functionunicode_literals c t S Nmybuffer jC:\Users\a\AppData\Local\Programs\Python\Python312\Lib\site-packages\pyreadline3\clipboard\no_clipboard.pyGetClipboardTextr s... | Python | 1 |
from sqlmodel import select
from sqlmodel.ext.asyncio.session import AsyncSession
from e_store.cart.models.cart import Cart, CartItem, CartPublic, CartPublicWithItems
from e_store.products.models.products import Product
from e_store.shared.exceptions.http_400s import not_found_404_excep
from e_store.users.models.user ... | Python | 1 |
"""Delete Resources"""
import json
from typing import cast
from langchain_core.runnables import RunnableConfig
from langchain_core.messages import ToolMessage, AIMessage
from research_canvas.langgraph.state import AgentState
async def delete_node(state: AgentState, config: RunnableConfig): # pylint: disable=unused-ar... | Python | 1 |
re_size
# initializer
self.init_std = init_std
self.init_xavier_std = init_xavier_std
# Hungarian matcher && loss
self.cross_entropy_weight = cross_entropy_weight
self.dice_weight = dice_weight
self.mask_weight = mask_weight
self.use_auxiliary_loss = use_a... | Python | 1 |
# Import necessary libraries
import cv2
# Load the image
img = cv2.imread("image.jpg")
# Convert the image to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Apply Gaussian blur to the image
blur = cv2.GaussianBlur(gray, (5, 5), 0)
# Apply adaptive thresholding to the image
thresh = cv2.adaptiveThreshold(b... | Python | 1 |
2)));
}
}
target
}
}
/// Calculates the number of eras and reward
///
/// # Panics
///
/// This function will panic if `era_rounds` is less than `2`
fn ecip1017_eras_block_reward(era_rounds: u64, mut reward: U256, block_number: u64) -> (u64, U256) {
// NOTE(niklasad1): all numbers is divisible by 1, it will ... | Rust | 0 |
else:
mui.Typography(t("No general logs available."))
except Exception as e:
print(e)
with mui.Card(
key=self._key,
sx={"display": "flex", "flexDirection": "column", "borderRadius": 2, "over... | Python | 1 |
valid_results.append(None) # Failed extraction
return valid_results
async def _adaptive_batch_delay(self, success_rate: float, properties: List[EnhancedSpitogatosProperty]):
"""Adaptive delay between batches based on performance and detection risk"""
base_dela... | Python | 1 |
"""
@brief test tree node (time=7s)
"""
from typing import Any
import unittest
import numpy as np
from pyquickhelper.pycode import ExtTestCase, ignore_warnings
from sklearn.compose import TransformedTargetRegressor
from sklearn.linear_model import LinearRegression
from mlprodict.onnx_conv import to_onnx
from mlpro... | Python | 1 |
"C" fn()>(notify_fg_color_trampoline::<Self, F> as *const ())), Box_::into_raw(f))
}
}
fn connect_property_height_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
unsafe extern "C" fn notify_height_trampoline<P, F: Fn(&P) + 'static>(this: *mut ffi::WebKitDOMHTMLDocument, _param... | Rust | 0 |
],
}),
Fp(blst_fp {
l: [0x0, 0x0, 0x0, 0x0, 0x0, 0x0],
}),
),
// Fp2(u + 1)**(((2q^3) - 2) / 3)
Fp2::new(
Fp(blst_fp {
l: [
0x43f5fffffffcaaae,
0x32b7fff2ed47fffd,
0x7e83a49a2e99d69,
... | Rust | 0 |
ze(multi_column_no_multiindex),
df_serializer.can_convert_to_records_without_objects(multi_column_no_multiindex, 'symA')),
'large_multi_column': (large_multi_column, df_serializer.serialize(large_multi_column),
df_serializer.can_convert_to_records_without_o... | Python | 1 |
None => vec![self.component_name().to_string()],
},
msg,
}
}
}
#[cfg(test)]
mod test {
use super::*;
use crate::{BuilderArgs, LogsDataBuilder};
use fuchsia_syslog::levels::{DEBUG, ERROR, INFO, TRACE, WARN};
use std::convert::TryFrom;
const TEST_U... | Rust | 0 |
e::create(&output_file_path)
}<filename>day10/src/part_two.rs
// part_two.rs
// NOTE:
//
// This challeger can be resolf using the
//
// `combinatorics(n, r) + 1`
//
// n: number of 1-jolt consecutive elements >= 2
// r: set size
//
// Example:
//
// (0), 1, 4, 5, 6, 7, 10, 11, 12, 15, 16, 19, (22)
//
// Calculate the... | Rust | 0 |
se(sq).await,
Ok(2)
);
assert_eq!(
async { Ok(2) }.async_or_else(err).async_or_else(sq).await,
Ok(2)
);
assert_eq!(
async { Err(3) }.async_or_else(sq).async_or_else(err).await,
Ok(9)
);
assert_eq!(
as... | Rust | 0 |
s_round(elem_format, encodes_infs, round,
saturate_normals, allow_denorm,
device, custom_cuda):
# generate inputs with 2 additional mbits, so rounding for 0.25, 0.5, 0.75
ebits, mbits, _, _, _ = _get_format_params(elem_format)
if ebits == 0:
m... | Python | 1 |
ult),
)) {
Ok(()) => {
let result = result.assume_init();
let current =
if result.rlim_cur == linux_raw_sys::v5_4::general::RLIM64_INFINITY as _ {
None
} else {
Some(result.rlim_cu... | Rust | 0 |
#!/usr/bin/env python3
"""
Git分支管理工具
帮助管理TradingAgents-CN项目的分支
"""
import subprocess
import sys
from typing import List, Dict
import argparse
class BranchManager:
def __init__(self):
self.current_branch = self.get_current_branch()
def run_git_command(self, command: List[str]) -> tuple:
... | Python | 1 |
"""Set Logger
The implementation is based on https://github.com/serend1p1ty/core-pytorch-utils/blob/main/cpu/logger.py
"""
import logging
import os
import sys
from typing import Optional
__all__ = [
"set_logger",
]
logger_initialized = {}
def set_logger(
name: Optional[str] = None,
output_dir: Optional... | Python | 1 |
nts: jbyteArray,
instance_id: jshort,
method_id: jshort,
) -> jbyteArray {
use utils::convert_hash;
let res = panic::catch_unwind(|| {
let node = cast_handle::<Node>(node_handle);
let hash = unwrap_jni_verbose(
&env,
|| -> JniResult<jbyteArray> {
l... | Rust | 0 |
teger because its too large to fit in memory
IntTooLarge,
/// A lexer error occurred. This might happen if the literal is malformed (e.g. 0b01012)
LexerError,
/// Encountered an unknown suffix
InvalidIntSuffix(SmolStr),
/// Encountered an unknown suffix
InvalidFloatSuffix(SmolStr),
/... | Rust | 0 |
#/**
# * @author Dream lab software technologies muhtarjaan mahmood (مۇختەرجان مەخمۇت)
# * @email ug-project@outlook.com
# * @create date 2025-05-04 22:29:51
# * @modify date 2025-05-04 22:29:51
# * @desc [description]
#*/
uyghur_symbols = {
"ھەرىپلەر": [
'ا', 'ە', 'ب', 'پ', 'ت', 'ج', 'چ', 'خ', 'د', 'ر', 'ز', 'ژ... | Python | 1 |
(mut input_dev, mut output_dev) = (CLI_DEV_INVALID, CLI_DEV_INVALID);
if let Ok(dev) = get_device_by_name(pa, DEFAULT_INPUT_DEV) {
input_dev = dev;
} else {
log::error!("could not find device \"{}\"", DEFAULT_INPUT_DEV);
}
if let Ok(dev) = get_device_by_name(pa, DEFAULT_OUTPUT_DEV) {
... | Rust | 0 |
from_i128(den).unwrap()
))
}
pub fn from_i128(num: i128) -> Number {
Self::from_i128s(num, 1)
}
pub fn from_i64s(num: i64, den: i64) -> Number {
Self::from_i128s(num as i128, den as i128)
}
pub fn from_i64(num: i64) -> Number {
Self::from_i64s(num, 1)
}
... | Rust | 0 |
ass BaseMainnetTesterChain(Chain):
vm_configuration = _generate_vm_configuration() # type: Tuple[Tuple[int, Type[BaseVM]], ...]
class MainnetTesterChain(BaseMainnetTesterChain): # type: ignore
"""
This class is intended to be used for in-memory test chains. It
explicitely bypasses the proof of wor... | Python | 1 |
arvis_user_input} {user_input}'| tee /dev/tty "
def toggle_piper_http_server_command():
"""
Function to toggle the Piper HTTP server command.
This function toggles the global variable PIPER_HTTP_SERVER, and depending on its value, either kills the Piper or starts the Piper TTS service.
"""
global ... | Python | 1 |
from ActionHelper import *
# 小丑肯帕雷拉
def main():
CreateBattleAction("as90020.dat", ((128, 176), (128, 176), (128, 176), (128, 176), (128, 176), (128, 176), (128, 176), (128, 176)))
AddPreloadChip((
"chr/ch03650.itc", # 00 0
"chr/ch03651.itc", # 01 1
"chr/ch03653.itc", ... | Python | 1 |
# -*- coding:utf-8 -*-
# author: Xinge
# @file: model_builder.py
from network.cylinder_spconv_3d_unlock import get_model_class
from network.segmentator_3d_asymm_spconv_unlock import Asymm_3d_spconv
from network.cylinder_fea_generator import cylinder_fea
def build(model_config):
output_shape = model_config['outp... | Python | 1 |
{'Passed' if check['passed'] else 'Failed'}")
if check["output"]:
for part in check["output"].split("\n"):
if len(part) == 0:
continue
p(f" {part}")
h3("Other checks")... | Python | 1 |
files)
}
pub fn transform(&self, errors: Errors) -> Errors {
self.offsets_map.transform(errors)
}
}
impl<'a> Interact for BuilderPreprocessor<'a> {
fn preprocess<'b>(&mut self, name: &'static str, source: Cow<'b, str>) -> Cow<'b, str> {
let source = attr_dialect(&self.dialect.name().to... | Rust | 0 |
import pandas as pd
def assert_df_equal(df1, df2):
print("-" * 100)
print("df1")
print(df1)
print("df2")
print(df2)
# df1.loc[:, "Start"] = df1.Start.astype(np.int64)
# df2.loc[:, "Start"] = df1.Start.astype(np.int64)
# df1.loc[:, "End"] = df1.End.astype(np.int64)
# df2.loc[:, "En... | Python | 1 |
ting_setting == "false":
enable_rate_limiting = False
logger.info("Rate limiting is disabled.")
else:
logger.error("ENABLE_RATE_LIMITING environment variable can only get values 'true' or 'false'. Exiting.")
sys.exit(1)
logger.info(f"Pre-loading page list for mediawiki: {mediawi... | Python | 1 |
:UnsafeCell::new(None));
#[doc(hidden)]
pub fn glFramebufferTextureLayer_is_loaded() -> bool {
unsafe { *glFramebufferTextureLayer_p.0.get() }.is_some()
}
#[doc(hidden)]
pub unsafe fn glFramebufferTextureLayer_load_with(f: &dyn Fn(*const u8) -> *const c_void) {
*glFramebufferTextureLayer_p.0.get() = core::mem::tran... | Rust | 0 |
if PYDANTIC_MAJOR_VERSION == 2:
from pydantic import BaseModel as BaseModelV2
from pydantic.fields import FieldInfo as FieldInfoV2
from pydantic.v1 import BaseModel as BaseModelV1
@overload
def get_fields(model: Type[BaseModelV2]) -> Dict[str, FieldInfoV2]: ...
@overload
def get_fields(m... | Python | 1 |
import json
import os
import numpy as np
from numpy.typing import *
import cv2
from seghist.utils import ImageToolkits
def main(data_root = './data/historical_document/IACC2022_CHDAC/official_dataset/preliminary/train/',
ann_file = 'label_train.json'):
data_root = './data/historical_document/IACC2022_CH... | Python | 1 |
from bpy.types import Context, UILayout
from ..node import node_type
from ..node import LogicNodeParameterType
from ...sockets import NodeSocketLogicObject
from ...sockets.integersocket import NodeSocketLogicInteger
from ...enum_types import _collision_bitmask_types
from bpy.props import EnumProperty
@node_type
clas... | Python | 1 |
rue)
for dt in dataset_oqmd:
for st in dt["data"]:
poscar, filename = get_poscar_from_optimade_structure(deepcopy(st))
target_value = deepcopy(st["attributes"]["_oqmd_band_gap"])
properties.append(",".join([filename, str(target_value)]))
with open(os.path.join... | Python | 1 |
redicate,
(MultiPoint, LineString): NotImplementedPredicate,
(MultiPoint, Polygon): NotImplementedPredicate,
(LineString, Point): LineStringPointIntersects,
(LineString, MultiPoint): LineStringPointIntersects,
(LineString, LineString): IntersectsPredicateBase,
(LineString, Polygon): LineStringPo... | Python | 1 |
import pyxel
from .settings import EDITOR_IMAGE
from .widgets import Widget
from .widgets.settings import BUTTON_ENABLED_COLOR, BUTTON_PRESSED_COLOR
class SoundSelector(Widget):
"""
Variables:
is_playing_var
help_message_var
"""
def __init__(self, parent):
super().__init__(pa... | Python | 1 |
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 30);
self.w.bits |= ((value as u3... | Rust | 0 |
nf.index = IndexFilter::Range(from, to);
debug!("setting index filter to {:?}", nf.index);
} else {
debug!("not setting filter ({:?}, {:?})", index_from, index_to);
}
},
// TODO: merge operator/value int... | Rust | 0 |
as0() -> &'static Region {
&SINGAPORE
}
/// 获取所有公有云区域实例
pub fn all() -> &'static [&'static Region] {
&ALL_REGIONS[..]
}
/// 查询七牛服务器,根据存储空间名称获取区域列表
///
/// 需要注意的是,当前方法具有缓存机制,对同一 Access Key 和存储空间多次调用时,将会返回缓存结果而不会发送 HTTP 请求
pub fn query<'a>(
bucket: impl Into<Cow<... | Rust | 0 |
points that deviate too much from the median. This gets rid
# of small, few-point anomalies.
if max_deviation > 0:
med = ndimage.median_filter(np.nan_to_num(ret), size=(1, 1, 3, 3))
bad = (np.max(np.abs(med - ret)[:2, ...], axis=0) > max_deviation)
apply_mask(ret, bad)
if min_patch_size > 0:
bad ... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.