text string | label_name string | labels int64 |
|---|---|---|
processed_items = self.process_acc_response(response, grade, part)
if not processed_items:
continue
# 첫 페이지 저장
dup_item_num = self.save_acc_items(processed_items, self.current_cycle_id)
... | Python | 1 |
etermine primary LOF mechanism"""
if stability > 0.5:
return 'protein_instability'
elif conservation > 0.7:
return 'critical_residue_loss'
elif structural > 0.5:
return 'structural_disruption'
else:
return 'mild_functional_impact'
... | Python | 1 |
LP);
let mut client = Client::builder(&token)
.framework(framework)
.event_handler(Handler)
.await?;
{
let mut data = client.data.write().await;
data.insert::<CommandCounter>(Arc::new(RwLock::new(HashMap::default())));
data.insert::<ShardManagerContainer>(client... | Rust | 0 |
process.call(['ip', 'route', 'add', '224.0.0.0/4', 'dev', br_ifname])
params = {"ssid": "test-1",
"bridge": br_ifname,
"iapp_interface": br_ifname}
hapd = hostapd.add_ap(apdev[0], params)
dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
dev[0].connect("test-1", key_mgmt="N... | Python | 1 |
=> DATA_AR::DATA_BYTES_0_3_UNCHA,
}
}
#[doc = "Checks if the value of the field is `TRANSFER_DATA_BYTES_`"]
#[inline]
pub fn is_transfer_data_bytes_(&self) -> bool {
*self == DATA_AR::TRANSFER_DATA_BYTES_
}
#[doc = "Checks if the value of the field is `DATA_BYTES_0_3_UNCHA`"]
... | Rust | 0 |
# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | Python | 1 |
tries_limit=1000):
"""Find a new sample for the starting window"""
found = False
N_tries = 0
while found is False:
# Generate a random sample
new_samp = rng.randint(N_samp)
# Check how close the sample is to other window starts
dists = np.abs(window_starts - new_sa... | Python | 1 |
\ingroup libusb_dev
/// Masks for the bits of the
/// \ref libusb_ss_usb_device_capability_descriptor::bmAttributes "bmAttributes" field
/// field of the SuperSpeed USB Device Capability descriptor.
pub type libusb_ss_usb_device_capability_attributes = u32;
/// Wireless USB device capability
pub const LIBUSB_BT_WIRELE... | Rust | 0 |
# Ultralytics YOLO 🚀, AGPL-3.0 license
"""Module utils."""
import copy
import math
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.init import uniform_
__all__ = "multi_scale_deformable_attn_pytorch", "inverse_sigmoid"
def _get_clones(module, n):
"""Create a... | Python | 1 |
nce.enable_caching,
"cache_ttl_hours": preference.cache_ttl_hours,
"enable_learning": preference.enable_learning,
"configured_providers": list((preference.personal_api_keys or {}).keys()),
"provider_priorities": preference.provider_priorities or {},
"model_preferences": preferenc... | Python | 1 |
hing about accounts that posted a wrong key
return Ok(().into())
}
Err(Error::<T>::InvalidPublicKeys.into())
}
#[transactional]
#[pallet::weight(0)]
pub fn submit_public_key_signature(
origin: OriginFor<T>,
signature_proposal: RefreshProposalSigned,
) -> DispatchResultWithPostInfo {
let o... | Rust | 0 |
e_b)
else:
B = (rng.random(b_shape) + 1j*rng.random(b_shape)).astype(dtype_b)
# single application
sol_mat = expm_multiply(A, B)
sol_op = estimated(expm_multiply)(aslinearoperator(A), B)
direct_sol = np.dot(sp_expm(A), B)
assert_allclose_(sol_mat, direct_sol)
assert_allclose_(sol_op... | Python | 1 |
OT_ON_CURVE,
]
# Individual Cells
CELL_RANDOM_VALID1 = b"".join(
[
field_element_bytes(pow(2, n + 256, spec.BLS_MODULUS))
for n in range(spec.FIELD_ELEMENTS_PER_CELL)
]
)
CELL_RANDOM_VALID2 = b"".join(
[
field_element_bytes(pow(3, n + 256, spec.BLS_MODULUS))
for n in range(... | Python | 1 |
_matte, 0, index);
rsSetElementAt_uchar(g_sharp_dilated_depth, 0, index);
// Does not reset sharp->actual depth, which will be used in future
// layer processing.
if (matte == 0) {
return;
}
float factor = (float)matte * g_blend_info.matte_normalizer;
// The following blending amounts to:
// sharp... | Rust | 0 |
#[cfg(not(target_os="linux"))]
fn main() {}
#[cfg(target_os="linux")]
extern {
fn syscall(number: c_int, ...) -> c_int;
}
//! Module containing the MIDI-related code
use crate::Message;
use midir::{MidiOutput, MidiOutputConnection};
/// Sysex message start byte
pub const SYSEX_START_BYTE: u8 = 0xF0;
/// Sysex... | Rust | 0 |
iteration',fontsize=15)
plt.ylabel(r'Element$_{k}$ - Element$_{k-1}$',fontsize=15)
plt.legend(fontsize=15)
plt.savefig(homedir+'/Desktop/KimConger_Assignment7/eval_policy.png')
plt.close()
if __name__ == '__main__':
homedir = os.getenv("HOME")
print('PART ONE')
print()
k_range, ... | Python | 1 |
from nano_graphrag._utils import encode_string_by_tiktoken
from nano_graphrag.base import QueryParam
from nano_graphrag.graphrag import GraphRAG
from nano_graphrag._op import chunking_by_seperators
def chunking_by_token_size(
tokens_list: list[list[int]], # nano-graphrag may pass a batch of docs' tokens
doc_... | Python | 1 |
from docx import Document
# Create a new Document
doc = Document()
# Add the title
doc.add_heading('Architectural Differences Between RTX and GTX GPUs', 0)
# Add the Keywords section
doc.add_heading('Keywords:', level=1)
keywords = [
"RTX GPUs",
"GTX GPUs",
"Real-Time Ray Tracing",
"Low-Light Ray Cal... | Python | 1 |
cimal_': 'asc',
},
)
assert found is not None
assert found.decimal_ == Decimal('2.1234')
def test_filtering_nulls(client: Prisma) -> None:
"""None is a valid filter for nullable Decimal fields"""
client.types.create(
{
'string': 'a',
'optional_decimal': None... | Python | 1 |
# !wget "https://archive.ics.uci.edu/ml/machine-learning-databases/00240/UCI HAR Dataset.zip"
# !wget "https://archive.ics.uci.edu/ml/machine-learning-databases/00240/UCI HAR Dataset.names"
# !wget https://archive.ics.uci.edu/ml/machine-learning-databases/00226/OpportunityUCIDataset.zip
# import copy
import os
from su... | Python | 1 |
# Copyright (C) 2016-2017 DLR
#
# All rights reserved. This program and the accompanying materials are made
# available under the terms of the Eclipse Public License v1.0 which
# accompanies this distribution, and is available at
# http://www.eclipse.org/legal/epl-v10.html
#
# Contributors:
# Franz Steinmetz <franz.ste... | Python | 1 |
date, c.symbol);
continue;
}
agg1d.put_timestamp(c.ts);
agg1d.put_symbol(c.symbol);
agg1d.put_f64(c.open);
agg1d.put_f64(c.high);
agg1d.put_f64(c.low);
agg1d.put_f64(c.close);
agg1d.put_u64(c.volume);
agg1d.write();
}
eprintln!("{}: Flushing {} candles", year, num_candles)... | Rust | 0 |
,
],
k: &[0x12],
x: &[
0x03, 0xda, 0x14, 0x31, 0xde, 0x0a, 0xcb, 0xd3, 0xf4, 0x27, 0x61, 0x09, 0xe9, 0xa4,
0xed, 0x3a, 0x74, 0x82, 0x45, 0xa1, 0x4e, 0xfa, 0x7f, 0x1d, 0xa8, 0x4f, 0xe9, 0x17,
0x07, 0x39, 0x59, 0xd8, 0xac, 0x6f, 0xdf, 0xb5, 0xde, 0x3f, 0x90, 0xe... | Rust | 0 |
move {
let game_id = src_manifest.game_id();
match jigs.lock().await.game_to_jig.get(&game_id) {
Some(jig_list) => {
for jig in jig_list {
let jig_id = jig.id.0.to_string();
update_jig(&... | Rust | 0 |
test]
fn integration_basic() {
let ttl = Duration::ZERO;
let heap_size = 2 * 256;
let segment_size = 256;
let mut cache = Seg::builder()
.segment_size(segment_size)
.heap_size(heap_size)
.hash_power(16)
.build();
println!("filling seg 0");
let _ = cache.insert(
... | Rust | 0 |
"""source_code table filename
Revision ID: 37b73c74eebe
Revises: 3dd5bafe949d
Create Date: 2025-04-21 07:57:16.696999
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = "37b73c74eebe"
down_revision: Union[str, None] = "3dd... | Python | 1 |
"YearlyProfitLossTimeSeries": [
{
"Date": "2015-12-31",
"Value": 0
},
{
"Date": "2016-12-31",
"Value": 0
},
{
"Date": "2017-12-31",
... | Python | 1 |
pub use downsample::Downsample;
pub use invariants::*;
/// Level of precision to be expected in implementations comparisons.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Validation {
/// Output is random
Random,
/// Implementation may induce rounding errors
Rounding,
/// Implementa... | Rust | 0 |
().clone();
shared
.atoms_mut()
.for_each(|a| a.set_occupancy(a.occupancy() / (count as f64)).unwrap());
residue.remove_conformer(index);
for conformer in residue.conformers_mut() {
conformer.join(shared.clone())... | Rust | 0 |
import os
from manipulator_mujoco.robots.gripper import Gripper
_AG95_XML = os.path.join(
os.path.dirname(__file__),
'../assets/robots/ag95/ag95.xml',
)
_JOINT = 'left_outer_knuckle_joint'
_ACTUATOR = 'fingers_actuator'
class AG95(Gripper):
def __init__(self, name: str = None):
super().__init__(... | Python | 1 |
import os
MyPC = os.path.basename(__file__) != "Main.py"
if MyPC:
from icecream import ic
ic.disable()
else:
def ic(*args):
return None
ic.enable() if MyPC else None
def main():
n, w = map(int, input().split())
col_list = [[] for _ in range(w)] # x座標ごとの、その列に存在するブロックのy座標のリスト
block_dict = {} # ブロックの座... | Python | 1 |
= &dict;
if TFIDF_INSTANCE.get().is_some() {
return Err(Error::new(
Status::GenericFailure,
"TFIDF has loaded, can not load dict again".to_owned(),
));
}
TFIDF_INSTANCE.get_or_try_init(|| {
let jieba = JIEBA.get_or_init(Jieba::new);
let mut tfidf = TFIDF::new_with_jieba(jieba);
tf... | Rust | 0 |
from .model import *
from .decoder import *
from .loss import *
| Python | 1 |
ce_running:
print("\n📋 To start Ollama service:")
print(" Run: ollama serve")
print(" Or check if it's running as a system service")
return False
# Check models
models = get_installed_models()
if not models:
print("\n❓ Would you like to install recommended m... | Python | 1 |
# Copyright 2009-2011 Ram Rachum.
# This program is distributed under the LGPL2.1 license.
'''Testing module for `nifty_collections.ordered_dict.OrderedDict`.'''
from __future__ import with_statement
from garlicsim.general_misc import cute_testing
from garlicsim.general_misc.nifty_collections.ordered_dict import Or... | Python | 1 |
import psutil
def get_cpu_usage():
cpu_percentages = psutil.cpu_percent(percpu=True)
return cpu_percentages
def get_memory_usage():
memory = psutil.virtual_memory()
return {
'total': memory.total,
'available': memory.available,
'used': memory.used,
'percent': memory.per... | Python | 1 |
kuberenetes and vector logs.
// This is correct, but on best effort basis filtering out of logs from kuberentes system components.
// More specificly, it will work for all Kubernetes 1.14 and higher, and for some bellow that.
exclude.push((LOG_DIRECTORY.to_owned() + r"kube-system_*... | Rust | 0 |
match error {
RDKafkaErrorCode::TopicAlreadyExists => {
log::info!("Kafka topic '{}' already exists", topic);
}
_ => {
anyhow::bail!("Kafka topic '{}' not created: {:?}", topic, error);
}
},
}
... | Rust | 0 |
"""
Problem: Rotate Matrix 90 Degrees
Description:
-------------
Given an `n x n` 2D matrix, rotate the matrix in-place by 90 degrees:
- `clockwise` rotation: top becomes right, right becomes bottom, etc.
- `anti-clockwise` rotation: top becomes left, left becomes bottom, etc.
Approach:
---------
Both approaches foll... | Python | 1 |
Troption::None
} else {
let mut storage = SkeensMultiStorage::new(num_locs, size, None);
storage.fill_from(&mut msg);
Troption::Left(storage)
}
}
EntryLayout::Data => Troption::None,
EntryLayo... | Rust | 0 |
import keras
import tensorflow as tf
import numpy as np
from keras import callbacks
from sklearn.model_selection import KFold
import create_model
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
gpus = tf.config.experimental.list_physical_devices('GPU')
if gpus:
try:
for gpu in gpus:
tf.config... | Python | 1 |
}
/// Send data.
pub fn send(&self, data: T) -> Result<(), SendError<T>> {
self.sender.send(data)
}
/// Receive some data and block if no data is available yet.
pub fn recv(&self) -> Result<T, RecvError> {
self.receiver.recv()
}
/// Try to receive some data and return without blocking if
/// no data is a... | Rust | 0 |
)
# Send the request using the OctoAI client
try:
output = octoai_client.infer(self.endpoint_url, parameter_payload)
if output and "choices" in output and len(output["choices"]) > 0:
text = output["choices"][0].get("mes... | Python | 1 |
ED_DRIVES_KB)
pub type xcb_xkb_im_flag_t = u32;
/// The `xkb::IMFlag::NoExplicit` enum variant.
///
/// This is a variant of [`xcb_xkb_im_flag_t`].
pub const XCB_XKB_IM_FLAG_NO_EXPLICIT: xcb_xkb_im_flag_t = 128;
/// The `xkb::IMFlag::NoAutomatic` enum variant.
///
/// This is a variant of [`xcb_xkb_im_flag_t`].
pub con... | Rust | 0 |
resolution=(1080, 1920))): # 判断是否在城镇,防止队列影响按钮
print_space('不在城镇,点击去往城镇')
touch([950, 1850]) # 点击野外
time.sleep(5)
touch([2, 812]) # 点击右侧按钮
time.sleep(1)
touch([170, 400])
print_space('检查盾兵训练是否完成')
# region_1=(560,900,650,1000)
if exists(Template(r"icon/tpl1719478488282.... | Python | 1 |
import requests
import torch
from PIL import Image
from transformers import CLIPProcessor
from aesthetics_predictor import AestheticsPredictorV1, AestheticsPredictorV2Linear, AestheticsPredictorV2ReLU
from io import BytesIO
def open_image(image):
if isinstance(image, bytes):
image = Image.open(BytesIO(imag... | Python | 1 |
};
Box::new(func)
}
/// Builds a binary `Deploy Template` transaction.
pub fn build_deploy(
code_version: u32,
name: &str,
layout: FixedLayout,
ctors: &[String],
wasm: WasmFile,
) -> Vec<u8> {
let code = CodeSection::new_fixed(wasm.into_bytes(), 0);
let ctors = CtorsSection::ne... | Rust | 0 |
Failed loading previuos log file: {err}")
prev_logs.append(info)
with open(log_path, "w", encoding="utf8") as f_out:
for log_line in prev_logs:
f_out.write(json.dumps(log_line, cls=NpEncoder) + "\n")
current... | Python | 1 |
04v\
q\x86\xb5\xb8\x8f\x1e\xabR\xe9\xc9\xe7i\xc61\xcf\xca\
T\xd3\x22?f\xd4nU\x98*\x93\xbb\x9fJ\xc9:\
\xe2X=\xccQ\x03!\xdcH\xdb\xef@\xb9\x8d]>\
`,\x86\xf2\x17a*s\xedTo\xf5\xf8b%-\
\xc1\x96On\xd5\xcd\xa5\xc4\xf7\x9b\xb7\x19\x14\x16? \
\x15~\xdbN`U\x80\xf2\x94\xfe$\xd3\x13w)\xdc\
\xdd]]\x1c\xcb#*\x9f\xe1\x15n\xd3HW]\xf3\
... | Python | 1 |
=200,
warmup_ratio=0.001,
step=[20,])
runner = dict(type='EpochBasedRunner', max_epochs=20)
custom_hooks = [
dict(
type='MEGVIIEMAHook',
init_updates=10560,
priority='NORMAL',
resume='work_dirs/geobev-correct-mydistill-r50-cbgs/epoch_5_ema.pth',
),
# dict(
# ... | Python | 1 |
.unwrap()
))))
});
index_start += index_count;
}
for (i, data) in mat_temp_datas.into_iter().enumerate() {
let texture1_default = render_pass.shaders.texture1_default.clone();
let future1: Box<Future<Output = _> + Send + Unpin> =
if data.texture1_name_size != 0 {
file.seek(SeekFrom::Start(data... | Rust | 0 |
import pathlib
from setuptools import setup
# The directory containing this file
HERE = pathlib.Path(__file__).parent
# The text of the README file
README = (HERE / "README.md").read_text()
# This call to setup() does all the work
setup(
name="sent2vec",
version="0.3.0",
description="How to encode senten... | Python | 1 |
Initializes the loader.
Args:
ckpt_path: The filepath to the safetensors file.
is_symmetric: Whether to apply symmetric or asymmetric quantization.
attention_quant_bits: An integer that specify the target quantization bits
(support 8 or 4) for the attention layers.
feedforward_quant... | Python | 1 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class MedicalShopMarketingActivityRule(object):
def __init__(self):
self._reduce_price = None
self._reduce_price_threshold = None
@property
def reduce_price(self):
retu... | Python | 1 |
index: String) -> String {
opt_get_kv(options, index, &proto_options::ENUM_KEY_VALUE)
}
////////////////////////////////////////////////////
// EnumValueOptions
#[rhai_fn(get = "deprecated", pure)]
pub fn enum_value_opt_deprecated(opt: &mut EnumValueOptions) -> bool {
opt.deprecate... | Rust | 0 |
# ensure proper identification of scalar
# data-types by issctype()
actual = np.issctype(rep)
assert_equal(actual, expected)
@pytest.mark.skipif(sys.flags.optimize > 1,
reason="no docstrings present to inspect when PYTHONOPTIMIZE/Py_OptimizeFlag > 1")
@pytest.mark.xfail(IS_PYPY, reas... | Python | 1 |
_or_else(|| home_dir.join(".local/share"));
let font_dir = data_dir.join("fonts");
let user_dirs = UserDirs {
home_dir: home_dir,
audio_dir: run_xdg_user_dir_command("MUSIC"),
desktop_dir: run_xdg_user_dir_command("DESKTOP"),
document_dir: run_xd... | Rust | 0 |
m1.m21)) + (m0.m33 * m1.m31)) + (m0.m34 * m1.m41);
m2.m32 = (((m0.m31 * m1.m12) + (m0.m32 * m1.m22)) + (m0.m33 * m1.m32)) + (m0.m34 * m1.m42);
m2.m33 = (((m0.m31 * m1.m13) + (m0.m32 * m1.m23)) + (m0.m33 * m1.m33)) + (m0.m34 * m1.m43);
m2.m34 = (((m0.m31 * m1.m14) + (m0.m32 * m1.m24)) + (m0.m33 ... | Rust | 0 |
from .audio import AudioDevice
| Python | 1 |
vBC;
(*s).count = 2;
} else if uCA > 0.0 && vCA > 0.0 && vABC <= 0.0 {
(*s).b = (*s).a;
(*s).a = (*s).c;
(*s).a.u = uCA;
(*s).b.u = vCA;
(*s).div = uCA + vCA;
(*s).count = 2;
} else {
(*s).a.u = uABC;
(*s).b.u = vABC;
(*s).c.u = wA... | Rust | 0 |
combine_signatures(
AlgorithmId::from(&public_coefficients),
&shares_to_vector(&transcript_data, shares, dkg_id)?,
public_coefficients,
)
.map_err(map_csp_combine_sigs_error_or_panic)?;
combined_threshold_sig_or_panic(csp_signature)
}
}... | Rust | 0 |
= app
.instantiate_contract(
cw20_code_id,
Addr::unchecked(OWNER),
&msg,
&[],
"cw20",
None,
)
.unwrap();
// Instantiate a DAO with an existing CW20 (other_cw20_addr) and an existing staking contract
// (staking_addr... | Rust | 0 |
= vcode.stackslot_offsets().clone();
let disasm = if want_disasm {
Some(vcode.show_rru(Some(&create_reg_universe(flags))))
} else {
None
};
let buffer = buffer.finish();
Ok(MachCompileResult {
buffer,
frame_size,
dis... | Rust | 0 |
__all__ = ('ActivityFlag', )
from ...bases import FlagBase, FlagDescriptor as F
class ActivityFlag(FlagBase):
"""
The flags of an activity provided by Discord. These flags supposed to describe what the activity's payload
includes.
The activity flags are the following:
+-----------------... | Python | 1 |
# -*- coding: utf-8 -*-
"""
Created on Sat May 18 21:25:33 2019
@author: Guru
"""
from pylab import *
from scipy.optimize import curve_fit
from scipy import stats
def func(x, a, b, c):
'''Exponential 3-param function.'''
return a * np.exp(b * x) + c
# Read data.
x, y = np.loadtxt('exponential_data.dat', u... | Python | 1 |
})
}
#[cfg(not(feature = "task_monitor"))]
/// Create a new task with the configuration set as arguments passed.
pub fn create_task(
task_manager: &'static Mutex<RefCell<Scheduler>>,
priority: TaskId,
stack: &mut [u32],
handler_fn: fn() -> !,
) -> Result<(), KernelError> {
priv_execute!({
... | Rust | 0 |
R_LEVEL_SEMIALPHABETIC: u8 = 5;
// The number of types we actually use
const NUM_TYPES: u8 = FOUR_LEVEL_SEMIALPHABETIC - ONE_LEVEL + 1;
// The total number of types we configure. Over the lifetime of the X server, the number
// of types must never decrease. Therefore we have to use a large value here and configure
// ... | Rust | 0 |
, inplace=True)
return df
@beartype
def main(
input_jsons: list,
msasl_dir: Path,
msasl_meta_data_url: str,
output_dir: Path,
trim_format: str,
num_jobs: int,
tmp_dir: Path,
):
info_tar = msasl_dir / "msasl.tar"
output_dir = msasl_dir / "videos_original"
if not info_tar.exi... | Python | 1 |
Err(_) => {
return;
}
}
};
}
#[macro_export]
macro_rules! some_or_continue {
($body:expr) => {
match $body {
Some(r) => r,
None => {
continue;
}
}
};
}
#[macro_export]
macro_rules! ok_or_con... | Rust | 0 |
char); 27] = [
(Numrow1Key, 'ä', 'Ä'), // 1
(QKey, 'à', 'À'),
(AKey, 'á', 'Á'),
(ZKey, 'â', 'Â'),
(WKey, 'ñ', 'Ñ'), // 2
(SKey, 'ß', 'ß'),
(XKey, 'ç', 'Ç'),
(Numrow3Key, 'ë', 'Ë'), // 3
(DKey, 'è', 'È'),
(EKey, 'é', 'É'),
(CKey, 'ê', 'Ê'),
(TKey, '€', '€'), // 4
(HKe... | Rust | 0 |
let cpp_files = [
"src/cpp/main.cpp",
"src/cpp/module.cpp",
"src/cpp/object.cpp",
"src/cpp/vessel.cpp",
];
// Tell Cargo when to rerun
println!("cargo:rerun-if-changed=build.rs");
println!("cargo:rerun-if-env-changed={}", ORBITER_DIR_ENV);
println!("cargo:rerun-i... | Rust | 0 |
f: &mut fmt::Formatter<'_>) -> fmt::Result {
let implied_size = (
self.blocks.len() / self.size.total_size(),
self.size.0,
self.size.1,
);
let mut values = vec![];
for x in 0..implied_size.0 {
let mut row = vec![];
for y in 0..... | Rust | 0 |
# sunday 算法,T 为文本串,p 为模式串
def sunday(T: str, p: str) -> int:
n, m = len(T), len(p)
bc_table = generateBadCharTable(p) # 生成后移位数表
i = 0
while i <= n - m:
j = 0
if T[i: i + m] == p:
return i # 匹配完成,返回模式串 p 在文本串 T 的位置
if i + m... | Python | 1 |
apped
# namespace of a CuPy array.
xp = array_api_compat.get_namespace(array_mod.asarray(1))
if (
array_namespace == "torch"
and device == "cuda"
and not xp.backends.cuda.is_built()
):
raise SkipTest("PyTorch test requires cuda, which is not available")
elif array_nam... | Python | 1 |
n_ty_2::_SC_MEMLOCK;
pub const _SC_MEMLOCK_RANGE: _bindgen_ty_2 = _bindgen_ty_2::_SC_MEMLOCK_RANGE;
pub const _SC_MEMORY_PROTECTION: _bindgen_ty_2 = _bindgen_ty_2::_SC_MEMORY_PROTECTION;
pub const _SC_MESSAGE_PASSING: _bindgen_ty_2 = _bindgen_ty_2::_SC_MESSAGE_PASSING;
pub const _SC_SEMAPHORES: _bindgen_ty_2 = _bindgen... | Rust | 0 |
@SHUT_RD: shutdown receptions
/// @SHUT_WR: shutdown transmissions
/// @SHUT_RDWR: shutdown receptions/transmissions
pub const SHUT_RD: i32 = 0;
pub const SHUT_WR: i32 = 1;
pub const SHUT_RDWR: i32 = 2;
//struct socket_wq {
// // Note: wait MUST be first field of socket_wq
// wait_queue_head_t wait;
//
// struct fasy... | Rust | 0 |
pl<B> ImageView<B>
where
B: gfx_hal::Backend,
{
/// Wrap an image view.
///
/// `raw` image view must be created from the `image`.
/// `info` must match information about raw image view.
/// `terminal` will receive image and memory block upon drop, it must free image and memory properly.
///... | Rust | 0 |
most spatial algorithms to work correctly,
/// **this metric must satisfy the Triangle Inequality.**
///
/// Panics if the points have different dimensions.
fn distance<D: Dimension>(&self, a: ArrayView<F, D>, b: ArrayView<F, D>) -> F;
/// A faster version of the distance metric that keeps the ord... | Rust | 0 |
libc::read(
self.fd,
buf.as_mut_ptr() as *mut c_void,
::std::cmp::min(buf.len(), max_len()),
)
})?;
Ok(ret as usize)
}
}
use bevy::{core::Time, prelude::*};
use bevy_ecs_tilemap::prelude::*;
use rand::{thread_rng, Rng};
mod helpers;
... | Rust | 0 |
pub const BCRYPT_DSA_PARAMETERS_MAGIC: ULONG = 0x4d505344;
pub const BCRYPT_DSA_PARAMETERS_MAGIC_V2: ULONG = 0x324d5044;
STRUCT!{struct BCRYPT_DSA_PARAMETER_HEADER {
cbLength: ULONG,
dwMagic: ULONG,
cbKeyLength: ULONG,
Count: [UCHAR; 4],
Seed: [UCHAR; 20],
q: [UCHAR; 20],
}}
STRUCT!{struct BCRYP... | Rust | 0 |
]
unsafe fn _enqueue_map_buffer<T, M>(
command_queue: &CommandQueue,
buffer: M,
block: bool,
map_flags: MapFlags,
offset: usize,
len: usize,
wait_list_len: cl_uint,
wait_list_ptr: *const cl_event,
new_event_ptr: *mut cl_event,
) -> OclCoreR... | Rust | 0 |
.subcommand(
App::new("install")
.about("Install theme from json file")
.arg(
Arg::new("theme")
.about("Packaged theme file")
.takes_value(true)
.multiple_values(false)... | Rust | 0 |
0 => panic!("zero is not a valid argument to fib()!"),
//! 1 | 2 => 1,
//! 3 => 2,
//! _ => fib(n-1).await + fib(n-2).await
//! }
//! }
//! ```
//!
//! The compiler helpfully tells us that:
//!
//! ```console
//! error[E0733]: recursion in an `async fn` requires boxing
//! --> src/m... | Rust | 0 |
'''
Subject: Cricket Book Game through Data Handling
Created By: Anup Kumar.
Date: 14-April-2025.
'''
import random
class cricket:
def __init__(self):
pass
def file_read(self):
file.seek(0) # Pointer will set on Zero
file_content = file.read() # Read the file content
print(f... | Python | 1 |
ock = TokenLock::new(token.id(), 1);
//! let guard = lock.write(&mut token);
//! drop(lock); // compile error: `guard` cannot outlive `TokenLock`
//! drop(guard);
//! ```
//!
//! ```compile_fail
//! # use tokenlock::*;
//! # use std::mem::drop;
//! # let mut token = ArcToken::new();
//! # let lock = TokenLock::new(toke... | Rust | 0 |
#!/usr/bin/env python3
# Knowage, Open Source Business Intelligence suite
# Copyright (C) 2016 Engineering Ingegneria Informatica S.p.A.
#
# Knowage is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, eith... | Python | 1 |
"""A building block for other tests."""
__author__ = "Tom Goetz"
__copyright__ = "Copyright Tom Goetz"
__license__ = "GPL"
import logging
import cProfile
import pstats
logger = logging.getLogger(__name__)
class TestDBBase():
@classmethod
def setUpClass(cls, db, table_dict, table_not_none_cols_dict={}):
... | Python | 1 |
iece::Ant, Color::Black))),
((-1, 0, 1), BoardSquare::new(Piece::new(BoardPiece::Ant, Color::Black))),
(grasshopper_square, BoardSquare::new(grasshopper.clone())),
];
board.from_iter(pos.into_iter());
board.turns = board.len();
let mut legal_moves = grasshopper... | Rust | 0 |
_supported_infrastructure_auth_cipher_pairs = 9,
wlan_intf_opcode_supported_adhoc_auth_cipher_pairs = 10,
wlan_intf_opcode_supported_country_or_region_string_list = 11,
wlan_intf_opcode_current_operation_mode = 12,
wlan_intf_opcode_supported_safe_mode = 13,
wlan_intf_opcode_certified_safe_mode = 14,... | Rust | 0 |
an. Mozjpeg-sys includes the right
// sources but doesn't export the definitions.
extern "C" {
fn jcopy_markers_setup(srcinfo: j_decompress_ptr, option: JCOPY_OPTION);
}
extern "C" {
fn jcopy_markers_execute(
srcinfo: j_decompress_ptr,
dstinfo: j_compress_ptr,
option: JCOPY_OPTION,
);
}
#[allow(unused_assi... | Rust | 0 |
where
V: Clone,
{
self.raw.resize(new_len, value)
}
/// Clones and appends all elements in a slice to the `TiVec`.
///
/// See [`Vec::extend_from_slice`] for more details.
///
/// [`Vec::extend_from_slice`]: https://doc.rust-lang.org/std/vec/struct.Vec.html#method.extend_fro... | Rust | 0 |
}
}
#[doc = "Control ATLAS/Ripple AGC force mode based on radioCNTL2-FORCEAGC_LENGTH value\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum FORCEAGC_EN_A {
#[doc = "0: Disable"]
FORCEAGC_EN_0 = 0,
#[doc = "1: Enable"]
FORCEAGC_EN_1 = 1,
}
impl From<FORCEAGC_EN_A> for bool {
#... | Rust | 0 |
from facebook_scraper.utils import parse_datetime
class TestParseDate:
dates = [
'Oct 1 at 1:00 PM',
'Oct 1 at 11:00 PM',
'Oct 16 at 1:00 PM',
'Oct 16 at 11:00 PM',
'October 1 at 1:00 PM',
'October 1 at 11:00 PM',
'October 16 at 1:00 PM',
'October 16... | Python | 1 |
= br::FormatQueryPred::default();
fmq.bit(32).components(br::FormatComponents::RGBA).elements(br::ElementType::UNORM);
let fmt = pd.surface_formats(&obj)?.into_iter().find(|sf| fmq.satisfy(sf.format))
.expect("No suitable format found");
let pres_modes = pd.surface_present_modes... | Rust | 0 |
SqlGraphEntity::ExtensionRoot(item) => item.to_sql(context),
}
}
}
<reponame>whtcorpsinc/einsteindb-prod
// Copyright 2020 EinsteinDB Project Authors & WHTCORPS INC. Licensed under Apache-2.0.
mod gc_worker;
mod pessimistic_txn;
mod violetabftstore;
mod split_check;
use alkahest::{Schema, Seq};
use crit... | Rust | 0 |
import argparse
import os
import numpy as np
import json
from tqdm import tqdm
import gc
os.makedirs("results", exist_ok=True)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('--dataroot', type=str, required=True, help='path to dataset')
parser.add_argument('--model', typ... | Python | 1 |
s = HashSet::new();
for _ in 0..100 {
for pos in black_tiles.iter().copied() {
let mut black_neighbor_count = 0;
for dir in ALL_DIRECTIONS.iter() {
let neighbor_pos = dir.step(pos);
if black_tiles.contains(&neighbor_pos) {
black_... | Rust | 0 |
# First part solution
def adder(good = 1, bad = 2, ugly = 3):
return good + bad + ugly
print(adder())
print(adder(5))
print(adder(5, 6))
print(adder(5, 6, 7))
print(adder(ugly = 7, good = 6, bad = 5))
# Second part solution
def adder1(*args): # Sum any number of positional args
tot = args[0]
for ar... | Python | 1 |
);
assert_eq!(pgettext("context", "Hello, World!"), "Hello, World!");
}
#[test]
fn ngettext_fn() {
let _ = *SETUP;
assert_eq!(
current_textdomain().unwrap(),
"initialized_domain".as_bytes()
);
assert_eq!(
ngettext("Hello, World!", "Hello, Worlds!", 1),
"Hello,... | Rust | 0 |
},
_ => (),
}
idx += len as usize;
}
panic!("Configuration ended without terminator.")
}
mod hid;
mod cdc;
pub use hid::*;
pub use cdc::*;
<filename>fog/view/connection/src/lib.rs
// Copyright (c) 2018-2021 The MobileCoin Foundation
use fog_api::view_grpc;
use fog_enclave_connec... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.