text string | label_name string | labels int64 |
|---|---|---|
{
// Check if we have a valid UTF-8 string
if let Ok(name) = str::from_utf8(&file[name_start + 1..name_end - 1]) {
let mut buffer = std::mem::take(&mut buffer);
for _ in 0..newline_size {
buffer.pop();
}... | Rust | 0 |
with self.neo4j_driver.session() as session:
for match in response['matches']:
query = """
MATCH (i:Image {id: $image_id})
RETURN i
"""
result = session.run(query, image_id=match['vectorId'])
... | Python | 1 |
_START};
use crate::to_romaji::TO_ROMAJI_NODE_TREE;
use crate::utils::is_char_katakana::*;
use crate::utils::is_char_long_dash::*;
use crate::utils::is_char_slash_dot::*;
use fnv::FnvHashMap;
use std;
pub fn is_char_initial_long_dash(char: char, index: usize) -> bool {
is_char_long_dash(char) && index == 0
}
pub f... | Rust | 0 |
"""Tests for rotary positional embedding."""
import pytest
import torch
from cinema.rotary import RotaryEmbedding, apply_rotary_emb, rotate_half
def test_rotate_half() -> None:
"""Test rotate_half."""
x = torch.tensor([[[[1, 2], [3, 4]]]])
expected = torch.tensor([[[[-2, 1], [-4, 3]]]])
assert torch... | Python | 1 |
umb_ldrsp_r1,
thumb_ldrsp_r2,
thumb_ldrsp_r3,
thumb_ldrsp_r4,
thumb_ldrsp_r5,
thumb_ldrsp_r6,
thumb_ldrsp_r7,
/* 0xA */
thumb_addpc_r0,
thumb_addpc_r1,
thumb_addpc_r2,
thumb_addpc_r3,
thumb_addpc_r4,
thumb_addpc_r5,
thumb_addpc_r6,
thumb_addpc_r7,
thumb_ad... | Rust | 0 |
Initial => dest.write_str("initial"),
CSSWideKeyword::Inherit => dest.write_str("inherit"),
CSSWideKeyword::Unset => dest.write_str("unset"),
CSSWideKeyword::Revert => dest.write_str("revert"),
}
}
}
/*
* $Id$
*
* Copyright (c) 2021, <NAME>.
* All rights reserved.
*
* Redistribution and use in source ... | Rust | 0 |
lmholtz_energy_density: Vec<Array<Dual64, D>> =
Vec::with_capacity(functional_contributions.len() + 1);
helmholtz_energy_density.push(
self.ideal_chain_contribution()
.calculate_helmholtz_energy_density(&density.mapv(Dual64::from))?,
);
for (c, wd) in fun... | Rust | 0 |
# Binarian
# Copyright (C) 2025 Sarahtonin & Lyxminx
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program ... | Python | 1 |
///
/// `VEX.256.0F.WIG 59 /r`
///
/// `AVX`
///
/// `16/32/64-bit`
VEX_Vmulps_ymm_ymm_ymmm256 = 1356,
/// `VMULPS xmm1 {k1}{z}, xmm2, xmm3/m128/m32bcst`
///
/// `EVEX.128.0F.W0 59 /r`
///
/// `AVX512VL and AVX512F`
///
/// `16/32/64-bit`
EVEX_Vmulps_xmm_k1z_xmm_xmmm128b32 = 1357,
/// `VMULPS ymm1 {k1}... | Rust | 0 |
None
}
};
let mut cli = self.cli.take().unwrap();
let greeting = self.greeting.take();
loop {
cli.run(&mut self, greeting.unwrap_or(DEFAULT_GREETING));
}
}
}
<reponame>georgbramm/rust-se
use mongodb::oid::ObjectId;
use primitive_types::{H160, U256};
u... | Rust | 0 |
001, 0.002), 5)
nodei.recievequeuedict[bb1] = nodei.recievequeuedict[bb]
del nodei.recievequeuedict[bb]
nodei.sendqueuedict.update(nodei.recievequeuedict)
nodei.recievequeuedict={}
# print(f'after {nodei.nodeid} nodei.sendqueuedict:{nod... | Python | 1 |
hutil.copytree('llmuses', proj_dir)
shutil.copy('requirements/requirements.txt', 'package/requirements.txt')
shutil.copy('README.md', 'package/README.md')
if __name__ == '__main__':
print('Usage: python3 setup.py bdist_wheel')
pack_resource()
os.chdir('package')
install_requires, deps_link = ... | Python | 1 |
.h
pub const B_LIVE_QUERY: u32 = 0x00000001;
pub const B_QUERY_NON_INDEXED: u32 = 0x00000002;
// kernel/fs_volume.h
pub const B_MOUNT_READ_ONLY: u32 = 1;
pub const B_MOUNT_VIRTUAL_DEVICE: u32 = 2;
pub const B_FORCE_UNMOUNT: u32 = 1;
// kernel/image.h
pub const B_FLUSH_DCACHE: u32 = 0x0001;
pub const B_FLUSH_ICACHE: u... | Rust | 0 |
related methods) or `finish()` after `finish()` has completed without
/// error is invalid and will panic.
///
/// # Errors
///
/// Base64 encoding itself does not generate errors, but errors from the wrapped writer will be
/// returned as per the contract of `Write`.
///
/// # Performance
///
/// It has some minor per... | Rust | 0 |
mat!(":{:0<4X}", *(p as *const u16)).as_str());
}
*/
}
return Err(ErrorKind::Nix(nix::Error::Sys(Errno::EINVAL)).into());
}
impl Drop for RtnlHandle {
fn drop(&mut self) {
unsafe {
libc::close(self.fd);
}
}
}
pub struct RtRoute {
pub dest: Option<Ve... | Rust | 0 |
roof().0;
let validation_data = PersistedValidationData {
relay_parent_number: 1,
parent_head: parent_header.encode().into(),
..Default::default()
};
let block = client
.init_block_builder_with_timestamp(
&at,
Some(validation_data),
sproof_builder,
timestamp,
)
.build_parachain... | Rust | 0 |
total_jobs += jobs_found
log("Number of new positions found for \"{query}\": {count}/{jobs_found}".format(query=query, count=len(job_results), jobs_found=jobs_found))
if (len(jobs) == 0):
jobs = job_results
else:
for job in job_results:
found = Fa... | Python | 1 |
jl_is_unary_and_binary_operator(
sym: *mut ::std::os::raw::c_char,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn jl_operator_precedence(sym: *mut ::std::os::raw::c_char) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn jl_apply_generic(
F: *mut jl_value_t,
args: *mut *mut jl_value... | Rust | 0 |
ase_balance(state, index as u64, amount).unwrap();
return;
}
}
//# Verify the deposit signature (proof of possession) for new validators.
//# Note: The deposit contract does not check signatures.
//# Note: Deposits are valid across forks, thus the deposit domain is retrieved directly... | Rust | 0 |
"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
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 f... | Rust | 0 |
builder().status(200).body(Body::from(s)),
Err(TeketekeError::InternalError(s)) => {
Response::builder().status(417).body(Body::from(s))
}
_ => Response::builder()
.status(... | Rust | 0 |
ady!(self.resolution.poll()) {
Update::Add(endpoints) => {
for (addr, endpoint) in endpoints.into_iter() {
self.active.insert(addr);
self.pending.push_back(Change::Insert(addr, endpoint));
}
}
... | Rust | 0 |
from academia_mcp.tools import (
s2_get_citations,
s2_get_references,
s2_corpus_id_from_arxiv_id,
s2_get_info,
)
def test_s2_citations_pingpong() -> None:
citations = s2_get_citations("2409.06820")
assert citations.total_count >= 1
assert "2502.18308" in str(citations.results)
def test_s... | Python | 1 |
"""Removed unique from name and added unique constraints on User Settings table
Revision ID: b418df217fab
Revises: a91aa25dd787
Create Date: 2025-05-19 00:31:33.665641
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = 'b41... | Python | 1 |
# from RNN.time_series_prediction.Sensor import *
import os
os.environ['CUDA_VISIBLE_DEVICES'] = '-1'
from Sensor import Sensors
import os
# configuration
save_info = 1 # 1: save information in file, 0: do not save
train = 0 # 1: train model, 0: load model
n_lag = 1
n_epochs = 100
dataset_path = os.pa... | Python | 1 |
NativeType::IntervalYM => Ok(self.get_interval_ym_unchecked()?.to_string()),
NativeType::CLOB => self.get_clob_as_string_unchecked(),
NativeType::BLOB => self.get_blob_as_hex_string_unchecked(),
NativeType::Object(ref objtype) => {
if objtype.is_collection() {
... | Rust | 0 |
position for second Channel-2 label"
assert anim_panel.fig.texts[3].get_position()[0] > 0.5, "Wrong x position for second Channel-2 label"
def test_animationpanel_time_slider():
anim_panel.microanims[0,0].add_time_stamp(unit='MM', unit_per_frame=3, location='lower left')
anim_panel.time_slider.v... | Python | 1 |
Do not put anything below this section - it will be ignored
*View 1
$192-192-192,0,Times New Roman|12||0-0-0|0-0-0|0-0-255|-1--1--1|-1--1--1|72,72,100,0
10,1,Stock,351,249,40,20,3,3,0,0,0,0,0,0
12,2,48,513,251,10,8,0,3,0,0,-1,0,0,0
1,4,6,2,4,0,0,22,0,0,0,-1--1--1,,1|(478,251)|
1,5,6,1,100,0,0,22,0,0,0,-1--1--1,,1|(41... | Rust | 0 |
_each(|(x, y, z)| println!("(AxisMap::{},AxisMap::{},AxisMap::{}),", x, y, z));
}
// Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use std::collections::{HashMap, HashSet};
type EntityReference = String;... | Rust | 0 |
t2 = centers[idx], centers[idx+1]
self.draw_line_alpha(drawn_frame, pt1, pt2,
line_rgb, line_alpha,
thickness=line_thickness)
# Only draw lines in mask if line_alpha is non-zero
if line_alpha > 0:
... | Python | 1 |
}
}
}
fn perform_sort<D: Distinct>(
&self,
mut distinct: D,
matching_words: MatchingWords,
mut criteria: Final,
) -> Result<SearchResult> {
let mut offset = self.offset;
let mut initial_candidates = RoaringBitmap::new();
let mut e... | Rust | 0 |
t, "** لم يتم تفعيل الاسم الوقتي للكروب/القناة بالأصل **")
END_CMDS = [
"الصورة الوقتية",
"اسم وقتي",
"بايو وقتي",
"كروب وقتي",
"كروب صورة وقتي",
]
if input_str not in END_CMDS:
await edit_delete(
event,
f"عـذرا يجـب استـخدام الامـر بشـ... | Python | 1 |
/// ```
fn check_device_state(&self, destination_window: impl AsHWND) -> ErrorKind {
ErrorKind(unsafe { self.as_winapi().CheckDeviceState(destination_window.as_hwnd()) })
}
/// \[[docs.microsoft.com](https://docs.microsoft.com/en-us/windows/win32/api/d3d9/nf-d3d9-idirect3ddevice9ex-checkresour... | Rust | 0 |
_trait_with_sync::async_trait(Sync)]
impl Constructor for SingletonDependency {
async fn ctor(_: anthill_di::DependencyContext) -> BuildDependencyResult<Self> {
Ok(Self { str: "test".to_string() })
}
}
pub fn benchmark_single_singleton_set_get(c: &mut Criterion) {
c.bench_function("benchmark_singl... | Rust | 0 |
test(enable = "neon")]
unsafe fn test_vmulq_s8() {
let a: i8x16 = i8x16::new(1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2);
let b: i8x16 = i8x16::new(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16);
let e: i8x16 = i8x16::new(1, 4, 3, 8, 5, 12, 7, 16, 9, 20, 11, 24, 13, 28, 15, 32);
... | Rust | 0 |
import pandas as pd
def remove_repeated_gyro_values(excel_in, excel_out):
"""
从 excel_in 中读取数据,逐行扫描 gyro_x, gyro_y, gyro_z:
- 对第一行,直接保留原值;
- 对后续行,若与“上一次非 0 行”的三项值完全相同,则设为 0,否则保留并更新“上一次非 0 行”的记录。
处理后输出到 excel_out。
"""
df = pd.read_excel(excel_in)
required_cols = ["gyro_x", "gyro_y",... | Python | 1 |
let root = parser.parse_script(stack_limit);
let errors = parser.errors();
let sc_state = parser.into_sc_state();
(root, errors, sc_state)
}
//! Data collection for network usage/IO.
//!
//! For Linux and macOS, this is handled by Heim.
//! For Windows, this is handled by sysinfo.
cfg_if::cfg_if! {
if ... | Rust | 0 |
::ErrorKind::Other, e))?;
Ok(())
}
<reponame>EgorRepnikov/storage
use actix_web::web::Json;
#[derive(Debug, Deserialize, Serialize, PartialEq)]
pub struct HealthResponse {
status: String
}
pub async fn health() -> Result<Json<HealthResponse>, ()> {
Ok(Json(HealthResponse {
status: "OK".into()
... | Rust | 0 |
xtern crate netbricks;
use netbricks::common::Result;
use netbricks::config::load_config;
use netbricks::interface::{PacketRx, PacketTx};
use netbricks::operators::{mpsc_batch, Batch, Enqueue, MpscProducer, ReceiveBatch};
use netbricks::packets::icmp::v6::{EchoReply, EchoRequest, Icmpv6};
use netbricks::packets::ip::v6... | Rust | 0 |
:fmt::Result {
self.0.fmt(f)
}
}
impl ::core::fmt::Debug for Dbgctrl {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
try!(write!(f, "[0x{:08x}", self.0));
if self.dbgstop() != 0 { try!(write!(f, " dbgstop"))}
try!(write!(f, "]"));
Ok(())
}
}... | Rust | 0 |
e number of markers along with whether the choice was sticky and the remaining line.
pub fn parse_choice_markers_and_text(
content: &str,
) -> Result<Option<(u32, bool, &str)>, LineErrorKind> {
let is_sticky = marker_exists_before_text(content, STICKY_CHOICE_MARKER);
let is_not_sticky = marker_exists_before... | Rust | 0 |
ate-pallet-tfgrid
#![cfg_attr(not(feature = "std"), no_std)]
/// Edit this file to define custom logic or remove it if it is not needed.
/// Learn more about FRAME and the core library of Substrate FRAME pallets:
/// https://substrate.dev/docs/en/knowledgebase/runtime/frame
use frame_support::{
decl_error, decl_even... | Rust | 0 |
contains(ttrace.0) {
continue;
}
let score = trace_similiarity(&trace, &ttrace.1);
if score < min {
min = score;
best = &ttrace.1;
id = *ttrace.0;
}
}
paired.insert(id);
ret.push((trac... | Rust | 0 |
# features/twap.py
from __future__ import annotations
import datetime as dt
import pandas as pd
from feature_base import BaseFeature, FeatureContext
class TwapFeature(BaseFeature):
"""
09:30–15:59(交易所本地时区,默认 America/New_York) 内,
按 symbol 计算 close 的均值;若该 symbol 当日无有效点,则 NaN。
输出: ['symbol', 'value']。
... | Python | 1 |
params.get("chart_ref"),
" ".join(helm_pull_opts),
)
if not module.check_mode:
rc, out, err = module.run_helm_command(helm_cmd_common, fails_on_error=False)
else:
rc, out, err = (0, "", "")
if rc == 0:
module.exit_json(
failed=False,
changed=True,... | Python | 1 |
import torch
import torch.nn as nn
import torch.nn.functional as F
from lib.models.backbones.backbone_selector import BackboneSelector
from lib.models.tools.module_helper import ModuleHelper
class ISANet(nn.Module):
"""
Interlaced Sparse Self-Attention for Semantic Segmentation
"""
def __init__(self,... | Python | 1 |
to())
}
fn handle_rpc_single(
&mut self,
space: Arc<KitsuneSpace>,
to_agent: Arc<KitsuneAgent>,
from_agent: Arc<KitsuneAgent>,
payload: Vec<u8>,
timeout_ms: Option<u64>,
) -> KitsuneP2pHandlerResult<Vec<u8>> {
let space_sender = match self.spaces.get_... | Rust | 0 |
from mock import patch, Mock
from arctic._compression import compress, compress_array, decompress, decompress_array, enable_parallel_lz4
def test_compress():
assert len(compress(b'foobar')) > 0
def test_compress_LZ4():
cfn = Mock()
with patch('arctic._compression.lz4_compress', cfn):
compress(b... | Python | 1 |
price,
side: _side,
qty,
ts: _ts,
} => self.validate_amend(id, price, qty),
OrderRequest::CancelOrder { id, side: _side } => self.validate_cancel(id),
}
}
/* Internal validators */
fn validate_market(
... | Rust | 0 |
peat_last_pre_step: bool = False,
) -> Tuple[Dataset, Dataset, TSamplesMap]:
# TODO: Doesn't check whether the time index on cov, targ, treat etc. matches.
data_0_kwargs, data_1_kwargs = dict(), dict()
samples_count_map = None
for container_name, container in data.temporal_data_containers.items():
... | Python | 1 |
cutor("debug", mod=mod)
defunc_ex = relay.create_executor("debug", mod=defunc_mod)
out = ex.evaluate()(input)
defunc_out = defunc_ex.evaluate()(input)
np.testing.assert_equal(out.asnumpy(), defunc_out.asnumpy())
def test_global_recursion():
code = """
#[version = "0.0.5"]
type List[A] {
Cons(A... | Python | 1 |
# 1910. Remove All Occurrences of a Substring
# Given two strings s and part, perform the following operation on s until all occurrences of the substring part are removed:
# Find the leftmost occurrence of the substring part and remove it from s.
# Return s after removing all occurrences of part.
# A substring is a ... | Python | 1 |
because the `grouper` object ensures it.
req_args = all_gen_kwargs[0]
# unpack our keyword arguments.
until = get_until(req_args)
max_gen_toks = req_args.get("max_gen_toks", self.max_gen_toks)
remaining_length = self.max_length - max_gen_toks
cont... | Python | 1 |
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LogNorm
import h5py
import matplotlib.animation as animation
# =============================================================================
# Plot results
# =============================================================================
#... | Python | 1 |
from . import _AWS
class _Storage(_AWS):
_type = "storage"
_icon_dir = "resource_images/aws/storage"
class Backup(_Storage):
_icon = "backup.png"
class CloudendureDisasterRecovery(_Storage):
_icon = "cloudendure-disaster-recovery.png"
class EFSInfrequentaccessPrimaryBg(_Storage):
_icon = "ef... | Python | 1 |
atchVtbl)
{}}
RIDL!{#[uuid(0x5eb06bef, 0x4adf, 0x3cc1, 0xa6, 0xf2, 0x62, 0xf7, 0x68, 0x86, 0xb1, 0x3a)]
interface _SoapName(_SoapNameVtbl): IDispatch(IDispatchVtbl)
{}}
RIDL!{#[uuid(0x7947a829, 0xadb5, 0x34d0, 0x9c, 0xc8, 0x6c, 0x17, 0x27, 0x42, 0xc8, 0x03)]
interface _SoapIdrefs(_SoapIdrefsVtbl): IDispatch(IDisp... | Rust | 0 |
#!/usr/bin/env python3
"""
Timing utilities
Copyright (c) 2023 ROX Automation - Jev Kuznetsov
"""
import asyncio
import time
import logging
from functools import wraps
def timeit(func):
@wraps(func)
async def async_wrapper(*args, **kwargs):
logger = logging.getLogger(func.__module__)
start_... | Python | 1 |
# Import necessary libraries
import matplotlib.pyplot as plt
import os
import pickle
from agents.orignal_players import Generous, Selfish, RandomPlayer, CopyCat, Grudger, Detective, Simpleton, Copykitten
from agents import *
from tqdm import tqdm
from agents.ppo_agent import *
from game import Game, save_q_table, load... | Python | 1 |
"""
A development config to test BinderHub locally.
Run `jupyterhub --config=binderhub_config.py` terminal
Host IP is needed in a few places
"""
import os
import socket
from dockerspawner import DockerSpawner
from binderhub.binderspawner_mixin import BinderSpawnerMixin
def random_port() -> int:
"""Get a singl... | Python | 1 |
'PROXYLIST_DOWNLOAD_SOCKS4', 'PROXYLIST_DOWNLOAD_SOCKS5'}:
matches = findall(r'\d+\.\d+\.\d+\.\d+</td>\s*<td>\d+', r.text)
self.proxies = [sub(r"</td>\s*<td>", ":", m) for m in matches]
else:
matches = findall(r'\d+\.\d+\.\d+\.\d+</td><... | Python | 1 |
index to get the probability of the action
pred_prob = res[index_res]
# New confidence code:
last_pred = predictions[-10:]
last_values, last_counts = np.unique(last_pred, return_counts=True)
# last_values will be either [0] or [0 1] or [1]
... | Python | 1 |
from ast import List
import sys
import re
import math
from itertools import combinations
from collections import defaultdict, Counter
from functools import cache
import copy
import time
sys.setrecursionlimit(10**6)
drr = [(0,-1), (1,0), (0,1), (-1,0)]
f = open("2024/10/test_input.txt").read().strip()
f = open("2024/10/... | Python | 1 |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models
class EventRegistration(models.Model):
""" Store answers on attendees. """
_inherit = 'event.registration'
registration_answer_ids = fields.One2many('event.registration.answ... | Python | 1 |
"""
(*)~---------------------------------------------------------------------------
Pupil - eye tracking platform
Copyright (C) Pupil Labs
Distributed under the terms of the GNU
Lesser General Public License (LGPL v3.0).
See COPYING and COPYING.LESSER for license details.
----------------------------------------------... | Python | 1 |
elf, v: u64) -> Result<ConsistencyValue, E> {
Ok(ConsistencyValue::Explicit(v as u32))
}
fn visit_u32<E: de::Error>(self, v: u32) -> Result<ConsistencyValue, E> {
Ok(ConsistencyValue::Explicit(v))
}
fn visit_u16<E: de::Error>(self, v: u16) -> Result<ConsistencyV... | Rust | 0 |
ssage(LinearCmd::new(0, vec![VectorSubcommand::new(0, 200, 0.51)]).into())
.await
.unwrap();
check_test_recv_value(
&command_receiver,
DeviceImplCommand::Write(DeviceWriteCmd::new(
Endpoint::Tx,
vec![
0x01, 0x10, 0x00, 0x6b, 0x00, 0x05, 0x0a, 0x00, 0... | Rust | 0 |
# -*- coding: utf-8 -*-
"""
meta attributes for packaging which does not import any dependencies
"""
__version__ = '3.1.0'
__author__ = u'python-ldap project'
__license__ = 'Python style'
| Python | 1 |
list::<_, u64>("foo").len(), 3);
}
}
// vim: tw=80
#![deny(warnings)]
use mockall::*;
mock! {
MyIter {}
impl Iterator for MyIter {
type Item=u32;
fn next(&mut self) -> Option<u32>;
}
}
#[test]
fn returning() {
let mut mock = MockMyIter::new();
mock.expect_next()
.retu... | Rust | 0 |
, &squared_euclidean).unwrap().iter() {
println!("P: {:?}", p);
}
}
// Copyright 2019 Parity Technologies (UK) Ltd.
//
// 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 withou... | Rust | 0 |
ature_fraction=0.8,
bagging_fraction=0.8,
bagging_freq=5,
verbosity=-1,
random_state=42,
n_jobs=-1
)
model.fit(X_train, y_train)
... | Python | 1 |
art_timestamp_nanos: AnyProperty,
}
});
}
#[fuchsia::test]
fn processing_time_tracker() {
let inspector = Inspector::new();
let mut tracker = ProcessingTimeTracker::new(inspector.root().create_child("test"));
tracker.track("a", 1e9 as u64);
assert_data_t... | Rust | 0 |
er is located.
//!
//! The `State` type from each module is a dynamic representation of register state, useful for
//! storing the state of multiple registers in a collection.
//!
//! The `Map` type from each module is a collection that is guaranteed to contain the state of all
//! registers. This is useful for remotel... | Rust | 0 |
::CooMatrix`)
//! support multiplication with scalars, in addition to division by a scalar.
//! Note that only `Matrix * Scalar` works in a generic context, although `Scalar * Matrix`
//! has been implemented for many of the built-in arithmetic types. This is due to a fundamental
//! restriction of the Rust type system... | Rust | 0 |
REFH_R(crate::FieldReader<u8, u8>);
impl TOUCH_DREFH_R {
#[inline(always)]
pub(crate) fn new(bits: u8) -> Self {
TOUCH_DREFH_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for TOUCH_DREFH_R {
type Target = crate::FieldReader<u8, u8>;
#[inline(always)]
fn deref(&self) -> &Self... | Rust | 0 |
import tclab
import time
import numpy as np
from simple_pid import PID
import matplotlib.pyplot as plt
# process model
Kp = 0.9
taup = 175.0
thetap = 15.0
c = ['IMC','ITAE']
for xi,ci in enumerate(c):
if ci=='IMC':
# -----------------------------
# Calculate Kc,tauI,tauD (IMC Aggressive)
... | Python | 1 |
Ok(())
} else if num < INTERRUPT_PLATFORM_START {
Err(PendInterruptLineError::BadParam)
} else {
// Safety: We are delegating the call in the intended way
unsafe { <System as InterruptController>::pend_interrupt_line(num) }
}
}
#[inline]
... | Rust | 0 |
#!/usr/bin/python
#coding: utf-8
# -------------------------------------------------------------------
# aapanel
# -------------------------------------------------------------------
# Copyright (c) 2015-2099 aapanel(http://www.aapanel.com) All rights reserved.
# --------------------------------------------------------... | Python | 1 |
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import xarray as xr
import geocat.viz as gv
#随便设置一些内容
plt.rcParams['axes.unicode_minus'] = False
plt.rcParams.update({"font.size":12})
plt.rcParams['xtick.direction'] = 'out'#x刻度线方向
plt.rcParams['ytick.direction'] = 'out'#y轴的刻度方向
plt.rcParams['xtic... | Python | 1 |
print("2. View Marks")
print("3. Logout")
choice = input("Enter choice: ")
if choice == "1":
print(f"Roll No: {student[0]}, Name: {student[1]}")
elif choice == "2":
view_marks_student(roll_no)
elif choice == "3":
... | Python | 1 |
.ok_or_else(|| der::Tag::ContextSpecific(PUBLIC_KEY_TAG).value_error())?
.bit_string()?;
if let Ok(pk) = sec1::EncodedPoint::<C>::from_bytes(public_key.as_ref()) {
if C::validate_public_key(&secret_key, &pk).is_ok() {
return Ok(secret_key);
... | Rust | 0 |
etric_autoencoder_kl_from_original_checkpoint(
scale: Literal["1.5", "2"], original_checkpoint_path: str, map_location: torch.device
) -> AsymmetricAutoencoderKL:
print("Loading original state_dict")
original_state_dict = torch.load(original_checkpoint_path, map_location=map_location)
original_state_dic... | Python | 1 |
for the scheduler
* @return a list of tasks
*/
pub fn get_tasks() -> Vec<ScheduledTask> {
let mut tasks: Vec<ScheduledTask> = Vec::new();
let conn = rusqlite::Connection::open("rori.db").unwrap();
let mut stmt = conn.prepare("SELECT * FROM scheduler").unwrap();
let mut row... | Rust | 0 |
# MG additional stuff
self.dedent = dedent
self.debug = debug
def __call__(self, func):
func.__doc__ = func.__doc__ if func.__doc__ else ''
self.addendum = self.addendum if self.addendum else ''
if self.dedent:
docitems = [dedent(func.__doc__), dedent(s... | Python | 1 |
import requests
ATBASH = [
["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M"],
["Z", "Y", "X", "W", "V", "U", "T", "S", "R", "Q", "P", "O", "N"],
]
INITIAL_TEXT = "UNQDBBYKKNHACSYZCIKIUKTRILEKLZOAHNXJTZPFEZPHZVHRSJWWFNEX"
def load_french_words() -> list[str]:
'''
Load a list of Fr... | Python | 1 |
impl_parser!(
(ParseHex, ParseHexGen) for NtHex,
|i: u8| i.count_ones() as u8,
0x3f,
);
/// A trait for parsing [non-totalistic hexagonal rules](http://www.conwaylife.com/wiki/Hexagonal_neighbourhood).
/// Both [isotropic](http://www.conwaylife.com/wiki/Isotropic_non-totalistic_Life-like_cellular_automaton... | Rust | 0 |
;
use std::sync::Mutex;
#[test]
fn pythagoras_was_right() {
assert!(
(5.0 - (Position { x: 3.0, y: 0.0 }).distance(&Position { x: 0.0, y: 4.0 })).abs() < 0.01
);
}
struct TestEnvironment {
game_server: GameServer,
server_to_client_queue: Arc<Mutex<HashMap<UUID, Vec<ServerToClientMessage>>>>,
players: Ha... | Rust | 0 |
Self(f64::INFINITY)
}
fn is_unsigned() -> bool {
false
}
}
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
pub struct UFloatWeight(f64);
impl UFloatWeight {
pub fn new(value: f64) -> Option<Self> {
// Includes inf, but not NaN or -inf.
if value >= 0.0 {
... | Rust | 0 |
de::create(nums.clone());
/// let ans = TreeNode::literal(root);
/// assert_eq!(nums, ans);
/// ```
pub fn literal(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<Option<i32>> {
if root.is_none() {
return vec![];
}
let mut ans = vec![];
let mut queue = VecDeque::n... | Rust | 0 |
ut.input_from(0..1000 as i32)?.copied()?;
src1.key_by(|x| Ok((1 as i32, x)))?
.partition_by_key()
.inner_join(src2.key_by(|x| Ok((1 as i32, x)))?.partition_by_key())?
.map(|(d1, d2)| Ok(((d1.key, d1.value), (d2.key, d2.value))))?
.collect::<Vec... | Rust | 0 |
wl, g61nzt0awz2: v75q8rurr7j):
qawumg1yoil.mixq_pii1ti: False = pkr8x2gi3eb
from n5k3599vhgu import eapdwi4if8i, yddoe9i2zhs, u0ikl6xovs9 as i073d1__una, opm5lxpfhzv as maf7k_7txuk, zi8uj22ymuk, ahe405pwa9k, s6hwb1_hi5x as ixrynwam39e, dqqrmoe0w95 as flvio9qlags, qbclfu4jmq0, rtfix48qf95
'# speech_blackboar... | Python | 1 |
lif "focalloss" in classifier_model:
criterion = get_loss_func("focal_loss")(reduction="none").to(device)
elif "weightedbce" in classifier_model:
location_num = analysisData[['image_' + i for i in cfg.CLASSIFIER.LOCATIONS]].values.flatten()
loc... | Python | 1 |
ARGE", "134"),
("(gint) G_REGEX_ERROR_INCONSISTENT_NEWLINE_OPTIONS", "156"),
(
"(gint) G_REGEX_ERROR_INEXISTENT_SUBPATTERN_REFERENCE",
"115",
),
("(gint) G_REGEX_ERROR_INFINITE_LOOP", "140"),
("(gint) G_REGEX_ERROR_INTERNAL", "4"),
("(gint) G_REGEX_ERROR_INVALID_CONDITION", "135"... | Rust | 0 |
P.plot(100*t/t.max(), 'ro')
P.xticks([0,1,2], ('strings', 'numpy auto', 'inline'))
P.gca().set_xlim((-0.25, 2.25))
P.gca().set_ylim((0, 110))
P.gca().set_ylabel(r"% of slowest time")
P.legend(loc=8)
P.title('Casting raw file data to an MR volume')
P.show()
def time_casting(int_dat... | Python | 1 |
ted sampled proposals, that were obtained on all feature maps
# concatenated via the fg_bg_sampler, into individual feature map levels
for img_idx, (pos_inds_img, neg_inds_img) in enumerate(
zip(sampled_pos_inds, sampled_neg_inds)
):
img_sampled_inds = torch.nonzero(pos_i... | Python | 1 |
.borrow_configuration {
let mut object_300 = object.key("BorrowConfiguration").start_object();
crate::json_ser::serialize_structure_borrow_configuration(&mut object_300, var_299);
object_300.finish();
}
}
pub fn serialize_structure_tag(
object: &mut smithy_json::serialize::JsonObjectWri... | Rust | 0 |
(z1, z).combine_sign(x)
}
}
#[inline(always)]
fn fraction2<S: Simd>(x: Vf32<S>) -> Vf32<S> {
// set exponent to 0 + bias
(x & Vf32::<S>::splat(f32::from_bits(0x007FFFFF))) | Vf32::<S>::splat(f32::from_bits(0x3F000000))
}
#[inline(always)]
fn exponent<S: Simd>(x: Vf32<S>) -> Vi32<S> {
// shift out sign... | Rust | 0 |
AL_FILTER: _spinColorProcessingAlgorithm = 8;
#[doc = " Slowest but produces good results."]
pub const _spinColorProcessingAlgorithm_RIGOROUS: _spinColorProcessingAlgorithm = 9;
#[doc = " Weighted pixel average from different directions."]
pub const _spinColorProcessingAlgorithm_WEIGHTED_DIRECTIONAL_FILTER: _spinColorP... | Rust | 0 |
import inspect
import re
import typing
from enum import IntFlag
from interactions.models.discord.snowflake import Snowflake
from typing import Any, Dict, Union, Optional
import aiohttp # type: ignore
from interactions.client.const import get_logger
import importlib.util
__all__ = ("FastJson", "response_decode", "ge... | Python | 1 |
= Ase;
state[22] = Asi;
state[23] = Aso;
state[24] = Asu;
}
fn keccak_absorb(s: &mut [u64], r: usize, m: &[u8], mut mlen: u64, p: u8) {
let t = &mut [0; 200];
let mut m_clone: &[u8] = m.clone();
while mlen >= r as u64 {
for i in 0..(r / 8) {
s[i as usize] ^= load64(&m_clone... | Rust | 0 |
# -*- coding: utf-8 -*-
"""統一資料庫連接工具模組
此模組提供統一的資料庫連接和初始化功能,避免在各個服務中重複實現。
整合了最佳實踐的資料庫連接管理、會話工廠創建和錯誤處理。
主要功能:
- 統一的資料庫引擎創建
- 會話工廠管理
- 資料庫初始化
- 連接池配置
- 錯誤處理和重試機制
Example:
基本使用:
```python
from src.utils.database_utils import get_database_session
# 使用便捷函數獲取會話
with get_database_session() as session:
... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.