text string | label_name string | labels int64 |
|---|---|---|
""" Module to take a water_level reading."""
# Raspi-sump, a sump pump monitoring system.
# Al Audet
# https://www.linuxnorth.org/raspi-sump/
#
# All configuration changes should be done in raspisump.conf
# MIT License -- https://www.linuxnorth.org/raspi-sump/license.html
from hcsr04sensor import sensor
from raspisum... | Python | 1 |
t="", description="OpenRouter API key")
api_url: str = Field(default="https://openrouter.ai/api/v1", description="OpenRouter API URL")
# -----------------------------
# Opik Observability Settings
# -----------------------------
class OpikObservabilitySettings(BaseModel):
api_key: str = Field(default="", desc... | Python | 1 |
# import numpy as np
# import matplotlib.pyplot as plt
# from bayes_opt import BayesianOptimization
# from bayes_opt import UtilityFunction
# from icecream.icecream import ic
# from scipy.stats import norm
# mu = 146.05
# y_best = 107.94
# sigma = 32.0832
# z_score = (y_best - mu) / sigma
# print(z_score)
# probab... | Python | 1 |
_latest_reward_event_timestamp_seconds",
governance.latest_reward_event().actual_timestamp_seconds as f64,
"Timestamp of the latest reward event, in seconds since the Unix epoch.",
)?;
w.encode_gauge(
"governance_last_rewards_event_e8s",
governance.latest_reward_event().distribut... | Rust | 0 |
"""Functions to get vehicle properties or geometrical parameters."""
import sys
sys.path.append("./helpers")
from commonroad.scenario.obstacle import ObstacleType
import numpy as np
from collision_helper_function import angle_range
def get_obstacle_mass(obstacle_type, size):
"""
Get the mass of the consider... | Python | 1 |
().name());
let path = Path::new(&path_str);
tokio::fs::create_dir_all(path.parent().unwrap()).await.unwrap();
let mut output = File::create(path).await.unwrap();
reader.copy_to_end_crc(&mut output, 65536).await.unwrap();
}
}
<gh_stars>0
use anyhow::Result;
use reqwest::{blocking::C... | Rust | 0 |
"image_root:", image_root)
if (len(xmins) > 0) and (2 < 1):
print(" nlines:", line_count, "classes0, scores0",
"xmins0, ymins0, xmaxs0, ymaxs0",
detected_classes[0],
... | Python | 1 |
n = $message_header.number_of_entries_in_the_question_section();
if unlikely!(number_of_entries_in_the_question_section != 1)
{
return Err(ResponseDoesNotContainExactlyOneQuestion(number_of_entries_in_the_question_section))
}
}
}
}
macro_rules! validate_is_response
{
($message_header: ident) =>
{
i... | Rust | 0 |
mskw_XMMf64_XMMf64_AVX512 = 5965,
XED_IFORM_VXORPD_YMMf64_MASKmskw_YMMf64_MEMf64_AVX512 = 5966,
XED_IFORM_VXORPD_YMMf64_MASKmskw_YMMf64_YMMf64_AVX512 = 5967,
XED_IFORM_VXORPD_YMMqq_YMMqq_MEMqq = 5968,
XED_IFORM_VXORPD_YMMqq_YMMqq_YMMqq = 5969,
XED_IFORM_VXORPD_ZMMf64_MASKmskw_ZMMf64_MEMf64_AVX512 = ... | Rust | 0 |
)
type2 : See the TRACK_BAND_TYPES enum. (type:uint8_t, values:ICAROUS_TRACK_BAND_TYPES)
min2 : min angle (degrees) [deg] (type:float)
max2 : max angle (degrees) [deg] (type:float)
type3 ... | Python | 1 |
>,
resMsg: ResMsg,
}
let txt = http_get("https://www.zbg.com/exchange/api/v1/future/common/contracts").unwrap();
let resp = serde_json::from_str::<Response>(&txt).unwrap();
let swap_markets = resp.datas;
let mut mapping = HashMap::<i64, SwapContractInfo>::new();
for swap_market in swap... | Rust | 0 |
from PIL import Image
from collections import Counter
def extract_colors(image_path, num_colors=5):
image = Image.open(image_path).convert('RGB')
image = image.resize((100, 100)) # Resize for faster processing
pixels = list(image.getdata())
most_common = Counter(pixels).most_common(num_colors)
ret... | Python | 1 |
xStrides, [((a % 3) * 6), 7])
indexVars, indexStrides = DetectNonLinearIndex(a % 3 * b * 6 + 7, [b])
assert IsEqualExprList(indexVars, [a % 3])
assert IsEqualExprList(indexStrides, [(b * 6), 7])
indexVars, indexStrides = DetectNonLinearIndex(a % 3 * b * 6 + 7, [a % 3, b])
assert IsEqualExprList(in... | Python | 1 |
) -> str:
return (f'dim={self.dim}, num_heads={self.num_heads}, \n'
f'window_size={self.window_size}, overlap_ratio={self.overlap_ratio}, \n'
f'LR_window_size={self.attn.overlap_win_size}, HR_window_size={self.attn.window_size_up}')
def flops(self, h, w):
hr_h, hr_w ... | Python | 1 |
from prettytable import PrettyTable
x = PrettyTable()
pid = list((input("Enter process ids: ").split()))
burst = list(map(int, input("Enter the burst time: ").split()))
priority = list(map(int, input("Enter the priority: ").split()))
# Assumption: All processes arrive at time 0
for i in range(0, len(priority)):
... | Python | 1 |
::iter::successors(Some(from_module), |m| {
let parent_id = def_map[*m].parent?;
Some(parent_id)
});
ancestors.any(|m| m == to_module.local_id)
}
}
<reponame>hoijui/sophia_rs<gh_stars>100-1000
// this module is transparently re-exported by its parent `graph::inmem`
use std::... | Rust | 0 |
story = []
count = 300
start = req.start
path = f"/products/{req.symbol}/candles"
time_delta = TIMEDELTA_MAP[req.interval]
while True:
# Break if start time later than end time
if start > req.end:
break
# Calculate start and e... | Python | 1 |
#!/usr/bin/python3
# Origin: https://github.com/adafruit/Adafruit-Raspberry-Pi-Python-Code
import smbus
# ===========================================================================
# Adafruit_I2C Base Class
# ===========================================================================
class Adafruit_I2C :
def __i... | Python | 1 |
None:
"""Parse option values from Flake8's OptionManager."""
if options.builtins:
cls.builtIns = cls.builtIns.union(options.builtins)
cls.with_doctest = options.doctests
included_files = []
for included_file in options.include_in_doctest:
if included_fil... | Python | 1 |
# -*- coding: utf-8 -*-
"""
Created on Fri Sep 5 15:04:28 2025
@author: david
"""
import numpy as np
import pandas as pd
import Vinted_Definitions as vd
#------------------------------------------------------Adjustable-----------------------------------------------------
#File
name = "test"
#Pathes
git_path = "ht... | Python | 1 |
from collections import deque
input=__import__('sys').stdin.readline
MIS=lambda:map(int,input().rstrip().split())
n,m=MIS();board=[]
for _ in range(n):
board.append(list(MIS()))
def bfs():
global result
q=deque();q.append((0,0,0,0))
visited=[[False for _ in range(n)] for _ in range(n)]
visited[0][... | Python | 1 |
_AX25: u32 = 3;
pub const PF_IPX: u32 = 4;
pub const PF_APPLETALK: u32 = 5;
pub const PF_NETROM: u32 = 6;
pub const PF_BRIDGE: u32 = 7;
pub const PF_ATMPVC: u32 = 8;
pub const PF_X25: u32 = 9;
pub const PF_INET6: u32 = 10;
pub const PF_ROSE: u32 = 11;
pub const PF_DECnet: u32 = 12;
pub const PF_NETBEUI: u32 = 13;
pub c... | Rust | 0 |
"""
====================
- author: Robin Schmidiger
- version: 0.1
- date: 13 May 2025
====================
"""
from brel.contexts.factory import create_filing_context
from brel.parsers.factory import create_xhtml_filing_parser, create_xml_filing_parser
from brel.parsers.filing_parser import FilingParser
class Fil... | Python | 1 |
::SetProgramStatusFlagState(ProgramStatusFlags::Zero, false),
Microcode::WriteMemory(0x00ff, 0xd5)
]
),
mc
);
}
#[test]
fn should_generate_accumulator_addressing_mode_ror_machine_code() {
let cpu = Mos6502::default()
.with_gp_register(GpRegister::Acc, General... | Rust | 0 |
if let Some((notch_left, notch_right)) = style.notch_left_right
{
match bipolar_state {
BipolarState::Left => draw_notch(knob_info, ¬ch_left),
BipolarState::Right => draw_notch(knob_info, ¬ch_right),
BipolarState::Center => draw_notch(knob_info, &style.notch_center... | Rust | 0 |
import boto3
import json
import os
import base64
import re
def lambda_handler(event, context):
# S3イベントからバケット名とオブジェクトキーを取得
bucket = event['Records'][0]['s3']['bucket']['name']
key = event['Records'][0]['s3']['object']['key']
# S3クライアントの初期化
s3 = boto3.client('s3')
# 画像をダウンロード
local... | Python | 1 |
import torch
from PIL import Image
from transformers import AutoModelForCausalLM, AutoTokenizer
device = "cuda"
tokenizer = AutoTokenizer.from_pretrained("THUDM/glm-4v-9b", trust_remote_code=True)
model = AutoModelForCausalLM.from_pretrained(
"THUDM/glm-4v-9b",
torch_dtype=torch.bfloat16,
low_cpu_mem_usag... | Python | 1 |
.state = State::Left;
}
}
State::Right => {
if result.y == 0 || (result.on_corner() && result.x > 0) {
result.state = State::Up;
}
result.x += 1;
}
State::Down => {
result.... | Rust | 0 |
e values.
On,
/// Do not write values.
Off,
}
/// The stencil test is a bit weird. It’s a [`Comparison`] as well as the « stencil mask ».
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub struct StencilTest {
/// Comparison to apply to make a fragment pass the test.
pub comparison: Comparison,
/// Referenc... | Rust | 0 |
GST_RTCP_SDES_CCID")]
Ccid,
#[cfg(any(feature = "v1_20", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v1_20")))]
#[doc(alias = "GST_RTCP_SDES_MID")]
Mid,
#[doc(hidden)]
__Unknown(i32),
}
#[doc(hidden)]
impl IntoGlib for RTCPSDESType {
type GlibType = ffi::GstRTCPSDE... | Rust | 0 |
import mysql.connector
def connect_db():
return mysql.connector.connect(
host="localhost", # Ändere dies, falls deine DB woanders läuft
user="root", # Dein MySQL-Benutzername
password="password", # Dein MySQL-Passwort
database="testdb" # Dein Datenbankname
)
def insert_entr... | Python | 1 |
new config object based on yaml file
pub fn new(name: &str) -> Result<Self, SpanreedError> {
let path = find_config(name, "yaml")?;
let data = std::fs::read_to_string(path)?;
return Ok(serde_yaml::from_str(&data)?);
}
}
/// Tries to find the config file based on the name. Starts by lo... | Rust | 0 |
#
# Copyright (c) 2022 Arm Limited
# Copyright (c) 2022 Hanno Becker
# Copyright (c) 2023 Amin Abdulrahman, Matthias Kannwischer
# SPDX-License-Identifier: MIT
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal... | Python | 1 |
import streamlit as st
import paho.mqtt.client as mqtt
# MQTT Settings
broker = "broker.hivemq.com"
port = 1883
topic = "lumishue/MAHESH/control"
# MQTT Setup
client = mqtt.Client()
client.connect(broker, port, 60)
client.loop_start()
def send_command(command):
client.publish(topic, command)
st.success(f"✅ S... | Python | 1 |
= "prune":
slim.prune.save_model(exe, train_info_dict['train_program'],
save_path)
elif is_slim == "quant":
save_model(eval_info_dict['program'], save_path)
else:
raise ValueError(
... | Python | 1 |
name=name, rho=rho, elements=elements, quantities=quantities,
*args, **kwargs)
class ZincSulfide(rmat.Material):
def __init__(self, name='ZnS',
elements=['Zn', 'S'],
quantities=[1, 1],
rho=4.079, *args, **kwargs):
super().__init__(
... | Python | 1 |
0].get_weights()
alpha = (self._duration + tau) / (t + tau)
beta = b + tau * (self._duration - t) / (t + tau) * w * input_b_l
keras.backend.set_value(self.snn.layers[0].kernel, alpha * w)
keras.backend.set_value(self.snn.layers[0].bias, beta)
def _get_timestep_at_spikecount(self, x)... | Python | 1 |
,
crawler="pathik",
time_seconds=pathik_result["time"],
memory_mb=pathik_result["memory"],
success_count=pathik_result["success_count"]
)
# Run playwright benchmark
playwright_result = await batch_crawl_with_playwright(
urls,
... | Python | 1 |
uuid = callback.data.split(":", 1)[1]
try:
# Используем прямой HTTP вызов для включения inbound
api_client = RemnaAPI()
result = await api_client.put(f"inbounds/{uuid}/enable")
if result:
await callback.answer("✅ Inbound включен", show_alert=True)
... | Python | 1 |
efault=False,
dest="hmm_scan",
help="if the flag is on, the program will run hmmscan instead of hmmsearch[default] and swap Z scores")
parser.add_argument(
"-Z",
"--z_flip",
action="store_true",
default=False,
... | Python | 1 |
ub mod http_framed_write;
pub mod queued_write;
pub mod write_buffer;
<gh_stars>0
use iota_streams_core::Result;
use iota_streams_ddml::{
command::{
sizeof,
unwrap,
wrap,
},
io,
};
pub trait ContentSizeof<F> {
fn sizeof<'c>(&self, ctx: &'c mut sizeof::Context<F>) -> Result<&'c ... | Rust | 0 |
));
}
#[test]
fn complex_repeat() {
let words = vec!["aaaabbbbaaaabbbb"];
let g = grammar! { top => [&words] };
let m = g.matcher().unwrap();
for w in words {
assert!(m.is_match(w));
}
assert_eq!("(?:a{4}b{4}){2}", &g.rx().unwrap().to_string());
}
#[test]
fn has_test() {
let g = gr... | Rust | 0 |
ommand(label="close",command=root.quit)
filemenu.add_separator()
filemenu.add_command(label="exit",command=root.quit)
menubar.add_cascade(label="file",menu=filemenu)
edit=Menu(menubar,tearoff=0)
edit.add_cascade(label="undo",command=undo)
edit.add_separator()
edit.add_command(label="cut",)
edit.add_command(label="copy"... | Python | 1 |
ml"
testproject_path = validate_mkdocs_file(tmp_path, f"tests/fixtures/{mkdocs_file}")
file = testproject_path / "site/empty/index.html"
contents = file.read_text(encoding="utf8")
validate_additional_script_code(contents, exists=False)
def test_error(tmp_path):
mkdocs_file = "mkdocs-error.yml"
... | Python | 1 |
return Ok(None);
},
}
}
}
fn bv_to_cut_point_sq_dist(axis: &Axis, bounding_volume: &Rect2d, cut_point: &Point2d) -> i64 {
let dist = match axis {
&Axis::X =>
min((bounding_volume.lt.x - cut_point.x).abs() as i64, (bounding_volume.rb.x - cut_point.x).abs() ... | Rust | 0 |
example_2() {
let n = 4;
let k = 9;
let result = "2314".to_string();
assert_eq!(Solution::get_permutation(n, k), result);
}
#[test]
fn test_0060_example_3() {
let n = 3;
let k = 1;
let result = "123".to_string();
assert_eq!(Solution::get_per... | Rust | 0 |
19);
assert_eq!(node.value, 0);
assert_eq!(node.max, 24);
assert_eq!(node.height, 2);
let node = root
.right
.as_ref()
.and_then(|node| node.left.as_ref())
.unwrap();
assert_eq!(node.key, 16..=22);
assert_eq!(node.value, 6)... | Rust | 0 |
Self {
cas,
encoded,
flags,
}
}
pub fn cas(&self) -> u64 {
self.cas
}
pub fn content_as<'a, T>(&'a self) -> Result<T, CouchbaseError>
where
T: serde::Deserialize<'a>,
{
match from_slice(&self.encoded.as_slice()) {
... | Rust | 0 |
O" for mimo
channel mode = "SISO_TX1", "SISO_TX0" for siso tx1, tx0 respectively.
"""
with self.regs:
reg_val = self.peek32(self.MB_DBOARD_CTRL)
if channel_mode == "MIMO":
reg_val = (0b1 << self.MB_DBOARD_CTRL_MIMO)
self.log.trace("Setting ... | Python | 1 |
else:
cbb_X_O.grid_forget()
clone_Label_Depth.grid_forget()
cbb_Depth.grid_forget()
clone_Label.grid(row = 0, column = 2)
clone_Label1.grid(row = 0, column = 1, padx = 117)
except:
pass
# Hàm xử lý độ khó trò chơi
def choose_Level(e):
... | Python | 1 |
5 => Ok(InfringementType::CollisionFailedToHandBackPositionSingle),
6 => Ok(InfringementType::CollisionFailedToHandBackPositionMultiple),
7 => Ok(InfringementType::CornerCuttingGainedTime),
8 => Ok(InfringementType::CornerCuttingOvertakeSingle),
9 => Ok(InfringementType::CornerCuttingOve... | Rust | 0 |
.get_static_object_field(class, field)
}
}
/// public static final [RECORD_SOUND_ACTION](https://developer.android.com/reference/android/provider/MediaStore.Audio.Media.html#RECORD_SOUND_ACTION)
pub const RECORD_SOUND_ACTION : &'static str = "android.provider.MediaStore.RECORD_SOUND... | Rust | 0 |
Vec<String> {
let raw_contents =
fs::read_to_string(file_path).expect("Something went wrong when reading the file");
let re = Regex::new(r"^\s*(bind|.*(C|c)ategory:)").unwrap();
raw_contents
.split('\n')
.filter(|e| re.is_match(e))
.map(|e: &str| e.trim().to_string())
... | Rust | 0 |
// Find the line that starts with `Description=`.
.find(|x| x.starts_with("Description="))
// Split the line and return the latter half that contains the description.
.map(|description| description.split_at(12).1)
}
/// Returns true if the given `UnitType` and `UnitState` indicates tha... | Rust | 0 |
#[derive(Deserialize, Debug, Clone)]
pub struct SymbolLiteral(pub symbol_literal_tag, pub SymbolOrBare);
#[derive(RipperDeserialize, Debug, Clone)]
pub enum SymbolOrBare {
Ident(Ident),
Op(Op),
Kw(Kw),
Symbol(Symbol),
GVar(GVar),
}
#[derive(RipperDeserialize, Debug, Clone)]
pub enum IdentOrConst ... | Rust | 0 |
[macro_use]
extern crate bitflags;
#[cfg(feature = "serde")]
#[macro_use]
extern crate serde;
use e2p_sys::*;
use std::ffi::CString;
use std::fs::File;
use std::io::{Error, ErrorKind};
use std::os::unix::io::AsRawFd;
use std::path::Path;
bitflags! {
#[derive(Default)]
#[cfg_attr(feature = "serde", derive(Ser... | Rust | 0 |
`create` is `true`,
/// a new note file is created and filled with some default content.
pub fn notepath(&mut self, config: &Config, create: bool) -> Result<Option<PathBuf>, Fallacy> {
let note;
// Paper has note path.
if let Some(notepath) = self.notepath.as_ref() {
note = ... | Rust | 0 |
_base_ = ["stage2.py"]
# Define model components
model = dict(cond_embed=True)
grad_ckpt_buffer_size = 25 * 1024**3
condition_config = dict(
t2v=1,
i2v_head=5,
i2v_loop=1,
i2v_tail=1,
)
is_causal_vae = True
bucket_config = {
"_delete_": True,
"256px": {
1: (1.0, 195),
5: (1.0,... | Python | 1 |
d authenticate(with log)")
.long("test-log")
)
)
.subcommand(
SubCommand::with_name("cred")
.about("(alpha)Credential management\n- Enumerate discoverable credentials")
.arg(
Arg::with_name("list")
... | Rust | 0 |
# I built this file to read the data and find where the missing game was as I had 2429 games in the 2024 regular season instead of the usual 2430 games
# As I found out, this is because in 2024, a game between the Astros and Guardians was cancelled due to a rain delay, and due to its proximity to the end of the season ... | Python | 1 |
_CONFIG_SPEC {
type Writer = W;
}
#[doc = "`reset()` method sets cks_config to value 0"]
impl crate::Resettable for CKS_CONFIG_SPEC {
#[inline(always)]
fn reset_value() -> Self::Ux {
0
}
}
<filename>tests/supported.rs
extern crate cookie;
extern crate hyper;
extern crate hyper_serde;
extern crat... | Rust | 0 |
input_mask = mask3d_batch
elif mask_type == None:
input_mask = None
return mask3d_batch, input_mask
def init_meas(gt, mask, input_setting):
if input_setting == 'H':
input_meas = gen_meas_torch(gt, mask, Y2H=True, mul_mask=False)
elif input_setting == 'HM':
input_meas = gen... | Python | 1 |
query_common::Result;
/// FreeDaemon that retrieves events from the source executor
/// and only produces part of the events.
pub struct BatchLimitFreeDaemon<Src: BatchFreeDaemon> {
src: Src,
remaining_rows: usize,
}
impl<Src: BatchFreeDaemon> BatchLimitFreeDaemon<Src> {
pub fn new(src: Src, limit: usize)... | Rust | 0 |
logger throughout
log.logger = logger
exceptions.logger = logger
safetymonitor.start_safety_device(logger)
discovery.logger = logger
set_shr_logger(logger)
#########################
# FOR EACH ASCOM DEVICE #
#########################
safetymonitor.logger = logger
# -----------... | Python | 1 |
location_id : str
transaction_id : str
request_options : typing.Optional[RequestOptions]
Request-specific configuration.
Returns
-------
VoidTransactionResponse
Success
Examples
--------
import asyncio
from squa... | Python | 1 |
val_aucs_by_attrs[ii])):
logger.logkv(f'eval_auc_attr{ii}_group{iii}', round(eval_aucs_by_attrs[ii][iii],4))
for ii in range(len(between_group_disparity)):
logger.logkv(f'eval_auc_attr{ii}_std_group_disparity', round(between_group_disparity[ii][0],4))
logger.logkv(f'eval... | Python | 1 |
are is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITE... | Rust | 0 |
) {
return Err(Error::InvalidSize);
}
let mask = 0x8080_8080_8080_8080_8080_8080_8080_8080_u128 >> (8 * (16 - len));
unsafe { helpers::make_u128_bytes(bytes, len, mask) }
}
#[test]
fn test_u128_from_bytes() {
assert_eq!(
NonZeroU128::new(if cfg!(target_endian = "little") {
0... | Rust | 0 |
er,
offset: usize,
mut_: bool,
idx: StructDefinitionIndex,
type_args: &Signature,
) -> VMResult<()> {
// check and consume top of stack
let operand = verifier.stack.pop().unwrap();
if operand != ST::Address {
return Err(err_at_offset(
StatusCode::BORROWGLOBAL_TYPE_MISMATC... | Rust | 0 |
0;
}
let batch_size = self.batchszs[self.batch];
apply(self);
self.batch += 1;
self.offset += batch_size;
if self.node.count() == num_out_batches as _ {
self.in_op.borrow_mut()._traverse_bwd(epoch, apply);
for _ in 0 .. num_out_batches {
self.node.pop(epoch);
}
}
... | Rust | 0 |
eqlens is not None else None
NT = triton.cdiv(T, BT) if cu_seqlens is None else len(chunk_indices)
if check_shared_mem('ampere'): # A100
BV = min(triton.next_power_of_2(V), 128)
elif check_shared_mem('ada'): # 4090
BV = min(max(triton.next_power_of_2(V), 16), 64)
else:
BV = mi... | Python | 1 |
import FWCore.ParameterSet.Config as cms
from RecoJets.JetProducers.ak4GenJets_cfi import ak4GenJets
from RecoJets.JetProducers.ak8GenJets_cfi import ak8GenJets
from RecoHI.HiJetAlgos.HiGenJets_cff import *
ak4GenJetsNoNu = ak4GenJets.clone( src = "genParticlesForJetsNoNu" )
ak8GenJetsNoNu = ak8GenJets.clone( src =... | Python | 1 |
me_difference = abs(destination.timestamp - source.timestamp)
# Calculate consciousness time coherence
time_coherence = 1 / (1 + time_difference / 3600) # Decay with time difference
# Calculate quantum time tunneling probability
tunneling_probability = math.exp(-time_d... | Python | 1 |
; graph.flush();
worker.step_while(|| probe.less_than(graph.time()));
println!("queried; elapsed: {:?}", timer.elapsed());
for round in 0 .. rounds {
for element in 0 .. batch {
if worker.index() == 0 {
graph.insert((rng1.gen_range(0, nodes), rng1... | Rust | 0 |
import os
import mlflow
import mlflow.pytorch
import torch
from ultralytics import YOLO
from src.utils import logger, settings
class ModelTraining:
"""
Handles the training of a YOLO model using MLflow for experiment tracking.
"""
def __init__(self) -> None:
"""
Initializes the Mode... | Python | 1 |
ittteeList(CommitteeList):
source = "http://www.kslegislature.org/li/b2023_24/committees/"
chamber = "upper"
selector = CSS("#senate-standing-comm-tab-2 li")
class House1CommittteeList(CommitteeList):
source = "http://www.kslegislature.org/li/b2023_24/committees/"
chamber = "lower"
selector = ... | Python | 1 |
;
mod generator;
mod prover;
mod verifier;
pub use self::generator::*;
pub use self::prover::*;
pub use self::verifier::*;
#[derive(Clone)]
pub struct Proof<E: Engine> {
pub a: E::G1Affine,
pub b: E::G2Affine,
pub c: E::G1Affine
}
impl<E: Engine> PartialEq for Proof<E> {
fn eq(&self, other: &Self) -... | Rust | 0 |
# 스택
'''
--> 스택 자체는 python에서 list로 구현 가능
명령 총 5가지:
push X: 정수 X를 스택에 넣는 연산이다.
pop: 스택에서 가장 위에 있는 정수를 빼고, 그 수를 출력한다. 만약 스택에 들어있는 정수가 없는 경우에는 -1을 출력한다.
size: 스택에 들어있는 정수의 개수를 출력한다.
empty: 스택이 비어있으면 1, 아니면 0을 출력한다.
top: 스택의 가장 위에 있는 정수를 출력한다. 만약 스택에 들어있는 정수가 없는 경우에는 -1을 출력한다.
'''
import sys
input = sys.stdin.rea... | Python | 1 |
from .plain_text_view import PlainTextView
from .bold_decorator import BoldDecorator
from .italic_decorator import ItalicDecorator
from .underline_decorator import UnderlineDecorator
def decorator_demo():
"""Demonstrate Decorator pattern with text formatting"""
print("=== Decorator Pattern Demo ===")
... | Python | 1 |
import dataclasses
import logging
import subprocess
import sys
from pathlib import Path
from typing import List
from typing import Optional
from kloch.launchers import BaseLauncher
LOGGER = logging.getLogger(__name__)
@dataclasses.dataclass
class PythonLauncher(BaseLauncher):
"""
A launcher that execute th... | Python | 1 |
ive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub enum RuleTarget {
Local(String),
Abs(String),
}
impl RuleRef {
pub fn local(target: String) -> Self {
RuleRef {
target: RuleTarget::Local(target),
platform: None,
}
}
pub fn abs(target: String) -> ... | Rust | 0 |
from ase.io import read
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.stats import gaussian_kde
# 读取数据
df = pd.read_csv('site_energy_ptcocu.csv')
# 创建子图
fig, axs = plt.subplots(3, 1, figsize=(4, 4))
colors = ['#D85558', '#276BB3', '#FF7F50'] # 保留直方图的颜色
plt.rc('font', family='Arial'... | Python | 1 |
ng: Xoshiro256StarStar = SeedableRng::seed_from_u64(SEED);
for _ in 0..1000 {
let xslen = rng.gen::<usize>() % 10;
let xs = crate::gen_seq::generate_seq(&mut rng, xslen);
let yslen = rng.gen::<usize>() % 10;
let ys = crate::gen_seq::generate_seq(&mut rng, yslen);
... | Rust | 0 |
from typing import Dict, Any
def validate_coins_config(config_dict: Dict[str, Any]) -> bool:
"""
Validate the coins.json config dict.
Raises ValueError if invalid.
"""
if not isinstance(config_dict, dict):
raise ValueError("Config must be a dict of symbol: {leverage, sl_percent}")
for ... | Python | 1 |
ExtendMethod),
//! * [TrailingWhitespaceMethod](crate::trailing_whitespace::TrailingWhitespaceMethod).
//!
//! For more info read docs on each one of the above encoders.
use crate::{
context::{PivotByLineContext, PivotByRawLineContext},
impl_complex_decoder, impl_complex_encoder,
method::{line_extend, rand... | Rust | 0 |
"name": "Redis缓存",
"description": "用于缓存推荐结果和消重",
"connection_type": "redis",
"host": "redis",
"port": 6379,
"username": "",
"password": "redispassword",
"database": "0",
"config": json.dumps({"decode_responses": Tr... | Python | 1 |
::asm;
use register::{mmio::*, register_bitfields};
register_bitfields! {
u32,
///Place holder for struct alignment.
GPFSEL0 [
RESERVED OFFSET(0) NUMBITS(32)
],
/// GPIO Function Select 1
GPFSEL1 [
/// I/O Pin 15 (RXD)
FSEL15 OFFSET(15) NUMBITS(3) [
INPUT = 0b000,
... | Rust | 0 |
#!/usr/bin/env python3
# Copyright (C) 2024 Checkmk GmbH - License: GNU General Public License v2
# This file is part of Checkmk (https://checkmk.com). It is subject to the terms and
# conditions defined in the file COPYING, which is part of this source code package.
from cmk.graphing.v1 import graphs, metrics, Title
... | Python | 1 |
#[doc = "Bit 8 - Not Acknowledged (cleared on read)"]
#[inline(always)]
pub fn nack(&self) -> NACK_R {
NACK_R::new(((self.bits >> 8) & 0x01) != 0)
}
#[doc = "Bit 9 - Arbitration Lost (cleared on read)"]
#[inline(always)]
pub fn arblst(&self) -> ARBLST_R {
ARBLST_R::new(((sel... | Rust | 0 |
le = File::create(file_path).expect("failed to create kernel_stack_address.rs");
let kernel_stack_address = address_from_env("BOOTLOADER_KERNEL_STACK_ADDRESS");
file.write_all(
format!(
"const KERNEL_STACK_ADDRESS: Option<u64> = {:?};",
kernel_stack_address,
)
.as... | Rust | 0 |
def tool_usage(model_response, task):
# Extract tool calls from model_response.all_messages()
tool_usage_value = []
all_messages = model_response.all_messages()
# Process messages to extract tool calls and their results
tool_calls_map = {} # Map tool_call_id to tool ca... | Python | 1 |
year
# 基础生肖顺序(2025年龙年的顺序)
base_zodiacs = ["蛇", "龙", "兔", "虎", "牛", "鼠", "猪", "狗", "鸡", "猴", "羊", "马"]
# 计算年份差值(以2025年为基准)
year_diff = year - 2025
# 计算生肖偏移量(每年农历一月一日,末尾生肖调整到第一个,其他生肖整体后移)
offset = year_diff % 12
# 调整生肖顺序
... | Python | 1 |
_string();
try!(ops::registry_login(shell, token).map_err(|e| {
CliError::from_boxed(e, 101)
}));
Ok(None)
}
use std::any::Any;
use std::cell::RefCell;
thread_local!(static LAST_ERROR: RefCell<Option<Box<Any + Send>>> = {
RefCell::new(None)
});
#[cfg(feature = "unstable")]
pub fn wrap<T, F: F... | Rust | 0 |
import PIL
from torchvision import transforms
from timm.data import create_transform
from timm.data.constants import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD
from PIL import ImageFile, Image
ImageFile.LOAD_TRUNCATED_IMAGES = True
Image.MAX_IMAGE_PIXELS = None
def build_transform(is_train, args):
mean = IMAGEN... | Python | 1 |
Some(path) => Box::new(::std::fs::File::create(path)?),
None => Box::new(::std::io::stdout()),
};
let request_body: graphql_client::GraphQLQueryBody<()> = graphql_client::GraphQLQueryBody {
variables: (),
query: introspection_query::QUERY,
};
let headers = set_headers(a... | Rust | 0 |
for df in results_dfs.values())} total results"
)
return results_dfs
@staticmethod
def pivot_for_export(results_df: pd.DataFrame) -> pd.DataFrame:
"""
Pivot results DataFrame to export format (concentrations as rows).
Args:
results_df: R... | Python | 1 |
) / (
gradient_magnitude.max() - gradient_magnitude.min())
# 恢复原始分辨率
gradient_magnitude = F.interpolate(gradient_magnitude, size=original_resolution, mode='bilinear',
align_corners=False)
return gradient_magnitu... | Python | 1 |
(&target) {
old_expr.find_free_vars()
} else {
return Err(Error::MissingBinding(target))?;
};
let new_vars = new_expr.find_free_vars();
let vars_to_delete = old_vars.difference(&new_vars);
let vars_to_add = new_vars.difference(&old_vars);
// Per... | Rust | 0 |
}
}),
(other, _) => Box::pin(match other.id().cloned() {
None => future::ok(None),
Some(id) => {
let res = Response::error(Some(id), Error::invalid_request());
... | Rust | 0 |
# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
"""Common zone-related types."""
# This is a separate file to avoid import circularity between dns.zone and
# the implementation of the ZONEMD type.
import hashlib
import dns.enum
class DigestScheme(dns.enum.IntEnum):
"""ZONEMD Scheme... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.