text string | label_name string | labels int64 |
|---|---|---|
# 日模式因素 (weekday: 较高, weekend: 较低)
day_factor = day_pattern
# 计算最终负荷
load = base_load * hour_factor * random_factor * price_factor * day_factor
# 应用计算负荷异常事件
if anomaly and 'compute_surge' in anomaly:
load += anomaly['compute_surge']
... | Python | 1 |
MessageBox(screen,message):
def close():
nonlocal tmpFrame
tmpFrame.kill()
tmpFrame = Frame(screen,htitle="Message",width=300,height=100)
t = TypableSurface((190,90),text=message)
tmpButton = Button(tmpFrame,width=50,height=20,text="Close",target=close)
tmpFrame.blit(t,(10,10))
... | Python | 1 |
_ as usize },
16usize,
concat!(
"Offset of field: ",
stringify!(_CPullResult_),
"::",
stringify!(minOffset)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<_CPullResult_>())).maxOffset as *const _ as usize },
24usize,
... | Rust | 0 |
set. */
header_addr: u32,
load_addr: u32,
load_end_addr: u32,
bss_end_addr: u32,
entry_addr: u32,
/* These are only valid if MULTIBOOT_VIDEO_MODE is set. */
mode_type: u32,
width: u32,
height: u32,
depth: u32
}
/* The symbol table for a.out. */
struct multiboot_aout_symbol_table {
tabsize: u32,... | Rust | 0 |
ntegers: 1..N (N included)
// 'Little squares' (3x3 in example above) may also only contain integers: 1..N (N included)
#[derive(Debug)]
struct Sudoku{
data: Vec<Vec<u32>>,
}
impl Sudoku{
fn is_valid(&self) -> bool {
// println!("{:?}", self);
let len = self.data.len();
if len < 1 ... | Rust | 0 |
"""
Write a python function to find the last position of an element in a sorted array.
assert last([1,2,3],1) == 0
"""
def last(arr,x):
if len(arr) == 0:
return -1
if arr[len(arr)-1] == x:
return len(arr)-1
if arr[0] == x:
return 0
if arr[0] > x:
return -1
if arr[len... | Python | 1 |
nExclude => {
println!("{:20} {}", "Excludes", self.s3_url(key));
}
// if there is an include and not in incluse, we silently skip it
Inex::ExcludeNotInInclude => (),
}
Ok(())
}
}
/// Inclusion/Exclusion result
enum Inex {
Include,
ExcludeInExclude,
ExcludeNotInInclude,
}
/// validate the Include... | Rust | 0 |
:{Interests, RegisterOption, OsQueue};
///
/// // Unique ids and addresses for both the sender and echoer.
/// const SENDER_ID: event::Id = event::Id(0);
/// const ECHOER_ID: event::Id = event::Id(1);
///
/// let sender_address = "127.0.0.1:7000".parse()?;
/// let echoer_address = "127.0.0.1:7001".parse()?;
///
/// // ... | Rust | 0 |
bot.send_message(chat_id=chat_id, text='Добавлено!', reply_markup=markup)
user = PaidUser.objects.get(user=user_id)
current_day = (timezone.now().date() - user.paid_day).days
user_data[user_id][current_day][user_data[user_id][current_day]['selected_meal']][
f"{calories_data[use... | Python | 1 |
ally specifying the DMA length used, even if the buffer is larger
/// Panics if the buffer(s) are too small
pub trait ReadWriteDmaLen<RXB, TXB, TS>: Transmit + Receive
where
RXB: WriteBuffer<Word = TS>,
TXB: ReadBuffer<Word = TS>,
Self: core::marker::Sized + TransferPayload,
{
fn read_write_len(
... | Rust | 0 |
}", event),
}
}
#[test]
fn hal_initialized_failure() {
let buffer = [0x01, 0x00, 0x00];
match BlueNRGEvent::new(&buffer) {
Err(HciError::Vendor(BlueNRGError::UnknownResetReason(val))) => assert_eq!(val, 0),
other => panic!("Did not get unknown reset reason: {:?}", other),
}
}
#[test]
#... | Rust | 0 |
enizer.from_pretrained(args.pretrain_model)
test_data = prepare_data(args, tokenizer)
# step 3. load finetuned model
model = torch.load(args.model, map_location=device)
# step 4. predict
res = []
if args.use_multiprocess and device == 'cpu':
print('Parent process %s.' % os.getpid()... | Python | 1 |
from typing import List, Tuple
import torch
import torch.nn as nn
from torch_geometric.data import Data
from model.mol_graph import ATOM_FEATURES
class Atom_Embedding(nn.Module):
def __init__(self,
atom_embed_size: List[int]
) -> None:
super().__init__()
assert len(atom_embed_size) ==... | Python | 1 |
ExecuteError, Executor};
use futures::executor::{self, Notify, Spawn};
use futures::Async;
use std::collections::VecDeque;
use std::result::Result as StdResult;
use std::cell::{Cell, RefCell};
use std::rc::Rc;
use std::cmp;
use webcore::try_from::TryInto;
use webcore::value::Reference;
// TODO: Determine optimal val... | Rust | 0 |
"""
self._cancelled = True
self.cancel_pending()
if timeout or timeout is None:
try:
await self.wait_for(timeout)
except asyncio.TimeoutError:
pass
for task in self.active_tasks:
if not task.done():
task.... | Python | 1 |
# Copyright 2021 The Funnel Rocket Maintainers
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... | Python | 1 |
from fastapi import APIRouter, Depends, HTTPException
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from app.schemas.mcq_schemas import (
UserLoginInput,
UserLoginOutput,
UserOutput,
UserRegisterInput,
UserRegisterOutput,
)
from app.services import UserUnitOfWork, user_servi... | Python | 1 |
_NOTOSANS_REGULAR.clone()),
interface.fonts.insert(FONT_DEFAULT_NOTOSANS_BOLD.clone()),
),
};
// Create window contents drawer
let mut drawer =
DisplayDrawerBuilder::new(window, context, events_loop, &mut interface, fonts);
drawer.run();
}
}
... | Rust | 0 |
se:
cer_ctc_val = ec(ys_pad, ys_hat, is_ctc=True)
_cer, _wer = ec(ys_pad, ys_hat)
assert cer_ctc_val is not None
assert _cer is not None
assert _wer is not None
def test_error_calculator_nospace(tmpdir):
from espnet.nets.e2e_asr_common import ErrorCalculator
space = "<... | Python | 1 |
:.2f} kPa"
tk.messagebox.showinfo("Calculated Values", message)
# Add a button to calculate and display values
calculate_button = tk.Button(popup_window, text="Calculate", command=calculate_and_display_values)
calculate_button.grid(row=1, column=0, columnspan=3, pady=10)
# ... | Python | 1 |
},
&FieldVal { id: FIELD_ORDTYPE, val: v } => {
ord_type = Some( FieldOrdTypeEnum::from_str(v).unwrap() );
},
&FieldVal { id: FIELD_PRICE, val: v } => {
price = Some( f32::from_str(v).unwrap() );
},
&FieldVal { id: FIELD_STO... | Rust | 0 |
case KeybdKey::Type::Numrow3:
return 0x033;
case KeybdKey::Type::Numrow4:
return 0x034;
case KeybdKey::Type::Numrow5:
return 0x035;
case KeybdKey::Type::Numrow6:
return 0x036;
case KeybdKey::Type::Numrow7:
return 0x037;
case KeybdKey::Type::Numrow8:
return 0x038... | Rust | 0 |
();
println!("Tock");
}
}
//! Common functionality for the sentry relay.
#![warn(missing_docs)]
#[macro_use]
mod macros;
#[macro_use]
pub mod metrics;
mod cell;
mod constants;
mod glob;
mod log;
mod retry;
mod time;
mod utils;
pub use crate::cell::*;
pub use crate::constants::*;
pub use crate::glob::*;
... | Rust | 0 |
g_if = "Option::is_none")]
#[serde(deserialize_with = "fix_common::workarounds::from_opt_str")]// https://github.com/serde-rs/serde/issues/1183
#[serde(default)]
#[serde(rename = "43024")]
pub underlying_return_rate_valuation_end_date_offset_day_type: Option<i32>,
/// UnderlyingReturnRateValuationEndDateAdjusted
... | Rust | 0 |
import os
import tensorflow as tf
from src.data_loader import load_wlasl_sequence_dataset
from src.video_sign_bilstm_model import build_video_sign_bilstm_model
# --- Config ---
FRAME_DATA_DIR = '/content/drive/MyDrive/asl_project/WLASL/start_kit/frame_data/'
BATCH_SIZE = 8
IMG_SIZE = (224, 224)
FRAMES = 16
NUM_CLASSES... | Python | 1 |
fn status(&self) -> &String {
&self.status
}
}
<filename>src/scsi/commands/requestsense.rs
use error::{ErrorCause, ScsiError};
use scsi::commands::{Command, CommandBlockWrapper, Direction};
use traits::{BufferPullable, BufferPushable};
/// Requests "sense"-style status information about the device.
///
///... | Rust | 0 |
"""
Given a collection of intervals, find the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping.
Example 1:
Input: [[1,2],[2,3],[3,4],[1,3]]
Output: 1
Explanation: [1,3] can be removed and the rest of intervals are non-overlapping.
Example 2:
Input: [[1,2],[1,2],[1... | Python | 1 |
se { data: "json_pong" })
}
#[get("/_secret_ping")]
async fn secret_ping(_:ApiKey) -> impl Responder {
HttpResponse::Ok().json(PingResponse { data: "spying_pong" })
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| {
App::new()
// TODO: Pull secret from env v... | Rust | 0 |
import os
from functools import cache
from typing import Any
from datasets import Dataset
from huggingface_hub import snapshot_download # type: ignore
from inspect_ai import Task, task
from inspect_ai.dataset import Sample, hf_dataset
from inspect_ai.model import ChatMessage, ChatMessageUser, ContentImage, ContentTex... | Python | 1 |
minimum=0,
maximum=max_64_bit_int,
step=1,
)
randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
motion_bucket_id = gr.Slider(
label="Motion bucket id",
info="Controls how much motion to add/rem... | Python | 1 |
import pytest
from Starfish.grid_tools.instruments import *
class TestInstrumentBase:
@pytest.mark.parametrize("attr", ["name", "FWHM", "oversampling", "wl_range"])
def test_attributes(self, attr, mock_instrument):
assert hasattr(mock_instrument, attr)
def test_string(self, mock_instrument):
... | Python | 1 |
run: bool,
) -> Result<()> {
let mut summary = vec![vec![
"User".to_string(),
"Role Name".to_string(),
"Detail".to_string(),
"Status".to_string(),
]];
summary.push(vec![
"---".to_string(),
"---".to_string(),
"---".to_string(),
"---".to_string()... | Rust | 0 |
transmute(notify_pointing_to_trampoline::<Self> as usize), Box_::into_raw(f) as *mut _)
}
}
#[cfg(any(feature = "v3_12", feature = "dox"))]
fn connect_property_position_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
unsafe {
let f: Box_<Box_<Fn(&Self) + 's... | Rust | 0 |
on across multiple days:
(["2023-05-16 23:30:00"], "America/New_York", "Asia/Kolkata"),
# timezone with half-hour offset:
(["2023-05-17 12:00:00"], "Asia/Kolkata", "Australia/Adelaide"),
# timezone conversion with a timestamp in the future:
(["2025-01-01 00:00:00"], "America/New_... | Python | 1 |
v[0], v[1], v[2], v[3], v[4], v[5], v[6], v[7], v[8], v[9], v[10], v[11], v[12], v[13],
v[14], v[15],
)
}
}
fn calculate(n: usize) -> (i32, u32) {
let mut max_flip_count: u32 = 0;
let mut checksum: i32 = 0;
let mut perm = unsafe { _mm_setr_epi8(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... | Rust | 0 |
e(response)
# Show retrieved documents
with st.expander("📚 Retrieved Documents"):
for i, doc in enumerate(results):
st.write(f"**Document {i+1}** (Similarity: {doc['similarity']:.3f})")
... | Python | 1 |
import streamlit as st
st.title("Histórico de Emissões 🌫️")
# Inicializa o session state se não existir
if 'calculos' not in st.session_state:
st.session_state['calculos'] = []
# Inicializa o session state se não existir
if 'calculos_de_consumo' not in st.session_state:
st.session_state['calculos_de_consumo... | Python | 1 |
body: &serde_json::Value,
) -> Result<()> {
let url = "/admin/api/2020-01/fulfillment_services.json".to_string();
self.client
.post(&url, Some(reqwest::Body::from(serde_json::to_vec(body)?)))
.await
}
/**
* .
*
* This function performs a `GET` ... | Rust | 0 |
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Remote Work with calendar',
'version': '1.0',
'category': 'Human Resources/Remote Work',
'depends': ['hr_homeworking', 'calendar'],
'data': [
'security/security.xml',
'security/ir.model.access.csv'... | Python | 1 |
IV"]
pub type R = crate::R<u16, super::P4IV>;
#[doc = "Port 4 interrupt vector value\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u8)]
pub enum P4IV_A {
#[doc = "0: No interrupt pending"]
P4IV_0 = 0,
#[doc = "2: Interrupt Source: Port 4.0 interrupt; Interrupt Flag: P4IFG0; Interrup... | Rust | 0 |
import os
import unittest
from gradescope_utils.autograder_utils.json_test_runner import JSONTestRunner
if __name__ == "__main__":
# Gather all of the tests in the `/autograder/source/tests/` directory.
suite = unittest.defaultTestLoader.discover("tests")
# All cargo tests need to run with the test crate... | Python | 1 |
pointer or a stable ID; "
"compatible with --single-path",
)
parser.add_argument(
"--dark",
action="store_const",
dest="dark",
const=True,
default=False,
help="dark mode",
)
parser.add_argument(
"--gray",
action="store_const",
... | Python | 1 |
const c_void) -> OGRErr;
pub fn OGR_F_SetGeometryDirectly(hFeat: *const c_void, hGeom: *const c_void) -> OGRErr;
pub fn OGR_F_SetFieldString(hFeat: *const c_void, iField: c_int, pszValue: *const c_char) -> c_void;
pub fn OGR_F_SetFieldDouble(hFeat: *const c_void, iField: c_int, dfValue: c_double) -> c_void;... | Rust | 0 |
# Ülesanne 4
# Kontrollida N inimese sisestatud isikukoodi õigsust. Määrake isiku sugu. Mitu inimest N-st on mees ja mitu naissoost,
# ütle kasutajale.
N=int(input("Mitu isikukoodi soovid kontrollida? "))
km=0
kn=0
for i in range(N):
ik=input(f"Sisesta isikukood {i+1}: ")
while True:
if len(ik)==11 ... | Python | 1 |
2u8, 3u8, 4u8, 5u8, 6u8, 7u8, 0u8,
1u8, 2u8, 3u8, 4u8, 5u8, 6u8, 7u8, 0u8, 1u8, 2u8, 3u8, 4u8, 5u8, 6u8, 7u8,
];
let input: Vector<u8, COUNT> = bytes.try_into().expect("test data");
let mut buffer = vec![];
let _ = input.serialize(&mut buffer).expect("can serialize");
... | Rust | 0 |
::core::GUID = ::windows_sys::core::GUID { data1: 3530145628, data2: 55745, data3: 4563, data4: [179, 143, 0, 16, 90, 31, 71, 58] };
#[repr(C)]
#[doc = "*Required features: 'Win32_System_Wmi', 'Win32_Foundation'*"]
#[cfg(feature = "Win32_Foundation")]
pub union SWbemRpnConst {
pub m_pszStrVal: super::super::Foundat... | Rust | 0 |
andleMouseDown(mp, 2, 2, 0, paint)
#鼠标左键抬起
elif msg == WM_LBUTTONUP:
point = POINT()
user32.GetCursorPos(ct.byref(point))
user32.ScreenToClient(hwnd, ct.byref(point))
mp = FCPoint(point.x, point.y)
mp.x /= paint.scaleFactorX
mp.y /= paint.scaleFactorY
if paint.isDoubleClick:
handleMouseUp(m... | Python | 1 |
?} scope prefix must be an object",
scope_prefix
)));
}
let potential_specifier_map =
potential_specifier_map.as_object().unwrap();
let scope_prefix_url =
match Url::parse(base_url).unwrap().join(scope_prefix) {
Ok(url) => url.to_string(),
_ => {... | Rust | 0 |
bottom = nn.ConvTranspose2d(64, out_channels, 4, 2, 3)
else:
self.conv_bottom = nn.Conv2d(64, out_channels, 3, 1, 0)
for m in self.modules():
if isinstance(m, (nn.Conv2d, nn.ConvTranspose2d)):
nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')... | Python | 1 |
e)
if track_oris is not None and bboxes is not None:
for index, track_bbox in enumerate(bboxes):
bbox_color=(0,255,0)
# print(track_bbox)
x1, y1, x2, y2 = track_bbox[:4].astype(np.int32)
text = "{:d}".format(track_oris[index])
... | Python | 1 |
vent": "types-pywin32",
"win32evtlog": "types-pywin32",
"win32evtlogutil": "types-pywin32",
"win32file": "types-pywin32",
"win32gui_struct": "types-pywin32",
"win32gui": "types-pywin32",
"win32help": "types-pywin32",
"win32inet": "types-pywin32",
"win32inetcon": "types-pywin32",
"win... | Python | 1 |
ist.sort()
print(video_list)
error_threshold = 17
time_diff_data = get_time_diff(save_root, date)
for video_id in tqdm(video_list):
try:
process_frame_loss2(camera_list, upload_date_root, save_root, time_diff_data, video_id, error_threshold)
except Except... | Python | 1 |
unit_price = pricelist.with_context({'uom': uom}).get_product_price(spam, qty, False)
self.assertAlmostEqual(unit_price, expected_unit_price, msg='Computed unit price is wrong')
# Test prices - they are *per unit*, the quantity is only here to match the pricelist rules!
test_unit_price(2, k... | Python | 1 |
#---------------------------------------
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#---------------------------------------
"""
Evaluate a trained model using imple... | Python | 1 |
ytest.mark.parametrize("pixel_x, zoom", assert_pixels)
def test_assert_pixel_x(pixel_x, zoom):
pixel_y = 1
with pytest.raises(AssertionError) as assertion_info:
_ = Point.from_pixel(pixel_x=pixel_x, pixel_y=pixel_y, zoom=zoom)
assert 'Point X needs to be a value between 0 and (2^zoom) * 256.' in s... | Python | 1 |
index_mut(&mut self, idx: (usize, usize)) -> &mut Self::Output {
&mut self.matrix[idx.0 * self.height + idx.1]
}
}
impl<T: Display> Display for DynMatrix<T> {
fn fmt(&self, f: &mut Formatter) -> Result {
for i in 0..self.height {
for val in self.matrix.iter().skip(i).step_by(self.h... | Rust | 0 |
rive(Debug, PartialEq, Eq, Clone, Copy)]
enum Operation {
FastForward,
Forced,
Pruned,
Tag,
New,
Reject,
Noop,
}
/// Parse the `Operation` enum from the one-character prefix in git-fetch
fn parse_operation(chr: &str) -> Result<Operation, Error> {
if chr.len() != 1 {
return Err(E... | Rust | 0 |
_result,
GetIncensePokemonResponse::get_result,
));
fields.push(::protobuf::reflect::accessor::make_singular_enum_accessor(
"pokemon_id",
GetIncensePokemonResponse::has_pokemon_id,
GetIncensePokemonResponse::... | Rust | 0 |
x: 0.0,
// y: 0.0,
// radius: 2.0,
// };
// 関連関数は Struct::function() という構文で呼び出される
let c = Circle::new(0.0, 0.0, 2.0);
println!("{}", c.area());
let d = c.grow(2.0).area();
println!("{}", d);
// Builderパターンによる書き方はこんなかんじ
let c = CircleBuilder::new().x(1.0).y(2.0).radi... | Rust | 0 |
_style_set_public(&mut auth, &*conn)?;
let uid = auth.uid.unwrap();
Ok(Json(json!(style::access(&*conn, &uid, &id, true)?)))
}
#[post("/style/<id>/private")]
fn style_private(
conn: State<DbReadWrite>,
mut auth: auth::Auth,
auth_rules: State<auth::CustomAuth>,
id: i64
) -> Result<Json<serde_js... | Rust | 0 |
extracted = []
for span, span_quantities in zip(existing, spans_quantities):
if len(span_quantities):
span._.set(span.label_, span_quantities[0]._.get(span.label_))
extracted.append(span)
elif self.merge_mode == "intersect":
... | Python | 1 |
get_document<T: Document>(&self, uid: String, did: String) -> Result<T, ServiceError> {
documents::get_document(&self.config, uid, did).await
}
pub async fn get_documents<T: Document>(&self, uid: String, offset: Option<usize>, limit: Option<usize>, attributes: Option<&str>) -> Result<Vec<T>, ServiceEr... | Rust | 0 |
Context, Tcti,
};
/*
* Input: None
* Return: Connection context
*
* Example call:
* let mut ctx = tpm::get_tpm2_ctx();
*/
pub(crate) fn get_tpm2_ctx() -> Result<Context> {
let tcti_path = match std::env::var("TCTI") {
Ok(val) => val,
Err(_) => if std::path::Path::new("/dev/tpmrm0").exist... | Rust | 0 |
from sqlalchemy import Column, Integer, ForeignKey, String
from alchemyClasses import db
class CategoriasPredefinidas(db.Model):
__tablename__ = "categorias_predefinidas"
categoria_id = Column(Integer, primary_key=True, autoincrement=True)
nombre_categoria = Column(String(50), unique=True, index=True)
... | Python | 1 |
pub hash: &'a str,
}
impl<'a> Fingerprint<'a> {
pub(crate) fn new(value: &'a str) -> Result<Self> {
let mut split = value.split(' ');
let r#type = parse_str(split.next(), 1)?;
let hash = parse_str(split.next(), 2)?;
Ok(Self { r#type, hash })
}
}
#[cfg(test)]
mod tests {
us... | Rust | 0 |
yboardMarkup([
[InlineKeyboardButton("↻ Обновить", callback_data=f"act:stats:{name}:{scope}:{page}")],
[InlineKeyboardButton("← Назад", callback_data=f"user:{name}:{scope}:{page}")],
])
def build_global_stats_markup(scope: str, page: int) -> InlineKeyboardMarkup:
return InlineKeyboardMarkup(... | Python | 1 |
1];
let cap = level_capacity(self.k, self.levels.len() - 1, level, self.m);
if pop >= cap {
return level;
}
}
panic!("capacity calculation error")
}
fn add_empty_top_level_to_completely_full_sketch(&mut self) {
let new_level_capacity ... | Rust | 0 |
en incorporated into the function "set_case_running"
# (see above). LukeD 05-05-2020
#
#def perturb_CoreRadiusFraction(var, perturbedVariables,\
# DictOfCases, levels):
# """
# Perturbation of the CoreRadiusFraction may be completed
# as a post-processing step using the nominal c... | Python | 1 |
act_excerpt_markdown(content: &str, excerpt_separator: &str) -> String {
lazy_static!{
static ref MARKDOWN_REF: Regex = Regex::new(r"(?m:^ {0,3}\[[^\]]+\]:.+$)").unwrap();
}
let mut trail = String::new();
if MARKDOWN_REF.is_match(content) {
for mat in MARKDOWN_REF.find_iter(content) {
... | Rust | 0 |
from typing import List, Callable, Optional, Dict
from PySide6.QtGui import QShortcut, QKeySequence
from common import common, widget_base
class Shortcut:
def __init__(self,
widget: widget_base.WidgetBase,
shortcut_name: str,
shortcut_key: List[str],
... | Python | 1 |
crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for SARADC_WAIT_ARB_CYCLE_R {
type Target = crate::FieldReader<u8, u8>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `SARADC_WAIT_ARB_CYCLE` writer - wait arbit signal stable after sar_done"]
pub stru... | Rust | 0 |
Dead,
// rule 2 - stable population
(Cell::Alive, 2) | (Cell::Alive, 3) => Cell::Alive,
// rule 3 - overpopulation
(Cell::Alive, n) if n > 3 => Cell::Dead,
// rule 4 - reproduction
(Cell::Dead, 3) => Cell::Alive,
// anything else is sta... | Rust | 0 |
异常={result['votes']['anomaly']}")
print(f"加权得分(支持正常的权重占比): {result['weighted_score']:.3f}")
print("\n各模型预测:")
for model_name, pred in result['model_predictions'].items():
if 'error' not in pred:
print(f" - {model_name}: {pred['prediction']} (置信度... | Python | 1 |
ll_lon.units = 'degrees_east'
load_cell_lon.long_name = 'loadcell_longitude'
# Assign data
# https://unidata.github.io/netcdf4-python/ (see "Dealing with Strings")
# sta_comp_id[:] = netCDF4.stringtochar(np.array(dmrows,dtype='S10'))
# load_cell_id[:] = netCDF4.stringtochar(np.array(load_cells,dt... | Python | 1 |
import numpy as np
import gym
from ray.rllib.utils.annotations import PublicAPI
@PublicAPI
class Simplex(gym.Space):
"""Represents a d - 1 dimensional Simplex in R^d.
That is, all coordinates are in [0, 1] and sum to 1.
The dimension d of the simplex is assumed to be shape[-1].
Additionally one can... | Python | 1 |
'name' : 'QQ APP ID',
'group' : '登录接口设置',
'editor' : 'text',
'default' : '',
},
'THINK_SDK_QQ.APP_SECRET' : {
'name' : 'QQ KEY',
'group' : '登录接口设置',
'editor' : 'text',
'default' : '',
},
'THINK_SDK_TAOBAO.APP_KEY' : {
'... | Python | 1 |
0x00, 0x00, 0x00, 0x01],
ByteSplitGranularity::TwoBits,
);
test_split_merge(
0x0F,
vec![0x00, 0x00, 0x03, 0x03],
ByteSplitGranularity::TwoBits,
);
test_split_merge(
0x11,
vec![... | Rust | 0 |
_zero()));
let lambda = ((point_x + point_x + point_x)*point_x + A)/(point_y + point_y);
let new_x = (&lambda).square() - point_x - point_x;
let new_y = lambda*(point_x - &new_x) - point_y;
(new_x, new_y)
}
// Note incorrect when given zero inputs
pub fn add(x_p: &FieldElement, y_p: &FieldElement, x_q:... | Rust | 0 |
56, 3)
Sleep(100)
OP_62(0x00FE, 0x00000000, 2000, 0x00, 0x01, 0x000000FA, 0x02)
PlaySE(38, 0x00, 0x64)
Sleep(800)
ChrTalk(
0x00FE,
(
'#1980180504V……礼物?\n',
'工作手套?',
TxtCtl.Enter,
),
)
CloseMessageWindow()
ChrTalk(
0x... | Python | 1 |
#!/bin/python3
def showInstructions():
#print a main menu and the commands
print('''
RPG Game
========
Get to the Garden with a key and a potion
Avoid the monsters!
Commands:
go [direction]
get [item]
''')
def showStatus():
#print the player's current status
print('---------------------------')
pr... | Python | 1 |
_string()),
base_path: None,
trace_parser: trace,
trace_checker: trace,
};
let fs = &mut fe::FileSet::new();
let asto = &mut fe::objects::Objects::new();
let el = &mut fe::errors::ErrorList::new();
let tco = &mut types::TCObjects::new();
let results = &mut HashMap::new();... | Rust | 0 |
);
Ok(WebGpuResult::empty())
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GpuColor {
pub r: f64,
pub g: f64,
pub b: f64,
pub a: f64,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RenderPassSetBlendConstantArgs {
render_pass_rid: ResourceId,
color: Gp... | Rust | 0 |
lookup = KuhnPokerLookup()
low = False
@classmethod
def from_game(
cls,
hole_cards: CardsLike,
board_cards: CardsLike = (),
) -> Hand:
"""Create a poker hand from a game setting.
In a game setting, a player uses private cards from their hole
... | Python | 1 |
Prepare(HashMap<ArtifactId, Vec<PendingExecutionRequest>>);
impl AwaitingPrepare {
fn add(&mut self, artifact_id: ArtifactId, params: Vec<u8>, result_tx: ResultSender) {
self.0
.entry(artifact_id)
.or_default()
.push(PendingExecutionRequest { params, result_tx });
}
fn take(&mut self, artifact_id: &Arti... | Rust | 0 |
impl<'a> Parseable<'a> for Program {
fn parse(stream: &mut TokenStream<'a>) -> Result<Self, String> {
let res = parse_stmt_vec!(stream)?;
Ok(Self(res))
}
}
impl Evaluatable for Program {
fn evaluate<L: LoggerTrait>(self, env: &mut Rc<RefCell<Enviroment>>, logger: &mut L) -> Value {
for stmt in self... | Rust | 0 |
predicted_chars = list(predicted_answer)
true_chars = list(true_answer)
# 计算交集字符数
common = set(predicted_chars) & set(true_chars)
num_common = sum(min(predicted_chars.count(c), true_chars.count(c)) for c in common)
# 计算精确率和召回率
precision = num_common / len(predicted_chars) if len(predicted_cha... | Python | 1 |
from duckiematrix_engine.template import MatrixEntityBehavior
import copy
import numpy as np
class RunInCircleScript(MatrixEntityBehavior):
def __init__(self, *args, radius: float = 0.2, speed: float = 0.5):
super(RunInCircleScript, self).__init__(*args)
self._initial_pose = copy.deepcopy(self.p... | Python | 1 |
e.get_bet())))
sume = 0.0
total_bet = 0.0
for value in moneys:
sume += value
for value in bets:
total_bet += value
print "\n%d hands overall, %0.2f hands per game on average" % (nb_hands, float(nb_hands) / GAMES)
print "%0.2f total bet" % total_bet
print("Overall winnings: ... | Python | 1 |
to_sleep_date(dataframe['end_time'])
sleep_series = pd.Series(dataframe['sleep_time'].values, index=sleep_index)
# get the sum of time slept during days (so this includes naps)
# the result is timedeltas though, so convert below
sleep_aggregate = sleep_series.resample('D').sum()
... | Python | 1 |
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from .views import ProductViewSet, CustomerViewSet, OrderViewSet
from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView
router = DefaultRouter()
router.register(r"products", ProductViewSet, basename="produ... | Python | 1 |
"total_speed_improvement"] / max(1, self.stats["optimizations"])
}
# Helper functions for simpler usage
def optimize_whisper_model(
model_size: str = "tiny",
language: Optional[str] = None,
optimization_level: OptimizationLevel = OptimizationLevel.MEDIUM,
target_device: DeviceTarget = DeviceT... | Python | 1 |
# Copyright (C) 2016 Kevin Ross
#
# This program 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
# (at your option) any later version.
#
# This program is distributed in the... | Python | 1 |
}
// pub fn get_pin(pin: u8) -> bool {
// unsafe {
// let ptr = k210_pac::GPIOHS::ptr();
// get_bit((*ptr).input_val.read().bits(), pin)
// }
// }
use errors::{parse_ok, Error, ErrorKind, ParseResult};
use Buffer;
use std::io::Write;
use whitespaces::{skip_cfws, replace_cfws};
use quoted_string... | Rust | 0 |
#[async_trait::async_trait]
impl InherentDataProvider for MockValidationDataInherentDataProvider {
fn provide_inherent_data(
&self,
inherent_data: &mut InherentData,
) -> Result<(), sp_inherents::Error> {
// Calculate the mocked relay block based on the current para block
let relay_parent_number =
self.rel... | Rust | 0 |
forcing the funciton to return a result too.
println!("{}", next_match);
}
2 => {
let team_info = get_team_info().unwrap();
println!("{}", team_info);
}
3 => {
let rankings = get_all_rankings().unwrap();
... | Rust | 0 |
et "
f"is {y_type}."
)
if y_prob.max() > 1:
raise ValueError("y_prob contains values greater than 1.")
if y_prob.min() < 0:
raise ValueError("y_prob contains values less than 0.")
try:
pos_label = _check_pos_label_consistency(pos_label, y_true)
except ValueE... | Python | 1 |
{
alt((map(token, Cow::Borrowed), map(quoted_string, Cow::Owned)))(input)
}
pub fn values_list(input: &[u8]) -> IResult<&[u8], Vec<Cow<[u8]>>> {
terminated(separated_list1(tuple((tag(b","), space0)), value), space0)(input)
}
pub fn pair(input: &[u8]) -> IResult<&[u8], (&[u8], Cow<[u8]>)> {
separated_pair... | Rust | 0 |
ED, MAC, HOSTNAME);
dhcp.set_broadcast_addr(SocketAddrV4::new(Ipv4Addr::LOCALHOST, 2050));
dhcp.set_src_port(2051);
dhcp.set_timeout_secs(11);
dhcp.setup_socket(&mut w5500).unwrap();
const DHCP_SN: Sn = Sn::Sn0;
let mut server: Server = Server::default();
let mut mono: MockMonotonic = Moc... | Rust | 0 |
invoked a single time per socket per event
/// loop tick.
fn ready(&mut self, event_loop: &mut EventLoop<Self>, token: Token, events: Ready) {
}
/// Invoked when a message has been received via the event loop's channel.
fn notify(&mut self, event_loop: &mut EventLoop<Self>, msg: Self::Message) {
... | Rust | 0 |
MandatoryStmt(MandatoryStmt { arg })
}
}
///
/// The "presence" Statement.
///
#[derive(Debug, Clone, PartialEq, Getters)]
pub struct PresenceStmt {
/// String.
arg: String,
}
impl Stmt for PresenceStmt {
/// Arg type.
type Arg = String;
/// Sub Statements.
type SubStmts = ();
/// Re... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.