text string | label_name string | labels int64 |
|---|---|---|
.split(',')
errs = []
import traceback
from xml.sax.saxutils import escape
def handleError(name,fmt):
msg = 'Problem drawing %s fmt=%s file'%(name,fmt)
if shout or verbose>2: print(msg)
errs.append('<br/><h2 style="color:red">%s</h2>' % msg)
buf = StringIO()
trac... | Python | 1 |
KEN_EXPIRY)?;
}
}
#[cfg(not(target_os = "linux"))]
mod auth_token {
use crate::api::Api;
use anyhow::Error;
use secrecy::Secret;
#[fehler::throws]
#[tracing::instrument]
fn load() -> Secret<String> {
None
}
#[fehler::throws]
#[tracing::instrument]
fn store() {}
}
... | Rust | 0 |
"from_records avg time: {}\n",
time.elapsed().as_nanos() / TESTS_AMOUNT as u128
);
}
#[tokio::test]
#[ignore]
async fn benchmark_from_file() {
const RECORDS_AMOUNT: usize = 1_000_000;
const META_SIZE: usize = 1_000;
const TESTS_AMOUNT: usize = 1_000;
const KEY_MAPPER: fn(u32) -> u32 = |k| k... | Rust | 0 |
let cases = [
(func1, S3X_AMZ_COPY_SOURCE),
(func2, S3X_AMZ_SERVER_SIDE_ENCRYPTION),
(func3, S3X_AMZ_METADATA_DIRECTIVE),
(func4, S3_LOCATION_CONSTRAINT),
];
for (key, expected_result) in cases {
let result = key.key();
assert_... | Rust | 0 |
t': img_gt, 'key': key}
def __len__(self):
return len(self.keys)
@DATASET_REGISTRY.register()
class Vimeo90KRecurrentDataset(Vimeo90KDataset):
def __init__(self, opt):
super(Vimeo90KRecurrentDataset, self).__init__(opt)
self.flip_sequence = opt['flip_sequence']
self.neighbor... | Python | 1 |
rules.len() {
if tickets
.iter()
.all(|ticket| is_valid_value(&ticket.values[i], &rules[j]))
{
let matching_set = mapping.entry(rules[j].field_name.clone()).or_insert(HashSet::new());
matching_set.insert(i);
}
}
... | Rust | 0 |
[pivot * 3]]
}
#[derive(Clone, Copy, Debug)]
pub struct Estimate(pub f64, pub f64);
impl Estimate {
pub fn from_slice(values: &[f64]) -> Self {
let [mean, var] = mean_var(values);
Estimate(mean, var.sqrt())
}
}
impl slog::Value for Estimate {
fn serialize(
&self,
_rec: &s... | Rust | 0 |
self, start: Vec3, end: Vec3, duration: f32, color: Color) {
self.line_gradient(start, end, duration, color, color);
}
/// Draw a line in world space with a specified gradient color, or update an existing line
///
/// # Arguments
///
/// * `start` - The start of the line in world space
... | Rust | 0 |
"fSAMPLING = fDTS / 32, N = 5"] FDTSDIV32_N5,
#[doc = "fSAMPLING = fDTS / 32, N = 6"] FDTSDIV32_N6,
#[doc = "fSAMPLING = fDTS / 32, N = 8"] FDTSDIV32_N8,
}
impl IC4FW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline(always)]
pub fn _bits(&self) -> u8 {
match *self {
IC4FW::N... | Rust | 0 |
#references_column.to_string(),
))
})
} else {
quote!(None)
};
let primary_key = name == "id";
Ok(quote!(
awto::database::DatabaseColumn {
... | Rust | 0 |
"""
LangGraph工作流测试模块
"""
import pytest
from unittest.mock import Mock, patch
from src.workflows.langgraph_workflow import LangGraphWorkflow, GraphState
class TestLangGraphWorkflow:
"""LangGraph工作流测试"""
@patch('langchain_openai.ChatOpenAI')
def test_init(self, mock_llm):
"""测试工作流初始化"""
... | Python | 1 |
# process data from music parser here
import xml.etree.ElementTree as ET
from position_mapping.musicClasses import Note, Song
def XMLInterpret(fileName: str):
"""Parses MusicXML file into Song class containing objects of class Notes"""
tree = ET.parse(fileName)
score = tree.getroot()
songNotes = []
... | Python | 1 |
)(c4[nH]c5ccccc5c4CC3)c3cc4c(cc3OC)N(C)[C@@H]3[C@]44CCN5CC=C[C@](CC)([C@@H]45)[C@@H](OC(C)=O)[C@]3(O)C(=O)OC)[C@H]1O2",
"(-)-folicanthine": "[H][C@]12N(C)CC[C@]1(c1ccccc1N2C)[C@@]12CCN(C)[C@]1([H])N(C)c1ccccc21",
"fumiquinazoline A": "[H][C@]12N[C@@H](C)C(=O)N1c1ccccc1[C@@]2(O)C[C@@H]1C(=O)N[C@@H](C)c2n... | Python | 1 |
ock, bluez.OGF_HOST_CTL,
bluez.OCF_WRITE_INQUIRY_MODE, struct.pack("B", mode) )
pkt = sock.recv(255)
status = struct.unpack("xxxxxxB", pkt)[0]
# restore old filter
sock.setsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, old_filter )
if status != 0: return -1
return 0
def device_inquiry... | Python | 1 |
iptors.py --mp yes --mpParams
"inputDataMode,Lazy,numProcesses,4,chunkSize,8" -i Sample.smi
-o SampleOut.sdf
To compute all available 2D descriptors including Autocorr2D descriptor and
excluding fragment count descriptors, and write out a TSV file, type:
% RDKitCalculateMolecularD... | Python | 1 |
# COMP30024 Artificial Intelligence, Semester 1 2024
# Project Part A: Single Player Tetress
from .core import Coord, PlayerColor, BOARD_N
def apply_ansi(
text: str,
bold: bool = True,
color: str | None = None
):
"""
Wraps some text with ANSI control codes to apply terminal-based formatting.
... | Python | 1 |
for i in range(inH):
for k in range(inW):
if sx == -1:
px = (4 / 255.0) * inImage[rgb][i][k] * (255 - inImage[rgb][i][k])
outImage[rgb][i][k] = int(px)
else:
if (sx <= k < ex) an... | Python | 1 |
none() || stored == Some(IVec::from(NO_INCIDENT)) {
log::warn!("_NOTIFY_: found incident from Atom feed {}", self.feed_url);
self.notify(
alerts,
Notification {
from: "atom".to_owned(),
name: self.nam... | Rust | 0 |
VirtualMachineContext {
vm: vm,
msgqueue: RwLock::new(ArrayDeque::new()),
},
)
})
.collect(),
}
}
}
/// A set of physical hardware that may be attached to a VM... | Rust | 0 |
infos.is_some() {
Version::Multi
} else {
Version::TwoPrime
}
}
/// Encode this [`RsaPrivateKey`] as ASN.1 DER.
#[cfg(feature = "alloc")]
#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
pub fn to_der(&self) -> Result<RsaPrivateKeyDocument> {
self.try... | Rust | 0 |
..],
})
);
assert_eq!(
string(&[0, 0, 0, 4, 1, 2, 3, 4]),
Ok(ParsedValue {
value: &[1, 2, 3, 4][..],
rest_input: &[],
})
);
assert_eq!(
string(&[0, 0, 0, 0, 1, 2, 3, 4]),
Ok(ParsedValu... | Rust | 0 |
:<BlockInfo>,
// block
pub fs_size: i32,
}
impl Filesystem for HelloFS {
fn lookup(&mut self, _req: &Request, _parent: u64, name: &OsStr, reply: ReplyEntry) {
println!("[D] -- lookup --");
let node_idx = self.nid_get_from_name(name);
if node_idx != INVALID_INO {
reply.en... | Rust | 0 |
)
@html_translator_mixin.override
def depart_desc_inline(
self: html_translator_mixin.HTMLTranslatorMixin,
node: sphinx.addnodes.desc_inline,
super_func: html_translator_mixin.BaseVisitCallback[sphinx.addnodes.desc_inline],
) -> None:
self.body.append("</code>")
if sphinx.version_info < (8, 2):
... | Python | 1 |
############################################################
# Gathering values in ``TensorDict``
# ----------------------------------
# The :meth:`TensorDict.gather <tensordict.TensorDict.gather>` method can be used to
# index along the batch dimensions and gather the results into a single dimension much
# like :func:... | Python | 1 |
#[doc = "Bit 6 - VBUS Gate"]
#[inline]
pub fn vbgate(&mut self) -> _VBGATEW {
_VBGATEW { w: self }
}
#[doc = "Bit 9 - FIFO Mode"]
#[inline]
pub fn fifo_mode(&mut self) -> _FIFO_MODEW {
_FIFO_MODEW { w: self }
}
}
use crate::cipher_mode::{ECB, EmptyPadding, EncryptStream, ... | Rust | 0 |
for DIO_BB_RX_SRC {}
#[doc = "Baseband Controller RX Data And Clock Input Selection"]
pub mod dio_bb_rx_src;
#[doc = "Baseband Controller SPI Input Selection\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](cr... | Rust | 0 |
ctxtS_WERKS-LOW").text = "{store}"
session.findById("wnd[0]/usr/ctxtS_DATUM-LOW").text = "{start_date}"
session.findById("wnd[0]/usr/ctxtS_DATUM-HIGH").text = "{end_date}"
session.findById("wnd[0]/tbar[1]/btn[8]").press 'execution f9
session.findById("wnd[0]/tbar[1]/btn[26]").press 'normal view
... | Python | 1 |
class Solution:
def repeatedNTimes(self, nums: List[int]) -> int:
for i in range(len(nums) - 2):
if nums[i] == nums[i + 1] or nums[i] == nums[i + 2]:
return nums[i]
return nums[-1]
| Python | 1 |
)r r rG r= r rK s r) __repr__zIncompleteRead.__repr__ sK ==$$t}}4AA$(?(?(+DLL(91(> > >r6 r )rG rH rI ru r r" __str__rJ r6 r) r r s !> nnGr6 r c e Zd Zy)r
Nr rJ r6 r) r
r
r r6 ... | Python | 1 |
のワルツネぞなぞ小さな楽しみ遊びま.longboi",
..Default::default()
},
],
..Default::default()
},
]
}
#[test]
fn detect_encodings() {
color_backtrace::install();
for case in test_cases() {
if let Some(... | Rust | 0 |
value = reask_response_dict.get(key)
update_response_by_path(merged_json, value.path, corrected_value)
else:
update_reasked_elements(
pruned_reask_json[key], reask_response_dict[key]
)
elif isinstance(pruned_reas... | Python | 1 |
from views import Gtk
class SearchPage(Gtk.Box):
def __init__(self, controller):
super().__init__(orientation=Gtk.Orientation.VERTICAL, spacing=10)
label = Gtk.Label(label="Menu de Inserção")
customer_button = Gtk.Button(label = "Buscar Cliente")
customer_button.connect("clicked", l... | Python | 1 |
stage.stage_id)?;
let mut id = AtomicUsize::new(0);
build_exec_plan_diagram(&mut w, stage.child.as_ref(), stage.stage_id, &mut id, true)?;
writeln!(w, "\t}}")?;
}
// draw relationships
for stage in stages {
let mut id = AtomicUsize::new(0);
build_exec_plan_diagram(&... | Rust | 0 |
2).max(m3)
})
.map(float_ord::FloatOrd)
.max()
.map(|x| x.0)
.unwrap_or(0.0)
}
fn load_animations<E: std::error::Error + 'static>(
animations: gltf::iter::Animations,
buffers: &[Vec<u8>],
) -> Result<Vec<Labeled<Animation>>, GltfLoadError<E>> {
let mut result = Vec::... | Rust | 0 |
] [INFO] alloc_kernel_memory({:#x})", arg1),
0x01 => println!("[BIOS] [INFO] free_kernel_memory({:#x})", arg1),
0x07 => println!("[BIOS] [INFO] DeliverEvent({:#x}, {:#x})", arg1, arg2),
0x08 => println!("[BIOS] [INFO] OpenEvent({:#x}, {:#x}, {:#x}, {:#x})", arg1, arg2, arg3, arg4),
... | Rust | 0 |
sg for MsgChannelOpenInit {
type ValidationError = Error;
fn route(&self) -> String {
crate::keys::ROUTER_KEY.to_string()
}
fn get_type(&self) -> String {
TYPE_MSG_CHANNEL_OPEN_INIT.to_string()
}
fn validate_basic(&self) -> Result<(), Self::ValidationError> {
self.chan... | Rust | 0 |
import os
import multiprocessing
import zmq
import zmq.asyncio
from communication.zeromq import ContextManager, reset_context_after_fork
def test_set_io_threads():
"""测试设置 I/O 线程数量"""
num = 2
ContextManager.set_io_threads(num)
assert ContextManager._io_threads ==num
def test_get_context_main_process... | Python | 1 |
replay_buffer,
cfg.overrides.batch_size,
0, # no validation data
cfg.overrides.sequence_length,
max_batches_per_loop_train=cfg.overrides.num_grad_updates,
use_simple_sampler=True,
)
trainer.train(
dataset, num_epochs=1... | Python | 1 |
kick it, CC";
let cleartext_len = cleartext.len();
assert!(cleartext_len <= k - 11);
let mut padded_cleartext = vec![2u8];
let mut rng = rand::thread_rng();
padded_cleartext.extend((0..(k - 3 - cleartext_len)).map(|_| rng.gen_range(1, 256) as u8));
padded_cleartext.push(0... | Rust | 0 |
(key, val),
}
}
}
#[test]
fn sequential_test_mut_order() {
let nlogs = NLOGS;
let mut logs = Vec::with_capacity(nlogs);
// Allocate the logs.
for i in 0..nlogs {
let log = Arc::new(Log::<<CNRHashmap as Dispatch>::WriteOperation>::new(
4 * 1024 * 1024,
i + 1,... | Rust | 0 |
provided.
Returns
-------
An ``Instance`` containing the following fields:
raw_tokens : ListField[MetadataField]
The raw str tokens in the sequence. Each MetadataField stores the raw string
of a single token.
arc_indices : ``SequenceArra... | Python | 1 |
ARTITION_SIZE), head_dim],
# Mid_O_LogExpSum: [batchs, num_heads, cdiv(seq_len, PARTITION_SIZE)]
"""
BLOCK_N_SIZE = 16
# BLOCK_DMODEL = q.shape[-1]
assert PARTITION_SIZE % BLOCK_N_SIZE == 0, (
"PARTITION_SIZE 必须是 BLOCK_N_SIZE 的倍数"
)
batchs, num_heads, head_dim = (
q.shape
... | Python | 1 |
, e);
}
}
})
.flat_map(|mut line| {
line.push_str("\n"); // BufRead::lines unfortunately strips \n and \r\n
line.into_chars()
});
// Initialize our token lexer and shell parser with the program's input
let lex = Lexer::new(stdin);
... | Rust | 0 |
medias = []
classifica = []
times = [
(['Jeff'],[10, 12]),
(['Rodr'], [9, 9]),
(['Ferr'], [11, 8]),
(['Leoo'], [13, 10])
]
for i, j in times:
media = sum(j) / len(j)
medias.append((j, media))
medias = sorted(medias)
for i in medias:
if i in medias:
continue
classifica.append(i)
print(times[2][1]... | Python | 1 |
Ref<'a, 'schema> {
pub(crate) fn constrained_columns<'b>(&'b self) -> impl Iterator<Item = ColumnRef<'a>> + 'b {
self.table()
.columns()
.filter(move |column| self.foreign_key.columns.contains(&column.column.name))
}
pub(crate) fn constraint_name(&self) -> Option<&'a str> {
... | Rust | 0 |
() {
title = vbscmt.title().map(|v| v.join(" "));
artist = vbscmt.artist().map(|v| v.join(" "));
album = vbscmt.album().map(|v| v.join(" "));
duration = get_duration(&path).ok();
}
}
MP3 => {
... | Rust | 0 |
ariable (e.g. for skip connections to input)
if self.pass_as_var:
setattr(batch, f'pe_{self.kernel_type}', pos_enc)
return batch
@register_node_encoder('RWSE')
class RWSENodeEncoder(KernelPENodeEncoder):
"""Random Walk Structural Encoding node encoder.
"""
kernel_type = 'RWSE'
... | Python | 1 |
ort.append("-" * 20)
for keyword, count in stats['common_issues']:
report.append(f" - {keyword}: {count} 次提及")
report.append("")
# 最新反饋摘要
report.append("💬 最新反饋摘要")
report.append("-" * 20)
rece... | Python | 1 |
't ProgressBars
/// attached, so we add a hidden/bogus one
/// - the hidden/bogus ProgressBar needs to be cleaned up (by Drop, in this
/// implementation) when we don't need to update progress bars anymore
pub struct MultiProgressGuard {
/// Pointer to the multi-progress bar, cloned internally and passed to a
/... | Rust | 0 |
unsafe impl<TInput, TCollected> Sync for InBlockInfo<TInput, TCollected> {}
use std::mem;
use std::ptr;
use winapi::um::winuser::*;
pub fn message_loop() {
unsafe {
let mut msg: MSG = mem::zeroed();
while GetMessageW(&mut msg, ptr::null_mut(), 0, 0) > 0 {
DispatchMessageW(&msg);
... | Rust | 0 |
('bar', None, 'pass'))
os.chmod(fn, 0o622)
self.assertRaises(netrc.NetrcParseError, netrc.netrc)
def test_file_not_found_in_home(self):
d = support.TESTFN
os.mkdir(d)
self.addCleanup(support.rmtree, d)
with support.EnvironmentVarGuard() as enviro... | Python | 1 |
import re
from scrubadub.detectors.catalogue import register_detector
from .base import RegexDetector
from ..filth import UrlFilth
@register_detector
class UrlDetector(RegexDetector):
"""Use regular expressions to remove URLs that begin with ``http://``,
``https://`` or ``www.`` from dirty dirty ``text``.
... | Python | 1 |
rt_instr(vgatherqps, scale = 1))]
#[rustc_args_required_const(4)]
pub unsafe fn _mm512_mask_i64gather_ps(
src: __m256,
mask: __mmask8,
offsets: __m512i,
slice: *const u8,
scale: i32,
) -> __m256 {
let src = src.as_f32x8();
let slice = slice as *const i8;
let offsets = offsets.as_i64x8();... | Rust | 0 |
Ok(msg) = result {
let s = String::from_utf8(msg.data.clone()).unwrap();
log::debug!("server:receive: msg = {:?}", s);
sever_clone.send(msg).await;
}
tokio::time::sleep(Duration::from_millis(300)).await;
}
});
tokio::spawn(async move {
loop {
le... | Rust | 0 |
from __future__ import annotations
from typing import Final
import win32api
import win32event
from ._base import BaseMutex, BaseSemaphore
__all__ = ["AccessRight", "Semaphore"]
class AccessRight:
DELETE: Final = 0x00010000
READ_CONTROL: Final = 0x00020000
SYNCHRONIZE: Final = 0x00100000
WRITE_DAC:... | Python | 1 |
cx)
}
fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
Pin::new(&mut self.inner).poll_shutdown(cx)
}
}
impl<S> PeekableStream<S> {
pub fn new(inner: S) -> Self {
PeekableStream {
inner,
buf: VecDeque::new(),
}
... | Rust | 0 |
[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl R {
#[doc = "Bits 0:31"]
#[inline(always)]
pub fn se_trng_0_test_out_1(&self) -> SE_TRNG_0_TEST_OUT_1_R {
SE_TRNG_0_TEST_OUT_1_R::new((self.bits & 0xffff_ffff) as u32)
}
}
#[doc = "se_trng_0_test_out_1.\n\nThis ... | Rust | 0 |
to be saved to.
:return:
"""
state_dict = self.state_dict()
with open(checkpoint_file, "wb") as f:
pickle.dump(state_dict, f)
def restore(self, checkpoint_file, **config):
"""
restore model from file
:param checkpoint_file: the model file
... | Python | 1 |
import logging
import pandas as pd
from src.outlier_detection import OutlierDetector,ZcSoreOutlierDetection,IQROutlierDetection
from zenml import step
@step
def outlier_detection_step(df:pd.DataFrame,column_name:list[str])->pd.DataFrame:
logging.info(f"Starting outlier deteection step with data.")
if df is Non... | Python | 1 |
od tests {
use super::*;
#[test]
fn test_124() {
assert_eq!(Solution::max_path_sum(tree![1, 2, 3]), 6);
assert_eq!(
Solution::max_path_sum(tree![-10, 9, 20, null, null, 15, 7]),
42
);
assert_eq!(
Solution::max_path_sum(tree![5, 4, 8, 11, n... | Rust | 0 |
from transformers import GenerationConfig
from transformers import LlamaTokenizer, LlamaForCausalLM
import torch
import os
from tqdm import tqdm
import argparse
from peft import PeftModel
import json
def parse_args():
parser = argparse.ArgumentParser(description="Test Llama model")
parser.add_argument('--mode... | Python | 1 |
gs};
#[derive(Parser, Debug)]
#[clap(author, version, about, long_about = None)]
pub struct CliArgs {
/// Path to one or multiple files or directories of files to analyze
path: Vec<String>,
/// Normalize casing by lowercasing each occuring word
#[clap(short, long)]
lowercase: bool,
/// Number o... | Rust | 0 |
crop_region=cropped_region,
bbox=single_bbox_loc,
label=single_bbox.label if isinstance(single_bbox, BBOX_imagutils) else None,
control_net_wrapper=None
)
SEG_list.append(seg... | Python | 1 |
])", index, begin, block.len()),
_ => write!(f, "{:?}", self),
}
}
}
extern crate wasm_bindgen;
extern crate web_sys;
use engine::canvas_board::CanvasBoardRenderer;
use engine::canvas_board::piece_at;
use engine::piece::Color;
use engine::piece::Piece;
use engine::piece::PieceType;
use engine::... | Rust | 0 |
from typing import List, Tuple
from pyrep.objects.shape import Shape
from pyrep.objects.dummy import Dummy
from pyrep.objects.proximity_sensor import ProximitySensor
from rlbench.backend.task import Task
from rlbench.backend.conditions import DetectedCondition, NothingGrasped
from rlbench.backend.spawn_boundary import ... | Python | 1 |
import logging
logger = logging.getLogger(__name__)
class LineTracer:
"""代码行追踪器"""
def __init__(self, lines, blockly_workspace):
"""初始化追踪器
Args:
lines: 代码行列表
blockly_workspace: Blockly工作区实例
"""
self.lines = lines
self.blockly = bloc... | Python | 1 |
ion': [random.randint(3, 10)]},
'A086345': {'valuesTestValidation': [random.randint(3, 10), random.randint(11, 20), random.randint(21, 30), random.randint(31, 40)]},
'A178961': {'valuesTestValidation': [random.randint(3, 11)]},
'A223094': {'valuesTestValidation': [random.randint(3, 11)]},
'A259702': {'valuesTestVal... | Python | 1 |
(&self) -> (i32, i32) {
let w: c_int = 0;
let h: c_int = 0;
unsafe { ll::SDL_GetWindowSize(self.raw, &w, &h) };
(w as i32, h as i32)
}
pub fn get_drawable_size(&self) -> (i32, i32) {
let w: c_int = 0;
let h: c_int = 0;
unsafe { ll::SDL_GL_GetDrawableSize(... | Rust | 0 |
rbar has x/y errors.
"""
def __init__(self, lines, has_xerr=False, has_yerr=False, **kwargs):
self.lines = lines
self.has_xerr = has_xerr
self.has_yerr = has_yerr
super().__init__(lines, **kwargs)
class StemContainer(Container):
"""
Container for the artists created i... | Python | 1 |
import uvicorn
from fastapi import FastAPI
from starlette.middleware.cors import CORSMiddleware
from api.v1.router import api_router as organizations_service_router
app = FastAPI(
title="OrganizationService",
openapi_url="/organization_service/openapi.json",
docs_url="/organization_service/docs",
)
app.a... | Python | 1 |
#Write a function that takes in a string and character, replaces blank spaces in the string with the character, and returns the string.
def replace_blank(str1,char):
str2 = str1.replace(' ', char)
return str2 | Python | 1 |
String::from_utf8_lossy(&make_output.stdout),
String::from_utf8_lossy(&make_output.stderr));
}
// Copy libraries to output directory
let out_dir = env!("OUT_DIR");
fs::copy(&"./src/corange/libcorange.a", &Path::new(out_dir).join("libcorange.a"))
.ok()
.expect("Failed to move... | Rust | 0 |
o,
'nivel_confianca': nivel_confianca,
'odd': odd,
'valor_apostado': valor
}
except Exception as e:
return {'erro': f'Erro na previsão: {str(e)}'}
# Instância global do gestor ML
gestor_ml = GestorML()
# Carregar modelos salv... | Python | 1 |
# Description: This script creates a bar chart with multiple bars for each label.
import matplotlib.pyplot as plt
# Data
labels = ['A', 'B', 'C', 'D']
# Data for the first bar chart
values1 = [10, 20, 30, 40]
# Data for the second bar chart
values2 = [20, 30, 40, 50]
# Data for the third bar chart
values3 = [30, 40... | Python | 1 |
display adjacent to the annotation.
label: Option<String>,
}
#[derive(Debug)]
pub struct RenderedLine {
pub text: Vec<StyledString>,
pub kind: RenderedLineKind,
}
#[derive(Debug)]
pub struct StyledString {
pub text: String,
pub style: Style,
}
#[derive(Debug)]
pub struct StyledBuffer {
text:... | Rust | 0 |
import math
N = int(input())
L = []
for _ in range(N):
num = int(input())
L.append(num)
L.sort()
if N % 2 == 0:
i = N // 2
print(math.ceil((L[i-1] + L[i]) / 2))
else:
i = N // 2
print(round(L[i])) | Python | 1 |
slice: gfx::Slice<back::Resources>,
vertices: h::Buffer<back::Resources, Vertex>,
material: Material,
list: Vec<Instance>,
}
#[derive(Clone, Debug)]
pub(crate) struct DynamicData {
pub num_vertices: usize,
pub buffer: h::Buffer<back::Resources, Vertex>,
}
/// Shadow type is used to specify sh... | Rust | 0 |
UnsignedShort = 0x1403,
UnsignedInt = 0x1405,
}
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum ClearMode {
Color = 0x4000,
Depth = 0x0100,
ColorAndDepth = 0x0100 | 0x4000,
}
#[inline]
fn check_error() -> Result<(), String> {
let err_code = unsafe { gl::GetError() };
let err_type = Erro... | Rust | 0 |
"""Copyright 2022 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, software
dist... | Python | 1 |
for src in &srcs {
let (properties, styles) =
if let Some(ContentConfigure { properties, styles, .. }) = self.data.cfg.config(src.as_ref()) {
let properties = properties.iter().map(|p| p.clone()).collect::<Vec<Properties>>();
let styles = styles.i... | Rust | 0 |
import torch
import torch.nn as nn
import torchvision.models as models
from torch.autograd import Variable
import torch.nn.functional as F
class resnet_mil(nn.Module):
def __init__(self, opt):
super(resnet_mil, self).__init__()
import model.resnet as resnet
resnet = resnet.resnet101()
... | Python | 1 |
EVP_DIGESTFINAL_XOF": (
cryptography_has_evp_digestfinal_xof
),
"Cryptography_HAS_ENGINE": cryptography_has_engine,
"Cryptography_HAS_VERIFIED_CHAIN": cryptography_has_verified_chain,
"Cryptography_HAS_SRTP": cryptography_has_srtp,
"Cryptography_HAS_GET_PROTO_VERSION": cryptography_has_get_p... | Python | 1 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Licensed under the GNU General Public License, version 3.
# See the file http://www.gnu.org/licenses/gpl.txt
from pisi.actionsapi import autotools
from pisi.actionsapi import pisitools
from pisi.actionsapi import shelltools
from pisi.actionsapi import get
def build():
... | Python | 1 |
model_dir = "/basic"
model_name = "basic_main.py"
#版本信息
basicver , basicupdatedate = 1.0 , 20250807
import time,machine
def reboot_system(hmi):
print("<basic> 信息 系统重启")
hmi.tx("page api_wait")
hmi.tx('title.txt="重启"')
time.sleep(0.1)
hmi.tx('info.txt="正在重启系统,请稍后"')
machine.reset()
def main(hmi... | Python | 1 |
import os
import hashlib
from app import app, db
from models import Archivo
def calcular_hash(ruta_archivo):
hasher = hashlib.sha256()
with open(ruta_archivo, 'rb') as f:
for bloque in iter(lambda: f.read(8192), b''):
hasher.update(bloque)
return hasher.hexdigest()
with app.app_context... | Python | 1 |
async fn reports_worst_accuracy_if_accuracy_is_unknown() {
let (cobalt_sender, cobalt_receiver) = make_fake_cobalt_connection();
let (proxy, stream) = create_proxy_and_stream::<EmergencyProviderMarker>()
.expect("internal error: failed to create emergency provider");
... | Rust | 0 |
for TPM2B_ATTEST {
fn default() -> Self { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct TPMS_AUTH_COMMAND {
pub sessionHandle: TPMI_SH_AUTH_SESSION,
pub nonce: TPM2B_NONCE,
pub sessionAttributes: TPMA_SESSION,
pub hmac: TPM2B_AUTH,
}
#[test]
fn bindgen_test_layout_TPMS_A... | Rust | 0 |
stats['tokencount'] for x in testcurve[:take]]
traincurve = [trainstats['initialerrors']]
for rulescore in trainstats['rulescores']:
traincurve.append(traincurve[-1] - rulescore)
traincurve = [1 - x/trainstats['tokencount'] for x in traincurve[:take]]
import matplotlib.pyplot as plt
r = list(ran... | Python | 1 |
utes"]
pub mod tcd10_attr;
#[doc = "TCD Minor Byte Count (Minor Loop Mapping Disabled)\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::mo... | Rust | 0 |
control over what packages we require.
'''
ret = list()
ret.append('setuptools')
if openbsd():
#print(f'OpenBSD: libclang not available via pip; assuming `pkg_add py3-llvm`.')
pass
elif macos() and platform.machine() == 'arm64':
#print(
# f'MacOS/arm64: forcing ... | Python | 1 |
"""This test checks for correct wait3() behavior.
"""
import os
import time
import unittest
from test.fork_wait import ForkWait
from test.test_support import run_unittest, reap_children
try:
os.fork
except AttributeError:
raise unittest.SkipTest, "os.fork not defined -- skipping test_wait3"
try:
os.wait3... | Python | 1 |
l Response
Examples
--------
import asyncio
from mirascope import AsyncLilypad
client = AsyncLilypad(
api_key="YOUR_API_KEY",
token="YOUR_TOKEN",
base_url="https://yourhost.com/path/to/api",
)
async def main() -> None:
... | Python | 1 |
result.write(message.as_slice())?;
}
Ok(result)
}
fn validate_mac(&self, msg: &SrpMessage) -> Result<(), SrpErr> {
if msg.has_mac() {
let mut hmac = Hmac::<Sha256>::new_varkey(&self.priv_key)?;
hmac.input(&self.get_mac_data()
.map_er... | Rust | 0 |
pub(crate) fn parse_input(
input: TokenStream,
) -> Result<(Vec<Attribute>, Vec<TokenTree>, TokenTree)> {
let mut input = input.into_iter().peekable();
let mut attrs = Vec::new();
while let Some(attr) = parse_next_attr(&mut input)? {
attrs.push(attr);
}
let sig = parse_signature(&mut i... | Rust | 0 |
This is safe, because AsUninit is marked #[repr(transparent)], and is thus
// guaranteed to follow the exact same layout and ABI as the type T.
unsafe { crate::cast_slice_same_layout::<Self, T>(selves) }
}
}
impl<'a, T> ioslice::CastSliceMut<'a, T> for crate::wrappers::AsUninit<T> {
fn cast_sli... | Rust | 0 |
import torch
from tqdm import trange
def bayes_error_grad_torch(X, y, sigma, num_classes, chunk_size=512):
N, D = X.shape
sigma_sq = sigma ** 2
grads = torch.zeros_like(X)
for start in trange(0, N, chunk_size):
end = min(start + chunk_size, N)
X_chunk = X[start:end] # [B, D]
... | Python | 1 |
stop_limit_sell_order() {
let mock_stop_limit_sell_order = mock("POST", "/api/v3/order")
.with_header("content-type", "application/json;charset=UTF-8")
.match_query(Matcher::Regex("price=0.1&quantity=1&recvWindow=1234&side=SELL&stopPrice=0.09&symbol=LTCBTC&timeInForce=GTC×tamp... | Rust | 0 |
(&var)?;
}
Syntax::Var(var) => {
let serched = self.serch_var(var.get_name());
match serched.1? {
Some(serch_type) => {
if &serch_type != types {
return Err(result::Error::InterpreterError(format!(
"function {} argment {} th miss matched t... | Rust | 0 |
0:-1, 1]
# r1 = vertices[1: , 1]
# td = np.where(t1 > t0, t1 - t0, twopi - (t0 - t1))
# td_scaled = td / (np.pi * 0.5)
# rd = r1 - r0
# r0kappa = r0 * kappa * td_scaled
# r1kappa = r1 * kappa * td_scaled
# ravg_kappa = ((r1 + r0) / 2.... | Python | 1 |
lse gen_ops_library()
)
filtered_instances = list(
filter(lambda op: self.filter_op(op), unfiltered_instances)
)
# NB: when using a fixed list order, most likely we will pick the subset of instances
# which are very similar to each other. Randomizing the choice seems ... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.