text
string
label_name
string
labels
int64
import cv2 def visualize(img, license_plateScore, license_plate, pointx1, pointy1, pointx2, pointy2): label = "%d%% %s" % (int(license_plateScore * 100), license_plate) cv2.rectangle(img, (int(pointx1), int(pointy1)), (int(pointx2), int(pointy2)), (0, 255, 0), 2) cv2.putText(img, label, (int(pointx1), int...
Python
1
%s%s.t7' % (args.arch, suffix) print('Using path: %s' % path) # Model if args.resume: # Load checkpoint. print('==> Resuming from checkpoint.. %s' % path) assert os.path.isdir('checkpoint'), 'Error: no checkpoint directory found!' checkpoint = torch.load(path) net = checkpoint['net'] best_acc =...
Python
1
p_predicted_values"] = True cfg_ppo["entropy_loss_scale"] = 0.0 cfg_ppo["value_loss_scale"] = 2.0 cfg_ppo["kl_threshold"] = 0 cfg_ppo["state_preprocessor"] = RunningStandardScaler cfg_ppo["state_preprocessor_kwargs"] = {"size": env.observation_space, "device": device} cfg_ppo["value_preprocessor"] = RunningStandardScal...
Python
1
from datetime import datetime from typing import Optional from pydantic import BaseModel, Extra, Field, PositiveInt class CharityProjectBase(BaseModel): name: Optional[str] = Field(None, max_length=100) description: Optional[str] = Field(None) full_amount: Optional[PositiveInt] = Field(None) class C...
Python
1
import vacuum_cleaner import environment def main(): env = environment.Enviroment(5, 5) # Create a vacuum cleaner at position (0, 0) with 0 initial energy vacuum = vacuum_cleaner.VacuumCleaner(0, 0) # Start the vacuum cleaner vacuum.start_cleanup(env) env.print_status() if __name__ == "__ma...
Python
1
#!/usr/bin/env python # -*- coding:utf-8 -*- # @Time : 2024/6/6 # @Author : cyq # @File : __init__.py # @Software: PyCharm # @Desc: from fastapi import Header from utils import MyLoguru from app.mapper.user import UserMapper from ..exception import AuthError LOG = MyLoguru().get_logger() class Authentication: ""...
Python
1
valores = [] for i in range(0, 100): valores.append(int(input())) print(max(valores)) print(valores.index(max(valores)) + 1)
Python
1
Default::default() } }); s.is_scanning = false; s.entries = sorted_entries(&traversal.tree, s.root, s.sorting); s.selected = s.selected.or_else(|| s.entries.get(0).map(|b| b.index)); s ...
Rust
0
ASH值 real_grid_list = game.grid_history if len(real_grid_list) > 1: # 真实的上上步的棋盘状态HASH值 two_step_real_grid_hash = real_grid_list[len(real_grid_list)-2] # 计算虚拟结果的棋盘状态HASH值 current_virtual_grid_hash = GameHelp.cal_current_grid_hash(_game.grid) if ...
Python
1
バレッジ)(arg: order_id, price, losscut_price)", 3, |io, _, s|{ match s[0].parse::<usize>() { Ok(id) => { writeln!(io, "{:#?}", private::api::change_order( id, s[1].to_string(), Some(s[2].to_stri...
Rust
0
{ self.as_bytes().p(s) } } impl<P1: Recognize, P2: Recognize> Recognize for (P1, P2) { #[inline(always)] fn p(&self, s: &[u8]) -> Option<usize> { self.0.p(s).and_then(|len1| self.1.p(&s[len1..]).map(|len2| len1 + len2)) } } /// Choice from two heterogeneous...
Rust
0
import networkx as nx import pandas as pd # Load the data data = pd.read_csv(r'C:\Users\habha\Desktop\codingSpace\SchoolCodes\year3\SNA\dataset\data_2024-02-01.csv') # Create a graph from the data G = nx.Graph() for i, row in data.iterrows(): artists = row['artistName'].split(',') artists = [a.strip() for a i...
Python
1
pages', '0001_initial'), ('sites', '0001_initial')] after = [('flatpages_custom', '0001_add_help_page_if_not_present')] # app_name = 'flatpages_custom' # before = 'zero' # after = '0001' def test_migration_when_help_flatpage_already_exists(self): FlatPage = self.get_model_before('flatpages....
Python
1
""" build123d imports name: test_skip_clean.py by: Gumyr date: January 22, 2025 desc: This python module contains tests for the build123d project. license: Copyright 2025 Gumyr Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the ...
Python
1
tion=cv2.INTER_LINEAR) x_t = resized_screen[18:102, :] x_t = np.reshape(x_t, [84, 84, 1]) return x_t.astype(np.uint8) class ProcessFrame84(gym.Wrapper): def __init__(self, env=None): super(ProcessFrame84, self).__init__(env) self.observation_space = spaces.Box(low=0, high=255, shape=(8...
Python
1
lash_light.on() else: flash_light.off() OK(cs) @route('/fmt') def fmt(cs,w): setting(cs,w,(w>=1 and w<=9),camera.pixformat,'pixformat') @route('/pix') def pix(cs,w): setting(cs,w,(w>0 and w<18),camera.framesize,'framesize') @route('/qua') def qua(cs,w): setting(cs,w,(w>9 and w<64),camera.quali...
Python
1
of variational 3D assets. One day, //! perhaps digital content creation tools will include ways to export variational assets natively. //! Until that day, this is how we're doing it. //! //! In this prerelease version, the tool produces files with the Khronos extension //! [`KHR_materials_variants`](https://github.com...
Rust
0
in() { let conn = cargo_registry::db::connect_now().unwrap(); conn.transaction::<_, diesel::result::Error, _>(|| { transfer(&conn); Ok(()) }) .unwrap() } fn transfer(conn: &PgConnection) { let from = match env::args().nth(1) { None => { println!("needs a from-use...
Rust
0
At = transpose(A, x) if self.cov_x is None: cov_y_xt = lambda v: self.cov_y @ v + cov_t * A(*vjp(At(v))) else: cov_x_xt = cov_t + (-(cov_t**2)) * (self.cov_x + cov_t).inv cov_y_xt = lambda v: self.cov_y @ v + A(cov_x_xt @ At(v)) b = self.y - y ...
Python
1
e.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Thread-local random number generator use std::cell::UnsafeCell; use std::rc::Rc; use {RngCore, Crypt...
Rust
0
trimmed_params.push(param); } let (ttype, subtype) = (top_s.to_string(), sub_s.to_string()); let params = params.map(|_| trimmed_params.join(";")); Ok(ContentType::with_params(ttype, subtype, params)) } } impl fmt::Display for ContentType { /// Formats the ContentType a...
Rust
0
"std")] pub mod std_types; /// `utils` contains utility functions for working with bytestrings, including /// hex encoding and decoding. #[cfg(feature = "std")] pub mod utils; #[cfg(test)] #[doc(hidden)] #[cfg_attr(tarpaulin, skip)] pub mod test_utils { extern crate hex; extern crate std; use primitive...
Rust
0
wchar_t, ap: va_list, ) -> c_int { unimplemented!(); } // #[no_mangle] pub extern "C" fn swscanf(s: *const wchar_t, format: *const wchar_t, ap: va_list) -> c_int { unimplemented!(); } // #[no_mangle] pub extern "C" fn towlower(wc: wint_t) -> wint_t { unimplemented!(); } // #[no_mangle] pub extern "C"...
Rust
0
sable); rupro_todo_mark!(Dynamic); TypingReturnInfo { return_type: locl_ty, } } pub fn fun_implicit_return<R: Reason>(_env: &TEnv<R>) { rupro_todo_mark!(Dynamic); rupro_todo_mark!(AwaitableAsync); rupro_todo_mark!(Generators); rupro_todo_mark!...
Rust
0
TR_EC`](https://docs.microsoft.com/en-us/windows/win32/controls/en-align-ltr-ec) /// command notification. } pub_fn_cmd_noparm_noret! { en_align_rtl_ec, co::EN::ALIGN_RTL_EC, /// [`EN_ALIGN_LTR_EC`](https://docs.microsoft.com/en-us/windows/win32/controls/en-align-rtl-ec) /// command notification. } ...
Rust
0
losing_score: self.boards[losing_board_index.unwrap()].score() * number as u64, }); } } return Err(Box::new(DepletedRandomNumbersError {})); } } fn main() -> Result<(), Box<dyn Error>> { let stdin = io::stdin(); let mut bingo_subsystem = BingoSu...
Rust
0
# Copyright © 2023-2024 Apple Inc. import asyncio from typing import List, Tuple from pfl.aggregate.base import Backend from pfl.context import CentralContext from pfl.metrics import Metrics from pfl.model.base import Model from pfl.stats import StatisticsType def run_train_eval( algorithm, backend: Backend...
Python
1
# back to 3D if len(current_obs.shape) == 2: current_obs = np.expand_dims(current_obs, axis=-1) if not cfg.env.grayscale: current_obs = np.repeat(current_obs, 3, axis=-1) # channel first (PyTorch default) ob...
Python
1
0, method="SLSQP", bounds=bounds, constraints=constraints ) if result.success: return dict(zip(available_stocks, result.x)) else: return weights except Exception as e: logger.error(f"再平衡錯誤: {e}") return weights class...
Python
1
d_part ) )); assert_eq! (unsafe { & ( * ( 0 as * const st_mysql_time ) ) . neg as * const _ as usize } , 28usize , concat ! ( "Alignment of field: " , stringify ! ( st_mysql_time ) , "::" , stringify ! ( neg ) )); assert_eq! (unsafe { ...
Rust
0
import os from typing import Union, List, Tuple import pandas as pd import numpy as np from joblib import load def read_train_dev_test( target_path: str, if_dev_data: bool = False ) -> Union[Tuple[pd.DataFrame, pd.DataFrame, pd.DataFrame, np.ndarray, np.ndarray, np.ndarray], Tuple[pd.DataFrame, No...
Python
1
rtNodeMeshToJbeam, DEVTOOLS_JBEAMEDITOR_IMPORT_OT_BeamngImportPcFileToNodeMeshes, OBJECT_OT_BeamngCreateEmptiesBase, OBJECT_OT_BeamngCreateMetaBallCloud, OBJECT_OT_BeamngParentToStart01Empty, OBJECT_OT_BeamngClearChildrenStart01Empty, OBJECT_OT_BeamngConvertJbeamToNodeMes...
Python
1
} } fn close(fd: RawFd) { let _ = syscall!(close(fd)); } fn epoll_add(epoll_fd: RawFd, fd: RawFd, mut event: libc::epoll_event) -> io::Result<()> { syscall!(epoll_ctl(epoll_fd, libc::EPOLL_CTL_ADD, fd, &mut event))?; Ok(()) } fn epoll_modify(epoll_fd: RawFd, fd: RawFd, mut event: libc::epoll_event) -...
Rust
0
from django.contrib import admin from .models import Feedback @admin.register(Feedback) class FeedbackAdmin(admin.ModelAdmin): list_display = ('name', 'course', 'rating', 'status', 'timestamp') list_filter = ('course', 'rating', 'status') search_fields = ('name', 'course', 'comment') readonly_fields = ...
Python
1
from_repr(&*base_field, fp_9_repr).unwrap(); // // // fp2_non_residue.c0 = fp_9.clone(); // // // fp2_non_residue.c1 = one.clone(); // // // let mut extension_6 = Extension3Over2::new(fp2_non_residue.clone()); // // // extension_6.calculate_frobenius_coeffs_optimized(&modulus).expect("...
Rust
0
# Code for Jupyter/IPython Notebook environment from keras.models import Sequential from keras.layers.core import TimeDistributedDense, Activation, Dropout from keras.layers.recurrent import GRU import numpy as np from keras.utils.layer_utils import print_layer_shapes %matplotlib inline import matplotlib.pyplot a...
Python
1
s if word in positive_words) negative_count = sum(1 for word in words if word in negative_words) # Przygotuj wyniki analizy analysis = { "total_characters": len(text), "total_words": len(words), "unique_words": len(unique_words), "sentences_count": len(sentences), ...
Python
1
else: secrets_fmt.SecretTableUsingArgument(args, api_version=api_version) if not project_ref: raise exceptions.RequiredArgumentException( 'project', 'Please set a project with `--project` flag or `gcloud config set' ' project <project_id>`.', ) server_filter =...
Python
1
[u32; 4]) -> U where T: Simd, <T as Simd>::Element: Shuffle<[u32; 4], Output = U>; pub fn simd_shuffle8<T, U>(x: T, y: T, idx: [u32; 8]) -> U where T: Simd, <T as Simd>::Element: Shuffle<[u32; 8], Output = U>; pub fn simd_shuffle16<T, U>(x: T, y: T, idx: [u32; 16]) -> U...
Rust
0
is the only, then use stdin let total_bytes_removed = match args.files.len() { 0 => handle_stdin(&args), 1 if args.files.get(0).unwrap().to_str() == Some("-") => handle_stdin(&args), _ => handle_vec(&args), }; if !args.no_total { println!("{}", meta_summary("-- total", tota...
Rust
0
} // 使用unsafe pub fn invert_tree_2(mut root: Option<Rc<RefCell<TreeNode>>>) -> Option<Rc<RefCell<TreeNode>>> { if root.is_none() { return None; } let ref_mut = root.as_mut().unwrap().as_ptr(); unsafe { let l = &mut (*ref_mut).left; let r = &m...
Rust
0
namesyntax: u32, profilename: *const u16, inquirytype: u32, ifid: *const RPC_IF_ID, versoption: u32, membernamesyntax: u32, membername: *const u16, inquirycontext: *mut *mut ::core::ffi::c_void) -> RPC_STATUS; #[doc = "*Required features: `\"Win32_System_Rpc\"`*"] pub fn RpcNsProfileEltInqDone(inquirycontext: *...
Rust
0
-> anyhow::Result<u8> { unsafe { match READ_U8_CALLBACK { Some(f) => { let mut value = 0u8; let raw_value = &mut value as *mut u8; if f(self.stream_handle, raw_value) == 0 { Ok(value) ...
Rust
0
REATE TABLE test (id INTEGER PRIMARY KEY, value INTEGER)", "INSERT INTO test VALUES (1, 7)", ]; update_integer: "UPDATE test SET value = 3", update_integer_conflict: "UPDATE test SET value = 'abc'", update_integer_float: "UPDATE test SET value = 3.14", update_integer_null: "UPDATE test SET v...
Rust
0
let file = File { path: path, bins: machos, }; result.push(file); } } Ok(result) } fn scan_uuids_in_executable_file(exe: &Path) -> CIResult<Vec<MachO>> { use goblin::Object; use goblin::mach::Mach::*; let content = fs::read(exe)?;...
Rust
0
# Imprime 3 #Intentar seguir iterando lanza una excepción StopIteration #print(next(iterador)) # Lanza StopIteration # Iterar con un bucle for (automáticamente gestiona el iterador) print("\nIteración con bucle for:") for elemento in mi_lista: print(elemento) #Creación de un iterador personalizado class Iterado...
Python
1
= unsafe { _mm_set_pd(tw7.im, tw7.im) }; let twiddle8re = unsafe { _mm_set_pd(tw8.re, tw8.re) }; let twiddle8im = unsafe { _mm_set_pd(tw8.im, tw8.im) }; let twiddle9re = unsafe { _mm_set_pd(tw9.re, tw9.re) }; let twiddle9im = unsafe { _mm_set_pd(tw9.im, tw9.im) }; let twiddle10r...
Rust
0
fn create_3dxz() -> Self { (3, 2, 1).into() } pub fn create_3dx2y2() -> Self { (3, 2, 2).into() } } impl From<(i8, i8, i8)> for AtomicOrbital { fn from(qnumber: (i8, i8, i8)) -> Self { Self { n: Shell::try_from(qnumber.0 as u8).unwrap(), l: AngularMomen...
Rust
0
+ WithPwm, PINS: Pins<TIM, P>, { timer: Timer<TIM, FREQ>, _pins: PhantomData<(P, PINS)>, } impl<TIM, P, PINS, const FREQ: u32> Pwm<TIM, P, PINS, FREQ> where TIM: Instance + WithPwm, PINS: Pins<TIM, P>, { pub fn split(self) -> PINS::Channels { PINS::split() } pub fn release(mut...
Rust
0
"""Visualizer for modelAPI.""" # Copyright (C) 2024-2025 Intel Corporation # SPDX-License-Identifier: Apache-2.0 from __future__ import annotations from typing import TYPE_CHECKING import numpy as np from PIL import Image from model_api.models.result import ( AnomalyResult, ClassificationResult, Detect...
Python
1
ln!("avx: {:?}", c) } } #[cfg(any(target_arch = "arm"))] mod arch { use simdty::f32x4; use llvmint::arm; pub fn main() { let a = f32x4(1.0, 2.0, 3.0, 4.0); let b = f32x4(6.0, -7.0, 8.0, -9.0); let c = unsafe {arm::neon_vmax_v4f32(a, b)}; println!("{:?}", c); } } <f...
Rust
0
w']).sum() / 3 else: trend_consistency = (recent_trend['ema_fast'] < recent_trend['ema_slow']).sum() / 3 confidence_factors.append(trend_consistency) # 4. Factor de volumen if 'volume_ratio' in current: volume_facto...
Python
1
kOut.entryTerm, ",", sep="") print(" \"closeTerm\" : ", channelBreakOut.closeTerm, ",", sep="") if channelBreakOut.rangePercent is None: print(" \"rangePercent\" : ", "null,", sep="") else: print(" \"rangePercent\" : ", channelBreakOut.rangePercent, ",", sep="") if channelBreakO...
Python
1
lvals.append(np.linalg.norm(dWdftmodule - dWdftauto)) tolstrs.append(f"gradient of W w.r.t. f_{t}") ####################################################################### # Ultimate final report ####################################################################### print(" ") print(72 * "*") # 72 columns in ho...
Python
1
# 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
j,k) = F_ij(i,j,k)`. (in turn implying that `F_CH == F_HC`) // // We will assume he meant the latter, stronger condition, based on the following: // // * Stuart is more explicit and says `F_ij(i,j,k) = F_ij(j,i,k)` // * The LAMMPS implementation does it this way. // * All...
Rust
0
e. pub threshold: WeightOrRatio, } impl Default for VotePolicy { fn default() -> Self { VotePolicy { weight_kind: WeightKind::RoleWeight, quorum: U128(0), threshold: WeightOrRatio::Ratio(1, 2), } } } /// Defines voting / decision making policy of this DA...
Rust
0
mpress ed25519 Edwards Point".into()).into(), ); } }; let res = xDalekPublicKey::from(ep.to_montgomery().to_bytes()); Ok(res) } } impl TryFrom<&SecretKey> for SlatepackAddress { type Error = Error; fn try_from(key: &SecretKey) -> Result<Self, Self::Error> { let d_skey = match edDalekSecretKey::from_b...
Rust
0
# -*- coding: utf-8 -*- # # Copyright 2025 Google LLC. 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 requir...
Python
1
["hammerhead, hammerhead shark"], "shrew": [], "skunk": ["skunk, polecat, wood pussy"], "skyscraper": [], "snail": ["snail"], "snake": ["sea snake"], "spider": [ "barn spider, Araneus cavaticus", "black and gold garden spider, Argiope aurantia", "black widow, Latrodectus...
Python
1
e adjusted to {n}" ) self.n_dim = n logits = self._get_logits(features) log.info("Computing principal space ...") # calculate eigenvectors of the covariance matrix ec = EmpiricalCovariance(assume_centered=True) ec.fit(features - self.u) eig_vals,...
Python
1
t) if HIDE_OUTPUT: print_table(results, by_levels=False, single_field=None) if warnings: print("Warnings: ") print("\n".join(warnings)) print("You can run again to see if it is noise, or consistent.") if errors: print("Errors: ") print("\n".join(errors)) print( """If you expect yo...
Python
1
flag types #[derive(Debug, PartialEq)] pub enum Type { Str, Int, Float, Bool, FileIn, FileOut, Path, None, Arr(Box<Type>), Error, } impl Default for Type { fn default() -> Type { Type::None } } impl Type { pub fn from_name(s: &str) -> Result<Type> { match s { ...
Rust
0
4 => CurlExerciseName::BarbellReverseWristCurl, 5 => CurlExerciseName::BarbellWristCurl, 6 => CurlExerciseName::BehindTheBackBarbellReverseWristCurl, 7 => CurlExerciseName::BehindTheBackOneArmCableCurl, 8 => CurlExerciseName::CableBicepsCurl, ...
Rust
0
("A.123.a.X"); assert_eq!(is_ipv4, false); } #[test] fn test_inet6_aton() { let cases = vec![ ( Datum::Bytes(b"0.0.0.0".to_vec()), Datum::Bytes(vec![0x00, 0x00, 0x00, 0x00]), ), ( Datum::Bytes(b"10.0.5.9".to...
Rust
0
a_turn_strategy(90, 38, cutoff=12, num_rolls=5) 0 """, 'hidden': False, 'locked': False, 'multiline': False }, { 'code': r""" >>> extra_turn_strategy(35, 51, cutoff=7, num_rolls=4) 0 """, 'hidden': False,...
Python
1
#poner en pantalla un mensaje print('bienvenido waza') #solicita el primer numero numero_1 = int(input('digite el primer numero: ')) #solicita el segundo numero numero_2 = int(input('digite el segundo numero: ')) #multiplicamo los numero resultado = numero_1 * numero_2 print(f'el resultado de la multiplicacion es {...
Python
1
acts { fn as_ref(&self) -> &Vec<Fragment> { &self.0 } } impl AsMut<Vec<Fragment>> for Contacts { fn as_mut(&mut self) -> &mut Vec<Fragment> { &mut self.0 } } impl Contacts { pub(crate) fn new(fragment: Fragment) -> Self { Contacts(vec![fragment]) } /// Check if any...
Rust
0
impl ::core::clone::Clone for UiInfo_0 { fn clone(&self) -> Self { *self } } <gh_stars>1-10 use crate::identifiers::build_unnamed_idents; use syn::parse_quote; use syn::Expr; use syn::Fields; use syn::Ident; use syn::ItemStruct; use syn::Variant; pub fn build_struct_constructor(input_struct: &ItemStru...
Rust
0
} } } /// The information about the database see DBREF documentation wwPDB v3.30 <https://www.wwpdb.org/documentation/file-format-content/format33/sect3.html#DBREF> #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)] pub struc...
Rust
0
from typing import List, Tuple from transformers import pipeline # type: ignore class Scorer: ''' Class for creating more interpritable scores ''' def __init__( self, device: str='cpu', batch_size: int=8 ) -> None: """ Args: device (str, optional): Device. Defau...
Python
1
on { required: ["spec".to_string()].into(), properties: [( "spec".to_string(), Schema::Object(SchemaObject { instance_type: Some(InstanceType::Object.into()), object: Some(Box::new(ObjectValidation { ...
Rust
0
#!/usr/bin/env python3 import os import sys import re if len(sys.argv) < 2: print('you must supply an input file') quit() variables = {} chr = 0 source = '' with open(sys.argv[1]) as file: source = file.read() def squeeze(): global chr while chr < len(source) and source[chr] in [' ', '\t', '\n']: chr += 1 ...
Python
1
from fastapi import APIRouter, Depends, HTTPException from starlette.requests import Request from starlette.status import HTTP_409_CONFLICT from rearq import CronTask, ReArq from rearq.server import templates from rearq.server.depends import get_rearq from rearq.server.models import JobResult from rearq.server.schemas...
Python
1
dxschafe0': '["Objects"]["1169592956.59sdnaik"]["Objects"]["1193084928.0dxschafe0"]','1193085056.0dxschafe': '["Objects"]["1169592956.59sdnaik"]["Objects"]["1193085056.0dxschafe"]','1193085056.0dxschafe0': '["Objects"]["1169592956.59sdnaik"]["Objects"]["1193085056.0dxschafe0"]','1193085056.0dxschafe1': '["Objects"]["11...
Python
1
ize("checkpoint_activation", [True, False]) @pytest.mark.parametrize("num_microbatches", [1, 5]) @pytest.mark.parametrize("use_auto_shard", [True, False]) def test_correctness(use_fp16, checkpoint_activation, num_microbatches, use_auto_shard): pytest.skip("skip this test until the issue #900 is resolved.") if u...
Python
1
32) -> Val { unimplemented!("Table::get") } pub fn set(&self, _index: u32, _val: &Val) -> usize { unimplemented!("Table::set") } pub fn size(&self) -> u32 { unimplemented!("Table::size") } pub fn grow(&mut self, _delta: u32) -> bool { unimplemented!("Table::gro...
Rust
0
from langchain.prompts import PromptTemplate # Emotional interpretation prompt emotional_prompt = PromptTemplate.from_template( """ You are an expert dream interpreter focused on emotional meaning. Dream: "{dream_text}" Symbols in the dream: {symbols} User's mood: {user_mood} Interpret the dream from an emotion...
Python
1
ut self, cx: f32, cy: f32, zoom: f32) { // Apply the zoom self.center_x = cx; self.center_y = cy; self.zoom = zoom.max(1.0); // Clamp to make sure camera doesn't go out of bounds self.center_x = self .center_x .min(self.width * (1.0 - 0.5 / self.z...
Rust
0
for method_name, description in test_cases: print(f"\n{description}:") print(f"Method: {method_name}") result = extractor.extract(test_file, "TestClass", method_name) print(f"Status: {result.status}") if result.status == "su...
Python
1
file.functions.push(nl_func); } RootDeceleration::Enum(nl_enum) => { file.enums.push(nl_enum); } } } Ok((input, file)) } else { Ok((input, file)) } } pub fn parse_string<'a>(input: &'a s...
Rust
0
: Vec<EmissionKind>, /// The output directory #[structopt(default_value = "build")] pub out_dir: PathBuf, /// Silence all compiler output #[structopt(short = "q", long = "quiet")] pub quiet: bool, /// Set the colors of terminal output #[structopt(long = "color", default_value = "auto"...
Rust
0
es(), 2), ("b".as_bytes(), 3), ("bcd".as_bytes(), 4), ]; // build a double-array trie binary let da_bytes = DoubleArrayBuilder::build(keyset); assert!(da_bytes.is_some()); // create a double-array trie instance let da = DoubleArray::new(da_bytes.unwrap()); // save to file ...
Rust
0
peated" } fn len_field(&self, m: &TestTypes) -> uint { m.get_string_repeated().len() } fn get_rep_str<'a>(&self, m: &'a TestTypes) -> &'a [::std::string::String] { m.get_string_repeated() } } #[allow(non_camel_case_types)] struct TestTypes_bytes_repeated_acc_type; static TestTypes...
Rust
0
#Los productos en oferta de una tienda de informática se guardan una cadena como la de más abajo, donde cada línea (separadas por el carácter de cambio de línea ‘\n’) contiene el nombre del producto, el número de unidades en stock, el precio (en €) y el descuento que tiene (en porcentaje), separados por punto y coma. ...
Python
1
#Importação das bibliotecas from flask import Blueprint #Importação dos controladores from controladores.administrador.controlador_administrador_atualizar_produto import administrador_atualizar_produto from controladores.administrador.controlador_administrador_cadastrar_mesa import administrador_cadastrar_mesa from co...
Python
1
# This file is part of Dictdiffer. # # Copyright (C) 2015 CERN. # # Dictdiffer is free software; you can redistribute it and/or modify # it under the terms of the MIT License; see LICENSE file for more # details. import unittest from dictdiffer.conflict import Conflict, ConflictFinder class ConflictTest(unittest.Te...
Python
1
{ let dir = PathBuf::from(dir); rf::set_save_ref_dir(dir); Ok(()) } #[pyfunction] pub fn apply_ref(key: &str) -> PyResult<()> { Ok(rf::apply_ref(Path::new(key))?) } #[pyfunction] pub fn apply_all_new_refs() -> PyResult<()> { Ok(rf::apply_all_new_refs()?) } #[pyfunction] pub fn apply_all_changed_...
Rust
0
<Term<'src>>), Match( Span<'src>, Rc<Term<'src>>, Vec<(Rc<Pattern<'src>>, Rc<Term<'src>>)>, ), Id(Span<'src>, &'src str), Lambda( Span<'src>, Rc<Pattern<'src>>, Option<Rc<Type<'src>>>, Rc<Term<'src>>, ), Let( Span<'src>, Rc<...
Rust
0
adj = [] visited = [] num = 0 def dfs(v): global adj, visited, num visited[v] = True num += 1 for i in range(len(adj[v])): if not visited[adj[v][i]]: dfs(adj[v][i]) def numberOfPairs(N, arr): global adj, visited, num adj = [] for i in range(N): adj.append([]) ...
Python
1
# Copyright (c) Mathias Kaerlev 2012. # This file is part of Anaconda. # Anaconda is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # ...
Python
1
全检测', 'code', '(webscan.360.cn/status/pai/hash)'], ['H3C ER5200G2', 'code', '(ER5200G2系统管理)'], ['华为(HUAWEI)安全设备', 'code', '(sweb-lib/resource/)'], ['H3C ER6300', 'code', '(ER6300系统管理)'], ['华为_HUAWEI_ASG2100', 'code', '(HUAWEI ASG2100)'], ['TP-Link 3600 DD-WRT', 'code', '(TP-Link 3600 DD-WRT)'], ...
Python
1
that is assigned to ALL output fn foo<'a>(x: &'a i32) -> &'a i32 3. if multiple input, BUT ONE is &self or &mut self - as in method - self is assigned to ALL OUTPUT lifetime (sugar on method) Applying on first_word: fn first_word(s: &str) -> &str Rule 1 -> fn first_word<'a>(s:...
Rust
0
def exec21(): massa= float(input("Insira a massa da amostra de carbono: ")) num_mols= massa/12 print(f"O número de mols de carbona na amostra é: {num_mols}") if __name__== '__main__': exec21()
Python
1
import os from unittest.mock import Mock, patch import pytest from core.config.app_config import AppConfig from core.logger.logger import Logger @pytest.fixture def mock_logger() -> Logger: return Mock(Logger) @pytest.fixture def app_config() -> AppConfig: return AppConfig() def test_initialize(app_conf...
Python
1
move_selection_up: map_keybindings(&key_bindings.move_selection_up), move_up: map_keybindings(&key_bindings.move_up), move_up_step: map_keybindings(&key_bindings.move_up_step), open_in_external_editor: map_keybindings(&key_bindings.open_in_external_editor), rebase: map_keybindings(&key_bindings.rebase), ...
Rust
0
tml) //! instance, which when [Drop](struct.Registered.html#impl-Drop)-ed causes the callback to be //! de-registered using the provided function. //! * In case the [Registered](struct.Registered.html) instance is not //! [Drop](struct.Registered.html#impl-Drop)-ed, for example by calling `std::mem::forget` //! ...
Rust
0
/// assert_relative_eq!(q * a, b); /// assert_relative_eq!(q.inverse() * b, a); /// ``` #[inline] pub fn rotation_between<SB, SC>(a: &Vector<N, U3, SB>, b: &Vector<N, U3, SC>) -> Option<Self> where SB: Storage<N, U3>, SC: Storage<N, U3>, { Self::scaled_rotation_betwe...
Rust
0
mage\n -f, --force Remove existing image before build\n -m, --missing Build only missing image\n -s, --skip-redownload If binary is present, don't check if new version is available"); } #[test] fn build_unknow_option() { let io_helper: &TestInputOutputHelper = &TestInputOu...
Rust
0
3, 3) layers = [ nn.utils.spectral_norm(ops.Conv2d(c_in, c_hidden // (2 ** d), kernel_size=3, stride=2, padding=1)), nn.LeakyReLU(0.2), ] for i in range(depth - 1): c_in = c_hidden // (2 ** max((d - i), 0)) c_out = c_hidden // (2 ** max((d - 1 - i...
Python
1