text string | label_name string | labels int64 |
|---|---|---|
}
data.sccs.push(cur_scc);
}
}
}
sccs
}
#[test]
fn graph_sccs() {
fn prop(g: Graph<(), ()>) -> bool {
let mut sccs = scc(&g);
let mut tsccs = tarjan_scc(&g);
// normalize sccs
for scc in &mut sccs { scc.sort(); }
f... | Rust | 0 |
#!/usr/bin/python3 -i
#
# Copyright (c) 2018 Valve Corporation
# Copyright (c) 2018-2024 LunarG, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without ... | Python | 1 |
import sys, os, shutil, inspect, random, json;
CURRENTDIR = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())));
ROOT = os.path.dirname(CURRENTDIR);
sys.path.append(ROOT);
from api.systemctl import Systemctl
from api.CONST import *;
def main():
ctl = Systemctl( JSON_SERVICE );
ctl.resta... | Python | 1 |
// Addenda from rfc 5289 Elliptic Curve Cipher Suites with
// HMAC SHA-256/384.
pub const TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256: SSLCipherSuite = 0xC023;
pub const TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384: SSLCipherSuite = 0xC024;
pub const TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256: SSLCipherSuite = 0xC025;
pub const T... | Rust | 0 |
= libc::c_long;
#[repr(C)]
#[derive(Copy, Clone)]
pub union __mbstate_t
{
pub __mbstate8: [libc::c_char; 128usize],
pub _mbstateL: __int64_t,
}
pub type time_t = __time_t;
pub type pid_t = __pid_t;
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct pthread
{
_unused: [u8; 0],
}
#[repr(C)]
#[derive(Debug,... | Rust | 0 |
ername".
#![deny(missing_docs)]
#![feature(format_args_capture)]
/// Defines a bunch of Endpoint implementing structs, which do not take any arguments.
pub mod endpoints;
mod util;
/// Defines Query implementing structs, which do take one or more arguments.
pub mod queries;
#[cfg(test)]
mod test;
#[derive(Debug)]
///... | Rust | 0 |
let base_high = system.read_operand(cpu, pc);
let base = (base_high as u16) << 8 | (base_low as u16);
let ea = base.wrapping_add(cpu.get_y() as u16);
if (ea & 0xFF00) != (base & 0xFF00) {
let pc = cpu.get_pc().wrapping_sub(1);
system.read_spurious(cpu, pc);
}
... | Rust | 0 |
rimes = Sieve::odd_primes().take(n + 1);
// in each iteration of the for loop, we use the value yielded
// by the previous iteration. This leaves one value left at the
// end, which we call NEXT_PRIME.
let mut x = primes.next().unwrap();
for next in primes {
// format the table
let ... | Rust | 0 |
: Option<String>,
context: Context,
}
static EMPTY_LIST: &[u8; 2] = b"[]";
impl ExecuteStoredProcedureBuilder {
pub(crate) fn new(client: StoredProcedureClient) -> Self {
Self {
client,
parameters: None,
consistency_level: None,
allow_tentative_writes: T... | Rust | 0 |
# Problem link - https://www.geeksforgeeks.org/problems/triplet-sum-in-array-1587115621/1
class QuickSort:
@staticmethod
def _get_partition_index(arr, low, high):
pivot = arr[low]
i, j = low, high
while i < j:
while arr[i] <= pivot and i <= high - 1:
i += 1
... | Python | 1 |
false) => panic!("Some tests failed"),
Err(e) => {
panic!("I/O failure during tests: {:?}", e);
},
}
}
fn run_ui_cargo(config: &mut compiletest::Config) {
fn run_tests(
config: &compiletest::Config,
filters: &[String],
mut tests: Vec<tester::TestDescAndFn>,
... | Rust | 0 |
rak{",
r"\mathsf{",
r"\mathbb{",
r"\mathtt{"];
fn tex_style(weight: &str, style: &str, content: &str) -> String {
// Calculate worst case size
let size = weight.len() + style.len() + content.len() + 4;
... | Rust | 0 |
from Crypto.PublicKey import RSA # Generation of RSA key pais [Public/Private]
from cryptography.fernet import Fernet # For generating Encryption Key
def rsa_key_gen(): # Private, Public Key generation
key = RSA.generate(2048)
private_key = key.export_key()
public_key = key.public_key().export_key()
... | Python | 1 |
the
/// caller must make sure that the buffer can be written to safely.
pub(crate) unsafe fn new<Word>(
handle: &Handle<T::Instance, state::Enabled>,
stream: T::Stream,
buffer: Pin<B>,
target: T,
address: u32,
direction: Direction,
)
-> ... | Rust | 0 |
from enum import Enum
class FindingType(Enum):
#INFO
INFO_HEADER = 1 #used for collecting raw headers
INFO_DIRECTIVE = 2 #used for recording directive info
INFO_URL = 3
#syntax issues
MISSING_SEMICOLON = 100
UNKNOWN_DIRECTIVE = 101
INVALID_KEYWORD = 102
IGNORED = 405
DEPRECATED... | Python | 1 |
123"
@pytest.mark.stage3
@pytest.mark.integration
def test_load_stage2_data_file_exists(self, stage3_processor):
"""🚨 整合測試:從檔案載入Stage2數據 (檔案存在時)"""
# 設置檔案載入模式
stage3_processor.input_data = None
# 模擬檔案存在
stage2_output_path = Path("/orbit-engine/data/outputs/stage2/s... | Python | 1 |
lf, config_file: Path) -> Optional[Dict[str, Any]]:
"""读取配置文件"""
try:
with open(config_file, 'r', encoding='utf-8') as f:
if config_file.suffix.lower() == '.json':
return json.load(f)
elif config_file.suffix.lower() in ['.yaml', '.yml']:
... | Python | 1 |
with open('people_finder.py', 'r') as file:
content = file.read()
content = content.replace("if meta_tag and 'content' in meta_tag.attrs:", "if meta_tag and meta_tag.get('content'):")
content = content.replace("return meta_tag['content']", "return meta_tag.get('content')")
content = content.replace("if img and... | Python | 1 |
from mage_ai.api.oauth_scope import OauthScope
from mage_ai.api.operations import constants
from mage_ai.api.policies.BasePolicy import BasePolicy
from mage_ai.api.presenters.SyncPresenter import SyncPresenter
class SyncPolicy(BasePolicy):
pass
SyncPolicy.allow_actions([
constants.DETAIL,
constants.LIST... | Python | 1 |
import sys
sys.path.append("../../")
import bmf
import time
from bmf.builder.ff_filter import decode
def extract_frame_test():
graph = bmf.graph({'dump_graph': 1})
video = graph.decode({
"input_path": "../../files/big_bunny_1min_30fps.mp4",
"video_params": {
"hwaccel": "cuda",
... | Python | 1 |
flags,
flagging_threshold: msg.flagging_threshold,
},
)?;
OWNER.initialize(deps.storage, info.sender)?;
Ok(Response::default())
}
#[cfg_attr(not(feature = "library"), entry_point)]
pub fn execute(
deps: DepsMut,
env: Env,
info: MessageInfo,
msg: ExecuteMsg,... | Rust | 0 |
let private_key = "1d9d6b11b9570e50a8511de539be9d125dda022b7d65452acc03de3aa3e87d6c";
let pri_key = hex::decode(private_key).unwrap();
let pub_key = KeyPair::get_public_key_from_private_key(&pri_key).unwrap();
let pub_key_hex = hex::encode(&pub_key);
assert_eq!(pub_key_hex, "03f9e9a50... | Rust | 0 |
if role.lower() in ["human"]:
role = "user"
elif role.lower() in ["ai", "assistant"]:
role = "assistant"
else:
# Default unexpected roles to user
role = "user"
return {"role": role, "content": conten... | Python | 1 |
belonging_to(&race)
.filter(runner_name.eq(&maybe_runner))
.first(&conn)
{
Ok(s) => s,
Err(_) => {
return Err(anyhow!(
"Could not find submission for runner \"{}\" in this race",
&maybe_runner
)
.into())
}
... | Rust | 0 |
flags'),
(_any_role, 'flags.work_klass'),
(_any_role, 'flush'),
(_any_role, 'httpx'),
(_any_role, 'HttpParser.state'),
(_any_role, 'HttpProtocolHandler'),
(_any_role, 'multiprocessing.Manager'),
(_any_role, 'proxy.core.base.tcp_upstream.TcpUpstreamConnectionHandler'),
(_any_role, 'work_k... | Python | 1 |
raw_ctx: *mut ffi::Context) -> ManuallyDrop<Secp256k1<AllPreallocated<'buf>>> {
ManuallyDrop::new(Secp256k1 {
ctx: raw_ctx,
phantom: PhantomData,
buf: ptr::null_mut::<[u8;0]>() as *mut [u8] ,
})
}
}
impl<'buf> Secp256k1<SignOnlyPreallocated<'buf>> {
/// Creat... | Rust | 0 |
inserts a table at the given path.
pub fn find_or_insert_table<'doc, I, V>(&'doc mut self, path: I)
-> Result<Table<'src, 'doc>, InsertTableError>
where I: IntoIterator<Item=V>, V: Into<Key<'src>>
{
let slice = path.into_iter().map(|v| v.into()).collect::<Vec<_>>();
let (table... | Rust | 0 |
Win32_Security\"`*"]
pub const szRPAREN: &str = ")";
#[doc = "*Required features: `\"Win32_Security\"`*"]
pub const wszCERTENROLLSHAREPATH: &str = "CertSrv\\CertEnroll";
#[doc = "*Required features: `\"Win32_Security\"`*"]
pub const wszFCSAPARM_CERTFILENAMESUFFIX: &str = "%4";
#[doc = "*Required features: `\"Win32_Secu... | Rust | 0 |
import os
import subprocess
import argparse
import shutil
from pathlib import Path
def run_command(cmd, cwd=None):
"""Run a shell command, streaming its output"""
process = subprocess.Popen(cmd, shell=True, cwd=cwd)
process.communicate()
if process.returncode != 0:
print(f"❌ Command failed with... | Python | 1 |
from typing import Callable, TYPE_CHECKING, Tuple, Type
from dataclasses import replace
import numpy as np
from .base import Field, ARG_TYPE
from ..pipeline.operation import Operation
from ..pipeline.state import State
from ..pipeline.allocation_query import AllocationQuery
if TYPE_CHECKING:
from ..memory_manage... | Python | 1 |
::as_bool)
}
}
pub fn read_long<R: Read>(reader: &mut R) -> Result<i64, Error> {
zag_i64(reader)
}
pub fn zig_i32(n: i32, buffer: &mut Vec<u8>) {
zig_i64(i64::from(n), buffer)
}
pub fn zig_i64(n: i64, buffer: &mut Vec<u8>) {
encode_variable(((n << 1) ^ (n >> 63)) as u64, buffer)
}
pub fn zag_i32<R: ... | Rust | 0 |
f'.. versionchanged:: {version}',
f'.. version-deprecated:: {version}',
f'.. deprecated:: {version}',
f'.. version-removed:: {version}',
f'.. versionremoved:: {version}',
]
def hl(no: int, line: str) -> str:
line = '<a name="L%s"> <... | Python | 1 |
NORMAL).unwrap();
let normal = match normal {
VertexAttributeValues::Float3(v) => v,
_ => panic!("invalid vertex type"),
};
//face 0
normal.push([1.0, 0.0, 0.0]);
normal.push([1.0, 0.0, 0.0]);
normal.push([1.0, 0.0, 0.0]);
normal.push([1.0, 0.0, 0.0]);
//face 1
norm... | Rust | 0 |
,)(\\d\\d\\d\\d)[\xa0\u202f]([a-zA-Zµ][a-zA-Z0-9Ωℓ⁰¹²³⁴⁵⁶⁷⁸⁹/·]*)(?![’'])(?![\\w–-])", False, '#1325p', 'num_nombre_quatre_chiffres', 4, [['_c_num_nombre_quatre_chiffres_1', '-', '=_s_num_nombre_quatre_chiffres_1', 1, 'Formatage des grands nombres.', '']]],
]],
["", [
['(?<![\\w.,–-])\\d\\d?\\d?(?:[.]\\d\\d\\d)... | Python | 1 |
.code {
Some(code) => code.clone(),
None => Lrc::new(MISC_OBLIGATION_CAUSE_CODE),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, Lift)]
pub struct UnifyReceiverContext<'tcx> {
pub assoc_item: ty::AssocItem,
pub param_env: ty::ParamEnv<'tcx>,
pub substs: SubstsRef<'tcx... | Rust | 0 |
atmosphere. Soft, natural lighting highlights the textures of the flowers, the cat’s fur, and the metallic shine of the vase.",
"a beautiful bouquet of soft pink and peach roses arranged in an ornate, reflective golden vase",
"a fluffy, blue-eyed Ragdoll cat, looking curious and elegant",
... | Python | 1 |
ronous calls, continuing");
None
}
WaitStatus::Stopped(pid, signal) => {
debug!("PID {} Stopped: signal {}", pid, signal);
match signal {
SIGSTOP | SIGCHLD => Some(pid),
SIGTRAP => Some(handle_trap(
... | Rust | 0 |
import numpy as np
from Utiliy import Create_kinetc_signal , Generate_matrix_withrate
def Check_best_residualts(time, Signal, model_matrix, taus, Spectra):
# generate parameters
N_states = 5
t_0 = 0
Scores = np.zeros(1)
GS_spectra = np.zeros([256,1])
Spectra = np.concatenate((Spectra,GS_spect... | Python | 1 |
et"),
help_text=_("Estimate of the lowest bracket for which this panel might be"))
bracket_max = models.FloatField(default=0,
verbose_name=_("maximum bracket"),
help_text=_("Estimate of the highest bracket for which this panel might be"))
room_rank = models.IntegerField(default=0,
... | Python | 1 |
from lpython import i32, f64, TypeVar
import numpy
H = TypeVar("H")
W = TypeVar("W")
def Pixel(H: i32, W: i32, Screen: i32[H, W], x: i32, y: i32) -> None:
if x >= 0 and y >= 0 and x < W and y < H:
Screen[H - 1 - y, x] = 255
def Clear(H: i32, W: i32, Screen: i32[H, W]):
i: i32
j: i32
for i in ... | Python | 1 |
g and argumentation skills",
"schedule": "Fridays, 3:30 PM - 5:30 PM",
"schedule_details": {
"days": ["Friday"],
"start_time": "15:30",
"end_time": "17:30"
},
"max_participants": 12,
"participants": ["charlotte@mergington.edu", "amelia@mergingt... | Python | 1 |
let (s_ch1, r_ch1) = mpsc::channel();
let s_ch1_engin = mpsc::Sender::clone(&s_ch1);
let (s_ch2, r_ch2) = mpsc::channel();
thread::spawn(|| {
create_body(s_ch1);
create_engin(s_ch1_engin);
assemble_car(s_ch2, r_ch1);
});
let handle = thread::spawn(|| {
sell_car(r_c... | Rust | 0 |
=> 105,
ServiceError::BalanceOverflow => 106,
ServiceError::TransferToSelf => 107,
ServiceError::ApproveToSelf => 108,
ServiceError::NotHexCaller => 109,
}
}
}
impl<T: Default> From<ServiceError> for ServiceResponse<T> {
fn from(err: ServiceError) -> Serv... | Rust | 0 |
aşabilmemizi sağlıyor.
# hayvan grubunun içindeki her bir hayvan için eğer hayvan kedi ise al ve cat generatoruna koy.Kedi yok ise bişey yapma
if len(group_of_animals) == 1:
survived_ones.append(group_of_animals[0])
elif cat and human:
survived_ones.append(human)
... | Python | 1 |
{
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x... | Rust | 0 |
, $msg:expr) => {{
if let Some(guild) = $msg.guild_id {
let data = $ctx.data.read();
let guilds = data
.get::<crate::lib::settings::guilds::GuildSettingsHandler>()
.expect("Expected GuildSettingsHandler in ShareMap.");
if let Some(guild_setting... | Rust | 0 |
,
("Focus assist", "start ms-settings:quiethours"),
("Graphics Settings", "start ms-settings:display-advancedgraphic"),
("Messaging", "start ms-settings:messaging"),
("Multitasking", "start ms-settings:multitasking"),
("Night light settings", "start ms-settings:nightlight"),
... | Rust | 0 |
.get_vs(vsid);
// NOTE:
// - If the requested VP was allocated, we need to tell the
// microkernel to destroy it. Once that is done we can
// deallocate the VsT so that it can be used again in the
// future.
//
if vs.is_allocated() {
bsl::expec... | Rust | 0 |
get = BoweHopwoodPedersenCRHGadget<MNT6G1Projective, MNT4Fr, MNT6G1Gadget>;
type BHMNT6Gadget = BoweHopwoodPedersenCRHGadget<MNT4G1Projective, MNT6Fr, MNT4G1Gadget>;
type BHMNT4Parameters = BoweHopwoodPedersenParameters<MNT6G1Projective>;
type BHMNT6Parameters = BoweHopwoodPedersenParameters<MNT4G1Projecti... | Rust | 0 |
control mode before using it, refer to project\'s readme', wait=True)
return True
config_manager.config['master-mode'] = True
self_activated_master_mode = True
cprint(f'MASTER CONTROL MODE: ON', "blue", attrs=['bold'])
speak('Activated Master Control Mode', wait=True)
... | Python | 1 |
f.emb_mix, self.emb_a)
emb_logit_b = torch.einsum('mc,cb->mb', self.emb_mix, self.emb_b)
emb = emb_logit_a.unsqueeze(2) + emb_logit_b.unsqueeze(1)
emb = F.softmax(emb.view(self.m, -1), dim=0).view(self.m, 1, 1, 1, 1, self.kernel_size, self.kernel_size)
v_out = emb * v_out
k_out... | Python | 1 |
mosaic_feature_map[:, 0, :] = feature_map[0, :]
feature_map_spatial = feature_map[1:, :].reshape(1, h, w, c)
feature_map_spatial_repeated = feature_map_spatial.repeat(h * w, 1, 1, 1) # 196, 14, 14, 192
spatial_order = torch.arange(h * w).reshape(h, w)
gaussian = to... | Python | 1 |
'''
This code is used for extracting car-following sequences
'''
import pandas as pd
# Define the CSV file path
csv_file = 'data\original_data.csv'
# Read the CSV file into a pandas DataFrame
df = pd.read_csv(csv_file, delimiter=',')
# Group by 'Vehicle_ID'
grouped_df = df.groupby('Vehicle_ID')
# List to hold d... | Python | 1 |
_TIMEOUT);
// Peer now decides to disconnect remote.
peer.outputs()
.find(|o| {
matches!(o, Io::Disconnect(
addr,
DisconnectReason::PeerTimeout("ping")
) if addr == &remote)
})
.expect("peer disconnects remote");
}
#[test]
fn test_... | Rust | 0 |
import frappe
from erpnext.setup.install import create_default_energy_point_rules
def execute():
frappe.reload_doc("social", "doctype", "energy_point_rule")
create_default_energy_point_rules()
| Python | 1 |
::as_array) {
Some(history) => {
assert_eq!(2, history.len());
}
_ => unreachable!(),
}
}
}
use crate::term::{Term, TermOrDef, Program};
use std::collections::HashMap;
use std::rc::Rc;
const MAX_RECURSION_DEPTH: i16 = 10;
fn count_max_binders(term: &Ter... | Rust | 0 |
ture = context.active_object
sub_coll_name = f"{armature.name}_FakeBones"
sub_coll = bpy.data.collections[sub_coll_name]
settings = context.scene.fake_bones_settings
cone_size = settings.cone_size
updated = False
for obj in sub_coll.objects:
if obj.name.endsw... | Python | 1 |
MSG_WAITALL: u32 = 0x100;
pub const MSG_FIN: u32 = 0x200;
pub const MSG_SYN: u32 = 0x400;
pub const MSG_CONFIRM: u32 = 0x800;
pub const MSG_RST: u32 = 0x1000;
pub const MSG_ERRQUEUE: u32 = 0x2000;
pub const MSG_NOSIGNAL: u32 = 0x4000;
pub const MSG_MORE: u32 = 0x8000;
pub const MSG_WAITFORONE: u32 = 0x10000;
pub const ... | Rust | 0 |
#!/usr/bin/env python3
import rospy
from std_msgs.msg import Float64
import time
def set_initial_positions():
# 初始化节点
rospy.init_node('set_initial_positions')
# 创建发布器
publishers = {
'joint_1': rospy.Publisher('/arm_controller/joint_1_position_controller/command', Float64, queue_size=1),
... | Python | 1 |
version = get_nightly_version() if is_nightly else detect_model_server_version()
print(f"-- {name} building version: {version}")
requirements = ["Pillow", "psutil", "packaging", "wheel"]
setup(
name=name,
version=version,
description="TorchServe is a tool for serving neural net m... | Python | 1 |
with a custom string creator.
"""
if self.custom_trial_name:
return self.custom_trial_name
if "env" in self.config:
env = self.config["env"]
if isinstance(env, type):
env = env.__name__
identifier = "{}_{}".format(self.trainable_na... | Python | 1 |
application_dienstnr").agg(
proces_count_last_year=pd.NamedAgg(column="pro_id_hist", aggfunc="size"),
)
features = features.join(
at_least_one_true(
df=applications_proces,
col_to_group_by="application_dienstnr",
col_to_sum="beheerp... | Python | 1 |
refill_interval = Some(refill_interval);
self
}
/// Set the refill amount to use.
#[inline(always)]
pub fn refill_amount(mut self, refill_amount: usize) -> Self {
self.refill_amount = Some(refill_amount);
self
}
/// Construct a new leaky bucket.
pub fn build(self) -... | Rust | 0 |
e sequence for rotary embeddings. Defaults to 0.
Returns:
torch.Tensor: Logits tensor of shape (batch_size, vocab_size).
"""
seqlen = tokens.size(1)
h = self.embed(tokens)
freqs_cis = self.freqs_cis[start_pos:start_pos+seqlen]
mask = None
if seqlen > ... | Python | 1 |
# vim: set expandtab shiftwidth=4 softtabstop=4:
# === UCSF ChimeraX Copyright ===
# Copyright 2022 Regents of the University of California. All rights reserved.
# The ChimeraX application is provided pursuant to the ChimeraX license
# agreement, which covers academic and commercial uses. For more details, see
# <http... | Python | 1 |
#!/usr/bin/python3
"""Rotate 2D Matrix"""
def rotate_2d_matrix(m):
"""Rotates 90 degrees clockwise a matrix in place.
Args:
m: n x n matrix.
"""
n = len(m[0])
for i in range(n // 2):
for j in range(i, n - i - 1):
temp = m[i][j]
m[i][j] = m[n - 1 - j][i]
... | Python | 1 |
p.start();
let hash_end = p.cur_tok().range().end;
p.expect(T![#]);
if p.at(T![ident]) && hash_end != p.cur_tok().start() {
// test_err private_member_name_with_space
// class A {
// # test;
// }
p.error(
p.err_builder("Unexpected space or comment betw... | Rust | 0 |
unsafe {
(*context.devcon).PSSetConstantBuffers(
1,
3,
&[
context.common.camera_buffer.ptr(),
self.data.ptr(),
context.common.light_buffer.ptr(),
][0],
);
(*... | Rust | 0 |
None else None,
"last_update": V0040Uint64NoVal.from_dict(obj["last_update"]) if obj.get("last_update") is not None else None,
"meta": V0040OpenapiMeta.from_dict(obj["meta"]) if obj.get("meta") is not None else None,
"errors": [V0040OpenapiError.from_dict(_item) for _item in obj["er... | Python | 1 |
: String,
/// 何路盤。
pub board_size: usize,
/// 大会用 out.txt 局面ファイルへのパス。
pub out_path: String,
/// 大会用 in.txt 局面ファイルへのパス。
pub in_path: String,
}
impl Config {
pub fn load(path:&str) -> Config {
let mut file = match File::open(path) {
Ok(n) => n,
Err(err) => p... | Rust | 0 |
# common/apf_navigator.py
import math
from common.coordinate import Coordinate
class ApfNavigator:
def __init__(
self,
k_att: float = 1.0, # 吸引力係數
k_rep: float = 1.5, # 排斥力係數
safe_dist: float = 1.0, # 物體安全距離 (m)
max_speed: float = 0.5 # UAV 速度上限 (m/s... | Python | 1 |
"""
URL configuration for recruitment app.
This module defines the URL patterns for recruitment and ATS endpoints.
"""
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from . import views
app_name = 'recruitment'
# Create router for ViewSets
router = DefaultRouter()
router.regi... | Python | 1 |
base,
pub garage_door: Arc<Mutex<GarageDoor>>,
// pub http_server: HttpServer,
pub iot_thing: IotThing,
pub rfid_reader: RfidReader,
pub root_logger: RootLogger,
pub slacker: Arc<Mutex<Slacker>>,
}
impl GreatManager {
pub fn new() -> Result<GreatManager, config::ConfigError> {
let configuration = Con... | Rust | 0 |
# Python bytecode 2.7 (decompiled from Python 2.7)
# Embedded file name: battle_royale/scripts/client/battle_royale/gui/Scaleform/daapi/view/battle/battle_loading.py
from gui.Scaleform.daapi.view.meta.BattleRoyaleLoadingMeta import BattleRoyaleLoadingMeta
from gui.impl.gen.resources import R
from gui.impl import backpo... | Python | 1 |
y);
}use regex::Regex;
use std::fmt;
fn main() {
let input = std::fs::read_to_string("input").unwrap();
challenge_1(&input);
challenge_2(&input);
}
fn challenge_1(input: &str) {
let ore = required_ore(input);
println!("Challenge 1: Required ore = {}", ore);
}
fn challenge_2(input: &str) {
le... | Rust | 0 |
()> {
let accept = accept.trim();
let accept = parse_accept_header(accept)?;
if accept.is_empty() {
return Err(anyhow!("Accept header is empty"));
}
let q_sxg = accept
.iter()
.filter_map(|t| {
if t.media_range
.primary_type
.eq_ign... | Rust | 0 |
def __init__(self):
self._transform = CustomTransform()
def get_transform(self):
return self._transform
def set_default_locators_and_formatters(self, axis):
axis.set_major_locator(AutoLocator())
axis.set_major_formatter(ScalarFormatter())
... | Python | 1 |
pop(&self, cpu_id: usize) -> Option<Tid>;
/// Got a tick from CPU.
/// Return true if need reschedule.
fn tick(&self, current_tid: Tid) -> bool;
/// Set priority of a thread.
fn set_priority(&self, tid: Tid, priority: u8);
}
fn expand<T: Default + Clone>(vec: &mut Vec<T>, id: usize) {
let len ... | Rust | 0 |
set.insert(345));
assert!(!set.insert(123));
println!("{:?}",set);
assert_eq!(set.into_iter().collect::<Vec<_>>(), vec![234, 345, 123]);
}
use std::any::Any;
use std::sync::Arc;
use std::time::{Duration, Instant};
use anyhow::Result;
use crossbeam::{channel as chan, select};
use log::*;
use synthizer as syz;
us... | Rust | 0 |
eign types, look at `deref-recursive-pathbuf.rs`.
// @has 'foo/struct.Foo.html'
// @has '-' '//*[@id="deref-methods-Bar"]' 'Methods from Deref<Target = Bar>'
// @has '-' '//*[@class="impl-items"]//*[@id="method.bar"]' 'pub fn bar(&self)'
// @has '-' '//*[@id="deref-methods-Baz"]' 'Methods from Deref<Target = Baz>'
// ... | Rust | 0 |
To find the `k`th smallest element in a given binary search tree (BST) without modifying the tree, we can perform an in-order traversal. In-order traversal of a BST processes nodes in ascending order. This can be accomplished using either recursion or an iterative approach with a stack. Here, we'll use an iterative app... | Python | 1 |
actual, actual_dnn = f(X)
actual_dnn = np.array(actual_dnn)
assert np.allclose(expected, actual)
assert np.allclose(actual, actual_dnn)
# Case 5: col shape < col stride
shp = (2, 2)
strd = (2, 3)
im_shp = (6, 4)
pool_it = max_pool(X_sym, pool_shape=shp, pool_stride=strd,
... | Python | 1 |
\x90\x8c\
\x01p\x17\x16\xc4\xe1,\x9f\xf7(]\x05\x0dp\xb4\xd3\
%\x00\x1dCz\xba\xb1R\x84\x92;\xa1\xd3\xa3\x0cA\
q\x96\xa9G\x00B\x8c\xdc\x1d\xb7\x10p\x09\x0c9\xd9\
\xba\x96\xf9\xa0M\x13\xe6\x98\xa8P\xb2\x99\x5c.Rk\
\xa3RNgq\x81\xb1\xe1\xa90\x1a\xef5\x070<\
\x02\x9b\xd8k\x0e\xbb^\x0b\xc5VwL;\x08o\xe2\
M\x11\x06\xbdHc \x1a\x... | Python | 1 |
id_to_bitmap: HashMap::new(),
viewport_width: 0,
viewport_height: 0,
use_color_transform_hack: is_firefox,
// For rendering non-smoothed bitmaps.
// crisp-edges works in Firefox, pixelated works in Chrome (and others)?
pixelated_property_value: if... | Rust | 0 |
g(id, 'status,status_str', 'status=2,status_str=待发货', '用户撤消退款,更新订单表,订单明细表状态')
if str(kuaid) == '1':
sql = "update wechat_mall_order set status=4,status_str='待自提' where usr_id=%s and wechat_user_id=%s and id=%s"
self.db.query(sql, [self.subusr_id, wechat_user_id, order_id])
sq... | Python | 1 |
b67cb9db30b32c138750377f6c3e1bb2f45588aeb0db1509f3562107f896b47d5b2c8972809e42e6bb68455": [
"file1.txt"
]
},
"message": "initial commit",
"user": {
"name": "<NAME>",
... | Rust | 0 |
levant info for your server...)".into()
};
check_msg(msg.author.dm(&ctx, |m| m.content(reply_txt)).await);
Ok(())
}
<reponame>TheSven73/executor
use core::future::Future;
use core::{
pin::Pin,
task::{Context, Poll},
};
struct Foo {}
impl Future for Foo {
type Output = ();
fn poll(self: Pin<&mut... | Rust | 0 |
tokens.peek().map(|token| &token.value) {
Some(TokenKind::Semicolon) => None,
Some(TokenKind::TypeName(_)) => Some(parse_declaration(ctx, tokens)?),
_ => Some(parse_expr(ctx, tokens)?),
};
consume(tokens, TokenKind::Semicolon)?;
let cond = match tokens.peek().map(|token| &token.valu... | Rust | 0 |
cx_public_agent_deserialize(command_handle: {}, agent_json: {})", command_handle, agent_json);
execute(move || {
match agent::from_string(&agent_json) {
Ok(agent_handle) => {
trace!("vcx_public_agent_deserialize_cb(command_handle: {}, rc: {}, agent_handle: {})",
... | Rust | 0 |
// pi/2 around z also
expect_quaternion_eq!(
Quaternion::from_vectors(&Float3::new(0.707106769, 0.707106769, 0.0),
&Float3::new(-0.707106769, 0.707106769, 0.0)),
0.0, 0.0, 0.707106769, 0.707106769);
// Aligned vectors
expect_quaternion... | Rust | 0 |
os::raw::{c_char, c_int, c_uchar, c_ushort, c_void};
use std::path::Path;
use std::sync::atomic::{AtomicPtr, Ordering};
use std::sync::Mutex;
use std::thread_local;
mod config;
mod redir;
/////////////////////////////////////// Symbol lookup/redirection ///////////////////////////////////////
macro_rules! as_char_pt... | Rust | 0 |
from datetime import datetime
##global variables for strategy
close_up = 0.1
close_down = 0.1
rsi_up = 65
rsi_down = 35
stoploss_percentage = 0.1
target_percentage = 0.2
lot_size = 50
##global variables for processing tick data
candle_time = 5 # in minutes
sma_period = 10 # simple moving average, previous 10 candl... | Python | 1 |
64);
stress_test_load_store!();
stress_test_load_swap!();
}
<filename>src/test/ui/feature-gates/feature-gate-type_alias_impl_trait.rs<gh_stars>10-100
use std::fmt::Debug;
type Foo = impl Debug; //~ ERROR `impl Trait` in type aliases is unstable
trait Bar {
type Baa: Debug;
fn define() -> Self::Baa;
}... | Rust | 0 |
for key, value in elem.items():
if isinstance(key, QName):
key = key.text
if key not in qnames:
add_qname(key)
if isinstance(value, QName) and value.text not in qnames:
add_qname(value.text)
text = elem.text
if ... | Python | 1 |
0_config_file(serv00_ct8_dir, 'heartbeat.conf')
return SysConfigEntry(sys_config_file), heart_beat_config_file
def main() -> None:
try:
logger.info(f"==============> 开始心跳模块 <==============")
host_name, user_name = utils.get_hostname_and_username()
private_key_file = utils.get_ssh_ed255... | Python | 1 |
import asyncio
import httpx
import json
MCP_URL = "http://localhost:8000/mcp"
async def call_tool_http(method, arguments, id=1):
payload = {
"jsonrpc": "2.0",
"method": "tools/call",
"params": {
"name": method,
"arguments": arguments
},
"id": id
... | Python | 1 |
ed("int", vec![]);
/// assert_eq!(t, t_eq);
/// ```
///
/// Make a variable type:
///
/// ```
/// # use polytype::{tp, Type};
/// let t = tp!(0);
/// assert_eq!(format!("{}", t), "t0");
/// // Equivalent to:
/// let t_eq = Type::Variable(0);
/// assert_eq!(t, t_eq);
/// ```
///
/// Make a composite type:
///
/// ```
//... | Rust | 0 |
error!("FileInfoMgr::get_range_block: failed to send get range block for ino: {}, offset: {}, size: {} err: {:?}",
ino, offset, size, err);
return Errno::Eintr;
}
}
}
pub fn send_flush(&self, ino: u64, fh: u64, req_id: u64, tx: Sender<MetaOpAs... | Rust | 0 |
from PyQt5.QtWidgets import QApplication
import rclpy.logging
from rclpy.node import Node
from qasync import QEventLoop
from PyQt5.QtCore import QThread
import rclpy
import asyncio
import signal
from .main_window import MainWindow
class Supervisor(Node):
def __init__(self):
super().__init__('radar_super... | Python | 1 |
<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
if self.channel.lock(|c| c.is_closed_with_context(Some(cx))) {
Poll::Ready(())
} else {
Poll::Pending
}
}
}
impl<'ch, M, T, const N: usize> Drop for Sender<'ch, M, T, N>
where
M: MutexKind,
{
fn drop(... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.