text
string
label_name
string
labels
int64
class TaskFamily: @staticmethod def get_tasks() -> dict[str, dict]: return { "1": {"event": "The signing of the Declaration of Independence in 1776.", "context": "Rewrite this event as a scene in a science fiction novel, incorporating elements of advanced technology and interstellar politics...
Python
1
# 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 # distributed under t...
Python
1
crate) show_commit: Vec<Event>, /// Key bindings for showing a diff. pub(crate) show_diff: Vec<Event>, /// Key bindings for toggling visual mode. pub(crate) toggle_visual_mode: Vec<Event>, } impl CustomKeybinding for AppKeyBindings { /// Create a new instance from the configuration keybindings. fn new(key_bindin...
Rust
0
vin.into(), vout: vout.into(), locktime, })) } /// Get the version number from the underlying tx fn version(&self) -> u32 { match self { BitcoinTx::Witness(tx) => tx.version(), BitcoinTx::Legacy(tx) => tx.version(), } } /// G...
Rust
0
C, A> LinkGetCall<'a, C, A> where C: BorrowMut<hyper::Client>, A: oauth2::GetToken { /// Perform the operation you have build so far. pub fn doit(mut self) -> Result<(hyper::client::Response, Link)> { use std::io::{Read, Seek}; use hyper::header::{ContentType, ContentLength, Authorization, Bea...
Rust
0
FileOrStdout; use rust_elm_types::*; use std::{error::Error, path::PathBuf, process::exit}; use structopt::StructOpt; #[derive(Debug, StructOpt)] struct Opt { #[structopt(short, long, help = "Silence all log messages")] quiet: bool, #[structopt(short, long, parse(from_occurrences), help = "Increase log ou...
Rust
0
from kivy.app import App from kivy.clock import Clock from kivy.lang import Builder from kivy.properties import NumericProperty from kivy.properties import ObjectProperty from kivy.uix.boxlayout import BoxLayout Builder.load_string(''' #:import temperature plyer.temperature <TemperatureInterface>: temperature: te...
Python
1
ype> WasmPtr<T, Array> { #[inline] pub fn deref<'a>( self, memory: &'a Memory, index: u32, length: u32, ) -> Result<&'a [Cell<T>], __wasi_errno_t> { if (self.offset as usize) + (mem::size_of::<T>() * ((index + length) as usize)) >= memory.size().bytes().0 ...
Rust
0
", r#""urn:schemas-nds-com:service:SkyBrowse:2#Browse""#) .body(body) .send() .await? .text() .await?; // Parse the response and get element 'Result' let doc = roxmltree::Document::parse(&resp)?; let result_elem = doc.descendants().fin...
Rust
0
from grid import Grid class Search: def __init__(self, graph : Grid): self.graph = graph def RunSearch(self, start, target): pass # Override # Get list of directions (unit vectors) to follow # To navigate to target def GetPathEdges(self) -> list[tuple[int,int]]: ...
Python
1
s = ratings[[c.noteIdKey, c.raterParticipantIdKey] + c.notHelpfulTagsTSVOrder] # Add weights to ratings, which will inherently filter out ratings where either the note or # rater were not included in matrix factorization. ratings = ratings.merge(ratingWeights, on=[c.noteIdKey, c.raterParticipantIdKey], how="inner...
Python
1
from datetime import datetime from typing import Optional from uuid import UUID from pydantic import BaseModel, Extra, Field from backend.core.config import settings class TelegramUserBase(BaseModel): """Базовая схема для TelegramUser.""" username: str = Field(...) role_id: Optional[UUID] = None fi...
Python
1
() { let mut database = MemoryDatabase::new(); add_transaction( &mut database, vec![OutPoint::from_str( "aad194c72fd5cfd16d23da9462930ca91e35df1cfee05242b62f4034f50c3d41:5", ) .unwrap()], vec![50_000], ); let fi...
Rust
0
problem with pencil (A, B) fn generalized_eig<A: NdFloat>(a: Array2<A>, b: Array2<A>) -> Result<(Array1<A>, Array2<A>)> { let (vals_b, vecs_b) = b.eigh_into()?; let vals_b_recip = vals_b.mapv_into(|x| (x.max(A::from(1e-10f32).unwrap())).sqrt().recip()); let vecs_b_tilde = vecs_b * vals_b_recip; let a_t...
Rust
0
on y = prob.reconstruct(x) # %% # The estimated measurements b = A.times(x) # %% # Let us visualize the original and reconstructed representation plot_representations(x0, x) # %% # Let us visualize the original and reconstructed signal plot_signals(y0, y) # %% # Let us visualize the original and reconstructed meas...
Python
1
::native_monitor::NativeMonitorId::Unavailable } #[inline] pub fn get_dimensions(&self) -> (u32, u32) { unimplemented!() } } impl Window { pub fn new(window: &WindowAttributes, pf_reqs: &PixelFormatRequirements, opengl: &GlAttributes<&Window>) -> Result<Window, Creat...
Rust
0
error!("Called deprecated group function!"); info!("Delete group item {} ", id); self.data_base.delete_group_item(id) } fn process_bad_command(&self) -> (String, i32) { (String::from(""), 1) } fn process_one_time_event_command(&mut self, uid:i64, c: OneTimeEventImpl) -> (String...
Rust
0
se", "they", "thick", "thin", "third", "this", "those", "though", "three", "through", "throughout", "thru", "thus", "to", "together", "too", "top", "toward", "towards", ...
Python
1
# %% from pandas_ta import sma, ema, wma, cross from ta.algo import fixed_cross import numpy as np import pandas as pd from random import Random nmacd_ma_type_map = { "ema": ema, "wma": wma, "sma": sma, } def nmacd_signals( series: pd.Series, fast: int = 12, slow: int = 21, signal: int = ...
Python
1
m.setObjects( *(("ESPA-MIB", "ObjectOfReference"), ("ESPA-MIB", "EventTime"), ("ESPA-MIB", "EventType"), ("ESPA-MIB", "PerceivedSeverity"), ("ESPA-MIB", "ThresholdInformation"), ("ESPA-MIB", "Description")) ) if mibBuilder.loadTexts: alarm.setStatus( "current" ...
Python
1
"""restore_idx_status_started_index Revision ID: 59991b568c7d Revises: 78777e6b12d3 Create Date: 2025-04-08 10:43:53.361024 """ from alembic import op # revision identifiers, used by Alembic. revision = "59991b568c7d" down_revision = "78777e6b12d3" branch_labels = None depends_on = None def upgrade() -> None: ...
Python
1
able!() })) })?, // faster ("std", "join") => parse_args!(context, "std.join", args, 2, [ 0, sep: [Val::Str|Val::Arr], vec![ValType::Str, ValType::Arr]; 1, arr: [Val::Arr]!!Val::Arr, vec![ValType::Arr]; ], { Ok(match sep { Val::Arr(joiner_items) => { let mut out = Vec::new(); let mut ...
Rust
0
0 2 DCE Security version, with embedded POSIX UIDs. /// 0 0 1 1 3 The name-based version that uses MD5 hashing. /// 0 1 0 0 4 The randomly or pseudo-randomly version. /// 0 1 0 1 5 The name-based version that uses SHA-1 hashing. ...
Rust
0
# Copyright 2023 The Google Earth Engine Community Authors # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable...
Python
1
e(item) = body.next().await { bytes.extend_from_slice(&item?); } let transset = match TransferSet::from_serialized(&String::from_utf8(bytes.to_vec()).unwrap()) { Ok(ts) => ts, Err(e) => { return Ok(HttpResponse::BadRequest() .header(http::header::CONTENT_TYPE...
Rust
0
while let Some(b) = next!() { if is_char_boundary(*b) { break; } } Utf8Token::Invalid(&src[..n-1]) } }; } loop { let b = if let Some(b) = next!() { *b } else { ...
Rust
0
# The MIT License (MIT) # Copyright (c) 2021-2024 Krux contributors # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, co...
Python
1
new_peer(1, 1)); // Make sure region 1 is removed from store 1. cluster.must_region_not_exist(r1, 1); let region = pd_client.get_region_by_id(r1).wait().unwrap().unwrap(); // Local reader panics if it finds a delegate. let reader_has_delegate = "localreader_on_find_delegate"; fail::cfg(reade...
Rust
0
) { todo!() } }// Generated by `scripts/generate.js` use utils::vk_traits::*; /// Wrapper for [VkLogicOp](https://www.khronos.org/registry/vulkan/specs/1.2-extensions/man/html/VkLogicOp.html). #[repr(i32)] #[derive(Debug, PartialEq, Copy, Clone)] pub enum VkLogicOp { Clear = 0, And = 1, AndRev...
Rust
0
import os import httpx from typing import Dict, Any, Optional from fastapi import HTTPException from core.utils.logger import logger class TriggerSchemaService: def __init__(self): self.api_base = os.getenv("COMPOSIO_API_BASE", "https://backend.composio.dev").rstrip("/") self.api_key = os.getenv("C...
Python
1
"""Plugin for checking super calls.""" from __future__ import annotations from astroid import nodes from pylint.checkers import BaseChecker from pylint.interfaces import INFERENCE from pylint.lint import PyLinter METHODS = { "async_added_to_hass", } class HassEnforceSuperCallChecker(BaseChecker): """Checker...
Python
1
<'a, P: Into<Option<&'a gdk::Window>>>(&self, window: P) { let window = window.into(); let window = window.to_glib_none(); unsafe { ffi::gtk_gesture_set_window(self.to_glib_none().0, window.0); } } #[cfg(any(feature = "v3_14", feature = "dox"))] fn ungroup(&self)...
Rust
0
tive_eventloop} eventloop. Doing nothing" ) return self.log.warning( f"Shell is already running a different gui event loop for {self.active_eventloop}. " "Call with no arguments to disable the current loop." ) return ...
Python
1
&vault::signer_seeds(safe_addr, beneficiary_acc_info.key, &vesting.nonce), program_id, ) .map_err(|_| LockupErrorCode::InvalidVaultNonce)?; if va != *vault_authority_acc_info.key { return Err(LockupErrorCode::InvalidVault.into()); } Ok(va) } pub fn token(acc_info: &AccountIn...
Rust
0
from numpy import pi from tqdm import tqdm # added tqdm def ramanujan_perimeter(a, b): return pi * (3 * (a + b) - ((3 * a + b) * (a + 3 * b))**0.5) def perimeter_fourier(a, b, k_func): return [k_func(bi / ai) * pi * (ai + bi) for ai, bi in tqdm(zip(a, b), total=len(a), desc="Fourier perimeter")] def perimet...
Python
1
() { return Err(Error::MalformedPCK.into()); } // Verify TCB level. let tcb_level = self.tcb_info .verify(&fmspc.unwrap(), tcb_comp_svn.unwrap(), pcesvn.unwrap())?; self.tcb_level = Some(tcb_level); // Extract PCK public key. let ...
Rust
0
all_arrivals .iter() .filter(|(_, _, route, stop)| r.id == *route && id == *stop) .map(|(t, car, _, _)| (*t, *car)) .collect(); let mut txt = Text::new(); if let Some((t, _)) = arrivals.last() { // TODO Button to jump to the bus tx...
Rust
0
, } } } #[doc(hidden)] impl FromGlib<nm_sys::NMWepKeyType> for WepKeyType { fn from_glib(value: nm_sys::NMWepKeyType) -> Self { match value { 0 => WepKeyType::Unknown, 1 => WepKeyType::Key, 2 => WepKeyType::Passphrase, value => WepKeyType::__Unkno...
Rust
0
* decoder_state: final hidden state from the decoder * attns: distribution over src at each tgt `[batch x tgt_len x src_len]`. """ # Check assert isinstance(state, RNNDecoderState) # tgt.size() returns tgt length and batch ...
Python
1
u{1F225}' => Some(&['\u{5439}']), '\u{1F226}' => Some(&['\u{6F14}']), '\u{1F227}' => Some(&['\u{6295}']), '\u{1F228}' => Some(&['\u{6355}']), '\u{1F229}' => Some(&['\u{4E00}']), '\u{1F22A}' => Some(&['\u{4E09}']), '\u{1F22B}' => Some(&['\u{904A}']), '\u{1F22C}' =>...
Rust
0
t_filename) _, stdout, _ = config.hdfs_client_list_files(alice_dir) assert test_filename in stdout # bob doesn't have read/write access to alice's directory sdk_auth.kdestroy(hdfs_client["id"]) sdk_auth.kinit(hdfs_client["id"], keytab=config.KEYTAB, principal=kerberos.get_principal("bob")) con...
Python
1
NSIGNED_BC6H = 32, CU_RES_VIEW_FORMAT_SIGNED_BC6H = 33, CU_RES_VIEW_FORMAT_UNSIGNED_BC7 = 34, } pub type CUresourceViewFormat = CUresourceViewFormat_enum; /** * Resource view descriptor */ #[repr(C)] #[derive(Debug, Copy)] pub struct CUDA_RESOURCE_VIEW_DESC_st { /**< Resource view format */ pub format...
Rust
0
0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ], }, StatusChannel { index: 2, name: "51B".into(), phase: "".into(), circuit_component_be...
Rust
0
import os import argparse import numpy as np import pandas as pd def generate_graph_seq2seq_io_data(df, x_offsets, y_offsets, add_time_in_day=True, add_day_in_week=False, scaler=None): num_samples, num_nodes = df.shape # (seq_length, num_nodes) data = np.expand_dims(df.values, axis=-1) # (seq_length, num_no...
Python
1
#差分 n, m = map(int,input().split()) s = input() a = [int(s) for s in input().split()] b = [int(s) for s in input().split()] o = {"W":0, "M":1, "L":2} #b的位置 c = [0]*n #時間圖 for i, ch in enumerate(s): j = o[ch] c[i] += a[j] p = i+b[j] if p<n: #判斷會不會超出串列長度 c[p] -= a[j] ans = 0 cur = 0 for i in c: ...
Python
1
import torch import numpy as np from math import exp import torch.nn.functional as F from torch.autograd import Variable def compute_measure(x, y, pred, data_range): original_psnr = compute_PSNR(x, y, data_range) original_ssim = compute_SSIM(x, y, data_range) original_rmse = compute_RMSE(x, y) pred_ps...
Python
1
per::tokio::prelude::*; use std::time::{Duration, Instant}; #[derive(Debug)] struct F_with_notification { state: i32, } impl Future for F_with_notification { type Item = i32; type Error = (); /**idea is to return NotReady few times and only then return Ready*/ fn poll(&mut self) -> Poll<Self::Ite...
Rust
0
import numpy as np import cv2 import matplotlib.pyplot as plt def show_side_by_side(original: np.ndarray, compressed: np.ndarray) -> None: # Display two grayscale images side by side for comparison. fig, axs = plt.subplots(1, 2, figsize=(12, 6)) axs[0].imshow(original, cmap='gray') axs[0].set_title("Or...
Python
1
of Botha", "title": "Managing Partner", "company": "Sequoia Capital", "location": "San Francisco Bay Area", "linkedin_url": "https://www.linkedin.com/in/roelofbotha/", "headline": "Managing Partner at Sequoia Capital | I...
Python
1
_capacity { min_capacity = max_capacity; } self.weight += max_capacity - min_capacity; self.min_capacity += min_capacity; match self.tables.entry(TypeId::of::<T>()) { Entry::Occupied(mut e) => { let c = &mut e.get_mut().caches()[group_i]; ...
Rust
0
a mix of (ordered and non-overlaping) cells and cells range /// (a cell range is a range at the cell depth, while regular ranges are at the /// largest possible depth and depends on type `T`). /// This is used as the result of a MOC ASCII deserialization. #[derive(Debug)] pub struct CellOrCellRangeMOC<T: Idx, Q: MocQ...
Rust
0
if !status.success() { bail!("screen failed") } Ok(()) } pub fn objdump( cfg: &Config, args: &ArgMatches, cmd_args: &ArgMatches, out: &mut Printer, ) -> Result<()> { Ok(()) } pub fn itm( cfg: &Config, args: &ArgMatches, cmd_args: &ArgMatches, out: &mut Printer, )...
Rust
0
import json from openai import OpenAI from schemes.task_categorizer import TaskCategories, CATEGORIZER_OUTPUT_SCHEME class TaskCategorizer: """Categorizes tasks based on their content and schema""" PROMPT = "Please categorize the task based on the content provided." OPENAI_CONFIG = { "model": "...
Python
1
_node belongs to the new connected component } used[next_node] = true; used_count += 1; if sel_e[next_node] != graph.node_bound() { let pred = sel_e[next_node]; msf.push((next_node, pred)); } for edge in graph.edges(graph.from_index(next_node)) ...
Rust
0
) def quadtree_mtf( image_data: np.array, ground_sampling_distance: float, detail_error_threshold: float = 25, ): """Obtain the quadtree compressed image data. Args: image_data (np.array): The image data to compress. ground_sampling_distance (float): The ground sampling distance o...
Python
1
import socket import sys import locale import argparse def send_R_code(rcode, hostname, port): """ Evaluate the R code in `rcode` (on a possibly remote machine) """ # Create a socket (SOCK_STREAM means a TCP socket) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Connect to server ...
Python
1
from discretehelpers.a import abbrev_testing as abbrev from discretehelpers.boolf import Boolf from discretehelpers.ex import ArgMismatchError, ArgComboError def test(): f = Boolf('0') assert Boolf(fullspots=[], arity=0) == f assert Boolf(fullspots=[], arity=1) == f assert Boolf(fullspots=[], arity...
Python
1
wCardinality(String) ) ENGINE = BaseStorage PARTITION BY mod(uuid, 100000) SETTINGS a=32768, b=0"##; let pairs = BqlParser::parse(Rule::create_table, c) .unwrap_or_else(|e| panic!("{}", e)); println!("{}", pretty_parse_t...
Rust
0
1: yesterday = df.index[i] day_before_yesterday = df.index[i - 1] buy_signal = (df[f"SMA_{short_window}"].loc[yesterday] > df[f"SMA_{long_window}"].loc[yesterday] and df[f"SMA_{short_window}"].loc[day_before_yesterday] <= df[f"SMA_{long_window}"].loc[day_be...
Python
1
from manim import * import numpy as np class UnitCircleAndSine(Scene): def construct(self): # Create coordinate plane plane = NumberPlane( x_range=[-1.5, 1.5, 1], y_range=[-1.5, 1.5, 1], x_length=6, y_length=6, background_line_style={ ...
Python
1
import sys from pathlib import Path sys.path.append(str(Path(__file__).parent.parent)) import asyncio from control.coordinates import Coordinates from pathlib import Path from config.config_manager import ConfigManager from drone.drone_controller import DroneController async def sequence_test_goto(drone: DroneContro...
Python
1
_eq!(BLOCK_STRUCT.b, 0 as *const ()); assert_eq!(BLOCK_ENUM, Some(100)); assert_eq!(BLOCK_UNSAFE, 1000); // FIXME: #13970 // assert_eq!(BLOCK_FN_INFERRED(300), 300); // FIXME: #13971 // assert_eq!(BLOCK_FN(300), 300); // FIXME: #13972 // assert_eq!(BLOCK_ENUM_CONSTRUCTOR(200), Some(20...
Rust
0
} use std::collections::BTreeMap; use bitflags::bitflags; use git_repository as git; pub mod conventional { use git_repository as git; /// A message that is associated with a Segment for a particular git-conventional segment #[derive(PartialEq, Eq, Debug, Clone)] pub enum Message { User { ...
Rust
0
from test_helper import * from task import * if __name__ == '__main__': tests = [ ([5, -4, -6, 3, -2, 4, 8, 12], 3, [-4, -4, -6, -2, -2, 0]), ([-1, -2, 4, -5, -1, -3], 6, [-1]), ([-1, -2, -3, -5, -1, -3], 1, [-1, -2, -3, -5, -1, -3]), ([2, -9, 8, 1, 0, 0, 1, -2, 5, 5, 4, -7, 10, -1,...
Python
1
注意:此字段可能返回 null,表示取不到有效值。 :type UsedVip: list of str :param UnuseVip: 未使用vip 注意:此字段可能返回 null,表示取不到有效值。 :type UnuseVip: list of str """ self.SetName = None self.UsedVip = None self.UnuseVip = None def _deserialize(self, ...
Python
1
# Python bytecode 2.7 (decompiled from Python 2.7) # Embedded file name: scripts/client/gui/impl/lobby/comp7/tooltips/rank_inactivity_tooltip.py from frameworks.wulf import ViewSettings from gui.impl.gen import R from gui.impl.gen.view_models.views.lobby.comp7.tooltips.rank_inactivity_tooltip_model import RankInactivit...
Python
1
'', transform=ax.transAxes, color='white', fontsize=10) # Crear botones ax_nuke = plt.axes([0.81, 0.02, 0.1, 0.05]) ax_heal = plt.axes([0.70, 0.02, 0.1, 0.05]) button_nuke = Button(ax_nuke, 'Nuke') button_heal = Button(ax_heal, 'Heal') button_nuke.on_clicked(nuke) button_heal.on_clicked(heal) # Agregar widget Text pa...
Python
1
""" Check that `alr show` shows the same info when used outside/inside working copy """ import os from glob import glob from drivers.alr import run_alr from drivers.asserts import assert_eq def detach_origin(lines): # Return lines without "Origin:", and the origin separately # Initially the lines is simply...
Python
1
step(); } /// Is the queue empty? pub fn idle(&self) -> bool { self.current.is_none() && self.queue.peek().is_none() } /// Try to move the queue one step /// /// This will update the GPIO with the next state in the current /// pattern, or start the next pattern. If the queue is...
Rust
0
LENDMODE_BLEND as isize, Add = ll::SDL_BLENDMODE_ADD as isize, Mod = ll::SDL_BLENDMODE_MOD as isize } #[derive(Copy, Clone, PartialEq)] pub enum RendererFlip { None = ll::SDL_FLIP_NONE as isize, Horizontal = ll::SDL_FLIP_HORIZONTAL as isize, Vertical = ll::SDL_FLIP_VERTICAL as isize, } impl Render...
Rust
0
class TaskFamily: @staticmethod def get_tasks() -> dict[str, dict]: return { "1": {"content": "An advertisement for a winter clothing line", "original_context": "North America", "target_context": "Japan"}, "2": {"content": "A short story about a summer festival", "original_contex...
Python
1
ts the DMA transfer atomic::compiler_fence(Ordering::SeqCst); chan.ccr().modify(|_, w| unsafe { w.mem2mem() .clear_bit() // 00: Low, 01: Medium, 10: High, 11: Very high ...
Rust
0
<CratesResult<CratesVersion>>(&bytes)?; match crates_result { CratesResult::Ok(val) => Ok(val.version.name == package.name), CratesResult::Err { errors } => { for error in errors { println!("crates-error:\n{}", error.detail); } Ok(false) } } } async fn r...
Rust
0
#!/usr/bin/env python3 import re import functools from wxpy import * from tempfile import NamedTemporaryFile from concurrent.futures import ThreadPoolExecutor from . import meme from .logger import logger pool = ThreadPoolExecutor(100) class BotSetting: suffix_reply = True at_reply = False # TODO blackli...
Python
1
'r mut self) -> &'r mut StorageLocation<Vec<UV>> { &mut self.uvs } } /// Comutes normals from a set of faces. pub fn compute_normals_array(coordinates: &[Coord], faces: &[Face]) -> Vec<Normal> { let mut res = Vec::new(); compute_norma...
Rust
0
igmax = ig if ovmax >= self.at: tp[ip] = 1 # true gtflag[igmax] = 1 else: fp[ip] = 1 # false positive tp_arr[i_sem] = tp fp_arr[i_sem] = fp return mean_cov_arr, mean_weigh...
Python
1
; } // This example is expired by // https://scikit-learn.org/stable/auto_examples/model_selection/plot_cv_predict.html pub fn plot_cross_val_predict() { // Load Diabetes dataset let diabetes_data = diabetes::load_dataset(); let x = DenseMatrix::from_array( diabetes_data.num_samples, diabet...
Rust
0
q!(tree.get_leaf(1), Some(HashOf::from_hash(Hash([2; 32])))); assert_eq!(tree.get_leaf(2), Some(HashOf::from_hash(Hash([3; 32])))); assert_eq!(tree.get_leaf(3), None); } #[test] fn add() { let tree = vec![Hash([1_u8; 32]), Hash([2_u8; 32]), Hash([4_u8; 32])] .into_iter()...
Rust
0
""" 消息管理模块 管理每个聊天流的上下文信息,包含历史记录和未读消息,定期检查并处理新消息 """ import asyncio import random import time from collections import defaultdict, deque from typing import TYPE_CHECKING, Any from src.chat.chatter_manager import ChatterManager from src.chat.message_receive.chat_stream import ChatStream from src.chat.planner_actions.ac...
Python
1
(1), Const(0)) } fn sqrt_addition(v: u32) -> Addition { Addition(Sqrt::new(v), Const(0)) } fn sqrt_times(v: u32) -> Times { Times(Const(1), sqrt_addition(v)) } pub fn sqrt(v: u32) -> Fraction { Fraction(sqrt_times(v), one()) } pub fn fraction(a: i32, b: i32) -> Fraction { Fraction(Times(Const(a), on...
Rust
0
critical, so you should call this _immediately_ after the /// vblank interrupt (every 1/60th of a second). #[inline(always)] pub fn sound_driver_vsync() { #[cfg(not(all(target_vendor = "nintendo", target_env = "agb")))] { unimplemented!() } #[cfg(all(target_vendor = "nintendo", target_env = "agb"))] { ...
Rust
0
unique_masks=False, debug=False, noise_type='uniform', train_masks=False, mix_maps=None): return CifarNet(nfilters=nfilters, nclasses=nclasses, nmasks=nmasks, level=level, filter_size=filter_size, pool_type=pool_type, scale_noise=scale_noise, act=act, use_act=use_act, first_filter_size=first_...
Python
1
mask_a1 | mask_a2)) b_masked3 = np.ma.masked_array(b, mask=(mask_b1 | mask_b2)) with np.testing.suppress_warnings() as sup: message = 'invalid value encountered' sup.filter(RuntimeWarning, message) res = func(a_nans, weights=b_nans, nan_policy="omit", axis=axis) res1 = func(a_ma...
Python
1
标签的字体大小为25号 self.text_label_cheat_state.setFont(QFont(self.text_label_cheat_state.font().family(), 25)) # 设置文本标签的背景颜色 self.text_label_cheat_state.setAutoFillBackground(True) # 9个按钮上面的调试文本 self.text_label_5 = QLabel() # 文本内容设置为“系统执黑棋” self.text_label_5.setText("当...
Python
1
tVAE.pth → Place in: ComfyUI/models/vae/ layerlora.safetensors: https://huggingface.co/RedAIGC/Flux-version-LayerDiffuse/blob/main/layerlora.safetensors → Place in: ComfyUI/models/loras/ 2. Flux Model: Download any Flux.1-dev model → Place in: ComfyUI/models/diffusion_models/ 3. Basic Workflow: ...
Python
1
let from = get_pair_from_str(arg_from); let to = get_accountid_from_str(arg_to); info!("from ss58 is {}", from.public().to_ss58check()); info!("to ss58 is {}", to.to_ss58check()); let _api = api.clone().set_signer(sr25519_core::Pair::from(from)); let tx_hash = ma...
Rust
0
cgg': 'Urugwai', 'chr': 'ᏳᎷᏇ', 'ckb': 'ئوروگوای', 'cs': 'Uruguay', 'cv': 'Уругвай', 'cy': 'Uruguay', 'da': 'Uruguay', 'dav': 'Urugwai', 'de': 'Uruguay', 'dje': 'Uruguwey', 'dsb': 'Uruguay', 'dz': 'ཡུ་རུ་གུ་ཝའི', 'ebu': 'Urugwai', 'ee': 'uruguaydukɔ', 'el': 'Ουρουγουάη', 'el-polyton': 'Οὐρουγουάη', 'en': 'Uruguay', 'en-...
Python
1
language_args(languages or [], ocr_languages) or ["eng"] return partition_pdf_or_image( filename=filename, file=file, is_image=True, include_page_breaks=include_page_breaks, infer_table_structure=infer_table_structure, languages=languages, strategy=strategy, ...
Python
1
""" 仪表盘服务模块 @author: pgao @date: 2024-03-13 """ from sqlalchemy import func, case, text, select, desc, and_ from sqlalchemy.orm import Session from sqlalchemy.exc import SQLAlchemyError from datetime import datetime, timedelta, date from typing import List, Dict, Any, Tuple, Optional, Union, Callable import traceback ...
Python
1
(!on_same_side(PLAYER_W, BP)); assert!(!on_same_side(PLAYER_B, WK)); assert!(!on_same_side(PLAYER_B, WQ)); assert!(!on_same_side(PLAYER_B, WR)); assert!(!on_same_side(PLAYER_B, WB)); assert!(!on_same_side(PLAYER_B, WN)); assert!(!on_same_side(PLAYER_B, WP)); } } use ...
Rust
0
let manifest = lal::Manifest::read(&component_dir)?; lal::list::configurations(&manifest.name.to_string(), &manifest) } pub fn list_buildables(component_dir: &Path) -> lal::LalResult<()> { let manifest = lal::Manifest::read(&component_dir)?; lal::list::buildables(&manifest) } <filename>src/query/queryutil....
Rust
0
from langgraph.graph import START, END, StateGraph from langgraph.types import interrupt, Command from langgraph.checkpoint.memory import MemorySaver from pydantic import BaseModel from dotenv import load_dotenv load_dotenv() class State(BaseModel): itinerary: str user_feedback: str def generate_main_itiner...
Python
1
import requests symbol = 'EGLD' def calculate_profit(symbol): # Получаем стаканы котировок с двух бирж (Bitmart и Mexc) URL1 = f"https://api.mexc.com/api/v3/depth?symbol={symbol}USDT&limit=10" URL2 = f"https://api-cloud.bitmart.com/spot/v1/symbols/book?symbol={symbol}_USDT&depth=10" response1 = reques...
Python
1
non_accent.strip(): return True count = 0 lst_words = sentence.split() lst_words_no_accent = sentence_non_accent.split() # Count the number of words in lst_words_no_accent. for index, word in enumerate(lst_words): # count of words in lst_words_no_accent. ...
Python
1
curr_time); for vertex in dual_graph.into_iter() { if vertex.timestamp != usize::max_value() { let mut chull = vertex.chull.unwrap(); denormalize(&mut chull, &center, diag); result.push(chull); parts.push(vertex.parts.unwrap()); } } (result...
Rust
0
or hhvm_types_ffi::Attr { fn from(k: Visibility) -> Self { match k { Visibility::Private => Self::AttrPrivate, Visibility::Public => Self::AttrPublic, Visibility::Protected => Self::AttrProtected, // TODO(T115356820): Decide whether internal should be mutually...
Rust
0
: return None self._doc = BeautifulSoup(html, features="html5lib") return self._doc def select(self, css_selector): soup = self.doc return soup.select(css_selector) @property def html(self): # cache if self._html is not None: return s...
Python
1
p.bump(SyntaxKind::union_KW); let mut meets_requirements = false; match p.peek() { Some(TokenKind::Name) => name::name(p), _ => p.err("expected a Name"), } if let Some(T![@]) = p.peek() { meets_requirements = true; directive::directives(p); } if let Some(T![=...
Rust
0
from ..tools import arg_tools def add_args(parser): parser.add_argument('--attn-query-proj-bias', type=arg_tools.str_bool_with_default_error) parser.add_argument('--attn-key-proj-bias', type=arg_tools.str_bool_with_default_error) parser.add_argument('--attn-value-proj-bias', type=arg_tools.str_bool_with_d...
Python
1
am.info/api/address/" + str(caddr)) balance = float(response.json()['chain_stats']['funded_txo_sum']) totalSent = float(response.json()['chain_stats']['spent_txo_sum']) txs = response.json()['chain_stats']['funded_txo_count'] #uaddr = ice.privatekey_to_address(0, False, dec) HEX = "%064x" % dec ...
Python
1