text
string
label_name
string
labels
int64
imizer = optimizer_class(trainable_params, lr=lr, nesterov=True, **optimizer_kwargs) elif optimizer_type == "Lion8bit".lower(): print(f"use 8-bit Lion optimizer | {optimizer_kwargs}") try: optimizer_class = bnb.optim.Lion8bit except AttributeError: ...
Python
1
use crate::cache::Cache; use crate::engine::Engine; use crate::listing::Kind; use crate::site::Website; #[derive(Debug, StructOpt)] #[structopt( name = "truffles", about = "\ntruffles is a command-line tool that scrapes listings off of real estate websites." )] struct Args { #[structopt( short = "a", lon...
Rust
0
ated when running `huggingface-cli login` (stored in `~/.huggingface`). create_pr (`bool`, *optional*, defaults to `False`): Whether to create a PR with the uploaded files or directly commit. """ repo_url = create_repo( repo_id=repo_id, ...
Python
1
nd(t_recall, stim_dim) < self.p_flip x_stim[t_store:, :stim_dim] = x_stim_recall * (1 - flip_matrix) + (1 - x_stim_recall) * flip_matrix x = np.concatenate((x_stim, x_store_signal), axis=1) self.ob = x self.gt = y self.mask = m self.tmax = t * self.dt return...
Python
1
add_i64(i64::from(src_size)).unwrap().into(); let dest_end: i64 = dest_offset .try_add_i64(i64::from(dest_size)) .unwrap() .into(); if src_end <= dest_offset.into() || dest_end <= src_offset.into() { return SpatialOverlap::No; } SpatialOverlap::Partial } #[derive(Copy, ...
Rust
0
n1ResolvedCharacterString, Asn1ResolvedEnumerated, Asn1ResolvedInteger, Asn1ResolvedNull, Asn1ResolvedObjectIdentifier, Asn1ResolvedOctetString, ResolvedBaseType, }, Resolver, }; pub(crate) fn resolve_base_type( ty: &Asn1Type, resolver: &mut Resolver, ) -> Result<ResolvedBaseType, Error...
Rust
0
= &'static str; fn from_str(s: &str) -> Result<Self, Self::Err> { match s { "dot" => Ok(Format::Dot), "plain" => Ok(Format::Plain), _ => Err("no match"), } } } pub struct ReplContext<'a> { pub da: &'a DoubleArray, pub dict: &'a IPADic, pub word_...
Rust
0
''' API v1 ''' # from flask import Blueprint from flask_restx import Api from .home import api as ns_home from .cat import api as ns_cat from .card import api as ns_card # blueprint = Blueprint('api', __name__, url_prefix='/api/v1') api = Api( title='Tarjetametrobus-pma API Documentation', version='1.0.0', ...
Python
1
nt, motive: str, country: str, date: str, run_manager: Optional[ langchain_core_callbacks.CallbackManagerForToolRun ] = None, ) -> str: VerifyAllInfo = DoctorMPatient( MeetPatient=MeetPatient, AllInfo=AllInfo, name=name,...
Python
1
#[inline] pub fn log(&self) -> &ArconLogger { &self.logger } /// Get current event time #[inline] pub fn current_time(&mut self) -> StateResult<u64> { self.timer.get_time() } /// Schedule at a specific time in the future /// /// Returns Ok if the entry was sche...
Rust
0
-is in 32-bit Unicode Scalar Values, but Unicode //! character code points are reserved only for 21-bits, and UTF-16 surrogates are invalid in //! UTF-32. Since UTF-32 is a fixed-width encoding, it is much easier to deal with, but equivalent //! methods to the 16-bit strings are provided for compatibility. //! //! All ...
Rust
0
# Copyright 2021-2024 The PySCF Developers. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appl...
Python
1
planes, ...). #[allow(clippy::missing_safety_doc)] pub unsafe fn from_external_pixmaps( info: &YUVAInfo, pixmaps: &[Pixmap; Self::MAX_PLANES], ) -> Option<Self> { Self::try_construct(|pms| { sb::C_SkYUVAPixmaps_FromExternalPixmaps(pms, info.native(), pixmaps.native().as_p...
Rust
0
""" # --8<-- [start:login] import polars_cloud as pc workspace = pc.login() # --8<-- [end:login] """
Python
1
e { match *self { Type::Bool | Type::Int | Type::List(_) | Type::Var(_) => 0, Type::Forall(ref ty) => ty.argn(), Type::Func(_, ref r) => 1 + r.argn(), } } } //! Module that describes LIA logic. //! //! Note that the functions and structs that are defined. use std...
Rust
0
!(camel_case_until("abcDef"), 0); assert_eq!(camel_case_until("aDbc"), 0); } #[test] fn until_partial() { assert_eq!(camel_case_until("AbcDef_"), 6); assert_eq!(camel_case_until("CallTypeC"), 8); assert_eq!(camel_case_until("AbcDD"), 3); } #[test] fn until_caps() { assert_eq!(camel_case_until("ABC...
Rust
0
use std::fs; use std::io; use std::io::Write; use anyhow::Result; use assembler::Assembler; use vm::VM; fn user_input(prompt: &str) -> Result<String> { let mut s = String::new(); print!("{}", prompt); io::stdout().flush()?; io::stdin().read_line(&mut s)?; Ok(String::from(s.trim())) } fn run_co...
Rust
0
{ debug_assert_ne!(cap, 0); // For small tables we require at least 1 empty bucket so that lookups are // guaranteed to terminate if an element doesn't exist in the table. if cap < 8 { // We don't bother with a table size of 2 buckets since that can only // hold a single element. Inste...
Rust
0
# library import geopandas as gpd from shapely.geometry import Polygon from geopy.distance import geodesic import pandas as pd # functions def create_circle(center, radius=1.0): """ Create a polygon representing a circle based on a center point and a radius. Parameters: center (tuple): The latitude an...
Python
1
join(save_directory, "__init__.py") with open(init_file, "w") as f: for key, file_name in auto_map_files.items(): base_name = os.path.basename(file_name).split(".")[0] f.write(f"from .{base_name} import {auto_map[key].__name__}\n") def create_default_model_card( models: list[st...
Python
1
name=input("Please enter your name: ") colour=input("Enter the colour you love: ") print(name+" likes "+colour+"!!")
Python
1
x| x.ok()) .filter_map(|x| pyiter_to_vec::<i32>(py, x)) .collect::<Vec<_>>(); assert_eq!(vec.len(), 2); assert_eq!(vec[0].len(), BOARD_CAPACITY); assert_eq!(vec[1].len(), BOARD_CAPACITY); assert_eq!(vec[0], vec![Player::None as i32; BOARD_CAPACITY]); assert_eq!(vec[1], vec![Player:...
Rust
0
TDS_UNI: &'static str = "https://remotetest.unidata.ucar.edu/thredds/dodsC/testdods/"; pub const TDS_MET: &'static str = "https://thredds.met.no/thredds/dodsC/"; pub const TDS_LCL: &'static str = "http://localhost:8002/thredds/dodsC/test/data/"; pub fn test_log() { let _ = env_logger::Builder::from_env( en...
Rust
0
decode func-buf` interface. //! //! For more info regarding the encoding scheme see the counterpart `svm-abi-encoder` crate. //! #![no_std] #![allow(missing_docs)] #![allow(unused)] #![deny(dead_code)] #![deny(unreachable_code)] mod calldata; mod cursor; mod decoder; pub use calldata::CallData; /// `ReturnData` is ...
Rust
0
= 2; //const HOPS_IDX: usize = 3; const XID_IDX: usize = 4; const SECS_IDX: usize = 8; const FLAGS_IDX: usize = 10; const CIADDR_IDX: usize = 12; const YIADDR_IDX: usize = 16; const SIADDR_IDX: usize = 20; const GIADDR_IDX: usize = 24; const CHADDR_IDX: usize = 28; const SNAME_IDX: usize = 44; const FILE_IDX: usize = ...
Rust
0
visit function. /// dict['$0splice0' => $0splice0, '$0splice1' => $0splice1], /// /// // The visit function itself. Visitors define what they want to do when /// // they see each piece of syntax. They might build an AST, or construct a /// // SQL query. /// function (MyDsl $v) { /// // (ignor...
Rust
0
let start_log_pos = match log_line.find(",") { Some(val) => val, None => return Err(LogParsingError::NoValidParser(log)), }; //let syslog_header = &log_line[0..start_log_pos]; let log_content = &log_line[start_log_pos + 1..]; let csv_content = extract_fields(log_content); let module...
Rust
0
ersion::DeviceV1_0, vk}; use core::slice; use std::mem; pub struct MemMapHandle<'a, T> { ptr: *mut T, ptr_len: usize, // elements not bytes device: &'a Dev, memory: vk::DeviceMemory, non_coherent: bool, } pub struct StageBuffer<T> where T: PartialEq, { usage: vk::BufferUsageFlags, non...
Rust
0
hyper_yaml_path, 'r') as f: configs = load_hyperpyyaml(f, overrides={'qwen_pretrain_path': os.path.join(model_dir, 'CosyVoice-BlankEN')}) assert get_model_type(configs) == CosyVoice2Model, 'do not use {} for CosyVoice2 initialization!'.format(model_dir) self.frontend = CosyVoiceFrontEnd(conf...
Python
1
.. res.append(w @ f(x)) >>> >>> ref = np.full_like(res, 14.7680137457653) >>> err = abs(res - ref)/abs(ref) >>> plt.semilogy(orders, err) >>> plt.xlabel('order $n$') >>> plt.ylabel('relative error') >>> plt.title(r'Convergence for $f(x, y, z) = \exp(x)$') >>> plt.show() """ ...
Python
1
#Juan Paulo Farías Rodríguez PIMO 2013-1 #Código: 2091691 #Laboratorio 3 #1 def maximo(X,N,i,m): r=0 if i==N: r=m else: r=maximo(X,N,i+1,max(m, X[i])) return r #2 def vecinas(X,N,i): vec=True if i==N: r=vec else: r = ((X[i]!= X[i-1]) and (vecinas(X, N,...
Python
1
When the last process in an IPC namespace exits, // all IPC objects in the namespace are automatically destroyed. // But it can cause an overhead (about 30ms) of shutting down the last process, // which increase the `real_time` number in sandbox output. // Is it a kernel bug? // ...
Rust
0
import torch.nn as nn from layers.LSTM_EncDec import Encoder from layers.graph_modules import GraphLayer, GraphNetwork from layers.graph_blocks import unsorted_mean_agg from layers.Embed import GraphDataEmbedding from layers.Functionality import MLPLayer class Model(nn.Module): """ GNN with LSTM as update fun...
Python
1
/// should read from the 1st component in the underlying texture. pub const FROM_1: Self = Self(1); /// Value for use with `ComponentMapping` constructors. Means that the component being mapped /// should read from the 2nd component in the underlying texture. pub const FROM_2: Self = Self(2); /// ...
Rust
0
= TcpStream::connect(addr); assert!(tcp_stream.is_ok()); if let Ok(mut tcp_stream) = tcp_stream { let res = tcp_stream.set_write_timeout(Some(Duration::from_millis(64))); assert!(res.is_ok()); ...
Rust
0
def test_parse_arguments(): from speechbrain.core import parse_arguments filename, run_opts, overrides = parse_arguments( ["params.yaml", "--device=cpu", "--seed=3", "--data_folder", "TIMIT"] ) assert filename == "params.yaml" assert run_opts["device"] == "cpu" assert overrides == "seed...
Python
1
-let-vs--match for a bit more detailed explanation if let CHILD = event.token() { // read message from the init process let mut buf = [0; 1]; match receiver.read_exact(&mut buf) { // This error simply means that there are no more incoming c...
Rust
0
#some plot def #trajectory map import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from matplotlib.animation import FuncAnimation, PillowWriter # 假设您有两组连续平滑的姿势数据集,一组表示预测值,一组表示真值 # 每个数据点包含姿势信息 [x, y, z, roll, pitch, yaw] # 这里使用一些示例数据,您需要替换为您的实际数据 num_poses = 200 # 增加轨迹点数 t = np.l...
Python
1
] #[inline(always)] pub fn adc14ch2map_0(self) -> &'a mut W { self.variant(ADC14CH2MAP_A::ADC14CH2MAP_0) } #[doc = "ADC input channel internal 2 is selected for ADC input channel MAX-4"] #[inline(always)] pub fn adc14ch2map_1(self) -> &'a mut W { self.variant(ADC14CH2MAP_A::ADC14...
Rust
0
path = output_dir makedirs(render_path, exist_ok=True) # Future TODO: render depth of panorama (could be used for adjusting HDR intensity) with torch.no_grad(): cube_map_dict = {} for view_name, view in tqdm(views.items(), desc="Rendering progress"): rendering = render(view, ga...
Python
1
per_route=request.maxPointsPerRoute, max_cluster_radius=request.spatialThreshold * 2, # 设置为空间阈值的2倍 amap_key=os.getenv("AMAP_KEY") # 从环境变量获取高德地图API密钥 ) # 执行路线规划 planning_result = scheduler.process_requests(formatted_requests) if not planning_res...
Python
1
gt_blank("0.1", "", &CompOp::Gt), case::bugfix_increment("1.2.3", "1.2.4", &CompOp::Lt), case::fourth_place_greater("1.0.0.1", "1.0.0.0", &CompOp::Gt), case::fourth_place_lower("1.0.0.0", "1.0.0.1", &CompOp::Lt), case::left_more_specific("1.2.3.4", "1.2", &CompOp::Gt), ...
Rust
0
"策略開發": 45, "風險管理": 30, "高級技術": 10 } # 進度條顯示 for topic, progress in progress_data.items(): st.write(f"**{topic}**") st.progress(progress / 100) st.write(f"完成度: {progress}%") st.write("") ...
Python
1
ttingName, val): setattr(self, settingName, val) #-------------------------------------------------------------------------- def menuItemCheckboxSetup(self, control, settingName, additionalCommand=None): if additionalCommand: def compositeCommand(): self.menuItemChe...
Python
1
//! type of indentation for each sub-value. You may mix indentation per-file. //! //! ```rust //! let source = r#" //! ## tab //! a //! 1 //! //! ## single space //! b //! 2 //! "#; //! let config = nccl::parse_config(&source).unwrap(); //! assert_eq!(config["a"].value(), Some("1")); //! assert_eq!(config["b"].value(...
Rust
0
<Vec<ConnectedModuleInfo>>, diesel::result::Error> { use schema::connected_modules::dsl::*; let info = connected_modules .filter(module_id.eq(id_)) .get_results::<ConnectedModuleInfo>(conn) .optional()?; Ok(info) } pub fn find_b...
Rust
0
act_sell = round(self.impact_panel.loc[timestamp]['act_sell_side'] * slippage_ratio, 0) slippage_result = {} bid_seq_len = 0 ask_seq_len = 0 if lob_data['slippage_ask1_price_side']==0: slippage_result['hedge_ask'] = lob_data['hedge_ask_price_lag'] else: ...
Python
1
"); cs.road_center_line = hex("#BCFF00"); cs } fn osm() -> ColorScheme { let mut cs = ColorScheme::standard(); // TODO normal_intersection, driving_lane, parking_lane depends on osm rank cs.general_road_marking = Color::BLACK; cs.road_center_line = Color::rgb(202...
Rust
0
audio_clips_list = glob.glob(os.path.join(audio_path, "*.wav")) while len(audio_clips_list) == 0 and max_recursion_depth > 0: audio_path = os.path.join(audio_path, "**") audio_clips_list = glob.glob(os.path.join(audio_path, "*.wav")) max_recursion_depth -= 1 clips.ext...
Python
1
RESTRICTED_ENVS: _bindgen_ty_4 = 5; pub const _CS_LFS_CFLAGS: _bindgen_ty_4 = 1000; pub const _CS_LFS_LDFLAGS: _bindgen_ty_4 = 1001; pub const _CS_LFS_LIBS: _bindgen_ty_4 = 1002; pub const _CS_LFS_LINTFLAGS: _bindgen_ty_4 = 1003; pub const _CS_LFS64_CFLAGS: _bindgen_ty_4 = 1004; pub const _CS_LFS64_LDFLAGS: _bindgen_ty...
Rust
0
from rest_framework import serializers from .models import Journal from django.contrib.auth import get_user_model class JournalSerializer(serializers.ModelSerializer): """Serializer for retrieving journal entries""" username = serializers.CharField(source='user.username', read_only=True) class Meta: ...
Python
1
print(f"Added Playlist: {playlist['Name']} to Firebase") #get all the users from the database sql = "SELECT * FROM Users" cursor.execute(sql) result = cursor.fetchall() for user in result: #Add the user to the firebase database print(user['Username']) if(fireDB....
Python
1
if axis in visible_ticks and coord_ticklabels_bbox[axis][0] is not None: right = coord_ticklabels_bbox[axis][0].x1 else: right = xcen xpos = right + padding self.set_position((xpos, ycen)) ...
Python
1
import math # điều kiện n > 1 def P(n): total = 0 if n > 1: n = int(n) for i in range(1, n + 1): total += i return total else: print("Vailed ,please Enter Esc") print("P(6) =", P(6)) m = int(input("Nhập m:")) # Kiểm tra điều kiện m > 1 if m > 1: total = 0 ...
Python
1
import torch import torch.nn as nn from openunmix.transforms import make_filterbanks from djtransgan.config import settings class AsteroidSTFT(nn.Module): def __init__(self, n_fft=settings.N_FFT, hop_length=settings.HOP_LENGTH, sr=settings.SR, ...
Python
1
tOwn::from_str("university").set_stem(&lang); let qtext2 = TextOwn::from_str("university"); let rtext = TextOwn::from_str("universe").set_stem(&lang); assert_debug_snapshot!(word_match(&rtext.view(0), &qtext1.view(0))); assert_debug_snapshot!(word_match(&rtext.view(0), &qtext2.view(0)))...
Rust
0
ams2)); let n2 = results2.get_int64(PARAM_INT_VALUE).value(); ctx.results().get_int64(PARAM_INT_VALUE).set_value(n1 + n2); ctx.log("testcore.fibonacci ok"); } pub fn func_inc_counter(ctx: &ScFuncContext) { ctx.log("testcore.incCounter"); ctx.state().get_int64(VAR_COUNTER).set_value(ctx.state().get...
Rust
0
shape()[2]; let img_w = img.shape()[3]; let gx = gy.col2im( img_w, img_h, self.kernel_size, self.stride, self.padding, self.dilation, ); [gx] } } impl Operator<1> for Col2Im { fn compute(&self, x: [&Tensor;...
Rust
0
""" スタックのリークしているアドレスを抽出し(正規表現を利用して)、 そのアドレスとコマンド文字列のアドレスの差分を調べるためのスクリプト """ import re from pwn import * HOST = "127.0.0.1" PORT = 8080 def send_payload(host, port, payload): s = remote(host, port) s.send(payload) response = b"" try: while True: chunk = s.recv(4096) ...
Python
1
else len(user_qq_list)): impression = max(impression_list) index = impression_list.index(impression) user = user_qq_list[index] group = group_list[index] user_qq_list.pop(index) impression_list.pop(index) group_list.pop(index) if user not in users and imp...
Python
1
RIES_PER_PAGE_TABLE - 5; pub const MAX_PAGE_NUMBER: usize = MAX_VIRTUAL_ADDRESS / PAGE_SIZE; /// The size in pages of each kernel stack. /// If it's too small, complex kernel functions will overflow, causing a page fault / double fault. #[cfg(not(debug_assertions))] pub const KERNEL_STACK_SIZE_IN_PAGES: usize = 16;...
Rust
0
.rs // Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT...
Rust
0
fn test_solve_3x3_permute() { let mut mat = vec![ GF(0), GF(0), GF(8), GF(89), GF(0), GF(2), GF(45), GF(10), GF(5), ]; let mut b = [GF(126), GF(23), GF(99)]; let solved = solve(&mut mat, &mut b[..], 3); assert!(solved); ass...
Rust
0
y({"details": details}) #multi face @app.route('/recognize', methods=['POST']) def recognize(): if 'image' not in request.files: return jsonify({"error": "No image provided"}), 400 file = request.files['image'] image_data = file.read() image_array = np.frombuffer(image_data, np.uint8) image...
Python
1
eposit: u64 = 500; pub const MaxLocks: u32 = 50; pub const MaxReserves: u32 = 50; } impl pallet_balances::Config for Runtime { type MaxLocks = MaxLocks; /// The type for recording an account's balance. type Balance = Balance; /// The ubiquitous event type. type Event = Event; type DustR...
Rust
0
].try_into().unwrap(), ]); } fn reserve(cx: &mut Self::Context, num_triangles: u32) { // Use reserve_exact because binary stl has information on the exact number of triangles. cx.mesh.faces.reserve_exact(num_triangles as _); cx.mesh.normals.reserve_exact(num_triangles as _); ...
Rust
0
# get chamfer distance map from image segmentation import numpy as np import scipy def get_chamfer(mask, scale=0.25): h, w = mask.shape mask_tmp = np.zeros((h,w,3)) mask_tmp[:,:,:] = np.reshape(mask, [h, w, 1]) mask = mask_tmp mask_small = scipy.misc.imresize(mask, scale) h_ = int(scale * h) w_ =...
Python
1
model = fit_scaling_model('dirichlet', dataloader_logits_calib, num_classes, binary_loss=False, regularization=True, num_epochs=num_epochs, temperature_ref=temp_tva) logits_scaled = model(logits_test.cuda()).detach().cpu() metrics_test = metrics_from_logits_labels(...
Python
1
"""Government US tests."""
Python
1
t({'tatstatus': 'passed'}), "time": "all time", "isclickable": True, "url": "consignments?limit=15&offset=0&tatStatus=passed", "query_param": "tatStatus=passed" }, { "title": "tat-failed", "value": ge...
Python
1
max(2.7)); Ok(Value::null()) }) } else { Err(runtime!( "Attempted to set a temperature to a number that is NaN or infinite." )) } } #[hook("/datum/gas_mixture/proc/partial_heat_capacity")] fn _partial_heat_capacity() { if args.is_empty() { Err(runtime!("Incorrect arg len for partial_heat_capacity (0)....
Rust
0
rank: usize) -> Self { WriteOnce { inner: UnsafeCell::new(None), rank: Cell::new(rank), init: false.into(), } } pub fn set(&self, data: T) -> Result<(), T> { if !self.init.compare_and_swap(false, true, Ordering::Acquire) { unsafe { ...
Rust
0
"Standard_NC24s_v3")] StandardNc24sV3, #[serde(rename = "Standard_NC6")] StandardNc6, #[serde(rename = "Standard_NC6s_v2")] StandardNc6sV2, #[serde(rename = "Standard_NC6s_v3")] StandardNc6sV3, #[serde(rename = "Standard_ND12s")] StandardNd12s, #[serde(rename = "Standard_ND24rs"...
Rust
0
import os import pandas as pd import plotly.express as px import win32com.client as win32 data_list = os.listdir("Vendas") #print(data_list) joined_table = pd.DataFrame() for file in data_list: if "Devolucoes" in file: table = pd.read_csv(f"Vendas/{file}") joined_table = joined_table._append(table...
Python
1
# -*- coding: utf-8 -*- # Part of Softhealer Technologies. from odoo import models, fields class POSUserReport(models.Model): _name = 'sh.pos.report.user' _description = 'POS Report By User' name = fields.Char(string='Order Number') order_date = fields.Datetime() sh_partner_id = fields.Many2one( ...
Python
1
def find_smaller_larger(a, b): smaller = min(a, b) larger = max(a, b) print(f"Smaller number: {smaller}") print(f"Larger number: {larger}") num1 = float(input("Enter first number: ")) num2 = float(input("Enter second number: ")) find_smaller_larger(num1, num2)
Python
1
efore my eyes; *"), b: String::from("I have walked faithfully with you.") }, PsalmVerse { number: 4, a: String::from("I have not sat with the worthless, *"), b: String::from("nor do I consort with the deceitf...
Rust
0
ake_float(vm, x)?; let y = objfloat::make_float(vm, y)?; Ok(vm.ctx.new_float(x.powf(y))) } make_math_func!(math_sqrt, sqrt); // Trigonometric functions: make_math_func!(math_acos, acos); make_math_func!(math_asin, asin); make_math_func!(math_atan, atan); fn math_atan2(vm: &mut VirtualMachine, args: PyFuncArg...
Rust
0
} } } impl fmt::Display for Container { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { if self.siblings > 2 { fmt.write_str(&self.pod)?; fmt.write_str("/")?; fmt.write_str(&self.container)?; } else { fmt.write_str(&self.pod)?; } Ok(()) } } #[derive(Debug)] enum...
Rust
0
# SPDX-License-Identifier: MIT # Copyright (C) 2022 Max Bachmann from __future__ import annotations from rapidfuzz._utils import fallback_import as _fallback_import _mod = "rapidfuzz.distance.metrics" distance = _fallback_import(_mod, "osa_distance") similarity = _fallback_import(_mod, "osa_similarity") normalized_di...
Python
1
import pygame import pygame.freetype import pygame.locals import * # Initialize pygame pygame.init() # Set up the screen and font screen = pygame.display.set_mode((500, 500), pygame.RESIZABLE) pygame.display.set_caption("Stopwatch") font = pygame.freetype.SysFont(None, 24) font.origin = True # Function to display t...
Python
1
#ident_as_string ) )); } }); } let variant_id_read = if id.is_some() { quote! { let (__deku_new_rest, __deku_variant_id) = (__deku_rest, #id); } } else if id_type.is_some() { qu...
Rust
0
""" return isinstance(value,(int)) and value >= 0 and value <= 3000 def _parse_potion_value(self, value: str) -> Optional[int]: """ 解析藥水值,回傳 potion_value potion_value: int (e.g. "2,999" -> 2999) """ if not value or value == "N/A": return None ...
Python
1
ate_name = 'project/security_groups/add_rule.html' submit_label = _("Add") submit_url = "horizon:project:security_groups:add_rule" url = "horizon:project:security_groups:detail" page_title = _("Add Rule") def get_success_url(self): sg_id = self.kwargs['security_group_id'] return rev...
Python
1
from dataclasses import field from typing import TYPE_CHECKING, List, Optional from yandex_music import YandexMusicModel from yandex_music.utils import model if TYPE_CHECKING: from yandex_music import AutoRenewable, ClientType, JSONType, NonAutoRenewable, Operator, RenewableRemainder @model class Subscription(Y...
Python
1
ainder = rest; buffer_x.extend(&left.x[1..]); buffer_y.extend(&left.y[1..]); for t in t { let (left, rest) = split(remainder.as_slice(), (t - prev_t) / (1.0 - prev_t)); prev_t = t; remainder = rest; buffer_x.extend(&left.x[1..]); buf...
Rust
0
`tls` to attach app's certificate :param builtins.int port: Mapped external port number, either `port` or `start_port` and `end_port` must be set. :param builtins.int start_port: For a port range, the first port to listen on. """ if end_port is not None: pulumi.set(__self__,...
Python
1
0) // DO NOT EDIT use GutterRendererAlignmentMode; use ffi; use gdk; use glib; use glib::Value; use glib::object::Downcast; use glib::object::IsA; use glib::signal::connect; use glib::translate::*; use glib_ffi; use gobject_ffi; use gtk; use std::boxed::Box as Box_; use std::mem; use std::mem::transmute; glib_wrapper...
Rust
0
ter.get_stats() stat_height = stats_rect.height / len(monster_stats) for index, (stat, value) in enumerate(monster_stats.items()): single_stat_rect = pygame.FRect(stats_rect.left, stats_rect.top + index * stat_height, stats_rect.width, stat_height) #icon ...
Python
1
_ty(); SimdValue::from(ty, quote! { <#ty>::new(#idxs) }) } } impl ToTokens for SimdType { fn to_tokens(&self, tokens: &mut TokenStream) { let ty = &self.0; let width = &self.1; tokens.extend(quote!(Simd<[#ty; #width]>)); } } #[derive(Clone, Debug)] struct SimdValue(SimdType, TokenStream); impl Sim...
Rust
0
#Создаем вложеные последовательности nested = ["раз", ("два", "три"), ["четыре", "пять", "шесть"]] print(nested)
Python
1
xs = query_idxs + gallery_idxs self.num_query = len(query_idxs) # 重排序 self.global_feats = [self.global_feats[i] for i in re_idxs] self.local_feats = [self.local_feats[i] for i in re_idxs] self.vis_scores = [self.vis_scores[i] for i in re_idxs] self.pids = [self.pids[i] f...
Python
1
ow is raised synchronously. None for no limit. @ivar backlog: The maximum number of Deferred gets to allow at one time. When an attempt is made to get an object which would exceed this limit, QueueUnderflow is raised synchronously. None for no limit. """ def __init__(self, size=None, backlo...
Python
1
pub profiler_dbg: bool, /// Toggles `webrender::DebugFlags::RENDER_TARGET_DBG` pub render_target_dbg: bool, /// Toggles `webrender::DebugFlags::TEXTURE_CACHE_DBG` pub texture_cache_dbg: bool, /// Toggles `webrender::DebugFlags::GPU_TIME_QUERIES` pub gpu_time_queries: bool, /// Toggles `web...
Rust
0
pub fn from_aggregates_count( total_number_of_records: usize, aggregates_count: &AggregatesCountMap, resolution: usize, ) -> PrivacyRiskSummary { let mut records_with_unique_combinations = RecordsSet::default(); let mut records_with_rare_combinations = RecordsSet::defaul...
Rust
0
""" 格式:直接cid为自带的index位;aid放不下了,通过字典来查,反正就5w个 """ import os import traceback import logging logger = logging.getLogger(__name__) from multiprocessing import cpu_count import faiss import numpy as np from sklearn.cluster import MiniBatchKMeans # ###########如果是原始特征要先写save n_cpu = 0 if n_cpu == 0: n_cpu = cpu_coun...
Python
1
sp::{BoolExpr, BoolVar, Domain, IntExpr, IntVar, Stmt}; #[derive(PartialEq, Eq, Debug)] enum SyntaxTree<'a> { Ident(&'a str), Int(i32), Node(Vec<SyntaxTree<'a>>), } impl<'a> SyntaxTree<'a> { fn as_op_name(&self) -> &'a str { match self { &SyntaxTree::Ident(s) => s, _ =>...
Rust
0
(tcno+str(haneOn)+str(haneOnBir)) elif(yeraltisecim=="9"): import requests print("günlük 1 mesaj hakkınız vardır") telefonno = input("Telefon Numarası Giriniz : ") mesaj = input("Mesajınızı Giriniz: ") resp = requests.post('https://textbelt.com/text', { 'phone': telefonno, 'message': mesaj, ...
Python
1
nramp-osmetric-{}", "???")) .spawn(move || onramp_loop(&rx, &config, preprocessors, codec, metrics_reporter))?; Ok(tx) } fn default_codec(&self) -> &str { "json" } } // MountInfo #[derive(Debug, Serialize, Deserialize, Clone)] pub struct MountInfo { source: String, dest...
Rust
0
mask): from struct import pack, unpack from socket import inet_ntoa, inet_aton mask = 1L<<31 xnet = (1L<<32)-1 cidr_range = range(0, 32) cidr = long(nmask) if cidr not in cidr_range: print 'cidr invalid: %d' % cidr return None else: nm = ((1L<<cidr)-1)<<(32-cidr) netmask = str(inet_ntoa(pack...
Python
1