text string | label_name string | labels int64 |
|---|---|---|
21),
isizex8::new(0, 3, 7, 10, 14, 17, 21, 24),
isizex8::new(0, 4, 8, 12, 16, 20, 24, 28),
];
// Bitmask for ANDing during SIMD unpacking
const U32_SIMD_ANDMASK: [u32x8; 9] = [
u32x8::splat(0x0f),
// 1 nibble
u32x8::splat(0x0f),
// 2 nibbles, etc.
u32x8::splat(0x0ff),
u32x8::splat(0x0f... | Rust | 0 |
from django.urls import include, path
from rest_framework.routers import DefaultRouter
from .views import GroupView, ModeratorView
router = DefaultRouter()
router.register("group", GroupView, basename="group")
router.register("moderator", ModeratorView, basename="moderator")
urlpatterns = [
path("", include(rout... | Python | 1 |
# Copyright ServiceNow, Inc. 2021 – 2022
# This source code is licensed under the Apache 2.0 license found in the LICENSE file
# in the root directory of this source tree.
from azimuth.modules.perturbation_testing import (
PerturbationTestingMergedModule,
PerturbationTestingModule,
PerturbationTestingSumma... | Python | 1 |
uctCode(), false, 0, 0)
}
}
pub fn PL_30_68C_HI_48S_Config(&self) -> String {
unsafe {
let GetP = (*self).getP;
if !self._Init_Is_Japan() {
self._getHostNum((*GetP)("P_30_68C_HI_48S"), mw007312_def::_Code_30_68C_HI_48S(), self._productCode(), false, 0, 0)... | Rust | 0 |
e into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(
master_doc,
"CircuitPython_Button_Handler_Library.tex",
"CircuitPython Button_Handler Library Documentation",
author,
"m... | Python | 1 |
import pytest
from laia.data.transforms.text import ToTensor, tokenize, untokenize
from laia.utils import SymbolsTable
@pytest.mark.parametrize(
"sentence,tokenization,space_token,space_display",
[
(
"salut à toi l'endimanché",
"s a l u t <space> à <space> t o i <space> l ' e ... | Python | 1 |
pend(create_completion(
option,
start_position=-len(partial) if partial else 0,
display_meta=arg_info.help or ""
))
return completions
def _complete_option_value(self, option_info: ArgumentInfo, context: CompleterConte... | Python | 1 |
try :
import requests
import time
import os
from art import *
from colorama import Fore
from time import sleep
import json
import random
from tabulate import tabulate
import sys
import requests
from random_user_agent.user_agent import UserAgent
from random_user_agen... | Python | 1 |
ments
.into_iter()
.map(|a| {
let media_type = match a.media_type {
elefren::entities::attachment::MediaType::Image => MediaType::Image,
elefren::entities::attachment::MediaType::Video => MediaType::Video,
elefren::entit... | Rust | 0 |
ngs[:n, 1], umap_embeddings[:n, 2], c="r", label="Image")
ax.scatter(umap_embeddings[n:, 0], umap_embeddings[n:, 1], umap_embeddings[n:, 2], c="b", label="Text")
plt.legend()
if save_path:
# We are saving the 3D plot as a gif, rotating the plot 360 degrees
images = []
... | Python | 1 |
gs[0], embeddings[1])
assert isinstance(similarity_score, np.float32)
assert -1.0 <= similarity_score <= 1.0
def test_dimension_property(embedding_model: CohereEmbeddings) -> None:
"""Test dimension property."""
assert isinstance(embedding_model.dimension, int)
assert embedding_model.dimension > 0... | Python | 1 |
(ref bytes) | Parms(ref bytes) | Config(ref bytes) | Stats(ref bytes)=> bytes.len(),
// strings: +1 because we need to append a nul byte
Name(ref s) => s.len() + 1,
Threshold1(_) | Threshold2(_) | Threshold3(_) => 4,
GcInterval(_) => 8,
Other(ref attr) => attr... | Rust | 0 |
from typing import Dict, List, ClassVar
from llama_index.core.instrumentation.events import BaseEvent
from llama_index.core.instrumentation.event_handlers import BaseEventHandler
from llama_index.core.instrumentation import get_dispatcher
from llama_index.core.instrumentation.events.llm import LLMCompletionEndEvent
c... | Python | 1 |
from enum import Enum
from typing import Dict, Any, Optional
from dataclasses import dataclass
class ResourceType(Enum):
"""Enum representing different types of cloud resources."""
COMPUTE = "compute"
STORAGE = "storage"
NETWORK = "network"
DATABASE = "database"
SECURITY = "security"
MONITO... | Python | 1 |
Result<post::Post> {
let response = self
.client
.get(format!("{}/teams/{}/posts/{}", BASE_URL, self.team.id, id))
.bearer_auth(self.team.access_token.to_string())
.send()
.await?;
if response.status().is_success() {
let post = re... | Rust | 0 |
uler
//! This library implements several solvers for `P || C_max` task scheduling problem.
//!
//! `P || C_max` is a `a|b|c` notation used in *operations research* where
//! 1. `P` stands for **parallel identical resources**
//! 2. `||` denotes that there are no task constraints, notably that **tasks are non-preemp... | Rust | 0 |
import datetime
import unittest
from borb.pdf import HexColor
from borb.pdf.document import Document
from borb.pdf.layout_element.calendar.day_view import DayView
from borb.pdf.page import Page
from borb.pdf.visitor.pdf import PDF
class TestDayView(unittest.TestCase):
def test_day_view(self):
d: Documen... | Python | 1 |
ficha = list()
while True:
nome = str(input("Nome: "))
nota1 = float(input("Nota 1: "))
nota2 = float(input("Nota 2: "))
media = (nota1 + nota2) / 2
ficha.append(nome, [nota1, nota2], media)
resp = str(input("Quer continuar? [S/N] "))
if resp in "Nn":
break
print("-="*15)
print(f"{"N... | Python | 1 |
eq!(podcast.last_checked, p.last_checked);
assert_eq!(podcast.image_url, p.image_url);
assert_eq!(podcast.cache_key, p.cache_key);
Ok(())
}
#[async_std::test]
async fn test_delete_podcast() -> Result<()> {
let d = Database::new(Connection::Memory).await?;
let p = d.... | Rust | 0 |
print("Welcome to the rollercoaster!")
height = int(input("What is your height in cm? "))
bill = 0
if height >= 120:
print("You can ride the rollercoaster")
age = int(input("What is your age?"))
if age < 12:
bill = 5
print("Child tickets are $5.")
elif age <= 18:
bill = 7
print("Yout tickets ar... | Python | 1 |
f"tx_receipt: {tx_receipt['blockHash']!r}."
)
elif allow_missing_data is False:
raise EthPMValidationError(
"No block hash found in deployment data. "
"Unable to verify block hash on tx receipt. "
"I... | Python | 1 |
gister the Formlabs 3D Printers at [https://formlabs.com/dashboard/#setup](https://formlabs.com/dashboard/#setup). This involves connecting a Formlabs 3D Printer to the Internet and then visiting the Dashboard Registration screen on the Printer to get a registration code. Type this registration code on the Dashboard Pr... | Python | 1 |
>,
Q: Hash + Eq
{
let mut hasher = self.hasher().build_hasher();
value.hash(&mut hasher);
let hash = hasher.finish();
let entry = self.raw_entry_mut().from_key_hashed_nocheck(hash, &value);
match entry {
RawEntryMut::Occupied(e) => *e.key(),
... | Rust | 0 |
}
#[cfg_attr(any(test, feature = "debug_ctap"), derive(Debug, PartialEq))]
pub struct PublicKeyCredentialUserEntity {
pub user_id: Vec<u8>,
pub user_name: Option<String>,
pub user_display_name: Option<String>,
pub user_icon: Option<String>,
}
impl TryFrom<&cbor::Value> for PublicKeyCredentialUserEnti... | Rust | 0 |
nter, bbox_size, dir_angle], dim=-1)
return bbox3d
def split_pred(self, cls_preds, reg_preds, base_xyz, prefix=''):
"""Split predicted features to specific parts.
Args:
cls_preds (torch.Tensor): Class predicted features to split.
reg_preds (torch.Tensor): Regression... | Python | 1 |
SerdeJSONError(err) => Display::fmt(err, f),
}
}
}
impl Error for JSONGetTextBuildError {}
impl From<io::Error> for JSONGetTextBuildError {
#[inline]
fn from(v: io::Error) -> JSONGetTextBuildError {
JSONGetTextBuildError::IOError(v)
}
}
impl From<JSONError> for JSONGetTextBuildError {... | Rust | 0 |
import os
from dotenv import load_dotenv
from langchain_google_genai import ChatGoogleGenerativeAI
from langchain_groq import ChatGroq
load_dotenv()
def get_llm(model_choice: str):
"""Get LLM based on model choice."""
if model_choice == "gemini":
return ChatGoogleGenerativeAI(
model="gemin... | Python | 1 |
path.write_text(old_content)
return {"output": "Last edit undone successfully"}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.post("/bash")
async def handle_bash(request: BashRequest):
try:
if request.restart:
# Kill existing b... | Python | 1 |
t_filesign;
use frame_support::sp_runtime::{
testing::Header,
traits::{BlakeTwo256, IdentityLookup},
};
use sp_core::H256;
type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<TestRuntime>;
type Block = frame_system::mocking::MockBlock<TestRuntime>;
// Configure a mock runtime to test the... | Rust | 0 |
#!/usr/bin/env python
import os
from vtkmodules.vtkFiltersCore import vtkContourFilter
from vtkmodules.vtkFiltersSources import vtkSphereSource
from vtkmodules.vtkIOLegacy import (
vtkDataSetReader,
vtkDataSetWriter,
)
from vtkmodules.vtkImagingHybrid import vtkVoxelModeller
from vtkmodules.vtkRenderingCore imp... | Python | 1 |
[doc = "0x0c - Digital I/O control for port 0 pins PIO0_3"]
pub pio0_3: crate::Reg<pio0_3::PIO0_3_SPEC>,
#[doc = "0x10 - Digital I/O control for port 0 pins PIO0_4"]
pub pio0_4: crate::Reg<pio0_4::PIO0_4_SPEC>,
#[doc = "0x14 - Digital I/O control for port 0 pins PIO0_5"]
pub pio0_5: crate::Reg<pio0_... | Rust | 0 |
(), (-1.5371385).to_channel(), (-0.4985314).to_channel(),
(-0.9692660).to_channel(), 1.8760108.to_channel(), 0.0415560.to_channel(),
0.0556434.to_channel(), (-0.2040259).to_channel(), 1.0572252.to_channel(),
])
}
}
impl TransferFunction for Srgb{
fn from_linear<T: Float>(x: T... | Rust | 0 |
be avoided.
if module.params['sshpubkey'] is not None:
if len(module.params['sshpubkey']) == 1 and module.params['sshpubkey'][0] == "":
module.params['sshpubkey'] = None
try:
client.login(username=module.params['ipa_user'],
password=module.params['ipa_pass'])
... | Python | 1 |
Control> {
if let Some(WorkResultControl::Standard(ref std)) = self.result_control {
Some(std)
} else {
None
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn serialize_works_ident() {
let works = Works::doi("10.1037/0003-066X.59.1.29");
... | Rust | 0 |
CircleShapeNew(body.borrow().ptr, radius, offset),
body: body.clone(),
}
}
}
/// See [Working With Circle Shapes](http://chipmunk-physics.net/release/Chipmunk-7.x/Chipmunk-7.0.1-Docs/#cpShape-Circles)
pub fn offset(&self) -> CPVect {
unsafe { cpCircleShapeGetOffs... | Rust | 0 |
shape (..., 5).
Returns:
Boolean array which specifies whether `bboxes_a` and `bboxes_b` overlap each
other of shape (...).
"""
chex.assert_shape(bboxes_a, (..., 5))
chex.assert_equal_shape((bboxes_a, bboxes_b))
def _overlap_a_over_b(first, second):
c, s = jnp.cos(first[..., 4]), jnp.sin(first... | Python | 1 |
ent', '—'))
}
]
})
# 历史记录表格
history_table = {
'component': 'VCard',
'props': {'variant': 'outlined', 'class': 'mb-4'},
'content': [
{
'component': 'VCardTitle',
... | Python | 1 |
# 调用 nvidia-smi 获取 GPU 信息
result = subprocess.run(
["nvidia-smi", "--query-gpu=index,name,power.draw,power.limit,memory.total,memory.used", "--format=csv,noheader,nounits"],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True
... | Python | 1 |
asks.append(asyncio.create_task(_parse_retail_item(url, title, snippet, grams, milli_l)))
else:
# CSE images → Vision OCR (с base64) — пробуем, если есть ключ
if VISION_KEY:
# Try to extract image URL from snippet or use cached image
image_url = re.search(... | Python | 1 |
import cx_Freeze
import sys
base = None
base = "Win32GUI"
shortcut_table = [
("DesktopShortcut", # Shortcut
"DesktopFolder", # Directory_
"Auto WM", # Name
"TARGETDIR", # Component_
"[TARGETDIR]\\Auto WM.exe", # Target
None, # Arguments
None, # Description
None, # Hotkey
... | Python | 1 |
_ptr() as *mut _,
&lda,
ipiv.as_ptr(),
work.as_mut_ptr() as *mut _,
&nb,
info,
)
}
#[inline]
pub unsafe fn csytrs2(
uplo: u8,
n: i32,
nrhs: i32,
a: &[c32],
lda: i32,
ipiv: &[i32],
b: &mut [c32],
ldb: i32,
work: &mut [c32],
info: &mut i... | Rust | 0 |
"]
pub uartmis: crate::Reg<uartmis::UARTMIS_SPEC>,
#[doc = "0x44 - Interrupt Clear Register, UARTICR"]
pub uarticr: crate::Reg<uarticr::UARTICR_SPEC>,
#[doc = "0x48 - DMA Control Register, UARTDMACR"]
pub uartdmacr: crate::Reg<uartdmacr::UARTDMACR_SPEC>,
_reserved14: [u8; 0x0f94],
#[doc = "0... | Rust | 0 |
ocle_competency.cycle::text = $3
AND eval_observation.active = true
AND eval_observation.date <= $2
AND eval_observation_student.student_id = $1
",
&[student_id, date, &cycle.to_str()],
)? {
// debug!(?row, "eval_observation_stats_by_cycle 2");
let competency_id = row.get(0);
if... | Rust | 0 |
from helpers import pytester_path
PYFILE = (
"""
import matplotlib.pyplot as plt
import pytest
@pytest.mark.mpl_image_compare
def test_mpl():
fig, ax = plt.subplots()
ax.plot([1, 2, 3])
return fig
"""
)
def test_generate_baseline_images(pytester):
pytester.makepyfi... | Python | 1 |
'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 6)) | (((value as u16) & 0x01) << 6);
self.w
}
}
#[doc = "JTAG mailbox output interrupt enable\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum JMBOUTIE_A {
#[doc = "0: Interrupts disabled"]
DISABLE = 0,
#[doc = "1... | Rust | 0 |
import json
from battleController import gSet
levelNum = 5
def load(level):
"""
Load the data of the level
"""
with open(f"./save/level{level}.json", "r", encoding="utf-8") as file:
data = json.load(file)
return data
def save(level, data):
"""
Save the data of the level
""... | Python | 1 |
ops.append(to_var.assign(from_var))
return ops
if __name__ == '__main__':
mask = get_mask(['A', 'A', 'A'], action_space)
print(mask[0])
# _, response_mask, _, _ = get_mask_alter(['A', 'A', 'A', 'J', 'J', '10', '6', '6', '5'], ['9', '9', '9', '5'], False,
# ... | Python | 1 |
n \\x7f ÿ $ \\\\ end\"", toks.to_string()?);
//!
//! let toks: js::Tokens = quote!(#(quoted("start π 😊 \n \x7f ÿ $ \\ end")));
//! assert_eq!("\"start π 😊 \\n \\x7f ÿ $ \\\\ end\"", toks.to_string()?);
//! # Ok(())
//! # }
//! ```
use crate::fmt;
use crate::tokens::ItemStr;
use relative_path::{RelativePath, Relative... | Rust | 0 |
t.iter().next() {
Some(rep) => rep.clone(),
None => bail!(
"[Bool::choose_rep] cannot choose representative of empty set"
),
} ;
let was_there = set.remove(& rep) ;
debug_assert!( was_there ) ;
Ok( (rep, set) )
}
}
}
impl Domain for Int {
fn of_cst(cst:... | Rust | 0 |
import pytest
import subprocess
import os
import re
def run_main_py(input_file):
possible_names = ["Assignment4.py", "assignment4.py", "main.py", "Main.py"]
script_name = None
for name in possible_names:
if os.path.isfile(name):
script_name = name
break
if script_name is... | Python | 1 |
from app.models.stay import Stay
class AvailableStaysService:
available_stays_offers = []
def set_stay(self, stay: Stay) -> Stay:
self.available_stays_offers.append(stay)
return stay | Python | 1 |
"""Almacenar y mostrar información de
estudiantes
Escribe un programa que permita al usuario ingresar el nombre y la calificación de
varios estudiantes. El programa debe almacenar esta información en un diccionario
donde las claves sean los nombres de los estudiantes y los valores sean sus
calificaciones. Al final, el ... | Python | 1 |
decoded: Request = decoder.decode(&buffer[..]).unwrap();
assert_eq!(decoded, request);
}
// Test an encoding when the provided buffer is too small (should panic).
#[test]
#[should_panic(expected = "failed to write whole buffer")]
fn cqc_hdr_buf_too_small() {
let client = Client::ne... | Rust | 0 |
latent = outputs.last_hidden_state
ids_restore = outputs.ids_restore
mask = outputs.mask
decoder_outputs = self.decoder(latent, ids_restore, interpolate_pos_encoding=interpolate_pos_encoding)
logits = decoder_outputs.logits # shape (batch_size, num_patches, patch_size*patch_size*num_c... | Python | 1 |
)
for record, claimed_by in stats['claimed_by_external']:
print(f" • {record['name']} - claimed by '{claimed_by}' (not in competing set)")
print(f" Competing packs: {record['node_ids']}")
print()
# Still unresolved
if stats['unresolved']:
print("4. STIL... | Python | 1 |
inn::{Connection, Endpoint};
use tokio::net::{TcpListener, TcpStream};
use tokio_rustls::TlsAcceptor;
use futures::StreamExt;
use tokio::io::AsyncWriteExt;
use crate::tls::{get_quic_cfg, get_tls_cfg};
use config::Config;
use crate::server::quic::{handle_quic};
#[derive(Debug, Clone)]
pub struct Server {
cache: Ar... | Rust | 0 |
gonna sneak up on him.",
"Now the hunted becomes the hunter.",
"Yeah, right.",
"Shake his hand?",
"Maybe I won't send her that check.",
"All right, all right, two fifty.",
"She can't take it.",
"It's not hers, it's theirs.",
"Once there's no theirs there's no hers, it should be ours.",
"How could you... | Rust | 0 |
continue;
}
let bodies = stream::iter(urls)
.map(|url| {
let client = &client;
async move {
let resp = client
.get(&url)
.timeout(Duration::from_secs(5))
... | Rust | 0 |
'occaecat cupidatat non proident, sunt in ' \
'culpa qui officia deserunt mollit anim id ' \
'est laborum.'
ticket['component'] = 'component1'
ticket['version'] = '2.0 Standard and International Edition'
ticket['res... | Python | 1 |
# Helper function to check if a position is valid
def is_valid(x, y, rows, cols):
return 0 <= x < rows and 0 <= y < cols
# DFS function to find unique paths from a trailhead to a '9'
def dfs(grid, x, y, rows, cols, path, all_paths):
# Directions: up, down, left, right
directions = [(-1, 0), (1, 0), (0, -1... | Python | 1 |
match board[row][column].to_digit(10) {
None => continue,
Some(idx) => {
if table[idx as usize] > 0 {
return false;
} else {
... | Rust | 0 |
nable_parallel_execution=False, # Force sequential mode
)
print(" ✅ Sequential-only agent created")
print(" 📝 This would use traditional LangGraph workflow for compatibility")
# 4. Show configuration options
print("\n4. Configuration Options:")
print(" 📋 Parallel Execution Configurati... | Python | 1 |
f))
}
}
fn connect_property_selection_end_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
unsafe {
let f: Box_<F> = Box_::new(f);
connect_raw(self.as_ptr() as *mut _, b"notify::selection-end\0".as_ptr() as *const _,
Some(transmute(notify_... | Rust | 0 |
model_inputs["input_ids"].append(input_ids)
model_inputs["attention_mask"].append([1] * len(input_ids))
model_inputs["labels"].append(labels)
model_inputs["kl_input_ids"].append(kl_input_ids)
model_inputs["kl_attention_mask"].append([1] * len(kl_input_ids))
model_inputs["kl_l... | Python | 1 |
from typing import List
class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
"""
Rotate the image by 90 degrees (clockwise).
Do not return anything, modify matrix in-place instead.
Args:
matrix: n x n 2D matrix representing an image
... | Python | 1 |
ule in self.denoising_unet.attn_processors.items():
if isinstance(attn_module, IPAttnProcessor2_0):
if 'up' in attn_name:
ip_attn_tm.append(torch.clone(attn_module.attn_map2))
ip_attn_face.append(torch.cl... | Python | 1 |
ION_LOW_POWER: u32 = 0;
pub const XCHAL_HAVE_FUSION_AES: u32 = 0;
pub const XCHAL_HAVE_FUSION_CONVENC: u32 = 0;
pub const XCHAL_HAVE_FUSION_LFSR_CRC: u32 = 0;
pub const XCHAL_HAVE_FUSION_BITOPS: u32 = 0;
pub const XCHAL_HAVE_FUSION_AVS: u32 = 0;
pub const XCHAL_HAVE_FUSION_16BIT_BASEBAND: u32 = 0;
pub const XCHAL_HAVE_... | Rust | 0 |
return Ok(());
}
if dev_buf.capacity > 0 && mem::size_of::<T>() > 0 {
let capacity = dev_buf.capacity;
let ptr = mem::replace(&mut dev_buf.buf, DevicePointer::null());
unsafe {
match cuda_free(ptr) {
Ok(()) => {
... | Rust | 0 |
)
@classmethod
def get_logger_class(cls, name: str):
return cls.get_class(name, "logger_name_mapping")
@classmethod
def get_trainer_class(cls, name: str):
return cls.get_class(name, "trainer_name_mapping")
@classmethod
def get(cls, name: str, default=None, no_warning: bool = F... | Python | 1 |
entities = vec!["Hello","my","name","is","John","What","is","your","name","A","name","is","a","personal","identifier","Never","share","your","name","My","ssn","is","003-67-0998"];
/// let mut pttrn_def = PatternDefinition::new();
/// let rslt = pttrn_def.analyze_entities(entities);
/// let pttrns = vec!["C... | Rust | 0 |
# Quick test script
from tetris_env import TetrisEnvironment
print("Testing environment directly...")
env = TetrisEnvironment()
print("Resetting...")
state, _ = env.reset(seed=123)
print(f"Reset worked, state shape: {state.shape}")
print("Taking one action...")
state, reward, done, _, _ = env.step(13)
print(f"Action... | Python | 1 |
) if !self.include_nonconstraining => {
// Constant expressions are not injective
return c.ty().visit_with(self);
}
ty::ConstKind::Param(data) => {
self.parameters.push(Parameter::from(data));
}
_ => {}
}
c.... | Rust | 0 |
pub DeviceHandle: ::HANDLE,
}
DEFINE_GUID!(D3DAUTHENTICATEDCONFIGURE_SHAREDRESOURCE, 0x772d047, 0x1b40, 0x48e8,
0x9c, 0xa6, 0xb5, 0xf5, 0x10, 0xde, 0x9f, 0x1);
#[repr(C)] #[derive(Clone, Copy, Debug)]
pub struct D3DAUTHENTICATEDCHANNEL_CONFIGURESHAREDRESOURCE {
pub Parameters: D3DAUTHENTICATEDCHANNEL_CONFIGUR... | Rust | 0 |