text string | label_name string | labels int64 |
|---|---|---|
from typing import List
from sqlalchemy.orm import Session
from fastapi import HTTPException
from ..models.models import UserSchedule
from ..schemas.schedule import UserScheduleCreate
from .base import CRUDBase
class CRUDUserSchedule(CRUDBase[UserSchedule, UserScheduleCreate, UserScheduleCreate]):
def create(self,... | Python | 1 |
from fontTools.pens.boundsPen import BoundsPen
from fontbakery.prelude import check, FAIL, Message
from fontbakery.checks.iso15008.utils import (
xheight_intersections,
stem_width,
pair_kerning,
DISCLAIMER,
)
@check(
id="iso15008/intercharacter_spacing",
rationale="""
According to ISO... | Python | 1 |
e in `test_round_trip`.
#[test]
fn test_rustc_precedence() {
use walkdir::{WalkDir, WalkDirIterator};
use std::fs::File;
use std::io::Read;
common::check_min_stack();
common::clone_rust();
let abort_after = common::abort_after();
if abort_after == 0 {
panic!("Skipping all precedence... | Rust | 0 |
import requests
def check_username(username, platform):
"""
Checks if a username exists on a given platform.
Args:
username (str): The username to check.
platform (str): The URL template for the platform, with '{username}' placeholder.
Returns:
bool: True if the username exist... | Python | 1 |
, StoryMeta},
prelude::*,
utils::{self, FileIter},
},
format_ao3::{ParsedChapters, ParsedInfo, ParsedMeta},
std::{
collections::HashMap,
ffi::OsStr,
fs::{self, DirEntry},
hash::Hasher as _,
path::Path,
time::SystemTime,
},
};
// open index... | Rust | 0 |
leep(Duration::from_millis(1))
}
Err(e) => return Err(e),
}
};
writeln!(file, "int main(){{}}")?;
drop(file);
// Check for Standards versions
use CStandard::*;
for (std, flag) in [
(C89, "c89"),
(C95, "c9... | Rust | 0 |
<= self.gamma && self.gamma <= 1.0) {
return Err(BuildError::GammaOutOfRange);
}
Ok(TpeOptimizer {
param_range,
estimator_builder,
trials: Vec::new(),
is_sorted: false,
gamma: self.gamma,
candidates: NonZeroUsize::new(... | Rust | 0 |
import heapq
def shortest_path(matrix):
# Convert matrix into graph
graph = {}
for i in range(len(matrix)):
for j in range(len(matrix[i])):
if matrix[i][j] != 'x':
node = (i, j)
graph[node] = {}
# North, South, West, East
... | Python | 1 |
t(1)[0]
for elem in elems_flat[1:]:
n_static.merge_with(elem.get_shape().with_rank_at_least(1)[0])
for r in results_flat:
r.set_shape(tensor_shape.TensorShape(n_static).concatenate(
r.get_shape()[1:]))
if varscope_caching_device_was_none:
varscope.set_caching_device(None)
r... | Python | 1 |
{
/// The payload will be a UTF-8 string containing the resource representation of the object’s metadata.
JsonApiV1,
/// No payload is included with the notification.
None,
}
impl Default for PayloadFormat {
fn default() -> Self {
Self::JsonApiV1
}
}
use std::collections::hash_map::{En... | Rust | 0 |
def linearSearch(arr, x):
n = len(arr)
for i in range(n):
if arr[i] == x:
return i
return -1
arr = [1, 0, 3, 0, 5, 6]
x = 0
call = linearSearch(arr, x)
print(call)
| Python | 1 |
取完成,共获取到 {len(all_articles)} 篇文章")
return all_articles, success
def get_article_content(link, gzh_name, session=None):
"""获取文章正文 - 优化版本使用会话复用"""
if session is None:
session = SESSION
try:
headers = {
'referer': 'https://mp.weixin.qq.com/',
'accept': 'tex... | Python | 1 |
ethod)
} else {
self.update_disabled_methods("Alert", rpc_method);
}
self
}
pub fn enable_indexer(mut self, indexer_config: &IndexerConfig, shared: Shared) -> Self {
let store = DefaultIndexerStore::new(indexer_config, shared);
let rpc_method = IndexerRpcImpl... | Rust | 0 |
# frontend/admin/admin_grades_window.py
from PyQt5.QtWidgets import QWidget, QLabel, QVBoxLayout, QFormLayout, QLineEdit, QComboBox, QPushButton, QMessageBox, QTableWidget, QTableWidgetItem, QHBoxLayout
from PyQt5.QtCore import Qt
from frontend import style
from backend import grades_model, student_model, course_model... | Python | 1 |
ite-api).\n\nFor information about available fields see [syscon_flash_ace1_attr](syscon_flash_ace1_attr) module"]
pub type SYSCON_FLASH_ACE1_ATTR = crate::Reg<u32, _SYSCON_FLASH_ACE1_ATTR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _SYSCON_FLASH_ACE1_ATTR;
#[doc = "`read()` method returns [syscon_flash_ace1_attr... | Rust | 0 |
::new_num(100),
/// ])))
/// ]).unwrap();
///
/// let mut fmtr = Formatter::new(&kserd);
///
/// fmtr.concise(0).unwrap();
/// fmtr.inline(2).unwrap();
///
/// for i in 0..fmtr.len() {
/// fmtr.id(i, false).unwrap(); // set all ids to false
/// }
///
/// asser... | Rust | 0 |
Here we reserve 'length'
// bytes so it will have non-zero size.
body.resize(length, 0);
self.port.read_exact(&mut body)?;
// And unmarshal the reply body into a reply type.
return Ok(T::try_from(wire::Payload(body)).map_err(|e| e.to_string())?);
}
}
#[cfg(test)]
mod tests... | Rust | 0 |
Rel,
atomic::Ordering::Relaxed,
)
.is_ok()
{
return;
}
}
self.list.append(atomic::AtomicPtr::new(descriptor));
}
pub fn get(&self, ptr: *mut u8) -> Option<*mut Descriptor> {
for a_ptr in self.li... | Rust | 0 |
{name} varlen forward. '
f'{NO_ATTN_WEIGHTS_MSG}', 'current')
module.forward = types.MethodType(varlen_attn_forward, module)
elif name in VARLEN_ATTN_DISPATCH_MAPPING:
if varlen_attn_forward is None:
varlen_attn_forward = VARLEN_ATTN_DISPATCH_MAPPING[name]... | Python | 1 |
print(f"未发现有效bypass tech")
#todo 分离敏感信息发现函数
# anchors=self.getApiWithoutTokenAnchor(fuzzResultList)
anchors=self.getApiWithoutTokenAnchor2(fuzzResultList)
juicyApiList=self.getSuspiciousApiFromFuzzResult(anchors,fuzzResultList)
#敏感信息发现
... | Python | 1 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from test053_phid_helpers2 import *
import opengate as gate
def main(dependency="test053_phid_10_all_ref_mt.py"):
paths = get_default_test_paths(__file__, "", output_folder="test053")
# bi213 83 213
# ac225 89 225
# fr221 87 221
# pb 82 212
# po... | Python | 1 |
f)
}
(Date64, Date32) => {
let date_array = array.as_any().downcast_ref::<Date64Array>().unwrap();
let mut b = Date32Builder::new(array.len());
for i in 0..array.len() {
if array.is_null(i) {
b.append_null()?;
} else... | Rust | 0 |
def buscaMenor(arr):
menor = arr[0]
menor_indice = 0
for i in range(1, len(arr)):
if arr[i] < menor:
menor = arr[i]
menor_indice = i
return menor_indice
def ordenacaoporSelecao(arr):
novoArr = []
for i in range(len(arr)):
menor = buscaMenor(arr)
... | Python | 1 |
lden_ears'"):
m2h.export_vtk(cwd, 'golden_ears')
# invalid frequency steps
# not enough values
with pytest.raises(ValueError, match="frequency_steps must contain"):
m2h.export_vtk(cwd, frequency_steps=1)
# too many values
with pytest.raises(ValueError, match="frequency_steps must co... | Python | 1 |
type_name: Ident,
internal: bool,
block: TokenStream,
) -> TokenStream {
let const_name = Ident::new(
&format!("_palette_derive_{}_for_{}", trait_name, type_name),
Span::call_site(),
);
if internal {
quote!{
#[allow(non_snake_case, unused_attributes, unused_... | Rust | 0 |
"""
Plot SurfRad Data
-----------------
This data shows how to read in SurfRad data from the urls and plot
the data up in a time series
Author: Adam Theisen
"""
import act
import matplotlib.pyplot as plt
# Easily download data from SURFRAD
results = act.discovery.download_surfrad_data('tbl', startdate='20230601', ... | Python | 1 |
<Ident>,
pub name: Ident,
}
impl FromStr for CompositeType {
type Err = ();
fn from_str(s: &str) -> Result<CompositeType, Self::Err> {
if s.contains('.') {
let mut split = s.rsplitn(2, '.');
let name = Ident::from(String::from(split.next().unwrap()));
let namesp... | Rust | 0 |
= temperatures.grab_mut(target);
let direction = {
if rolled_damage.options.contains(DamageOptions::RAISE_TEMPERATURE) {
Some(TemperatureDirection::Heat)
} else if rolled_damage.options.contains(DamageOptions::LOWER_TEMPERATURE) {
Some... | Rust | 0 |
import json
from typing import Optional
from opentelemetry.context import Context
from opentelemetry.sdk.trace import ReadableSpan as OTelReadableSpan
from opentelemetry.sdk.trace import Span as OTelSpan
from opentelemetry.sdk.trace.export import BatchSpanProcessor, SpanExporter
from mlflow.entities.trace_info import... | Python | 1 |
logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error when DEBUG=False.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
... | Python | 1 |
197.597000, 4226.259000)]);
}
fn init_struct_1() -> Root {
let root_struct: Root = Root {
chapters: {
vec![
Chapter {
id: 16,
time_base: String::from("1/1000"),
start: 197597,
... | Rust | 0 |
::raw::c_int,
skipsensor: ::std::os::raw::c_int,
);
}
extern "C" {
pub fn mj_inverseSkip(
m: *const mjModel,
d: *mut mjData,
skipstage: ::std::os::raw::c_int,
skipsensor: ::std::os::raw::c_int,
);
}
extern "C" {
pub fn mj_defaultLROpt(opt: *mut mjLROpt);
}
extern ... | Rust | 0 |
'''
鼠标操作api测试
注意,只有接盒子上的键盘鼠标才能被屏蔽。
'''
import kmNet
import time
#连接盒子
ip='192.168.2.188'
port ='1282'
uuid ='AF425414'
kmNet.init(ip,port,uuid)
print('连接盒子ok')
kmNet.monitor(5001) #开启键鼠监控
#首先屏蔽鼠标所有按键,以及键盘的a键和左ctrl键
kmNet.mask_left(1)#屏蔽物理鼠标左键
kmNet.mask_right(1)#屏蔽物理鼠标右键
kmNet.mask_middle(1)#屏蔽物理鼠标中键
kmNet.mask_sid... | Python | 1 |
# src/infrastructure/persistence/migrations/env.py
"""Arquivo de configuração do Alembic para migrações."""
from logging.config import fileConfig
from sqlalchemy import engine_from_config
from sqlalchemy import pool
from alembic import context
import os
import sys
sys.path.append(os.path.dirname(os.path.dirname(os.p... | Python | 1 |
ax.set_xlabel(xlabel)
ax.set_ylabel(ylabel)
# Plot points if provided
if positive_points is not None:
for point in positive_points:
px, py = point
ax.plot(px, py, 'ro', markersize=6, label="Positive Point")
if negative... | Python | 1 |
}
pub fn bindings(&self) -> &[DamlBinding<'a>] {
&self.bindings
}
pub fn body(&self) -> &DamlExpr<'a> {
self.body.as_ref()
}
}
impl<'a> DamlVisitableElement<'a> for DamlBlock<'a> {
fn accept(&'a self, visitor: &'a mut impl DamlElementVisitor) {
visitor.pre_visit_block... | Rust | 0 |
v)| v && !tile_cache.contains(n, LayerType::Displacements))
// .map(|(n, v)| n.level())
// .min();
// if let Some(min) = min_missing_level {
// for (n, v) in node_visibilities.iter_mut() {
// if n.level() >= min {
// *v = false;
// ... | Rust | 0 |
clone(),
get_button_style(1),
).on_click(name_1)),
Widgets::Button(Button::new(
name_2.clone(),
get_button_style(2),
).on_click(name_2)),
Widgets::Button(Button::new(
name_3.cl... | Rust | 0 |
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
# --------------------------------------------------------------------------
import os
expected_coverage = dict()
expected_coverage["collectives.py"]... | Python | 1 |
# Copyright (c) 2025 PaddlePaddle 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 applicab... | Python | 1 |
"""
HOC Configurator
Copyright (C) Souldbminer
This program is free software; you can redistribute it and/or modify it
under the terms and conditions of the GNU General Public License,
version 2, as published by the Free Software Foundation.
This program is distributed in the hope that it will be useful, but WITHOU... | Python | 1 |
control_wakeupmon() {
assert_eq!(
::std::mem::size_of::<proc_rlimit_control_wakeupmon>(),
8usize,
concat!("Size of: ", stringify!(proc_rlimit_control_wakeupmon))
);
assert_eq!(
::std::mem::align_of::<proc_rlimit_control_wakeupmon>(),
4usize,
concat!("Alignment... | Rust | 0 |
= reader.read_var_uint()?;
Ok(StreamDataBlockedFrame {
stream_id,
max_offset,
})
}
fn put_contents(&self, buf: &mut impl MutBufOerExt) {
buf.put_var_uint(self.stream_id);
buf.put_var_uint(self.max_offset);
}
}
#[cfg(test)]
mod serialization {
u... | Rust | 0 |
<_>>().into() }
// }
/// Obtains the current value for a particular key.
/// Not for end-users; they can use `probe_value`.
fn value(&self, key: K) -> &VarValue<K, V> {
&self.values[key]
}
/// Find the root node for `vid`. This uses the standard
/// union-find algorithm with path compression:
/// ... | Rust | 0 |
let incoming_service = ValidatorService::incoming(incoming_service);
// Handle incoming packets sent via BTP
btp_service.handle_incoming(incoming_service.clone());
// TODO should this run the node api on a ... | Rust | 0 |
import numpy as np
def normalize_data(data):
return data / 255.0
def reshape_data(data):
return np.expand_dims(data, axis=-1)
| Python | 1 |
Self::xyz(x, y, 0.)
}
pub(crate) fn update_with_velocity(&mut self, velocity: Velocity, delta_time: Duration) {
self.x += velocity.x * delta_time.as_secs_f32();
self.y += velocity.y * delta_time.as_secs_f32();
self.z += velocity.z * delta_time.as_secs_f32();
}
pub(crate) fn upd... | Rust | 0 |
eck the number of nodes
assert np.allclose(graph.num_nodes(), len(mol.get_atomic_numbers()))
# check the atomic feature of atom 0
assert np.allclose(graph.ndata["node_type"].detach().numpy()[0], 1)
# check the atomic feature of atom 4
assert np.allclose(graph.ndata["node_type"].detach().numpy()[1], ... | Python | 1 |
r.hidden_dim, device=device)
outputs = []
for i in range(self.max_caption_len):
if i > 0 and numberic_captions[:, i].sum() == 0:
output_word = torch.zeros([bsz, n_vocab]).cuda()
outputs.append(output_word)
continue
it = numberic_c... | Python | 1 |
# gunbot_quant_tools/strategies/base_strategy.py
from abc import ABC, abstractmethod
import pandas as pd
import numpy as np
class BaseStrategy(ABC):
"""Abstract base class for all generic trading strategies."""
def __init__(self, name: str, params: dict = None):
self.name = name
self.params = ... | Python | 1 |
ProcessStatus::from(kproc.ki_stat);
// from FreeBSD source /src/usr.bin/top/machine.c
let virtual_memory = (kproc.ki_size / 1_000) as u64;
let memory = (kproc.ki_rssize * page_size) as u64 / 1_000;
// FIXME: This is to get the "real" run time (in micro-seconds).
// let run_time = (kproc.ki_runtime ... | Rust | 0 |
[nll]~^^ ERROR implementation of `FnOnce` is not general enough
//[nll]~| ERROR mismatched types
}
/*
* Copyright (c) 2021 gematik GmbH
*
* 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 ... | Rust | 0 |
ss:
progress(5, "Mische Stems…")
mix = None
for name, y in stems.items():
if allow is not None and name not in allow:
continue
if is_canceled():
return np.zeros(1, dtype=np.float32)
if mix is None:
mix = y.as... | Python | 1 |
48",
"0191707a-1d95-25a2-e24f-34d798199fa7",
"0191707a-1d95-3da7-8305-7175a9f56470",
"0191707a-1d95-543c-712f-a4db06ba98fc",
"0191707a-1d95-6c28-c534-7b0673b63e59",
"0191707a-1d95-78b2-729e-a5e8ab9edd... | Python | 1 |
2: [*mut ::std::os::raw::c_void; 64usize],
}
#[test]
fn bindgen_test_layout__NV_ENC_PRESET_CONFIG() {
assert_eq!(
::std::mem::size_of::<_NV_ENC_PRESET_CONFIG>(),
5128usize,
concat!("Size of: ", stringify!(_NV_ENC_PRESET_CONFIG))
);
assert_eq!(
::std::mem::align_of::<_NV_ENC_P... | Rust | 0 |
yAttempts) -> usize {
let mut inner_val = &mut this_ptr.get_native_mut_ref().0;
*inner_val
}
#[no_mangle]
pub extern "C" fn RetryAttempts_set_a(this_ptr: &mut RetryAttempts, mut val: usize) {
unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.0 = val;
}
/// Constructs a new RetryAttempts given each field
#[must_us... | Rust | 0 |
default_layout();
start_run(&mut timer);
make_progress_run_with_splits_opt(&mut timer, &[Some(5.0), None, Some(10.0)]);
let state = layout.state(&timer.snapshot());
let mut renderer = Renderer::new();
c.bench_function("Dummy Rendering (Default)", move |b| ... | Rust | 0 |
}
/// An iterator over edges.
pub struct OsrmEdges<'a, R: Read> {
entry: tar::Entry<'a, R>,
pub number_of_edges: u64,
current_edge_index: u64,
}
/// A connection between two nodes (source and target).
///
/// Nodes are referenced by their index which starts at zero and encodes the order in which the
/// ... | Rust | 0 |
}
}
fn parse_ch(cat: u8, ch: u8, stack: &mut Vec<u8>, mut state: u8,
ds: &mut Vec<Value>, ss: &mut String, es: &mut String)
-> Result<u8, JsonError>
{
loop {
let mut code: u16 = STATES[state as usize][cat as usize];
let mut action: u8 = (code >> 8 & 0xFF) as u8;
code &= ... | Rust | 0 |
) -> (String, Ed25519Pair) {
(
get_chain("fail_missing_head"),
get_leaf_key("fail_missing_head"),
)
}
use crate::keyring::{KeyPair, Nonces, PubKey};
use arraystring::{error, typenum::U10, ArrayString};
use serde::ser::{Serialize, SerializeStruct, SerializeTupleVariant, Serializer};
use sp_core::... | Rust | 0 |
, pending: ZX_SIGNAL_NONE },
];
assert_eq!(object_wait_many(&mut items, deadline_after(ten_ms)), Err(Status::ErrTimedOut));
assert_eq!(items[0].pending, ZX_SIGNAL_LAST_HANDLE);
assert_eq!(items[1].pending, ZX_SIGNAL_LAST_HANDLE);
// Signal one object and it should return success... | Rust | 0 |
abled)"]
pub mod dma_tcd11_biter_elinkno;
#[doc = "DMA_TCD11_BITER_ELINKYES register accessor: an alias for `Reg<DMA_TCD11_BITER_ELINKYES_SPEC>`"]
pub type DMA_TCD11_BITER_ELINKYES =
crate::Reg<dma_tcd11_biter_elinkyes::DMA_TCD11_BITER_ELINKYES_SPEC>;
#[doc = "TCD Beginning Minor Loop Link, Major Loop Count (Channe... | Rust | 0 |
fmt::Formatter) -> fmt::Result {
write!(f, "#{}", self.0)
}
}
//! This example demonstrates how to use `Text` to draw TrueType font texts efficiently.
extern crate good_web_game as ggez;
use ggez::event;
use ggez::graphics::{self, Align, Color, DrawParam, Font, PxScale, Text, TextFragment};
use ggez::time... | Rust | 0 |
import os
from rolerag import RoleRAG
from rolerag.llm import gpt_4o_mini_complete
#########
# Uncomment the below two lines if running in a jupyter notebook to handle the async nature of rag.insert()
# import nest_asyncio
# nest_asyncio.apply()
#########
WORKING_DIR = "workspace"
if not os.path.exists(WORKING_DIR):
... | Python | 1 |
}
pub(crate) fn parse(src: &str, radix: u32) -> Result<Digits, ParseError> {
let basis = Basis::new(radix);
let bytes = src.as_bytes();
if bytes.len() <= basis.digits_per_word {
Ok(Digits::Fix(parse_word(bytes, radix)?))
} else {
let chunks = bytes.rchunks(basis.digits_per_word);
l... | Rust | 0 |
'''
Phân tích từng biểu thức:
(a) i1 + (i2 * i3)
Tính: 2 + (5 * -3) = 2 + (-15) = -13
Nhân trước, cộng sau (theo thứ tự toán học).
(b) i1 * (i2 + i3)
Tính: 2 * (5 + -3) = 2 * 2 = 4
Phép cộng trong ngoặc được thực hiện trước.
(c) i1 / (i2 + i3)
Tính: 2 / (5 + -3) = 2 / 2 = 1.0
Phép chia trả về số thực (float).
(... | Python | 1 |
t differs between signing and verification!"
);
assert_eq!(
proof_too, *proof_batchable,
"Returning batchable proof failed!"
);
}
for (k, (ios, proof, _proof_batchable)) in keypairs.iter().zip(&ios_n_proofs) {
let outs = ios... | Rust | 0 |
write!(f, " at {}", path)?;
}
Ok(())
}
}
pub fn tokenize(source: Option<String>, input: &str) -> Result<Vec<Token>, TokenizeErr> {
let mut tokenizer = Tokenizer::new(source, input);
tokenizer.tokenize()
}
pub fn tokenize_lines(source: Option<String>, input: &str) -> Result<Vec... | Rust | 0 |
# Program 9: You are planning to throw a small bird at a distance d, with time t, and height h to some structure. Write a code in which you will use the physical quantities such as initial velocity,final velocity, angle in radians, gravity, height, sling shot etc.
import math
# User inputs
velocity = float(input('Gi... | Python | 1 |
k
}
}
}
}
}
}#![allow(unused_imports)]
/* automatically generated by rust-bindgen */
#![allow(dead_code,
non_camel_case_types,
non_upper_case_globals,
non_snake_case)]
use libc;
use libc::*;
use utypes::*;
use ustring::*;
use utf8::*;
use utf16::*;
u... | Rust | 0 |
final_answer_text = final_answer_text.replace("\n", " ")
# Display the search query at the top
final_answer_placeholder.markdown(
f'<h1 class="search-query">{user_query}</h1>',
... | Python | 1 |
READ_ONLY: bool = true;
const SET_ONCE: bool = false;
}
impl Property for Used {
fn name(&self) -> &str {
<Self as NativeProperty>::NAME
}
fn name_cstr(&self) -> &::std::ffi::CStr {
<Self as NativeProperty>::NAME_CSTR
}
}
impl<'a> ::std::fmt::Display for Used {
fn fmt(&self, f: ... | Rust | 0 |
import os
import json
from typing import Optional, Union
import pandas as pd
from datasets import load_dataset, Dataset
class MedicalOrderDataLoader:
def __init__(self, trs_json_path: str):
if not os.path.exists(trs_json_path):
raise FileNotFoundError(f"Dataset file not found: {trs_json_path}... | Python | 1 |
let mut utf8_buf = [0u8; 4];
// Bytes fill buffer from the front
c.encode_utf8(&mut utf8_buf);
// Slice disregards the unused portion of the buffer
utf8_buf[..c.len_utf8()].iter().for_each(|byte| {
// Conv... | Rust | 0 |
None,
} {
return Ok(ast::Expr {
span: span,
data: data,
});
}
// Try to parse a name-prefixed primary expression.
if let Some(expr) = try_name_or_qualified_primary_expr(p)? {
return Ok(expr);
}
// If we arrive here, nothing matched.... | Rust | 0 |
file.GetRootKey()
if root_key:
# For now treat AMCache.hve separately.
if root_key.name.lower() in self._AMCACHE_ROOT_KEY_NAMES:
self._ParseRecurseKeys(parser_mediator, root_key)
elif not parser_mediator.registry_find_specs:
self._ParseRecurseKeys(parser_mediator, root... | Python | 1 |
e, DND3CA_DESC, DND3CA_HELP, method_dnd3_2,
&["d&d", "dnd", "d20", "d&d3", "dnd3", "choice"]));
m.insert("dnd3randomavg", Method::new(
"d&d", true, DND3RA_DESC, DND3RA_HELP, method_dnd3_3,
&["d&d", "dnd", "d20", "d&d3", "dnd3", "ordered"]));
m.insert("dnd3highpow", Me... | Rust | 0 |
# Copyright © 2023 Huawei Technologies Co, Ltd. 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 appl... | Python | 1 |
#!/usr/bin/env python3
"""
智能依赖安装脚本
支持 uv 和 pip 两种方式
"""
import subprocess
import sys
import os
from pathlib import Path
def run_command(cmd, check=True):
"""运行命令并返回结果"""
try:
result = subprocess.run(cmd, shell=True, capture_output=True, text=True, check=check)
return result.returncode == 0, ... | Python | 1 |
except Exception as e:
print(f"Geometric consistency check failed: {e}")
return False
if __name__ == "__main__":
# Quick test
print("Testing φ-Geometric Layer...")
peak_data = get_cmb_phi_peaks(220.0)
print(f"Best series: {peak_data.series_name}")
print(f"ℓ₀ = {peak_data.l0}... | Python | 1 |
break;
}
p.pop();
}
//also look in subfolders
for entry in WalkDir::new(path)
.into_iter()
.filter_map(Result::ok)
.filter(|e| e.file_type().is_file())
.filter(|e| e.file_name() == ".ignore")
{
... | Rust | 0 |
tions=0.001,
logit_opacities=0.05,
log_scales=0.001,
cam_unnorm_rots=0.002,
cam_trans=0.005,
exp_a=0.001,
exp_b=0.001
),
loss_weights=dict(
im=1.0,
depth=1.0,
normal=1.0,
depth_dist=10... | Python | 1 |
"""Tests for the LED BLE Bluetooth integration."""
from homeassistant.components.bluetooth import BluetoothServiceInfoBleak
from tests.components.bluetooth import generate_advertisement_data, generate_ble_device
LED_BLE_DISCOVERY_INFO = BluetoothServiceInfoBleak(
name="Triones:F30200000152C",
address="AA:BB:... | Python | 1 |
cannot infer
//~^ ERROR: cannot infer
}
fn foo5(x: &int) -> &int {
//~^ NOTE: consider using an explicit lifetime parameter as shown: fn foo5<'a>(x: &'a int) -> &'a int
x //~ ERROR: mismatched types
//~^ ERROR: cannot infer
}
struct Bar<'x, 'y, 'z> { bar: &'y int, baz: int }
fn bar1(x: &Bar) -> (&int, &i... | Rust | 0 |
ine *
# b bb bbbb
avx_add = divide_loop(avx_add, "i", 8, ["ii", "lane"], perfect=True)
lane_loop = avx_add.find_loop("lane")
# TeX: end avx_add_full[1]
# TeX: begin avx_add_full[2]
# Cache 8-vectors of a and b, and used cached a_vec, b_vec within lane loop.
# This gives cursors ... | Python | 1 |
# Contains code from https://github.com/MagicStack/uvloop/tree/v0.16.0
# SPDX-License-Identifier: PSF-2.0 AND (MIT OR Apache-2.0)
# SPDX-FileCopyrightText: Copyright (c) 2015-2021 MagicStack Inc. http://magic.io
import enum
# After the connection is lost, log warnings after this many write()s.
LOG_THRESHOLD_FOR_CONN... | Python | 1 |
"""
Compute and plot the leading EOF of geopotential height on the 500 hPa
pressure surface over the European/Atlantic sector during winter time.
This example uses the plain numpy interface.
Additional requirements for this example:
* netCDF4 (http://unidata.github.io/netcdf4-python/)
* matplotlib (http://ma... | Python | 1 |
.len();
let y_size = heightmap[0].len();
let mut points: HashSet<(usize, usize)> = HashSet::new();
let mut sizes: Vec<usize> = Vec::new();
for i in 0..x_size {
for j in 0..y_size {
let result = compute_basin(i, j, heightmap, &mut points);
sizes.push(result);
}
... | Rust | 0 |
lines.append(f'@hide {prev_char_id}')
currently_in_choice_block = True
processed_any_choice_in_sheet = True
lines.append(f'@choice "{text}" goto:.{option_goto}') # New choice format
prev_char_id = None # Choices reset speaker context
continue
# I... | Python | 1 |
a
dz @ s d Z ddlmZ ddlmZmZm Z
mZm
Z ddlmZmZmZmZ ddlmZmZ ddlmZ ddlmZ m!Z" ddl#m$Z%m&Z' dd l(m(Z) dd
lZ*dd
l+Z+zddl,m-Z, W n e.y ddl/m-Z, Y n0 g dZ0d
ed ed Z1edZ2ded Z3dZ4de4 Z5G dd de+j6Z6G d... | Python | 1 |
"""
Calcula el crecimiento de una inversión durante un número determinado de años en base al capital
inicial, contribución anual, tipo de interés y número de años.
Tras solicitar los datos al usuario, la función calcula y muestra los resultados anuales del capital
inicial para ese año, beneficios obtenidos y capital o... | Python | 1 |
import random
from collections import Counter
from datasets import load_dataset
def balance_dataset_emo_class(
dataset,
column_name="emo_class",
target_count=2000,
seed=42
):
"""
对 dataset['train'] 中的 `column_name` 列进行上下采样,使每个类别样本数统一到 target_count。
- 对多数类(原数量>target_count)... | Python | 1 |
all(name="coalesce", args=[inner_expr, ast.Constant(value=0)])
return ast.Call(name="toFloat", args=[coalesce])
def _get_clicks_field(self) -> ast.Expr:
clicks_field = self.config.source_map.clicks
inner_expr: ast.Expr
if clicks_field is None:
inner_expr = ast.Constant(... | Python | 1 |
ame as vulnerable process)")
if writable_regions:
with open(mem_path, "rb") as mem:
for start_addr, end_addr in writable_regions[:3]: # Check first 3 regions
try:
mem.seek(start_addr)
region_size = min(end_... | Python | 1 |
h0_col, h1_col, mode=ctx.mode, dim=2)
s = y.shape
y = y.reshape([s[0], -1, 4, s[-2], s[-1]])
low = paddle.to_tensor(y[:, :, 0])
highs = paddle.to_tensor(y[:, :, 1:])
return low, highs
@staticmethod
def backward(ctx, low, highs):
dx = None
mode = ctx.mode
... | Python | 1 |
ield_string(
self, field.name, value, mask, indent, leading_zeros=leading_zeros
)
elif isinstance(field, ByteField):
if field.attribute == FIELD_ATTR.RESERVED:
continue
leading_zeros = (field.end - field.start + 1) * 2
... | Python | 1 |
import maya.cmds as cmds
def create_tornado_emitter():
# Create a sphere
sphere = cmds.polySphere(name='TornadoSphere')[0]
# Create a particle emitter
emitter = cmds.emitter(sphere, type='omni', rate=100, name='TornadoEmitter')[0]
particle = cmds.particle(name='TornadoParticles')[0]
# Connect... | Python | 1 |
s a query from the given query payload.
async fn get_query_from_payload(&self, qry: QueryData) -> Result<Box<dyn Query>> {
match qry.kind {
QueryKind::Fuzzy { ctx: query, cfg } => self.make_fuzzy_query(query, cfg),
QueryKind::Normal { ctx: query } => self.make_normal_query(query),
... | Rust | 0 |
NCEBTi12DBc93BEBXPk2DBv0ACEB2ju2DB
cJbvCEBhA62DB8yXCEBhA72DBFDlCEBam72DB
cdzCDEBQ1y2DB++1CEBhA52DBNT8CEBQ1y2DB
cJm6DEBR2m2DBl4VDEBQ1y2DB5lnDEBqGq2DB
c0iLEEB46s2DBp7AEEBpwl2DBcyFEEB/pq2DB
cb8fEEBtIq2DBWuREEBDXv2DBbcZEEBsHp2DB
cY6LGEBcSc3DBJ7EFEBY6v2DBNToFEBTiK3DB
cpbLHEBgVs4DBtokGEBbno3DBPK+G... | Rust | 0 |
&mut Predecessors, src: BlockId, dst: BlockId) {
predecessors.entry(dst).or_default().insert(src);
}
/// Compute the number of incoming control-flow edges to each block. If there are no
/// critical edges, this is also the number of predecessor blocks.
pub fn compute_num_predecessors(func: &Func<'_>, flags: Prede... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.