text string | label_name string | labels int64 |
|---|---|---|
c_tensor = self.alloc_map[allreduce_input]
self.binding_replacement_map[alloc_tensor] = relax.op.builtin.alloc_tensor(
alloc_tensor.args[0],
alloc_tensor.args[1],
alloc_tensor.args[2],
relax.StringImm("ipc_memory"),
)
self.binding_replacement_map[c... | Python | 1 |
NFIG_VIRTUALIZATION: u32 = 36u32;
#[doc = "*Required features: `\"Win32_System_Diagnostics_Etw\"`*"]
pub const EVENT_TRACE_TYPE_CONNECT: u32 = 12u32;
#[doc = "*Required features: `\"Win32_System_Diagnostics_Etw\"`*"]
pub const EVENT_TRACE_TYPE_CONNFAIL: u32 = 17u32;
#[doc = "*Required features: `\"Win32_System_Diagnost... | Rust | 0 |
}
/// Return a `ReplicaLogger` and its `AsyncGuard`
///
/// Note: Do not drop the `AsyncGuard`! If it is dropped, all async logs
/// (typically logs below level `Error`) will not be logged.
pub fn get_canister_http_logger(logger_config: &LoggerConfig) -> (ReplicaLogger, AsyncGuard) {
let base_logger = LoggerImpl::... | Rust | 0 |
'%s' % str(year), '%s' % str(int(year) + 1), '%s' % str(int(year) - 1), '0']
r = client.request(query)
r = dom_parser.parse_dom(r, 'article', attrs={'class': 'shortstory'})
r = dom_parser.parse_dom(r, 'div', attrs={'class': 's_info'})
r = dom_parser.parse_dom(r, 'h2')
... | Python | 1 |
= tba_blue.get("autoCoralCount")
tba_blue_tele = tba_blue.get("teleopCoralCount")
tba_red_auto = tba_red.get("autoCoralCount")
tba_red_tele = tba_red.get("teleopCoralCount")
if tba_blue_auto is not None and our_blue_auto != tba_blue_auto:
for scouter in match_alliance_scouters.get(match_num, {... | Python | 1 |
rame_id - min_frame_id
y_shift = offset_frames * AVERAGE_SPEED_MM_PER_FRAME
frame_pts_camera[:, 1] -= y_shift
if DEBUG_PRINT_PER_FRAME:
print(f"Frame {frame_id} => detected {len(frame_pts_camera)} points.")
time_lst.append((time.time() - time_start) * 1000)
if SHOW... | Python | 1 |
#!/usr/bin/env python3
"""
独立数据库清理脚本 - 不依赖Flask应用自动表创建
直接使用数据库连接清理和创建表
"""
import sys
import os
import pymysql
from sqlalchemy import create_engine, text
# 读取环境变量或使用默认配置
DB_HOST = os.getenv('DB_HOST', 'localhost')
DB_PORT = int(os.getenv('DB_PORT', '3306'))
DB_USERNAME = os.getenv('DB_USERNAME', 'dify_user')
DB_PASSW... | Python | 1 |
p::new(group));
}
}
Binds(map)
}
}
#[derive(Clone, Debug, Serialize)]
pub struct BindGroup<'a> {
pub first: Option<SvcMember<'a>>,
pub members: Vec<SvcMember<'a>>,
}
impl<'a> BindGroup<'a> {
fn new(group: &'a CensusGroup) -> Self {
BindGroup {
first: sel... | Rust | 0 |
# Script converts json output from KTT format into common autotuning output format, schema available https://github.com/odgaard/TuningSchema/blob/T4/results-schema.json
import json
import sys
if len(sys.argv) != 3 :
print("Error, run " + sys.argv[0] + ' ktt_json_file converted_json_filename')
exit(1)
with op... | Python | 1 |
r : A user found in a search.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct UserPickerUser {
/// The account ID of the user, which uniquely identifies the user across all Atlassian products. For example, *<KEY>*.
#[serde(rename = "accountId", skip_serializing_if = "Option::is_none")]
... | Rust | 0 |
o
Error,
// Single-character tokens.
Semicolon, // ;
LeftParen, // (
RightParen, // )
LeftBrace, // {
RightBrace, // }
LeftBracket, // [
RightBracket, // ]
Comma,
Dot,
// Math operators
Minus,
Plus,
Slash,
Star,
// Operators
// One or two character tokens.
Bang,
... | Rust | 0 |
put wait has failed
/// let input_wait_result = parse_input_wait_result_succeded("In:-1");
///
/// // Input wait has succeeded
/// let input_wait_result = parse_input_wait_result_succeded("In:0");
/// let input_wait_result = parse_input_wait_result_succeded("In:1");
/// ```
pub fn parse_input_wait_result(message: &str... | Rust | 0 |
# 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 |
_mem, x], dim=1)
# # 프로젝션
# query = self.q_proj(x_with_persistent)
# key = self.k_proj(x_with_persistent)
# value = self.v_proj(x_with_persistent)
# # 1. 슬라이딩 윈도우 어텐션 (단기 메모리)
# attention_output = self.attention(x_with_persistent)
# # 2.... | Python | 1 |
pub(super) pid: Pid,
pub(super) suspended: bool,
}
impl fmt::Display for Process {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "pid: {} (suspended: {})", self.pid, self.suspended)
}
}
impl std::str::FromStr for Process {
type Err = std::num::ParseIntError;
fn from_str(... | Rust | 0 |
#[serde(default)]
t: i32,
},
cast {
c: i32,
#[serde(default)]
t: i32,
},
accept,
mulligan,
foe {
t: i32,
},
resign {
c: i32,
},
}
mod config;
mod interface;
mod inventory;
mod shader;
mod utils;
mod world;
use bevy::{asset::LoadState, prelude::*};
use bevy_rapier3d::{
physics::{PhysicsInterpo... | Rust | 0 |
# String Initialization
my_string = " Hello, Python World! "
# 1. String length
print("Length of string:", len(my_string)) # Output: 24
# 2. String strip() - Remove leading and trailing whitespaces
stripped_string = my_string.strip()
print("String after stripping whitespaces:", stripped_string) # Output: "Hello, ... | Python | 1 |
#
# Copyright (c) The acados authors.
#
# This file is part of acados.
#
# The 2-Clause BSD License
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright n... | Python | 1 |
False
if self.frozen_stages >= 2:
self.pos_drop.eval()
for i in range(0, self.frozen_stages - 1):
m = self.layers[i]
m.eval()
for param in m.parameters():
param.requires_grad = False
def init_weights(self, pretrai... | Python | 1 |
`kernel-figure`` directive (it only knows about
standard nodes, e.g. table, figure etc.). Without any additional handling
this will result in a 'undefined label' for kernel-figures.
This handle adds labels of kernel-figure to the 'std' domain labels.
"""
std = app.env.domains["std"]
docname = ... | Python | 1 |
"""Test Tuya diagnostics platform."""
from __future__ import annotations
import pytest
from syrupy.assertion import SnapshotAssertion
from syrupy.filters import props
from tuya_sharing import CustomerDevice
from homeassistant.components.tuya import ManagerCompat
from homeassistant.components.tuya.const import DOMAIN... | Python | 1 |
#[export]
fn _process(&mut self, _owner: TRef<Control>, _: f64) {
if let Some(gui) = &self.gui {
let gui = unsafe { gui.assume_safe() };
gui.map_mut(|egui, o| {
egui.update_ctx(o, |ctx| {
egui::Window::new("Test Window")
.f... | Rust | 0 |
from typing import Optional
# Time: O(n)
# Space: O(n)
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def diameterOfBinaryTree(self, root: Optional[TreeN... | Python | 1 |
mer (C) or content-provider (CP).
Each edge models an ADV communication link (hence, bidirectional) with
attributes:
- type: transit|peer, the kind of commercial agreement between nodes;
- customer: <node id>, the identifier of the node acting as customer
('none' if type is peer).
Refe... | Python | 1 |
ExprEnv_kDisplayValidation: fmx_ExprEnv__bindgen_ty_1 = 1024;
pub const fmx_ExprEnv_kDisplayCustomFunctions: fmx_ExprEnv__bindgen_ty_1 = 2048;
pub const fmx_ExprEnv_kDisplayPrivileges: fmx_ExprEnv__bindgen_ty_1 = 4096;
pub const fmx_ExprEnv_kDisplayInFuture1: fmx_ExprEnv__bindgen_ty_1 = 8192;
pub const fmx_ExprEnv_kDis... | Rust | 0 |
class UserNotifyEvent:
ACCOUNT_CONFIRMATION = "account_confirmation"
ACCOUNT_PASSWORD_RESET = "account_password_reset"
ACCOUNT_CHANGE_EMAIL_REQUEST = "account_change_email_request"
ACCOUNT_CHANGE_EMAIL_CONFIRM = "account_change_email_confirm"
ACCOUNT_DELETE = "account_delete"
ACCOUNT_SET_CUSTOME... | Python | 1 |
if let Some(range) = readonly_range {
let err = guard
.err_builder("class methods cannot be readonly")
.primary(range, "");
guard.error(err);
}
if is_constructor {
let err = guard
.err_builder("constructors can't be generators")
.primary(generator_range, "");
guard.error(err);
}
... | Rust | 0 |
\xc0y\x1f\x02\x82\xa8\x98\x88.\
\xb5\x04\xd1Sg\xf7\xea\xe1\x9c\x1f\xe5yz8\xa0'\
D\xb5p\xc9\x15zJ\x1b\x08!=\x0c\xc1\xd9\xfd\x17\
_\xec\xeb\xfa\xces/|\xeeg\xbf$\xb3\xb4\xab\xeb\
xb\x9d\xf7\xdajkm&3\x8c\xf1\xf9\xae}H\
\x8b\xc2X\x130v\xce\xa9\xa6\x1e\xd7[*\x05\x0a!\
V\xff#\x84\xc6\xaes\xc6\xa4\x93IR\x96'o\xbd\
C(\x8dIn\x8c... | Python | 1 |
"price": "1998.99"
}]
}, {
"attr": [{
"attrId": "9",
"attrName": "颜色",
"attrValue": "白色"
}, {
"attrId": "10",
"attrName": "内存",
"attrValue": "12GB"
}],
"sku... | Python | 1 |
_ as usize } , 0usize , concat ! (
"Alignment of field: " , stringify ! ( TPMU_SYM_KEY_BITS ) ,
"::" , stringify ! ( exclusiveOr ) ));
assert_eq! (unsafe {
& ( * ( 0 as * const TPMU_SYM_KEY_BITS ) ) . na as * const _
as usize } , 0usize , concat ! (
... | Rust | 0 |
# This script hasn't been used since Test Build 9 - it may not work properly!
from cx_Freeze import setup, Executable
import os, os.path, shutil, sys
dir = 'distrib/linux'
print '[[ Freezing Reggie! ]]'
print '>> Destination directory: %s' % dir
sys.argv.append('build')
if os.path.isdir(dir): shutil.rmtree(dir)
os.... | Python | 1 |
# Generated by Django 5.1.8 on 2025-04-14 20:23
from django.db import migrations
from core.utils import UserGroupCodename, RoleCodename
def add_missing_ug_and_ra(apps, schema_editor):
Folder = apps.get_model("iam", "Folder")
UserGroup = apps.get_model("iam", "UserGroup")
RoleAssignment = apps.get_model("... | Python | 1 |
t system_proxy = env::var("http_proxy");
// set-up http proxy.
env::set_var(
"http_proxy",
format!("http://Aladdin:open sesame@{}", server.addr()),
);
let res = reqwest::Client::builder()
.build()
.unwrap()
.get(url)
.send()
.await
.unwra... | Rust | 0 |
import time
from selenium import webdriver
from selenium.webdriver.common import keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.select import Select
options = webdriver.ChromeOptions()
options.add_experimental_option('detach',True)
d = webdriver.Chrome(options=options)
d.maximize_wi... | Python | 1 |
....{ IMPORTS }....................
# Defer test-specific imports.
from beartype import beartype
from beartype.roar import BeartypeCallHintParamViolation
from beartype.typing import (
Iterator,
Union,
)
from contextlib import contextmanager
from pytest ... | Python | 1 |
mp.BANNED_CHATS.append(int(chat_))
await message.reply('ᴄʜᴀᴛ sᴜᴄᴄᴇssғᴜʟʟʏ ᴅɪsᴀʙʟᴇᴅ')
try:
buttons = [[
InlineKeyboardButton('sᴜᴘᴘᴏʀᴛ', url=f'https://t.me/{SUPPORT_CHAT}')
]]
reply_markup=InlineKeyboardMarkup(buttons)
await bot.send_message(
chat_id=chat_, ... | Python | 1 |
#
# Copyright (c) 2023 Airbyte, Inc., all rights reserved.
#
from .source import SourceFreshservice
__all__ = ["SourceFreshservice"]
| Python | 1 |
tch self._roles().get(role) {
Some(role_data) => role_data.members.get(address).cloned().unwrap_or(false),
None => false,
}
}
fn _get_role_admin(&self, role: &RoleType) -> RoleType {
match self._roles().get(role) {
Some(role_data) => role_data.admin_role.clon... | Rust | 0 |
e)
os.makedirs(self.output_path, exist_ok=True)
# 如果data目录为空,创建示例文件
if not os.listdir(self.default_data_path):
self.create_example_file()
# 初始化OpenAI客户端
self.client = OpenAI(
base_url='https://xiaoai.plus/v1',
api_key='sk-... | Python | 1 |
Ok(p);
} else {
fs::iunlock(inode);
return Err(SysError::IsDir);
}
}
None => fs::ialloc(dir_inode.get_dev(), typ, major, minor),
};
let mut inode = fs::ilock(&ip);
fs::iupdate(&inode);
if typ == InodeType::Dir {
// create... | Rust | 0 |
t(f'label >>>>> {label}')
output_label = classes[list(self.label_map.get(label, label))[0]]
print(f'>>> output_label: {output_label}')
if output_label not in self.labels_in_config:
print(output_label + ' label not found in project config.')
continue
... | Python | 1 |
Self {
title,
published,
description,
category,
}
}
}
<reponame>pontem-network/dove<filename>dove/src/natives/reflect.rs<gh_stars>1-10
use move_binary_format::errors::PartialVMResult;
use move_core_types::language_storage::TypeTag;
use move_vm_runtime:... | Rust | 0 |
#[doc = "0xff0 - Component Identification Bits7:0"]
pub intcid0: INTCID0,
#[doc = "0xff4 - Component Identification Bits15:8"]
pub intcid1: INTCID1,
#[doc = "0xff8 - Component Identification Bits16:23"]
pub intcid2: INTCID2,
#[doc = "0xffc - Component Identification Bits24:31"]
pub intcid... | Rust | 0 |
_name_mbes = vec![ $( mbe_one_name!($lhs => $rhs) ),*];
let mut res = crate::util::mbe::EnvMBE::new();
for m in &single_name_mbes {
res = res.merge(m);
}
res
}}
}
// FormPat
// TODO #8: `ast!` and `form_pat!` are inconsistent with each other.
macro_rules! form_pat {
... | Rust | 0 |
import pytest
from tests.helpers.run_command import run_command
from tests.helpers.runif import RunIf
def test_fast_dev_run():
"""Run 1 train, val, test batch."""
command = ["run.py", "trainer=default", "trainer.fast_dev_run=true"]
run_command(command)
def test_default_cpu():
"""Test default config... | Python | 1 |
pub struct cudnnFusedOpsVariantParamStruct {
_unused: [u8; 0],
}
pub type cudnnFusedOpsVariantParamPack_t = *mut cudnnFusedOpsVariantParamStruct;
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct cudnnFusedOpsPlanStruct {
_unused: [u8; 0],
}
pub type cudnnFusedOpsPlan_t = *mut cudnnFusedOpsPlanStruct;
#[repr(... | Rust | 0 |
de(deserialize_with = "fix_common::workarounds::from_opt_str")]// https://github.com/serde-rs/serde/issues/1183
#[serde(default)]
#[serde(rename = "697")]
pub redemption_price: Option<f64>,
/// RedemptionPriceType
#[serde(skip_serializing_if = "Option::is_none")]
#[serde(rename = "698")]
pub redemption_price_typ... | Rust | 0 |
import random
NUM_QUESTIONS = 53
file = open("questions.txt", "r")
lines = []
for line in file:
lines.append(line[:len(line)-1])
file.close()
right = 0
answer = 0
score = 0
answered_questions = 0
while answer != 5:
i = 1
num = random.randrange(0,NUM_QUESTIONS-1)*5
print(lines[num])
# Ge... | Python | 1 |
rc_inst, _)| {
let data = ctx.data(src_inst);
if data.opcode() == op {
return Some(src_inst);
}
None
})
}
/// Returns whether the given specified `input` is a result produced by an instruction with any of
/// the opcodes specified in `ops`.
fn matches_input_any<C: LowerC... | Rust | 0 |
ge = (
"\n".join([
"🤖 **Selamat datang di Bot Sinyal MEXC Futures**",
"",
"Pilih aksi utama atau jelajahi pasangan populer.",
])
)
keyboard = [
[InlineKeyboardButton("🎯 Dapatkan Sinyal", callback_data="get_signal_input... | Python | 1 |
STRESPONSE._serialized_start=3061
_GETSLACKAPPMANIFESTRESPONSE._serialized_end=3221
_GETCONNECTEDPLAYBOOKSREQUEST._serialized_start=3223
_GETCONNECTEDPLAYBOOKSREQUEST._serialized_end=3333
_GETCONNECTEDPLAYBOOKSRESPONSE._serialized_start=3336
_GETCONNECTEDPLAYBOOKSRESPONSE._serialized_end=3678
_GETCONNECTEDP... | Python | 1 |
uid())
}
"#;
let original_database_schema = infer_and_apply(test_setup, engine, &dm).sql_schema;
let conn = &test_setup.database;
let insert = Insert::single_into((SCHEMA_NAME, "Test")).value("id", "test");
conn.execute(SCHEMA_NAME, insert.into()).un... | Rust | 0 |
return []
all_rows = tables[0].select("tr")
filtered_rows = list(filter(lambda r: re.match(valid_pattern, r.select("td")[0].text.strip()), all_rows))
return filtered_rows
@staticmethod
def _parse_row(row: Tag, date_of_data: datetime.date) -> TgeHourData:
time_of_row = Tg... | Python | 1 |
[pos[j, 1], pos[j_parent, 1]],
[pos[j, 2], pos[j_parent, 2]], zdir='z', c=col))
# Plot 2D keypoints
points = ax_in.scatter(*keypoints[i].T, 10, color=colors_2d, edgecolors='white', zorder=10)
initialized = True
... | Python | 1 |
border-radius: 8px;
background: #2a2a2a;
font-size: 12px;
}
.agent-card.running { border-color: #4CAF50; }
.agent-card.starting { border-color: #FF9800; }
.agent-card.failed { border-color: #F44336; }
#events {
height: 5... | Python | 1 |
3cb92096f7434d9316c__spectacle_contributions",
&spec_projection.contributions().to_json_string()
);
let interactions_string = std::fs::read_to_string(interactions_file_path)
.expect("expected interactions file to be readable");
let interactions: Vec<HttpInteraction> = serde_json::from_str(&interactions_st... | Rust | 0 |
from langchain_community.document_loaders import WebBaseLoader, PyPDFLoader, TextLoader, NotebookLoader
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain_qdrant import QdrantVectorStore
from langchain_openai import OpenAIEmbeddings
from qdrant_client import QdrantClient
from tqdm import ... | Python | 1 |
};
(@parse ($proto:ident) { $($body:tt)* } $($rest:tt)*) => {
$crate::class_def!{@proto _ctx $proto $($body)*}
$crate::class_def!{@parse $($rest)*}
};
(@parse ($ctx:ident, $proto:ident) { $($body:tt)* } $($rest:tt)*) => {
$crate::class_def!{@proto $ctx $proto $($body)*}
$... | Rust | 0 |
#!/bin/python3
# coding:utf-8
# Author:lowkey0808
import sys
import requests
import argparse
import pyfiglet
print(pyfiglet.figlet_format('cve-2021-43857'))
print('''
免责声明:
脚本仅供学习参考,请勿恶意攻击他人网站,
如违法乱纪,造成一切后果由使用者自行承担
技术无罪,与作者无关
使用脚本默认同意以上说明!
--Author... | Python | 1 |
# Copyright (c) OpenMMLab. All rights reserved.
from .layer_decay_optim_wrapper import LayerDecayOptimWrapperConstructor
__all__ = ['LayerDecayOptimWrapperConstructor']
| Python | 1 |
"""注册所有文档转换器
这个模块负责注册所有可用的文档转换器。
新的转换器应该在这里注册。
"""
from pathlib import Path
from typing import Dict, Any, Optional
from .document_converter import DocumentConverter
# 导入所有转换器
try:
from tools.everything_to_text.pdf_to_md_mineru import mineru_pdf2md
_has_mineru = True
except ImportError:
_has_mineru = Fal... | Python | 1 |
//
/// let response = Request::get("localhost:3999")
/// .ssl_client_certificate(ClientCertificate::pem_file(
/// "client.pem",
/// PrivateKey::pem_file("key.pem", String::from("secret")),
/// ))
/// .body(())?
/// .send()?;
/// # Ok::<(), isahc::Error>(()... | Rust | 0 |
// pub conversion: BTreeMap<(Symbol, Symbol),>,
//
/// The list of local names for the symbol. If a symbol is missing from
/// this map, it may not have a local name but can still be a valid
/// symbol (refer to the list of symbols above).
#[n(4)]
pub local_names: BTreeMap<ledger::Symbol, St... | Rust | 0 |
#!/usr/bin/env python3
from pexpect_helper import SpawnedProc
import os
env = os.environ.copy()
env["TERM"] = "xterm"
sp = SpawnedProc(env=env)
send, sendline, sleep, expect_prompt, expect_re, expect_str = (
sp.send,
sp.sendline,
sp.sleep,
sp.expect_prompt,
sp.expect_re,
sp.expect_str,
)
expec... | Python | 1 |
from ccxt.base.types import Entry
class ImplicitAPI:
public_get_market_ticker = publicGetMarketTicker = Entry('{market}/ticker', 'public', 'GET', {})
public_get_market_orderbook = publicGetMarketOrderbook = Entry('{market}/orderbook', 'public', 'GET', {})
public_get_market_trades = publicGetMarketTrades =... | Python | 1 |
RoBERTa, does not make use of token type ids, therefore a list of zeros is returned.
Args:
token_ids_0 (:obj:`List[int]`):
List of IDs.
token_ids_1 (:obj:`List[int]`, `optional`):
Optional second list of IDs for sequence pairs.
Returns:
... | Python | 1 |
),
b
);
}
#[test]
fn inverse_3() {
let a = matrix(
(9.0, 3.0, 0.0, 9.0),
(-5.0, -2.0, -6.0, -3.0),
(-4.0, 9.0, 6.0, 4.0),
(-7.0, 6.0, 6.0, 2.0),
);
let b = a.inverse();
assert_eq!(
matrix(
(-0.04074, -0.07778, 0.14444, -0.22222),
... | Rust | 0 |
64_sae
0x00C9_0000, 0x0000_8008, 0x0000_3263,// Sha1msg1_xmm_xmmm128
0x00CA_0000, 0x0000_8008, 0x0000_3263,// Sha1msg2_xmm_xmmm128
0x00CA_0002, 0x03A0_C809, 0x0000_08E0,// EVEX_Vrcp28ps_zmm_k1z_zmmm512b32_sae
0x00CA_0002, 0x03A0_D809, 0x0000_08E0,// EVEX_Vrcp28pd_zmm_k1z_zmmm512b64_sae
0x00CB_0000, 0x0000_8008, 0x... | Rust | 0 |
from flask_smorest import Blueprint
from flask_jwt_extended import jwt_required, get_jwt_identity
from common.responses import ok
from common.utils import parse_uuid
from .schemas import BookingCreateSchema, BookingOutSchema, BookingListQuerySchema, BookingActionSchema
from .services import (
create_booking, accept... | Python | 1 |
reg.insert("Expand", |_| Ok(Box::new(tractops::array::MultiBroadcastTo::default())));
reg.insert("EyeLike", eye_like);
reg.insert("Flatten", flatten);
reg.insert("Gather", gather);
reg.insert("Pad", pad);
reg.insert("Reshape", |_| Ok(Box::new(tractops::array::Reshape::default())));
reg.inse... | Rust | 0 |
pointARecurs<N> = MeshedChannels<End, RecursAtoC<N>, StackARecurs, RoleA<RoleEnd>>;
type EndpointAFull<N> = MeshedChannels<End, InitA<N>, StackAInit, RoleA<RoleEnd>>;
/// For B
type EndpointBRecurs<N> = MeshedChannels<End, RecursBtoC<N>, StackBRecurs, RoleB<RoleEnd>>;
/// Functions related to endpoints
fn server(s: E... | Rust | 0 |
x.permute(0, 2, 1, 3, 4).contiguous()
# x = F.adaptive_max_pool3d(x, (1, None, None))
# x = x.permute(0, 2, 1, 3, 4).contiguous()
# x = x.view(-1, x.size(2), x.size(3), x.size(4)).contiguous()
# x_8 = F.relu(self.bn8_1(self.conv8_1(torch.cat((F.interpolate(x_7, scale_factor=(2, 2)), x)... | Python | 1 |
DEP.append(deps[token_id].split(':')[0])
if token_id == root_index:
DIR.append('0')
elif token_id in path1:
DIR.append('1')
elif token_id in path2:
DIR.append('2')
else:
DIR.append('****')
da... | Python | 1 |
import json
import os
import subprocess
from datetime import datetime
from functools import wraps
from typing import Union
def subprocess_error_handler(func): # type: ignore
@wraps(func)
def wrapper(*args, **kwargs): # type: ignore
try:
func(*args, **kwargs)
except subprocess.Cal... | Python | 1 |
import numpy as np
def normalize(data, min_val=-100, max_val=500):
normalized_data = (data - min_val) / (max_val - min_val) * (255 - 0) + 0
return normalized_data
def normalize_to_255(matrix):
shape = matrix.shape
# Find the min and max values of the matrix
axes_to_normalize = tuple(range(len(sh... | Python | 1 |
));
::protobuf::reflect::MessageDescriptor::new::<APResponseMessage>(
"APResponseMessage",
fields,
file_descriptor_proto()
)
})
}
}
}
impl ::protobuf::Clear for APResponseMessage {
fn clear(&mut... | Rust | 0 |
tegy: {temperature_decay}")
logger.info(f"Search completed, supernet converged")
logger.info(f"{'='*60}")
total_time = time.time() - total_start_time
logger.info(f"\n=== Total Time Statistics ===")
logger.info(f"DNAS search: {total_training_time:.2f}s ({total_training_time/60:.1f} minutes)")
lo... | Python | 1 |
")).pack(side=tk.LEFT)
if tz != "UTC": # Don't allow removal of UTC
remove_btn = ttk.Button(header_frame, text="X", width=2,
command=lambda tz=tz: self.remove_timezone(tz))
remove_btn.pack(side=tk.RIGHT)
... | Python | 1 |
_HIGHESTA=106,
R_PPC64_TLSGD=107,
R_PPC64_TLSLD=108,
R_PPC64_TOCSAVE=109,
R_PPC64_ADDR16_HIGH=110,
R_PPC64_ADDR16_HIGHA=111,
R_PPC64_TPREL16_HIGH=112,
R_PPC64_TPREL16_HIGHA=113,
R_PPC64_DTPREL16_HIGH=114,
R_PPC64_DTPREL16_HIGHA=115,
R_PPC64_REL24_NOTOC=116,
R_PPC64_ADDR64_LOC... | Python | 1 |
the current size of the file)
preallocated: u64
}
impl PhysicalVolume {
// I need to know the: store directory, volume id, and the cluster_id to make this store
/// Creates a new empty volume and corresponding index file
///
/// Will error out if the volume already exists
pub fn create(
config: ConfigRef, ... | Rust | 0 |
#!/usr/bin/env python3
zipClasses = """class Zip{n}Sequence<{tparams}>({args}) extends Sequence<({tparams})> {{
fun values(): mutable Iterator<({tparams})> {{
{values}
loop {{
({nexts}) match {{
| ({somes}) -> yield ({vals})
| _ -> break void
}}
}}
}}
fun size(): Int {{
Vector... | Python | 1 |
''' Check if a binary tree is a binary search tree
'''
from BinaryTree import BinaryTree
import sys
def is_bst(r):
return is_bst_helper(r,-sys.maxint, sys.maxint)
''' suppose r is 20, then r.data should be in range (-maxint, maxint)
when branch left, r.data (10) should be in range (-maxint, 20)
when bran... | Python | 1 |
# Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not... | Python | 1 |
SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [bt_lpck_div_int::R](R) reader structure"]
impl crate::Readable for BT_LPCK_DIV_INT_SPEC {
type Reader = R;
}
#[doc = "`write(|w| ..)` method takes [bt_lpck_div_int::W](W) writer structure"]
impl crate::Writable for BT_LPCK_DIV_INT_SPEC {
type Writer ... | Rust | 0 |
_string() )
}
}//! Filesystem Structures
use crate::*;
/// Filesystem Error
#[derive(Debug, Clone)]
pub enum FilesystemError
{
MissingRootMount,
FilesystemUninitialized,
UnableToFindDiskMount(usize),
FilesystemNotMounted,
INodeIsNotADirectory,
BadINode,
BadFilesystemFormat,
FileNot... | Rust | 0 |
quests")?;
register(g, r)?
},
peers: {
let g = Gauge::new("sync_peers", "Number of peers we sync with")?;
register(g, r)?
},
queued_blocks: {
let g = Gauge::new("sync_queued_blocks", "Number of blocks in import queue")?;
register(g, r)?
},
fork_targets: {
let g = Gauge::new("sy... | Rust | 0 |
> 0 {
// 3. decrypt the vector 'enc_packet' with the key.
let plaintext = transit.receive_record().await?;
f.write_all(&plaintext).await?;
// 4. calculate a rolling sha256 sum of the decrypted output.
hasher.update(&plaintext);
remaining_size -= plaintext.len();
}... | Rust | 0 |
import re
import chardet
DEBUG_FLAG = '#'
def detect_encoding(file_path):
with open(file_path, 'rb') as f:
result = chardet.detect(f.read())
return result['encoding']
def check(file1='stdout_1.txt', file2='stdout_2.txt', file_in='stdin.txt'):
line_number = 0
with open(file1, 'r', encoding=d... | Python | 1 |
_page(
array: &dyn Array,
descriptor: Descriptor,
options: WriteOptions,
) -> Result<DataPage> {
match array.data_type() {
DataType::List(_) => {
let array = array.as_any().downcast_ref::<ListArray<i32>>().unwrap();
list_array_to_page(
array.offsets(),
... | Rust | 0 |
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html
# useful for handling different item types with a single interface
from itemadapter import ItemAdapter
from .items import FinnAd
from downloader.spid... | Python | 1 |
import pywren
import subprocess
import sys
import ntplib
import cPickle as pickle
import time
import re
import exampleutils
def get_ifconfig_hwaddr(s):
a = re.search(r'.+?(HWaddr\s+(?P<hardware_address>\S+))', s, re.MULTILINE).groupdict('')
return a['hardware_address']
def get_offset(x):
hwaddr = exampl... | Python | 1 |
verify {
assert_last_event::<T>(Event::Deposited {
account: caller,
asset_amount: amount,
lp_amount: amount
}.into())
}
withdraw {
let caller: T::AccountId = whitelisted_caller();
let amount = T::CreationDeposit::get() * 10u32.into();
let (vault, _) = create_vault::<T>(A, caller.clone());
T::Cur... | Rust | 0 |
9c5ccc039253b2f42b7e6f8e06205ad32b3aa75c0efac5f31e4cb5ee0bf030a04ef4a3d84a4fc76dcd38fbcb5850a17b8a4ad7903e9e8554ea3c44ee266c886d632547a575080c3c40010a9051ab0ddbeddc65257cea716121ae49471cd1b477f6f41665fc229a3724a4c76d49cd4330aba8552295be7bae6ec4f5838facfa7f9a0bdd982d79cf491791b75860fa88059cd51f339592e10650d189df777d5913... | Rust | 0 |
"""A JsonRpcError exception can be raised from inside a method, as an alternative way to
return an error response. See https://github.com/explodinglabs/jsonrpcserver/discussions/158
"""
from typing import Any
from .sentinels import NODATA
class JsonRpcError(Exception):
def __init__(self, code: int, message: str, ... | Python | 1 |
break
# implicitly skips elements without any audio
# %% ../nbs/D. Common dataset utilities.ipynb 18
def vad_dataset(shards, ikey='vad.npy', kind='vad'):
return wds.WebDataset(shards).compose(
wds.decode(torch_audio_opus),
find_audio,
merge_in(derived_dataset(kind)),
l... | Python | 1 |
'area'})\
.query('prefecture != "全国"').reset_index(drop=True)
area_df
# %%
grp_capita_area_df = pd.merge(
grp_capita_df.assign(
_non_prefix = lambda x: np.where(x['prefecture'] == '北海道', '北海道', x['prefecture'].str[:-1])
),
area_df,
left_on='_non_prefix',
right_on='prefecture',
... | Python | 1 |
crate::src::jerror::JERR_CONVERSION_NOTIMPL as libc::c_int;
Some(
(*(*dstinfo).err)
.error_exit
.expect("non-null function pointer"),
)
.expect("non-null function pointer")(
dstinfo as crate::jpeglib_h::j_common... | Rust | 0 |
1;
years = (seconds / SECS_PER_REPEAT + 1) * YEARS_PER_REPEAT as Time;
seconds = years * AVERAGE_SECS_PER_YEAR;
if time < self.ats[0] {
new_time += seconds;
} else {
new_time -= seconds;
}
if new_time < self.ats[0... | Rust | 0 |
import typer
from rich.console import Console
from quantalogic_codeact.cli_commands.config_functions import load_project_config, save_project_config
from quantalogic_codeact.commands.toolbox.uninstall_toolbox_core import uninstall_toolbox_core
app = typer.Typer()
console = Console()
@app.command()
def uninstall_tool... | Python | 1 |
"));
}
}
unsafe impl Send for SharedLink {}
impl Drop for SharedLink {
fn drop(&mut self) {
self.deactivate();
}
}
enum Inner {
Unset,
Closed(io::Error),
InUse(imp::Map, u32),
Active(imp::Map),
}
impl Inner {
fn open() -> Inner {
match imp::Map::new(std::mem::size_of:... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.