text
string
label_name
string
labels
int64
Request::Body) } CheckedRequest::Account(_, req) => { trace!(target: "on_demand", "Account request completed {:?}", req); req.complete().map(CompleteRequest::Account) } CheckedRequest::Code(_, req) => { trace!(target: "on_demand", "Code request completed {:?}", req); req.complete().map(Compl...
Rust
0
pt Exception as e: logger.error(f"Error storing weather data: {e}") def calculate_weather_adjustment_factor( self, weather_data: WeatherData, venue_code: str ) -> float: """Calculate weather-based adjustment factor for predictions""" try: if not weather_data: ...
Python
1
erval=interval, levels=levels, support=support, legend=False, ax=ax, ) elif representation == "cdf": marginal_dist.plot_cdf( pointinterval=pointinterval, in...
Python
1
ge Duration: {avg_duration:.2f}s") print(f" Maximum Duration: {max_duration:.2f}s") print(f" Minimum Duration: {min_duration:.2f}s") print(f" Performance Target: {'✅ MET' if max_duration <= 30 else '❌ FAILED'} (30s max)") print(f"\n📋 DETAILED RESULTS:") for i, res...
Python
1
pin a0 = a2, /// Analog Pin 1 pin a1 = b8, /// Analog Pin 2 pin a2 = b9, /// Analog Pin 3 pin a3 = a4, /// Analog Pin 4 pin a4 = a5, /// Analog Pin 5 pin a5 = b2, /// Pin 0, rx pin d0 = a11, /// Pin 1, tx pin d1 = a10, pin d2 = a14, pin d3 = a9, ...
Rust
0
from contextlib import contextmanager from typing import Iterator import os import matlab.engine def mlx2others(eng, mlx_input_path, html_output_path: matlab.engine.MatlabEngine): mlx_input_path = os.path.abspath(mlx_input_path) html_output_path = os.path.abspath(html_output_path) eng.matlab.internal.live...
Python
1
#[doc = "*Required features: 'Win32_Media_KernelStreaming'*"] pub const KS_VIDEO_FLAG_FIELD2: i32 = 2i32; #[doc = "*Required features: 'Win32_Media_KernelStreaming'*"] pub const KS_VIDEO_FLAG_FIELD_MASK: i32 = 3i32; #[doc = "*Required features: 'Win32_Media_KernelStreaming'*"] pub const KS_VIDEO_FLAG_FRAME: i32 = 0i32...
Rust
0
} res } // Read pub fn read(bus: u8, drive: u8, blk: u32, buffer: &mut [u8]) -> Result<(), ()> { let mut buses = BUSES.lock(); buses[bus as usize].read(drive, blk, buffer) } // Write pub fn write(bus: u8, drive: u8, blk: u32, buffer: &[u8]) -> Result<(), ()> { let mut buses = BUSES.lock(); buses[bus as usize...
Rust
0
confirm.lower() != 'y': print("👋 Attack cancelled") return # 🚀 Create and execute attacker attacker = DistributedInstagramAttacker( targets=targets, proxies=proxies, password_list=passwords, max_concurrent=max_concurrent, delay_range=(min_delay, max_de...
Python
1
turn _embed ###################################################################### # Prefill # ~~~~~~~ # Before running the forward pass, we first get some help functions for preparation. add_sequence_func = tvm.get_global_func("vm.builtin.kv_state_add_sequence") begin_forward_func = tvm.get_global_func("vm.builtin....
Python
1
def collate_fn(examples): model_input = torch.stack([torch.tensor(example['model_input']) for example in examples]) original_sizes = [example['original_sizes'] for example in examples] crop_top_lefts = [example['crop_top_lefts'] for example in examples] prompt_embeds = torch.stack([torch.tensor(...
Python
1
>{ unsafe { let vec0 = key; let ptr0 = vec0.as_ptr() as i32; let len0 = vec0.len() as i32; let vec1 = value; let ptr1 = vec1.as_ptr() as i32; let len1 = vec1.len() as i32; let (result2_0,result2_1,) = match ttl{ None => { (0i32, 0i32)} Some(e) => { (1i32, wi...
Rust
0
""" Role模块API - 完全按照vue-fastapi-admin标准实现 提供角色管理的CRUD和权限分配功能 """ from typing import List, Optional from fastapi import APIRouter, Depends, Query, Body from sqlalchemy.orm import Session from app.utils.permissions import get_current_user from app.db.session import get_db from app.dto.base_dto import Success, Fail from...
Python
1
v1.div(&v2), Bar => v1.bitwise_or(&v2), _ => None, } } fn value_to_expr(v: TypedValue) -> tast::Expr_ { use tast::*; use TypedValue::*; match v { Int(i) => Expr_::Int(i.to_string()), Float(i) => Expr_::Float(hhbc_string_utils_rust::float::to_string(i)), Bool(fal...
Rust
0
("Newlines\n\nare bridged seamlessly.", vec![ (1, Range::new(0, 0), Range::new(0, 8)), (1, Range::new(0, 8), Range::new(10, 14)), ]), ("Jumping\n\n\n\n\n\n from newlines to whitespace selects whitespace.", vec!...
Rust
0
f64 { value.ln() } // emscripten: global.Math sqrt pub fn sqrt(value: f64) -> f64 { value.sqrt() } // emscripten: global.Math floor pub fn floor(value: f64) -> f64 { value.floor() } // emscripten: global.Math fabs pub fn fabs(value: f64) -> f64 { value.abs() } // emscripten: asm2wasm.f64-to-int pub ...
Rust
0
35\x61\x76\x5e".to_vec()), ), ( Some(b"hello".to_vec()), Some(i64::from(MAX_BLOB_WIDTH) + 1), Some(b"he".to_vec()), None, ), (None, Some(-1), Some(b"h".to_vec()), None), (None, None, None, None), ...
Rust
0
.into_bits() } Lanes::CD => { _mm256_blend_epi32(x.into_bits(), y.into_bits(), (C_LANES | D_LANES) as i32) .into_bits() } Lanes::BC => { _mm256_blend...
Rust
0
Arc::new(LocalFsTracer::new()), trace_sec: self.readahead_sec, trace_condvar: Arc::new((Mutex::new(false), Condvar::new())), }); table_guard.insert(blob_id.to_string(), entry.clone()); Ok(entry) } } } impl BlobBackend for LocalFs { fn...
Rust
0
ENABLE_TASKLISTS); let parser = Parser::new_ext(content, options); let mut res = String::with_capacity(content.len() * 2); html::push_html(&mut res, parser); res } pub fn get_title<S: AsRef<str>>(content: S) -> Option<String> { let content = content.as_ref(); let title = Regex::new(r##"<h1.*...
Rust
0
ffe_id(&x509) } /// Parse the chain of [`Certificate`] as X.509 certificates and validate them /// as signing certificates. pub(crate) fn validate_signing_certificates(certs: &[Certificate]) -> Result<(), X509SvidError> { for cert in certs { let ca = parse_der_encoded_bytes_as_x509_certificate(cert.content...
Rust
0
date .gitignore update_gitignore(root_folder) logger.info(f"Setup completed. Scripts created at: {script_path}") return script_path, dev_folder def update_gitignore(root_folder: str) -> None: """ Updates the .gitignore file to include necessary entries. Args: root_folder: The root di...
Python
1
{process_exits, VerifySignatures}, BlockProcessingError, }; use std::{ptr, slice}; use types::{BeaconState, EthSpec, MainnetEthSpec, VoluntaryExit}; #[derive(Decode, Encode)] struct VoluntaryExitTestCase<T: EthSpec> { pub pre: BeaconState<T>, pub voluntary_exit: VoluntaryExit, } impl<T: EthSpec> Voluntary...
Rust
0
* self.width + x } fn get_surrounding(&self, x: usize, y: usize) -> Vec<&Tile> { let mut surrounding = Vec::new(); for ox in -1..=1 as i32 { for oy in -1..=1 as i32 { if ox == 0 && oy == 0 { continue; } let tx = ...
Rust
0
fmt::Debug::fmt(&self.0, f) } } impl From<ogg::OggReadError> for PassthroughError { fn from(err: OggReadError) -> PassthroughError { PassthroughError(err) } } impl fmt::Display for PassthroughError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(&self.0, f)...
Rust
0
mmonPasswordValidator", }, { "NAME": "django.contrib.auth.password_validation.NumericPasswordValidator", }, ] # Internationalization # https://docs.djangoproject.com/en/5.1/topics/i18n/ LANGUAGE_CODE = "ko-kr" TIME_ZONE = "Asia/Seoul" USE_I18N = True USE_TZ = True # Static files (CSS, JavaScri...
Python
1
is tree that returns decoded for any single bit input return Ok(VorbisHuffmanTree { desc_prog :vec![1u32 << 31, 3, 3, decoded as u32], unrolled_entries :[ UnrolledLookupEntry::HasEntry(1, decoded as u32); 256 ], }); } else { // Single entry codebooks must have 1 as their only length ...
Rust
0
DEX_ENTRY_SIZE as u64; read_bucket_1 = true; read_bucket_2 = false; } else if ci_1 > ci_2 { merge_into(Source { key: ci_2, origin: Origin::Bucket2 { offset: data_off_2 } }, &mut data_1, &m...
Rust
0
String, serde_json::Error> for JsonRenderer { fn render( &mut self, tree: &WidgetUnit, _: &CoordsMapping, _layout: &Layout, ) -> Result<String, serde_json::Error> { if self.pretty { serde_json::to_string_pretty(tree) } else { serde_json::to...
Rust
0
""" Funções em Python (def) são trechos de cód usadas pra replicar/reutilizar determinada ação ao longo do cód. Podem receber valores como parâmetros (argumentos) e podem retornar valores específicos. padrão: None (retornam Nada), NÃO valor, como se fosse um 'vazio' (falsy) """ # Definindo uma função com parâmetros...
Python
1
lse: destination = guild.owner try: await destination.send(**self.bot.em( "__Thanks for adding Xenon to your server!__ 😃\n" f"Use `{self.bot.config.prefix}help` to get a list of commands. If you need more information, " "you can look at t...
Python
1
".mo") { Some(candid::bindings::motoko::compile(&type_env, &did_types)) } else if main.ends_with(&".rs") { Some(candid::bindings::rust::compile(&type_env, &did_types)) } else if main.ends_with(&".js") { Some(candid::bindings::ja...
Rust
0
#! python3 import pandas as pd import numpy as np import random import traceback class EquallyLikelyEventsProbabilityCalculator: def __init__(self, inFilePath) : try: self.filePath = inFilePath self.originalData = None self.rewardData = None except Exception as e: print(f"Error initializing calcula...
Python
1
!(race(&input, 1000), 1120); } #[test] fn examples_2() { let input = EXAMPLE_DATA.join("\n"); assert_eq!(race_2(&input, 1000), 689); } } //! # Structure //! This crate provides the procedural macro `NoCopy` to the buffering crate. Buffering is feature //! flagged to be able to use only ...
Rust
0
Continue(T), /// We're done early. Done(U), } /// Retrieve the blob with `key`. /// /// Returns an error if the database actor can't be accessed. pub async fn retrieve_blob<M, K>( ctx: &mut actor::Context<M, K>, db_ref: &mut ActorRef<db::Message>, passport: &mut Passport, key: Key, ) -> Result...
Rust
0
s(layer, num_layers) if input_projection: assert dim is not None self.proj = paddle.nn.Conv2D(in_channels=dim, out_channels=dim, kernel_size=1) def forward(self, x): x = self.proj(x) for layer in self.layers: x = layer(x) return x class MemoryEn...
Python
1
#숫자를 입력받아 3의 배수인지 아닌지 출력하시오 number = int(input("원하는 숫자 : ")) if number % 3 == 0: print(f"{number}는 3의 배수입니다.") else: print(f"{number}는 3의 배수아님") #점수를 입력받아 90점 이상 우수 70점이상 패스 미만이면 낙제라고 출력 jumsu = int(input("원하는 숫자 : ")) if jumsu >= 90: print("우수") elif jumsu >= 70: print("패쓰") else: print("낙제...
Python
1
{ Logger { pantsd_log: Mutex::new(MaybeWriteLogger::empty()), stderr_log: Mutex::new(MaybeWriteLogger::empty()), show_rust_3rdparty_logs: AtomicBool::new(true), engine_display_handles: Mutex::new(HashMap::new()), } } pub fn init(max_level: u64, show_rust_3rdparty_logs: bool) { ...
Rust
0
; } // これ以上下に行けない if i / 5 == 4 && *move_dir == Direction::S { continue; } for amount in 1..5 { let move_to = ((i as i8) +...
Rust
0
k0; #[doc = "HCINTMSK1 register accessor: an alias for `Reg<HCINTMSK1_SPEC>`"] pub type HCINTMSK1 = crate::Reg<hcintmsk1::HCINTMSK1_SPEC>; #[doc = "OTG_HS host channel-1 interrupt mask register"] pub mod hcintmsk1; #[doc = "HCINTMSK2 register accessor: an alias for `Reg<HCINTMSK2_SPEC>`"] pub type HCINTMSK2 = crate::Re...
Rust
0
ui.draw( ctx, &ui.tile_alt(fg_row, fg_column, bg_color, false)?, 1., 0., )?; ui.draw_text(ctx, &p(&game.mode).to_uppercase(), 2.5, 0., default_color)?; ui.draw_text(ctx, &format!("x{}", ui.scale), 18., 0., default_color)?; Ok(()) } } ...
Rust
0
from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup from telegram.ext import ContextTypes, CallbackQueryHandler from utils.admin_checker import is_temp_admin from config import ADMIN_ID from telegram.constants import ParseMode # --- Help Text Content --- def get_main_help_text(): return """ ...
Python
1
10 } else { $aaa }) + (if $bbb == $nothing { 100 } else { $bbb }) }; foo -a 90"#, "190", ) } #[test] fn missing_flags_are_nothing3() -> TestResult { run_test( r#"def foo [--aaa(-a): int, --bbb(-b): int] { (if $aaa == $nothing { 10 } else { $aaa }) + (if $bbb == $nothing { 100 } else { $bbb }) ...
Rust
0
ine.cmd = cmdline.cmd.trim().to_string(); match cmdline.cmd.chars().nth(0) { Some(first) => if first == '#' { continue }, None => continue // empty string } // parse preprocess(&mut cmdline); // handle ...
Rust
0
import rclpy from rclpy.node import Node from rclpy.qos import QoSProfile, ReliabilityPolicy, DurabilityPolicy from geometry_msgs.msg import Twist from nav_msgs.msg import Odometry class DisplayOdometry(Node): def __init__(self): # initialize node super().__init__("display_odom_node") ...
Python
1
# This code is originally from the official ActivityNet repo # https://github.com/activitynet/ActivityNet import json import urllib.request import numpy as np API = 'http://ec2-52-11-11-89.us-west-2.compute.amazonaws.com/challenge17/api.py' def get_blocked_videos(api=API): api_url = '{}?action=get_blocked'.forma...
Python
1
uple::origin()]; let n = using_a.operate(&mut ctx, &mut coords, FWD); assert_eq!(n, 1); assert!((37. - coords[0][0]).abs() < f64::EPSILON); println!("Vi fik {}", coords[0][0]); split_det_op(); } fn split_det_op() { let all = "\n # agurk \n en # agurk\r\n ## Arbejd med agurker \n##\n## agurker...
Rust
0
""" =============== Simple axis pad =============== """ import matplotlib.pyplot as plt import numpy as np from matplotlib.projections import PolarAxes from matplotlib.transforms import Affine2D import mpl_toolkits.axisartist as axisartist from mpl_toolkits.axisartist import angle_helper, grid_finder from mpl_toolki...
Python
1
################################################################### ### Top Plot ##################################################################################################################### #ax1 = plt.subplot(G[0, 0], projection=ccrs.PlateCarree(central_longitude=180)) ax1.set_extent([120, 290, -30, 30], crs=...
Python
1
from ..char_classes import ( ALPHA, ALPHA_LOWER, ALPHA_UPPER, CONCAT_QUOTES, HYPHENS, LIST_ELLIPSES, LIST_ICONS, ) _infixes = ( LIST_ELLIPSES + LIST_ICONS + [ r"(?<=[0-9])[+\-\*^](?=[0-9-])", r"(?<=[{al}{q}])\.(?=[{au}{q}])".format( al=ALPHA_LOWER, au...
Python
1
"local_map": local_map, "global_map": global_map, "flying_time": battery_scalar, } @classmethod def from_config_file( cls, config_file: Path, world: World[Any], drone: Drone, ) -> StateSpace: with config_file.open("r") as cs:...
Python
1
import os import re ####################### YAZILAN HEADER'LARI KALDIRMA ####################### target_dir = os.getcwd() # Çalışma dizini # Header'ı silen fonksiyon def remove_old_header(content): # Header'ı silmek için regex kullanıyoruz pattern = re.compile(r"/\*.*?YILDIZ ROKET TAKIMI.*?\*/\n*", re.DOT...
Python
1
import hashlib import logging import sys from typing import Dict, Any import numpy as np import tabliblib import tabliblib.io from tabliblib.language_detection import detect def add_content_hash(row: Dict[str, Any]) -> Dict[str, Any]: """Insert a content_hash column""" # This seems to be a base64 encoded ha...
Python
1
while self.get_reg_u16(reg) != 0 { if !self.pending_interrupts.is_empty() { // TODO: Service pending interrupts panic!(); } self.apply_string_instruction(&repeat_inst); self.sub_from_reg(reg, 1); //dbg!(self.get_reg_u16(reg)); /*if self.get_reg_u16(reg) == 0 { ...
Rust
0
vector in which all of its elements are zero. #[inline] pub fn zero() -> Vector3<S> { Vector3::new(S::zero(), S::zero(), S::zero()) } /// Determine whether a vector is the zero vector. #[inline] pub fn is_zero(&self) -> bool { self.data[0].is_zero() && self.data[1]....
Rust
0
.mean(0) hyp_embedding_avg = hyp_embedding[-5:].mean(0) ref_embedding = torch.cat([ref_embedding_min, ref_embedding_avg, ref_embedding_max], -1) hyp_embedding = torch.cat([hyp_embedding_min, hyp_embedding_avg, hyp_embedding_max], -1) for i in range(len(ref_tokens)): ...
Python
1
let lena = get_lena().expect("Couldn't load lena"); // Create transformation matrix let x = 0.5 * (lena.cols() as f64) - 0.5; let y = 0.5 * (lena.rows() as f64) - 0.5; let trans = rotate_around_centre(FRAC_PI_4, (x, y)).dot(&scale(0.7, 0.7)); let transformed = lena .transform(trans.view(),...
Rust
0
g|o|kundi\b', # Cebuano conjunctions } elif self.language == 'bikol': patterns = { 'VB': r'\b(MA|MAG|NAG|MANG|PINAG|PA|KA)[a-zA-Z]+\b', # Bikol verb markers 'NN': r'\b[a-zA-Z]+on\b|\b[a-zA-Z]+an\b|\b[a-zA-Z]+(TA|HON|LAY|LI)[a-zA-Z]*\b', # Bikol nouns ...
Python
1
LOCALHOST), 0)) .unwrap() }; let server_addr = endpoint.local_addr().unwrap(); drop(endpoint); // Ensure server shuts down when finished (server_addr, incoming) } /// Create a client endpoint and client connection pub async fn connect_client( server_addr: SocketAddr, server_cert: qu...
Rust
0
_or(false, |fs| match fs { Exfat | Ntfs | Fat16 | Fat32 | Lvm | Luks | Swap => false, Btrfs | Xfs | Ext2 | Ext3 | Ext4 | F2fs => true, }) } /// True if this is a LUKS partition fn is_luks(&self) -> bool { self.get_file_system().map_or(false, |fs| fs == FileSystem::Luks) } ...
Rust
0
import streamlit as st import pandas as pd import numpy as np from .utils import get_iqr_bounds from .undo_reset import save_snapshot def outlier_detection(df): st.subheader("🚨 Outlier Handler") mode = st.sidebar.radio("Outlier Mode", ['Show Outliers', 'Drop Outliers', 'Cap Outliers'], key = "outlier_mode") ...
Python
1
th_fglm_from_ring to_ring = convert_with_fglm_to_ring return _fglm(I, from_ring, to_ring) if interpolation_gb: first = next(iter(I)) if len(I) != 1 or first.ring().get_order_code() != OrderCode.lp: raise ValueError return lex_groebner_basis_for_polynomial_via_var...
Python
1
(0_f64, SIMILAR_VALUES[1][5] as f64); scale_similarity_similar_images.set_fill_level(SIMILAR_VALUES[1][5] as f64); label_similar_images_minimal_similarity.set_text(" Very Small "); }); } { let radio_button_similar_hash_size_32 = gui_data.main_notebook.radio_button_similar...
Rust
0
rotation. placement = tuple(filter(None, placement)) placement = min(placement[i:] + placement[:i] for i in range(len(placement))) placement_id = int("".join(map(str, placement))) xs = ["num_nodes", "num_replicas", "local_bsz"] ys = ["step_time", "sync_ti...
Python
1
versal_map, &mut state, &mut board, latin.size(), 0, &mut answers, ); let mut ret = vec![]; for answer in answers.into_iter() { let mut x = Latin::new(latin.size()); for i in 0..latin.size() { for j in 0..latin.size() { x.s...
Rust
0
o::Result<()> { encode_data_buf(w, v)?; Ok(()) } fn encode_vec_str<W: Write>(w: &mut W, v: &[&str]) -> std::io::Result<()> { if v.len() > 0xffff { return Err(std::io::Error::new( std::io::ErrorKind::InvalidInput, "string vec too long for 9p encoding", )); } e...
Rust
0
t will not allocate. /// /// Warning: `hash_builder` is normally randomly generated, and is designed /// to allow `StHashSet`s to be resistant to attacks that cause many /// collisions and very poor performance. Setting it manually using this /// function can expose a DoS attack vector. /// ...
Rust
0
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage from django.shortcuts import render, redirect from classes.models import Class from django import forms def classes_view(request): classes_list = Class.objects.all() paginator = Paginator(classes_list, 3) page_number = request.GET.ge...
Python
1
import streamlit as st from typing import Callable def setup_page_and_sidebar(dashboard_config: dict, add_to_sidebar: Callable = None) -> None: """ Set up the Streamlit page configuration, including title, description, custom CSS styling, and sidebar links. Parameters ---------- dashboard_con...
Python
1
lance: Option<i32>, } impl OIDCUser { #[must_use] pub fn has_group(&self, group_name: &str) -> bool { self.groups.iter().contains(&group_name.to_owned()) } } <reponame>crvdgc/hoice<filename>src/learning/ice/synth/adt.rs //! ADT qualifier synthesis. use crate::{common::*, fun::Functions}; use supe...
Rust
0
impl<K> Api<K> where K: Restart + Resource + DeserializeOwned, { /// Trigger a restart of a Resource. pub async fn restart(&self, name: &str) -> Result<K> { let mut req = self.request.restart(name).map_err(Error::BuildRequest)?; req.extensions_mut().insert("restart"); self.client.re...
Rust
0
"--font-size=1000 --ned --remove-default-ignorables --font-funcs=ft", ), "Aogonek|\ j@752,0" ); } #[test] fn gpos_1_005() { assert_eq!( shape( "text-rendering-tests/fonts/TestGPOSOne.ttf", "\u{0104}\u{0237}", "--font-size=1000 --ned --remove-...
Rust
0
from __future__ import annotations import pytest from dask.hashing import hash_buffer, hash_buffer_hex, hashers np = pytest.importorskip("numpy") buffers = [ b"abc", bytearray(b"123"), memoryview(b"456"), np.array(42), np.ones((100, 100)), np.zeros((100, 100), dtype=[("a", "i4"), ("b", "i2")...
Python
1
p[R"SS/U*U*S- /U*SU- -U*S- /U*U*S- /U*S//5n UR(dXS/- n UR(a XS- S/- n URS:XaU n OeU SS/-n URS :XaU n OK...
Python
1
# Copyright (c) 2024 S. Holzapfel <me@sebholzapfel.com> # # SPDX-License-Identifier: CERN-OHL-S-2.0 from amaranth import * from amaranth.lib import data, stream, wiring from amaranth.lib.wiring import In, Out from amaranth_future import fixed from . import ASQ class Trigger(wiring.Component): """ When tri...
Python
1
())?; let mut file = WhisperBuilder::default() .add_retentions(&[Retention { seconds_per_point: 1, points: 20, }]) .x_files_factor(0.5) .aggregation_method(AggregationMethod::Average) .build(&file_path)?; let m...
Rust
0
ter by threshold memory_scores = [] for memory in all_memories: similarity = cosine_similarity(query_embedding, eval(memory.embedding)) if similarity >= similarity_threshold: memory_scores.append({ "content": memory.content, "significance_score": memor...
Python
1
le.read_to_end(&mut buf).await?; "data:image/png;base64,".to_string() + &base64::encode(&buf) }, AttachmentType::Image(url) => { let url = Url::parse(url).map_err(|_| Error::Url(url.to_string()))?; let response = http.as_ref().client.get(url).send...
Rust
0
= new google.visualization.PieChart(document.getElementById("chart_services"));'+\ ' chart.draw(data, options);'+\ '}'+\ '</script>' r['html'] += hostdetails r['html'] += ''+\ '<div style="page-break-before: always;">'+\ ' <div>'+\ ' <div style="text-align:center;padding-top:600px;"><b>Generated with</b><br>...
Python
1
title VARCHAR NOT NULL, author_id INTEGER NOT NULL REFERENCES author ) ")?; // Insert the values to the tables in the Postgres database. let mut authors = HashMap::new(); authors.insert(String::from("<NAME>"), "United States"); authors.insert(Str...
Rust
0
[inline] pub fn bits(&self) -> u8 { self.bits } } impl R { #[doc = r" Value of the register as raw bits"] #[inline] pub fn bits(&self) -> u32 { self.bits } #[doc = "Bit 0 - DMA Enable Status"] #[inline] pub fn en(&self) -> ENR { let bits = { const ...
Rust
0
IndexOffsetError> { Ok(LayoutVerified::<_, [EntryV1]>::new_slice(self.entries()) .unwrap() .into_slice() .get(range) .ok_or(FindIndexOffsetError::read_index_file("invalid offset"))?) } fn entries_v2(&self, range: Range<usize>) -> Result<&[EntryV2], FindIn...
Rust
0
l_files += len(files) total_dirs += len(dirs) print(f"准备删除: {total_files} 个文件, {total_dirs} 个目录") # 删除整个目录树 shutil.rmtree(base_dir) print(f"✓ 已删除目录: {base_dir}") else: print(f"目录不存在: {base_dir}") def main(): """ 主函数 """ print("S...
Python
1
import time import matplotlib.pyplot as plt import numpy as np from mnist数据集.mnist import load_mnist from CNN深度学习架构.神经网络层.simple_convnet import SimpleConvNet from CNN深度学习架构.神经网络层.simple_convnet_trainer import Trainer from pathlib import Path # 读入数据 (x_train, t_train), (x_test, t_test) = load_mnist(flatten=False) # 处...
Python
1
ads) return l for i_epoch in range(5): for i_batch, (inps, tars) in enumerate(train_data()): loss = f_train(inps, tars) if (i_batch + 1) % 100 == 0: print(f'Epoch {i_epoch}, Batch {i_batch + 1:3d}, Loss {loss:.5f}') brainstate.nn.init_all_states(model, 1) x, y = build_inputs_and_t...
Python
1
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import IPython.display as ipd import matplotlib.pyplot as plt import torch def plot_waveform_and_specgram(waveform, sa...
Python
1
#! /usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function from os.path import join import sys import unittest from glob import glob sys.path.append('../../') from swbd.labels.ldc97s62.character import read_trans from ut...
Python
1
hir::Ty::S32 }); let n = exprs.alloc(hir::Expr::VarRef(hir::VarDefId::Param(n_def))); let fnc_def = fnc_defs.alloc(hir::FncDef { params: IdRange::new(n_def..=n_def), ret_ty: hir::Ty::S32, body: n, }); check( "fnc id(n: s32): s32 -> n;", ...
Rust
0
from __future__ import absolute_import from __future__ import print_function from __future__ import division import os from PIL import Image import numpy as np import os.path as osp import lmdb import io import random import torch from torch.utils.data import Dataset def read_image(img_path): """Keep reading im...
Python
1
DfuWddlmZmZmZddlZddlZddlZddlZddlZddl m Z ddl m cm Z ddlm cmZddlmZddlmZddlmZddlmZmZddlmZmZGdd eZd Zy) )absolute_importprint_functionunicode_literalsN) ReadlineError)make...
Python
1
'Yes'), ]) if 'tsn' in plt_params_list: print ("Applying changes to enable TSN") xml_change_list.append ([ ('./NetworkingConnectivity/TimeSensitiveNetworkingConfiguration/TsnEnabled', 'TSN 1 and TSN 2 Enabled'), ]) if 'cfg3' in plt_params_list: ...
Python
1
seSecret, Secret}; /// The prefix identifying an age stanza. const STANZA_TAG: &str = "-> "; /// The length of an age file key. pub const FILE_KEY_BYTES: usize = 16; /// A file key for encrypting or decrypting an age file. pub struct FileKey(Secret<[u8; FILE_KEY_BYTES]>); impl From<[u8; FILE_KEY_BYTES]> for FileKey...
Rust
0
y bad movies (not really a topic category) # 2. Movies about families # 3. War movies # 4. Art movies # 5. Crime movies # 6. Horror movies # 7. Comedies # 8. Movies somehow related to TV shows # 9. Movies based on books # 10. Action movies # To confirm that the categories make sense based on the reviews, let's plot 5 ...
Python
1
import sys input = sys.stdin.readline INF = int(1e9) def bellman_ford(start): dist = [INF] * (N + 1) dist[start] = 0 for i in range(N): for cur, next, cost in edges: if dist[cur] != INF and dist[next] > dist[cur] + cost: dist[next] = dist[cur] + cost ...
Python
1
import random POPULATION_SIZE = 4 # 개체 집단의 크기 MUTATION_RATE = 0.1 # 돌연 변이 확률 SIZE = 5 # 하나의 염색체에서 유전자 개수 # 염색체를 클래스로 정의한다. class Chromosome: def __init__(self, g=[]): self.genes = g.copy() # 유전자는 리스트로 구현된다. self.fitness = 0 # 적합도 if self.genes.__len__()==0: # 염색체가 초기 상태이면 초기화한...
Python
1
from translate.nouns.context import TranslatedNoun, DeterminedNoun from translate.vocabulary import vocabulary import polars as pl from translate.vocabulary.embedding_utils import most_similar from translate.vocabulary.translation_utils import meanings_distance, strip_explanation, segment_meaning def translate_deter...
Python
1
} } /// Get the counter value for a `key`. pub(crate) fn get_counter_val(ctx: &DummyCtx, key: &str) -> usize { *ctx.state.test_counters.borrow().get(key) } /// An extension trait for `Ip` providing test-related functionality. pub(crate) trait TestIpExt: Ip { /// Either [`DUMMY_CONFIG_V4`] or [`DUMMY_CONFI...
Rust
0
.unwrap(), milestone ); let results = MultiFetch::<MilestoneIndex, Milestone>::multi_fetch(storage, &[index]) .unwrap() .collect::<Vec<_>>(); assert_eq!(results.len(), 1); assert!(matches!(results.get(0), Some(Ok(Some(v))) if v == &milestone)); Delete::<MilestoneIndex, Mil...
Rust
0
from graphics import * import math as mt import time import imageio from PIL import ImageGrab # Ініціалізація вікна і фігури def init_window(text, xw, yw, size_x, size_y, center_x, center_y): # Ініціалізація вікна win = GraphWin(text, xw, yw) win.setBackground('white') # Координати вершин ромба в цен...
Python
1
StmtResult::Break => return Ok(Some(StmtResult::Break)), StmtResult::Continue => return Ok(Some(StmtResult::Continue)), _ => unimplemented!("{:?}", res), } } } Ok(None) },...
Rust
0