text
string
label_name
string
labels
int64
ubset body_parts_name[f'{imgname[:-4]}_foot_ground'] = part_names os.makedirs(out_dir, exist_ok=True) print(f'processing {idx}/{len(damon_list)} {imgname} with foot ground | Contact vertices: {len(contact_vertices_subset)}') ...
Python
1
""" .. module:: test_multisampling :synopsis: Test multisampling strategy .. moduleauthor:: David Eriksson <dme65@cornell.edu> """ import logging from pySOT import * from poap.controller import SerialController import numpy as np import os.path def main(): if not os.path.exists("./logfiles"): os.makedi...
Python
1
from django.db import models from django.utils.translation import gettext_lazy as _ from adhocracy4.categories.form_fields import IconChoiceField from adhocracy4.modules import models as module_models class IconField(models.CharField): def __init__(self, *args, **kwargs): kwargs["max_length"] = 254 ...
Python
1
import hashlib HASH = ['5f4dcc3b5aa765d61d8327deb882cf99','5a105e8b9d40e1329780d62ea2265d8a'] PASSLIST = ['test','name','hello','password','goodbye', '12345','1234567','123456789','123456','test1', '12345678','zinch','g_czechout','asdf','qwerty', 'picture1','111111','123123','123456...
Python
1
# Find the most frequent character in the paragraph import string rhyme = 'Twinkle, twinkle, little star. How I wonder what you are!' lower_string = rhyme.lower() clean_char = [] for char in lower_string: if char not in string.punctuation and not char.isspace(): clean_char.append(char) char_freq = {...
Python
1
import pyautogui, time, webbrowser, random def losowa_strona(): number = random.randint(1, 3) if number == 1: webbrowser.open('https://attachment.zip/') if number == 2: webbrowser.open('https://guthib.com/') if number == 3: webbrowser.open('https://steve78392.github.io/') def klawiatura_cyfry(): cyfra = r...
Python
1
ffef}'; const KANJI_START: char = '\u{4e00}'; const KANJI_END: char = '\u{9faf}'; /// Returns `true` if the `char` is Japanese (kana, kanji, Japanese punctuation, etc). pub fn is_japanese(ch: char) -> bool { is_hiragana(ch) || is_kanji(ch) || is_katakana(ch) || is_japanese_punctuation(ch) ...
Rust
0
let provides = { let mut p = Vec::new(); p.push(hash(&tx.from, tx.nonce)); p }; TransactionValidity::Valid(ValidTransaction { priority: tx.amount, requires, provides, longevity: 64, propagate: true, }) } /// Execute a transaction outside of the block execution function. /// This doesn't attempt to...
Rust
0
from my_raytracer import * (width, height) = (1920, 1080) # 屏幕尺寸 resolution= height/width light_pos = vec3(-2, 2, -2) # 点光源位置 center = vec4(0, 0, 0, 0) # 摄像机位置 focal_length= 200 shape1= Cylinder(vec3(0, .5, .5), vec3(0, -.5, .5), .5, lambda p: rgb(0.8,0,0.5)) shape2 = Sphere(.5, get_checkerboard_...
Python
1
ram_index(tree.id()) { return Ok(repo.find_tree(cached)?); } let mut arrs_own = vec![vec![]; 8]; let mut arrs_sub = vec![vec![]; 8]; let mut files = vec![vec![]; 8]; let mut result = tree::empty(repo); /* 'entry: */ for entry in tree.iter() { let name = entry.name().ok_or...
Rust
0
#!/usr/bin/python3 """ A function that adds a new attribute to an object if it's possible. """ def add_attribute(obj, name, value): """ Add a new attribute to an object if it's possible. Args: obj (object): The object to which the attribute should be added. name (str): The name of the attribute ...
Python
1
`error_if_nonfinite=False`" ) clip_coef = max_norm / (total_norm + 1e-6) # Note: multiplying by the clamped coef is redundant when the coef is clamped to 1, but doing so # avoids a `if clip_coef < 1:` conditional which can require a CPU <=> device synchronization # when the gradients do not resi...
Python
1
f_max=FMAX, # win_length=WIN_LENGTH # ): # """ # Extracts the log Mel spectrogram from an audio signal. # # Parameters: # - audio: numpy array, the audio signal. # - sr: int, the sampling rate...
Python
1
string(), instance: "myinstance".to_string(), role: "myrole".to_string(), group: "mygroup".to_string(), id: "123".to_string()}))] fn test_identity_pod_identity_try_from_pod_and_id( #[case] labels: &[(&str, &str)], #[case] id: &str, #[case] expe...
Rust
0
ge/v1/object/files/files/user/123/parsed/doc_20250906_150202.md?token=...", "webhook_url": "https://your-api.com/webhook/llamaparse/job_123", "result_type": "markdown", "api_key": "${LLAMAPARSE_API_KEY}" } print("POST https://api.cloud.llamaindex.ai/api/parsing/upload") print("C...
Python
1
from __future__ import absolute_import import os import socket try: import queue except ImportError: import Queue as queue __all__ = [ 'Empty', 'Queue', ] Empty = queue.Queue class Queue(queue.Queue, object): def __init__(self): super(Queue, self).__init__() if os.name == 'po...
Python
1
from lucidia_math_lab.recursion_sandbox import RecursiveSandbox def test_parse_and_detect(): sandbox = RecursiveSandbox() eq = sandbox.parse_equation("f(x)=f(f(x-1))+1") assert sandbox.detect_contradiction("f(x)=f(f(x-1))+1") assert str(eq.lhs) == 'f(x)'
Python
1
let unit_direction = ray.direction.unit_vector(); let t = 0.5 * (unit_direction.y() + 1.0); (1.0 - t) * Color::new(1, 1, 1) + t * Color::new(0.5, 0.7, 1.0) } fn random_scene(rng: &mut SmallRng, random_spheres: bool) -> impl Hittable { let mut world: HittableList = vec![ // Floor Box::new(Sp...
Rust
0
#!/usr/local/env python # Copyright 2021 Johns Hopkins University (Author: Desh Raj) # # Overlap detection using pretrained Pyannote models import torch import argparse import glob import os import pathlib def read_args(): parser = argparse.ArgumentParser() parser.add_argument("wav_scp", help="Path to wav.sc...
Python
1
f"❌ Error {i}: {error_msg}") break await message.reply(f"🧪 Prueba: {grupos_test_creados}/2 grupos") except Exception as e: await message.reply(f"❌ Error: {str(e)}") @bot_client.on_message(filters.command("estado") & filters.priv...
Python
1
istenceWindows> { self.persistence_windows.as_ref() } /// Return mutable reference to current persistence window, if any. pub fn persistence_windows_mut(&mut self) -> Option<&mut PersistenceWindows> { self.persistence_windows.as_mut() } /// Set persistence window to new value. ...
Rust
0
ive( url="https://ai.stanford.edu/~jkrause/car196/cars_test.tgz", download_root=str(self._base_folder), md5="4ce7ebf6a94d07f1952d94dd34c4d501", ) download_url( url="https://ai.stanford.edu/~jkrause/car196/cars_test_annos_withlabels....
Python
1
inner::PrincipalInner::from_slice(&[0; 0]); let _ = inner::PrincipalInner::from_slice(&[0; 4]); } #[cfg(feature = "serde")] #[test] fn serializes() { let seed = [ 0xff, 0xee, 0xdd, 0xcc, 0xbb, 0xaa, 0x99, 0x88, 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11, 0x00, 0xf...
Rust
0
import cv2 as cv def score(img): counter = 0 for i in range(img.shape[0]): for j in range(img.shape[1]): if img[i,j] > 127: counter += 1 return counter/(img.shape[0] * img.shape[1]) def img_show(img): cv.imshow("win", img) cv.waitKey(0) cv.destroyAllWindows...
Python
1
0 )] InvalidPaginationLength(String), #[fail( display = "invalid pagination start: `{}`", 0 )] InvalidPaginationStart(String), #[fail( display = "invalid number of outputs given: `{}`", 0 )] InvalidNumOutputs(String), #[fail( display = "inv...
Rust
0
_OSD, PSM_COUNT } #[allow(dead_code)] #[repr(C)] pub enum TessPageIteratorLevel { RIL_BLOCK, RIL_PARA, RIL_TEXTLINE, RIL_WORD, RIL_SYMBOL} #[allow(dead_code)] #[repr(C)] pub enum TessPolyBlockType { PT_UNKNOWN, PT_FLOWING_TEXT, PT_HEADING_TEXT, PT_PULLOUT_TEXT, PT_EQUATION, PT_INLINE_EQUATION, ...
Rust
0
import pytest from whisk.kitchenai_sdk.schema import WhiskQueryBaseResponseSchema, DependencyType @pytest.mark.asyncio async def test_basic_query_handler(kitchen, query_data): @kitchen.query.handler("query") async def query_handler(data): assert data.query == query_data.query assert data.metada...
Python
1
from dataclasses import dataclass import streamlit as st import ast import os from stablefusion.utils import base_path base_path = base_path() @dataclass class ModelRemoving: def read_model_list(self): try: with open('{}/model_list.txt'.format(base_path), 'r') as f: contents...
Python
1
h //! verification. pub mod block; pub mod header; pub mod redjubjub; mod script; mod transaction; // pub use block::init as block_init; // pub use header::init as header_init; <gh_stars>1-10 use rtfm::Threshold; use stm32f103xx::GPIOC; // Do stuff with SPI use ehal::blocking::spi::Transfer; use ehal::serial::Write...
Rust
0
# Copyright 2021 Toolchain Labs, Inc. All rights reserved. # Licensed under the Apache License, Version 2.0 (see LICENSE). # Generated by Django 3.2.8 on 2021-10-14 19:40 import shortuuid from django.db import migrations, models import toolchain.base.datetime_tools class Migration(migrations.Migration): depend...
Python
1
} } fn connect_property_css_value_type_notify<F: Fn(&Self) + 'static>( &self, f: F, ) -> SignalHandlerId { unsafe extern "C" fn notify_css_value_type_trampoline<P, F: Fn(&P) + 'static>( this: *mut webkit2_webextension_sys::WebKitDOMCSSValue, _param_sp...
Rust
0
OOLEAN ); CREATE TABLE project_version_layers ( layer_index integer NOT NULL, project_id UUID REFERENCES projects(id) ON DELETE CASCADE NOT NULL, project_version_id UUID REFERENCES projec...
Rust
0
import json import jsonlines from transformers import AutoTokenizer def preprocess_examples(example, tokenizer): # encode the code-docstring pairs statement = example['statement'] ids = example['identifiers'] prompt = f'''List the premises (i.e., theorems) used in the proof of the following Lean 4 th...
Python
1
int("\t\t", cofog3_code, cofog3_name) c3 = Cofog3(code=cofog3_code.strip(), name=cofog3_name.strip()) cofog3_sublist.append(c3) c2 = Cofog2(code=cofog2_code.strip(), name=cofog2_name.strip(), cofog3=cofog3_sublist) cofog2_sublist.append(c2...
Python
1
import os from collections import defaultdict # 路径设置 dataset_root = r"D:\pythonProject\ultralytics-main\GRAZPEDWRI-DX" labels_root = os.path.join(dataset_root, "data", "labels") splits = ["train", "valid", "test"] # 类名映射 class_names = { 0: "boneanomaly", 1: "bonelesion", 2: "foreignbody", 3: "fracture...
Python
1
Result::ok) .collect(); assert_eq!(lookup_result[0].symbol(), "func_record_with_end"); let mut lookup_result = symcache.lookup(0xd99).unwrap().filter_map(Result::ok); assert!(lookup_result.next().is_none()); // The last addr belongs to a public record which implicitly extends to infinity l...
Rust
0
from django.db import models from django.contrib.auth.models import User class Message(models.Model): sender = models.ForeignKey(User, on_delete=models.CASCADE, related_name='sent_messages') receiver = models.ForeignKey(User, on_delete=models.CASCADE, related_name='received_messages') message = models.Tex...
Python
1
''' Escreva um programa que leia um valor em metros e o exiba convertido em centímetros e milímetros.''' m = float(input('Digite a distância: ')) km = m*0.001 hm = m*0.01 dam = m*0.1 # verificar um valor em metros para hm, hm, dam, dm, cm e mm! dm = m*10 cm = m*100 mm = m*1000 print(f' O valor convertido para q...
Python
1
import os import boto3 from aws_lambda_powertools import Logger, Metrics, Tracer from aws_lambda_powertools.event_handler import APIGatewayRestResolver from aws_lambda_powertools.logging import correlation_paths from aws_lambda_powertools.metrics import MetricUnit logger = Logger() tracer = Tracer() metrics = Metric...
Python
1
if __name__ == '__main__': err_rate = 0.5 pkg_rep = 0.5 print(f"\n {err_rate} {pkg_rep}".format(err_rate, pkg_rep))
Python
1
name("secret") .long("secret") .value_name("key") .help("secret key for cookie encryption [default: randomly generated]; use `openssl rand -base64 32` to create one"), ) } #[derive(Serialize, Deserialize, Debug)] #[serde(default)] pub struct Config { pub secret_key: String, pub port...
Rust
0
_ => panic!(), } assert_eq!(t.value(), false); let mut t = ILBoolTag::new(); match t.deserialize_value(&factory, 1, &mut reader) { Err(ErrorKind::CorruptedData) => (), _ => panic!(), } match t.deserialize_value(&factory, 2, &mut reader) { Err(ErrorKind::Corrupte...
Rust
0
: """角色名 注意:此字段可能返回 null,表示取不到有效值。 :rtype: str """ return self._RoleName @RoleName.setter def RoleName(self, RoleName): self._RoleName = RoleName @property def RoleStatus(self): """角色状态,1-启用,2-禁用 注意:此字段可能返回 null,表示取不到有效值。 :rtype: int """ ...
Python
1
ter::once(&self.comm_f[j])). chain(iter::once(&g_inv)). chain(iter::once(&h_inv)), iter::once(challenge). chain(iter::once(&FieldElement::one())). chain(iter::once(&self.f_bar[j])). chain(iter::once(&self...
Rust
0
import argparse import pandas as pd import os def parse_args(): """解析命令列參數""" parser = argparse.ArgumentParser(description='CSV/Excel 樞紐表轉 Excel 工具') parser.add_argument('--csv', type=str, help='輸入的 CSV 或 Excel 檔案路徑', required=True) parser.add_argument('--excel', type=str, help='輸出的 Excel 檔案路徑', requi...
Python
1
![]; chunk.table_to_arrow(&mut batches, Selection::All).unwrap(); batches } } pub use self::textreader::*; pub use self::detector::*; mod textreader; mod detector; use core::cmp; use cast::u32; use stm32f042::{FLASH, RCC}; use time::Hertz; /// Extension trait that constrains the `RCC` peripheral...
Rust
0
ta = SharedTensor::<f32>::new(&10); assert!(shared_data.reshape(&vec![10, 2]).is_err()); } } // add `pub mod q_#` after solving a problem pub mod q_1; pub mod q_2; pub mod q_3; pub mod q_4; pub mod q_10; pub mod q_100; pub mod q_590; #![cfg_attr(target_os = "none", no_std)] #![cfg_attr(target_os = "none", n...
Rust
0
input_signal = input_signal[:, :, self.circle_indices] # Flatten circle and channels (B, T, N circle, C) -> (B, T, N) input_signal = input_signal.flatten(start_dim=2, end_dim=-1) # Flatten height, width and channels (B, T, H, W, C) -> (B, T, N) else: input_signal = ...
Python
1
(1 << WIDTH) - 1; ((reg >> (i * WIDTH)) & MASK) as usize } fn decode_option(reg: u64) -> Option<usize> { if reg == 0 { None } else { Some((reg & !(1 << 63)) as usize) } } let swap = call.read_value(); ...
Rust
0
# -*- coding: utf-8 -*- ''' Created on 2016-10-20 @author: hustcc ''' from app.wraps.login_wrap import login_required from app import app from app.utils import ResponseUtil, RequestUtil, AuthUtil from app.database.model import History # get history list @app.route('/api/history/list', methods=['GET']) @login_require...
Python
1
.deps.group_ay0_2048]; self.test_result(ct, ht, st, er, deps); } fn test_dep_expansion_count_2049(&self, er: ER) { let (ct, ht, st) = (CT::In, HT::Data, ST::Lock); self.intro(ct, ht, st, er, "dep expansion count is 2049"); let deps = &[&self.deps.code_bx0, &self.deps.group_ay0_2...
Rust
0
s(&tgt) { to_visit.push(dir); break; } } if to_visit.is_empty() { // Go back backtrack = path.pop(); } } let mut show_map_tiles = tiles.clone(); let mut path_pos = Vector...
Rust
0
irection: Direction::Up, count_infected: 0, } } fn next(&mut self) { if self.status.contains_key(&self.position) { // Uninfect and turn right self.status.remove(&self.position); self.direction = self.direction.right(); self.position = self.position.mov(self.direction); } e...
Rust
0
ference min_tuple=(A[i], A[j], A[k]) k-=1 else: return (A[i], A[j], A[k]) return min_tuple if __name__=='__main__': print 'two sum', two_sum([9,7,11,2,3], 14) #print three_sum_1([-10, 2, -7, -25, -3, 8, 4, 10]) print 'three su...
Python
1
let project_dirs = ProjectDirs::from("org", "Zellij Contributors", "Zellij").unwrap(); let data_dir = project_dirs.data_dir(); drop(fs::remove_file(data_dir.join("plugins/status-bar.wasm"))); drop(fs::remove_file(data_dir.join("plugins/tab-bar.wasm"))); drop(fs::remove_file(data_dir.join("plugins/st...
Rust
0
import pyttsx3 import speech_recognition as sr import webbrowser engine = pyttsx3.init() voice_notifications = False toggle_btn = None def set_toggle_btn(btn): global toggle_btn toggle_btn = btn def toggle_voice_notifications(): global voice_notifications, toggle_btn voice_notifications = not voice_n...
Python
1
rational(2, 1), // borrow_index Balance::zero(), // protocol_interest ) .set_pause_keeper(KSM, true) .build() .execute_with(|| { assert!(TestController::pause_keeper_storage(&KSM).deposit_paused); assert!(TestController::pause_keeper_storage(&KSM).redeem_paused); assert!(TestCon...
Rust
0
# import array as arr # Given an array arr,return the second largest distinct element from an array.If the second largest # element doesn't exixt then return -1 """ """ # def second_largest_element(self,arr): def second_largest_element(arr): n=len(arr) if n<2: return -1 first=second= fl...
Python
1
import os def rendering_evaluation(input_dir, full_exp_dir, exp_name, past_n_trials=0): files = sorted(os.listdir(input_dir)) os.makedirs(full_exp_dir, exist_ok=True) config_yml_path = os.path.join(input_dir, 'config.yml') exp_json = exp_name + '.json' full_exp_json = os.path.join(full_exp_dir...
Python
1
def prime_numbers(a): return list(filter(lambda x: len([i for i in range(1, x + 1) if x % i == 0]) <= 2, a)) print(prime_numbers([1, 2, 3, 4, 5]))
Python
1
error!("Severe error. Unkown alert type (type={})", alert.type_); return; } }; ctx.spawn(actix::fut::wrap_future::<_, AlerterActor>(alert_future).map(|_, _, _| ())); } } impl Actor for AlerterActor { type Context = Context<Self>; } impl Handler<Stat...
Rust
0
t sessions_manager = ctx.get_sessions_manager(); let processes_info = sessions_manager.processes_info(); let mut processes_id = Vec::with_capacity(processes_info.len()); let mut processes_type = Vec::with_capacity(processes_info.len()); let mut processes_host = Vec::with_capacity(proces...
Rust
0
""" Write a function to check if all the elements in tuple have same data type or not. assert check_type((5, 6, 7, 3, 5, 6) ) == True """ def check_type(tuple_data): """ :param tuple_data: tuple :return: True if all the elements in tuple have same data type or False """ data_type = tuple_data[0] ...
Python
1
/// use async_coap_uri::prelude::*; /// let authority = "user@[2001:0db8:85a3::1%en2]:8080"; /// /// let uri_buf = UriBuf::from_scheme_authority("http", authority); /// /// assert_eq!(uri_buf, uri!("http://user@[2001:0db8:8fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b%25en2]:8080")); /// /// ``` ...
Rust
0
arr = [1, 2, 3, 4, 5] print(arr == sorted(arr))
Python
1
: u32 = 32; pub const WORLD_UNIT_RATIO: f64 = (1.0 / PIXELS_PER_WORLD_UNIT as f64); pub struct GameState<'a, 'b> { pub world: World, pub tick_dispatcher: Dispatcher<'a, 'b>, pub physics_dispatcher: Dispatcher<'a, 'b>, } impl<'a, 'b> GameState<'a, 'b> { pub fn new(width: u32, height: u32) -> GameState<...
Rust
0
(alias = "gdk_display_get_app_launch_context")] pub fn app_launch_context(&self) -> Option<AppLaunchContext> { unsafe { from_glib_full(ffi::gdk_display_get_app_launch_context( self.to_glib_none().0, )) } } #[doc(alias = "gdk_display_get_default_cursor...
Rust
0
import os, json, multiprocessing, difflib, re, asyncio from typing import AsyncGenerator, List from pydantic import BaseModel from llama_cpp import Llama # ✅ 모델 캐시 LLM_CBT2_INSTANCE = {} def load_cbt2_model(model_path: str) -> Llama: global LLM_CBT2_INSTANCE if model_path not in LLM_CBT2_INSTANCE: NUM...
Python
1
ray(uvs, dtype=np.float32) faces_uv = np.array(faces_uv, dtype=np.int32) - 1 return vertices, faces, uvs, faces_uv return vertices, faces class VertexNormals(nn.Module): def __init__(self, normalize=True): super().__init__() self.normalize = normalize def forward(self, ve...
Python
1
# To be used paired with bh_sshRcmd.py # NOTE: this is used to emulate the ssh server on Windows and here the roles # of the client and the server are reversed: the server is the one who sends the # command to the client. import socket import paramiko import threading import sys # using the server host key from the ...
Python
1
import abc import dataclasses import functools import json from typing import ClassVar from primitive_metadata import ( gather, primitive_rdf as rdf, ) from trove import exceptions as trove_exceptions from trove.vocab import mediatypes from trove.vocab.trove import TROVE_API_THESAURUS from trove.vocab.namespa...
Python
1
r default runtime should not fail"); } server.use_pool(DEFAULT_RUNTIME.handle().clone()); server } use derive_new::new; use game_input_model::config::Axis; use sequence_model::loaded::SequenceId; use crate::config::InputReactionAppEvents; /// Transition to a specified fallback sequence. #[derive(Clone, D...
Rust
0
import json import sys def transform(src_json_file, target_json_file): with open(src_json_file) as f: src_json = json.load(f) stack_trace_samples = src_json['stackTraceSamples'] target_json_array = [] # 处理第一个 stack if stack_trace_samples: sample_first = stack_...
Python
1
)*) -> Result<$ret> { let form_data = json!({ $( stringify!($param): $param, )* }); let response = self.client.$method(&self.route(concat!("/api/v1/", $url))) .headers(self.headers.clone...
Rust
0
=self.eos_token_id, max_length=max_length, ) sequences = sequence_output["sequences"] sequence_scores = sequence_output["sequence_scores"] self.parent.assertListEqual(list(sequences.shape), [self.num_beams * self.batch_size, max_length]) self.parent.assertListEqual(l...
Python
1
from datetime import datetime, timedelta from airflow.utils.dates import days_ago from airflow import DAG from airflow.operators.python import PythonOperator, BranchPythonOperator from random import choice default_args = { 'owner':'nshk' } def random_num_picker(): return choice([1, 2, 3, 4]) def even_odd_bran...
Python
1
ationMethod::rand_data(rng)) .collect::<Vec<_>>(); Self { account_version: Self::VALID_ACCOUNT_VERSION, authority: Keypair::generate(rng).pubkey(), version: Self::DEFAULT_VERSION.to_string(), controller: vec![], authentication: Self::rand_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
p::entities::User; use crate::app::helpers::postgres_helper; pub fn find_by_email(project: &String, email: &String) -> Option<User> { let sql = "SELECT id, name, email, password FROM apis WHERE email=$1 and project=$2;"; let apis = postgres_helper::select(sql, &[ &email, &project ]); if apis.is_some() { ...
Rust
0
, debug) return model def _patch_attention_entropy(self, diffusion_model, entropy_scale, debug): """Patch attention mechanisms to apply entropy scaling""" def patch_attention_module(module, path=""): # Check if this is an attention module if has...
Python
1
} } //查找失败,返回错误 Err(_) => { return Box::new(None); } }; } } unreachable!(); } fn query(&self, key: &[K]...
Rust
0
import streamlit as st import cv2 import numpy as np from PIL import Image import tempfile import time import os from config.logging_config import setup_logging from models.model_loader import load_model from models.model_tester import test_model_inference from utils.image_processor import process_image # 配置日志 logger ...
Python
1
from datetime import datetime from config import config from gspread.client import Client def convert_date(date_str: str): dt = datetime.strptime(date_str, "%Y-%m-%d") month_names = [ "Январь", "Февраль", "Март", "Апрель", "Май", "Июнь", "Июль", ...
Python
1
E_GRAIN_BUFFER)) def has_fine_grain_system_svm(dev): return (_may_have_svm(dev) and bool(dev.svm_capabilities & cl.device_svm_capabilities.FINE_GRAIN_SYSTEM)) def has_fine_grain_buffer_svm_atomics(dev): return has_fine_grain_buffer_svm(dev) and bool(dev.svm_capabilities ...
Python
1
import random print("Password Generator -- A Project by Interstellar2424") choices = ("random", "costum") alpha = ("ajjsnx", "bhgvjhv", "chghg", "dhgcy", "egvgcyt", "fhgcty", "gghchg", "hyfj", "ihdksn", "jodmd", "khsic", "licnu", "mhusb", "nhds", "ogcbu","pgshi", "qmddjm", "rmemsk", "sjnsns", "tmemk", "uksmm", "vksm...
Python
1
_squares(squares); let recieved_threats = determine_all_threats(&board).unwrap(); let mut expected_threats = [IsThreatened(false); 64]; // Knight threats expected_threats[0] = IsThreatened(true); expected_threats[16] = IsThreatened(true); expected_threats[25] = IsThreate...
Rust
0
ObjectWriter, input: &crate::input::DisassociateDomainInput, ) { if let Some(var_30) = &input.domain_name { object.key("DomainName").string(var_30); } if let Some(var_31) = &input.fleet_arn { object.key("FleetArn").string(var_31); } } pub fn serialize_structure_disassociate_website_...
Rust
0
Mac/iOS memory resource exception flavors #[derive(Copy, Clone, PartialEq, Debug, Primitive)] pub enum ExceptionCodeMacResourceMemoryFlavor { FLAVOR_HIGH_WATERMARK = 1, } /// Mac/iOS I/O resource exception flavors #[derive(Copy, Clone, PartialEq, Debug, Primitive)] pub enum ExceptionCodeMacResourceIOFlavor...
Rust
0
# Lista com dez espaços inicialmente vazios (representados por 0) locais = [0,0,1,0,0,0,0,0,0,0] # Define o número de tentativas tentativas = 3 print("Bem-vindo ao jogo de caça ao tesouro!") print("Tente encontrar o tesouro. Você tem 3 tentativas.") print("Escolha um número entre 0 e 9 para procurar o tesouro.") # Inic...
Python
1
# vim: set expandtab shiftwidth=4 softtabstop=4: # === UCSF ChimeraX Copyright === # Copyright 2022 Regents of the University of California. All rights reserved. # The ChimeraX application is provided pursuant to the ChimeraX license # agreement, which covers academic and commercial uses. For more details, see # <http...
Python
1
(always)] pub fn fs_type(self) -> ffi::FT_Short { unsafe { (*self.raw).fsType } } #[inline(always)] pub fn y_subscript_x_size(self) -> ffi::FT_Short { unsafe { (*self.raw).ySubscriptXSize } } #[inline(always)] pub fn y_subscript_y_size(self) -> ffi::FT_Short { unsaf...
Rust
0
x = lambda a : a + 10 print(x(5)) x = lambda a, b, c : a + b + c print(x(1, 2, 3)) # use lambda function when an anonymous function is required for a short period of time def myfunc(n): return lambda a : a * n mydoubler = myfunc(2) mytripler = myfunc(3) print(mydoubler(2)) print(mytripler(5))
Python
1
c(hidden)] pub struct _RTC_CNTL_CPU_PERIOD_CONF; #[doc = "`read()` method returns [rtc_cntl_cpu_period_conf::R](rtc_cntl_cpu_period_conf::R) reader structure"] impl crate::Readable for RTC_CNTL_CPU_PERIOD_CONF {} #[doc = "`write(|w| ..)` method takes [rtc_cntl_cpu_period_conf::W](rtc_cntl_cpu_period_conf::W) writer str...
Rust
0
oc = " Get the name of the inner_l3 packet type"] #[doc = ""] #[doc = " @param ptype"] #[doc = " The packet type value."] #[doc = " @return"] #[doc = " A non-null string describing the packet type."] pub fn rte_get_ptype_inner_l3_name(ptype: u32) -> *const ::std::os::raw::c_char; } extern "C...
Rust
0
self.result_text.insert(tk.END, f"{error}\n") # 保存错误信息到文件 with open('syntax_errors.txt', 'w', encoding='utf-8') as f: f.write("编译错误:\n\n") for error in errors: f.write(error + '\n') except FileNo...
Python
1
he exponent to be an (odd) positive integer. // // [Knuth]: The Art of Computer Programming, Volume 2: Seminumerical // Algorithms (3rd Edition), Section 4.6.3. debug_assert_eq!(exponent & 1, 1); assert!(exponent < (1 << PUBLIC_EXPONENT_MAX_BITS.as_usize_bits())); let mut acc = try!(bas...
Rust
0
schema = pa.schema([pa.field("field_name", pa.int32())], metadata={"a": "b"}) assert schema.metadata == {b"a": b"b"} wrapped_schema = Wrapper(schema) assert pa.schema(wrapped_schema) == schema assert pa.schema(wrapped_schema).metadata == {b"a": b"b"} assert pa.schema(wrapped_schema, metadata={"a":...
Python
1
id": 4, "content": "Second tweet by User2", "author": {"id": 2, "name": "User2"}, "attachments": [], "likes": [{"user_id": 2, "name": "User2"}] }, { "id": 5, "content": "First tweet by User3", ...
Python
1
import pikepdf import os def desbloquear_pdf(input_pdf): # Abrir o arquivo PDF de entrada com a opção de permitir sobrescrever o arquivo with pikepdf.open(input_pdf, allow_overwriting_input=True) as pdf: # Salvar o PDF desbloqueado, sobrescrevendo o original pdf.save(input_pdf) # Solicitar o c...
Python
1
# This file includes code originally from the Geocalib repository: # https://github.com/cvg/GeoCalib # Licensed under the Apache-2.0 License. See THIRD_PARTY_LICENSES.md for details. from .extractor import GeoCalib
Python
1