text string | label_name string | labels int64 |
|---|---|---|
let data = build_data();
let pinyin_index = generate_pinyin_data(&data)?;
let heteronym_index = generate_heteronym_table(&data, &pinyin_index)?;
generate_char_table(&data, &pinyin_index, &heteronym_index)?;
// 输出这行以保证改动项目的其他文件不会触发编译脚本重新执行
println!("cargo:rerun-if-changed=build.rs");
Ok(())
}
fn... | Rust | 0 |
subgraph(mods: &Vec<EntityModification>, id: &DeploymentHash) -> bool {
mods.iter().all(|md| &md.entity_key().subgraph_id == id)
}
<filename>crates/runtime/src/lib.rs<gh_stars>1-10
//! Runtime library support for Wasmtime.
#![deny(missing_docs, trivial_numeric_casts, unused_extern_crates)]
#![warn(unused_import_br... | Rust | 0 |
clone(blockchain);
async move {
stream
.for_each_concurrent(Self::MAX_CONCURRENT_HANDLERS, |(msg, peer)| async {
let blockchain = Arc::clone(&blockchain);
tokio::spawn(async move {
trace!(
"[{... | Rust | 0 |
ion, out_translation);
assert_approx_eq!(
in_mat,
Mat4::from_scale_rotation_translation(out_scale, out_rotation, out_translation),
1e-5
);
// negative scale
let in_scale = Vec3::new(4.0, -1.0, -2.0);
let in_mat = Mat4::from_scale_rotation_translation(in_scale, in_rotation, i... | Rust | 0 |
= neighbor.node_id;
has_neighbor = true;
break;
}
}
}
walk.reverse();
// Extend forwards
has_neighbor = true;
current_node = graph.edge_endpoints(edge_index).to_node;
while has_neighbor {
/... | Rust | 0 |
if let Some(mut data) = suppliers.pop() { inputs.7.as_mut().map(|x| x.send_batch(&mut data)); } else { if seal { inputs.7 = None; } }
// catch all inputs up to the same (next) round.
let next_round = 1 + 8 * (round + 1) * physical_batch;
inputs.0.as_mut().map(|x| x.advance_to(ne... | Rust | 0 |
ET = 0x1A,
CLOSE_BRACKET = 0x1B,
BACKSLASH = 0x2B,
KEYBOARD_DELETE = 0x153,
END = 0x14F,
PAGE_DOWN = 0x151,
NUM_SEVEN = 0x47,
NUM_EIGHT = 0x48,
NUM_NINE = 0x49,
NUM_PLUS = 0x4E,
CAPS_LOCK ... | Rust | 0 |
(minecraft::chat::HoverEvent::ShowText(Box::new(Chat::from(&*attachment.url))));
extra
});
}
tellraw(&World::new(world_name), "@a", &chat).await?;
}
Ok(())
}))
.event_handler(serenity_utils::handler::user... | Rust | 0 |
from dotenv import load_dotenv
import os
load_dotenv()
DATA_COLLECTION_BUCKET = os.environ.get("DATA_COLLECTION_BUCKET", "")
AWS_ACCESS_KEY_ID = os.environ.get("AWS_ACCESS_KEY_ID", "")
AWS_STORAGE_BUCKET_NAME = os.environ.get("AWS_STORAGE_BUCKET_NAME", "")
AWS_SECRET_ACCESS_KEY= os.environ.get("AWS_SECRET_ACCESS_KEY"... | Python | 1 |
eferences().setValue(setting_key_str, current_version)
Logger.log("i", "Reading firmware version of %s: checked = %s - latest = %s",
self._machine_name, checked_version, current_version)
# The first time we want to store the current version, the notification w... | Python | 1 |
mel()
conv_b = torch.from_numpy(weights[ptr:ptr + num_b]).view_as(conv_layer.bias.data)
conv_layer.bias.data.copy_(conv_b)
ptr += num_b
# Load conv. weights
num_w = conv_layer.weight.numel()
conv_w = torch.from_n... | Python | 1 |
rea choice
inside_choice = request.form.get('inside_choice')
if inside_choice == '1':
config['inside_area_above'] = True
elif inside_choice == '2':
config['inside_area_above'] = False
else:
return jsonify({'status': 'error', 'message': 'Invalid inside area choice'})
# Se... | Python | 1 |
1),(0,1)]).unwrap().lock().unwrap().mesh().layers()[2].lock().unwrap()), 4);
}
#[test]
//A Parent network has two layers, each with a child network, each child has 2 meshes in on layer.
// Child network 1 receives outputs from child network 2's outputs.
fn create_links_r_w2n_w2m_wn1out0_all() {
let attribute = At... | Rust | 0 |
SPONSE_REJECT,
gtk.STOCK_OK, gtk.RESPONSE_ACCEPT ))
dialog.set_default_response(gtk.RESPONSE_ACCEPT)
dialog.set_has_separator(False)
dialog.set_resizable(False)
dialog.set_border_width(8)
label = gtk.Label(_('Enter a new title for the Terminator... | Python | 1 |
from abc import ABC
from llama_index import GPTVectorStoreIndex, SimpleDirectoryReader, get_response_synthesizer
from llama_index.retrievers import VectorIndexRetriever
from llama_index.query_engine import RetrieverQueryEngine
from llama_index.postprocessor import SimilarityPostprocessor
from llama_index.node_parser i... | Python | 1 |
def one_hot_array(self, i, n):
return map(int, [(ix == i) for ix in range(n)])
| Python | 1 |
from django.urls import path
from. import views
urlpatterns = [
path('register/',views.register,name='register'),
path('user_Details/',views.user_Details,name='user_Details'),
path('user_Update/',views.user_Update,name='user_Update'),
path('forgot_password/',views.forgot_password,name='forgot_password'... | Python | 1 |
x263a => 0x01,
0x263b => 0x02,
0x263c => 0x0f,
0x2640 => 0x0c,
0x2642 => 0x0b,
0x2660 => 0x06,
0x2663 => 0x05,
0x2665 => 0x03,
0x2666 => 0x04,
0x266a => 0x0d,
0x266b => 0x0e,
_ => 0xfe
}
}
<gh_stars>0
use crate::lib::*;
/// A t... | Rust | 0 |
_ptr(self.0.env);
let (__jni_class, __jni_method) = __jni_env.require_class_method("android/hardware/SensorListener\0", "onSensorChanged\0", "(I[F)V\0");
__jni_env.call_void_method_a(self.0.object, __jni_method, __jni_args.as_ptr())
}
}
/// [onAccuracyChanged... | Rust | 0 |
2)
eavesdrop_acc_mean.append(mean_tick)
plt.figure()
plt.plot(x, accuracies, label=f'{length} bits', color=colors[idx])
plt.xlabel('Trial')
plt.ylabel('Sift Key Accuracy (QBER noise)')
plt.title(f'BB84: Sift Key Accuracy ({length} bits)')
plt.ylim(0.5, 1.0)
yticks = list(np.arange(0.5,... | Python | 1 |
ub const GRID_BOT_EDGE: f32 = GRID_CENTER_Y - 0.5 * GRID_SIZE;
pub const NUM_OFFSET_X: f32 = 0.0 * CELL_SIZE;
pub const NUM_OFFSET_Y: f32 = 0.03 * CELL_SIZE;
}
// QUALITY: reduce asset loading code duplication dramatically
pub mod assets {
use crate::graphics::BACKGROUND_COLOR;
use super::*;
// V... | Rust | 0 |
panic!("Program failed. See above for output.")
}
}
}
}
fn compile_test_file(input_file: PathBuf, opt_mode: OptMode) -> Directory {
let file = fs::read_to_string(&input_file)
.unwrap_or_else(|_| panic!("Could not read test file {}", input_file.display()));
let mut config = Com... | Rust | 0 |
# 5. Escreva um programa para ler o nome e o sobrenome de uma pessoa e escrevê-los na seguinte forma: sobrenome seguido por uma vírgula e pelo nome
nome = input('escreva seu nome: ')
sobrenome = input("escreva seu sobrenome: ")
print(f'{sobrenome}, {nome}') | Python | 1 |
);
schema::authors::table
.filter(schema::authors::id.eq(any(reference_author_ids)))
.load::<Author>(&conn.0)
.map_err(|err| BadRequest(Some(err.to_string())))
}
#[cfg(test)]
mod test {
use rocket::http::{ContentType,Status};
use crate::{json_string};
use crate::app::test::{re... | Rust | 0 |
ref fields) => &fields.named,
syn::Fields::Unnamed(ref fields) => &fields.unnamed,
syn::Fields::Unit => panic!("Types with no fields are not supported"),
};
// If there is only one field, it is the inner field.
if fields.len() == 1 {
let field = &fields[0];
if field.ident.is_... | Rust | 0 |
import random
from hangman_words import word_list
from hangman_arts import stages, logo
print(logo)
# Randomly choose a word from the list of words and store
chosen_word = random.choice(word_list)
# Number of lives = 6
lives = 6
# Empty list
display = []
# Create number of dashes as in the chosen_word in a list
... | Python | 1 |
i_l.len()/2;
if i_l.len()%2 == 0 { // eve
return ( i_l[mid-1] as f64 + i_l[mid] as f64 )/ 2.
} else { // odd
return i_l[mid] as f64
}
}
// 最頻値
pub fn mode(i_l:& [i32]) -> Vec<i32> {
use std::collections::HashMap;
let mut num_count:HashMap<String,i32> = HashMap::new();
for n in i_l.iter... | Rust | 0 |
return "Address book is empty."
return "\n".join(str(record) for record in book.data.values())
@input_error
def add_birthday(args, book):
name, birthday = args
record = book.find(name)
if record is None:
raise KeyError("Contact not found.")
record.add_birthday(birthday)
return... | Python | 1 |
(width)?;
let height = usize::try_from(height)?;
Ok(self.liquid_rescale_image(width, height, delta_x, rigidity)?)
}
fn implode(&self, _: JNIEnv, _: JObject, amount: jdouble, method: jint) -> JNIResult<()> {
#[cfg(target_os="android")]
let method = u32::try_from(method)?;
... | Rust | 0 |
ception as e:
self.write_log(f"获取行情失败: {e}", level="ERROR")
def send_order(self, req: OrderRequest) -> str:
"""
发送委托
"""
if not self.connected:
self.write_log("网关未连接,无法发送委托", level="ERROR")
return ""
# 生成本地委托号
local_or... | Python | 1 |
OPT);
let rename = subcmd_args.value_of(RENAME_OPT);
let current = subcmd_args.is_present("current");
// make sure the user provided something useful for a timestamp
let time_opt = subcmd_args.value_of("timestamp");
if time_opt.is_some() && parse_datetime(time_opt).is_none() {
error_message... | Rust | 0 |
fo/qianggao/llama3/Llama-Chinese/output/04-27_llama3_pretrain_wudao___bs_1536_maxlen_1024_pad_right_lr_2e-4_format_wudao/checkpoint-1920",
),
parser.add_argument(
"--output_dir",
type=str,
help="Checkpoint path",
default="/apdcephfs_qy3/share_301372554/share_info/qianggao/llama3/... | Python | 1 |
pub coaches: std::vec::Vec<Coach>,
#[serde(rename = "teams")]
pub teams: std::vec::Vec<Team>,
#[serde(rename = "roundResults")]
pub round_results: std::vec::Vec<RoundResult>,
}
/// MatchInfo data object.
#[derive(Clone, Debug)]
#[derive(serde::Serialize, serde::De... | Rust | 0 |
pth_2d = list()
if hhr_fn != None:
L0 = len(msa[0])
dmin = 2.0
dmax = 20.0
nbins = 18
dbins = np.linspace(dmin, dmax, nbins+1)
hhr = parse_hhr(hhr_fn, ffdb.index, seqID)
for i, hit in enumerate(hhr[:10]):
# extract template from FFindexDB
... | Python | 1 |
from typing import List
import pandas as pd
from app.services import upbit, yahoo, kis
from data.coins_info import upbit_pairs
from data.stocks_info import KRX_NAME_TO_CODE
from .analyzer import Analyzer, DataProcessor
class UpbitAnalyzer(Analyzer):
"""Upbit 암호화폐 분석기"""
# 상수를 클래스 속성으로 정의합니다.
MIN_TRADE_... | Python | 1 |
ts
# own loop, or by checking the `input_is_ready` function regularly.
self.inputhook(InputHookContext(self._r, input_is_ready))
# Flush the read end of the pipe.
try:
# Before calling 'os.read', call select.select. This is required
# when the gevent monkey patch... | Python | 1 |
}
.build()
}
}
impl From<std::io::Error> for FuseQueryError {
fn from(err: std::io::Error) -> Self {
Internal {
message: err.to_string(),
}
.build()
}
}
impl From<std::fmt::Error> for FuseQueryError {
fn from(err: std::fmt::Error) -> Self {
Int... | Rust | 0 |
Mi", "Gi", "Ti", "Pi", "Ei", "Zi", "Yi"];
pub fn convert_to_unit(mut count: f32) -> (f32, &'static str) {
let mut suffix_index = 0;
while count > 1024. && suffix_index + 1 < ITER_UNITS.len() {
count /= 1024.;
suffix_index += 1;
}
(count, ITER_UNITS[suffix_index])
}
//! Constant Propag... | Rust | 0 |
# player = MediaPlayer()
# player.add_media(audio)
# player.add_media(video)
# player.add_media(podcast)
# TODO: 测试播放功能
# player.play_all()
# print(f"总时长: {player.get_total_duration()} 秒")
pass
def test_payment_strategy():
"""测试支付策略模式"""
print("=== 测试支付策略模式 ===")
... | Python | 1 |
#! /usr/bin/python
#-*- coding: utf-8 -*-
import datetime
today = datetime.datetime.now()
Autocompleter = {}
Autocompleter["directive"] = ["define", "include", "ifndef", "endif", "undef", "if", "elif", "else", "error", "warning"]
#from const.h
const = [ "PI", "HALF_PI", "TWO_PI", "DEG_TO_RAD", "RAD_TO_DEG", "NULL", ... | Python | 1 |
"nutdev".into(),
client_ip: "127.0.0.1".into(),
}
);
test_encode_decode!(
["BEGIN", "LIST", "VAR", "nutdev"] <=>
Sentences::BeginListVar {
ups_name: "nutdev".into(),
}
);
test_encode_decode!(
["E... | Rust | 0 |
"""
# Definition for a Node.
class Node:
def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None):
self.val = int(x)
self.next = next
self.random = random
"""
class Solution:
def copyRandomList(self, head: 'Optional[Node]') -> 'Optional[Node]':
if head == None:
... | Python | 1 |
#9663
def solve(row, n):
global sum
if row >= n:
sum += 1
return
else:
for i in range(n):
if not col[i] and not inc[row+i] and not dec[row-i+n-1]:
col[i] = inc[row+i] = dec[row-i+n-1] = 1
solve(row+1, n)
col[i] = inc[row+i] = dec[row-i+n-1] = 0
if __name__ == '__main__'... | Python | 1 |
:
print("❌ VERDICT: Sampling in ambient space")
print("="*80)
except Exception as e:
logger.error(f"❌ Fixed analysis failed: {e}")
import traceback
traceback.print_exc()
def main():
"""Main execution."""
checkpoint_path = "ou... | Python | 1 |
::p;
/// fn custom_xmul(a: u32, b: u32) -> (u32, u32) {
/// let (lo, hi) = p32(a).widening_mul(p32(b));
/// (u32::from(lo), u32::from(hi))
/// }
///
/// #[p(
/// width=32,
/// usize=false,
/// u=u32,
/// i=i32,
/// // naive,
/// xmul=custom_xmul,
/// )]
/// type my_p32;
///
/// # fn main... | Rust | 0 |
# O(n**2)
def fun1(n):
i = 1 # C
sumA = 0 # C
while i < n * n: # While loop = O(N^2)
sumA += 1 # C
i += 3 # C
# O(log(n))
def fun2(n):
i = 1 # C
sumB = 0 # C
while i < n * n: # While loop = O(log (N))
... | Python | 1 |
if type_ in ["exam", "essay", "homework"]:
break
else:
print("Invalid input! Please enter 'exam', 'essay', or 'homework'.")
days_until_due = int(input("In how many days is it due?: "))
assignments.append({
"name"... | Python | 1 |
io::Result<usize> {
if self
.ctx
.check_nonblocking(|b| self.sys.set_nonblocking(b))?
|| !self.ctx.check_context(|b| self.sys.set_nonblocking(b))?
{
return self.sys.write_vectored(bufs);
}
#[cfg(unix)]
{
self.io.reset(... | Rust | 0 |
import pytest
from spacy.tests import util
from spacy_legacy.architectures.tok2vec import Tok2Vec_v1, MultiHashEmbed_v1, CharacterEmbed_v1
from spacy_legacy.architectures.tok2vec import MaxoutWindowEncoder_v1
from spacy_legacy.architectures.tok2vec import MishWindowEncoder_v1
from spacy_legacy.architectures.tok2vec imp... | Python | 1 |
snapshots of the
/// database.
pub const NUM_SNAPSHOTS: &str = property!("num-snapshots");
/// "rocksdb.oldest-snapshot-time" - returns number representing unix
/// timestamp of oldest unreleased snapshot.
pub const OLDEST_SNAPSHOT_TIME: &str = property!("oldest-snapshot-time");
/// "rocksdb.num-live-versions" - retu... | Rust | 0 |
.or_else(|e| {
eprintln!("Got websocket error = {:?}", e);
Ok(OwnedMessage::Close(None))
});
// forward transitions
let push = r.and_then(|x| {
Answer::new([0u32; 4], Ok(AnswerAction::Tr... | Rust | 0 |
ctions = get_connections(&lines);
let graph = build_dependency_graph(connections);
let mut workers: Vec<Worker> = vec![Worker::new(1), Worker::new(2), Worker::new(3), Worker::new(3), Worker::new(4)];
let mut total_ticks = 0;
let mut order = String::new();
let mut owned: HashSet<&str> = HashSet::n... | Rust | 0 |
* 32)),
["--input-coin", bytes32([0] * 32).hex(), "--input-coin", bytes32([1] * 32).hex()],
),
],
)
@pytest.mark.parametrize(
"largest_first",
[ValueAndArgs(False, []), ValueAndArgs(True, ["--largest-first"])],
)
def test_combine_parsing(
id: ValueAndArgs,
target_amount: ValueAn... | Python | 1 |
info: [Option<Satellite>; 4],
}
fn parse_gsv_sat_info(i: &[u8]) -> IResult<&[u8], Satellite> {
let (i, prn) = number::<u32>(i)?;
let (i, _) = char(',')(i)?;
let (i, elevation) = opt(number::<i32>)(i)?;
let (i, _) = char(',')(i)?;
let (i, azimuth) = opt(number::<i32>)(i)?;
let (i, _) = char(',')... | Rust | 0 |
from collections.abc import Mapping
from typing import Any, TypeVar
from attrs import define as _attrs_define
from attrs import field as _attrs_field
T = TypeVar("T", bound="NoteContentBlock")
@_attrs_define
class NoteContentBlock:
"""A particular block of content in a note.
Attributes:
correlation... | Python | 1 |
user_invitations, UseCaseError};
use sos21_domain::test;
#[tokio::test]
async fn test_general() {
let user = test::model::new_general_user();
let app = test::build_mock_app()
.users(vec![user.clone()])
.build()
.login_as(user)
.await;
... | Rust | 0 |
torch.cuda.amp.GradScaler()
progress = tqdm(total=args.steps)
while progress.n < args.steps:
for src, dst in loader:
with torch.cuda.amp.autocast():
y_pred = model(src) # forward
loss = criterion(y_pred, dst) # loss
# backward
optimizer.zero_grad()
loss.backward()
optimizer.step()
schedu... | Python | 1 |
s
except Exception as e:
print(f"Error in metrics publisher: {e}")
await asyncio.sleep(10)
# Background task for trend monitoring
async def trend_monitoring_service():
"""Background service for continuous trend monitoring"""
while True:
try:
tren... | Python | 1 |
_EXP_IMAGE_PATH, overlay_out, LONG_EXP_OVERLAY)
# Stage 4: connected components visualizations (area-filtered view) for EACH chunk image
for or_img in chunk_imgs:
all_vis, filt_vis = _cc_paths_for_chunk(or_img)
connected_components_visuals(
or_img,
all_vis,
f... | Python | 1 |
self.apply_filter(new);
None
}
},
AppEvent::SetMeta(meta) => match meta {
SetMeta::Rating(rating) => self.set_rating(rating.clone()).none(),
},
AppEvent::Slideshow(slideshow) => ... | Rust | 0 |
f ready_no(message: Message, state: FSMContext):
await state.clear()
async with aiosqlite.connect(DB_PATH) as db:
cur = await db.execute("SELECT 1 FROM sessions WHERE tg_id = ?", (message.from_user.id,))
logged_in = await cur.fetchone()
kb = logged_in_kb if logged_in else main_kb
await m... | Python | 1 |
t().into_iter()))
.flat_map(|m| {
let mut m2 = m;
multiply_row(&mut m2, 0, -1);
vec![m, m2]
})
.flat_map(|m| {
let mut m2 = m;
multiply_row(&mut m2, 1, -1);
vec![m, m2]
})
.flat_map(|m| {
let mut ... | Rust | 0 |
Overhead,
40 => SquatExerciseName::KettlebellSwingWithFlipToSquat,
41 => SquatExerciseName::LateralDumbbellStepUp,
42 => SquatExerciseName::OneLeggedSquat,
43 => SquatExerciseName::OverheadDumbbellSquat,
44 => SquatExerciseName::OverheadSqu... | Rust | 0 |
nsform.index_mut((0, 3)) = vec_mouse_world_xyz[0];
*meshes[1].transform.index_mut((1, 3)) = vec_mouse_world_xyz[1];
*meshes[1].transform.index_mut((2, 3)) = vec_mouse_world_xyz[2];
lights[0].xyz = [
vec_mouse_world_xyz[0],
vec_mouse_world_xyz[1],
vec_mouse_wo... | Rust | 0 |
itertools.repeat(config),
max_workers=n_jobs,
)
logging.info(f""">> {s.nsim} seir simulations completed in {time.monotonic() - start:.1f} seconds""")
def states2Df(s, states):
# Tidyup data for R, to save it:
#
# Write output to .snpi.*, .spar.*, and .seir.* files
(
... | Python | 1 |
import sys
import json
import numpy as np
if len(sys.argv) != 2:
print('Usage: python print_retrieval_metrics.py in_file')
exit()
in_file = sys.argv[1]
in_data = [json.loads(line) for line in open(in_file).readlines()]
in_data = [x for x in in_data if '_abs' not in x['question_id']]
task2type = {
'singl... | Python | 1 |
WithRegularization<O, R> {
type State = O::State;
fn new_state(&self, shape: &[usize]) -> Self::State {
self.optimizer.new_state(shape)
}
fn update(&mut self, data: &mut NDArray, state: &mut Self::State, grad: &NDArray) {
let grad = (grad + &*self.regularizer.grad(&data.clone().into())... | Rust | 0 |
e, move |b| b.iter(|| bot.select(&chess, Depth(depth))));
}
fn depth_three(c: &mut Criterion) {
bench_fen(
c,
"rubot_simple vs handschaf 10+0, 01.05.2019",
"6k1/2ppqp1p/1p2p1p1/1b6/8/r3PPPQ/5K1P/6NR b - - 3 34",
3,
);
bench_fen(
c,
"rubot_simple vs gobok 10+0... | Rust | 0 |
online】:{self.token_online}\n账号【{self.phone_num}】成功获取到【ecs_token】:{self.ecs_token}\n账号【{self.phone_num}】成功获取到【appid】:{self.appid}\n账号【{self.phone_num}】成功获取到【deviceId】:{self.deviceId}')
# 拼接参数appid
if chinaUnicomParam_flag == True or chinaUnicomParam_flag == "True":
# 在前
if appid... | Python | 1 |
class Solution(object):
def updateBoard(self, board, click):
"""
:type board: List[List[str]]
:type click: List[int]
:rtype: List[List[str]]
"""
if not board or not board[0]:
return board
m, n = len(board), len(board[0])
visited = ... | Python | 1 |
der.
pub const NEGATIVE: untrusted::Input = untrusted::Input::from(include_bytes!("der/negative.bin"));
#[rustfmt::skip]
/// Generated from one_twenty_eight.der.
pub const ONE_TWENTY_EIGHT: untrusted::Input = untrusted::Input::from(include_bytes!("der/one_twenty_eight.bin"));
#[rustfmt::skip]
/// Generated from bad_b... | Rust | 0 |
- Masked interrupt status register"]
pub mis: MIS,
#[doc = "0x801c - Interrupt clear register"]
pub ic: IC,
}
#[doc = "Data register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic... | Rust | 0 |
tarting and is scheduled to shut down in {}",
fmt_duration_until_shutdown(body)?);
msg.channel_id.say(&ctx.http, resp).await?;
Ok(())
},
Err(e) => {
msg.channel_id.say(&ctx.http, "Startup has failed").await?;
Err(CommandError... | Rust | 0 |
encrypts a value lying in `range`.
///
/// The `proof` should be created with a call to [`Self::encrypt_range()`] with the same
/// [`PreparedRange`]; otherwise, the proof will not verify.
///
/// # Errors
///
/// Returns an error if the `proof` does not verify.
pub fn verify_range(
... | Rust | 0 |
ication:
-v - info
-vv - debug
-vvv - trace
NOTE: trace output is only available in debug builds, as it is extremely verbose."#))
)
.arg(
Arg::with_name("backtraces")
.long("--backtraces")
.takes_v... | Rust | 0 |
.device();
GqnLstm {
biases,
conv_ih,
conv_hh,
in_channels,
out_channels,
forget_bias,
device,
}
}
pub fn zero_state(&self, batch: i64, height: i64, width: i64) -> GqnLstmState {
let hidden_size = [batc... | Rust | 0 |
FLOAT_SQRT_THROUGHPUT: u8 = 7;
pub const FLOAT_RSQRT_THROUGHPUT: u8 = 13;
pub const FLOAT_MADD_THROUGHPUT: u8 = 1;
pub const FLOAT_LWC1_THROUGHPUT: u8 = 1;
}
pub mod requirements {
//! Constants containing the pipeline requirements for different
//! instruction classes on the EE Core.
use crate::{core::pipelin... | Rust | 0 |
from langchain_community.tools.semanticscholar.tool import SemanticScholarQueryRun
"""Semantic Scholar API toolkit."""
"""Tool for the Semantic Scholar Search API."""
__all__ = ["SemanticScholarQueryRun"]
| Python | 1 |
'code': 'invalid_claims',
'description': 'Incorrect claims. Please, check the audience and issuer.'
}, 401)
except Exception:
raise AuthError({
'code': 'invalid_header',
'description': 'Unable to parse authentication token.'
... | Python | 1 |
;
let obj = py_fn!(py, f(a: i32, b: i32) -> PyResult<i32> {
drop(py); // avoid unused variable warning
Ok(a * b)
});
assert!(obj.call(py, NoArgs, None).is_err());
assert_eq!(obj.call(py, (6, 7), None).unwrap().extract::<i32>(py).unwrap(), 42);
}
/* TODO: reimplement flexible sig suppor... | Rust | 0 |
import nltk
import regex as re
nltk.download('punkt')
from nltk.tokenize import sent_tokenize
def extract_text_by_citation(paragraph):
citation_regex = re.compile(r'(.*?)(\[\d+\]\.)', re.DOTALL)
parts_with_citation = citation_regex.findall(paragraph)
citation_dict = {}
for part, citation in parts_wit... | Python | 1 |
# Copyright 2018 The TensorFlow Authors. 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 required by applica... | Python | 1 |
# Test get() method
retrieved = await BoolTestModel.get(model.pk)
assert retrieved.name == "test_user"
assert retrieved.is_active is True
assert retrieved.is_admin is False
assert isinstance(retrieved.is_active, bool)
assert isinstance(retrieved.is_admin, bool)
# Test querying by boolean... | Python | 1 |
from pathlib import Path
class GherkinStep():
def __init__(self, id):
self.uri = None
self.ast_node_ids = None
self.text = None
self.id = id
self.lines = []
self._status = "undefined"
self.test_step_id = None
self.pickle_step_id = None
self.a... | Python | 1 |
d type {}'.format(repr(t)))
return keystore
def from_private_key_list(text):
keystore = Imported_KeyStore({})
for x in get_private_keys(text):
keystore.import_privkey(x, None)
return keystore
def from_old_mpk(mpk):
keystore = Old_KeyStore({})
keystore.add_master_public_key(mpk)
ret... | Python | 1 |
audio, sample_rate, length = extract_audio(video, tmp_wav)
voice_activity = extract_from_audio(audio, sample_rate, aggressiveness=aggressiveness)
tmp_wav.unlink()
tmp_wav.parent.rmdir()
return voice_activity, length
if __name__ == '__main__':
import sys
args = sys.argv[1:]
if not WEBRT... | Python | 1 |
from sense.engine import InferenceEngine
from sense.loading import build_backbone_network
from sense.loading import get_relevant_weights
from sense.loading import ModelConfig
from tools.sense_studio.project_utils import get_project_setting
SUPPORTED_MODEL_CONFIGURATIONS = [
ModelConfig('StridedInflatedEfficientNe... | Python | 1 |
-1, -1, 1, 1, 1, 1])
# 初始中心为(0, 0, 0)
box3d = np.vstack((x_corners, y_corners, z_corners))
# 旋转3D框
box3d = np.dot(orientation.rotation_matrix, box3d)
# 平移3D框
box3d[0, :] = box3d[0, :] + x
box3d[1, :] = box3d[1, :] + y
box3d[2, :] = box3d[2, :] + z
obj_ann['data_type'] = ann['data_t... | Python | 1 |
import os
folders = [
"BlackShell-Offensive-Suite/modules/recon",
"BlackShell-Offensive-Suite/modules/scan",
"BlackShell-Offensive-Suite/modules/vulnscan",
"BlackShell-Offensive-Suite/modules/exploit/payloads",
"BlackShell-Offensive-Suite/modules/report",
"BlackShell-Offensive-Suite/utils",
... | Python | 1 |
ceive Configuration 1 Register"]
pub struct RCR1 {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "SAI Receive Configuration 1 Register"]
pub mod rcr1;
#[doc = "SAI Receive Configuration 2 Register"]
pub struct RCR2 {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "SAI Receive Configuration 2 Register"]
pub m... | Rust | 0 |
#!/usr/bin/env python3
#
# Arm SCP/MCP Software
# Copyright (c) 2019-2024, Arm Limited and Contributors. All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
#
"""
Check for usage of banned API (banned_api.lst).
"""
import argparse
import glob
import sys
from utils import banner, get_filtered_files
#
#... | Python | 1 |
ed = preprocessor.transform(X_sample)
def predict_fn(X):
return nn_pipeline.named_steps['nn'].predict_proba(X)[:, 1] #probability of class 1: untrustworthy
explainer = shap.KernelExplainer(predict_fn, X_background_transformed)
shap_values = explainer.shap_values(X_sample_transformed, nsamples=100)
valid_columns... | Python | 1 |
vertex_buffer[self.vertex_counter + 10] = uy;
self.vertex_counter += 11;
}
/// Rebuilds the OpenGL backing buffer.
fn rebuild_vertices(&mut self, gl: &glow::Context) {
self.vertex_counter = 0;
self.index_counter = 0;
let glyph_size_x: f32 = 1.0 / 16.0;
let glyph_size... | Rust | 0 |
# This code is part of Qiskit.
#
# (C) Copyright IBM 2022.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative wo... | Python | 1 |
ns made in other Frappe apps
# override_doctype_dashboards = {
# "Task": "test.task.get_dashboard_data"
# }
# exempt linked doctypes from being automatically cancelled
#
# auto_cancel_exempted_doctypes = ["Auto Repeat"]
# Ignore links to specified DocTypes when deleting documents
# ----------------------------------... | Python | 1 |
CORE_APPS = (
'account',
'circuits',
'core',
'dcim',
'extras',
'ipam',
'tenancy',
'users',
'utilities',
'virtualization',
'vpn',
'wireless',
)
# RQ queue names
RQ_QUEUE_DEFAULT = 'default'
RQ_QUEUE_HIGH = 'high'
RQ_QUEUE_LOW = 'low'
# Keys for PostgreSQL advisory locks.... | Python | 1 |
onst c_char {
if luaL_callmeta(L, idx, cstr!("__tostring")) == 0 {
let t = lua_type(L, idx);
match t {
LUA_TNIL => {
lua_pushliteral(L, "nil");
}
LUA_TSTRING | LUA_TNUMBER => {
lua_pushvalue(L, idx);
}
LUA_TB... | Rust | 0 |
be greater than or equal to 8. Saw 5"), # noqa: E501
(1, 1, 1, 20, -1, 0, 1, 0, 0, "'max_mismatches_in_three_prime_region' must be between 0 and 'three_prime_region_length'=20 inclusive. Saw -1"), # noqa: E501
(1, 1, 1, 20, 21, 0, 1, 0, 0, "'max_mismatches_in_three_prime_region' must be between 0 and... | Python | 1 |
_map: &mut HashMap<PCIAddress, &'static AcpiDevice>,
) {
for child in device.children() {
if let Some(addr) = child.address() {
let function = (addr & 0x07) as u8;
let dev_id = ((addr >> 16) & 0x1F) as u8;
let pci_addr = PCIAddress::new(0, bus, dev_id, function);
... | Rust | 0 |
w(
cb.raw,
// 6 verts (two triangles) per cube face
6 * CARDINAL_DIRECTION_COUNT as u32 * VOLUME_DIMS * VOLUME_DIMS * VOLUME_DIMS,
1,
0,
0,
);
}
api.end_render... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.