text string | label_name string | labels int64 |
|---|---|---|
f'{model_name} train loss': avg_train_loss
})
# 每一轮进行一次测试
g_loss = 0
Model.eval()
with torch.no_grad():
for batch in tqdm(test_loader, desc="Testing Batches"):
label, pan, lrms, up_ms, hpan, hlrms = batch
label = label.to(device).float()
pan = pan.to(dev... | Python | 1 |
# '''
# Desc: On Balance Volume (OBV) implementation
#
# Copyright: (c) 2017-2020 Joshith Rayaroth Koderi
# This file is part of Wolfinch.
#
# Wolfinch 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, e... | Python | 1 |
for the specific language governing permissions and
// limitations under the License.
use std::collections::HashMap;
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Debug)]
pub struct SnapshotDetail {
pub ref_id: u32,
pub checksum: u32,
pub applied_ids: HashMap<u64, u64>,
pub r... | Rust | 0 |
# -*- coding: utf-8 -*- #
# Copyright 2022 Google LLC. All Rights Reserved.
#
# 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 requir... | Python | 1 |
ap;
use log::Level::Debug;
use rdkafka::{
client::ClientContext,
config::ClientConfig,
consumer::{
stream_consumer::{self, StreamConsumer},
CommitMode, Consumer, ConsumerContext, Rebalance,
},
error::{KafkaError, KafkaResult},
message::{BorrowedMessage, Headers},
util::AsyncR... | Rust | 0 |
_SHA256, TPM2_ALG_SHA384, TPM2_ALG_SHA3_256,
TPM2_ALG_SHA3_384, TPM2_ALG_SHA3_512, TPM2_ALG_SHA512, TPM2_ALG_SM2, TPM2_ALG_SM3_256,
TPM2_ALG_SM4, TPM2_ALG_SYMCIPHER, TPM2_ALG_TDES, TPM2_ALG_XOR,
},
tss2_esys::TPM2_ALG_ID,
Error, Result, WrapperErrorKind,
};
use log::error;
use num_derive::{F... | Rust | 0 |
A value was not good.")
return True
if a_value == 20:
self.thread_plan.SetPlanComplete(True)
return True
else:
self.queue_next_plan()
return False
def should_step(self):
return True
# Here's an example that steps out of the curre... | Python | 1 |
ame] if obj['name'] == classname]
bbox = np.array([x['bbox'] for x in R])
difficult = np.array([x['difficult'] for x in R]).astype(np.bool)
det = [False] * len(R)
npos = npos + sum(~difficult)
class_recs[imagename] = {'bbox': bbox,
'difficult': di... | Python | 1 |
# coding: utf-8
import os
from glob import glob
import os.path as osp
import imageio
import numpy as np
import cv2; cv2.setNumThreads(0); cv2.ocl.setUseOpenCL(False)
def load_image_rgb(image_path: str):
if not osp.exists(image_path):
raise FileNotFoundError(f"Image not found: {image_path}")
img = cv2... | Python | 1 |
Self>, ctx: &mut task::Context<'_>) -> Poll<Self::Output> {
// Safety: not moving `iter`.
unsafe { Pin::map_unchecked_mut(self, |s| &mut s.iter).poll_next(ctx) }
}
}
use config::{Config, ConfigError, File, FileFormat};
use serde_derive::Deserialize;
use std::time::Duration;
#[derive(Clone, Debug, D... | Rust | 0 |
[enumerate_str(rename = "=>")]
EqualMoreThan,
#[enumerate_str(rename = "<")]
LessThan,
#[enumerate_str(rename = "<=")]
LessThanEqual,
#[enumerate_str(rename = "-")]
Minus,
#[enumerate_str(rename = "-=")]
MinusEqual,
#[enumerate_str(rename = ">")]
MoreThan,
#[enumerate_str... | Rust | 0 |
pub address: BTreeMap<Address, Accesses>,
}
impl<const WORD_BITS: u32> Mem<WORD_BITS> {
/// Instead of providing two read only tapes as the TinyRAM specification does,
/// We take the aproach from page 13 of the Arya paper, and write the tapes to memory.
pub fn new(primary_tape: &[Word], auxiliary_tape... | Rust | 0 |
let system_ref = convert_ref::<System>(raw_system_ref);
let irq = match interrupt {
CpuInterrupt::NMI => Interrupt::NMI,
CpuInterrupt::RESET => Interrupt::RESET,
CpuInterrupt::IRQ => Interrupt::IRQ,
CpuInterrupt::BRK => Interrupt::BRK,
_ => Interrupt::RESET, // とりあえずResetにし... | Rust | 0 |
# Copyright 1999-2009 University of Chicago
#
# 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 or agreed t... | Python | 1 |
import oRBD
import numpy as np
import datetime as dt
from CraamTools.filters import RunningMean as rm
import pdb
def get_par():
d=oRBD.RBD()
d.readRBDinDictionary('rs1170914.1700')
# Liquid Nitrogen 1
i0=7900
i1=8500
r=np.arange(i0,i1+1)
nitro1 = np.zeros(6)
snitro1 = np.zeros(6)
... | Python | 1 |
ent_mlen(&WordU32::from(1u32));
}
}
}
//! This module defines the main function for the view/render/event thread.
use cgmath::{Vector2};
use gl;
use sdl2;
use sdl2::event::{Event, WindowEvent};
use sdl2::video;
use std;
use stopwatch;
use time;
use yaglw::gl_context::GLContext;
use common::interval_timer:... | Rust | 0 |
# Copyright 2021 Akretion France (http://www.akretion.com/)
# @author: Alexis de Lattre <alexis.delattre@akretion.com>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import api, fields, models
class AccountFiscalPosition(models.Model):
_inherit = "account.fiscal.position"
fr_vat_... | Python | 1 |
}
// Link program
let program_id = gl_context.create_program();
gl_context.attach_shader(program_id, vertex_shader_object);
gl_context.attach_shader(program_id, fragment_shader_object);
gl_context.link_program(program_id);
#[cfg(debug_assertions)] {
if... | Rust | 0 |
import math
def validate_dimensions(*dimensions: float) -> None:
for dimension in dimensions:
if dimension <= 0:
raise ValueError("Dimensions must be greater than 0.")
def calculate_rectangle_area(width: float, height: float) -> float:
validate_dimensions(width, height)
return width ... | Python | 1 |
(),
"hello".to_string(),
"-k".to_string(),
"-l".to_string(),
"-100".to_string(),
"-p".to_string(),
"100".to_string(),
]);
match opt.get_opt(Opt::one("-a")) {
Some(v) => {
assert_eq!(v.one(), "hello");
... | Rust | 0 |
import socket
import sys
# function code:
# https://www.schneider-electric.com/en/faqs/FA308725/
# https://www.schneider-electric.com/en/faqs/FA295250/
# https://www.schneider-electric.com/en/faqs/FA249614/
TID = '0000'
PROTOCOL_ID = '0000'
UID = '01'
BIT_COUNT = '0001'
BYTE_COUNT = '01'
FC = '0f' # Write Multiple ... | Python | 1 |
str1 = "apple"
str2 = "apple"
str3 = "orange"
print(str1 == str2)
print(str1 != str3)
| Python | 1 |
from run_on_video.run import run_example
youtube_url = 'https://youtu.be/QTqvR6vVyfc?si=38hl4xafh7KWRbZX'
results_dict = run_example(youtube_url, 'A woman is walking on the street.') | Python | 1 |
leader2.shutdown()?;
leader1.shutdown()?;
relay1.shutdown()?;
relay2.shutdown()?;
core.shutdown()?;
controller.finalize();
Ok(ScenarioResult::passed(name))
}
use smart_pointers::List::{Cons, Nil};
use smart_pointers::MyBox;
use smart_pointers::Node;
use smart_pointers::CustomSmartPointer;... | Rust | 0 |
"""
Definition of the FFDNet model and its custom layers
Copyright (C) 2018, Matias Tassano <matias.tassano@parisdescartes.fr>
This program is free software: you can use, modify and/or
redistribute it under the terms of the GNU General Public
License as published by the Free Software Foundation, either
version 3 of t... | Python | 1 |
ar_links': [
('Start', 'index'),
('Installation', 'installation'),
('Introduction', 'intro'),
('User Guide', 'user_guide'),
('Examples', 'auto_examples/index'),
('API', 'references'),
],
# Render the next and previous page links in navbar. (Default: true)
'na... | Python | 1 |
mask={:b}, pid_mask={:b}",
self.tasks_mask,
pid_mask
);
return Err(KernelError::AccessDenied);
}
if ceiling as i32 > pi_stack.system_ceiling {
pi_stack.push_stack(ceiling)?;
// XXX(bitops): se... | Rust | 0 |
List = CreateCraftList([
Craft_03E8,
相位重置,
置换,
空间转移,
伪盐之桩,
死亡之指,
玻璃渣,
时空追放,
真实之镜,
龙皇炼狱火,
闪电之力,
... | Python | 1 |
import logging
from dataclasses import dataclass, field
from typing import Optional
from ..schemas import Schemas
from .misc import verify
# Copyright © 2018-2019 Damir Jelić <poljar@termina.org.uk>
#
# Permission to use, copy, modify, and/or distribute this software for
# any purpose with or without fee is hereby gr... | Python | 1 |
ess, cfg, srdr as reader, ftype), srdr);
}
fn new_parser_from_file(sess: parse_sess, cfg: ast::crate_cfg, path: &Path,
ftype: parser::file_type) -> parser {
let (p, _) = new_parser_etc_from_file(sess, cfg, path, ftype);
move p
}
fn new_parser_from_tt(sess: parse_sess, cfg: ast::crate_c... | Rust | 0 |
},
random_seed)
ptarl.set_first_phase()
trainer.fit(ptarl, dm)
ptarl = PTARLLightning.load_from_checkpoint(checkpoint_callback.best_model_path)
from sklearn.metrics import accuracy_score
preds = trainer.predict(ptarl, DataLoader(train_ds, 128))
y_hat = []
for pred ... | Python | 1 |
import enum as Enum
class Move(Enum.Enum):
a1 = (0, 0)
a2 = (1, 0)
a3 = (2, 0)
a4 = (3, 0)
a5 = (4, 0)
a6 = (5, 0)
a7 = (6, 0)
a8 = (7, 0)
b1 = (0, 1)
b2 = (1, 1)
b3 = (2, 1)
b4 = (3, 1)
b5 = (4, 1)
b6 = (5, 1)
b7 = (6, 1)
b8 = (7, 1)
c1 = (0, 2)
... | Python | 1 |
0xed, 0xa8, 0x50, 0x6c, 0x1f, 0xb0, 0xbb, 0xcc, 0x3f, 0x62, 0x62, 0x6f, 0xef, 0x07, 0x4b,
0xbf, 0x2d, 0x09, 0xa8, 0xc7, 0xc6, 0x08, 0xf3, 0xfa, 0x14, 0x82, 0xc9, 0xa6, 0x25, 0xd0,
0x0f, 0x75,
];
assert_eq!(hash, &expected_hash[..]);
}
#[test]
fn test_sum() {
let msg1 = b"hello".to_vec();
let msg2 = b"how a... | Rust | 0 |
import ast
import operator
import math
import statistics
import sys # 用于 stdin, stdout, stderr
from typing import Union, Dict, Tuple, Any, List
import sympy # 导入 sympy 模块本身
# SymPy imports
from sympy import (
sympify, Symbol, integrate, diff, sin, cos, tan, pi as sympy_pi,
atan, asin, acos, sqrt, exp as sympy_... | Python | 1 |
all_words.get(&(word.as_ref(), false))
.ok_or("Can't find corrected word")?.clone()
);
}
word_possibilities.push(
all_words.get(&(longest_phrase[longest_phrase.len() - 1].as_ref(), ends_in_prefix))
.ok_or("Can'... | Rust | 0 |
null()),
("version".into(), Kind::integer().or_null()),
])
}
#[cfg(test)]
mod tests {
use chrono::TimeZone;
use vector_common::btreemap;
use super::*;
test_function![
parse_syslog => ParseSyslog;
valid {
args: func_args![value: r#"<13>1 2020-03-13T20:45:38.119... | Rust | 0 |
rch(&4, &vec![1, 2, 3, 4]);
assert_eq!(index, Some(3));
let index = exponential_search(&3, &vec![1, 2, 3, 4]);
assert_eq!(index, Some(2));
let index = exponential_search(&2, &vec![1, 2, 3, 4]);
assert_eq!(index, Some(1));
let index = exponential_search(&1, &vec![1, 2, ... | Rust | 0 |
uler1d".to_owned()
}
fn initial_primitive(&self, x: f64, _y: f64, primitive: &mut [f64]) {
let xl: f64 = -2.0;
let xr: f64 = 2.0;
let dx: f64 = 0.05;
let gaussian = |x: f64, x0: f64| f64::exp(-(x - x0).powi(2) / dx.powi(2));
let step = |x: f64, x0: f64| {
i... | Rust | 0 |
let mut x = SIZE;
loop {
// boundaries were obtained with NN-based image recognition
let mut lo = x / 2;
let mut hi = x;
while lo < hi {
let mid = lo + (hi - lo + 1) / 2;
match has_beam(program, x, mid)? {
HasBeam::Yes => lo = mid,
... | Rust | 0 |
e case of nested structs/account data, all nested structs
// must be defined in the current program as well.
// - byte string literal (e.g. b"MY_SEED").
// - byte string literal constant (e.g. `pub const MY_SEED: [u8; 2] = *b"hi";`).
// - array constants.
//
pub fn parse(
ctx: &CrateContext,
accounts: &Accou... | Rust | 0 |
...
Unknown,
UnpivotOperator,
UnpivotConfig, // ((c1, c2) FOR v IN ((v1, v2) 1, (v3, v4) 3))
UpdateStatement,
WhenClause, // WHEN MATCHED THEN DELETE
WhileStatement,
WindowClause, // WINDOW x AS (PARTITION BY c1)
WindowExpr, // x AS (PARTITION BY c1 ORDER B... | Rust | 0 |
import os
import pickle
import numpy as np
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "2"
from tensorflow import keras
from keras import layers
from time import perf_counter
from sklearn.model_selection import train_test_split
list_of_images = 'list_of_images.pkl'
list_of_answers = 'list_of_answers.pkl'
open_images_fil... | Python | 1 |
26 => offset.x + offset.y + offset.z - offset.w, // ( 0, 1, -1, -1)
27 => -offset.x + offset.y + offset.z - offset.w, // ( 0, -1, -1, -1)
_ => unreachable!(),
}
}
}
);
let g0000 = call_gradient!(Vector4::<isize>::new(0, 0, ... | Rust | 0 |
ervice,
std::convert::{From, TryFrom, TryInto},
std::net::IpAddr,
};
impl From<config::ForwardingAction> for netconfig::FilterAction {
fn from(action: config::ForwardingAction) -> Self {
match action {
config::ForwardingAction::Accept => netconfig::FilterAction::Allow,
confi... | Rust | 0 |
vec![
std::sync::Arc::new(arrow2::array::Utf8Array::<i64>::from_slice(
participantid_array,
)) as std::sync::Arc<dyn arrow2::array::Array>,
std::sync::Arc::new(
arrow2::array::PrimitiveArray::from_vec(effectivedate_array).to(
... | Rust | 0 |
: OwnedHandle = snapshot
.try_into()
.map_err(|_| io::Error::last_os_error())?;
Ok(Toolhelp32ThreadIterator {
snapshot,
first: true,
})
}
}
impl FallibleIterator for Toolhelp32ThreadIterator {
type Item = THREADENTRY32;
type Error = io::Error... | Rust | 0 |
:
n = ret.next()
t += n
Commit()
except StopIteration:
break
except Exception as e:
Rollback()
log.exception(e)
... | Python | 1 |
# SPDX-FileCopyrightText: 2024-2025 ModelCloud.ai
# SPDX-FileCopyrightText: 2024-2025 qubitium@modelcloud.ai
# SPDX-License-Identifier: Apache-2.0
# Contact: qubitium@modelcloud.ai, x.com/qubitium
from ..base import BaseQModel
class HymbaQModel(BaseQModel):
supports_desc_act = [False]
require_trust_remote_co... | Python | 1 |
e(Serialize, Deserialize, Debug)]
struct ResolvedPathResult<'a> {
resolved_path: &'a str,
result_params: HashMap<&'a str, &'a str>,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct RequestedPathResult<'a> {
requested_path: &'a str,
err_code: u32,
err_msg: &'a str,
resolved_path_results: Ve... | Rust | 0 |
nwrap_numeric();
// floor will be nop if has no fractional digits.
if d.0.exponent() >= 0 {
return a;
}
let mut cx = numeric::cx_datum();
cx.set_rounding(Rounding::Floor);
cx.round(&mut d.0);
numeric::munge_numeric(&mut d.0).unwrap();
Datum::Numeric(d)
}
fn round_numeric_unary<'... | Rust | 0 |
eue("myqueue".to_string());
let _ignore = session.send_message(&destination, msg);
}
<filename>src/resources/mod.rs
use crate::components::Position;
use std::collections::HashSet;
pub struct DeltaTime(pub f32);
pub struct MaxPos(pub Position);
pub struct HitTargets(pub HashSet<specs::world::Index>);
#[derive(Def... | Rust | 0 |
ain_loader, val_loader, test_loader, args = load_cifar10(args, **kwargs)
else:
raise Exception('Wrong name of the dataset!')
return train_loader, val_loader, test_loader, args
if __name__ == "__main__":
import matplotlib.pyplot as plt
from sklearn.preprocessing import QuantileTransformer
c... | Python | 1 |
, View, VarSel, ValSel>
where
Handler: VariablesHandler + VariableContainerHandler<View> + Send + 'static,
View: VariableContainerView + Send + 'static,
VarSel: VariableSelector<Handler, View> + Clone + Send + 'static,
ValSel: ValuesSelector<Handler, View> + Clone + Send + 'static,
{
fn branch(
... | Rust | 0 |
pca_dim = 16
job_name = 'cfa_test'
from pylearn2.datasets.mnist import MNIST
from pylearn2.pca import CovEigPCA
import theano.tensor as T
from theano import function
from models import expand
from pylearn2.utils import serial
import time
import SkyNet
import gc
import numpy as N
print 'Loading MNIST train set'
t1 = t... | Python | 1 |
2, ParseIntError>```
///
/// # Example
/// **** Already added to loggics file. Be careful. Editing code can break stability of devices. *****
/// ```
/// let mut config = config_parser::new(); // create object of config_parse
/// let val_u32: u32 = config.parse("55").unwrap(); // getting value u... | Rust | 0 |
// The same group element (self.V) has to be multiplied by each element in P_multiple, so we create a window table
let wits = multiply_field_elems_with_same_group_elem(
params.P.into_projective(),
P_multiple.as_slice(),
);
let wits_affine = E::G1Projective::batch_no... | Rust | 0 |
tartWindowProc(hWnd: HWND,uMsg: UINT,wParam: WPARAM,lParam: LPARAM)->LRESULT {
0
}
/*
CWindowImplBaseT< TBase, TWinTraits >* pThis = (CWindowImplBaseT< TBase, TWinTraits >*)hWnd;
// set a ptr to this message and save the old value
_ATL_MSG msg(pThis->m_hWnd, uMsg, wParam, lParam);
const _ATL_MSG* p... | Rust | 0 |
predicted probabilities for X_test_dtm (poorly calibrated)
y_pred_prob = nb.predict_proba(X_test_dtm)[:, 1]
y_pred_prob
# calculate AUC
metrics.roc_auc_score(y_test, y_pred_prob)
# ## Part 6: Comparing models
#
# We will compare multinomial Naive Bayes with [logistic regression](http://scikit-learn.org/stable/mod... | Python | 1 |
"""
cron: 30 7 * * * dcjd.py
new Env("微信小程序-东呈酒店")
env add dcjd_data
仅用于测试和学习研究,禁止用于商业用途,不能保证其合法性,准确性,完整性和有效性,请根据情况自行判断;您必须在下载后的24小时内从计算机或手机中完全删除以上内容。
如果任何单位或个人认为该项目的脚本可能涉嫌侵犯其权利,则应及时通知并提供身份证明,所有权证明,我们将在收到认证文件后删除相关脚本。
"""
import json
import ApiRequest
from notify import send
title = '微信小程序-东呈酒店'
tokenName = 'dcjd_data... | Python | 1 |
"overflowY": "auto",
"padding-left": "0.25in",
"padding-right": "0.25in",
"width": "5.5in",
},
style_cell={
... | Python | 1 |
/// get_hash calculate average hash.
///
/// # Examples
///
/// ```
/// let img = image::open("testdata/aws_batch.png").unwrap();
/// assert_eq!(simimgrs::get_hash(img), 18446744073709551615)
/// ```
pub fn get_hash(img: image::DynamicImage) -> usize {
let mut sum_pixels: usize = 0;
let mut pixels: Vec<usize>... | Rust | 0 |
ve(Debug, Serialize)]
struct JsonRpcRequest<T> {
id: u64,
jsonrpc: &'static str,
method: JsonRpcMethod,
params: T,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
enum BlockResponseScopeOptions {
TxnHash,
FullTxns,
FullTxnAndReceipts,
}
#[serde_as]
#[derive(Seri... | Rust | 0 |
func_c.bytes())
.chain(continuous.bytes())
.map(|c| c as i64)
.collect();
program.code[0] = 2;
// apparently the outut is the starting map, a print-out of main and the functions, then the
// ending map, a blank line, and finally the number of dust... so, what we really care about is... | Rust | 0 |
}
}
// whitespace
if is_whitespace(b) {
cx.i += 1;
advance_while(cx, bs, is_whitespace);
return SK::Whitespace;
}
// alphanumeric identifiers (include type variables) and keywords
match alpha_num(b) {
Some(AlphaNum::Prime) => {
cx.i += 1;
advance_while(cx, bs, |b| alpha_num(b).is... | Rust | 0 |
; 496usize],
#[doc = "0x704 - Unspecified"]
pub vregmain: VREGMAIN,
_reserved4: [u8; 504usize],
#[doc = "0x900 - Unspecified"]
pub vregradio: VREGRADIO,
_reserved5: [u8; 504usize],
#[doc = "0xb00 - Unspecified"]
pub vregh: VREGH,
}
#[doc = r"Register block"]
#[repr(C)]
pub struct VREGMAI... | Rust | 0 |
setattr(
user_store_mod.tempfile, "NamedTemporaryFile", _raising_named_tmpfile, raising=True
)
with pytest.raises(OSError, match=r".+") as e:
user_store_mod._save_store({"u": {"api_key": "x", "project_id": "y"}}) # noqa: SLF001
assert MSG_ERROR_SAVING_USER_STORE.format(error="disk full") ... | Python | 1 |
{
assert_eq!(a, b);
}
}
proptest! {
#[test]
fn stake_list_size_calculation(test_amount in 0..=100_000_u32) {
let validators = ValidatorList::new(test_amount);
let size = get_instance_packed_len(&validators).unwrap();
assert_eq!(ValidatorLi... | Rust | 0 |
_lineend_GE_SQUARE_CAP: R_GE_lineend = 3;
pub type R_GE_lineend = u32;
pub const R_GE_linejoin_GE_ROUND_JOIN: R_GE_linejoin = 1;
pub const R_GE_linejoin_GE_MITRE_JOIN: R_GE_linejoin = 2;
pub const R_GE_linejoin_GE_BEVEL_JOIN: R_GE_linejoin = 3;
pub type R_GE_linejoin = u32;
#[repr(C)]
#[derive(Copy, Clone)]
pub struct ... | Rust | 0 |
uts':
write_data._bytes_feature(['[ 5 2 ]', '[ 3 6 9 ]']),
'program':
write_data._bytes_feature([str(program)]),
}))
self.assertEqual(tf.train.Example.FromString(result), expected_result)
@parameterized.parameters(
# These cases are chosen... | Python | 1 |
ion::max_profit(prices), res);
}
<filename>src/lib/parser/module.rs<gh_stars>0
use super::expr::{
Expr,
BasicExpr,
TypedExpr,
Type,
SymbolTable,
TypeChecker,
TypeResult
};
#[derive(Debug)]
pub enum Definition<E: Expr> {
Function(String, Vec<(String, Type)>, Box<E>)
}
/// Struct that re... | Rust | 0 |
import os
import re
# Define helper functions for classification
def is_vietnamese(char):
return bool(re.match(r'[a-zA-Záàảãạăắằẳẵặâấầẩẫậđéèẻẽẹêếềểễệíìỉĩịóòỏõọôốồổỗộơớờởỡợúùủũụưứừửữựýỳỷỹỵ]', char))
def is_chinese(char):
return '\u4e00' <= char <= '\u9fff'
def is_emoji(char):
emoji_ranges = [
(0x1... | Python | 1 |
train_dataloaders=DataLoader(train_dataset, batch_size=None, num_workers=0),
val_dataloaders=DataLoader(val_dataset, batch_size=None, num_workers=0),
ckpt_path=(
cfg.training.ckpt_path
if "ckpt_path" in cfg.training and cfg.training.ckpt_path
else None
)... | Python | 1 |
lider = QSlider(Qt.Horizontal)
self.chunk_overlap_slider.setRange(0, 100) # 范围: 0ms 到 100ms (最大值会动态调整)
self.chunk_overlap_slider.setValue(10) # 默认值: 10ms
self.chunk_overlap_slider.setToolTip(
"设置相邻分析块之间的重叠量(单位:毫秒)。\n"
"重叠可以平滑块与块之间的过渡,尤其有助于改善F0曲线在拼接处的连续性。\n"
... | Python | 1 |
)
return EffectResult(
effect_id=effect.effect_id,
success=success,
actual_intensity=effect.intensity * (0.9 if success else 0.5),
hardware_used=[h.get_capability().device_id for h in hardware],
execution_time... | Python | 1 |
ert_eq!(regular, gradual);
}
}
// This file is part of Substrate.
// Copyright (C) 2017-2020 Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Publ... | Rust | 0 |
moryAccessWidth) {
use MemoryAccess::*;
use MemoryAccessWidth::*;
let page = (addr >> 24) as usize;
// TODO optimize out by making the LUTs have 0x100 entries for each possible page ?
let cycles = if page > 0xF {
// open bus
1
} else {
... | Rust | 0 |
})
.chain(std::iter::once(","))
)
.collect();
s.pop();
Ok(s)
}pub use self::{
decls::*,
term::{check, infer, simplify},
};
pub const ERROR_MSG: &str = "Please report this as a bug.";
/// Type check a function clause.
mod clause;
/// Type check data type & cons... | Rust | 0 |
);
}
// Consume the pending message.
let mut buffer = Vec::<u8>::with_capacity(5);
let mut handles = Vec::with_capacity(5);
expect_eq!(
OakStatus::OK,
oak::channel_read(in_channel, &mut buffer, &mut handles)
);
expect_eq!(3, buff... | Rust | 0 |
;
let alive_map = create_alive_map(&events);
let mut alive_tuples: Vec<(&i32, &isize)> = alive_map.iter().collect();
alive_tuples.sort_by_key(|&(_, v)| -v);
println!("");
for (k, v) in alive_tuples {
println!("{}: {}", k, v);
}
}
#[test]
fn test_parsing() {
let time = chron... | Rust | 0 |
essage)
if add_to_queue:
await event.wait()
if listener.isCancelled:
return
async with queue_dict_lock:
non_queued_dl.add(listener.mid)
async with task_dict_lock:
task_dict[listener.mid].queued = False
... | Python | 1 |
# Generated by Django 3.1.1 on 2020-09-22 15:56
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("testplans", "0008_remove_autofield"),
]
operations = [
migrations.AlterField(
model_name="historicaltestplan",
name="... | Python | 1 |
d = AccountId::from([0u8; 32]);
pub const FeedPledgedBalance: Balance = 500 * DOLLARS; // todo : pledge 500 dico?
pub const withdrawExpirationPeriod: BlockNumber = 10 * MINUTES; // TODO: 5 * DAYS;
}
type DicoDataProvider = pallet_oracle::Instance1;
impl pallet_oracle::Config<DicoDataProvider> for Runtime {
t... | Rust | 0 |
'0.1', '1', '2.5'."
)
# The sort direction will affect the quantity-sorted table.
parser.add_argument(
"--sort-dir",
choices=["asc", "desc"],
default="desc",
help="Sort direction for the quantity column (default: desc)."
)
args = parser.parse_args()
group_size_f... | Python | 1 |
import logging
import os
from datetime import datetime
import django
import pytz
from execution.service.blueprints.market_data import get_account_data
from shared.utils.decorators import handle_db_connection_error
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "database.settings")
django.setup()
from database.mode... | Python | 1 |
ere_clause}
ORDER BY q.question_id, a.score DESC;
"""
df = pd.read_sql_query(query, conn, params=params)
# Links
if db_source == "StackOverflow":
df["Link"] = df["Question_ID"].apply(lambda qid: f'<a href="https://stackoverflow.com/q/{qid}" target="_blank">Link<... | Python | 1 |
from core.application.protocols.use_case_protocol import UseCaseProtocol
from modules.user.application.create_customer_use_case import (
CreateUserInput,
CreateUserUseCase,
)
from modules.user.repositories.user_repository_in_memory import UserRepositoryInMemory
from modules.user.repositories.user_repository_pro... | Python | 1 |
import numpy as np
class CosineDecayLR(object):
def __init__(self, optimizer, T_max, lr_init, lr_min=0., warmup=0):
"""
a cosine decay scheduler about steps, not epochs.
:param optimizer: ex. optim.SGD
:param T_max: max steps, and steps=epochs * batches
:param lr_max: lr_m... | Python | 1 |
--baud': '9600',
'--help': False,
'--timeout': '30',
'--version': False,
'<host>': '127.0.0.1',
'<port>': '80',
'serial': False,
'tcp': True}
See also
--------
* For video introduction see http://docopt.org
* Full documentation is available in README.rst as well as on... | Python | 1 |
import mysql.connector
import datetime # Import the datetime module
# Connect to MySQL
myeb = mysql.connector.connect(
host="localhost",
user="root",
password="root",
database="tender_management_system"
)
cursor = myeb.cursor()
# Function to validate date format
def is_valid_date(date_str):
try:
... | Python | 1 |
InterruptDelivery1,
PostedInterrupt1,
PostedInterrupt2,
PostedInterrupt3,
PostedInterrupt4,
PostedInterrupt5,
VPID,
EptMemTypeUC,
EptMemTypeWB,
EptIncorrectPageWalkLength,
EptAccessedDirty,
EptReservedBitsLow,
PmlWithNoEpt,
PmlAddressAligned,
UnrestrictedGuestWith... | Rust | 0 |
none;
setenv(~"HOME", ~"/home/MountainView");
assert os::homedir() == some(Path("/home/MountainView"));
setenv(~"HOME", ~"");
setenv(~"USERPROFILE", ~"/home/MountainView");
assert os::homedir() == some(Path("/home/MountainView"));
setenv(~"HOME", ~"/home/MountainView... | Rust | 0 |
let interval = now - s;
assert!(interval >= Duration::from_millis(900) && interval < Duration::from_secs(2));
s = now;
}
}
}
<reponame>Electrux/Rust-Code<gh_stars>0
extern crate discord;
extern crate electrux_bot;
use discord::Discord;
use discord::model::Event;
use electr... | Rust | 0 |
# Any copyright is dedicated to the Public Domain.
# http://creativecommons.org/publicdomain/zero/1.0/
from nagini_contracts.contracts import *
from typing import List
def list_loop() -> None:
b = [1, 2, 3]
a = [b, [4, 5]]
for c in a:
Invariant(Forall(a, lambda l: (Acc(list_pred(l)), [])))
... | Python | 1 |
_version(V::constant());
match result {
Success(()) => Success(self.transit()),
Info(()) => Success(self.transit()),
Error(()) => Success(self.transit()),
}
}
/// Before an application allocates a connection which specification it follows. Currently
/// t... | Rust | 0 |
Wicklow Mountains",
"1DDR-IE-LK" => "Kildare",
"1DDR-IE-LL" => "Laois",
"1DDR-IE-LM" => "Meath",
"1DDR-IE-LMN" => "Newgrange",
"1DDR-IE-LN" => "Longford",
"1DDR-IE-LO" => "Offaly",
"1DDR-IE-LW" => "Westmeath",
"1DDR-IE-LX" => "Wexford",
"1DDR-IE-LY" => "Kilkenny",
"1DDR-IE-M" => ... | Rust | 0 |
import os, json, requests
class SlackConnector:
def __init__(self):
self.url = os.getenv("SLACK_WEBHOOK_URL")
def send(self, classification: dict):
emoji = "🚨" if classification["severity"] in ("high", "critical") else "🔔"
text = (
f"{emoji} *{classification['type']}* in ... | Python | 1 |
import pytest
from llmcompressor.core.state import Data, Hardware, ModifiedState, State
from llmcompressor.metrics import BaseLogger, LoggerManager
@pytest.mark.smoke
def test_state_initialization():
state = State()
assert state.model is None
assert state.teacher_model is None
assert state.optimizer ... | Python | 1 |
board.set_cell(winner, Cell::TopLeft);
board.set_cell(loser, Cell::BottomCentre);
board.set_cell(winner, Cell::Centre);
board.set_cell(loser, Cell::BottomLeft);
board.set_cell(winner, Cell::BottomRight);
let mut winner_message = String::new();
if board.has_player_... | Rust | 0 |
file is part of the uutils coreutils package.
//
// (c) <NAME> <<EMAIL>>
//
// For the full copyright and license information, please view the LICENSE file
// that was distributed with this source code.
//
use super::Uname;
use std::borrow::Cow;
use std::io::{self, Read};
use std::fs::File;
pub struct PlatformInfo {
... | Rust | 0 |
cmd,
clock,
deps,
start_time_ms,
missing_deps: 0,
}
}
pub fn get_missing_deps(&self) -> usize {
self.missing_deps
}
pub fn set_missing_deps(&mut self, missing_deps: usize) {
// this value can only be written if it's at zero... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.