text
string
label_name
string
labels
int64
_email_link(self, url: str, bot_name: str): subject = f"Check out my AI chatbot: {bot_name}" body = f"Hi! I've created an AI chatbot and would love for you to try it out: {url}" email_url = f"mailto:?subject={subject}&body={body}" st.markdown(f'📧 [Open Email Client]({email_url})', unsaf...
Python
1
popup.resizable(False, False) tk.Label(popup, text="Tên Giảng Viên:").grid(row=0, column=0, padx=10, pady=10) name_entry = tk.Entry(popup) name_entry.grid(row=0, column=1, padx=10, pady=10) name_entry.insert(0, current_tengv) tk.Label(popup, text="Chọn Khoa:").grid(row=...
Python
1
t enumerated values variant"] #[inline(always)] pub fn variant(&self) -> AXIMTYPE_A { match self.bits { 0 => AXIMTYPE_A::AXIMTYPE_0, 1 => AXIMTYPE_A::AXIMTYPE_1, 2 => AXIMTYPE_A::AXIMTYPE_2, 3 => AXIMTYPE_A::AXIMTYPE_3, _ => unreachable!(), ...
Rust
0
from sacrebleu.metrics import BLEU, CHRF, TER def mt_evaluate(decoded_preds, decoded_labels): bleu = ( BLEU(tokenize="flores200").corpus_score(decoded_preds, [decoded_labels]).score ) chrf = CHRF().corpus_score(decoded_preds, [decoded_labels]).score ter = TER().corpus_score(decoded_preds, [dec...
Python
1
push(_entity.id()); } _commands.insert_resource(ResidentEntity(_vec)); let _game = GameProc::new(&mut _commands, &_asset, &mut _tex_atlases); // ゲーム処理 _commands.insert_resource(_game); let _value = GameValue::new(_data.hi_score, &mut _commands, &_asset, &mut _tex_atlases); // 数値描画 _commands.insert_res...
Rust
0
local_addr = stream.local_addr().unwrap(); let mut sink = FramedWrite::new(stream, encoder); let mut lines = stream::iter(lines.into_iter()).map(Ok); sink.send_all(&mut lines).await.unwrap(); let stream = sink.get_mut(); stream.shutdown().await.unwrap(); Ok(local_addr) } pub async fn send_...
Rust
0
@result Returns a TidyDoc instance."] pub fn tidyCreateWithAllocator(allocator: *mut TidyAllocator) -> TidyDoc; } extern "C" { #[doc = " Free all memory and release the TidyDoc. The TidyDoc can not be used after"] #[doc = " this call."] #[doc = " @param tdoc The TidyDoc to free."] pub fn tidyReleas...
Rust
0
} extern crate quicli; extern crate structopt; extern crate fuzzy_pickles; use std::{ fs::File, io::prelude::*, }; use fuzzy_pickles::{ ast, visit::{Visit, Visitor}, }; use quicli::prelude::*; use structopt::StructOpt; /// Get statistics about Rust files #[derive(Debug, StructOpt)] struct Cli { ...
Rust
0
from PyQt5 import QtWidgets, uic import sys from drone_controller import * class MainWindow(QtWidgets.QMainWindow): def __init__(self): super(MainWindow, self).__init__() uic.loadUi('main_menu.ui', self) self.btn_conntect.clicked.connect(self.connect_to_ip) self.btn_close.clicked...
Python
1
highly_variable_features(data, batch="Channel") """ check_batch_key(data, batch, "Switch to not not consider batch effects for selecting highly variable features.") if flavor == "pegasus": select_hvf_pegasus(data, batch, n_top=n_top, span=span) else: assert flavor == "Seurat" se...
Python
1
# MAGIC # MAGIC - **Update the Existing Model Serving Endpoint:** # MAGIC # MAGIC - Go to the **Serving** page or **Models** page, where you originally created the model serving endpoint in Task 6. # MAGIC - Select the existing model serving endpoint that you want to update. # MAGIC - Look for an option to mo...
Python
1
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # NO CHECKED-IN PROTOBUF GENCODE # source: request_cancel_all_orders.proto # Protobuf Python Version: 6.31.0 """Generated protocol buffer code.""" from google.protobuf import descriptor as _descriptor from google.protobuf import descript...
Python
1
from app.logger import AppLogger from app.features.users.admin.types import Pg, PgInput, GetPg from app.features.users.admin.services import add_pg_service from app.features.shared.services import ( delete_table_row, get_table_data_ext, get_table_row_ext ) logger = AppLogger().get_logger() async def get_...
Python
1
1000148041, InvertOvgExt = 1000148042, RedExt = 1000148043, GreenExt = 1000148044, BlueExt = 1000148045, } #[doc(hidden)] pub type RawVkBlendOp = i32; impl VkWrappedType<RawVkBlendOp> for VkBlendOp { fn vk_to_raw(src: &VkBlendOp, dst: &mut RawVkBlendOp) { *dst = *src as i32 } } impl ...
Rust
0
from functions.presentation_functions import confederation_introduction, confederation_awards from functions.group_stage import group_stage from functions.progression import progression from functions.knockout import knockout def uefa(data, settings): # TODO: Add if loop for running more than one simulation s...
Python
1
items: self.storage.items.as_ptr() as *mut sys::AuthorizationItem, }; self.storage } } /// Used by `Authorization::set_item` to define the rules of he right. pub enum RightDefinition<'a> { /// The dictionary will contain the keys and values that define the rules. FromDictionar...
Rust
0
(), 0); let overtime = start_time + (parts.get_time() as i64) - current; assert!(overtime <= 0); if max_seq < parts.get_sequence() { max_seq = parts.get_sequence(); } assert_eq!(parts.get_machine_id(), machine_id); } assert_e...
Rust
0
, 1).squeeze() weights = weights + 0.01 z_vals_mid = 0.5 * (z_vals[: ,:-1] + z_vals[: ,1:]) importance_z_vals = self.sample_pdf(z_vals_mid, weights[:, 1:-1], N_importance).detach().reshape(batch_size, num_rays, N_importance, 1) re...
Python
1
from lc import * class Solution: def numSpecial(self, mat: List[List[int]]) -> int: n,m = len(mat), len(mat[0]) def check(i,j): if mat[i][j]==0: return 0 for x in range(n): if x!=i: if mat[x][j]!=0: return 0 for y in range(m): ...
Python
1
::new(self, lvl) } /// Consume this reader to create a decompression stream of this stream. fn gz_decode(self) -> io::Result<read::GzDecoder<Self>> { read::GzDecoder::new(self) } /// Consume this reader to create a compression stream at the specified /// compression level. fn zlib_...
Rust
0
ly guess for either t1 or period, T") if t1_guess is None: if T_guess <= 0: raise ValueError("Guess for period T must be positive") t1_guess = t0+T_guess if T_guess is None: T_guess = t0+t1_guess if t1_guess <= t0: raise ValueError("t1 guess must be greater than t...
Python
1
(Interface::Contact) } else { None } } #[inline(never)] fn respond(&mut self, message: &interchanges::Data) { debug!("<< {}", hex_str!(message.as_slice(), sep:"")); match self.current_interface { Interface::Contactless => self.contactless.respond(&mes...
Rust
0
, 0x90, 0xE0, 0x90, 0xE0, 0xF0, 0x80, 0x80, 0x80, 0xF0, 0xE0, 0x90, 0x90, 0x90, 0xE0, 0xF0, 0x80, 0xF0, 0x80, 0xF0, 0xF0, 0x80, 0xF0, 0x80, 0x80, ]; self.memory[..0x50].clone_from_slice(&numbers); } } impl Memory for BlockMemory { fn read_byte(&se...
Rust
0
import struct from collections.abc import Callable from typing import Any try: import _md5 as md5lib except ImportError: import hashlib as md5lib md5_unpacker = struct.Struct("4I") def stable_hash(t: tuple) -> int: cnt = _dump_tuple(t) hd = md5lib.md5(cnt).digest() return md5_unpacker.unpack(hd...
Python
1
, name: *const c_char, args_count: u32) -> Option<&'static MethodInfo>; pub fn class_get_type(class: &Il2CppClass) -> &'static Il2CppType; pub fn field_set_value(obj: &mut Il2CppObject, field: &FieldInfo, value: *const c_void); pub fn field_get_value(obj: &mut Il2CppObject, field: &FieldInfo, value: *mut c_...
Rust
0
process.Popen([frenterojo], shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, preexec_fn=os.setsid) time.sleep(5) self.get_logger().info(f"gripper") gripperrojo = 'ros2 action send_goal -f /MoveG ros2_data/action/MoveG "{goal: -0.01}"' ...
Python
1
.filter.group_index = Self::K_LARGE_GROUP; triangle_body_def.position.set(-5.0, 6.0); triangle_body_def.fixed_rotation = true; // look at me! let body2 = B2world::create_body(m_world.clone(), &triangle_body_def); B2body::create_fixture(body2.clone(), &triangle_shape_def); { let mut bd = B2bodyDef::defaul...
Rust
0
import unittest from unittest.mock import patch, MagicMock from src.services.llm_service import call_llm class TestLLMService(unittest.TestCase): @patch('src.services.llm_service.requests.post') def test_call_llm_success(self, mock_post): mock_response = MagicMock() mock_response.json.return_v...
Python
1
* devaldg * tuner.params.special[IDX_ATTACK_WEIGHT + 2 * pos.trace.attackers[BLACK] as usize + i] * dsafetytabledconstant(tuner, i, attacker_value_black - rook_check_black, pos.trace.rook_safe_check[BLACK], c) / 100.0; ...
Rust
0
.dtick(5.0) .grid_color(Rgb::new(255, 255, 255)) .grid_width(1) .zero_line_color(Rgb::new(255, 255, 255)) .zero_line_width(2), ) .margin(Margin::new().left(40).right(30).bottom(80).top(100)) .paper_background_color(Rgb::ne...
Rust
0
ftmax(output, dim=1)[0] * 100 predicted_class = output.argmax(1).item() confidence = probabilities[predicted_class].item() # 统计结果 total += 1 if predicted_class == true_label: correct += 1 else: ...
Python
1
# Copyright (C) 2024 MPI IS, Marilyn Keller import argparse import os import torch from aitviewer.viewer import Viewer from skel.viewer.renderables.skel import SKELSequence from skel.skel_model import SKEL if __name__ == '__main__': parser = argparse.ArgumentParser(description='Test the parametrisation...
Python
1
input.vpc_config { let mut object_62 = object.key("VpcConfig").start_object(); crate::json_ser::serialize_structure_vpc_config(&mut object_62, var_61); object_62.finish(); } if let Some(var_63) = &input.model_kms_key_id { object.key("ModelKmsKeyId").string(var_63); } } pub f...
Rust
0
from fastapi import APIRouter, Depends, HTTPException, status from sqlalchemy.orm import Session from typing import List from ..database import get_db from ..models.workload import WorkloadCreate, Workload from ..models.sql_workload import SQLWorkload router = APIRouter() @router.post("/workloads/submit", response_m...
Python
1
if lfi_found == 0: print "[!] Sorry, I was not able to detect a LFI vulnerability here." print "[!] Exiting now!" print "" print "" sys.exit() # Create a simple log file log_file_name = get_parsed_url.netloc + "_-_" + strftime("%d_%b_%Y_%H:%M:%S_+0000", gmtime()) + "_-_...
Python
1
_read() { let data = [ 0x30, 0x30, 0x31, 0x65, 0x23, 0x20, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x3d, 0x67, 0x69, 0x74, 0x2d, 0x75, 0x70, 0x6c, 0x6f, 0x61, 0x64, 0x2d, 0x70, 0x61, 0x63, 0x6b, 0x0a, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x65, 0x76, 0x65, 0x72, 0x73, 0...
Rust
0
# # File: # skewt3.py # # Synopsis: # Draws two skew-T plots using real data. # # Category: # Skew-T # # Author: # Fred Clare (based on an NCL example of Dennis Shea) # # Date of original publication: # March, 2005 # # Description: # Produces two skew-T plots using real data. # # Effects illu...
Python
1
} #[test] fn complex() { let p = parse("@3b3b `Bar` 18d12h 6i6l6f 3d32?0`Foo`").unwrap(); assert_eq!(p.modifier, Some(Modifier::Native)); assert_eq!( p.codes.last(), Some(&FormatCode { repeat: Some(0), chr: FormatChar::Ident("...
Rust
0
{}", name, challenge_one(&content[..])); println!("Challenge two ({}): {}", name, challenge_two(&content[..])); Ok(()) } fn main() -> anyhow::Result<()> { process("sample").context("sample data")?; process("input").context("real data")?; Ok(()) } use crate::word::word; use nom::{ branch::al...
Rust
0
from django.contrib.auth.forms import AuthenticationForm, PasswordChangeForm from django.core.exceptions import ValidationError from django.utils.translation import gettext_lazy as _ class AdminAuthenticationForm(AuthenticationForm): """ A custom authentication form used in the admin app. """ error_m...
Python
1
tr again *(&mut *r) = 17; drop(Box::from_raw(r)); }} fn into_unique() { unsafe { let b = Box::new(4i32); let u = Box::into_unique(b).0; // "lose the tag" let r = ((u.as_ptr() as usize)+0) as *mut i32; *(&mut *r) = 7; // Use original ptr again. drop(Box::from_raw(u.as_ptr())); }} ...
Rust
0
vm::FuncEnv` from `vm::FuncCtx`. let func_env = func_ctx.func_env; let func: &FN = match func_env { // The imported function is a regular // function, a closure without a captured // environment, or a closur...
Rust
0
l_pix: 0u32, top_precent: 0f64, left_pix: 0u32, left_precent: 0f64, width_pix: 0u32, width_precent: 0f64, height_pix: 0u32, height_precent: 0f64, blobs: blobs.clone() }; out.update_size_pos(dim, cur_height); out } fn empty() -> Content { Content { id: Uuid::new_v4(), top_pix: 0u3...
Rust
0
fn validate_paths_are_not_garbage() -> amethyst::Result<()> { let (mut display_config_path, mut key_bindings_path, mut assets_dir) = initialize_paths()?; assert!(display_config_path.is_absolute()); assert!(display_config_path.pop()); assert!(key_bindings_path.is_absolute()); ...
Rust
0
.yml"); let message = match &config.config { Some(_path) => couldnt_find, None => format!("{}; consider adding `config` property to `[alacritty]` section of `thcon.toml`", couldnt_find), }; error!("{}", message); re...
Rust
0
import numpy as np import os import argparse import cv2 import tqdm import json import shutil import h5py import hdf5plugin import glob import math from utils.event_utils import EventSlicer from utils.viz_utils import render def plot_seq(infile, rmap_fname, H=480, W=640): outvizfolder = os.path.join(os.path.dirna...
Python
1
try: fru_file = "/usr/share/sonic/device/{}/fru.json".format(platform) data = json.load(open(fru_file)) data["onie_version"] = version with open(fru_file, "w") as json_file: json.dump(data, json_file, indent=4) except: pass def set_ubootenv_config(): cmd ...
Python
1
/// `Nehalem` added SSE4.2 extensions, along with the `POPCNT` instruction. pub fn nehalem() -> InstDecoder { penryn() .with_sse4_2() .with_popcnt() } /// `Westmere` was the successor to `Nehalem`, launched in 2010. it added AES-NI and CLMUL /// extensions. pub fn we...
Rust
0
l library variables to match main program settings. dealWithEncoding.debug=debug dealWithEncoding.consoleEncoding=consoleEncoding inputEncodingType = dealWithEncoding.ofThisFile(myFileName=inputFileName, rawCommandLineOption=command_Line_arguments.inputEncoding, fallbackEncoding=defaultEncodingType) #...
Python
1
from pydantic import ConfigDict import fastworkflow from fastworkflow import CommandOutput, CommandResponse from fastworkflow.workflow import Workflow from fastworkflow.utils.signatures import InputForParamExtraction from fastworkflow.train.generate_synthetic import generate_diverse_utterances from fastworkflow.utils....
Python
1
|s| seconds, fractions permitted. pub fn wait(s: f32) { let ms = (s * 1000_f32) as u64; sleep(Duration::from_millis(ms)); } pub fn cursor_down(xiv_handle: super::XivHandle) { log::debug!("[down]"); send_key(xiv_handle, constants::KEY_DOWN); } pub fn cursor_up(xiv_handle: super::XivHandle) { log::...
Rust
0
fn test_err_div64_by_zero_reg() { test_interpreter_and_jit_asm!( " mov32 r0, 1 mov32 r1, 0 div r0, r1 exit", [], (), { |_vm, res: Result| matches!(res.unwrap_err(), EbpfError::DivideByZero(pc) if pc == 31) }, 3 ); } #[test] fn test_err_di...
Rust
0
#!/usr/bin/env python3.8 """ doc doc doc """ filter_datum = __import__("filtered_logger").filter_datum fields = ["password", "date_of_birth"] messages = [ "name=egg;email=eggmin@eggsample.com;password=eggcellent;date_of_birth=12/12/1986;", "name=bob;email=bob@dylan.com;password=bobbycool;date_of_birth=03/04/...
Python
1
Complexity N = limit ( #-balls) Q = #-queries Time complexity: O(Q) Space complexity: O(N)(E)O(1)(I) Code ''' URL := https://leetcode.com/problems/find-the-number-of-distinct-colors-among-the-balls/description/ 3160. Find the Number of Distinct Colors Among the Balls ''' class Solution: def queryResults(self, li...
Python
1
""" Path planning Sample Code with RRT with path smoothing @author: AtsushiSakai(@Atsushi_twi) """ import math import random import matplotlib.pyplot as plt import sys import pathlib sys.path.append(str(pathlib.Path(__file__).parent)) from rrt import RRT show_animation = True def get_path_length(path): le =...
Python
1
sfKeyNumpad3: sfKeyCode = 78; pub const sfKeyCode_sfKeyNumpad4: sfKeyCode = 79; pub const sfKeyCode_sfKeyNumpad5: sfKeyCode = 80; pub const sfKeyCode_sfKeyNumpad6: sfKeyCode = 81; pub const sfKeyCode_sfKeyNumpad7: sfKeyCode = 82; pub const sfKeyCode_sfKeyNumpad8: sfKeyCode = 83; pub const sfKeyCode_sfKeyNumpad9: sfKeyC...
Rust
0
from kol3btesty import runtests from queue import PriorityQueue def airports(G, A, s, t): n = len(G) distance = [float('inf')] * (n + 1) # n+1 dla wierzchołka "niebo" processed = [False] * (n + 1) queue = PriorityQueue() queue.put((0, s)) distance[s] = 0 while not queue.empty(): ...
Python
1
from collections import namedtuple import graphene from graphene import ObjectType class GrapheneCount(graphene.ObjectType): key = graphene.String() value = graphene.Int() GrapheneCountValueObject = namedtuple("GrapheneCount", ["key", "value"]) class NestedGrapheneCount(ObjectType): key = graphene.S...
Python
1
rmat!( r###"pub fn {}(procedure: u32, buf: &mut EasyBuf) -> io::Result<Option<{}Request>>"###, fn_name.as_ref(), prog_name.as_ref()), "", cb); } pub fn version_decoder_call<S: AsRef<str>>(fn_name: S, wr: &mut CodeWriter) { wr.write_line(&format!("{}(procedure, buf)", fn_name.as_ref())); } pub fn version_d...
Rust
0
er wrapper() # wraps the lower-level C-based class "list". # # Unwrapping this wrapper to this class would induce insanity throughout # the codebase, which sanely expects wrappers to be callables rather # than classes. Clearly, classes have *NO* signatures. Technically, a ...
Python
1
import torch import numpy as np def get_target_label_idx(labels, targets): """ Get the indices of labels that are included in targets. :param labels: array of labels :param targets: list/tuple of target labels :return: list with indices of target labels """ return np.argwhere(np.isin(label...
Python
1
()) } } impl<T, M: Msg<T>> Debug for NoDebug<T, M> { fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> { M::fmt(&self.0, f) } } impl<T, M: Msg<T>> Deref for NoDebug<T, M> { type Target = T; fn deref(&self) -> &Self::Target { &self.0 } } impl<T, M: Msg<T...
Rust
0
oor", "terrible"] response_lower = llm_response.lower() positive_count = sum(1 for word in positive_indicators if word in response_lower) negative_count = sum(1 for word in negative_indicators if word in response_lower) if positive_count > negative_count: base_score = 60 + ...
Python
1
6_64-linux-gnu/include/", "-O2", "--target=x86_64-linux-unknown", "-D_M_X86_64", ] # Add all the arguments to the different lists args_x86_64.extend(BaseArgs) # We need to find the default arguments through clang invocations args_x86_64 = FindClangArguments(args_x86_64) ...
Python
1
Err(e) => match e { mpsc::TryRecvError::Empty => break, mpsc::TryRecvError::Disconnected => unreachable!(), }, } } }; a.queue = unsafe { SlotNoArgs::new(NullPtr, handler) }; unsafe { a.timer.timeo...
Rust
0
luence_score = min(1.0, agent.influence_score + 0.1) # 更新活动时间 for agent in agents.values(): agent.last_activity = time.time() return {"success": True, "action": action, "subgraph_id": subgraph_id} def get_all_metrics(self) -> List[SubgraphMetrics]: ...
Python
1
=30) parser.add_argument("--lr", type=float, required=False, default=2e-3) parser.add_argument("--lr_decay", type=float, required=False, default=1.) parser.add_argument("--decay", type=float, required=False, default=0.05) parser.add_argument("--ls", type=float, required=False, default=0.2) parser.ad...
Python
1
, // Allowed casts Sint -> Sint. (IntSuffix::I8 , IntSuffix::I8 ) => IntSuffix::I8 , (IntSuffix::I8 , IntSuffix::I16) => IntSuffix::I16, (IntSuffix::I8 , IntSuffix::I32) => IntSuffix::I32, (IntSuffix::I8 , IntSuffix::I64) => IntSuffix::I64, (IntSuffix::I16, IntSuffix::I16...
Rust
0
#!/usr/bin/env python3 import os import shutil import sys import urllib.error import urllib.request import zipfile example_deps_urls = { 'glfw': "https://github.com/glfw/glfw/releases/download/3.3.9/glfw-3.3.9.zip", 'glm': "https://github.com/g-truc/glm/archive/refs/tags/0.9.9.8.zip", 'stb': "https://gith...
Python
1
from collections import namedtuple from Vintageous.vi.utils import modes from Vintageous.tests import first_sel from Vintageous.tests import second_sel from Vintageous.tests import ViewTest test_data = namedtuple('test_data', 'content sel params expected actual_func msg') TESTS = ( test_data(content='abc', sel=...
Python
1
/ Writes the full file contents. If any file contents already exist at /// `path`, they are replaced. Extension hooks are preserved. /// /// # Errors /// /// If access to the [`Native`] filesystem returns an error, the error is /// returned. See [`Native::write_file`]. pub fn write_file(&mut...
Rust
0
cked_print, mocked_input, mock_path, data): with patch('builtins.open', mock_open(read_data=data)) as mocked_open: App().run() mocked_input.assert_called() mocked_print.assert_called() handle = mocked_open() assert handle.write.mock_calls == [ call('Moto\tCA220NI\tKawasaki\tNinja\t9...
Python
1
#[test] #[cfg(feature = "serde_support")] fn test_ser_de() { use serde_test::{assert_tokens, Token}; let s = ThinStr::from("asdffdsa12344321"); assert_tokens(&s, &[Token::Str("asdffdsa12344321")]); let s = ThinStr::from(""); assert_tokens(&s, &[Token::Str("")]); ...
Rust
0
# tuple application with lists + range # Merge for list of student info(name,first,second) # compute the sum of first and second and append to list names = ["Saed","Jihad","Abdullah","Aya"] #del names[0] # names.pop(0) first = [22,17,21,19] second = [18,22,20,23] marks_sum = [] """for f,s in zip(first,second): mar...
Python
1
import pygame # Настройки экрана WINDOW_WIDTH = 800 WINDOW_HEIGHT = 600 WINDOW_TITLE = "Visual Novel" # Цвета WHITE = (255, 255, 255) BLACK = (0, 0, 0) BLUE = (50, 50, 150) GRAY = (200, 200, 200) DARK_GRAY = (100, 100, 100) TEXT_BOX_COLOR = (0, 0, 0, 180) # Настройки текста FONT_SIZE = 24 NAME_FONT_SIZE = 32 BUTTON_...
Python
1
er"] += 1 current["type"] = "Delta-Cache" else: cache_dic["cache_counter"] += 1 current["type"] = "ToCa" # Modified from https://github.com/Shenyi-Z/TaylorSeer/blob/main/TaylorSeers-xDiT/taylorseer_flux/cache_functions/cache_init.py def cache_init(self, num_steps: int): """ Initi...
Python
1
from .register import RegisterStates from .find_number import FindNumberStates from .settings import SetLanguageStates from .robot_find_number import RobotFindNumberStates
Python
1
if operands.len() > MAX_OPERANDS { return Err(ParseError::LimitExceeded); } } } } Ok(Dict { dict, default: PhantomData, }) } } fn offset_size(value: usize) -> Option<u8> { match value { ...
Rust
0
rip() logger.info(f"Job submitted successfully with ID: {job_id}") break if not job_id: raise DeadlineError("No job ID found in submission output") # ...
Python
1
upCommandClearArg::new() } fn descriptor_static() -> &'static ::protobuf::reflect::MessageDescriptor { static descriptor: ::protobuf::rt::LazyV2<::protobuf::reflect::MessageDescriptor> = ::protobuf::rt::LazyV2::INIT; descriptor.get(|| { let fields = ::std::vec::Vec::new(...
Rust
0
import csv import os import argparse def create_empty_sb_grid_file(width, height, file_path="./"): ''' Create an empty SB csv grid file with the given width and height. The user can use this as a sarting point for their SB grid lcoations. Writes a file called "sb_grid.csv" in the `file_path` direct...
Python
1
"Normalized Flap Cycle Time", ) lift_axes.set_ylabel( "Lift (N)", ) lift_axes.set_title( "Simulated and Experimental Lift Versus Time", ) lift_axes.legend( loc="upper left", facecolor=figure_background_color, edgecolor=figure_background_color, labelcolor=text_color, ) # Save the lift comparis...
Python
1
ults summary not found"} with open(all_results_file, 'r', encoding='utf-8') as f: all_results = json.load(f) total_images = len(all_results) high_confidence_count = 0 medium_confidence_count = 0 low_confidence_count = ...
Python
1
_drop_gauge(vec![worker_id.clone()]), pending_peeks: self .pending_peeks .get_delete_on_drop_gauge(vec![worker_id.clone()]), commands_processed: CommandsProcessedMetrics::new( &worker_id, &self.commands_processed_metric, ...
Rust
0
from __future__ import unicode_literals import re from datetime import date from django.core.management.base import BaseCommand, CommandError from redis_metrics.utils import r class Command(BaseCommand): """ Updates the weekly metrics so they use the new key format. For more information, see Issue #7: h...
Python
1
=> [T]); impl_container!((T) => [T; 0]); impl_container!((T) => [T; 1]); impl_container!((T) => [T; 2]); impl_container!((T) => [T; 3]); impl_container!((T) => [T; 4]); impl_container!((T) => [T; 5]); impl_container!((T) => [T; 6]); impl_container!((T) => [T; 7]); impl_container!((T) => [T; 8]); impl_containe...
Rust
0
], ) .unwrap(); MemTable::try_new(schema, vec![vec![batch]]).unwrap() } } <reponame>avranju/import-amusic-playlist use std::fs::File; use std::io::BufReader; use std::path::Path; use crate::errors::Result; #[derive(Serialize, Deserialize, Debug)] pub struct Entry { title:...
Rust
0
# wm, 14.03.2007 def groupby(seq, value=lambda x: x): def aux((vp, L), curr): vc = value(curr) if vp == vc: L[-1].append(curr) else: L.append([curr]) return (vc, L) return reduce(aux, seq, (aux, []))[1] def groupby2(seq, value=lambda x: x): def aux((vp, L), curr): vc = value(curr) if vp == vc:...
Python
1
Err(err) => ConsoleService::error(err.to_string().as_str()), } } Msg::FetchFailed }); let request = Request::get(&self.user_url).body(Nothing).unwrap(); let task = FetchService::fetch(request, callback)....
Rust
0
from tests.runtime_aggtest.aggtst_base import TstView class aggtst_map_some(TstView): def __init__(self): # checked manually self.data = [{"c1": True, "c2": True}] self.sql = """CREATE MATERIALIZED VIEW map_some AS SELECT SOME(c1 > c2) AS c1, SOME(c2 > c1) AS c2 ...
Python
1
g the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ (master_doc, 'memoize', 'memoize Documentation', author, 'memoize', 'One line description of project.', 'Miscellaneous'), ] # -- Option...
Python
1
Punctuated<syn::NestedMeta, Token![,]>, ) -> Result<SerAndDe<Vec<syn::WherePredicate>>, ()> { let (ser, de) = get_ser_and_de(cx, BOUND, items, parse_lit_into_where)?; Ok((ser.at_most_one()?, de.at_most_one()?)) } pub fn get_serde_meta_items(cx: &Ctxt, attr: &syn::Attribute) -> Result<Vec<syn::NestedMeta>, ()> ...
Rust
0
from models import Direction, Account, PrimaryKey, Trade, Position from datetime import datetime def test_position_model(): # Create a test account account = Account(accountId="1", accountName="Test Account") # Create a test primary key primary_key = PrimaryKey(account=account, tradeId="T001") # ...
Python
1
(v2, original_value); } #[test] fn test_add() { let v1: u64 = 123456; let v2: u64 = 654321; let mut numb1: Numb = Numb::from_num(v1, 10); let numb2: Numb = Numb::from_num(v2, 10); assert_eq!(numb1.add(numb2).to_num(), v1 + v2); } #[test] fn increment_o...
Rust
0
# ai/preprocess.py import re, string, emoji, nltk from nltk.corpus import stopwords nltk.download("stopwords", quiet=True) STOP = set(stopwords.words("english")) def clean(text: str) -> str: """Basic Twitter / Reddit style cleaning.""" text = emoji.replace_emoji(text, replace='') text = re.sub(r"http\S+",...
Python
1
Err(e) => { eprintln!("Failed to read TOML user configuration: {:?}", e); UserConf::default() } }; uconf } pub(crate) fn save(&self) { let tml = toml::to_string(&self).expect("failed to serialize user configuration"); let path = use...
Rust
0
oned() { t = FileType::PrivateKey; let other = match get_file_path(&t) { Ok(p) => p, Err(_) => { return false; }, }; if !path.is_file() || !other.is_file() { return false; } } true } fn get_file_path(_file_t...
Rust
0
), }; if example.has_errors != is_error || !expected.is_match(&output) { errors.push((output, example)); } } if !errors.is_empty() { panic!("{:#?}", errors); } } <reponame>Dawn-Equipment-Company/multican use crate::{CanMessage, CanNetwork}; use socket2::{Domain,...
Rust
0
"))] #[cfg_attr(all(test, target_arch = "arm"), assert_instr(vqshl, N = 2))] #[cfg_attr(all(test, target_arch = "aarch64"), assert_instr(sqshl, N = 2))] #[rustc_legacy_const_generics(1)] pub unsafe fn vqshl_n_s32<const N: i32>(a: int32x2_t) -> int32x2_t { static_assert_imm5!(N); vqshl_s32(a, vdup_n_s32(N.try_in...
Rust
0
on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::time::SystemTime; use crate::models::{ ActiveGameroom, Gameroom, GameroomMember, GameroomProposal, Gam...
Rust
0