text string | label_name string | labels int64 |
|---|---|---|
announce: BlockAnnounce<B::Header>,
) -> CustomMessageOutcome<B> {
let hash = announce.header.hash();
let number = *announce.header.number();
if let Some(ref mut peer) = self.context_data.peers.get_mut(&who) {
peer.known_blocks.insert(hash.clone());
}
let is_their_best = match announce.state.unwrap_o... | Rust | 0 |
.unwrap_or_default(),
size_iops_sec: params.get_u64("size_iops_sec").unwrap_or_default(),
}
}
}
#[derive(Default)]
pub struct DomainGetVcpusRequest(generated::remote_domain_get_vcpus_args);
delegate_pack_impl!(DomainGetVcpusRequest);
impl DomainGetVcpusRequest {
pub fn new(dom: remote_no... | Rust | 0 |
rvice: the local service to expose (defaults to Void)
:param config: configuration dict
:param server_service: the remote service to expose (of the server; defaults to Void)
:param server_config: remote configuration dict (of the server)
"""
listener = socket.socket()
listener.bind(("localhost",... | Python | 1 |
#!/usr/bin/python2
# coding: utf-8
import re, datetime, random, mido, sys, time
data = {}
def split(seq):
for i in range(len(seq) - 2):
yield tuple(seq[i:i+3])
def process(notes):
for note in split(notes):
key = note[:2]
value = note[2]
data[key] = data.get(key, []) + [value]... | Python | 1 |
et diff = to - from + 1;
if diff == 5 {
3
} else if diff > 5 {
1
} else {
0
}
}
// Each 2x2 square of the same color gives a score of 3.
fn evaluate_2x2(matrix: &Matrix) -> u16 {
let mut squares = 0;
for x in 0..matrix.size - 1 {
for y in 0..matrix.size - 1 {
... | Rust | 0 |
:rtype: None
"""
self._pnlPanel.lst_mode_probability = [x[0] for x in RAMSTK_FAILURE_PROBABILITY]
self._pnlPanel.lst_severity_class = [x[0] for x in RAMSTK_CRITICALITY]
def __make_ui(self) -> None:
"""Build the user interface for the FMEA tab.
:return: None
:rtype: ... | Python | 1 |
, ty)),
None => Err(Error::InvalidTypeSignature),
})?;
PrestoTy::Row(row)
} else {
let tuple = ir.try_map(|(name, ty)| match name {
Some(_) => Err(Error::InvalidTypeSignature),
... | Rust | 0 |
/8K_R single/multiple tile profiles require tile to be greater or equal to image size,\nor to be (1024,1024), or (2048,2048) for 4K_R/8K_R or (4096,4096) for 8K_R.\n-> %d,%d is non conformant\n-> Non-IMF codestream will be generated\n\x00"
as *const u8 as *const libc::c_char,
... | Rust | 0 |
from scipy.spatial import Voronoi, voronoi_plot_2d
Create a set of points for the example:
>>> rng = np.random.default_rng()
>>> points = rng.random((10,2))
Generate the Voronoi diagram for the points:
>>> vor = Voronoi(points)
Use `voronoi_plot_2d` to plot the diagram:
>>> fig = voron... | Python | 1 |
in.
# I've made an exception for the activity's total distance, but only because I want it later on for stats.
act.Laps[0].Stats = act.Stats
act.Stationary = False
act.StartTime = startTime
act.EndTime = endTime
act.CalculateUID()
return act
... | Python | 1 |
# Copyright 2023 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 |
final correspondences during testing
with torch.no_grad():
if not self.fine_matching.use_dustbin:
matching_scores = matching_scores[:, :-1, :-1]
ref_corr_points, src_corr_points, corr_scores, estimated_transform = self.fine_matching(
ref_node_corr_knn_poi... | Python | 1 |
bits.set_bits(0..44, ppn);
_write(bits);
}
//! Neo4j driver compatible with neo4j 4.x versions
//!
//! * An implementation of the [bolt protocol][bolt] to interact with Neo4j server
//! * async/await apis using [tokio][tokio]
//! * Supports bolt 4.2 specification
//! * tested with Neo4j versions: 4.0, 4.1, 4.2
//... | Rust | 0 |
not hasattr(self, 'packed_data'):
raise ValueError("Must pack data first.")
with open(path, "wb") as f:
f.write(self.packed_data)
self.progress("Data written to {}".format(path))
def data_to_float64(self):
self.progress("Converting data to float.")
def conv(... | Python | 1 |
))
}
}
impl<T> PartialOrd<Boxed<T>> for SmallInteger
where
T: PartialOrd<SmallInteger>,
{
#[inline]
fn partial_cmp(&self, other: &Boxed<T>) -> Option<Ordering> {
other.as_ref().partial_cmp(self).map(|o| o.reverse())
}
}
impl TryFrom<TypedTerm> for SmallInteger {
type Error = TypeError;
... | Rust | 0 |
ing instructions.
const SHADER_TEXTURE_SHADOW_LOD = 1 << 1;
/// Support memory barriers.
const MEMORY_BARRIERS = 1 << 2;
/// Vertex buffer layouts separate from the data.
const VERTEX_BUFFER_LAYOUT = 1 << 3;
}
}
bitflags::bitflags! {
/// Flags that indicate necessary wor... | Rust | 0 |
added since this code was generated.
Unknown(String),
}
impl std::convert::From<&str> for EncryptionOption {
fn from(s: &str) -> Self {
match s {
"CSE_KMS" => EncryptionOption::CseKms,
"SSE_KMS" => EncryptionOption::SseKms,
"SSE_S3" => EncryptionOption::SseS3,
... | Rust | 0 |
#
# Copyright (C) 2008-2022 Advanced Micro Devices, 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:
# 1. Redistributions of source code must retain the above copyright notice,
# this list of... | Python | 1 |
`panic()` below
use cortex_m::asm::bkpt; // Import cortex_m assembly function to inject breakpoint
use mynewt::{
fill_zero,
kernel::os, // Import Mynewt OS API
sys::console, // Import Mynewt Console API
result::*,
};
use watchface::{ // Import Watch Face Framewor... | Rust | 0 |
ages::BitfieldSigning(_) => unreachable!("Not interested in network events"),
AllMessages::Provisioner(_) => unreachable!("Not interested in network events"),
AllMessages::RuntimeApi(_) => unreachable!("Not interested in network events"),
AllMessages::AvailabilityStore(_) => unreachable!("Not interested in net... | Rust | 0 |
he path of this DIF relative to the search origin.
pub fn path(&self) -> &str {
&self.name
}
/// Returns the name of this DIF, including its file extension.
pub fn file_name(&self) -> &str {
Path::new(self.path())
.file_name()
.and_then(OsStr::to_str)
... | Rust | 0 |
config: SampleConstraintConfig):
logger = logging.getLogger(__name__)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
model = load_model(hydra.utils.to_absolute_path(config.checkpoint_path))
model = model.to(device=device)
if config.url is not None:
logger.info('Fetch... | Python | 1 |
PException(status_code=500, detail=f"启动WebSocket客户端失败: {str(e)}")
#
# @app.post('/api/server/stop')
# async def stop_socket_server(
# req: ServerStopRequest = ServerStopRequest(),
# tenant_id_query: str = Query(None, description="租户ID(URL参数)", alias="tenant_id")
# ):
# """停止WebSocket客户端连接 - 支持任务状态更新... | Python | 1 |
#!/usr/bin/env python
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "L... | Python | 1 |
am::connect("localhost:12321")?;
stream.set_nodelay(true)?;
stream.set_nonblocking(false)?;
stream.write_all(b"PING\r\nPI")?;
stream.read_exact(&mut buf)?;
assert_eq!(
buf,
expected_res,
"'{}' != '{}'",
EscapedByteString(&buf),
EscapedByteString(expected_res... | Rust | 0 |
enough room to claim the HTLC without our counterparty being able to
// time out the HTLC first.
// For outbound HTLCs which our counterparty hasn't failed/claimed, our primary
// concern is being able to claim the corresponding inbound HTLC (on another
// channel) before it expires. In fact, we do... | Rust | 0 |
))
# Create the directory if it doesn't exist
Path(output_dir).mkdir(exist_ok=True)
# Save enhanced transcript if requested
if save_enhanced_transcript:
# Use the transcript filename as a base
transcript_path = Path(transcript_file)
enhanced_transcript_filename = transc... | Python | 1 |
import torch
from torch.autograd import Variable
class ShakeDropFunction(torch.autograd.Function):
"""
never modify p_drop!!! Keep 0.5!!! because we always use "eval" mode
if modified, when gate = 1, the return value is not equal to the expectation of input.
you can modify alpha range, and keep the me... | Python | 1 |
/ }
/// });
///
/// // Back in the first thread, start Pop'ing values off the queue
/// for i in 0..100000 {
/// let t = c.pop();
/// assert!(t == i);
/// }
///
/// ```
///
/// # Panics
///
/// If the requested queue size is larger than available memory (e.g.
/// `capacity.next_power_of_two() * size_of::<T>() > a... | Rust | 0 |
from fastapi import APIRouter, status, Depends
from typing import List
from SCHEMA.schemas import ClassCreate, ClassDisplay
from USECASE.manage_classroom import ClassroomUseCase
from DEPEND.depend_usecase import get_classroom_usecase
router = APIRouter(prefix='/classroom', tags=['classroom'])
@router.post("/create/"... | Python | 1 |
}
}
// Step 5, 6, 7
loop {
match (small.pop(), large.pop()) {
// Step 5
(Some(l), Some(g)) => {
let p_l = probabilities[l];
prob[l] = p_l; // 5.3
alias[l] = g; // 5.4
... | Rust | 0 |
cuments and their nodes+metadata."""
node_doc_ids = self._index_struct.nodes
nodes = self.docstore.get_nodes(node_doc_ids)
all_ref_doc_info = {}
for node in nodes:
ref_node = node.source_node
if not ref_node:
continue
ref_doc_info = s... | Python | 1 |
'{host_ip}/{portfwd_path}')
trs = driver.find_element(By.XPATH, '//*[@id="form1"]/table/tbody/tr[10]/td/table/tbody').find_elements(By.XPATH, "tr")
trs = trs[1:]
ports = []
checkboxes = []
# //*[@id="form1"]/table/tbody/tr[10]/td/table/tbody/tr[2]/td[4]
for tr in trs:
cb = tr.find_elem... | Python | 1 |
ec3::new(2.0, 3.0, 4.0);
let b = Vec3::new(2.0, 6.0, 12.0);
assert!(a == b);
a *= 2.0;
assert!(a == Vec3::new(4.0, 12.0, 24.0));
}
#[test]
fn vec3_div_assign() {
let mut a = Vec3::new(1.0, 2.0, 3.0);
a /= Vec3::new(2.0, 3.0, 4.0);
let b = Vec3::new(0.5, 2.0/3.0, 3.0/4.0);
assert!(a == b... | Rust | 0 |
# -*- coding: utf-8 -*-
# Copyright 2017 - 2022 Avram Lubkin, All Rights Reserved
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
"""
**Enlighten manager submodule**
... | Python | 1 |
n_type, "method": quantisation_method_choice},
metadata={
"description": "Quantized TFLite model",
"training_time_sec": training_time,
"model_size_mb": quantized_model_size,
},
custom_objects={
"preprocess": lambda x: (x / 255.0), # Example prepro... | Python | 1 |
def _deserialize(self, params):
self._Region = params.get("Region")
if params.get("InstanceList") is not None:
self._InstanceList = []
for item in params.get("InstanceList"):
obj = TkeInstanceDetail()
obj._deserialize(item)
self._I... | Python | 1 |
11,
"s=j: Skipping k-combination pruning (utility not loaded).",
start_time,
progress_callback,
)
# ★ Run Greedy first to get warm start indices, even when s==j
# Define time budgets
overall_time_budget = time_limit or 30 ... | Python | 1 |
nt,
"-v",
&target_mount,
"-e",
user_env,
"-e",
cmd_env,
];
// Let the container talk to the docker daemon
if env.privileged {
let docker_socket_mount = "/var/run/docker.sock:/var/run/docker.sock";
ar... | Rust | 0 |
rain: &Vec<Vec<u8>>,
basin_map: &mut Vec<Vec<u8>>,
) -> Vec<Coord> {
// create a vec of coords pointing in every cardinal direction, then filter out the ones that
// aren't part of the basin (due to being equal to the breadcrumb, or out of bounds, or equal
// to 9)
let to_search: Vec<Coord> = vec![c... | Rust | 0 |
#!/usr/bin/env python3
#
# ExpansionHunter Denovo
# Copyright 2016-2020 Illumina, Inc.
# All rights reserved.
#
# Author: Egor Dolzhenko <edolzhenko@illumina.com>,
# Michael Eberle <meberle@illumina.com>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in co... | Python | 1 |
e значительное взаимодействие с
# одним из следующих элементов:
#
# GrLivArea # Надземная жилая площадь
# MoSold # Месяц продано
# Выполните следующую ячейку дважды, в первый раз с feature = "GrLivArea", а в следующий раз с feature = "MoSold":
# YOUR CODE HERE:
feature = "MoSold"
sns.lmplot(
x=feature, y="SalePri... | Python | 1 |
Activation.by_name("relu")(),
)
)
self.attention_norm_layer = LayerNorm(hidden_dim)
self.attention_layer = MultiHeadSelfAttention(
num_heads=num_attention_heads,
input_dim=hidden_dim,
attention_dim=attention_projection_dim,
... | Python | 1 |
}
ui.collapsing("Output events", |ui| {
ui.set_max_width(450.0);
ui.label("Recent output events from egui:");
ui.advance_cursor(8.0);
for event in &self.output_event_history {
ui.label(format!("{:?}", event));
}
});
}
... | Rust | 0 |
ssy();
let date_string = &tile[tile.len()-8..tile.len()];
let year = date_string[0..4].parse::<i32>()?;
let month = date_string[4..6].parse::<u32>()?;
let day = date_string[6..8].parse::<u32>()?;
let datetime = match Utc.ymd_opt(year, month, day) {
LocalResult::Single(date) => date.and_hms(... | Rust | 0 |
d matching objects would
# be non-trivial.
elif isinstance(value, list):
destination[key] = _union_list_of_pydantic_dicts(value, node)
else:
destination[key] = value
return destination
if IS_PYDANTIC_V2:
class V2RootModel(UniversalBaseModel, pydantic.RootModel... | Python | 1 |
dr
alloc_emergency_exception_buf(100)
verbose_l = verbose
client_list = []
client_busy = False
ftpsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
datasocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ftpsocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
datasocket.setsoc... | Python | 1 |
let expected = include_str!("build_schema/fixtures/invalid-object-extension-duplicated-server-field.expected");
test_fixture(transform_fixture, "invalid-object-extension-duplicated-server-field.graphql", "build_schema/fixtures/invalid-object-extension-duplicated-server-field.expected", input, expected);
}
#[te... | Rust | 0 |
= s_ids.astype(object)
# s_id (the FAISS index indices) can equal -1 if fewer than the
# requested number of nearest neighbors is returned. In this case,
# eliminate the -1 entries
self._log.debug("Getting descriptor UIDs from idx2uid mapping.")
uuids = list(s... | Python | 1 |
fmt::Result {
write!(f, "{}", self.display_name)
}
}
pub struct ComparisonFunctionCreator<T> {
t: PhantomData<T>,
}
impl<T: ComparisonImpl> ComparisonFunctionCreator<T> {
pub fn try_create_func(display_name: &str, args: &[&DataTypePtr]) -> Result<Box<dyn Function>> {
// expect array & str... | Rust | 0 |
X32_Stencil8 = 261,
X24_Stencil8 = 262
}
}
<filename>benches/map.rs<gh_stars>0
#[macro_use]
extern crate criterion;
use criterion::Criterion;
fn linked_hash_map_benchmark(c: &mut Criterion) {
use linked_hash_map::LinkedHashMap;
let mut map = LinkedHashMap::new();
c.bench_function("linked-ha... | Rust | 0 |
from aiogram import Bot, Dispatcher, types
from aiogram.contrib.fsm_storage.memory import MemoryStorage
from utils.db.storage import DatabaseManager
from data import config
bot = Bot(token=config.BOT_TOKEN, parse_mode=types.ParseMode.HTML)
storage = MemoryStorage()
dp = Dispatcher(bot, storage=storage)
db = DatabaseM... | Python | 1 |
from rpio.transformations.transformations import swc2code_py,message2code_py
from HelloWorld.Design.HelloWorld_AADLIL import *
#-------------------------------------------------------------------------------------------------------
# !! THESE COMMANDS NORMALLY ARE CALLED FROM THE RPIO CLI, FOR TESTING PURPOSE, A PYTHO... | Python | 1 |
.enumerate()
.map(move |(j, val)| (i, j, *val))
}).collect();
v.iter()
.for_each(|(i, j, val)| {
if row_max[*i] < *val {
row_max[*i] = *val;
}
if col_min[*j] > *val {
col_min[*j] = *val;
}
... | Rust | 0 |
string.parse().unwrap();
let func = expr.bind("x").unwrap();
let h: f64 = 1 as f64;
// let vs: Vec<_> = (0..100+1).map(|i| func(i as f64 / 100.)).collect();
println!("a derivada segunda de = {}", get_second_derivative1(&*func, 0.5 as f64, h, 0.001 as f64));
println!("O valor de h eh: {}", h);
}*/... | Rust | 0 |
Y_SELECTION,
HYPERGRAPH_PROPAGATION=HYPERGRAPH_PROPAGATION
)
elapsed = time.time() - start
display_top_images(
f"Top {TOP_K} Similar Images (CS + SV + HP)",
hp_final_ranks,
query_index,
f"Executed in {elapsed:.4f} seconds"
)
# CAS reranking
start = time.... | Python | 1 |
vec![tx.object_hash()],
sandbox.secret_key(ValidatorId(3)),
));
sandbox.add_time(Duration::from_millis(TRANSACTIONS_REQUEST_TIMEOUT));
sandbox.send(
sandbox.public_key(ValidatorId(3)),
&Sandbox::create_transactions_request(
sandbox.public_key(ValidatorId(0)),
... | Rust | 0 |
value as u32 & 0x01) << 31);
self.w
}
}
impl R {
#[doc = "Bits 0:1 - Slot Size"]
#[inline(always)]
pub fn slotsize(&self) -> SLOTSIZE_R {
SLOTSIZE_R::new((self.bits & 0x03) as u8)
}
#[doc = "Bits 2:4 - Number of Slots in Frame"]
#[inline(always)]
pub fn nbslots(&self) -> ... | Rust | 0 |
er().__init__()
inner_dim = dim_head * heads
context_dim = default(context_dim, query_dim)
self.scale = dim_head**-0.5
self.heads = heads
self.to_q = nn.Linear(query_dim, inner_dim, bias=False)
self.to_k = nn.Linear(context_dim, inner_dim, bias=False)
self.to_v ... | Python | 1 |
s[self._device_serial]["is_on"] = False
stream_switches[self._device_serial]["stream_url"] = None
# Remove from camera streams
camera_streams = self.coordinator.data.get("camera_streams", {})
if self._device_serial in camera_streams:
del c... | Python | 1 |
wrap();
assert_eq!(accounts.data.len(), 2);
}
#[tokio::test]
async fn account_video_channels() {
let (api, _) = crate::test::api().await;
let channels = api
.accounts
.video_channels(&crate::test::username(), &crate::param::Channels::default())
.... | Rust | 0 |
n");
}
#[test]
fn test_map() {
emit_and_compare(&[
Opcode::MapStart(None, None),
Opcode::Scalar(None, None, ScalarStyle::Auto, "a"),
Opcode::Scalar(None, None, ScalarStyle::Auto, "val"),
Opcode::Scalar(None, None, ScalarStyle::Auto, "b"),
... | Rust | 0 |
src_buf_len: size_t,
pout_len: *mut size_t,
flags: c_int)
-> *mut c_void;
pub fn tinfl_decompress_mem_to_heap(psrc_buf: *c_void,
... | Rust | 0 |
salary=float(input("Enter Annual Salary: "))
Tax=0
if 0<=salary<=3*10**5:
pass
elif 3*10**5<salary<=6*10**5:
Tax=salary*0.05
elif salary<=9*10**5:
Tax=15000+(salary-3*10**5)*0.1
elif salary<=12*10**5:
Tax=45000+(salary-9*10**5)*0.15
elif salary<=15*10**5:
Tax=90000+(salary-12*10**5)*0.2
elif 15*10**... | Python | 1 |
on=0, track_color='white')
可视化桥.结束关键帧()
'''
'''
for t in range(60):
可视化桥.发送几何体('Plane|%d|%s|%.2f'%(body, colors[body], 1), # 填入核心参量: “已声明的形状|几何体之ID标识|颜色|整体大小”
0, 0, 0, ro_x=(np.pi*t/120), ro_y=0, ro_z=0, ro_order='XYZ',# 6 DOF
opacity=1, label='ro_x', label_color=... | Python | 1 |
nt_creation: genesis.allow_account_creation,
linear_fees: genesis.linear_fees,
}
}
}
impl GenesisData {
pub fn to_block_0(self) -> Block {
let mut block_builder = BlockBuilder::new();
block_builder.message(Message::Update(UpdateProposal {
// TODO: this is not know... | Rust | 0 |
4, &['\u{0639}', '\u{064A}']),
(0x1d7ec, &['\u{0030}']),
(0x1d4cb, &['\u{0076}']),
(0x2085, &['\u{0035}']),
(0x32c7, &['\u{0038}', '\u{6708}']),
(0x1d73c, &['\u{03B7}']),
(0xff8c, &['\u{30D5}']),
(0x1da8, &['\u{029D}']),
(0xfeba, &['\u{0635}']),
(0x1d48e, &['\u{006D}']),
(0xfc42,... | Rust | 0 |
from discord import Guild, Role
@property
def actual_position(self: Role) -> int:
guild: Guild = self.guild
roles = [r for r in guild.roles][::-1]
return roles.index(self)
| Python | 1 |
`y0`: int
起点 y 坐标
`x1`: int
终点 x 坐标
`y1`: int
终点 y 坐标
返回
====
Iterator[Tuple[int, int]]
迭代器,返回 (x, y) 坐标
"""
euclidean_distance = np.linalg.norm(
[x1 - x0, y1 - y0],
ord=2,
)
... | Python | 1 |
# Você está desenvolvendo um programa em Python para calcular a soma dos números pares dentro de um intervalo determinado pelo usuário. O programa deve solicitar ao usuário que insira dois números inteiros, representando o início e o fim do intervalo (inclusive).
# Utilize um loop 'for' para iterar sobre todos os núm... | Python | 1 |
Barriers: *const VkImageMemoryBarrier2KHR,
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct VkSemaphoreSubmitInfoKHR {
pub sType: VkStructureType,
pub pNext: *const ::std::os::raw::c_void,
pub semaphore: VkSemaphore,
pub value: u64,
pub stageMask: VkPipelineStageFlags2KHR,
pub deviceIndex: ... | Rust | 0 |
import PySimpleGUI as sg
from inventory import INVENTORY
lTab_HQ = [
[sg.Column([
[sg.Text("HQ")],
[sg.Text("PLACEHOLDER")]
])]
]
lTab_Science = [
[sg.Column([
[sg.Text("Forschung1")],
[sg.Text("PLACEHOLDER1")]
]),
... | Python | 1 |
l,
"quantidade": quantidade_final,
"pedidos_sucesso": self.pedidos_sucesso,
"pedidos_falha": self.pedidos_falha,
"tipo_email": tipo_email_final,
"caminho_relatorio": caminho_relatorio,
}
except InterruptedError as e:
... | Python | 1 |
import json
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import warnings
warnings.filterwarnings("ignore", category=FutureWarning)
# 讀取旅館資料
with open('HotelList.json', 'r', encoding='utf-8-sig') as file:
data = json.load(file)
# 將資料轉換為 DataFrame
hotels_df = pd.json_normalize(data['Hote... | Python | 1 |
# mako/compat.py
# Copyright 2006-2024 the Mako authors and contributors <see AUTHORS file>
#
# This module is part of Mako and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
import collections
from importlib import metadata as importlib_metadata
from importlib import util
impo... | Python | 1 |
import numpy
from src.coilsnake.datamodules.data_module import YMLResourceDataModule
from src.objects.sector import Sector
from src.coilsnake.project_data import ProjectData
class SectorModule(YMLResourceDataModule):
NAME = "sectors"
MODULE = "eb.MapModule"
RESOURCE = "map_sectors"
FLOW_STYLE = False... | Python | 1 |
Episode {episode + 1}, Avg Reward: {avg_reward:.2f}, Epsilon: {epsilon:.3f}")
env.close() #! Close the environment after training is complete
#! Save the Q-table to a file
q_table_path = os.path.join("ModelData", "q_table.pkl")
os.makedirs("MountainCar", exist_ok=True) #! Ensure the save directory exists
with open(... | Python | 1 |
output = fn(datum)
outputs.append(output)
return tuple(outputs)
return inner
@collate_one_or_multiple_tensors
def curtail_to_shortest_collate(data):
min_len = min(*[datum.shape[0] for datum in data])
data = [datum[:min_len] for datum in data]
return torch.stack(data)
@col... | Python | 1 |
# %%
import colight.plot as Plot
# %% [markdown]
# Math within `Plot.md` (markdown) is rendered using [KaTeX](https://katex.org/), a fast math typesetting library for the web.
# %%
Plot.md(r"""
Math expressions can be written inline using single `$` delimiters, like $x^2$,
or as display math using double `$$` del... | Python | 1 |
angle);
}
world.destroy_body(body);
assert_eq!(world.body_count(), 1);
}
extern crate peg;
peg::parser!( grammar arithmetic() for str {
rule ident() -> &'input str = $(['a'..='z']+)
pub rule expression() -> Node = precedence!{
start:position!() node:@ end:position!() { Node { start, node... | Rust | 0 |
n="Business logic branch")
target_product_id: int | None = Field(description="Target product ID")
started_at: datetime = Field(description="Start time")
last_message_at: datetime | None = Field(description="Last message time")
total_messages: int = Field(description="Message count")
is_qualified: bo... | Python | 1 |
[0, 72, 40, 255],
[0, 83, 19, 255],
[0, 90, 2, 255],
[0, 69, 13, 255],
[0, 48, 24, 255],
[0, 33, 29, 255],
[0, 23, 29, 255],
[0, 19, 24, 255],
[0, 21, 11, 255],
... | Rust | 0 |
//! - [Packetized Elementary Stream][PES] (PES)
//! - [DVD subtitles](http://sam.zoy.org/writings/dvd/subtitles/)
//! - [System Time Clock](http://www.bretl.com/mpeghtml/STC.HTM)
//!
//! [PES]: http://dvd.sourceforge.net/dvdinfo/pes-hdr.html
//!
//! There are also any number of open source implementations of subtitles
... | Rust | 0 |
# This file is dual licensed under the terms of the Apache License, Version
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
# for complete details.
import pytest
from tls.ciphersuites import CipherSuites, select_preferred_ciphersuite
from tls.exceptions import UnsupportedCipherExceptio... | Python | 1 |
_file(
path=".gitignore",
message="Adiciona arquivo .gitignore padrão para Python",
content=conteudo_gitignore,
branch="main"
)
print("Aquivo .gitignore criado com sucesso")
except GithubException as e:
raise R... | Python | 1 |
ame_support::dispatch::ModuleConstantMetadata {
name: ::frame_support::dispatch::DecodeDifferent::Encode("ReservationFee"),
ty: ::frame_support::dispatch::DecodeDifferent::Encode("BalanceOf<T>"),
value: ::frame_support::dispatch::DecodeDifferent::Encode(
... | Rust | 0 |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'StartMenu.ui'
#
# Created by: PyQt5 UI code generator 5.15.10
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 import QtCore, Q... | Python | 1 |
).to_arrow(index=False))
assert sgpd_result.equals(gpd_result)
sgpd_result = pa.table(
GeoDataFrame(data, index=pd.RangeIndex(start=0, stop=3, step=1)).to_arrow(
index=True
)
)
gpd_result = pa.table(
gpd.GeoDataFrame(
... | Python | 1 |
essage {
/// returns the message bytess
pub fn data(&self) -> &[u8] {
&self.0
}
/// decrypt the message
pub fn decrypt(
&self,
nonce: &box_::Nonce,
key: &box_::PrecomputedKey,
) -> Result<BytesMessage, Error> {
box_::open_precomputed(&self.0, nonce, key)
... | Rust | 0 |
from django.shortcuts import render
from rest_framework import status
from rest_framework.generics import get_object_or_404
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from groups.models import Group
from groups.permission... | Python | 1 |
ignment/mod.rs
//! Machinery for assigning operations to sharing schemes
use crate::ir::term::*;
use fxhash::FxHashMap;
use serde_json::Value;
use std::{env::var, fs::File, path::Path};
#[cfg(feature = "lp")]
pub mod ilp;
/// The sharing scheme used for an operation
#[derive(Debug, PartialEq, Eq, Hash, Clone, Copy)]
... | Rust | 0 |
with(|| {
let claim: Vec<u8> = vec![0,1];
let _ = PoeModule::create_claim(Origin::signed(1), claim.clone());
assert_noop!(
PoeModule::revoke_claim(Origin::signed(2), claim.clone()),
Error::<Test>::NotClaimOwner
);
})
}
#[test]
fn transfer_claim_works() {
... | Rust | 0 |
l_classes:
st.warning("No document classes available for context.")
context = ""
else:
# Select latest class
latest_class = all_classes[-1]["class"]
context = client.query.get(late... | Python | 1 |
import numpy as np
import random
def init_grid():
grid = np.zeros((4, 4), dtype=int)
return grid
def add_new(grid):
# get 0 pos
zero_pos = []
for i in range(grid.shape[0]):
for j in range(grid.shape[1]):
if grid[i, j] == 0:
zero_pos.append((i, j))
if not... | Python | 1 |
item"));
for item_697 in var_696 {
#[allow(unused_mut)]
let mut entry_699 = list_698.entry();
entry_699.string(item_697);
}
list_698.finish();
}
#[allow(unused_mut)]
let mut scope_700 = writer.prefix("ResourceType");
if let Some(var_701) = &inp... | Rust | 0 |
"""排程管理混合類別模組
此模組提供資料收集器的排程功能,包括:
- 排程器管理
- 定時任務設定
- 手動觸發機制
Example:
>>> class MyCollector(BaseDataCollector, SchedulerMixin):
... def collect(self, *args, **kwargs):
... return "data"
>>> collector = MyCollector("test", "source")
>>> collector.schedule_daily("18:00", "2330.TW")
"""
i... | Python | 1 |
);
assert_eq!(
result.token_uri.unwrap(),
"<KEY>"
);
}
#[test]
fn buying() {
let mut deps = mock_dependencies(&[]);
let contract = setup_contract(deps.as_mut());
let token_uri = "https://www.merriam-webster.com/dictionary/petrify".to_string();
let attributes: Vec<Trait> = ... | Rust | 0 |
FINED, direction=Component.UNDEFINED, align_end=Component.UNDEFINED, right=Component.UNDEFINED, in_navbar=Component.UNDEFINED, addon_type=Component.UNDEFINED, disabled=Component.UNDEFINED, nav=Component.UNDEFINED, caret=Component.UNDEFINED, color=Component.UNDEFINED, menu_variant=Component.UNDEFINED, toggle_style=Compo... | Python | 1 |
# SPDX-FileCopyrightText: 2025-present Guille on a Raspberry pi <guilleleiratemes@gmail.com>
#
# SPDX-License-Identifier: GPL-3.0-or-later
import sys
from ..api import advanced
def main():
if len(sys.argv) < 2:
sys.argv.append("help")
local=False
if "--local" in sys.argv:
local = True
... | Python | 1 |
recipient = address(3);
// Before
deps.with_storage(|storage| {
assert_eq!(get_balance(&deps.api, storage, &owner), 11);
assert_eq!(get_balance(&deps.api, storage, &recipient), 33);
assert_eq!(get_allowance(&deps.api, storage, &owner, &spender), 0);
});
// Approve
let appr... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.