text string | label_name string | labels int64 |
|---|---|---|
when I am asleep"),
/// Status::Chilling => {
/// stand_up();
/// go_downstairs();
/// }
/// Status::Working => {
/// go_downstairs();
/// }
/// }
/// Ok(())
/// }
/// ```
///
/// # With an underlying error
///
/// Provide a `Result` as the fi... | Rust | 0 |
format: HardwareBufferFormat,
usage: HardwareBufferUsage,
stride: u32,
}
impl HardwareBufferDesc {
fn into_native(self) -> ffi::AHardwareBuffer_Desc {
ffi::AHardwareBuffer_Desc {
width: self.width,
height: self.height,
layers: self.layers,
format... | Rust | 0 |
mbinator::{all_consuming, opt, recognize},
error::{context, ContextError, ParseError},
sequence::{preceded, tuple},
IResult,
};
use crate::{parse, parse::NL, BStr, ByteSlice, TagRef};
pub fn git_tag<'a, E: ParseError<&'a [u8]> + ContextError<&'a [u8]>>(i: &'a [u8]) -> IResult<&[u8], TagRef<'a>, E> {
l... | Rust | 0 |
c;
use deno_core::anyhow::anyhow;
use deno_core::anyhow::bail;
use deno_core::error::AnyError;
use deno_core::futures::future;
use deno_core::serde_json;
use deno_core::serde_json::Value;
use tower_lsp::lsp_types as lsp;
use tower_lsp::lsp_types::ConfigurationItem;
use crate::lsp::repl::get_repl_workspace_settings;
... | Rust | 0 |
DEV_ADDR,
vec![
Register::ALM1SEC,
0b0100_0001,
0b0011_0010,
0b0001_0101,
0b0000_0100 | BitFlags::ALMPOL,
0b0000_0011,
0b0001_00... | Rust | 0 |
de enable"]
#[inline]
pub fn half(&mut self) -> _HALFW {
_HALFW { w: self }
}
#[doc = "Bit 4 - Re-triggerable mode"]
#[inline]
pub fn retrig(&mut self) -> _RETRIGW {
_RETRIGW { w: self }
}
#[doc = "Bit 3 - Continuous mode"]
#[inline]
pub fn cont(&mut self) -> _CON... | Rust | 0 |
lder="不希望出现在图像中的内容",
value=config.get("default_negative_prompt", ""),
lines=2
)
adaptive_ratio_edit = gr.Checkbox(
label="自适应原图比例",
value=True,
info="勾选后只需调整长边尺寸,自动保持原图比例"... | Python | 1 |
oerce(self, sys::napi_coerce_to_string)
}
fn as_napi_any(&self) -> Any {
Any::with_value(self.env(), self.as_sys_value())
}
fn value_type(&self) -> Result<ValueType> {
let env = self.env();
let mut result = sys::napi_valuetype::napi_undefined;
env.handle_status(unsafe ... | Rust | 0 |
acesso = 5
senha = 'Admin123'
print('Digite usúario e senha para entrar: ')
nome = print(input('Insira um u´suario:'))
# chave = print(input('Insira a senha:'))
if nome == acesso:
print('Benvido ao sistema.')
else:
print('Usúario sem acesso!') | Python | 1 |
= symbols.iter().filter_map(|(_, v)| match v.symbol_label {
LabelOrLoc::Ident(id) => Some((id, v.ty)),
LabelOrLoc::Loc(_) => None, // static variable
});
let symbols = HashRef::new_iter(&self, capa, symbols);
if let TCOpcodeKind::ScopeBegin(syms, _) = &mut env.ops[scope_... | Rust | 0 |
"]
pub const SPSVCINST_STOPSERVICE: u32 = 512u32;
#[doc = "*Required features: `\"Win32_Devices_DeviceAndDriverInstallation\"`*"]
pub const SPSVCINST_TAGTOFRONT: u32 = 1u32;
#[doc = "*Required features: `\"Win32_Devices_DeviceAndDriverInstallation\"`*"]
pub const SPSVCINST_UNIQUE_NAME: u32 = 65536u32;
#[doc = "*Require... | Rust | 0 |
"""
Main entry point for Cryptiq Telegram bot.
Sets up the bot, registers handlers, and starts polling.
"""
import os
from telegram.ext import Application, CommandHandler, MessageHandler, CallbackQueryHandler, filters, JobQueue
from dotenv import load_dotenv
import handlers
# Load environment variables from .env file ... | Python | 1 |
from collections import deque
def bfs(graph, start):
queue = deque([(start, [start])])
visited = {start: 0}
while queue:
node, path = queue.popleft()
for neighbor, edge in graph[node].items():
if neighbor not in visited:
queue.append((neighbor, path + [neighbor]... | Python | 1 |
OutputCase::B }, .. } ) ) );
}
#[test]
fn seq_should_handle_owned_item_match() {
enum Input {
A,
B,
}
struct Output<'a> {
a : &'a Input,
b : &'a Input,
}
seq!(m<'a>: &'a Input => Output<'a> = a <= Input::A, b <= In... | Rust | 0 |
from unittest import TestCase
from scripts.tokenizer import count_pairs, merge, BpeTokenizer
class TestTokenizer(TestCase):
def test_count_pairs(self):
data = [[0, 0, 1, 2, 2], [2, 2, 3, 4, 0, 10]]
self.assertEqual(
count_pairs(data),
{
(0, 0): 1,
... | Python | 1 |
[doc(alias = "gst_video_caption_meta_api_get_type")]
fn meta_api() -> glib::Type {
unsafe { from_glib(ffi::gst_video_caption_meta_api_get_type()) }
}
}
#[cfg(any(feature = "v1_16", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v1_16")))]
impl fmt::Debug for VideoCaptionMeta {
fn... | Rust | 0 |
# Custom Operator to execute multiple SQL statements in SQL file in Redshift
# Reference: https://blog.shellkode.com/airflow-postgresql-operator-to-execute-multiple-sql-statements-dd0d07365667
from airflow.providers.postgres.hooks.postgres import PostgresHook
from airflow.models.baseoperator import BaseOperator
from a... | Python | 1 |
is(produto_teste)
print("\nAplicação sequencial de regras:")
print(f"NCM sugerido: {resultado_regras['ncm_sugerido']}")
print(f"Confiança: {resultado_regras['confianca']}")
print(f"Justificativas: {resultado_regras['justificativas']}")
# Testa regras CEST (novo)
resultado_cest = processor.aplic... | Python | 1 |
1 == *output.first().unwrap()
} else {
false
}
}
fn check_box(program: &Program, x: i64, y: i64) -> bool {
is_beam(program, x, y) && is_beam(program, x + 99, y) && is_beam(program, x, y + 99)
}
#[aoc(day19, part1)]
pub fn solve_part1(input: &Program) -> usize {
let mut beam = HashSet::new... | Rust | 0 |
cli::parse_recipe(recipe_file) {
Ok(r) => {
cli::output_recipe_info(r, matches.is_present("ingredients"));
}
Err(e) => {
eprintln!("{:?}", e);
}
}
} else if let Some(matches) = matches.subcommand_matches("groceries") {
/... | Rust | 0 |
),
};
Timestamp::new(seconds, nanos)
}
TimeOrNow::Now => Timestamp::new(0, libc::UTIME_NOW as i32),
});
let mtimestamp = mtime.map(|time_or_now| match time_or_now {
TimeOrNow::SpecificTime(x) =>... | Rust | 0 |
u"""
Fixer for os.getcwd() -> os.getcwdu().
Also warns about "from os import getcwd", suggesting the above form.
"""
from lib2to3 import fixer_base
from lib2to3.fixer_util import Name
class FixGetcwd(fixer_base.BaseFix):
PATTERN = u"""
power< 'os' trailer< dot='.' name='getcwd' > any* >
... | Python | 1 |
ers.push(Players {
position: 1,
avatar: "|$C$ ",
avatar_overlap: "|*A#B$C%D ",
avatar_display: "$C$",
});
println!("Player C's avatar is {:?}", arr_players[2].avatar_display);
arr_playe... | Rust | 0 |
CheckResponse, Handlers};
//!
//! #[no_mangle]
//! pub fn wapc_init() {
//! Handlers::register_health_request(health);
//! }
//!
//! fn health(_msg: HealthCheckRequest) -> HandlerResult<HealthCheckResponse> {
//! Ok(HealthCheckResponse::healthy())
//! }
//! ```
//!
mod generated;
pub use generated::{
deser... | Rust | 0 |
import datetime
from django.db import transaction
from .generic_view import GenericView
from ..models.app import App
from ..models.conference import Conference
from ..decorators import check_request_body
from ..utils import (JSONHttpResponse, validate_string, validate_api_key)
from ..errors import (INVALID_API_KEY,... | Python | 1 |
]
batches.append(batch)
if self.shuffle:
batch_ids = torch.randperm(len(batches), generator=g).tolist()
batches = [batches[i] for i in batch_ids]
self.batches = batches
assert len(self.batches) * self.batch_size == self.num_samples
return i... | Python | 1 |
tup_pptdev_msix(struct vmctx *ctx, int vcpu, int pptfd,
int idx, uint64_t addr, uint64_t msg, uint32_t vector_control);
int vm_get_pptdev_limits(struct vmctx *ctx, int pptfd, int *msi_limit,
int *msix_limit);
*/
pub fn vm_get_intinfo( ctx: *mut vmctx, vcpu: c_int, i1: *mut uint64_t, i2: *mu... | Rust | 0 |
) {
Some(status) => {
if i32::from(status.as_u16()) != last_status {
last_status = i32::from(status.as_u16());
last_update = SystemTime::now();
println!(" HTTP/{}", status)
} else {
... | Rust | 0 |
#!/usr/bin/env python3
"""
Minimal SCF input generator using your vspyrun package.
"""
import os
import sys
import shutil
# --- CONFIG ------------------------------------------------------------
# INCAR (electronic settings) — keep as strings to match your function signatures
#Control
LWAVE = ".FALSE."
# electron sc... | Python | 1 |
message| {
message.embed(|embed| {
embed.author(|author| {
author.name(channel_name);
author.icon_url(guild_icon)
});
embed.color(serenity::utils::Colour::BLURPLE);
embed.description(format!(
"{}\
**_... | Rust | 0 |
// region Tests
/// Implement tests for all scalar binary operations on a matrix `Matrix<T>` and a scalar value `T`.
///
/// # Tested Binary Operators Traits
///
/// * [`Add`]
/// * [`BitAnd`]
/// * [`BitOr`]
/// * [`BitXor`]
/// * [`Div`]
/// * [`Mul`]
/// * [`Rem`]
/// * [`Shl`]
/// * [`Shr`]
/// * [`Sub`]
///
/// [... | Rust | 0 |
balance_time_ms = balance.get("time_ms", 0) # 时间(毫秒),默认值为 0
balance_type = balance.get("type", "UNKNOWN") # 类型,默认值为 "UNKNOWN"
user = balance.get("user", "UNKNOWN") # 用户 ID,默认值为 "UNKNOWN"
# 更新余额数据
self.balance[currency] = {
... | Python | 1 |
_avg / 400.0);
let e_win = r_win / (r_win + r_lose);
let e_lose = r_lose / (r_win + r_lose);
static K_FACTOR: f32 = 32.0;
let winner_delta = K_FACTOR * (1.0 - e_win);
let loser_delta = K_FACTOR * (-e_lose);
for id in winners {
user_pool.get_user(id).update... | Rust | 0 |
register.
pub mod STK LOAD;
0xE000_E014 0x20 0x0000_0000
RReg WReg;
/// RELOAD value.
RELOAD { 0 24 RRRegField WWRegField }
}
reg! {
/// SysTick current value register.
pub mod STK VAL;
0xE000_E018 0x20 0x0000_0000
RReg WReg;
/// Current counter value.
CURRENT { 0 24 RRRegF... | Rust | 0 |
let ip_address = matches.value_of("ip_address").unwrap();
let port = matches.value_of("port").unwrap().parse::<u16>()?;
let mut client = ImageManagementClient::connect(
format!("http://{}:{}", ip_address, port)).await?;
// parse load format
let format = match store_matches.value_of("FORMAT"... | Rust | 0 |
}', ['\u{1e923}', '\0', '\0']), ('\u{1e902}',
['\u{1e924}', '\0', '\0']), ('\u{1e903}', ['\u{1e925}', '\0', '\0']), ('\u{1e904}',
['\u{1e926}', '\0', '\0']), ('\u{1e905}', ['\u{1e927}', '\0', '\0']), ('\u{1e906}',
['\u{1e928}', '\0', '\0']), ('\u{1e907}', ['\u{1e929}', '\0', '\0']), ('\u{1e908}'... | Rust | 0 |
{
if ibase.isc_open_blob()(&mut status[0], db, tr, &mut handle, &mut blob_id) != 0 {
return Err(status.as_error(ibase));
}
}
// Assert that the handle is valid
debug_assert_ne!(handle, 0);
let mut blob_stat = 0;
while blob_stat == 0 || status[1] == (ibase::isc_segment... | Rust | 0 |
from typing import TYPE_CHECKING, Any
from langchain._api import create_importer
if TYPE_CHECKING:
from langchain_community.chat_models.azureml_endpoint import (
AzureMLChatOnlineEndpoint,
LlamaContentFormatter,
)
# Create a way to dynamically look up deprecated imports.
# Used to consolidate... | Python | 1 |
import time
import hmac
import hashlib
import base64
import urllib.parse
import os
import httpx
def format_message(slow_log):
line = (f"- 🕒 开始时间: {slow_log.start_time}\n"
f"- 🧑💻 用户主机: {slow_log.user_host}\n"
f"- 🔍 查询时间: {slow_log.query_time}\n"
f"- 🔒 锁定时间: {slow_log.lock_... | Python | 1 |
#!/usr/bin/python3
"""Defines a class Square"""
class Square:
"""Class that defines properties of square.
"""
pass
| Python | 1 |
class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
# Transpose
n = len(matrix)
for i in range(n-1):
for j in range(i+1, n):
matrix[i][j], matrix[j][i] = matrix[... | Python | 1 |
&mut H)
where
H: Hasher,
{
match *self {
Constant::Str(ref s, ref k) => {
s.hash(state);
k.hash(state);
},
Constant::Binary(ref b) => {
b.hash(state);
},
Constant::Char(c) => {
... | Rust | 0 |
import sqlite3
def init_db():
"""
Database connection banata hai aur 'users' table create karta hai.
"""
conn = sqlite3.connect('users.db')
cursor = conn.cursor()
print("Database connection successful.")
# SQL command to create the 'users' table
cursor.execute('''
CREA... | Python | 1 |
///
/// Serialization:
///
/// ```
/// # extern crate geojson;
/// # fn main() {
/// use geojson::FeatureCollection;
/// use geojson::GeoJson;
///
/// let feature_collection = FeatureCollection {
/// bbox: None,
/// features: vec![],
/// foreign_members: None,
/// };
///
/// let serialized = GeoJson::from(... | Rust | 0 |
from os.path import join
import json
"""
Helper script to split CoSQL splits [train, dev] into CoVis splits [train, dev, test]
"""
# Percent of the CoSQL dev to convert to the new dev and new test sets.
PERC_DEV = .65
PERC_TEST = .35
if __name__ == '__main__':
print('CAUTION: YOU SHOULD NOT BE RUNNING THIS IN PY... | Python | 1 |
import scrypt, os, binascii
passwd = "p@$$w0rD~3"
salt = os.urandom(32)
print("Salt: ", binascii.hexlify(salt))
key = scrypt.hash(passwd, salt, 16384, 16, 1, 32)
print("Derived key:", binascii.hexlify(key))
| Python | 1 |
# -*- coding: utf-8 -*-
from pandas import DataFrame, Series
from atklip.controls.pandas_ta._typing import DictLike, Int
from atklip.controls.pandas_ta.ma import ma
from atklip.controls.pandas_ta.utils import (
v_bool,
v_drift,
v_mamode,
v_offset,
v_pos_default,
v_series
)
def thermo(
hig... | Python | 1 |
# -*- coding: utf-8 -*-
# @Time : 2020/10/1 19:21
# @Author : Duofeng Wu
# @File : gd_handle.py
# @Description: 自动解析掼蛋所发送来的JSON数据
class State(object):
def __init__(self):
"""
每个实例的保护属性对应JSON中的字段值,私有属性表示根据不同type和stage进行不同解析。
type: 表示消息类型。可取值包括notify和act。notify表示通知... | Python | 1 |
>>>,
pub high: Option<flatbuffers::WIPOffset<Tensor<'a>>>,
}
impl<'a> Default for UniformArgs<'a> {
#[inline]
fn default() -> Self {
UniformArgs {
low: None,
high: None,
}
}
}
pub struct UniformBuilder<'a: 'b, 'b> {
fbb_: &'b mut flatbuffers::FlatBufferBuilder<'... | Rust | 0 |
only these files, ignore path"),
)
// add a video codec option
.arg(
Arg::with_name("video-codec")
.short("v")
.long("video-codec")
.takes_value(true)
.help("video codec to use")
.default_value("h264")
... | Rust | 0 |
from setuptools import find_packages, setup
setup(
name="luxai-s3",
version="0.2.1",
packages=find_packages(exclude="kits"),
install_requires=[
"jax",
"gymnax==0.0.8",
"tyro",
],
entry_points={"console_scripts": ["luxai-s3 = luxai_runner.cli:main"]},
author="Lux AI C... | Python | 1 |
r, tmp_path):
s3_folder = rh.folder(system="s3")
assert s3_folder.system == "s3"
s3_folder._upload(src=local_folder.path)
assert s3_folder.exists_in_system()
assert "sample_file_0.txt" in s3_folder.ls(full_paths=False)
downloaded_path_folder = tmp_path / "downloaded_s3... | Python | 1 |
from llama_cpp import Llama
import json
from typing import List, Union, Generator
from knowledge_store import MarqoKnowledgeStore
# Initialize LLM model with updated configuration
LLM = Llama(
model_path="models/8B/Meta-Llama-3.1-8B-Instruct-Q4_K_M.gguf",
n_ctx=4096, # Increased context size
n_gpu_layers=... | Python | 1 |
t v2: Value = serde_json::from_str(data).unwrap();
assert_eq!(v1, v2)
}
use std::collections::HashMap;
use super::model::{EventKind, Events, Model, Operations};
#[derive(Clone, Debug)]
pub enum Op {
GET,
PUT,
APPEND,
}
#[derive(Clone, Debug)]
pub struct KvInput {
pub op: Op,
pub key: String,... | Rust | 0 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
解析Apache Benchmark测试结果并生成性能对比报告
此脚本从feat-test/target/ab-results目录读取Apache Benchmark测试结果文件,
提取关键性能指标,并生成包含图表的HTML报告,用于比较Feat、Vert.x和Spring Boot框架的性能。
"""
import os
import re
import sys
from datetime import datetime
# 测试结果目录
RESULTS_DIR = 'target/ab-results'
# 输出报告文件... | Python | 1 |
thout_ligatures() {
let mut reshaper = ArabicReshaper::new();
*reshaper.configuration.get_mut("delete_harakat").unwrap() = false;
*reshaper.configuration.get_mut("support_ligatures").unwrap() = false;
*reshaper
.configuration
.get_mut("shift_harakat_position")
.unwrap() = true;
... | Rust | 0 |
from heapq import heappop, heappush
from collections import defaultdict, Counter, deque
from functools import reduce, lru_cache
import math
import sys
fin = open(sys.argv[1]) if len(sys.argv) > 1 else sys.stdin
res = 0
ordering = defaultdict(set)
for y, line in enumerate(fin):
if line == "\n": break
a, b = map(i... | Python | 1 |
result = self.find_node(NodeKey::new_leaf(nw, ne, sw, se));
node.result.set(result);
result
}
fn gc_root(&mut self, node: NodeId) {
self.gc_roots.push(node);
}
fn gc_save(&mut self) -> usize {
self.gc_roots.len()
}
fn gc_restore(&mut self, s: usize) {
self.gc_roots.truncate(s);
}
... | Rust | 0 |
increment_privacy_request_retry_count("test-request")
assert "Cache error" in str(exc_info.value)
def test_reset_privacy_request_retry_count(self, cache):
"""Test resetting retry count."""
from fides.api.util.cache import (
get_privacy_request_retry_cache_key... | Python | 1 |
人",
"人間蟻",
"悪癖九年",
"想定外の趣味",
"不可思議感",
"狂騒原理の記憶",
"終焉の起源",
"悲惨この礼",
"無いが意見の添姉妹",
"魔女の水晶体",
"才能の目",
"壊いもの知らず",
"豚人形",
"胸を穿つ病",
"迷走信経",
"先端恐怖症",
"ない意味で意味がない",
"胸中無念",
"四角い意識を丸く欠く",
"利害還元者",
"目に入れたい",
"選ばれし私",
"心配機能",
"白日の下に羞恥の事実",
... | Rust | 0 |
d;
pub mod error;
pub mod ready;
pub mod shutdown;
"#,
);
for event in events.iter() {
if !event.is_default() {
output = format!(
"{}pub mod {};\n",
output,
event.get_reference()?.to_lowercase().replace(".", "_")
... | Rust | 0 |
)]
pub enum Chunk {
OldPallette,
OtherOldPallette,
Layer(Layer),
Cel(Cel),
CelExtra{
flags: u32,
x: Fixed,
y: Fixed,
width: Fixed,
height: Fixed,
},
ColorProfile{
profile_type: u16,
flags: u16,
gamma: Fixed,
icc_size: u3... | Rust | 0 |
dule.DoesNotExist:
pass
# Clear block completion data
BlockCompletion.objects.clear_learning_context_completion(user, course.id)
# Clear a student grades for a course
clear_user_course_grades(user.id, course.id)
update_audit_status(course_reset_audit, CourseRese... | Python | 1 |
import numpy as np
from qiskit import QuantumCircuit
from qiskit_aer import Aer
from qiskit.visualization import plot_bloch_multivector, plot_histogram
from qiskit.quantum_info import Statevector, state_fidelity
from qiskit_experiments.library import StateTomography
import matplotlib.pyplot as plt
# 1. Build a 3-qubit... | Python | 1 |
age.wait_for_load_state("networkidle")
break
except TimeoutError:
logging.warning("Timeout waiting for network idle state.")
while True:
job_links = await extract_links(base_url, page, JOB_LINKS_PATTERN)
... | Python | 1 |
planet, in *AU*, with the Sun in
/// the center and the ecliptic plane as reference `z = 0`.
///
/// # Example
///
/// Given a date in [*JD*](http://aa.usno.navy.mil/data/docs/JulianDate.php), we can get the
/// position of the planet Mercury in the solar system using rectangular coordinates. In this case,
/// we calcu... | Rust | 0 |
pub type LodObjectFormatAltAlt = FUELObjectFormat<ObjectZ, LodZAltAlt>;
pub mod cfa;
pub mod cfi;
mod reader;
mod parser;
pub use self::parser::*;
#![forbid(unsafe_code)]
use std::io::Write;
use trillium::{Conn, KnownHeaderName::ContentType};
/**
Renders a template and sets content-type as "text/html; charset=utf-8"... | Rust | 0 |
r + i) as isize * rsa) as *mut i8);
});
for j in kc_prefetch..kc {
let a = a.stride_offset(csa, j);
// MR::full_unroll(&mut |i|{
// *(pack.offset((j*mr+i)as isize)) = *a.stride_offset(rsa, i);
// });
// for i in 0..MR::to_usize() {
// *(pack.offset((j*mr+i)as isize)) = *a.stride_offset(rsa, i);... | Rust | 0 |
#-------------------------------------------------------------------------------
# elftools: common/exceptions.py
#
# Exception classes for elftools
#
# Eli Bendersky (eliben@gmail.com)
# This code is in the public domain
#-------------------------------------------------------------------------------
class ELFError(Ex... | Python | 1 |
x12, 0x34], "");
assert_feed_err!(d, [], [0xdb, 0xff], [0x56, 0x78], "");
assert_feed_ok!(d, [], [0xdb, 0xff], "");
assert_feed_err!(d, [], [], [0xdb, 0xff], "");
assert_feed_ok!(d, [], [0xdb, 0xff], "");
assert_finish_err!(d, "");
}
#[test]
fn test_decoder_invalid_l... | Rust | 0 |
tCount, d_outCount)
# cl.enqueue_copy(queue,outMerge, d_outMerge)
# ref = ai.integrate1d(data,bins,unit="2th_deg", correctSolidAngle=False, method="splitpixelfull")
ref = splitPixelFullLUT.HistoLUT1dFullSplit(pos, bins, unit="2th_deg")
# assert(numpy.allclose(ref,outMerge))
# #plot(ref[0],outMerge, label="ocl_lut... | Python | 1 |
_bytes_with_nul<'a>(ptr: *const c_char) -> &'a [u8] {
let s = c_char_ptr_to_cstr(ptr);
s.to_bytes_with_nul()
}
/// Converts a C string pointer to a vector, including a trailing null byte.
pub fn c_char_ptr_to_vec(ptr: *const c_char) -> Vec<u8> {
let s = c_char_ptr_to_bytes_with_nul(ptr);
s.to_vec()
}
... | Rust | 0 |
303 | 307 | 308 => Ok(Code::Redirect(code)),
200...599 => Ok(Code::Normal(code)),
_ => return Err(Error::unexpected_message(
format!("invalid response code {}", code))),
}
}
pub fn as_code(&self) -> u32 {
match *self {
Code::Redirect(code) => c... | Rust | 0 |
[derive(Clone, PartialEq, ::prost::Oneof)]
pub enum Expr {
/// The FilterExpressions in and_group have an AND relationship.
#[prost(message, tag = "1")]
AndGroup(super::FilterExpressionList),
/// The FilterExpressions in or_group have an OR relationship.
#[prost(message, tag ... | Rust | 0 |
in system database",
));
}
return Err(ErrorCode::UnknownTable(format!(
"Unknown table: '{}'",
table_name
)));
}
async fn create_database(&self, _plan: CreateDatabasePlan) -> Result<CreateDatabaseReply> {
Err(ErrorCode::UnImplement("Cannot cre... | Rust | 0 |
, 0.1],
]
),
)
)
scene[1] = np.vstack((scene[1], np.zeros((4, scene[1].shape[1]))))
scene[2] = np.concatenate((scene[2], np.full_like((scene[2]), 255)[:4]))
crop = scene[0][:, 0] > 0
crop &= scene[0][:, 1] > 0
if crop.size ... | Python | 1 |
);
*val = null_mut();
*ty = 0;
}
}
}
}
}
if let Some(ai) = unit.guard_ai() {
// Guard ai share bug, just make this a military then.
// Should happen f... | Rust | 0 |
"""
Dot Dash Plot
=============
How to make the dot-dash plot presented in Edward Tufte's `Visual Display of Quantitative Information <https://www.edwardtufte.com/tufte/books_vdqi>`_. Based
on a JavaScript implementation by `g3o2 <https://bl.ocks.org/g3o2/bd4362574137061c243a2994ba648fb8>`_.
"""
# category: scatter plo... | Python | 1 |
hash_bits: HASH_BITS,
seed_bits: SEED_BITS,
cutoff: 0, // no small string optimizations
}
};
}
#[pyclass(noattr, name = "int_info")]
#[derive(PyStructSequence)]
pub(super) struct PyIntInfo {
bits_per_digit: usize,
sizeo... | Rust | 0 |
# coding: utf-8
"""
Graphiant APIs
**To use the APIs:** 1) Login using `/api/v1/auth/login` 2) Copy the value of \"token\" in the response 3) Click the \"Authorize\" button 4) In the \"Value\" text field enter: `Bearer <your token>` 5) Click \"Authorize\" 6) All requests are now authorized. **Toke... | Python | 1 |
using Rust")
.version("1.0")
.author("<EMAIL>@<<EMAIL>")
.about("Get Topic Attributes")
.arg(
Arg::with_name("topic_arn")
.short("t")
.long("topic_arn")
.help("Set Topic Name")
.required(true)
.t... | Rust | 0 |
_vec[..ops_vec.len() - 4].to_vec().into_boxed_slice()
}
#[cfg(target_arch = "aarch64")]
#[allow(clippy::unused_self)]
fn generate_shadow_check_exact_blob(&mut self, val: u64) -> Box<[u8]> {
let shadow_bit = self.allocator.shadow_bit();
macro_rules! shadow_check_exact {
($ops... | Rust | 0 |
import pandas as pd
from sklearn.datasets import load_digits
from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import train_test_split
from sklearn.metrics import log_loss
from gama import GamaClassifier
def _gama_on_digits(gama):
X, y = load_digits(return_X_y=True, as_frame=True)
X... | Python | 1 |
S looks like
assert_series_equal(
lhs,
pl.Series(
[
[[[3, 7]], [[0], [None], [], [], None]],
],
dtype=pl.List(pl.List(pl.List(pl.Int16))),
),
)
assert len(lhs) == 1
class _: # type: ignore[no-redef]
rhs = pl.Series([1... | Python | 1 |
registered function will be called in the interrupt service function
///
/// # Unimportant
/// I originally hoped to use closures to achieve this function,
/// But the API in RT thread does not support me to pass closures as parameters.
/// so I can only use basic functions as the callback function... | Rust | 0 |
"""
扩展搜索管理器
统一管理所有扩展搜索功能
"""
import asyncio
import logging
from typing import Dict, List, Any
from concurrent.futures import ThreadPoolExecutor
from .web_searcher import WebSearcher
from .gitlab_searcher import GitLabSearcher
from .docker_searcher import DockerSearcher
logger = logging.getLogger(__name__)
class Ex... | Python | 1 |
#!/usr/bin/env python
"""
配置載入測試腳本
此腳本用於測試環境變數和配置文件的載入是否正確。
"""
import os
import sys
import pytest
from pathlib import Path
# 添加專案根目錄到 Python 路徑
ROOT_DIR = Path(__file__).parent.parent.absolute()
sys.path.insert(0, str(ROOT_DIR))
# 導入配置模組
from src import config
def print_separator(title):
"""打印分隔線"""
prin... | Python | 1 |
# Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | Python | 1 |
from django.db import models
from apps.commun.models import TimeStampedModel
class Fournisseur(TimeStampedModel):
TYPE_FOURNISSEUR_CHOICES= [
('ALIMENT', 'Aliment'),
('OEUFS', 'Oeufs'),
('MATERIEL', 'Matériel'),
]
nom = models.CharField(max_length=100, verbose_name="Nom du fourniss... | Python | 1 |
if not data or 'username' not in data or 'content' not in data:
return jsonify({"error": "Missing username or content"}), 400
new_entry = Entry(
username = data['username'],
content=data['content'],
timestamp=datetime.now().strftime('%Y-%m-%d %H:%M:%S')... | Python | 1 |
i),
(Literal::UnsignedInt(u), types::B1) => builder.ins().bconst(ir_type, u != 0),
(Literal::UnsignedInt(u), _) => builder.ins().iconst(ir_type, u as i64),
(Literal::Float(f), types::F32) => builder.ins().f32const(f as f32),
(Literal::Float(f), types::F64) => builder.ins... | Rust | 0 |
iōng"),
('垨', "shǒu"),
('垩', "è,shèng"),
('垪', "bìng"),
('垫', "diàn"),
('垬', "hóng"),
('垭', "yā"),
('垮', "kuǎ"),
('垯', "da"),
('垰', "kǎ"),
('垱', "dàng"),
('垲', "kǎi"),
('垳', "háng"),
('垴', "nǎo"),
('垵', "ǎn"),
('垶', "xīng"),
('垷', "xiàn"),
('垸', "yuàn,... | Rust | 0 |
ready`]: crate::Service::poll_ready
/// [`BoxError`]: crate::BoxError
fn map_result<F, Response, Error>(self, f: F) -> MapResult<Self, F>
where
Self: Sized,
Error: From<Self::Error>,
F: FnOnce(Result<Self::Response, Self::Error>) -> Result<Response, Error> + Clone,
{
MapR... | Rust | 0 |
rde_json::from_str(problem_json).unwrap();
let solution: Pose = serde_json::from_str(solution_json).unwrap();
let fixed: Vec<usize> = serde_json::from_str(fixed_indices_json).unwrap();
log("started");
brute_force::amylase_bruteforce::solve(
problem,
&fixed,
solution,
|pos... | Rust | 0 |
moryDB::new(false);
let mut trie = PatriciaTrieMut::new(&mut memdb);
let (keys, values) = random_data(10000);
for i in 0..keys.len() {
trie.insert(&keys[i], values[i].clone()).unwrap()
}
b.iter(|| {
let key = trie.get(&keys[7777]).unwrap();
a... | Rust | 0 |
def inverse_kinematics(p: tuple[float, float, float], r: tuple[float, float, float]) -> tuple[float, float]:
"""
Gets the joint values needed to reach position "p" and orientation "r".
:param p: The position to reach in the form [x, y, z].
:param r: The orientation to reach in radians in the form [x, y,... | Python | 1 |
, read_seq in reader:
if limit != None and read_count >= limit: break
read_set.append((read_name, read_seq))
read_count += 1
read_set_bases += len(read_seq)
if read_set_bases >= batch_size: break
if not read_set: break
if le... | Python | 1 |
tomData);
// Mask away the unused bits at the beginning.
tmp.0
.as_mut()
.last_mut()
.map(|val| *val &= core::u64::MAX >> P::REPR_SHAVE_BITS);
if tmp.is_valid() {
... | Rust | 0 |
#!/usr/bin/env python
# coding: utf-8
# For licensing see accompanying LICENSE file.
# Copyright (C) 2023 Apple Inc. All Rights Reserved.
from __future__ import print_function
from glob import glob
import os
from os.path import join as pjoin
from setuptools import setup, find_packages
from jupyter_packaging import ... | Python | 1 |
// We can suppress spurious write-watchpoint triggerings by checking
// whether memory values have changed. So we can sometimes conserve
// debug registers by upgrading an unaligned range to an aligned range
// of a larger size.
let align: usize;
if range.len() <= 2 {
... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.