text
string
label_name
string
labels
int64
enc = _normalize_video_codec_name(encoder_name) ext = container_ext.lower().lstrip('.') # H.264 in OGG is not a supported combination if enc == 'h264' and ext == 'ogg': errors.append("H.264 video codec is not supported in OGG containers") # H.265/HEVC not supported in MP3 or OGG if enc ...
Python
1
(_) => response_server_error("Empty result"), } } else { response_server_error("Parser error") } } None => response_server_error("X-EVTC-FILENAME header is required"), ...
Rust
0
offset_start_pos < self.len(), "Time offset should not be empty" ); debug_assert_ok!(PartialTimeStr::from_bytes(&self.0[..offset_start_pos])); debug_assert_ok!(TimeOffsetStr::from_bytes(&self.0[offset_start_pos..])); let (partial_time, offset) = self.0.split_at_mut(o...
Rust
0
CTORS>())).areal_scale as *const _ as usize }, 16usize, concat!( "Offset of field: ", stringify!(P5_FACTORS), "::", stringify!(areal_scale) ) ); assert_eq!( unsafe { &(*(::std::ptr::null::<P5_FACTORS>())).angular_distortion as *cons...
Rust
0
PCWSTR, lpszvolumepathname: ::windows_sys::core::PWSTR, cchbufferlength: u32) -> super::super::Foundation::BOOL; #[doc = "*Required features: `\"Win32_Networking_Clustering\"`*"] pub fn ClusterGroupCloseEnum(hgroupenum: *const _HGROUPENUM) -> u32; #[doc = "*Required features: `\"Win32_Networking_Clustering\...
Rust
0
import numpy as np import matplotlib.pyplot as plt plt.rcParams['font.sans-serif'] = ['SimHei'] import warnings#引入警告信息库 warnings.filterwarnings('ignore')#过滤警告信息 from data import * from sklearn.svm import SVR #导入数据预处理工具 from sklearn.preprocessing import StandardScaler X_train,y_train,X_test,y_test=train_pca[:1000],all...
Python
1
#🔷 PART 2: tuple — Ordered and Unchangeable #🧠 Explanation: #A tuple is like a list, but you can’t change it. #It’s useful when the data should never be modified. #In real life: #Months of the year → ("Jan", "Feb", "Mar", ...) #Gender options → ("Male", "Female", "Other") #You use a tuple when: #You...
Python
1
list1 = ["abc", 34, True, 40, "male"]
Python
1
println!(); sanity_run(rewards, deadline); } } /// SNIP20 token handle messages #[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] #[serde(rename_all = "snake_case")] pub enum Snip20HandleMsg { // Basic SNIP20 functions Transfer { reci...
Rust
0
as_absolute_form() } } impl ShouldStackPerRequest for Config { fn should_stack_per_request(&self) -> bool { !self.settings.is_http2() && !self.settings.can_reuse_clients() } } impl fmt::Display for Config { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.target.addr.fmt(f) ...
Rust
0
# Licensed to the Apache Software Foundation (ASF) 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 u...
Python
1
> 8) as u8; let y = ((opcode & 0x00F0) >> 4) as u8; match opcode & 0xF000 { 0x0000 => match opcode { 0x00E0 => InstructionSet::ClearScreen, 0x00EE => InstructionSet::ReturnFromSubroutine, _ => InstructionSet::MachineLanguageSubroutine(opcode), }, 0x100...
Rust
0
ttUSHORT(((data).offset((encoding_record) as isize)).offset((2) as isize))) as i32) == STBTT_MS_EID_UNICODE_BMP || ((ttUSHORT(((data).offset((encoding_record) as isize)).offset((2) as isize))) as i32) == STBTT_MS_EID_UNICODE_FULL { ...
Rust
0
22], [3, 22]])) if is_progression: vtype = 0 else: vtype = 2 patch.write_token(APTokenTypes.WRITE, self.pointer + 88 + (replacement_target * 2), vtyp...
Python
1
.##.#..### ##...#..#. .#....####", ); assert_eq!(max_visibility(&m), (&Location { x: 5, y: 8 }, 33)); } #[test] fn example03() { let m = AsteroidMap::create_from( "\ #.#...#.#. .###....#. .#....#... ##.#.#.#.# ....#.#.#. .##..###.# ..#...##.. ..##....## ......#... .####....
Rust
0
doc = " FT_PIXEL_MODE_GRAY ::"] #[doc = " An 8-bit bitmap, generally used to represent anti-aliased glyph"] #[doc = " images. Each pixel is stored in one byte. Note that the number of"] #[doc = " 'gray' levels is stored in the `num_grays` field of the @FT_Bitmap"] #[doc = " structure (it generally i...
Rust
0
) .expect("Failed to get the private key for a key pair that should exist!"); for _ in 0..num_rotations { let new_public_key = storage .rotate_key_pair(CRYPTO_KEYPAIR_NAME) .expect("Failed to rotate a valid key pair!"); let new_private_key = storage .get_...
Rust
0
Virtual, Unknown, } /// What type of device has been detected. #[derive(Clone, Debug, Eq, PartialEq, Display, IntoStaticStr)] #[strum(serialize_all = "snake_case")] pub enum DeviceType { Disk, Partition, Unknown, } impl FromStr for DeviceType { type Err = BlockUtilsError; fn from_str(s: &...
Rust
0
let mut f_letter = FirstLetter { letter: ' ', read: false, vowel: false, }; let mut string = String::new(); io::stdin() .read_line(&mut string) .expect("Error while reading stdin"); let string = string.trim(); if stri...
Rust
0
, label: None, section: Some("Heading"), } .display() ); assert_eq!( "Label", ObsidianNoteReference { file: Some("Note"), label: Some("Label"), section: Some("Heading"), ...
Rust
0
om message")?; let message_lines: Vec<&str> = message.lines().collect(); if message_lines.len() >2 { Ok(( Some(message_lines[0].to_string()), Some(message_lines[2..].join("\n")) )) } else { Ok(( Some(message_lines[0].to_string()), Non...
Rust
0
, 27, 28, 29, 30, 31, 32, ]; let mut r = [0u8; 32]; c.bench_function("hash_sha3", |bench| { bench.iter(|| hash::sha3(black_box(&v), black_box(&mut r))) }); } criterion_group!(hash_group, blake3, sha3); criterion_main!(hash_group); // Copyright 2021 The Fuchsia Authors. All rights reserved. // U...
Rust
0
_assets.loaded = load_manager.loaded.clone(); fluid_assets .loaded .sort_by(|(a, _), (b, _)| alphanumeric_sort::compare_str(a.as_str(), b.as_str())); fluid_assets.loading = load_manager.loading.clone(); actions.fluids_loaded = fluid_assets.loaded.len(); actions.fluids_loaded_percent = ...
Rust
0
es.iter().enumerate() { if max < v { max_index = i; max = v; } } Some((max_index, *max)) } pub fn nx_count(nums: &Vec<usize>, x: f64) -> usize { if nums.is_empty() { return 0; } let frac = (x as f64) / 100.0; let mut nums_cp = nums.clone(); ...
Rust
0
20 min_width = 20 if text_region.shape[0] < min_height or text_region.shape[1] < min_width: continue # Save text region as an image file output_path = f"{saved_dir}/text_region_{i}_{j}.png" segmented_license.append(text_region) cv...
Python
1
slot, location: address_location, stack_pointer }; if cfg!( debug_assertions ) { let src = self.index; let dst = self.tls().tail; let len = self.tls().slice().len() - self.index; if dst + len > src { error!( "Asser...
Rust
0
_lifecycle_policy_details(&mut object_1883, var_1882)?; object_1883.finish(); } if let Some(var_1884) = &input.repository_name { object.key("RepositoryName").string(var_1884); } if let Some(var_1885) = &input.repository_policy_text { object.key("RepositoryPolicyText").string(var_...
Rust
0
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right from typing import Optional, List class Solution: def closestNodes(self, root: Optional[TreeNode], queries: List[int]) -> L...
Python
1
M' => 131.0404846241, b'N' => 114.042927463, b'P' => 97.0527638599, b'Q' => 128.0585775272, b'R' => 156.101111036, b'S' => 87.0320284257, b'T' => 101.0476784899, b'U' => 150.9536347957, b'V' => 99.0684139241, b'W...
Rust
0
#!/usr/bin/env python3 # Copyright (C) 2025 ERAS Research Group and sanimut Development Team # Author(s): Murray Ferris """ Example of using a socket to interact with network socket, e.g. send integers to emulator and receive their sum """ import socket import time remote_address = "127.0.0.1" remote_port = 20002 l...
Python
1
video_time_code; #[cfg(any(feature = "v1_10", feature = "dox"))] pub use video_time_code::{ValidVideoTimeCode, VideoTimeCode, VideoTimeCodeMeta}; #[cfg(any(feature = "v1_12", feature = "dox"))] mod video_time_code_interval; #[cfg(any(feature = "v1_12", feature = "dox"))] pub use video_time_code_interval::VideoTimeCode...
Rust
0
from pyrogram import filters from pyrogram.types import Message, InlineKeyboardButton, InlineKeyboardMarkup, CallbackQuery from pyrogram.types import Message from Strings import get_string, helpers from TOSUMUSIC import app from pyrogram.types import InputMediaVideo from TOSUMUSIC.music import SUDOERS from TOSUMUSIC.ut...
Python
1
#!/usr/bin/env python3.9 """Creating do-nothing threads, professionally""" import os from time import sleep from threading import Thread # IMPORTANT! Do `pip install psutil` if it is not installed yet import psutil GB = 1024 ** 3 MB = 1024 ** 2 # WARNING! # This can end up in `RuntimeError: can't start new thread` #...
Python
1
database.dbi(), &mut key_val, &mut d)) } } else { unsafe { lmdb_result(ffi::mdb_del(self.txn(), database.dbi(), ...
Rust
0
te}; extern crate rand; /// Representation of a standard Minesweeper board. #[derive(Clone)] pub struct Board { /// The total number of bombs (revealed or not) on the /// `Board`. pub num_mines: usize, /// Keeps track of whether the `Board` has been generated. was_generated: Cell<bool>, /// Th...
Rust
0
# from langchain_openai import ChatOpenAI from crewai import LLM as ChatOpenAI # 模型全局参数配置 根据自己的实际情况进行调整 # openai模型相关配置 根据自己的实际情况进行调整 OPENAI_API_BASE = "https://api.wlai.vip/v1" OPENAI_CHAT_API_KEY = "sk-dvdCgdO3LSWYgqnMiJR5NqG0eLSTM69yjryjD6LuL3lWkvf3" OPENAI_CHAT_MODEL = "gpt-4o-mini" # 非gpt大模型相关配置(oneapi方案 通义千问为例) ...
Python
1
load(self): if self._check_integrity(): return super(FC100ClassDataset, self).download() subfolder = os.path.join(self.root, self.subfolder) if not os.path.exists(subfolder): os.makedirs(subfolder) filename_fine_names = os.path.join(self.root, self.filen...
Python
1
= mmcv.imread(input_path) one_img = mmcv.imresize(one_img, input_shape[2:][::-1]) show_img = one_img.copy() if 'normalize_cfg' in input_config.keys(): normalize_cfg = input_config['normalize_cfg'] mean = np.array(normalize_cfg['mean'], dtype=np.float32) std = np.array(normalize_cfg[...
Python
1
a //! [`Scheme`](scheme::Scheme) by implementing the [`ToScheme`](scheme::ToScheme) trait. //! //! Note that this example prints the generated passphrase in the console, //! which might not be desired in most situations. extern crate chbs; use chbs::{config::BasicConfig, prelude::*, probability::Probability}; fn ma...
Rust
0
td::ptr::null::<_xmlDoc>())).doc as *const _ as usize }, // 64usize, // concat!( // "Offset of field: ", // stringify!(_xmlDoc), // "::", // stringify!(doc) // ) // ); // assert_eq!( // unsafe { &(*(::std::ptr::null::<_xmlDoc>())).compression as *const _ as usize }, // 72...
Rust
0
an address space. /// /// # Example /// /// ```no_run /// use inkwell::AddressSpace; /// use inkwell::context::Context; /// /// let context = Context::create(); /// let module = context.create_module("mod"); /// let i8_type = context.i8_type(); /// let global = module.add_gl...
Rust
0
(neuron.uid)); // Check that the stake is there. neuron } // Tests that the self emission returns the correct values with a single node. #[test] fn test_emit_does_not_exist() { new_test_ext().execute_with(|| { // Let's subscribe a new neuron to the chain. let neuron = NeuronMetadata::<u64> { ...
Rust
0
system::Module<Test>; type WeightInfo = (); } impl Trait for Test { type UpwardMessageSender = MessageBrokerMock; type UpwardMessage = TestUpwardMessage; type XCMPMessageSender = MessageBrokerMock; type Event = TestEvent; type Currency = Balances; } mod token_dealer { pub use crate::Event...
Rust
0
import requests from requests.adapters import HTTPAdapter from urllib3.util.retry import Retry import os import json import sys import logging from concurrent.futures import ThreadPoolExecutor, as_completed from pathlib import Path from tqdm import tqdm import hashlib import time class photographDownload: def __i...
Python
1
table.end_scope(); // scope Y let scope_y = table.start_scope(); // scope Y assert_eq!(scope_y.parent_id, Some(0)); let scope_y_id = scope_y.id; let var = Variable::build_local("A", SymbolId(1)); table.create_var_symbol(var.clone()); table.end_scope(); ...
Rust
0
#!/usr/bin/python # -*- coding: utf-8 -*- SPIDERS = { 1: 'manga_copy', 2: 'jm', 3: 'wnacg', 4: 'ehentai', 5: 'mangabz', } SPECIAL_WEBSITES = ['wnacg', 'jm', 'ehentai'] SPECIAL_WEBSITES_IDXES = [2, 3, 4] SPIDERS_NEED_PROXIES_IDXES = [3, 4] DEFAULT_COMPLETER = { # only take effect when init (mean va...
Python
1
/// Like `get`, but returns both the key and the value. pub fn get_entry<Sized? T>(&self, key: &T) -> Option<(&K, &V)> where T: PhfHash+Equiv<K> { self.get_entry_(key, |k| key.equiv(k)).map(|(_, e)| (&e.0, &e.1)) } /// Like `get`, but can operate on any type that is equivalent to a key. pub fn ...
Rust
0
({ 'direccion': 'Falucho entre Ayacucho y Pringles', 'departamento': 'Juan Martín de Pueyrredón' }) self.assertTrue(resp_btwn_1 and not resp_btwn_2) def test_basic_fields_set(self): """Se debería poder especificar un conjunto de parámetros preseleccionados l...
Python
1
# pygame.math module, pygame.math.Vector2 object # https://www.pygame.org/docs/ref/math.html # # Python center axis rotation segment # https://stackoverflow.com/questions/64446045/python-pygame-center-axis-rotation-segment-line/64446683#64446683 # # GitHub - PyGameExamplesAndAnswers - Vector - Reflection # https://gith...
Python
1
ed(); } else { root_name = torrent.metainfo .info() .files() .next() .unwrap() .paths() .next() .unwrap() ...
Rust
0
Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn...
Rust
0
internal_error_expr = None; let mut symbol_table = SymbolTable::default(); while !input.is_empty() { let lookahead = input.lookahead1(); if lookahead.peek(kw::read) { readers.push(input.parse()?) } else if lookahead.peek(kw::internal_erro...
Rust
0
ice}; /// /// assert_eq!( /// RSliceMut::from_mut_slice(&mut[0,1,2,3]).as_rslice(), /// RSlice::from_slice(&[0,1,2,3]), /// ); /// /// ``` pub fn as_rslice(&self) -> RSlice<'_, T> { self.as_slice().into() } /// Creates an `RSlice<'a, T>` with access to all the el...
Rust
0
::SCOPE_OP)?; trace!("Parsing scope op"); let scope_end_offset = self.parse_pkg_length()?.end_offset; let name_string = self.parse_name_string()?; let containing_scope = self.scope.clone(); self.scope = name_string; let _term_list = self.parse_term_list(scope_end_offset...
Rust
0
num = int(input("Digite um número: ")) resto = num % 5 print(resto)
Python
1
raise ValueError(f"Invalid OpenAI model name: {value}") elif model_type == "mistral" and value not in ["mistral-tiny", "mistral-small", "mistral-medium"]: raise ValueError(f"Invalid Mistral model name: {value}") elif model_type == "claude" and value not in ["claude-3.5-sonnet"]: ...
Python
1
carname = "Volvo" #print('test')
Python
1
lse: assert False, 'Unknown RandAugment config section' if use_cmc: ra_ops = rand_augment_ops_cmc(magnitude=magnitude, hparams=hparams) else: ra_ops = rand_augment_ops(magnitude=magnitude, hparams=hparams) choice_weights = None if weight_idx is None else _select_rand_weights(weig...
Python
1
ions<'a, T> { pub(crate) fn new(items: Vec<T>) -> Self { Self { items, ..Self::default() } } pub(crate) fn pre_select(&mut self, item: impl Into<Option<u32>>) -> &mut Self { let item = item.into(); if let Some(item) = item { assert!( ...
Rust
0
ESC_LUA: &[u8; 4] = b"\x1bLua"; pub const LUAC_VERSION: u8 = 0x54; pub const LUAC_FORMAT: u8 = 0; pub const LUAC_DATA: &[u8; 6] = b"\x19\x93\r\n\x1a\n"; pub const INSTRUCTION_SIZE: u8 = 4; pub const LUA_INTEGER_SIZE: u8 = 8; pub const LUA_NUMBER_SIZE: u8 = 8; pub const LUAC_INT: i64 = 0x5678; pub const LUAC_NUM: f64 =...
Rust
0
# IfcOpenShell - IFC toolkit and geometry engine # Copyright (C) 2022 Dion Moult <dion@thinkmoult.com> # # This file is part of IfcOpenShell. # # IfcOpenShell is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundat...
Python
1
df, 0xfd, 0x77, 0x9d, 0xd6, 0x3c, 0xb4, 0xd7, 0xff, 0xc, 0x6b, 0xf6, 0xd5, 0x9c, 0x85, 0xb3, 0x5f, 0x41, 0xaa, 0x5e, 0x8e, 0x32, 0xeb, 0xa0, 0xe8, 0x16, 0x6b, 0x86, 0xd4, 0x5b, 0xd0, 0xbb, 0x24, 0x14, 0x49, 0xd4, 0x93, 0x7f, 0xa7, 0xa3, 0x8, 0x6c, 0x4d, 0x8b, 0x8c, 0x37, 0x74, 0xae, 0x1c, 0xcb, ...
Rust
0
bench reports the diff between max/min. That // means we want a bar of equal height on top and // bottom, so divide by 2. let y_errors = ds_measurements.iter().map(|&i| measurements[i].variance); axes.y_error_lines(xs, ys, y_errors, &options); ...
Rust
0
import torch import numpy as np def plot_multivariate_gaussian(mu, Sigma, sigma_range=3.0): device = mu.device e,Q = torch.linalg.eigh(Sigma) Sigma_sqrt = Q @ torch.diag(torch.sqrt(e)) @ Q.T N = 1001 sigma_range = torch.linspace(-sigma_range, sigma_range, N, device=device) x, y = torch.meshgrid(sigma_r...
Python
1
import sys from collections import namedtuple from normir.files_with_list import CAUSE_PRESENCE_OF_DOWNTIME_LIST, CAUSE_PRESENCE_OF_DOWNTIME_CLASSIFICATIONS_LIST, \ OPERATIONS_OF_DOWNTIMES_LIST, CONTRACTOR_ZHGS_LIST from PyQt5.QtGui import QIntValidator, QDoubleValidator from PyQt5.QtWidgets import QWidget, QLabel...
Python
1
self): num_tasks = self.loop.run_until_complete(recursive_taskgroups(5, 4)) self.assertEqual(self.counter.get(), self.expected_task_count) def test_recursive_gather(self): self.loop.run_until_complete(recursive_gather(5, 4)) self.assertEqual(self.counter.get(), self.expected_task_co...
Python
1
s.is_empty() } pub fn remove_by_id(&mut self, id: Index) { let filter = move |(name, ent): (&Name, &Entity)| { if ent.id() == id { Some(name.clone()) } else { None } }; // OPT: This is super inefficient... if let S...
Rust
0
get_unknown_gen(i) .map(|(c, h)| (c, ColliderHandle(h))) } /// Gets a mutable reference to the collider with the given handle without a known generation. /// /// This is useful when you know you want the collider at position `i` but /// don't know what is its current generation number. ...
Rust
0
upsample.flops() return flops if __name__ == '__main__': device = 'cuda' window_size = 8 height = 128 width = 128 model = SwinIR(img_size=(height, width), window_size=window_size, img_range=1., depths=[6, 6, 6, 6], embed_dim=60, num_heads=[6, 6, ...
Python
1
CH1_R { DMA_IN_REMAIN_UNDER_1B_CH1_R::new(((self.bits >> 23) & 0x01) != 0) } #[doc = "Bits 2:7"] #[inline(always)] pub fn dma_infifo_cnt_ch1(&self) -> DMA_INFIFO_CNT_CH1_R { DMA_INFIFO_CNT_CH1_R::new(((self.bits >> 2) & 0x3f) as u8) } #[doc = "Bit 1"] #[inline(always)] pu...
Rust
0
()) } } #[cfg(test)] mod tests { use super::super::protocol::*; use super::*; #[test] fn ignores_empty_input() { let mut codec = KeyValueCodec::new(); let mut input = BytesMut::new(); let result = codec.decode(&mut input); assert_eq!(None, result.unwrap()); ...
Rust
0
m_bindgen (structural , method , getter , js_class = "GPUSupportedLimits" , js_name = maxStorageBufferBindingSize)] #[doc = "Getter for the `maxStorageBufferBindingSize` field of this object."] #[doc = ""] #[doc = "[MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/API/GPUSupportedLimits/maxSt...
Rust
0
n(file_name)?; let mut vec = Vec::new(); file.read_to_end(&mut vec)?; let size = vec.len(); if size < MIN_SRAM_SIZE || size > MAX_SRAM_SIZE || !size.is_power_of_two() { return Err(Error::new(ErrorKind::InvalidData, "Invalid SRAM size")); } let mut bytes = ve...
Rust
0
import windse import pytest import numpy as np from dolfin import * import windse_driver.driver_functions as df ############################################################### ######################## Setup Objects ######################## ############################################################### ### Alias Para...
Python
1
# Generated by Django 5.0.6 on 2024-08-27 07:59 import django.db.models.deletion import smart_selects.db_fields from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('providers', '0065_rename_price_courseprice_week_price_promotional_and_more'), ('quotations', ...
Python
1
Ok(None) } else if op.mem.scale > 0 { // this is something like `JMP [0x1000+eax*4]` (32-bit) Ok(None) } else { println!("{:#x}: get mem op xref", va); print_op(op); panic!("not supported"); } } // for a memory operand, like `mov eax, [0x401000]` // fetch what the po...
Rust
0
# Part of Odoo. See LICENSE file for full copyright and licensing details. import freezegun from odoo.tests.common import tagged from odoo.addons.l10n_mx_edi.tests.common import TestMxEdiCommon @tagged('-at_install', 'post_install', 'post_install_l10n') class TestMxEdiHrPayrollCommon(TestMxEdiCommon): @classme...
Python
1
dgeMathVerifier(k, model_name, url) else: judge_model = RuleBasedMathVerifier(k) return SampleLevelMetricGrouping( # use : to split metric_name and num_generations metric_name=f'Math_G-Pass@k:{n}', higher_is_better={ metric: True for metric in judge_model.get_all...
Python
1
/// add message handlers,priority is a u16 type /// 0 is highest priority,and 0xFFFF is the lowest priority. /// higher priority will be called first when there are more than one listeners for a message impl<'a,T> DlgMsg<'a,T> { // this should be called before TranslateMessage and DispathMessage // /// P...
Rust
0
ad_line(&mut input).unwrap(); let p: f32 = match input.trim().parse() { Ok(i) => i, Err(_) => { println!("you input error!!!"); continue; } }; account.balance.set(a...
Rust
0
tem.inventory["Dog Food"]["quantity"] == 10 def test_manage_inventory_use_item_insufficient(shelter_system): """Test using more inventory than available.""" shelter_system.inventory = {"Dog Food": {"quantity": 5, "reorder_threshold": 5}} result = shelter_system.manage_inventory("use", "Dog Food", 10) ...
Python
1
# turkish_nlp_toolkit/sentiment.py import re # Örnek pozitif/negatif kelime listeleri; projede dışarıdan genişletilebilir. POSITIVE_WORDS = { "güzel","harika","mükemmel","iyi","sevinç","mutlu","başarılı","hoş","şahane", "enfes","keyif","teşekkür","iyi" } NEGATIVE_WORDS = { "kötü","berbat","rezil","üzgün",...
Python
1
import pandas as pd import json file_name = "conversational_chat_response_0" df = pd.read_csv(f'{file_name}.csv') with open(f'{file_name}.jsonl', 'w') as f: for _, row in df.iterrows(): json_data = {"prompt": row['prompt'], "completion": row['completion'], 'response': row['response']} f.write(json...
Python
1
let end = (start + MAX_DETS as i64).min(num_dets); let ltrb_chunk = ltrb.i((start..end, ..)); let conf_chunk = conf.i((start..end, ..)); let group_chunk = group.i(start..end); let keep_chunk = tch_nms::nms_by_s...
Rust
0
import pygame import sys pygame.init() SCREEN_WIDTH = 800 SCREEN_HEIGHT = 600 screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) pygame.display.set_caption("Moving Image") BACKGROUND_COLOR = (136, 136, 136) # RGB values for #888888 # Load the image image = pygame.image.load('/Users/m.salim/PycharmProj...
Python
1
rsons to whom the Software // is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice // shall be included in all copies or substantial portions // of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF // ANY KIND, EXPRESS OR IMPL...
Rust
0
# This script assumes that the user has pip-installed the pytetrad package. Here is how: ## pip install git+https://github.com/cmu-phil/py-tetrad import pandas as pd import pytetrad.tools.TetradSearch as ts data = pd.read_csv("resources/airfoil-self-noise.continuous.txt", sep="\t") # data = pd.read_csv("resources/sa...
Python
1
\": \"2012-10-17\", \"Statement\": [{ \"Effect\": \"Allow\", \"Principal\": {\"AWS\": \"{}\"}, \"Action\": \"sts:AssumeRole\" }]}" .to_string(); let role_policy_document = role_policy_document.replace("{}", user.unwrap().arn.as_ref().unwrap()); let...
Rust
0
x = 10 y = 2 z = 15 print(z / 2) print(z // 2) print(z % 2)
Python
1
, but a field is expected." ))), }?, tags.to_owned(), )) } pub fn as_fields(&self) -> Result<(HashMap<String, Field>, Vec<String>), TypeDecError> { let (anon_type, tags) = match self { DenormalizedType::Annotated(inner, tags, _) => (inner, tag...
Rust
0
ue) max_dist = estimate_max_distance(laser, base_receiver, min_snr) print(f" При мощности {power} Вт: {max_dist:.1f} м") # 2. АНАЛИЗ ВЛИЯНИЯ ПЛОЩАДИ ПРИЕМНИКА plt.figure(figsize=(12, 8)) # Для разных площадей приемника с фиксированной мощностью power = 60 # Вт laser = Transmitter...
Python
1
import os import google.generativeai as genai # pip install -q -U google-generativeai class GeminiChat: def __init__(self, model_name): self.model_name = model_name self.api_key = os.getenv("GOOGLE_API_KEY") try: genai.configure(api_key=self.api_key) self.model = g...
Python
1
yFlags::WRITABLE); // Mark all entries as unused in the newly created table. let subtable = self.subtable::<S>(page); for entry in subtable.entries.iter_mut() { entry.physical_address_and_flags = PhysAddr::zero(); } } let subtable = self.subtable::<S>(page); subtable.map_page::<S>(page, ...
Rust
0
00, 4.12479856412430479e+00, -4.03523417114321381e-01, 0.0 ], v : [ -2.76742510726862411e-03 * DAYS_PER_YEAR, 4.99852801234917238e-03 * DAYS_PER_YEAR, 2.30417297573763929e-05 * DAYS_PER_YEAR, 0.0 ], mass ...
Rust
0
# Ingesting Policy Data import dlt from pyspark.sql import functions as F from pyspark.sql.types import * # DBTITLE 1,Define VOLUME_PATH = "/Volumes/insure_for_all/source/raw/policy/" SCHEMA_LOC = "/Volumes/insure_for_all/_schemas/policy_stg" # Explicit schema (prefer this over inferSchema) customer_schema = Stru...
Python
1
ight:.0f}', ha='center', va='bottom', color='white', fontsize=12) plt.tight_layout() plt.show() # Tampilkan plot di Streamlit st.pyplot(fig) except FileNotFoundError: st.write("Belum ada data konsultasi.") except Exception as e: st.error(f"Terjadi kesalahan: {e}"...
Python
1
v().is_err()); } } <reponame>sacooper/Copper #[macro_use] extern crate log; extern crate rustc_serialize; extern crate mmap; extern crate libc; extern crate rand; pub mod executor; pub mod entry; pub mod persist; pub mod database; mod util; mod index; pub use database::*; use { std::path::{Components, PathBuf...
Rust
0
pub fn feed_atom_footer<W, E>(into: &mut W, out_name_err: E) -> Result<Cow<'static, str>, Error> where W: Write, E: Into<Cow<'static, str>> { feed_atom_footer_impl(into, out_name_err.into()) } /// Output the post header for an Atom feed, /// /// The `post_id_name` argment is used as the entry GUID, /...
Rust
0
"admin": [ "system_status_monitoring", "security_permission_management", "multi_agent_system_management", "data_management", "strategy_development", "ai_decision_support", "portfolio_management", "risk_management", "trade_execution", "ai_model_management", "backtest_...
Python
1
-> IResult<&str, Expr> { map(preceded(space0, terminated(float, tag("f"))), |v: f32| Expr::F(v))(i) } /// parse_double parses a 64-bit floating point value, preceded by 0+ spaces. /// doubles are decimal precision numbers w/out a trailing f fn parse_double(i: &str) -> IResult<&str, Expr> { // if OK, parse it ...
Rust
0