text
string
label_name
string
labels
int64
import json import streamlit as st from PIL import Image from difflib import get_close_matches import webbrowser class ChatBotUI: def __init__(self, knowledge_base_file="knowledge_base.json"): self.knowledge_base_file = knowledge_base_file self.knowledge_base = self.load_knowledge_base() ...
Python
1
import logging from allennlp.common.util import JsonDict, sanitize from allennlp.data.dataset_readers.dataset_reader import DatasetReader from allennlp.data.instance import Instance from allennlp.models.model import Model from allennlp.service.predictors.predictor import Predictor from overrides import overrides logg...
Python
1
t = 'Total count : ' output += ('%s\n' % (str(num))) click.echo(output) @vxlan.command() @click.argument('remote_vtep_ip', required=True) @click.argument('count', required=False) def remotemac(remote_vtep_ip, count): """Show MACs pointing to the remote VTEP""" if (remote_vtep_ip != 'all') and (cli...
Python
1
map(|(i, _, _)| va_base + i as umem * x64::ARCH.page_size() as umem) .ok_or_else(|| { Error(ErrorOrigin::OsLayer, ErrorKind::ProcessNotFound) .log_trace("unable to locate ntoskrnl.exe") }) } pub fn find<T: MemoryView + VirtualTranslate>( virt_mem: &mut T, start_block...
Rust
0
loatX) elif ndim == 2: latent_sample = T.matrix('sample') latent_sample.tag.test_value = np.zeros( (self.exprs['inpt'].tag.test_value.shape[0], self.n_latent)).astype(theano.config.floatX) else: raise ValueError('unexpected ndim for sa...
Python
1
if catalog.fuzzy and not self.use_fuzzy: continue log.info('writing JavaScript strings in catalog %r to %r', po_file, js_file) jscatalog = {} for message in catalog: if any(x[0].endswith('.js') for x in message.locati...
Python
1
oder_for_enum_struct(name, ident, fields, prefix, false, sizer, header_size) }, Fields::Unit => { if sizer { quote! { &#name::#ident => { #header_size } } } else { ...
Rust
0
't be downloaded. But it may not work as expected." )] yolo: bool, }, #[clap(about = "Create project from the template")] Template(Template), } #[derive(Debug, Args)] struct Template { #[clap(subcommand)] command: TemplateCommands, } #[derive(Debug, Subcommand)] enum TemplateCommand...
Rust
0
return TestResult::passed(), _ => { println!( "\n\nLHS: {:?}\nRHS: {:?}\nMLHS: {:?}\nMRHS: {:?}\nRES: {:?}\nEXPECTED: {:?}\nVAL: {:?}", lhs, rhs, old_mlhs, ...
Rust
0
def print_board(board): # Function to print the current state of the board for row in board: print(" ".join(map(str, row))) print() def find_blank(board): # Function to find the position of the blank space (0) on the board for i in range(3): for j in range(3): if board[i...
Python
1
ULA_TOOTH_FIND) .args(&[x, "-name", "*.la", "-delete"]) .spawn() .unwrap() .wait() .unwrap(); } pub fn radula_behave_bootstrap_environment() { let x = &fs::canonicalize("..").unwrap(); env::set_var(constants::RADULA_ENVIRONMENT_DIRECTORY_GLAUCUS, x); env::set_var( ...
Rust
0
s fig.update_xaxes( showgrid=True, gridwidth=0.8, gridcolor='rgba(180,180,180,0.4)', zeroline=True, zerolinewidth=1, zerolinecolor='rgba(100,100,100,0.6)' ) fig.update_yaxes( ...
Python
1
IS0[nTimeIndex2,:,:]).max()<0.00001: TMin.append(999.0) TMax.append(0.0) else: TMin.append(MODIS0[nTimeIndex2,MODIS0[nTimeIndex2,:,:]>0].min() - dtl/2) # minus/plus half of the matching window time TMax.append(MODIS0[nTimeIndex2,MODIS0[nTimeIndex2,:,:]>0].max() + dtl/2) count = 0 f...
Python
1
etsGroupAccessTypeChoices.TYPE_HTTP, secret_type=SecretsGroupSecretTypeChoices.TYPE_TOKEN, ) librenms_api = LibreNMSApi( url=self.librenms_server.remote_url, port=port, token=token, verify=self.librenms_server.verify_ssl, ) self...
Python
1
!(&replica.transport[1].is_empty()); assert_eq!( &[Command::Reject { payload: (4, Ballot(0, 2), Ballot(1, 0)) }], &replica.transport[2] ); assert!(&replica.transport[3].is_empty()); assert!(replica.window.decisions().is_empty()); } #[test] fn node_pr...
Rust
0
out: MAXDWORD, ReadTotalTimeoutMultiplier: 0, ReadTotalTimeoutConstant: 0, WriteTotalTimeoutMultiplier: 0, WriteTotalTimeoutConstant: 0, } }; let timeout_read_ms: DWORD = if let Some(dur) = timeout { let mut dur_ms = dur.as_secs() * 1000 + dur.subsec_millis() as u64; if d...
Rust
0
""" Métodos da STRING: .split(): só separa a string quando encontra exatamente (vírgula e espaço) (geralmente retorna uma list) OBS.: esse método NÃO altera a string original, se a string original NÃO tiver o separador, ele não vai fazer nada - usar SEM argumento (): ele vai preencher o ...
Python
1
(&src_path, &dst_path)?; } Ok(()) } #[cfg(target_os = "windows")] fn create_dir_symlink(src_path: &Path, dst_path: &Path) -> io::Result<()> { os::windows::fs::symlink_dir(&src_path, &dst_path) } #[cfg(not(target_os = "windows"))] fn create_dir_symlink(src_path: &Path, dst_path: &Path) -> io::Result<()> {...
Rust
0
#----------------------------------------------------------------------------- # Copyright (c) 2012 - 2023, Anaconda, Inc., and Bokeh Contributors. # All rights reserved. # # The full license is in the file LICENSE.txt, distributed with this software. #-------------------------------------------------------------------...
Python
1
#[derive(PartialEq)] //~ ERROR: `derive` may only be applied to structs, enums and unions trait T { } #[derive(PartialEq)] //~ ERROR: `derive` may only be applied to structs, enums and unions impl S { } #[derive(PartialEq)] //~ ERROR: `derive` may only be applied to structs, enums and unions impl T for S { } #[deriv...
Rust
0
mock_playwright.return_value.start = AsyncMock( return_value=mock_playwright_instance ) mock_playwright_instance.chromium.launch.return_value = mock_browser mock_browser.new_page.return_value = mock_page async with AvailabilityPoller(mock_config) as p...
Python
1
".to_vec()).unwrap().into_bytes_with_nul() }, value ); ``` # update Specify custom code to run on the field when `.update()` is called on the struct/enum Example: ```rust use deku::prelude::*; use std::convert::{TryInto, TryFrom}; #[derive(Debug, PartialEq, DekuRead, DekuWrite)] struct DekuTest { #[deku...
Rust
0
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025) # # 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...
Python
1
import time from appium import webdriver from typing import Any, Dict from appium.options.common import AppiumOptions from appium.webdriver.common.appiumby import AppiumBy cap:Dict[str, Any]={ "platformName": "android", "automationName": "UIAutomator2", "deviceName": "android", # "appPackage": "com.an...
Python
1
::__Unknown(value), } } } impl ErrorDomain for TlsError { fn domain() -> Quark { unsafe { from_glib(ffi::g_tls_error_quark()) } } fn code(self) -> i32 { self.into_glib() } fn from(code: i32) -> Option<Self> { match code { ffi::G_TLS_ERROR_UNAVAILABL...
Rust
0
e)) => ParseResult(i, Err(e)), } } /// Applies the function `f` on the contained error if the parser is in an error state. /// /// # Example /// /// ``` /// use chomp::prelude::{Input, parse_only}; /// /// let r = parse_only(|i| i.err::<(), _>("this is") /// .ma...
Rust
0
er_width=True) # build / load vector index with st.spinner("🔨 Preparing vector index …"): index = build_or_load_index(df) retriever = index.as_retriever(similarity_top_k=5) # NL query st.subheader("🔍 Ask a question") user_q = st.text_input("e.g. “Which vendor has the highest total?”"...
Python
1
tems[1], ScopeItem::Var(Var { var_type: VarType::Event, size: 1, code: 0u32.into(), reference: "smt_clock".into(), index: None, }) ); let scope = match &header.items[2] { ScopeItem::Scope...
Rust
0
# plot_value.py - tare the sensor then read_value(). Send elapse_time_ms + coma + read_value() to REPL output. # Wait for a minimal value on the sensor to output data. # Script is halted when values fallback under the minimal value. # Pico LED (GPIO25) Lits while logging...
Python
1
color_from_triplet("Green Kelp", (37, 49, 28)), color_from_triplet("Curious Blue", (37, 150, 209)), color_from_triplet("Paua", (38, 3, 104)), color_from_triplet("Paris M", (38, 5, 106)), color_from_triplet("Wood Bark", (38, 17, 5)), color_from_triplet("Gon...
Rust
0
data.iloc[i] cate = item['category'] tot['Overall'] += 1 tot[cate] += 1 if item['log'] == 'Prefetch succeed': fetch['Overall'] += 1 fetch[cate] += 1 if post_check(item, prefetch=False): hit['Overall'] += 1 hit[cate] += 1 res =...
Python
1
table files, no memo<br/>0x63 dBASE IV SQL system files, no memo<br/>0x83 FoxBASE+/dBASE III PLUS, with memo<br/>0x8B dBASE IV with memo<br/>0xCB dBASE IV SQL table files, with memo<br/>0xF5 FoxPro 2.x (or earlier) with memo<br/>0xE5 HiPer-Six format with SMT memo file<br/>0xFB FoxBASE | /// | 1 - 3 | La...
Rust
0
r pub format: AudioFormat, pub channels: u8, pub silence: u8, pub samples: u16, pub size: u32 } impl AudioSpec { fn convert_from_ll(spec: ll::SDL_AudioSpec) -> AudioSpec { AudioSpec { freq: spec.freq, format: spec.format, channels: spec.channels, ...
Rust
0
location2.transform.location # 找到与当前后车位置最近的队列元素索引 (Find the index of the waypoint closest to the ego vehicle) if len(env.e2f_waypoints_queue) > 2: distances = [current_location2.transform.location.distance(wp.transform.location) for wp in env.e2f_way...
Python
1
from django.shortcuts import render from django.http import HttpResponse def captain(request): return HttpResponse('<h1> RCB Captain is VIRAT KOHLI </h1>') def vice_captain(request): return HttpResponse('<h1> RCB Vice Captain is RAJAT PATIDAR </h1>') def wicket_keeper(request): return HttpResponse('<h1>...
Python
1
# ruff: noqa def test_aliases(): """ make sure that the now deprecated ability to import from top level module isn't completely broken """ from gmft import Rect from gmft import ( TATRFormattedTable, AutoFormatConfig, AutoTableFormatter, CroppedTable, ...
Python
1
WIPOffset<flatbuffers::Vector<'a , u32>>>, pub lemmas: Option<flatbuffers::WIPOffset<flatbuffers::Vector<'a , H256>>>, } impl<'a> Default for MerkleProofArgs<'a> { #[inline] fn default() -> Self { MerkleProofArgs { indices: None, lemmas: None, } } } pub struct Me...
Rust
0
ja: releaseDir = os.path.join(srcpath, 'out', mode) else: releaseDir = os.path.join(srcpath, 'out', mode) # issue(16760) - we _need_ to fix our parsing of the FILES.cfg extra_files = [file for file in os.listdir(releaseDir) if file.endswith('manifest')] else: raise Exception('Unsupported p...
Python
1
Error::InvalidOperand); }, 0b0110 => (0, Deref_A0), 0b0111 => (0, Deref_A1), 0b1000 => (1, Disp8_A0), 0b1001 => (1, Disp8_A1), 0b1010 => (1, Disp8_SB), 0b1011 => (1, Disp8_FB), 0b1100 => (3, Disp20_A0), 0b1101 => (3, Disp20_A1), 0b1110 => (2, Disp1...
Rust
0
WriteCount: [u8; 16], } impl ::core::marker::Copy for STORAGE_ENDURANCE_INFO {} impl ::core::clone::Clone for STORAGE_ENDURANCE_INFO { fn clone(&self) -> Self { *self } } #[repr(C)] #[doc = "*Required features: `\"Win32_Storage_IscsiDisc\"`*"] pub struct STORAGE_ENDURANCE_INFO_0 { pub _bitfield: u32...
Rust
0
x_offset } fn render_effect_column(mut imgbuf: &mut image::ImageBuffer<image::Rgba<u8>, Vec<u8>>, effect_column: &Option<super::renoise::EffectColumn>, highlighted: bool, x: u32, x_offset: u32, y: u32) -> u32 { let empty_str_fx = &String::from(" "); let mut x_offset = x_offset; match effect_column { ...
Rust
0
ignmentMissing))?; let c = cs.new_input_variable(|| { let a = self.a.ok_or(SynthesisError::AssignmentMissing)?; let b = self.b.ok_or(SynthesisError::AssignmentMissing)?; Ok(a * b) })?; for _ in 0..self.num_constraints { cs.enforce_constraint(lc!() + a, lc!() + b, lc!() + c)?; } Ok(()) } } #[c...
Rust
0
# Copyright (C) 2017-2019 Linaro Limited # # Author: Neil Williams <neil.williams@linaro.org> # Remi Duraffort <remi.duraffort@linaro.org> # # SPDX-License-Identifier: GPL-2.0-or-later import grp import logging import logging.handlers import os import pwd from django.core.management.base import BaseCommand ...
Python
1
import os def get_data_path(Fpath, Access='img'): if Access == 'video': video_num = 1 videoRootpaths = Fpath videoName = os.listdir(videoRootpaths) videoFpaths = [] labels = os.listdir(videoRootpaths) for label in labels: video = [] file_names...
Python
1
en) arr_sato_velocity_mean_canny = run_canny(arr_sato_velocity_mean_screen_nor, sigma_canny) arr_sato_velocity_holes_label, arr_sato_velocity_holes_label_number = fill_holes_and_label(arr_sato_velocity_mean_canny) arr_sato_velocity_holes_label = filter_regions(arr_sato_velocity_holes_label) holes_label_...
Python
1
N_GAMMA_RAMP, } impl ::core::marker::Copy for PANEL_GET_BACKLIGHT_REDUCTION {} impl ::core::clone::Clone for PANEL_GET_BACKLIGHT_REDUCTION { fn clone(&self) -> Self { *self } } #[repr(C)] #[doc = "*Required features: 'Win32_Devices_Display'*"] pub struct PANEL_GET_BRIGHTNESS { pub Version: BRIGHTNES...
Rust
0
elf, *args, **kwargs): super().__init__(*args, **kwargs) if getattr(self.instance, "pk", None): self.fields["post"].disabled = True form = Form @admin.register(ProjectIndex) class ProjectIndexAdmin(admin.ModelAdmin): list_display = ["id", "type", "increasing_is_good"] ...
Python
1
) text = cmd[sepp+1:] except Exception as e: misc.addLog(rpieGlobals.LOG_LEVEL_ERROR,"Parameter error: "+str(e)) return False if x>0: x -= 1 if y>0: y -= 1 try: if self.device is not None: draw = ImageDraw.Draw(self.dispimage) resstr = self.oledparse(text) draw.text...
Python
1
cell } } impl<C> ::std::ops::DerefMut for GlyphCache<C> { fn deref_mut<'a>(&'a mut self) -> &'a mut RefCell<C> { &mut self.ref_cell } } <gh_stars>1-10 //! This module contains all decode functions for this crate. use crate::{ Addr, AnonymizedDnsCryptRelay, DecodeError, DecodeResult, DnsCrypt, D...
Rust
0
}; use types::Offset32; use std::collections::HashMap; use std::convert::TryFrom; use super::GlyphId; /// This table defines mapping of character codes to a default glyph index. Different subtables may /// be defined that each contain mappings for different character encoding schemes. The table /// header indicates th...
Rust
0
Register"] pub mod lradc_intc; #[doc = "LRADC_INTS register accessor: an alias for `Reg<LRADC_INTS_SPEC>`"] pub type LRADC_INTS = crate::Reg<lradc_ints::LRADC_INTS_SPEC>; #[doc = "LRADC Interrupt Status Register"] pub mod lradc_ints; #[doc = "LRADC_DATA register accessor: an alias for `Reg<LRADC_DATA_SPEC>`"] pub type...
Rust
0
under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the...
Rust
0
) if isinstance(args[1], int): # number of anchors args[1] = [list(range(args[1] * 2))] * len(f) elif m is Contract: c2 = ch[f] * args[0] ** 2 elif m is Expand: c2 = ch[f] // args[0] ** 2 else: c2 = ch[f] m_ = nn.Sequentia...
Python
1
)* #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, Deserialize, Serialize)] pub struct $Id(Snowflake); impl Display for $Id { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { Display::fmt(&self.0, f) } } impl ...
Rust
0
let retrieval_future = sp.tuple_in(tuple![E::str("foo"), E::Any]); let retrieval_result = executor::block_on(retrieval_future); match retrieval_result { Some(ref t) => assert_eq!(t, &tuple![E::str("foo"), E::I(42)]), a => assert!(false, "{:?}", a), }; } /* * Copyright (C) 2019 Kubos Co...
Rust
0
' &larr; '), ('<=>', ' &hArr; '), ('==>', ' &rArr; '), ('<==', ' &lArr; '), ('-', ' &minus; '), ('*', ' &sdot; '), ('\\cdot', ' &sdot; '), ('+', ' + '), ('/', '/'), (':=', ' := '), ('%', ' mod '), (r'\in', '&isin;'), (r'\notin', '&notin;...
Python
1
(Value::$kind(a), Value::$kind(b)) => Ok(Value::$kind(a.$func(b))), _ => Err(crate::error::Error::TypeMismatch(line!())), } }; } gen_binop! { $($tail)* } }; ($(,)? $name:ident => [$op:tt] $($tail:tt)*) => { #[macro_export] macro_...
Rust
0
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright 2012 - 2013 # Matías Herranz <matiasherranz@gmail.com> # Joaquín Tita <joaquintita@gmail.com> # # https://github.com/PyRadar/pyradar # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public #...
Python
1
"attr3": [], "attr4": {}, "attr5": { "subattr1": "value1", "subattr2": ["item1"], "subattr3": "value1", }, }, to_update, ) # dict value (remove and modify) to_upd...
Python
1
dowExt>(&self, win: &W, x_offset: i32, y_offset: i32) { unsafe { Fl_Image_Surface_draw_decorated_window( self._inner, win.as_widget_ptr() as *mut _, x_offset, y_offset, ) } } } impl Drop for ImageSurface { f...
Rust
0
_00B7, 0x1100_0001,// VEX_Vpsllvd_xmm_xmm_xmmm128 0x0000_00B7, 0x1100_0001,// VEX_Vpsllvd_ymm_ymm_ymmm256 0x0000_00B7, 0x1100_0001,// VEX_Vpsllvq_xmm_xmm_xmmm128 0x0000_00B7, 0x1100_0001,// VEX_Vpsllvq_ymm_ymm_ymmm256 0x0000_00B7, 0x2D00_0002,// EVEX_Vpsllvd_xmm_k1z_xmm_xmmm128b32 0x0000_00B7, 0x2D00_0002,// EVEX_...
Rust
0
ed".format(frontend.name, frontend.mode) ) # If Requested State is 'present' and Instance don't exists if not existing_frontend and state == 'present': # Create Instance create_frontend( module=module, client=client, transaction_id=transaction_id, ...
Python
1
capacity`] pub fn decode(compressed: &[u8], num_bits: u8, decompressed: &mut [u32]) -> usize { let bitpacker = BitPacker1x::new(); let compressed_block_size = BitPacker1x::BLOCK_LEN * num_bits as usize / 8; let compressed_chunks = compressed.chunks_exact(compressed_block_size); let decompressed_chunks...
Rust
0
mod serde_multi; use derive_more::Constructor; use prost::Message; use tentacle::{bytes::Bytes, SessionId}; use crate::{ endpoint::Endpoint, error::{ErrorKind, NetworkError}, }; #[derive(Constructor)] pub struct RawSessionMessage { pub(crate) sid: SessionId, pub(crate) msg: Bytes, } #[derive(Message...
Rust
0
p_derivedfrom = p_original .derived_from .as_ref() .and_then(|s| all_peripherals.iter().find(|x| x.name == *s)); let p_merged = p_derivedfrom.map(|ancestor| p_original.derive_from(ancestor)); let p = p_merged.as_ref().unwrap_or(p_original); if let (Some(df), None) = (p_original.de...
Rust
0
-03-13 01:59:59", 1300010399), ("America/Los_Angeles", "2011-03-13 03:00:00", 1300010400), // ("America/Los_Angeles", "2011-11-06 01:59:59", 1320569999), // ambiguous ("America/Los_Angeles", "2011-11-06 02:00:00", 1320573600), ("America/Toronto", "2013-11-18 11:55:00", 13...
Rust
0
# ============================== # Conversión de fecha y hora # ============================== import datetime from datetime import datetime def convertirDate(fecha): """ Convierte una cadena de fecha en formato 'dd/mm/yy' a un objeto datetime.date. """ nfecha = datetime.strptime(fecha, "%d/%m/%y")....
Python
1
results['memory_stress'] = self._test_multi_gpu_memory_stress_comprehensive() print("⏳ 等待3秒...") time.sleep(3) # 压力测试 (多GPU版本) print("\n" + "="*60) results['stress_test'] = self._test_multi_gpu_stress_test(3) print("⏳ 等待3秒...") time.sleep(3) ...
Python
1
__all__ = ['regular_cube_mesh'] from numpy import array,asarray,hstack,vstack,arange,zeros,ndim class regular_cube_mesh: """ A regular grid of hypercubes. Examples: # create a 2x2 cube mesh bitmap = ones((2,2),dtype='bool') c_mesh = regular_cube_mesh(bitmap) # creates ...
Python
1
grid < 1000 else "(unconstrained)" ) title += f"\nScaling: min={indiv_scaling_min:.0f}, max={indiv_scaling_max:.0f} {scaling_source}" elif rescale_reward == False: title += ( f"\nNo rescaling. min={indiv_scaling_min:.0f}, max={indiv_scaling_max:.0f}" ) pl...
Python
1
ue", s=1, marker="s") for worker in bees_swarm.workers: ax.scatter(worker[0], worker[1], worker[2], c="black", s=1, marker="s") b = bees_swarm.get_best() ax.scatter(b[0], b[1], b[2], c="red") canvas.draw() window.update() def make_square(x, y, rad, func): ...
Python
1
e_to_numpy=False, coerce_to_pandas=False, ): """Validate input data. Parameters ---------- X : pd.DataFrame y : pd.Series or np.array enforce_univariate : bool, optional (default=False) Enforce that X is univariate. enforce_min_instances : int, optional (default=1) Enfor...
Python
1
ch?v=5XK4v2fgMPU", "Fecha_lanzamiento": "2018-10-05" }, { "Tema": "Stupid Love", "Vistas": "300 millones", "Duracion": "3:13", "Link_youtube": "https://www.youtube.com/watch?v=5L6xyaeiV58", "Fecha_lanzamiento": "2020-02-28" }, { "Tema": "Ariana Gra...
Python
1
) -> io::Result<()> { Cmd::PropValueInsert.try_pack(buffer)?; self.0.try_pack(buffer)?; self.1.try_pack(buffer)?; Ok(()) } fn on_response( self, response: Result<SpinelFrameRef<'_>, Canceled>, ) -> Result<Self::Result, Error> { let frame = response?; ...
Rust
0
:new(time::time_us() as u64); let mut terrain = [0; WIDTH]; let w = WIDTH as f32; let off0 = rng.rand_float() * 100.0; let off1 = rng.rand_float() * 100.0; let freq0 = rng.rand_float() * 100.0; let freq1 = rng.rand_float() * 100.0; let scale0 = rng.rand_float(); let scale1 = rng.rand_flo...
Rust
0
erify the correctness of a password by generating the //! hash again yourself, and naively comparing the newly calculated hash with the stored hash. This //! opens the door to [timing attacks](https://en.wikipedia.org/wiki/Timing_attack). The //! [`store_password]/[`verify_password`] API is designed to prevent this: [`...
Rust
0
"HtmlFile": r"""Creates a HtmlFile object from a BytesIO object. Args: file (BytesIO): A BytesIO object representing the contents of the html file. filename (str): The name of the file. Returns: HtmlFile: A HtmlFile object. """ ...
Python
1
.file) } } } impl AsyncRead for PtyMasterRead { fn poll_read( self: Pin<&mut Self>, cx: &mut Context, buf: &mut [u8], ) -> Poll<Result<usize, io::Error>> { self.get_file().poll_read(cx, buf) } } impl AsRawFd for PtyMaster { fn as_raw_fd(&self) -> RawFd { sel...
Rust
0
_CONVERGENCE, EIGEN_ITERATIONS) .and_then(|m| { // We need to sort the eigenvectors by their corresponding eigenvalue. let mut sources = [0, 1, 2, 3, 4, 5, 6, 7, 8]; sources.sort_unstable_by_key(|&ix| float_ord::FloatOrd(m.eigenvalues[ix])); let mut nullspace = Nu...
Rust
0
tion() test_edge_cases() logger.info("\n" + "=" * 50) logger.info("RESUMEN DE PRUEBAS:") logger.info("✅ Extractor de JSON robusto implementado") logger.info("✅ Validación de estructura específica para WhisPad") logger.info("✅ Manejo de casos extremos y errores") logger.info("✅ Compatibl...
Python
1
(config: Config) -> MyResult<()> { let amount = config.amount; let pennies: Vec<Coin> = (0..=amount).map(Coin::Penny).collect(); let nickels: Vec<Coin> = (0..=(amount / 5)).map(Coin::Nickel).collect(); let dimes: Vec<Coin> = (0..=(amount / 10)).map(Coin::Dime).collect(); let quarters: Vec<Coin> = ...
Rust
0
as_ptr(&self) -> *const T { self.2[..].as_ptr() } #[inline] fn as_mut_ptr(&mut self) -> *mut T { (&mut self.2[..]).as_mut_ptr() } } } <gh_stars>0 use bevy::{prelude::*, sprite::collide_aabb::collide}; use bevy_ecs_ldtk::prelude::*; use crate::stats::{SkinCo...
Rust
0
../gir-files (@ 38b7451) // DO NOT EDIT #![allow(non_camel_case_types, non_upper_case_globals, non_snake_case)] #![allow(clippy::approx_constant, clippy::type_complexity, clippy::unreadable_literal, clippy::upper_case_acronyms)] #![cfg_attr(feature = "dox", feature(doc_cfg))] use gdk_pixbuf_sys as gdk_pixbuf; use gio...
Rust
0
# django environ import environ # system environ from os import environ as osenv import os from dotenv import load_dotenv, find_dotenv # ======== GLOBAL SETTINGS ======== # BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) BASE_DIR = os.getcwd() print(f'>>> CWD: {BASE_DIR} <<<') # ======== GENE...
Python
1
import os.path as Pathing import os as OS import torch from diffusers import StableDiffusionPipeline as Pipeline import torch as Engine # !需要完全地面向对象传值 # ·Stable Diffusion Web UI使用ldm Library读取Model,超出本项目的需求,直接恢复PyTorch直读 class Model: # Field ListModel = [ ] Model_Activated=None # !需要转为Private Directory_Diffusi...
Python
1
, obj_type: FindType) -> Result<u64, String> where T: FindObject { let find_text = &args[a_index]; let obj_name = match obj_type { FindType::Channel => "channel", FindType::Role => "role", FindType::User => "user" }; let mut matched_objects: Vec<(u64, String)> = Vec::new(); ...
Rust
0
T::Id => "id", T::Key => "key", T::Label => "label", T::Value => "value", }; Ok(json!({ "@type" : "g:T", "@value" : v })) } (_, GV...
Rust
0
_realm_data_for_authority}; /// Processes SetRealmAuthority instruction pub fn process_set_realm_authority( program_id: &Pubkey, accounts: &[AccountInfo], new_realm_authority: Option<Pubkey>, ) -> ProgramResult { let account_info_iter = &mut accounts.iter(); let realm_info = next_account...
Rust
0
, 0.0, 0.0]), }, mass: 1.0, }, dt: 0.5, target_planet: MOON, target_orientation: (1.0, [1.0, 0.0, 0.0]), }; let max_depth = 10; let eps_depth = 0.0; let mut settings = AiSettings::new(max_depth, eps_depth); settings.analysis = true; settin...
Rust
0
t}; use core::mem::size_of; let ptr = DescriptorTablePointer { base: self as *const _ as u64, limit: (size_of::<Self>() - 1) as u16, }; unsafe { lidt(&ptr); } } } <filename>examples/basic.rs use easy_error::{ensure, ResultExt, Terminator}; use std...
Rust
0
, 5]; let y = [42, 0, 0, 0, 0]; let z = [41, 3, 3, 4, 5]; assert!(add_le(&mut x, &y).is_ok()); assert!(!x.iter().all(|x| *x == 0)); assert_eq!(x, z); let mut x = [255, 255, 3, 4, 5]; let z = [41, 0, 4, 4, 5]; assert!(add_le(&mut x, &y).is_ok()); as...
Rust
0
y::IShellItemArrayVT; pub use super::itaskbarlist::ITaskbarListVT; pub use super::itaskbarlist2::ITaskbarList2VT; pub use super::itaskbarlist3::ITaskbarList3VT; pub use super::itaskbarlist4::ITaskbarList4VT; } // Copyright (c) The Starcoin Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::{...
Rust
0
Ok(d.map_encoded_cnum_to_current(cnum)) } } impl<'a, 'tcx> Decodable<DecodeContext<'a, 'tcx>> for DefIndex { fn decode(d: &mut DecodeContext<'a, 'tcx>) -> Result<DefIndex, String> { Ok(DefIndex::from_u32(d.read_u32()?)) } } impl<'a, 'tcx> FingerprintDecoder for DecodeContext<'a, 'tcx> { f...
Rust
0
ansfer { pub file_type: FileType, pub data: Vec<u8>, } use crate::*; /// Dictates whether a cylinder is open ended /// or has closed ends. #[derive(Debug, Copy, Clone, PartialEq)] pub enum CylKind { Open, Closed, } /// Creates an infinitely long open cylinder whose length extends along the y-axis, /...
Rust
0
tuirealm = "^1.0.0" //! ``` //! //! If you're not using the default features, be sure to enable the **derive** feature: //! //! ```toml //! [dependencies] //! tuirealm = { version = "^1.0.0", default-features = false, features = ["derive", "with-termion"] } //! ``` //! //! Then you need to include tuirealm in your proj...
Rust
0
from colorama import Fore, Back, Style class Character: def __init__(self, name, dialogue): self.name = name self.dialogue = dialogue class Quest: def __init__(self): self.characters = [] self.inventory = Inventory() self.points = 0 def add_character(self, characte...
Python
1
new_config) => { handler::config::update_configuration(&mut config, &new_config) .expect("update configuration failed"); } } } } <reponame>Tellyo/gst-meet<gh_stars>10-100 // Copyright (c) 2019 <NAME> <<EMAIL>> // // This Source Code Form is subject to the term...
Rust
0
{thread_rng, Rng}; use rand::distributions::Uniform; #[cfg(feature = "std")] use std::alloc::{alloc, dealloc, Layout}; // HELPERS macro_rules! assert_abs_diff_list_eq { ($a:expr, $b:expr) => { assert_eq!($a.len(), $b.len()); let mut iter = $a.iter().zip($b.iter());...
Rust
0
# Copyright (c) 2024, Shanghai Iluvatar CoreX Semiconductor Co., Ltd. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/license...
Python
1
L = ( """data:text/plain, var knownOrigins = (function () { return [%(origins)s].reduce(function(t, h) { t[h] = true; return t; }, {}) })(); var uriRegex = new RegExp('^([a-z][-a-z0-9+.]*)' + '://' + '(?:[^/@]*@)?' + '(.*?)' + ...
Python
1