text
string
label_name
string
labels
int64
else: print(f"❌ Document status check failed: {doc_status_response.status_code}") # Step 5: Verify file exists in storage print("\n🔄 Step 5: Verifying file exists in storage...") verify_response = await client.get(signed_url) if verify_response.status_co...
Python
1
�', "fú"), ('𦿂', "yuán"), ('𦿃', "shǎo"), ('𦿅', "bìng"), ('𦿆', "dàng"), ('𦿇', "shì"), ('𦿊', "lú"), ('𦿋', "qiè"), ('𦿌', "luó"), ('𦿍', "pò"), ('𦿏', "méng,mèng"), ('𦿐', "jié"), ('𦿓', "jī"), ('𦿖', "lù"), ('𧀄', "chàng"), ('𧀅', "miè,mò"), ('𧀆', "m...
Rust
0
("a", Integer), ("b", Integer), ("c", Integer), ("d", Integer), ("e", Integer), ("f", Integer), ]; pub const TIME_SUFFIX: &[(&str, McGroupType)] = &[("s", TimeS), ("t", TimeT), ("d", TimeD)]; pub fn uq_string(p: &mut McParser) { p.try_token(uq_string_tk, UnquotedString); } pub fn uq_stri...
Rust
0
"set_property BITSTREAM.CONFIG.SPI_FALL_EDGE YES [current_design]", ] self.toolchain.additional_commands = \ ["write_cfgmem -force -format bin -interface spix1 -size 4 " "-loadbit \"up 0x0 {build_name}.bit\" -file {build_name}.bin"] def create_programmer(self): ret...
Python
1
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, models class ProjectTask(models.Model): _inherit = "project.task" def _send_sms(self): for task in self: if task.partner_id and task.stage_id and task.stage_id.sms_tem...
Python
1
import cohere from typing import List, Dict, Any from app.config import settings import logging logger = logging.getLogger(__name__) class Reranker: def __init__(self): self.co = cohere.Client(settings.COHERE_API_KEY) def rerank(self, query: str, documents: List[Dict[str, Any]], top_k: int = 5) -> Li...
Python
1
/// async fn add_to_db( conn: &mut SqliteConnection, zettels: Vec<ParserGatherer>, ) -> Result<(), anyhow::Error> { conn.execute("BEGIN").await?; for zettel in zettels { conn.execute( sqlx::query("INSERT OR REPLACE INTO full_text VALUES(?,?);") ...
Rust
0
function. """ global WORKLOAD_FUNC_REGISTRY workload = json.loads(workload_key) if not workload[0] in WORKLOAD_FUNC_REGISTRY: raise ValueError( "%s is not registered. " % workload[0] + "Please register it with @auto_scheduler.register_workload" ) return workl...
Python
1
""" ASGI config for lab_management project. It exposes the ASGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/4.2/howto/deployment/asgi/ """ import os from django.core.asgi import get_asgi_application os.environ.setdefault('DJANG...
Python
1
# ! Adding Metadata new_room.add_metadata(room_a) new_room.add_metadata(room_b) new_room.refresh() new_room.compute_orientations() new_room.set_status(ROOM_STATUS.MERGED) room_a.set_status(ROOM_STATUS.FOR_DELETION) room_b.set_status(ROOM_STATUS.FOR_DELETION) ...
Python
1
mat!("Failed to persist record: {}", e))) } async fn batch_set(&self, records: Vec<DbRecord>) -> Result<(), AkdStorageError> { // TODO: This is really bad, we may end up with partial writes in case of failure. for record in records { self.set(record).await?; } Ok(())...
Rust
0
# This file is not meant for public use and will be removed in SciPy v2.0.0. # Use the `scipy.linalg` namespace for importing the functions # included below. import warnings from . import _special_matrices __all__ = [ # noqa: F822 'tri', 'tril', 'triu', 'toeplitz', 'circulant', 'hankel', 'hadamard', 'leslie'...
Python
1
ted_file_path): decrypt_file(encrypted_file_path, key) def is_file_encrypted(file_path): return file_path.endswith('.dedsec') def encrypt_file(file_path, key): iv = os.urandom(16) cipher = Cipher(algorithms.AES(key), modes.CFB(iv), backend=default_backend()) with open(file_path, 'rb'...
Python
1
[id] { for (t, val) in track.iter().enumerate() { waveform[t + start] += val; } } } Some(waveform) } fn box_clone(&self) -> Box<dyn Sample> { let mut tracks = Vec::new(); for track in &self.tracks { trac...
Rust
0
class LRMult(object): def __init__(self, lr_mult=1.): self.lr_mult = lr_mult def __call__(self, m): if getattr(m, 'weight', None) is not None: m.weight.lr_mult = self.lr_mult if getattr(m, 'bias', None) is not None: m.bias.lr_mult = self.lr_mult
Python
1
from tests.runtime_aggtest.aggtst_base import TstView from decimal import Decimal class aggtst_decimal_arg_min_value(TstView): def __init__(self): # checked manually self.data = [{"c1": Decimal("1111.52"), "c2": Decimal("2231.90")}] self.sql = """CREATE MATERIALIZED VIEW decimal_arg_min AS...
Python
1
Alias", alias, "doesn't exist"].join(" "))); match existing_alias { Ok(alias_record) => { // Check if alias is owned by user match slack_users.filter(slack_users_id.eq(&alias_record.slack_user_id)).first::<SlackUser>(conn) { Ok(SlackUser { id: _, s...
Rust
0
from math import factorial, comb total_games = int(input("Въведете брой мачове: ")) p_win = float(input("Вероятност за победа (в проценти): ")) / 100 p_draw = float(input("Вероятност за равен (в проценти): ")) / 100 p_loss = float(input("Вероятност за загуба (в проценти): ")) / 100 all_probabilities = {} for k_win i...
Python
1
县"), ("330226", "浙江省宁海县"), ("330227", "浙江省鄞县"), ("330281", "浙江省余姚市"), ("330282", "浙江省慈溪市"), ("330283", "浙江省奉化市"), ("330300", "浙江省温州市"), ("330301", "浙江省温州市市辖区"), ("330302", "浙江省温州市鹿城区"), ("330303", "浙江省温州市龙湾区"), ...
Rust
0
.clone().unwrap()); // assert_eq!(decoded.unwrap()[0].value, amount); let signed = sign(sign_config, &psbt_origin.clone().unwrap().psbt); println!("{:#?}", signed.clone().unwrap()); assert_eq!(signed.clone().unwrap().is_finalized, true); // let broadcasted = broadcast(config, &signed.unwrap().psbt);...
Rust
0
oad.put_u16_le(this.warnings as u16); payload.put_slice(this.info.as_bytes()); payload } } impl MySQLPacket for MySQLOKPacket { fn get_sequence_id(&self) -> u32 { self.sequence_id } } /** * ERR packet protocol for MySQL. * * @see <a href="https://dev.mysql.com/doc/internals/en...
Rust
0
_static, use_calib_mode=False) elif args.run_mode == "trt_fp16": config.enable_tensorrt_engine( workspace_size=1 << 30, max_batch_size=1, min_subgraph_size=15, precision_mode=PrecisionType.Half, use_static=trt_use_static, us...
Python
1
''' sample_async_00.py asyncと協調テスト - Pico W 本体のLEDとボタンの操作 - プログラム開始時に LEDを 3回点滅させる - ボタンを押して点滅開始、ボタン長押しで消灯 - ボタンを 20秒以上操作しないと、LEDを消灯してプログラム終了 ''' import time from e_module import Edas from e_machine import Eloop, Button, Bootsel_button, LED # Eloop.start(loop_interval=10, tracelevel=14) Eloop.start(loop_interval...
Python
1
ring()); let name: Name = vec!["x", ".", "y"].into(); assert_eq!("x.y", name.to_string()); let name: Name = vec!["x", " . ", "y"].into(); assert_eq!("x.y", name.to_string()); let name: Name = vec![".", "x", "y"].into(); assert_eq!(".x y", name.to_string()); let name: Name = vec!["x", "y...
Rust
0
e various nodes of the network. pub bit_segment_1: u8, /// Specifies the number of time quanta in Bit Segment 2: 1TQ..8TQ /// defines the location of the transmit point. It represents the /// PHASE_SEG2 of the CAN standard. Its duration is programmable /// between 1 and 8 time quanta but may also b...
Rust
0
from fastapi import FastAPI, HTTPException, Request from fastapi.staticfiles import StaticFiles from fastapi.responses import FileResponse from pydantic import BaseModel from chat_bot import PaintChatbot from core.config import settings import logging import traceback import time logging.basicConfig(level=logging.INFO...
Python
1
= get_console_mode(self.stdstream_handle)?; // To enable ANSI colors (Windows 10 only): // https://docs.microsoft.com/en-us/windows/console/setconsolemode if original_stdstream_mode & wincon::ENABLE_VIRTUAL_TERMINAL_PROCESSING == 0 { let raw = original_stdstream_mode...
Rust
0
/ 8]; let iter = chunks.chunks_exact(size_of); let start = if slice.len() > size_of { slice.len() - size_of } else { 0 }; let remainder = &slice[start..]; Self { iter, remainder, phantom: std::marker::PhantomDa...
Rust
0
def test_inference_batch_consistent(self): self._test_inference_batch_consistent(batch_sizes=[2])
Python
1
_WAIT_SECS seconds for the zwave network # to be ready. for i in range(NETWORK_READY_WAIT_SECS): _LOGGER.info( "network state: %d %s", NETWORK.state, NETWORK.state_str) if NETWORK.state >= NETWORK.STATE_AWAKED: _LOGGER.info("zwave ready after %d se...
Python
1
{ |it| $( -> $crate::Ae![$( $ty )|+] )? { $crate::Either::Right($crate::Either::Right($crate::Either::Right($crate::Either::Right($crate::Either::Left(it))))) } }; ($( <$( $ty:ty )|+> )? :: 4 ) => { |it| $( -> $crate::Ae![$( $ty )|+] )? { $crate::Either::Right($crate::Either::Right($crate::Ei...
Rust
0
b struct Caret { syntax: crate::SyntaxToken, } impl crate::ast::AstToken for Caret { /// Returns `true` if the given [`SyntaxKind`] is a [`CARET`] /// [`SyntaxKind`]: crate::SyntaxKind /// [`CARET`]: crate::SyntaxKind::CARET #[inline] fn can_cast_from(kind: crate::SyntaxKind) -> bool { k...
Rust
0
import numpy as np import matplotlib.pyplot as plt def plotWithLabels(data, labels, title="Best Path Found by Genetic Algorithm"): """ Plot the path between cities with city labels. Parameters: - data (numpy.ndarray): Array of city coordinates [lat, lng] - labels (list): List of city names corresp...
Python
1
""" Celery workers monitoring Мониторинг Celery воркеров и очередей """ import logging import time from datetime import datetime, timedelta from typing import Dict, Any, List, Optional logger = logging.getLogger(__name__) class CeleryMonitor: """ Монитор для Celery workers и задач Отслеживает: ...
Python
1
import pandas as pd import pyodbc import numpy import time from pyneoinstance import Neo4jInstance from pyneoinstance import load_yaml_file from bs4 import BeautifulSoup import logging logging.basicConfig(level=logging.INFO) def importingNodeMicroblogPost(cnxn, graph): """ graph as neo4j (Target DB) connector...
Python
1
writer_with_size(DEFAULT_BUFFER_LENGTH) } /// Create a stream writer with custom buffer size. /// /// See [`stream_writer`]. /// /// [`stream_writer`]: #fn.stream_writer pub fn stream_writer_with_size(&mut self, size: usize) -> Result<StreamWriter<W>> { StreamWriter::new(ChunkOutput...
Rust
0
ld_points() * 2 { let coord: <Range<T> as AsRangedCoord>::CoordDescType = self.0.clone().into(); let normal = coord.key_points(hint.max_num_points()); return normal; } self.bold_key_points(&hint) } } impl<T: TimeValue + Clone> DiscreteRanged for Monthly<T> where ...
Rust
0
""" Тип данных bool в Python представляет собой логические значения и используется для хранения произвольных значений, которые могут быть истинными (True) или ложными (False). 1) Хотя bool является отдельным типом данных, в Python он на самом деле является подтипом int. Значение True эквивалентно 1, а значение Fal...
Python
1
# config.py - Configuration settings import os from pathlib import Path from dotenv import load_dotenv # Get the directory where this config file is located CONFIG_DIR = Path(__file__).resolve().parent # Load environment variables from .env file in the same directory env_path = CONFIG_DIR / '.env' load_dotenv(dotenv_...
Python
1
f}||q||r|j|}|||f}||qn|td||S)NrrYr r<zunexpected option string: %s)rtrr rzrr"r`r) r'rrr option_prefixrr~rshort_option_prefixshort_explicit_argr.r.r/r s:        ...
Python
1
.0, (self.actor.player.width - 20) as f32, (self.actor.player.height - 35) as f32, ); } /// 敵の移動を自動で行い、コリジョン値を指定する fn enemy_move(&mut self) { self.enemy_move_speed_adjust(); // e_blockたちの表示座標を動かす for i in 0..self.actor.e_block.len() { ...
Rust
0
d, AddAssign, Mul, MulAssign, Neg, Sub, SubAssign}, }; use ff::Field; use rand_core::RngCore; use subtle::{Choice, ConditionallySelectable, ConstantTimeEq, CtOption}; use crate::fp2::Fp2; use crate::to_limb; // Little-endian non-Montgomery form. #[allow(dead_code)] const MODULUS: [u64; 6] = [ 0xb9fe_ffff_ffff_aa...
Rust
0
clone began somebody initiates a push. Everything goes well and as a new pack was created the server /// wants to tell the object database to update its packs, making the new one available. To do that, it needs mutable access to the /// repository instance, and obtaining it will take until the end of the ong...
Rust
0
a_file = absolute_path("_data/plugins/apps/webserver/citrix/httpaccess.log") fs_bsd.map_file("var/log/httpaccess.log", data_file) with pytest.raises( UnsupportedPluginError, match=re.escape("Use the 'apps.webserver.citrix' apache plugin instead") ): target_citrix.add_plugin(ApachePlugin) ...
Python
1
#!/usr/bin/env python3 import os import time import radical.pilot as rp # ------------------------------------------------------------------------------ # if __name__ == '__main__': # demonstrate task cancelation during execution: we start some tasks, then # wait for some to finish, and cancel some more, b...
Python
1
0070,// VEX_Vpshuflw_xmm_xmmm128_imm8 0x22DA_0070,// VEX_Vpshuflw_ymm_ymmm256_imm8 0x225A_0070,// EVEX_Vpshuflw_xmm_k1z_xmmm128_imm8 0x22DA_0070,// EVEX_Vpshuflw_ymm_k1z_ymmm256_imm8 0x235A_0070,// EVEX_Vpshuflw_zmm_k1z_zmmm512_imm8 0x6802_0071,// Psrlw_mm_imm8 0x680A_0071,// Psrlw_xmm_imm8 0x6A4A_0071,// VEX_Vp...
Rust
0
get_federation_by_block_height(block_height); federation.node_index() } pub fn pubkey_list(&self, block_height: u64) -> Vec<PublicKey> { let federation = self.get_federation_by_block_height(block_height); federation.signers().iter().map(|s| s.pubkey).collect() } pub fn aggregat...
Rust
0
odes are # to have the same task count, that count is followed by # "(x#)" where "#" is the repetition count. For example, # "SLURM_TASKS_PER_NODE=2(x3),1" indicates that the first # three nodes will each execute three tasks and the # fourth node will exe...
Python
1
import pytest from test_utils import run_query children = [ ( 5209574053332910079, 5, [ 5214064458820747263, 5214068856867258367, 5214073254913769471, 5214077652960280575, ], ), ( 5209574053332910079, 6, ...
Python
1
rink-wine, "drink wine")] #[default_options] #[command("0.0.1-fruits-eater", eat [food], "eat food")] fn eat_fn(food: Option<Food>, mutex_thing: Result<MutexThing, String>) { match food { Some(Food::Noodles) | Some(Food::Beef) | Some(Food::Fish) => println!("I eat it, I like it!"), _ => println!("I ...
Rust
0
SharedPtr, SessionSharedWeakPtr, }, ticks::Ticks, }; use libc::{sysconf, _SC_NPROCESSORS_CONF}; use nix::{ sched::{sched_getaffinity, CpuSet}, unistd::Pid, }; use rand::{seq::SliceRandom, thread_rng}; use std::{ collections::{BTreeMap, VecDeque}, mem, rc::Weak, }; // Tasks sorted by...
Rust
0
# -*- python -*- # This software was produced by NIST, an agency of the U.S. government, # and by statute is not subject to copyright in the United States. # Recipients of this software assume all responsibilities associated # with its operation, modification and maintenance. However, to # facilitate maintenance we as...
Python
1
fence)(vk.device, fence, null()) } pub unsafe fn wait(connection: &Gpu, fence: u64) { let vk = connection.get(); (vk.wait_fence)(vk.device, 1, [fence].as_ptr(), 1, ::std::u64::MAX) .unwrap(); } impl Drop for FenceContext { fn drop(&mut self) { unsafe { drop(&self.vulkan, self.fence) } } } // run-pass #![allo...
Rust
0
current_pre_cas = current_dates.get('pre_cas') if current_pre_cas == status.get('pre_cas_date'): history.setdefault('pre_cas_observations', []) if not any(o.get('timestamp') == last_up_iso for o in history['pre_cas_observations']): history['pre_cas_observ...
Python
1
def convert_to_snake_case(pascal_or_camel_cased_string): snake_cased_char_list = [ '_' + char.lower() if char.isupper() else char for char in pascal_or_camel_cased_string ] return ''.join(snake_cased_char_list).strip('_')
Python
1
} fn descriptor_static() -> &'static ::protobuf::reflect::MessageDescriptor { static descriptor: ::protobuf::rt::LazyV2<::protobuf::reflect::MessageDescriptor> = ::protobuf::rt::LazyV2::INIT; descriptor.get(|| { let mut fields = ::std::vec::Vec::new(); fields.push(::protobuf...
Rust
0
Writes `variant` to the field"] #[inline] pub fn variant(self, variant: ISOURCEW) -> &'a mut W { { self.bits(variant._bits()) } } #[doc = "Current source disabled"] #[inline] pub fn off(self) -> &'a mut W { self.variant(ISOURCEW::OFF) } #[doc = "Curre...
Rust
0
mfr_data()? .get(&MFR_DATA_FIELD)? .get(7)?; Some((((*acc_x_top as u16) << 8) | *acc_x_bottom as u16) as i16) } pub fn get_acceleration_y(&self) -> Option<i16> { let device = self.get_bt_device(); let acc_y_top = device .get_mfr_data()? .g...
Rust
0
login_type.to_string().is_empty() { query_args.push(("login_type".to_string(), login_type.to_string())); } if !option.to_string().is_empty() { query_args.push(("option".to_string(), option.to_string())); } let query_ = serde_urlencoded::to_string(&query_args).unwr...
Rust
0
merged if clip_depth == 16 else depth(merged, clip_depth) def multi_debander(clip: vs.VideoNode, old_clip: vs.VideoNode) -> vs.VideoNode: from debandshit.debanders import dumb3kdb from vsutil import get_y, join, plane mask = detail_mask(old_clip, brz=(1000, 3000), pf_sigma=False) deband = dumb3kdb(g...
Python
1
optimizers.SGD( learning_rate=learning_rate, momentum=momentum, nesterov=nesterov ) opt_type, opt_args = get_optimizer_info(opt) self.assertEqual(opt_type, "SGD") self.assertEqual(opt_args, expected_args) beta_1 = 0.8 beta_2 = 0.6 epsilon = 1e-08 ...
Python
1
from pybullet_rendering import BaseRenderer, RenderingPlugin import panda3d.core as p3d from surrol.gui.scene import GymEnvScene class Panda3DSceneRenderer(BaseRenderer): def __init__(self): BaseRenderer.__init__(self) self.plugin = None self._scene = None def build(self, cid, scene...
Python
1
: bool, } #[doc(hidden)] pub fn eval(ast: &Ast) -> f64 { match ast.children.len() { // numeric types 0 => match ast.tok { Token::Int(n) => n as f64, Token::Float(f) => f, _ => panic!("zero children should be numeric"), }, // unary operators ...
Rust
0
import pandas as pd import numpy as np import os df=pd.read_csv("labels.csv") #list columns print(df.columns) list_age_label=df["age"].unique() list_race_label=df["race"].unique() list_masked_label=df["masked"].unique() list_skintone_label=df["skintone"].unique() list_emotion_label=df["emotion"].unique() list_gender_...
Python
1
().remove(&String::from(key)); () } // Copyright 2021 <NAME> // // 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...
Rust
0
# Copyright (c) 2009-2011 Reza Lotun http://reza.lotun.name/ # # 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 limitation the rights to use, copy, mod...
Python
1
ullets = [] for bullet_data in section_data.get("bullets", []): # Validate claim IDs referenced_ids = bullet_data.get("claim_ids", []) valid_ids = [cid for cid in referenced_ids if cid in claim_ids] ...
Python
1
{}-{}", left, right); } Ok((left, right)) } fn parse_frac_range(input: &str) -> Result<(f64, f64)> { let toks: Vec<&str> = input.split("-").collect(); if toks.len() != 2 { bail!("Frac range {:?} is not FLOAT-FLOAT", input); } let (left, right) = (par...
Rust
0
ious resolutions, and how out of bounds /// samples are handled. /// /// For more background see: https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/texParameter /// #[derive(Copy,Clone,Debug,Default)] pub struct Parameters { /// Specifies the setting for the texture magnification filter (`Conte...
Rust
0
> ADC14SC_A::ADC14SC_0, true => ADC14SC_A::ADC14SC_1, } } #[doc = "Checks if the value of the field is `ADC14SC_0`"] #[inline(always)] pub fn is_adc14sc_0(&self) -> bool { **self == ADC14SC_A::ADC14SC_0 } #[doc = "Checks if the value of the field is `ADC14SC_1`"] ...
Rust
0
"""Constants for Moonraker.""" from enum import Enum from homeassistant.const import Platform # Base component constants DOMAIN = "moonraker" DOMAIN_DATA = f"{DOMAIN}_data" VERSION = "1.10.0" MANIFACTURER = "@marcolivierarsenault" # Platforms PLATFORMS = [ Platform.SENSOR, Platform.CAMERA, Platform.BUTT...
Python
1
from multiprocessing import Process, set_start_method def _verify_no_extra_import(extra_module: str): """Verifies that extra modules are not imported.""" import sys import oumi.cli.main # noqa assert extra_module not in sys.modules, f"{extra_module} was imported." def test_cli_speed_regression_no...
Python
1
pub fn rate(&self) -> f32 { ((self.unique as f64 / self.total as f64) * 100.0) as f32 } /// Retrieves the total count of input entries. pub fn total(&self) -> u64 { self.total } /// Retrieves the total count of unique entries. pub fn uniques(&self) -> u64 { self.unique ...
Rust
0
: usize| { *sp -= size as u64; std::slice::from_raw_parts_mut(*sp as usize as _, size) }; // This contains (guest) pointers to all argument strings annd environment variables. let mut env_pointers = Vec::new(); let mut arg_pointers = Vec::new(); // Copy ...
Rust
0
""" AU audio file parser Author: Victor Stinner Creation: 12 july 2006 """ from hachoir.parser import Parser from hachoir.field import UInt32, Enum, String, RawBytes from hachoir.core.endian import BIG_ENDIAN from hachoir.core.text_handler import displayHandler, filesizeHandler from hachoir.core.tools import createDi...
Python
1
oop { // Business goes here owner::update_wallet_state( self.wallet_inst.clone(), (&keychain_mask).as_ref(), status_send_channel, false, None, // In background make sense to update all accounts )?; let sec = frequency.as_secs(); for _ in 0..sec { if !self.is_running.load(Orderin...
Rust
0
sinstance(transformer_obj, GenericListTransformer): # Recreate list transformers sequentially for transformer in dt[name].transformers.values(): deserialized = preprocessor.transformer_types()[name].deserialize( transformer ...
Python
1
element type is &'a T. pub fn iter(&self) -> ValuesIter<'_, T, S> { match self.0 { ValuesInner::Short(ref v) => ValuesIter(ValuesIterInner::Short(v.iter())), ValuesInner::Long(ref v) => ValuesIter(ValuesIterInner::Long(v.iter())), } } /// Returns a guarded reference ...
Rust
0
:/t/t/t/ //F:\\t\\t\\t\\ pub fn convert_path(path_str: &str) -> String { if cfg!(target_os = "windows") { String::from(path_str.replace("\\", "/")) } else { String::from(path_str) } } pub fn convert_spell() -> &'static str { return if cfg!(target_os = "windows") { "\\" } e...
Rust
0
i= 0 while i <1 : print("elije: ") print("1. Celsius a Fahrenheit") print("2. Fahrenheit a Celsius") print("oprime un numero mayor para terminar") x = int(input()) if x <= 2: if x == 1: c = float(input("Celsius: ")) f = (c* 9/5)+32 print("Fahrenhei...
Python
1
Vec::new(); let r = r.transform(self.transform.inverse()); let sphere_to_ray = r.origin - Point::new(0.0, 0.0, 0.0); let a = r.direction.dot(r.direction); let b = 2.0 * r.direction.dot(sphere_to_ray); let c = sphere_to_ray.dot(sphere_to_ray) - 1.0; let discriminant =...
Rust
0
const fn iter() -> &'static [Self] { /// &[Flag::Flag1, Flag::Flag2, Flag::Flag5] /// } /// /// /// Returns the flag with the highest bit value. /// #[inline(always)] /// const fn max() -> Self { /// let mut i = 0; /// let mut max = Flag::Flag1; /// /// while i < Self::it...
Rust
0
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # NO CHECKED-IN PROTOBUF GENCODE # source: request_subscribe_for_order_updates.proto # Protobuf Python Version: 6.31.0 """Generated protocol buffer code.""" from google.protobuf import descriptor as _descriptor from google.protobuf impor...
Python
1
string()); } else if ch == '/' { tks.push("/".to_string()); } else if ch.is_numeric() { let mut nums: Vec<char> = Vec::new(); nums.push(ch); loop { if let Some(d) = iter.peek() { if d.is_numeric() { ...
Rust
0
self.style_count): latents.append(self.styles[j](p1)) out = torch.stack(latents, dim=1) return out class BackboneEncoderUsingLastLayerIntoW(Module): def __init__(self, num_layers, mode='ir', opts=None): super(BackboneEncoderUsingLastLayerIntoW, self).__init__() print('...
Python
1
ds[i], ( f"J_{i} ({fields[i]}) does not match J_{i}_ref ({ref_for_fields[i]})" ) assert not any(fields[len(ref_for_fields) :]) def compute_moiety_conservation_laws_demartino2014( data_demartino2014, quiet=False ): """Compute conserved quantities for De Martino's published results f...
Python
1
let inp_in: *mut bindings::VipsImage = inp.ctx; let direction_in: i32 = direction as i32; let mut nolines_out: f64 = f64::from(0); let vips_op_response = bindings::vips_countlines( inp_in, &mut nolines_out, direction_in.try_into().unwrap(), ...
Rust
0
import json import pandas as pd import nltk from string import punctuation from nltk.tokenize import word_tokenize from nltk.stem import WordNetLemmatizer from sklearn.preprocessing import LabelEncoder from sklearn.model_selection import train_test_split from sklearn.feature_extraction.text import TfidfVectorizer fro...
Python
1
#%% packages import os import re from pprint import pprint from pypdf import PdfReader from langchain.text_splitter import RecursiveCharacterTextSplitter, SentenceTransformersTokenTextSplitter import chromadb import openai from openai import OpenAI openai.api_key = os.environ["OPENAI_API_KEY"] # %% ipcc_report_file = ...
Python
1
#coding: utf-8 ''' “获取页面上所有外链”这样的小函数是不错的做法,以后可以方便地修 改代码以满足另一个采集任务的需求。例如,如果我们的目标是采集一个网站所有的外 链,并且记录每一个外链,我们可以增加下面的函数 ''' from urllib.request import urlopen from urllib.error import HTTPError from bs4 import BeautifulSoup from . import flexible_implement_different_crawlers # import sys # sys.path.append(r'flexible_imp...
Python
1
("could not create window"); let window = unsafe { window .make_current() .expect("could not make window context current") }; (event_loop, window) } fn glow_context(window: &Window) -> glow::Context { unsafe { glow::Context::from_loader_function(|s| window.get_proc_addre...
Rust
0
import glob import os import cv2 def show_img(path): img_dir = os.path.join(path,'images') lab_dir = os.path.join(path, 'xmls_txt') for img_path in glob.glob(img_dir + '/*'): file_name = os.path.basename(img_path).split('.')[0] im = cv2.imread(img_path) img_height,img_width,c...
Python
1
"""Testing formula 4.3N of EN 1992-1-1:2004.""" import pytest from blueprints.codes.eurocode.en_1992_1_1_2004.chapter_4_durability_and_cover.formula_4_3n import Form4Dot3nCheckExecutionTolerances from blueprints.validations import LessOrEqualToZeroError, NegativeValueError class TestForm4Dot3nCheckExecutionToleranc...
Python
1
from ._anvil_designer import Form1Template from anvil import * import anvil.tables as tables import anvil.tables.query as q from anvil.tables import app_tables class Form1(Form1Template): def __init__(self, **properties): # Set Form properties and Data Bindings. self.init_components(**properties) self.ca...
Python
1
import pyfiglet ascii = pyfiglet.figlet_format("Kela Khao Khao Khao") print(ascii)
Python
1
"pond", "darkness", "snowflake", "silence", "sound", "sky", "shape", "surf", "thunder", "violet", "water", "wildflower", "wave", "water", "resonance", "sun", "wood", "dream", "cherry", "tree", "fog", "frost", "voice", "paper...
Rust
0
import urllib.request from pathlib import Path from threading import Thread from urllib.error import HTTPError from tqdm import tqdm default_models = { "encoder": ("https://drive.usercontent.google.com/download?id=1qbQCsSvO_yBWNd-o5oKof2J9M6i-XSdP&export=download&authuser=0&confirm=t&uuid=732920b9-8b71-4148-9a2f...
Python
1
''' 《剑指Offer第2版》第38题 字符串的排列 LCR 157. 套餐内商品的排列顺序 某店铺将用于组成套餐的商品记作字符串 goods,其中 goods[i] 表示对应商品。请返回该套餐内所含商品的 全部排列方式 。 返回结果 无顺序要求,但不能含有重复的元素 ''' class Solution(object): def goodsOrder(self, goods): """ :type goods: str :rtype: List[str] """ arr=list(goods) res=[] ...
Python
1
j, ); if result <= 17. { delta -= NUDGE_VALUE; } else if 40. >= result && result <= 42. { delta += NUDGE_VALUE; } result = sum_values_in_neighborhood( &cellular_state, ...
Rust
0
sition().unwrap(), exp_pos); assert_eq!(pos.error_offset().unwrap().line(), 1); assert_eq!(pos.error_offset().unwrap().byte(), 7); let exp_pos = _Position::new().set_line(2).set_byte(8).set_record(0).clone(); validate_position!(pos.position().unwrap(), exp_pos); assert!(pos.recor...
Rust
0