text string | label_name string | labels int64 |
|---|---|---|
40000
1 <= dominoes[i][j] <= 9
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/number-of-equivalent-domino-pairs
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
/*
由于骨牌的数字范围是1~9,因为4个bit就能够存储,两个数字的话8个bit就足够了。
我们初始化一个hashmap进行存储和记录即可。
*/
use std::collections::HashMap;
pub fn num_equiv_domino_pairs(dominoes: Vec<Vec<i32>>... | Rust | 0 |
e AutoQuant object
auto_quant = AutoQuant(allowed_accuracy_drop=0.01,
unlabeled_dataset_iterable=unlabeled_data_loader,
eval_callback=eval_callback)
# Step 6. (Optional) Set adaround params
ADAROUND_DATASET_SIZE = 2000
adaround_data_loader = _create_sampled_data_loader(unl... | Python | 1 |
}
def fast_parse_text(file_stream: IO[bytes], filename: str) -> str:
"""
Быстро извлекает сырой текст из потока байтов файла PDF или DOCX.
Args:
file_stream (IO[bytes]): Файл в виде потока байтов.
filename (str): Оригинальное имя файла для определения типа.
Returns:
str... | Python | 1 |
def test_clip_sample(self):
for clip_sample in [True, False]:
self.check_over_configs(time_step=self.default_valid_timestep,
clip_sample=clip_sample)
| Python | 1 |
additional time for <code>StartWindowMinutes</code>, or if the backup started later than scheduled.</p>
pub complete_window_minutes: std::option::Option<i64>,
/// <p>The lifecycle defines when a protected resource is transitioned to cold storage and when it expires. Backup will transition and expire backups au... | Rust | 0 |
;
}
.instrument(info_span!(
"async_spawn_by_smol: routine-exec",
task_id,
record_id
))
})
}
#[inline(always)]
fn spawn_by_smol(&self, task_context: TaskContext) -> Self::SmolHandle {
let fn_handle = unblock_... | Rust | 0 |
= match window.raw_window_handle() {
RawWindowHandle::Windows(h) => h,
_ => unreachable!(),
};
Some(handle.hwnd)
};
let config = PlatformConfig {
dbus_name: "my_player",
display_name: "My Player",
hwnd,
};
let mut controls = MediaControls... | Rust | 0 |
# Copyright (c) 2019-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
from logging import getLogger
import os
import numpy as np
import torch
from evariste.model.data.dictionary import UNK_WORD, D... | Python | 1 |
-> *const () {
/// v as *const ()
/// }
/// }
/// # fn main() { }
/// ```
///
/// ## Comparison with Hypothesis' `@composite`
///
/// `prop_compose!` makes it easy to do a lot of things you can do with
/// [Hypothesis' `@composite`](https://hypothesis.readthedocs.io/en/latest/data.html#composite-strategies),
... | Rust | 0 |
|login| login.is_valid(ctx.now()))
.collect();
Ok(edges)
})
} else {
Ok(RelayConnection::empty())
}
}
}
#![allow(non_camel_case_types, non_upper_case_globals, non_snake_case)]
#![cfg_attr(not(feature = "std"), no_std)]
#[cfg(feature = "std... | Rust | 0 |
## @ingroup Optimization-Package_Setups-TRMM
# TRMM_setup.py
#
# Created: Apr 2017, T. MacDonald
# Modified:
# ----------------------------------------------------------------------
# Imports
# ----------------------------------------------------------------------
from SUAVE.Optimization.Package_Setups.TRMM import... | Python | 1 |
"""
Operaciones
"""
s1 = "Hola"
s2 = "Python"
# Concatenación
print(s1 +" "+ s2 + "!")
# Repetición
print(s1 * 3)
# Indexación
print(s1[0] + s1[1] + s1[2] + s1[3])
# Longitud
print(len(s2))
# Slicing
print(s2[2:6])
print(s2[2:])
print(s2[0:2])
print(s2[:2])
# Búsqueda
print("Ho" in s1)
print("i" in s1)
# Remplaz... | Python | 1 |
;
engine.run(sdl_context, window);
}
// Copyright (c) 2022 Intel Corporation
//
// SPDX-License-Identifier: Apache-2.0
use anyhow::Result;
use serde::Deserialize;
use std::path::{Path, PathBuf};
pub mod overlay;
/// Snapshot types.
#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq, Hash)]
#[serde(rename_a... | Rust | 0 |
ble_on_gatt_disc_chrs(
conn_handle: u16,
error: *const esp_idf_sys::ble_gatt_error,
chr: *const esp_idf_sys::ble_gatt_chr,
cb_arg: *mut esp_idf_sys::c_types::c_void,
) -> esp_idf_sys::c_types::c_int {
let cb_arg = (cb_arg as *mut Box<dyn FnMut(BlePeerCharacteristicDiscoveryE... | Rust | 0 |
on) and (sf[1] < w_seg[i].percent_span_location):
s_sf = np.array([sf[0],sf[1]])
append_CS = True
# Case 7
elif (sf[0] > w_seg[i-1].percent_span_location) and (sf[1] == w_seg[i].percent_span_location) :
s_s... | Python | 1 |
__author__ = 'bryson'
class Beverage(object):
def __init__(self):
self.description = "Unknown Beverage"
def get_description(self):
return self.description
def cost(self):
raise NotImplementedError()
class CondimentDecorator(Beverage):
def get_description(self):
rais... | Python | 1 |
# coding: utf-8
# Copyright (c) 2016, 2025, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may c... | Python | 1 |
from datetime import datetime, timedelta
import pytest
import api_logging as logging
from account.models import Nonce, tz
pytestmark = pytest.mark.django_db
log = logging.getLogger(__name__)
def test_nonce_validation():
"""Make sure a nonce is properly validate:
- validation is successfull if nonce was no... | Python | 1 |
lf):
utils.logger.info("[DouYinLogin.login_by_mobile] Begin login douyin by mobile ...")
mobile_tap_ele = self.context_page.locator("xpath=//li[text() = '验证码登录']")
await mobile_tap_ele.click()
await self.context_page.wait_for_selector("xpath=//article[@class='web-login-mobile-code']")
... | Python | 1 |
UnpinAllChatMessagesBuilder<'a> {
#[serde(skip)]
bot: &'a Bot,
/// Unique identifier for the target chat or username of the target channel (in the format @channelusername)
pub chat_id: i64,
}
impl<'a> UnpinAllChatMessagesBuilder<'a> {
pub fn new(bot: &'a Bot, chat_id: i64) -> Self {
Self {... | Rust | 0 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Represents the size of a page in a PDF document.
The `PageSize` class allows for the definition and management of page dimensions,
including width and height. This class is essential for specifying page sizes and
ensuring consistent layouts across different pages withi... | Python | 1 |
easing/decreasing
Pauli RGB images. The default is 10dB.
Returns
-------
pinc : ndarray, shape (..., 3)
Change representation corresponding to the Pauli RGB of the increasing
polarization states within the range (p_min, p_max) in dB.
pdec : ndarray, shape (..., 3)
Chang... | Python | 1 |
source_file = r"source.txt"
destination_file = r"destination.txt"
with open(source_file, 'r') as src, open(destination_file, 'w') as dest:
dest.write(src.read())
| Python | 1 |
{
use crate::Variant::*;
match self.bits {
0 => Val(GPIO4_A::RF_GPIO4_SRC_DIO_0),
1 => Val(GPIO4_A::RF_GPIO4_SRC_DIO_1),
2 => Val(GPIO4_A::RF_GPIO4_SRC_DIO_2),
3 => Val(GPIO4_A::RF_GPIO4_SRC_DIO_3),
4 => Val(GPIO4_A::RF_GPIO4_SRC_DIO_4),
... | Rust | 0 |
(1182,279,93,266), threshold=0.7, method="Template matching", file="./tasks/DemonEncounter/demon/demon_de_find_boss.png")
# Ocr Rule Assets
# 计数已经开启多少的
O_DE_COUNTER = RuleOcr(roi=(1204,685,48,34), area=(1204,685,48,34), mode="DigitCounter", method="Default", keyword="", name="de_counter")
# Click Rule Assets
... | Python | 1 |
builder(default, setter(into))]
pub channel_points_per_vote: Option<i64>,
}
impl helix::private::SealedSerialize for CreatePollBody {}
// FIXME: I'd prefer this to be a Vec<String> on CreatePollBody
/// Choice settings for a poll
#[derive(PartialEq, typed_builder::TypedBuilder, Deserialize, Serialize, Clone, Debu... | Rust | 0 |
else _orderByTechnique()
if found:
kb.orderByColumns = found
infoMsg = "目标URL在查询中似乎有 %d 列%s" % (found, 's' if found > 1 else "")
singleTimeLogMessage(infoMsg)
return found
elif kb.futileUnion:
return None
... | Python | 1 |
#FLEXdub_Official
import re
import time
import html
import logging
from telegram import Update
from telegram.ext import CallbackContext, CallbackQueryHandler
from html import escape
from cachetools import TTLCache
from pymongo import ASCENDING
from telegram import Update, InlineQueryResultPhoto, InlineKeyboardButton, I... | Python | 1 |
shortest_path_to_get_food;
//
mod _1732_find_the_highest_altitude;
//
mod _1733_minimum_number_of_people_to_teach;
//
mod _1734_decode_xored_permutation;
//
mod _1736_latest_time_by_replacing_hidden_digits;
//
mod _1737_change_minimum_characters_to_satisfy_one_of_three_conditions;
//
mod _1738_find_kth_largest_xor_coor... | Rust | 0 |
pub const LIBDECOR_ACTION_RESIZE: libdecor_capabilities = 2;
pub const LIBDECOR_ACTION_MINIMIZE: libdecor_capabilities = 4;
pub const LIBDECOR_ACTION_FULLSCREEN: libdecor_capabilities = 8;
pub const LIBDECOR_ACTION_CLOSE: libdecor_capabilities = 16;
pub type libdecor_error_callback =
unsafe extern "C" fn(context:... | Rust | 0 |
"""Create conversation table
Revision ID: 0a65ee47b8a8
Revises: 30b391ca28e5
Create Date: 2024-12-04 15:19:00.872168
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = "0a65ee47b8a8"
down_revision: Union[str, None] = "30b3... | Python | 1 |
Header { address: revision_id.to_owned() },
);
},
};
delete_record::<EntryStorage, _>(&revision_id)
}
fn is_satisfiedby_commitment(event_or_commitment: &EventOrCommitmentAddress) -> OtherCellResult<CommitmentResponse> {
call_local_zome_method(
|conf: DnaConfigSlicePlanning| { c... | Rust | 0 |
t(tmp_parser[2])
rule = u"[0-9]?[0-9]?[0-9]{2}\\.((10)|(11)|(12)|([1-9]))\\.((?<!\\d))([0-3][0-9]|[1-9])"
pattern = re.compile(rule)
match = pattern.search(self.exp_time)
if match is not None:
tmp_target = match.group()
tmp_parser = tmp_target.split(".")
... | Python | 1 |
"}],"name":"Product","type":"tuple[]"}],"name":"Result","type":"tuple[]"},{"name":"Status","type":"bytes"},{"name":"TestValue2","type":"bytes"},{"name":"Numbers","type":"int32[]"}],"name":"obj","type":"tuple"}
],
"outputs": [
]
},
{
... | Rust | 0 |
fn from_str(s: &str) -> Result<Self, Self::Err> {
if let Some(value) = s.strip_prefix("fold along y=") {
Ok(Self::FoldAlongY(value.trim().parse::<usize>().map_err(
|error| FoldInstructionFromStrError::ParseInt(value.to_string(), error),
)?))
} else if let Some(val... | Rust | 0 |
以和您IDC中哪些网段通信。
:type SecurityPolicyDatabases: list of SecurityPolicyDatabase
:param IKEOptionsSpecification: IKE配置(Internet Key Exchange,因特网密钥交换),IKE具有一套自我保护机制,用户配置网络安全协议
:type IKEOptionsSpecification: :class:`tcecloud.vpc.v20170312.models.IKEOptionsSpecification`
:param IPSECOptionsSpec... | Python | 1 |
traits::parameter_type_with_key;
use primitives::nft::{ClassType, NftPermissions};
use primitives::ReserveIdentifier;
use primitives::{asset::AssetPair, Amount, AssetId, Balance};
use sp_core::H256;
use sp_runtime::{
testing::Header,
traits::{BlakeTwo256, BlockNumberProvider, IdentityLookup},
};
use std::{cell::RefCe... | Rust | 0 |
# -*- coding: utf-8 -*-
import sys
from typing import Optional
class TwilioException(Exception):
pass
class TwilioRestException(TwilioException):
"""A generic 400 or 500 level exception from the Twilio API
:param int status: the HTTP status that was returned for the exception
:param str uri: The UR... | Python | 1 |
# Необходимые импорты
from ...classes.button_frame import Button
# Импорт дочерней функции
from ..calendars_func.selected_button import select_button
from .set_clock_postion import circle_position
# Не обязательный импорт
import customtkinter as ctk
def create_clock(entry_frames: dict = {}, parent: object = ctk.CTk)... | Python | 1 |
from(e: EventId) -> Self {
e.0.get()
}
}
/// This module contains a proptest `Arbitrary` implementation for
/// event ids. It is only present if the `"test_support"` feature is set.
#[cfg(feature = "test_support")]
pub mod prop {
use super::*;
use proptest::prelude::*;
use proptest::{
... | Rust | 0 |
list = [out]
self.valid_op_map = {
"pd_op.add": 0,
"pd_op.layer_norm": 0,
"pd_op.embedding": 0,
"pd_op.fused_embedding_eltwise_layernorm": 1,
}
yield [main_prog, start_prog], False
def se... | Python | 1 |
import time
import torch
def evaluate(model, loader, loss_fn, ema, device):
if ema is not None:
with ema.average_parameters():
eval_metrics = run_eval(
model=model,
loss_fn=loss_fn,
loader=loader,
device=device,
)
... | Python | 1 |
/// assert_eq!("12foo1bar12".trim_left_matches(x), "foo1bar12");
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn trim_left_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str {
core_str::StrExt::trim_left_matches(self, pat)
}
/// Returns a string slice with all suffixes th... | Rust | 0 |
# no synchronization is needed
after_report = "No synchronization needed"
# send the before and after reports, along with instructions for
# syncing manually, as an email to the administrators
mail_admins("Mongo DB sync status",
'\n\n'.join([before_report,
... | Python | 1 |
RMUKHI")]
Gurmukhi,
#[doc(alias = "G_UNICODE_SCRIPT_HAN")]
Han,
#[doc(alias = "G_UNICODE_SCRIPT_HANGUL")]
Hangul,
#[doc(alias = "G_UNICODE_SCRIPT_HEBREW")]
Hebrew,
#[doc(alias = "G_UNICODE_SCRIPT_HIRAGANA")]
Hiragana,
#[doc(alias = "G_UNICODE_SCRIPT_KANNADA")]
Kannada,
#[... | Rust | 0 |
import torch
import matplotlib.pyplot as plt
def plot_pcd(pcd,
elev=30,
azim=0,
x_lim=[-0.25, 0.25],
y_lim=[-0.25, 0.25],
z_lim=[0, 0.3],
alpha_value=1,
remove_zeros=False,
title=None,
return_fig=False)... | Python | 1 |
}
Val::Wildcard => Val::Cons(Box::new(head), Arc::new(tail)),
Val::PatternVar(_) => Val::Cons(Box::new(head), Arc::new(tail)),
_ => {
panic!("Can't cons to a not list {:?}", tail);
}
}
}
pub fn concat(l1: &Val, l2: &Val) -> Val
{
if l1 == &Val::Nil {
return l... | Rust | 0 |
if let Some(mm) = &mut max_measurement {
*mm = mm.values_max(&measurement);
} else {
max_measurement = Some(measurement.clone());
}
if let Some(mm) = &mut min_measurement {
*mm = mm.values_min(&measurement);
} else {
min_measuremen... | Rust | 0 |
# takes care of creating the directory and all of its parents in a
# longpath-safe manner.
# We must pretend to have extracted this directory, even if it's
# empty, therefore we mustn't rely on creating it as a parent
# directory of a subsequently extracted zip entry (because there may
... | Python | 1 |
.check_and_get_result()
.gas_left,
0
);
} else {
if t.opcode == OpCode::RETURNDATACOPY {
// In case of RETURNDATACOPY the "invalid memory access" might also be returned.
tester.st... | Rust | 0 |
pub struct CheckEndpoint {
/// `NetworkAddress` of remote server interface
#[structopt(long)]
address: NetworkAddress,
/// `ChainId` of remote server
#[structopt(long)]
chain_id: ChainId,
/// `NetworkId` of remote server interface
#[structopt(long)]
network_id: NetworkId,
/// `P... | Rust | 0 |
Match::Exact,
Match::Missing,
Match::Missing,
]
);
}
}
<reponame>rsnively/rangetools<filename>src/test/iterator/bounded_range.rs
use crate::{BoundedRange, LowerBound, UpperBound};
#[test]
fn text_next_included_included() {
let mut r: BoundedRange<i32> = (0..=... | Rust | 0 |
IllFormed => "Font data is ill-formed",
CollectionIndexOutOfBounds => "Font collection has no font at the given index",
CollectionContainsMultipleFonts => {
"Attempted to convert collection into a font, \
but collection contais more than one font"
... | Rust | 0 |
er_for_metrics(completion_mask.sum(1))
.float()
.mean()
.item()
)
self._metrics["completion_length"].append(completion_length)
mean_kl = (
(per_token_kl * completion_mask).sum(dim=1) / completion_mask.sum(dim=1)
).mean()
self._metr... | Python | 1 |
es()
color_frame = frames.get_color_frame()
if not color_frame:
continue
now = time.time()
if (now - last_save_time) >= float(args.interval):
color_bgr = np.asanyarray(color_frame.get_data())
fname = f"{saved:06d}.png"
... | Python | 1 |
al message and typing action
processing_msg = await update.message.reply_text(f"🔍 正在查找与 '{original_code}' 匹配的下载目录...")
await context.bot.send_chat_action(chat_id=chat_id, action=ChatAction.TYPING)
# --- Step 1: Find the actual directory ---
# Pass the BASE Alist URL and the PARENT download directory
... | Python | 1 |
from collections import deque
from dataclasses import dataclass
from mido import MidiFile as MidoFile, MidiTrack as MidoTrack, Message as MidoMessage
from os import path, PathLike
from typing import Self
__all__: list[str] = ['MidiData', 'MidiTrack', 'MidiNote']
@dataclass
class MidiNote:
note: int
start: int
end... | Python | 1 |
Some(
initial_stream_window_size?.unwrap_or(DEFAULT_INITIAL_STREAM_WINDOW_SIZE),
),
initial_connection_window_size: Some(
initial_connection_window_size?.unwrap_or(DEFAULT_INITIAL_CONNECTION_WINDOW_SIZE),
),
..Default::default()
};
let buffer_capacity = b... | Rust | 0 |
nize(Self::RULE, s)?;
let pair = pairs.next().unwrap();
// Check EOI was reached
if pair.as_span().end() != s.len() {
let span = pair
.as_span()
.end_pos()
... | Rust | 0 |
from .iterable import IterableModel
from .maybe import Maybe
from .partial import Partial
from .validators import llm_validator, openai_moderation
from .citation import CitationMixin
from .simple_type import is_simple_type, ModelAdapter
__all__ = [ # noqa: F405
"CitationMixin",
"IterableModel",
"Maybe",
... | Python | 1 |
use std::sync::Arc;
use std::sync::atomic::{AtomicU32, Ordering};
use std::thread;
use contend::{TestCase, contend};
const NUM_LOOPS: usize = 30;
const MAX_EXP: usize = 9;
const YIELD_INTERVAL: usize = 8;
const FUTEX_WAIT_BITSET_PRIVATE: usize = 9 | 128;
const FUTEX_WAKE_BITSET_PRIVATE: usize = 10 | 128;
struct Ti... | Rust | 0 |
c_int, c_long, c_ulong};
use std::mem;
use std::ptr;
use asn1::Asn1GeneralizedTimeRef;
use error::ErrorStack;
use hash::MessageDigest;
use stack::StackRef;
use x509::store::X509StoreRef;
use x509::{X509Ref, X509};
use {cvt, cvt_p};
bitflags! {
pub struct OcspFlag: c_ulong {
const NO_CERTS = ffi::OCSP_NOCE... | Rust | 0 |
__all__ = [
"GLM", "GEE", "OrdinalGEE", "NominalGEE",
"BinomialBayesMixedGLM", "PoissonBayesMixedGLM",
"families", "cov_struct"
]
from .generalized_linear_model import GLM
from .generalized_estimating_equations import GEE, OrdinalGEE, NominalGEE
from .bayes_mixed_glm import BinomialBayesMixedGLM, PoissonBay... | Python | 1 |
, 'text': 768},
{"covarep":74},
{"facet42":35}],
'pom_SDK':[
{'glove':300, 'last_hidden_state':768, 'masked_last_hidden_state':768, 'summed_last_four_states': 768, 'text': 768},
{"covarep":43},
{"facet42":35}],
'avec2019':[
{'text': 768},
{'mfcc':39,... | Python | 1 |
from jesse.config import config
from jesse.enums import exchanges, timeframes
from jesse.routes import router
from jesse.store import store
def test_routes():
# re-define routes
router.set_routes([
{'exchange': exchanges.BITFINEX_SPOT, 'symbol': 'ETH-USD', 'timeframe': timeframes.HOUR_3, 'strategy': '... | Python | 1 |
.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#[allow(missing_doc)];
use container::Container;
use core::cmp::{Ord, Eq};
use ops::{Add, Sub, Mul, Div, Re... | Rust | 0 |
import numpy as np
import pandas as pd
from plotnine import ggplot, aes, geom_line, labs, theme_minimal, theme, scale_y_continuous, element_text
# 模拟数据
np.random.seed(42)
test_counts = np.arange(1, 101)
accuracy_software_1 = np.random.normal(loc=0.8, scale=0.05, size=len(test_counts))
accuracy_software_2 = np.random.n... | Python | 1 |
m = MeanIoU(self.num_class)
data = self.create_input_data(DatasetSubset.TEST)
acc_time = 0
for i in range(len(data)):
start = time.time()
x, y = data.get_batch_sample(i, batch=1)
samples = np.zeros((mc_iteration, *x.shape[1:]))
for ii in range(... | Python | 1 |
# """
# This is ArrayReader's API interface.
# You should not implement it, or speculate about its implementation
# """
# Class ArrayReader:
# def get(self, index: int) -> int:
class Solution:
def search(self, reader: 'ArrayReader', target: int) -> int:
l = bisect.bisect_left(range(10**4), target,
... | Python | 1 |
Trace_beginSection(sectionName: *const ::std::os::raw::c_char);
}
extern "C" {
pub fn ATrace_endSection();
}
extern "C" {
pub fn ATrace_beginAsyncSection(sectionName: *const ::std::os::raw::c_char, cookie: i32);
}
extern "C" {
pub fn ATrace_endAsyncSection(sectionName: *const ::std::os::raw::c_char, cookie:... | Rust | 0 |
assert_eq!(*data3, 1.0);
HttpResponse::Ok()
},
),
),
)
.await;
let req = TestRequest::get().uri("/test").to_request();
let resp = call_service(&mut srv, req).await;
assert_eq!(res... | Rust | 0 |
##########################################################################
#
# Copyright (c) 2012, John Haddon. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of so... | Python | 1 |
future used to receive a datagram from a UDP socket.
///
/// This is created by the `UdpSocket::recv_dgram` method.
#[must_use = "futures do nothing unless polled"]
#[derive(Debug)]
pub struct RecvDgram<T> {
/// None means future was completed
state: Option<RecvDgramInner<T>>
}
/// A struct is used to represe... | Rust | 0 |
):
node_surcharged_duration[i] = node.statistics['surcharge_duration']
T = np.sum(node_surcharged_duration) / 30
# 注意优化目标函数与约束都只能是min的形式 这里上面的R已经全部添加了负号进行计算
f1 = 221.64 * a_BC + 110.78 * b_RG
# 约束 同样是min的形式
g1 = a_BC - 5500
g2 = b... | Python | 1 |
codes_or_none) in enumerate(zip(*lines)):
if points_or_none is not None and codes_or_none is not None:
check_point_array(points_or_none)
check_code_array(codes_or_none)
if len(points_or_none) != len(codes_or_none):
raise ValueError(f"Points... | Python | 1 |
usize = 0xf;
const IPPROTO_IP: usize = 0;
const IPPROTO_ICMP: usize = 1;
const IPPROTO_TCP: usize = 6;
const TCP_SENDBUF: usize = 512 * 1024; // 512K
const TCP_RECVBUF: usize = 512 * 1024; // 512K
const UDP_SENDBUF: usize = 64 * 1024; // 64K
const UDP_RECVBUF: usize = 64 * 1024; // 64K
pub fn sys_socket(domain: us... | Rust | 0 |
import os
import tempfile
from datasets.image_utils import (
is_supported_image,
validate_image,
sanitize_image,
resize_image,
generate_thumbnail,
extract_exif,
scrub_exif,
)
from PIL import Image
import pytest
def create_test_image(fmt="JPEG", exif=False):
"""Create a simple image fil... | Python | 1 |
= "Win32_Graphics_Gdi"))]
impl ::core::clone::Clone for PRINTER_DEFAULTSA {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_Graphics_Printing\"`, `\"Win32_Foundation\"`, `\"Win32_Graphics_Gdi\"`*"]
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Gd... | Rust | 0 |
}
."data-nwg-visible"?={visible}
."data-nwg-placeholder_text"?={placeholder_text}
."data-nwg-focus"?={focus}
."data-nwg-limit"?={limit.map(|limit| format!(in bump, "{}", limit).into_bump_str())}
on bubble "nwg-OnTextInput" = fn(self, _event) {
todo!()
}
!"{}"(self.text.borrow())
>
}
//! Contains ... | Rust | 0 |
.clone(), recv));
smol::spawn(run_listen(socket, out_send, m2));
Ok(send)
}
}
/// Listen for outside send job.
/// Split message to buffers, if ok, send to remote.
async fn run_self_recv(socket: Arc<UdpSocket>, recv: Receiver<EndpointMessage>) -> Result<()> {
let mut send_buffers = Buffers::new... | Rust | 0 |
ld_sv.create_entity().with(conn_to_client).build();
sleep(Duration::from_millis(50));
{
let mut sto = WriteStorage::<NetConnection<()>>::fetch(&world_cl.res);
for mut cmp in (&mut sto).join() {
for _i in 0..100 {
cmp.send_buffer.single_write(... | Rust | 0 |
benchmark-enable")
@nox.session(name="benchmarks:current-venv", venv_backend="none", default=False, tags=["benchmarks"])
def benchmarks_current_venv(session):
"""Run benchmarks in the current virtualenv only"""
session.run("uv", "run", "pytest", BENCHMARK_DIR, "--benchmark-enable")
@nox.session(name="lint",... | Python | 1 |
match obj.ray_hit(ray, t_min, t_max) {
None => None,
Some((t, _)) => Some((t, idx, obj)),
})
}
}
impl<'a, B: BoundingBox, T: BoundsHittable<B>, const N: usize> Bvh<B, T, N> {
pub fn query_bounds_exact(
&'a self,
bounds: &'a B,
) -> impl Iterator<... | Rust | 0 |
""" lec_avgs_example.py
Companion codes lecture
"""
# ----------------------------------------------------------------------------
# The dates and prices lists
# ----------------------------------------------------------------------------
dates = [
'2020-01-02',
'2020-01-03',
'2020-01-06',
'2020-01-07',
... | Python | 1 |
from typing import Any, Dict, Type, Optional
from transformers import ( # type: ignore
pipeline, # type: ignore
Pipeline,
)
from utca.core.executable_level_1.interpreter import Evaluator
from utca.core.executable_level_1.schema import (
Input, Output
)
from utca.core.predictor_level_2.predictor import Pre... | Python | 1 |
chooses to represent the `Map` type using `Vec<(Value, Value)>` instead.
//!
//! This decision was made because this type preserves the order of the pairs
//! on the wire. Further, for those that need the properties of `BTreeMap` or
//! `HashMap`, you can simply `collect()` the values into the respective type.
//! Thi... | Rust | 0 |
instances
assert len(detections) == 2
def test_mixed_pii_detection(self):
"""Test detection of multiple PII types in one text."""
text = "Email john@test.com or call 555-123-4567 from 192.168.1.1"
detections = self.detector.detect(text)
assert len(detections) == 3
t... | Python | 1 |
where blocking is not allowed. This
/// happens when a runtime is dropped from within an asynchronous
/// context.', .../tokio-1.4.0/src/runtime/blocking/shutdown.rs:51:21
pub fn new(thread_name: &str, num_threads: usize) -> Self {
let thread_name = thread_name.to_string();
let (tx_tasks, ... | Rust | 0 |
*const _ as usize },
16usize,
concat!(
"Offset of field: ",
stringify!(Pedge_t),
"::",
stringify!(b)
)
);
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct vconfig_s {
_unused: [u8; 0],
}
pub type vconfig_t = vconfig_s;
extern "C" {
... | Rust | 0 |
")]
pub ty: u16,
pub message_structure: String,
pub messages: Vec<Message>,
}
impl Service {
pub fn get_messages<'a>(&'a self) -> impl Iterator<Item = &'a Message> {
self.messages.iter()
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Message {
pub name: String,
#[serde(ren... | Rust | 0 |
.0
// SPDX-License-Identifier: MIT
//! Re-exported winit API with extended features.
//!
//! This module re-export [winit] APIs on macOS and Windows. And since wry uses Gtk to create
//! WebView. This module is a re-implementation of winit APIs for Gtk on Linux. It also extends
//! more methods to some platform specif... | Rust | 0 |
from .base import Augmentor
import copy
import random
import torch
class RandomDropNode(Augmentor):
def __init__(self, is_x: bool = True, is_adj: bool = False, drop_percent=0.2):
super().__init__()
self.is_x = is_x
self.is_adj = is_adj
self.drop_percent = drop_percent
... | Python | 1 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
真實數據爬取器 - 基於官方交易所渠道
=====================================
使用TWSE官方API和櫃買中心獲取準確的股票數據,
替代之前不準確的模擬數據。
數據來源優先級:
1. TWSE官方API (最高準確性)
2. 櫃買中心 (上櫃股票)
3. Yahoo Finance (備援)
Author: AI Trading System
Date: 2025-01-28
Version: 1.0
"""
import requests
import pandas as pd
imp... | Python | 1 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# C++ version Copyright (c) 2006-2007 Erin Catto http://www.box2d.org
# Python version by Ken Lauer / sirkne at gmail dot com
#
# This software is provided 'as-is', without any express or implied
# warranty. In no event will the authors be held liable for any damages
# a... | Python | 1 |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'demo70_seleccion_pais.ui'
#
# Created by: PyQt5 UI code generator 5.14.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_SeleccionPais(object):
def setupUi(self, SeleccionP... | Python | 1 |
IP-211: New opcodes: RETURNDATASIZE and RETURNDATACOPY
check!(SPEC::enabled(BYZANTINE));
pop!(interp, memory_offset, offset, len);
gas_or_fail!(interp, gas::verylowcopy_cost(len));
let len = as_usize_or_fail!(len, Return::OutOfGas);
let memory_offset = as_usize_or_fail!(memory_offset, Return::OutOfG... | Rust | 0 |
import sys
import logging
from decouple import config
from sqlalchemy.exc import OperationalError
from sqlalchemy import create_engine as ce, MetaData as md
import pandas as pd
logging.basicConfig(
format = '%(asctime)-5s %(levelname)-8s %(message)s',
level=logging.INFO,
stream=sys.stdout,
encoding="... | Python | 1 |
s,
} => grouped_commands_to_plain_string(&help_options, &help_description, &groups),
CustomisedHelpData::SingleCommand {
ref command,
} => single_command_to_plain_string(&help_options, &command),
};
match msg.channel_id.say(&ctx, result).await {
Ok(response) => Some(... | Rust | 0 |
ast::BiMul => {
if is_float { llvm::LLVMConstFMul(te1, te2) }
else { llvm::LLVMConstMul(te1, te2) }
}
ast::BiDiv => {
if is_float { llvm::LLVMConstFDiv(te1, te2) }
else if signed { llvm::LLVMConstSDi... | Rust | 0 |
ysvar::rewards::create_account(1, 0.0, 0.0)
),
],
&serialize(&StakeInstruction::Deactivate).unwrap(),
),
Err(InstructionError::InvalidArgument),
);
// Tests correct number of accounts are provided in deactivate
assert_e... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.