text
string
label_name
string
labels
int64
) if dir.endswith(('.jpg', '.png')): text = dir.split('__')[0] if '_' in dir else dir.split('.png')[0] with open(os.path.join(path, text.replace(' ','_')+f'_{num}.gt.txt'), 'w') as file: file.write(text) os.rename(os.path.join(path, dir), os.path.join(path, te...
Python
1
"""Slack bot chapters command.""" from apps.slack.commands.command import CommandBase from apps.slack.common.constants import COMMAND_HELP, COMMAND_START from apps.slack.common.handlers.chapters import get_blocks from apps.slack.common.presentation import EntityPresentation class Chapters(CommandBase): """Slack ...
Python
1
import numpy as np from pyscf import gto, scf from pyxdh.Utilities import FormchkInterface from pkg_resources import resource_filename from pyxdh.DerivOnce import DipoleUSCF, DipoleUMP2 class TestDipoleU: mol = gto.Mole(atom="C 0. 0. 0.; H 1. 0. 0.; H 0. 2. 0.; H 0. 0. 1.5", basis="6-31G", spin=1, verbose=0).bui...
Python
1
}; bind_multicast(&socket, &addr)?; Ok(socket.into_udp_socket()) } fn main() { let max_retries = 5; let worker_id = Uuid::new_v4(); println!("Initialising worker {}", worker_id); let mut retries = 1; while establish_connection(worker_id).is_none() { if retries >= max_retries { ...
Rust
0
_output() .expect_success(); // BigQuery to gs://. testdir .cmd() .args(&[ "cp", "--if-exists=overwrite", &format!("--schema=postgres-sql:{}", schema.display()), &bq_table, &gs_dir_2, ]) .tee_output() .e...
Rust
0
# -*- coding: utf-8 -*- # # This file is part of Karesansui. # # Copyright (C) 2009-2012 HDE, Inc. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without lim...
Python
1
feature = "Win32_Foundation")] pub union WIAS_CHANGED_VALUE_INFO_1 { pub lVal: i32, pub fltVal: f32, pub bstrVal: super::super::Foundation::BSTR, pub guidVal: ::windows_sys::core::GUID, } #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for WIAS_CHANGED_VALUE_INFO_1 {} #[cfg(feature = "Win...
Rust
0
'# speech_blackboard_purges -> detail_plastic_gangways' 0 import tc2t8w2oe0i as mhdr9ya194a from gsjyc6bjd93 import yz1zp20phyw as i_fyqvmqm78, l324um4ta0r, m4_27knifu7, mtcop83gatv as nqkgo3bni28, q7vka1tea8m, b0fumt3lo18 as ul3y45cfgqu, f62g1_4f9bo as buhaoei6gzr assert r8p4blfhys0 nabe_oqcub...
Python
1
if size > 0 { array[size - 1] = 0; } array } // Push middle pub fn helper_random_array_push_middle_i64(size: usize) -> Vec<i64> { let mut array = (0..size).into_par_iter().map(|i| i as i64).collect::<Vec<i64>>(); if size > 0 { array[size - 1] = (size / 2) as i64; } ...
Rust
0
(&self.buffer, other.buffer(), blend_op, intensity)) } pub fn drawing(&self, radius: u32, mode: DrawingMode) -> Image { Self::new_from_buffer_with_meta(self, ops::drawing(&self.buffer, radius, mode)) } pub fn interlace(&self, offset: u32) -> Image { Self::new_from_buffer_with_meta(self...
Rust
0
se None, error_y=y_error[index] if y_error else None, meta=get_meta(series_names, index, hover_data, y), hovertemplate=get_hover_template(hover_data), mode=get_mode(lines, markers), marker_size=8, con...
Python
1
tant self.scale_1x1.requires_grad_(False) self.scale_conv.requires_grad_(False) if use_se: raise NotImplementedError("se block not supported yet") else: self.se = nn.Identity() def forward(self, inputs): out = self.scale_conv(self.conv(inputs)...
Python
1
, "10 mins"), BarSize::_15Mins => write!(f, "15 mins"), BarSize::_20Mins => write!(f, "20 mins"), BarSize::_30Mins => write!(f, "30 mins"), BarSize::_1Hour => write!(f, "1 hour"), BarSize::_4Hours => write!(f, "4 hours"), BarSize::_1Day => write!(f...
Rust
0
parent_message_weakref = weakref.proxy(parent_message) # As an optimization, we also indicate directly on the listener whether # or not the parent message is dirty. This way we can avoid traversing # up the tree in the common case. self.dirty = False def Modified(self): if self.dirty: ret...
Python
1
GamalPK) -> (ElGamalCT, ElGamalRand) { ElGamal::encrypt(pk, self) } } #[derive(Serialize, Deserialize, Clone, Copy, Debug, Eq, PartialEq)] pub struct ElGamalPK(pub RistrettoPoint); impl ElGamalPK { pub fn encrypt(self, msg: GroupEncoding) -> (ElGamalCT, ElGamalRand) { ElGamal::encrypt(self, msg...
Rust
0
Some(info) => cb_sink .send(Box::new(|s| update_time_from_properties(s, info))) .map_err(|err| Error::CrossbeamSendError(err.to_string()))?, None => (), // I guess we didn't get the data this time.. } ...
Rust
0
olumns, keys): # GH#43999 df = DataFrame({"a": [1, 1, 2, 3], "b": [4, 5, 6, 7]}) df[cat_columns] = df[cat_columns].astype("category") msg = "The default of observed=False is deprecated" klass = FutureWarning if set(cat_columns) & set(keys) else None with tm.assert_produces_warning(klass, match=m...
Python
1
_sets(&ALL[3..7], &|v: f64| libm::powd(*val, v), &|_| f64::NAN); }) }); } #[test] fn normal_cases() { assert_eq!(libm::powd(2.0, 20.0), (1 << 20) as f64); assert_eq!(libm::powd(-1.0, 9.0), -1.0); assert!(libm::powd(-1.0, 2.2).is_nan()); assert!(libm::powd(-1.0, -1.14).is_nan()); } #[test] ...
Rust
0
19-01-11T04:41:19Z in UTC let utc_date = Utc.ymd(2019, 1, 11).and_hms(23, 41, 19); let updated = Utc .ymd(utc_date.year(), utc_date.month(), utc_date.day()) .and_hms(0, 0, 0); assert_eq!(updated, Utc.ymd(2019, 1, 11).and_hms(0, 0, 0)); } #[test] fn calculate...
Rust
0
{"role": "user", "content": f"故事提示:{prompt}\n主题:{themes}\n世界观:{setting}\n角色:{characters}"} ], complexity="complex") self.current_story["outline"] = outline logger.info("故事大纲创建完成") # 5. 生成章节梗概(复杂任务) logger.info("Step 5/6: 生成章节梗概......
Python
1
:{Duration, Instant}, }; use dashmap::DashMap; use tokio::io::unix::AsyncFd; use tokio::time::timeout; use crate::error::{Error, Result}; use crate::packet::{icmpv4, icmpv6, IcmpPacket}; use crate::socket; #[derive(Debug)] pub struct AsyncSocket { inner: AsyncFd<socket::Socket>, } impl AsyncSocket { pub fn...
Rust
0
led by adding feature flags to your //! `Cargo.toml` file: //! //! - **std:** adds `std::error::Error` impls to any errors and switches to //! `Vec` for the default backing buffers //! - **serde-1:** allows serializing and deserializing most types with `serde` #![deny( bare_trait_objects, elided_lifetimes_in_...
Rust
0
); impl_try_from_bitwise!( Int128Impl, i128, 113, [114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128,] ); impl_try_from_bitwise!( Int128Impl, i128, 114, [115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 1...
Rust
0
import os import sys import requests def download_page(num, page, output_dir="data/raw"): """ Download a single HTML page given the numeric part and page number. The URL pattern is: http://[base]/kent{num_formatted}.htm#P{page} The downloaded file is saved as "kent{num_formatted}_P{page}.html...
Python
1
de::Component(comp) => comp.reorder(parent, next), VNode::None => Ok(()) } } fn remove(&self, parent: &Self::Node) -> Result<(), JsValue> { match self { VNode::Text(txt) => txt.remove(parent), VNode::Element(el) => el.remove(parent), VNode::List(l...
Rust
0
if (mid as i64) * (mid as i64) <= x as i64 { ans = mid; left = mid + 1; } else { right = mid - 1; } } ans } /// 力扣(69. x 的平方根) /// 方法2:换底公式(自然数e为底) pub fn my_sqrt_v2(x: i32) -> i32 { if x == 0 { return 0; } // x1/2=(elnx)1/2=e21​lnx /...
Rust
0
aw * sin_pitch, cos_pitch, cos_yaw * sin_pitch]; let zaxis = [sin_yaw * cos_pitch, -sin_pitch, cos_pitch * cos_yaw]; let cam_arr = [cam.pos.0, cam.pos.1, cam.pos.2]; [ [xaxis[0], yaxis[0], zaxis[0], 0.0], [xaxis[1], yaxis[1], zaxis[1], 0.0], [xaxis[2], yaxis[2], zaxis[2], 0.0], ...
Rust
0
exhaustive enums, i.e., no enum has the `#[non_exhaustive]` attribute //! - `no_vex`: Disables all `VEX` instructions. See below for more info. //! - `no_evex`: Disables all `EVEX` instructions. See below for more info. //! - `no_xop`: Disables all `XOP` instructions. See below for more info. //! - `no_d3now`: Disable...
Rust
0
/// to reserve adding new trait implementations to it later. It can be /// ignored for now. pub fn spawn<F>(f: F) -> Spawn where F: Future<Item=(), Error=()> + Send + 'static, { tokio::spawn(f); Spawn { _inner: (), } } /// Start the Tokio runtime using the supplied future to bootstrap executio...
Rust
0
e = "CFBundleIdentifier")] pub bundle_identifier: String, /// The bundle ID of the watchOS app. /// /// This key is automatically included in your WatchKit extension’s /// information property list when you create a watchOS project from a template. /// /// ## Availability /// * watchOS 2...
Rust
0
)cntpref_cntrrrs rK _format_count%memory_summary.<locals>._format_countZ"!"12,J*$F DLC  H ' b6(!$$rJallocated_bytesAllocated memory active_bytes Active memoryrequested_bytesRequested memoryreserved_bytesGPU reserved memoryinactive_split_bytesNon-re...
Python
1
可变借用,而这里要获取v的所有权,这是不允许的 // 2 下面的 println! 语句无法使用 v,因为v的所有权已经被for语句获取,for之后v已经无效 for x in v{ println!("{}",x); } //println!("{:?}",v); } fn step2(){ struct Counter{ count : u32, } impl Counter { fn new() -> Counter{ Counter{count: 0} ...
Rust
0
_CATEGORY, 1+len(Certs))) sep = ' ' for i in xrange(0, len(Certs)): out.write('%s{ %s_Data, %s_Size} /* %s */' % (sep, CertNames[i], CertNames[i], CertComments[i])) sep = ',\r\n ' out.write(sep+'{0, 0} /* sentinel */\n') out.write('};\n') out.close() out = open('NptTlsDefaultTrustAnchors'+CERT_CATEGO...
Python
1
neration_path)) }) .map_err(|_| DieselError::RollbackTransaction)?; Ok(()) })?; Ok(()) } pub fn rollback_ns(&self, ns_name: &Name, gen: i32) -> Result<()> { let ns_entry = self.ns_entry_for_name(ns_name)?; let _lock = self ...
Rust
0
e std::io::Write; use std::os::unix::fs::PermissionsExt; use std::path::{Path, PathBuf}; use tar::{Archive, Builder}; pub const REPLICA_KEY: &str = "replica"; pub const NODEMANAGER_KEY: &str = "nodemanager"; #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct ReleaseIdentifier(pub [u8; 32]); imp...
Rust
0
predicted_tensor_list = [torch.from_numpy(predicted_array) for predicted_array in predicted_fold] targets_tensor = torch.cat(targets_tensor_list, dim=0) predicted_tensor = torch.cat(predicted_tensor_list, dim=0) # Print the F1-score, precision, and recall print() print('F1-sco...
Python
1
import os def search_pattern(pattern, data): """使用Boyer-Moore算法搜索字节模式""" m = len(pattern) n = len(data) if m == 0 or n == 0: return -1 # 预处理跳转表 jump_table = [m] * 256 for i in range(m - 1): jump_table[pattern[i]] = m - 1 - i # 搜索模式 i = m - 1 while i < n: ...
Python
1
span, callee: ExprOrSuper::Expr(box Expr::Member(MemberExpr { span: DUMMY_SP, obj: ExprOrSuper::Expr(box Expr::Ident(i.clone())), prop: box Expr::Ident(Ident::new("call".into(), sp...
Rust
0
_base_ = ['./repmlp-base_8xb64_in1k.py'] model = dict(backbone=dict(deploy=True))
Python
1
extend_from_slice(&value.to_f32().unwrap().to_bits().to_be_bytes()), DataType::F64 => data.extend_from_slice(&value.to_f64().unwrap().to_bits().to_be_bytes()), } } fn read_u32(data: &Vec<u8>, index: usize) -> Result<u32> { if index > data.len() - 4 { return Err(Error::new(ErrorKind::InvalidData...
Rust
0
e crate::token; #[test] fn codegen() { let input = token::scan(r#" .text _start: ; program entry point ; disable interrupts di ; no operation nop fini: ; halt the cpu ...
Rust
0
64_sae 0x82,// 'v', Normal_2 0x8F, 0x09,// 1167 = "vrcp28sd" 0x08,// 0x8 = ShowNoMemSize_ForceSize // Sha256msg1_xmm_xmmm128 0x01,// Normal_1 0xCD, 0x09,// 1229 = "sha256msg1" // EVEX_Vrsqrt28ps_zmm_k1z_zmmm512b32_sae 0x81,// 'v', Normal_1 0xA7, 0x09,// 1191 = "vrsqrt28ps" // EVEX_Vrsqrt28pd_zmm_k1z_zmmm51...
Rust
0
= *input, None => { println!("Waiting for input at {}", i); break; }, }; i += 2; }, (4, Some(arg1), _, _) => { output = Some(code[arg1]); // if let Some(o) = output { // println!("Diagnostic test output: {}", o); // } i += 2; }, (5, Some(arg1), Some(arg2),...
Rust
0
Debug)] pub(crate) struct KeyVaultGetCertificateResponse { kid: String, sid: String, x5t: String, cer: String, id: String, attributes: KeyVaultGetCertificateResponseAttributes, policy: KeyVaultGetCertificateResponsePolicy, } #[derive(Deserialize, Debug)] pub(crate) struct KeyVaultGetCertif...
Rust
0
class Solution(object): def twoCitySchedCost(self, costs): """ :type costs: List[List[int]] :rtype: int """ costs.sort(key=lambda x: x[0] - x[1]) print(costs) n = len(costs) // 2 return sum(costs[i][0] for i in range(n)) + sum(costs[i][1] for i in rang...
Python
1
batch_size, max_steps=1000, dataloader_num_workers=args.num_workers, dataloader_pin_memory=True, report_to=["tensorboard"], # log statistics for tensorboard ) # #### Preprocessing of training data # We tokenize the data into torch tensors, split training into training and v...
Python
1
self.assertFalse(cg_mock.called) if distribution_cls is gpytorch.variational.CholeskyVariationalDistribution: # finally test fantasization # we only will check that tossing the entire training set into the model will reduce the mae model.likelihood = likelih...
Python
1
ax.set_proj_type('ortho') #this is better for e.g. xy view if axesEqual: ax.set_aspect('auto') ax.set_box_aspect([1,1,1]) ax.autoscale() #end 3D plotting if title!='': plt.title(title) plt.autoscale() # plt.margins(0.1) plt.tight_layout() #not...
Python
1
"message": st.session_state["generated"][-1], "is_user": False, "keyname": "assistant" + str(timestamp_str()), } ) message(st.session_state["generated"][-1], is_user=False) # 模型返回未知的场景标签 elif not is_numbe...
Python
1
write_striple_with_enc(&cypher,&pubstriples.pubsha256,None,&mut datafile, &public_enc).unwrap(); write_striple_with_enc(&cypher,&pubstriples.rsa2048_sha512,None,&mut datafile, &public_enc).unwrap(); write_striple_with_enc(&cypher,&pubstriples.ecdsaripemd160,None,&mut datafile, &public_enc).unwrap(); } #[cfg(feat...
Rust
0
transform: number_transform, ..Default::default() }) .insert(CellNumber) .id(); commands .entity(cell_entity) .insert_relation(DisplayedBy, text_entity); } } } mod actions { us...
Rust
0
[test] fn test_add_user() -> common_exception::Result<()> { let usr_mgr = UserMgr::new(); let name = "test_user"; let pass = "<PASSWORD>"; let salt = "<PASSWORD>"; let pass_hash: [u8; 32] = Sha256::digest(pass.as_bytes()).into(); let salt_hash: [u8; 32] = Sha256::digest(salt.as_bytes()).into(); ...
Rust
0
from collections import defaultdict class RangeFreqQuery: def __init__(self, arr): """ Initializes the class with the given array `arr`. """ self.freq_map = defaultdict(list) for index, value in enumerate(arr): self.freq_map[value].append(index) def query(se...
Python
1
def find_golomb_count(n): # Initialize memoization dictionary with the base case memo = {1: 1} # Iterate from 2 to n to compute Golomb sequence terms iteratively for i in range(2, n + 1): # Compute the next term in the Golomb sequence using the formula: # G(n) = 1 + G(n - G(G(n - 1))) ...
Python
1
that's annoying and stupid for several reasons. // We redefine them as u8's. pub const VK_LBUTTON: u8 = 0x01; pub const VK_RBUTTON: u8 = 0x02; pub const VK_CANCEL: u8 = 0x03; pub const VK_MBUTTON: u8 = 0x04; pub const VK_XBUTTON1: u8 = 0x05; pub const VK_XBUTTON2: u8 = 0x06; pub const VK_BACK: u8 = 0x08; pub const VK_T...
Rust
0
res.status(), "Received payload:: {:?}", response_as_str(res) ); Ok(()) } #[actix_rt::test] async fn should_add_and_delete_record() -> anyhow::Result<()> { std::env::set_var("RUST_BACKTRACE", "full"); let db_manager = DbManager::new(DbConfig::new_per_test_defaults())?; let ...
Rust
0
#[m48_robo_rust::entry] fn main() -> ! { let dp = m48_robo_rust::Peripherals::take().unwrap(); let mut pinsd = dp.PORTD.split(); let mut serial = m48_robo_rust::Serial::new( dp.USART0, pinsd.pd0, pinsd.pd1.into_output(&mut pinsd.ddr), 2400, ); ufmt::uwriteln!(&mut ...
Rust
0
use crate::jpeglib_h::JDITHER_FS; pub use crate::jpeglib_h::JDITHER_NONE; pub use crate::jpeglib_h::JDITHER_ORDERED; pub use crate::jpeglib_h::JHUFF_TBL; pub use crate::jpeglib_h::JPEG_ROW_COMPLETED; pub use crate::jpeglib_h::JPEG_SCAN_COMPLETED; pub use crate::jpeglib_h::JPEG_SUSPENDED; pub use crate::jpeglib_h::JPOO...
Rust
0
ram dt: time step size [s] :return: new ACC state """ # Plan the ACC trajectory based on the selected controller a_acc = acc_planner.acc_control(node.lead_state.velocity, node.acc_state.velocity, node.get_lead_x_position_rear(lead_vehicle_param), ...
Python
1
.wgsl") .unwrap() .contents_utf8() .unwrap(), )), }); let blit_frag = args.device.create_shader_module(&ShaderModuleDescriptor { label: Some("tonemapping frag"), source: ShaderSource::Wgsl(Cow::Borrowed( ...
Rust
0
bits { 0 => Some(LED_RGB_MODE_A::GRB), 1 => Some(LED_RGB_MODE_A::GBR), 2 => Some(LED_RGB_MODE_A::RGB), 3 => Some(LED_RGB_MODE_A::RBG), 4 => Some(LED_RGB_MODE_A::BGR), 5 => Some(LED_RGB_MODE_A::BRG), _ => None, } } #[doc ...
Rust
0
# Generated by Django 5.1 on 2025-05-29 07:34 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("larpmanager", "0021_association_nationality_featuremodule_nationality"), ] operations = [ migrations.AlterUniqueTogether( name="ass...
Python
1
lt, self.position), // ) // } // } // // impl<'a> From<&str> for Input<'a> { // fn from(content: &str) -> Self { // Input { // content, // position: 0, // } // } // } // // impl<'a> InputTake for Input<'a> { // fn take(&self, count: usize) -> Self { // ...
Rust
0
)).expect("Error writing in file"); } /// foo // /// <caret>/ bar <gh_stars>1000+ use std::process::{Child, Command, Output, Stdio}; use std::ffi::OsStr; #[cfg(target_os = "windows")] use std::os::windows::process::CommandExt; #[cfg(target_os = "windows")] const CREATE_NO_WINDOW: u32 = 0x08000000; #[cfg(target_os = ...
Rust
0
as e: logger.error(f"태그 목록 조회 중 오류 발생: {str(e)}") raise ObsidianError(f"Failed to get all tags: {str(e)}") @mcp.tool() def add_tag_to_file(vault_name: str, file_path: str, tag: str) -> dict: """파일에 태그 추가""" try: logger.info(f"파일에 태그 추가 시작 - Vault: {vault_name}, 파일: {file_path}, 태그: {ta...
Python
1
declare module 'foo' {}"#, r#"declare module foo {}"#, r#"declare namespace foo {}"#, }; } #[test] fn no_namespace_invalid() { assert_lint_err! { NoNamespace, "module foo {}": [{col: 0, message: MESSAGE }], "namespace foo {}": [{col: 0, message: MESSAGE }], "namespace ...
Rust
0
ess_state.to_owned(), process_char: process.process_state_char, process_description_prefix: None, is_disabled_entry: false, is_collapsed_entry: false, user, }, ); } } // Now c...
Rust
0
set()?; assert_eq!(ws, vec![None]); } Ok(()) } #[test] fn add_to_working_set() -> anyhow::Result<()> { let tmp_dir = TempDir::new()?; let mut storage = KvStorage::new(&tmp_dir.path())?; let uuid1 = Uuid::new_v4(); let uuid2 = Uuid::new_v4(); ...
Rust
0
import dash from dash import html import dash_bootstrap_components as dbc dash.register_page(__name__, path='/paper') layout = dbc.Container([ dbc.Row([ dbc.Col(html.H2("Paper"), className="text-center my-4") ]), dbc.Row( dbc.Col([ 'Please cite', html.Ul([ ...
Python
1
.into_iter() .map(|_| Node::random(rng, &dimensions, &min_max_v, &min_max_radius)) .collect(); World::new(nodes, dimensions, config) } pub fn step_nodes(&mut self, dt: f64) where Coord: Add<Coord, Output=Coord> + AddAssign<Coord> ...
Rust
0
from re import I import h5py import numpy as np from pathlib import Path import pandas as pd np.set_printoptions(precision=3) def get_all(name): if "voxels" in name: print(name) def main(f): f.visit(get_all) print() ts_dataset = f["voxels_removed/voxel_time_stamp"] voxel_color = f["vox...
Python
1
X AccelerometerY AccelerometerZ Subject 1 3 7 8 s01 2 8 9 6 s01 3 8 9 6 s01 """ # if per-column mins and maxes are not provided...
Python
1
image_path, ".png" image_name = os.path.basename(image_path).split(".")[0] try: image = Image.open(image_path) except: image = Image.open(image_path.replace("images", "train")) print(f"Error: {image_path} not found, use {image_path.replace('images', 'train')} ...
Python
1
y) { *self.ctx.cfg.runtime.sim_file.write() = body.into(); Ok(Self::empty_200()) } else { self.error_400() } } else { self.error_400() } } ...
Rust
0
import time from openvino.inference_engine import IECore from tqdm import tqdm import numpy as np import cv2 from skimage import img_as_ubyte import argparse def make_parser(): parser = argparse.ArgumentParser("openvino demo") parser.add_argument( "--source", type=str, help="input source image" ) ...
Python
1
from generate_dataset import generate_gaussian_noise from generate_dataset import generate_series from generate_dataset import generate_squarewave from generate_dataset import generate_sinewave import pandas as pd import pyActigraphy from pytest import approx sampling_period = 60 frequency = pd.Timedelta(sampling_per...
Python
1
from .base import TaskBase from ..stream_filter import StreamFilter from ..enums import EAnnType, EGameEvent, ERegionType, ETurn from ..config import cfg, override, LogDebug, LogInfo from ..regions import REGIONS from ..feature import ActionCardHandler, CropBox, CardName from ..database import SaveImage from ..stream_...
Python
1
subRtAssoc: Type: 'AWS::EC2::SubnetRouteTableAssociation' Properties: SubnetId: { Ref: subnet } RouteTableId: { Ref: rt } rt: Type: 'AWS::EC2::RouteTable' route1: Type: 'AWS::EC2::Route' Properties: GatewayId: { Ref: gw } RouteT...
Rust
0
""" 手写数字识别 运行前需要先下载 MNIST 数据集,并解压到 ./data 目录下。 下载地址:https://www.kaggle.com/datasets/oddrationale/mnist-in-csv MNIST 数据集是手写数字数据集,包含 60000 张训练图像和 10000 张测试图像 """ import torch import torch.nn as nn # 神经网络模块 import torch.optim as optim # 优化器模块 from torch.utils.data import DataLoader # 数据加载器 from torchvision import dat...
Python
1
>>; /// A raw relative pointer that uses an archived `i64` as the underlying offset. #[cfg(target_pointer_width = "64")] pub type RawRelPtrI64 = RawRelPtr<Archived<i64>>; /// A raw relative pointer that uses an archived `u8` as the underlying offset. pub type RawRelPtrU8 = RawRelPtr<Archived<u8>>; /// A raw relative p...
Rust
0
# Importing pandas and matplotlib import pandas as pd import matplotlib.pyplot as plt # Start coding! # Load the CSV and store as a variable netflix_df = pd.read_csv("netflix_data.csv") # Filter the data and remove the tv and store as var netflix_subset = netflix_df[netflix_df['type'] == 'Movie'] # Investigate the...
Python
1
from typing import List def all_prefixes(string: str) -> List[str]: """ Return list of all prefixes from shortest to longest of the input string >>> all_prefixes('abc') ['a', 'ab', 'abc'] """ /0x01-python-if_else_loops_functions/10-add.py #!/usr/bin/python3 def add(a, b): """ Returns the sum o...
Python
1
Err(anyhow!("No active tmux window")) } } else { Err(anyhow!("Couldn't get layouts")) } } fn target(session_name: &str, window_name: &str, pane: i32) -> String { format!( "{}:{}.{}", clean_for_target(session_name), clean_for_target(window_name), pane )...
Rust
0
`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [daddr4](daddr4) module"] pub type DADDR4...
Rust
0
an not being installed. """ major, minor, _ = platform.python_version_tuple() if not int(major) >= 3 and int(minor) >= 5: pytest.skip("Python version below 3.5 TemporaryDirectory not available.") molecule = Molecule(os.path.join(datad, "ethane.com")) engine = Gaussian(molecule=molecule, exe=...
Python
1
= row_group.row_ids_from_predicate(&Predicate::with_time_range(&[], 200, 600)); assert_eq!(row_ids.unwrap().to_vec(), vec![1, 2, 4, 5]); // Fully covering "time range" predicate let row_ids = row_group.row_ids_from_predicate(&Predicate::with_time_range(&[], 10, 601)); assert!(matches!(r...
Rust
0
import pycorrector from pycorrector.macbert.macbert_corrector import MacBertCorrector class ErrorCorrect: def __init__(self, model_path="shibing624_macbert4csc-base-chinese/"): self.m = MacBertCorrector(model_path) def correct(self, input_prompt): correct_sent, err = self.m.macbert_correct(in...
Python
1
. For"] #[doc = " font formats not having this information, it is set to `bbox.yMin`."] #[doc = " Note that this field is negative for values below the baseline."] #[doc = " Only relevant for scalable formats."] #[doc = ""] #[doc = " height ::"] #[doc = " This value is the vertical distance between t...
Rust
0
let (mut head_velocity, mut head_position) = head_query.single_mut().unwrap(); reset_level( &level, (&mut wheel_velocity, &mut wheel_position), (&mut body_velocity, &mut body_position), (&mut head_velocity, &mut head_position), ...
Rust
0
""" from scipy.cluster.vq import kmeans # 注意一下下面的thr不是传入的thr,而是1/thr, 所以在计算指标这方面还是和check_anchor一样 thr = 1. / thr prefix = colorstr('autoanchor: ') def metric(k, wh): # compute metrics r = wh[:, None] / k[None] x = torch.min(r, 1. / r).min(2)[0] # ratio metric # x = wh_...
Python
1
ion = ort.InferenceSession(model_path, so) test_image_path = _this_dirpath / 'MauiSuperResolution' / 'Resources' / 'Raw' / 'lr_lion.png' test_image_bytes = np.fromfile(test_image_path, dtype=np.uint8) outputs = inference_session.run(['image_out'], {'image': test_image_bytes}) upsized_image_bytes = outp...
Python
1
(m)) } _ => Err(serde::de::Error::custom("Default value required")), } } } deserializer.deserialize_seq(JtOffsetsWrapperVisitor {}) } } #[cfg(test)] mod tests; #![feature(plugin)] #![plugin(rocket_codegen)] extern crate rocket; e...
Rust
0
FSET_PATH, false, false); assert_eq!(pcap.is_err(), true); // should fail because offset_path does not exist. assert_eq!(std::path::Path::new(OFFSET_PATH).exists(), false); // 2nd: Create new offset file => success let mut pcap = PcapReaderIndex::new_full_control(PCAP_PA...
Rust
0
ocketAddrs; /// Run an HTTP handler in either AWS Lambda or as a local development HTTP server. /// /// If the `AWS_LAMBDA_RUNTIME_API` environment variable is present (as it is when running in /// Lambda), requests are received via the [AWS Lambda Runtime Interface][lambda-interface]. /// /// If not, an HTTP server i...
Rust
0
import matplotlib.pyplot as plt import numpy as np """ Örnek 1 *** x = [1,2,3,4] y = [1,4,9,16] plt.plot(x,y,"o--r") plt.axis([0,6,0,20]) plt.title("Grafik Başlığı") plt.xlabel("x label") plt.ylabel("y label") plt.show() """ """ Örnek 2 ***""" x = np.linspace(0,2,100) plt.plot(x, x, label="linear",color="red") pl...
Python
1
supply_point .is_empty() { return Err(Error::MissingServiceSupplyPoints); } } } Ok(()) } pub fn prepare_no_op(_: &mut TrustServiceStatusList) -> Result<(), Error> { Ok(()) } fn is_pkc_service(info: &ServiceInformation) -> bool { const ID...
Rust
0
DOM: &'static [u8] = include_bytes!("../data/random.txt"); pub const RANDOM10X: &'static [u8] = include_bytes!("../data/random10x.txt"); pub const WORDS_100_RAW: &'static str = include_str!("../data/words-100"); pub const WORDS_5000_RAW: &'static str = include_str!("../data/words-5000"); pub const WORDS_15000_RAW: &'s...
Rust
0
to(), BOB, SETT_USD_ID, 50)); assert_eq!(Stp258::free_balance(SETT_USD_ID, &ALICE), 50); assert_eq!(Stp258::free_balance(SETT_USD_ID, &BOB), 150); let transferred_event = TestEvent::stp258(RawEvent::Transferred(SETT_USD_ID, ALICE, BOB, 50)); assert!(System::events().iter().any(|record| record.event == tran...
Rust
0
# https://pyrocko.org - GPLv3 # # The Pyrocko Developers, 21st Century # ---|P------/S----------~Lg---------- ''' A toolbox and library for seismology. ''' import sys try: from .info import * # noqa __version__ = version # noqa except ImportError: pass # not available in dev mode grumpy = 0 # noqa ...
Python
1
reference: passwd, } impl OwnedPwd { fn into_global(self) -> *mut passwd { unsafe { PASSWD_BUF = Some(self.buffer); PASSWD = self.reference; &mut PASSWD } } } #[derive(Clone, Copy, Debug)] enum Cause { Eof, Other, } static mut READER: Option<BufRead...
Rust
0