text
string
label_name
string
labels
int64
from pathlib import Path from .generic_eval import main from .safe_subprocess import run LANG_NAME = "C++" LANG_EXT = ".cpp" def eval_script(path: Path): basename = ".".join(str(path).split(".")[:-1]) build_result = run(["g++", path, "-o", basename, "-std=c++17"]) if build_result.exit_code != 0: ...
Python
1
let expr = FloatExpr::<f32>::from_iter(tokens).unwrap(); assert_eq!(expr.evaluate(), Ok(7.0)); } #[test] fn simple_substraction() { let expr_str = "4 3 -"; let tokens = expr_str.split_whitespace(); let expr = FloatExpr::<f32>::from_iter(tokens).unwrap(); asse...
Rust
0
ke_paint(darkgray); ctx.global_composite_operation(CompositeOperation::Basic(BasicCompositeOperation::SrcOver)); ctx.fill_paint(Gradient::Radial { center: origin.into(), in_radius: 0.0, out_radius: boss_rad, inner_color: silver, outer_color: da...
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...
Python
1
# Figure 7.8, page 384. # Chernoff lower bound. from cvxopt import matrix, mul, exp, normal, solvers, blas #solvers.options['show_progress'] = False # Extreme points and inequality description of Voronoi region around # first symbol (at the origin). m = 6 V = matrix([ 1.0, 1.0, -1.0, 2.0, ...
Python
1
Get the key associated with the entry pub fn key(&self) -> &K { if let Some(node) = self.map.get_node(&self.key) { &node.key } else { &self.key } } /// Insert a value if the entry does not already exist in the map /// and call a continuation /// /...
Rust
0
smithy_client::bounds::SmithyMiddleware<C>, R: aws_smithy_client::retry::NewRequestPolicy, { /// Creates a new `ListAvailableZones`. pub(crate) fn new(handle: std::sync::Arc<super::Handle<C, M, R>>) -> Self { Self { handle, inner: Default::default(...
Rust
0
import os import shutil import zipfile from celery import shared_task, Task, task from tika_tasks import create_index from django.conf import settings class UploadZipTask(Task): abstract = True def on_failure(self, *args, **kwargs): """If there is an error, set the index status to UPLOAD FAILURE."...
Python
1
oo".to_owned()).unwrap(), Some(ByteBuf::from(v1)) ); let c2 = h2.flush().unwrap(); assert_eq!( hex::encode(c2.to_bytes()), "0171a0e4022017a2dc44939d3b74b086cd78dd927edbf20c81d39c576bdc4fc48931b2f2b117" ); } #[test] #[cfg(not(feature = "identity-hash"))] fn reload_empty() { ...
Rust
0
with the mapping established expect_da = "2001:db8::69" expect_sa = test.public_ipv4_xlate expect_data = randbytes(128) expect_len = 128 rt = router(f"169.254.0.0/16") rt.apply() send_pkt = IP(dst=str("169.254.0.80"),src=str(test.public_ipv4),proto=16) / Raw(expect_data) test.send_and_ch...
Python
1
LButtonUp, /// [`WM_LBUTTONUP`](https://docs.microsoft.com/en-us/windows/win32/inputdev/wm-lbuttonup) /// message. } fn_wm_withparm_noret! { wm_m_button_dbl_clk, co::WM::MBUTTONDBLCLK, wm::MButtonDblClk, /// [`WM_MBUTTONDBLCLK`](https://docs.microsoft.com/en-us/windows/win32/inputdev/wm-mbuttondblclk) ...
Rust
0
larity([a], [b]) @staticmethod def _euclidean_distance(a: np.ndarray, b: np.ndarray) -> np.floating: """Compute the Euclidean distance between two vectors. Args: a (np.ndarray): The first vector. b (np.ndarray): The second vector. Returns: np.floati...
Python
1
plane): {goal}') # adjustable (but requires recalibration or math) initial_pose = np.array([0, 0, np.pi/2]) # print(f'goal is: {goal} and initial pose is: {initial_pose}') opt = robot.optimize(initial_pose, goal) # print(opt) ...
Python
1
i32 { self.count } } // compile-flags: -C opt-level=0 use std::env; fn main() { let x = env::args().count(); let mut res = 42; if x > 4 { res = 100; } println!("res: {}", res); } // END RUST SOURCE // bb0: <gh_stars>0 pub fn find_saddle_points(input: &[Vec<u64>]) -> Vec<(...
Rust
0
let label: *mut Object = msg_send![label, initWithFrame: warning_frame]; let colour = gui::colours::get(gui::colours::ORANGE, 1.); let font = gui::get_font("HelveticaNeue-Bold", WARNING_LBL_FONT_SIZE); let _: () = msg_send![label, setTextColor: colour]; let _: () = ...
Rust
0
:vec::Vec<Result<ast::Function<LocationMeta>, Vec<FrontendError<LocationMeta>>>>, usize), __7: (usize, &'input str, usize), ) -> ast::TopDefKind<LocationMeta> { let __start0 = __0.0.clone(); let __end0 = __0.0.clone(); let __temp0 = __action111( errors, input, &__start0, ...
Rust
0
import re import sys sys.path.append("..") def process(responses:str, aspect): #把所有中文冒号替换为英文冒号 responses = responses.replace(":", ":") responses = responses.split("####")[1:] assert len(responses) == 4 annotation = [] try: if aspect in ["instruction_following", "honesty"]: ...
Python
1
its parent (the task that spawned it), unless this parent is the root task. //! //! The root task can also wait on the completion of the child task; a call to [`spawn`] produces a //! [`JoinHandle`], which implements `Future` and can be `await`ed: //! //! ``` //! use async_std::task; //! //! # async_std::task::block_o...
Rust
0
# rospy.logdebug("-D- %s wheelCallback msg.data= %0.3f wheel_latest = %0.3f mult=%0.3f" % (self.nodename, enc, self.wheel_latest, self.wheel_mult)) ###################################################### def targetCallback(self, msg): #####################################################...
Python
1
12; const EVP_PKEY_CTRL_SCRYPT_MAXMEM_BYTES: c_int = EVP_PKEY_ALG_CTRL + 13; const EVP_PKEY_HKDEF_MODE_EXTRACT_AND_EXPAND: c_int = 0; const EVP_PKEY_HKDEF_MODE_EXTRACT_ONLY: c_int = 1; const EVP_PKEY_HKDEF_MODE_EXPAND_ONLY: c_int = 2; pub unsafe extern "C" fn EVP_PKEY_CTX_set_tls1_prf_md( pctx: *mut crate::EVP_PK...
Rust
0
ize, usize>, Vec<usize>), ) { // Arrange the input by all columns in order. let mut all_columns = Vec::new(); for column in 0..arity { all_columns.push(mz_expr::MirScalarExpr::Column(column)); } let (permutation, thinning) = permutation_for_arrangement(&all_column...
Rust
0
ct[str, Any]) -> bool: """Check if the object is a Kustomization.""" return obj.get("kind") == KUSTOMIZE_KIND and obj.get("apiVersion", "").startswith( KUSTOMIZE_DOMAIN ) def _strip_attrs(metadata: dict[str, Any], strip_attributes: list[str]) -> None: """Update the resource object, stripping a...
Python
1
tants' description. The returned macro is used by types conversions generator to initialize a enum description table (enum_properties_table) mapping enum names to a struct (EnumProperties) describing the enum properties, including the enum values. A typical output of get_constants() looks like the following - ...
Python
1
", "k1", "k2", "k3", "k4", "kernelMatrix", "kernelUnitLength", "kerning", "keyPoints", "keySplines", "keyTimes", "lang", "lengthAdjust", "letter-spacing", "lighting-color", "limitingConeAngle", "local", "marker-end", "marker-mid", "marker-start...
Rust
0
def compare_gas_prices(distance, price_of_gallon_of_gas): # MPG for Honda Pilot honda_pilot_mpg = 22 # Calculate gas consumption for Honda Pilot honda_pilot_gas_consumption = distance / honda_pilot_mpg # Calculate total cost for Honda Pilot honda_pilot_total_cost = honda_pilot_gas_consumption ...
Python
1
' => EndLoop, n => Comment(n.to_string()) } } pub fn parse_file(path: &Path) -> Vec<BFToken> { use self::BFToken::*; let mut toks = Vec::new(); let content = File::open(path).read_to_string().unwrap_or("".to_string()); for ch in content.chars() { ...
Rust
0
209, 154, 102), base0a: Colour::rgb(229, 192, 123), base0b: Colour::rgb(152, 195, 121), base0c: Colour::rgb(86, 182, 194), base0d: Colour::rgb(97, 175, 239), base0e: Colour::rgb(198, 120, 221), base0f: Colour::rgb(190, 80, 70), }; pub const MATERIAL: Base16Theme = Base16Theme { base00: Colo...
Rust
0
if updates.is_empty() { eprintln!("Destination already matches source. No updates needed."); return Ok(ctx.get_ref().requeue_action()); } // Create the patch from the changes let patch = serde_json::to_vec(&serde_json::json!({ "data": updates })) ...
Rust
0
to Minute => 60 * 24 + 90, minutes); test!("1 01:30:40", Day to Second => (60 * 24 + 90) * 60 + 40, seconds); test!("3 02:30:40.1234", Day to Second => (((3 * 24 + 2) * 60 + 30) * 60 + 40) * 1_000_000 + 123_400, microseconds); test!("12:34", Hour to Minute => 12 * 60 + 34, minutes);...
Rust
0
ead-local state. let malloc = find_wbindgen_malloc(module)?; body.i32_const(tls.size as i32) .i32_const(tls.align as i32) .drop() // TODO: need to actually respect alignment .call(malloc) .call(tls.init); // Finish off our newly generated function. let id = builder.finis...
Rust
0
}, "mz_sleep" => Scalar { params!(Float64) => UnaryFunc::Sleep(func::Sleep), oid::FUNC_MZ_SLEEP_OID; } } }; } fn plan_current_timestamp(ecx: &ExprContext, name: &str) -> Result<HirScalarExpr, anyhow::Error> { match ecx.qcx.lifetime { QueryLife...
Rust
0
BLTARITHSTRETCHYN: i32 = 16i32; #[doc = "*Required features: `\"Win32_Graphics_DirectDraw\"`*"] pub const DDFXCAPS_BLTFILTER: i32 = 32i32; #[doc = "*Required features: `\"Win32_Graphics_DirectDraw\"`*"] pub const DDFXCAPS_BLTMIRRORLEFTRIGHT: i32 = 64i32; #[doc = "*Required features: `\"Win32_Graphics_DirectDraw\"`*"] p...
Rust
0
(opcode), opcode & 0x000F), (0xE, 9) => OpCode::KeyPressedX(extract_x(opcode)), (0xE, 1) => OpCode::KeyNotPressedX(extract_x(opcode)), (0xF, _) => { let sub_group = (opcode & 0x00F0) >> 4; match (sub_group, selector) { (0, 7) => OpCode::TimerX(extract_x(op...
Rust
0
# Pyrofork - Telegram MTProto API Client Library for Python # Copyright (C) 2017-present Dan <https://github.com/delivrance> # Copyright (C) 2022-present Mayuri-Chan <https://github.com/Mayuri-Chan> # # This file is part of Pyrofork. # # Pyrofork is free software: you can redistribute it and/or modify # it under ...
Python
1
} #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 30)) | ((value as u...
Rust
0
not include any extras from step halving. n_iter += 1; n_steps += it_result.steps; } Ok(Fit::new( &model.data, model.use_intercept, result, options, model_like, n_iter, n_steps, )) }...
Rust
0
_ => Ok(ObjectSyntax::UnknownSimple(BerObject::from_obj(x))) as Result<_,u32>, } } ) } }, Err(e) => Err(e) } } #[inline] fn parse_varbind(i:&[u8]) -> IRe...
Rust
0
import numpy as np import cv2 as cv class Histogram(): def __init__(self) -> None: pass def equalize(self, image: np.ndarray) -> np.ndarray: """ Equalize the histogram of the image. This function will be used to equalize the histogram of the image. We use the Contr...
Python
1
ip] fn cross_module_call_twice() -> Result<()> { let callee_modname = "tests/bcfiles/call.bc"; let caller_modname = "tests/bcfiles/crossmod.bc"; let funcname = "cross_module_twice_caller"; init_logging(); let proj = Project::from_bc_paths(&[callee_modname, caller_modname]) ...
Rust
0
# -*- encoding:utf-8 -*- """本地缓存监测模块""" from __future__ import print_function from __future__ import absolute_import from __future__ import division import os import logging import math from ..UtilBu import ABuFileUtil from ..CoreBu import ABuEnv from ..CoreBu.ABuEnv import EDataCacheType, EMarketTargetType, EMarket...
Python
1
# -*- coding: utf-8 -*- import timeit import numpy as np from PIL import Image from skimage.feature import greycomatrix class CoMatrix(): ''' Co-occurrence matrix class ''' def __init__(self, dx, dy): ''' Initialize the class. Set non-negative distance between neighbours ''' if dx < 0 or dy < 0...
Python
1
private_prefix: 0xb0, xpub_prefix: [0x04, 0x88, 0xB2, 0x1E], xprv_prefix: [0x04, 0x88, 0xAD, 0xE4], }); networks.push(BtcForkNetwork { coin: "LITECOIN", network: "MAINNET", seg_wit: "P2WPKH", hrp: "", p2pkh_prefi...
Rust
0
""" file organization style - defillama__yields_per_pool__uniswap_v2__2025-01-01--01-01-02.000.parquet - defillama__fees_per_chain__solana__2025-01-01--01-01-02.parquet ^ timestamp in filename is time that file was collected or last timesatmp in file? """ from __future__ import annotations import typing default_roo...
Python
1
" @brief Function for indicating that message is in use."] #[doc = ""] #[doc = " @details Message can be used (read) by multiple users. Internal reference"] #[doc = " counter is atomically increased. See @ref log_msg_put."] #[doc = ""] #[doc = " @param msg Message."] pub fn log_msg_...
Rust
0
""" The ECB provider."""
Python
1
class person(): nl = 12 person.nl = 22 ren = person() ren.nl = 12 print(ren.nl)
Python
1
:<Vec<_>>(), ))) } } HoconValue::EmptyObject => Ok(Node::Node { children: vec![], key_hint: Some(KeyType::String), }), HoconValue::EmptyArray => Ok(Node::Node { children: vec![], ...
Rust
0
from plotly.graph_objs import Scatterternary
Python
1
parser. #[derive(Copy, Clone, Eq, PartialEq, Debug)] pub enum StringKind { Standard, Multiline, } /// Distinguish between a normal case `id => exp` and a default case `_ => exp`. #[derive(Clone, Debug)] pub enum SwitchCase { Normal(Ident, RichTerm), Default(RichTerm), } /// Make a span from parser byt...
Rust
0
_string()).collect(); dest.write_str(&values.join(" ")) }, } } } #[derive(Clone, Debug)] pub struct GenericCounter<I> { name: CustomIdent, value: Option<I>, } impl<I> GenericCounter<I> { pub fn parse_with<'i, 't, F>(input: &mut Parser<'i, 't>, item_parser: F) -> Result<Self, ParseError<'i>> where F: F...
Rust
0
true), (7, false), (11, false)]; for (n, expected) in cases { assert_eq!(has_alternating_bits(n), expected); } } use super::*; #[allow(unreachable_pub)] // https://github.com/rust-lang/rust/issues/57411 pub use crate::{ ast_enum::{FnArg, ForeignItem, ImplItem, Item, TraitItem, UseTree}, ast_str...
Rust
0
import cozmo from cozmo.util import degrees, distance_mm, speed_mmps import time import sys import os # GLOBALS imageNumber = 0 directory = '.' liveCamera = False def on_new_camera_image(evt, **kwargs): global liveCamera if liveCamera: pilImage = kwargs['image'].raw_image global directory ...
Python
1
坐标系中) best_y = best_idx // num_w best_x = best_idx % num_w # 转换为40x40 ROI内的坐标(加上half_window偏移) best_local_center = (best_x + half_window, best_y + half_window) # 步骤3: 将局部坐标转换为全局坐标 global_x = roi_x1 + best_local_center[0] global_y = roi_y1 + best_...
Python
1
# Copyright 2023 Google LLC # # 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 applicable law or agreed to in writing, ...
Python
1
# digit1 = int(input("digit1: ")) # digit2 = int(input("digit2: ")) # op = input("enter the operator(+,-,*,/,//,%): ") # if op == '+': # print(digit1+digit2) # elif op == '-': # print(digit1-digit2) # elif op == '*': # print(digit1*digit2) # elif op == '/': # print(digit1/digit2) # elif op == '%': # ...
Python
1
ore digits we don't need. if discard_digits > 0 { discard_digits -= 1; exp += 1; continue; } // Drop trailing zeros. if in_trail && digit == 0 { exp += 1; } else { in_trail = fals...
Rust
0
while True: try: nombre = input("Escribe tu nombre: ") if nombre == "": raise ValueError("El nombre no puede estar vacío") print("Hola, " + nombre + "!") break except ValueError as e: print("Error:", e, "Intenta de nuevo.")
Python
1
,tp} } /// Behavior link constructor. pub fn behavior<T:HasId>(t:&T) -> Link { let source = t.id(); let tp = LinkType::Behavior; Self {source,tp} } /// Mixed link constructor. pub fn mixed<T:HasId>(t:&T) -> Link { let source = t.id(); let tp = Li...
Rust
0
ensure_is_valid_migration_msg(&deps, info, &wallet_info, &wallet_addr, migration_msg)?; // Further checks applied to ensure user has signed the correct relay msg / tx if let CosmosMsg::Wasm(WasmMsg::Migrate { contract_addr, new_code_id, msg, }) = tx_msg.clone() { ...
Rust
0
should be a `columns=` parameter to this. assert_series_equal( pl.Series([r'{"a": 1}', r'{"a": 2, "b": 2}']).str.json_decode( dtype=pl.Struct({"a": pl.Int64}) ), pl.Series([{"a": 1}, {"a": 2}]), ) def test_escape_regex() -> None: df = pl.DataFrame({"text": ["abc", "def...
Python
1
elf.exchange_B}"] + [ f" Quote Diff: {profitability_analysis['buy_a_sell_b']['quote_diff']:.7f}"] + [ f" Base Diff: {profitability_analysis['buy_a_sell_b']['base_diff']:.7f}"] + [ f" Percentage: {profitability_analysis['buy_a_sell_b']['profitability_pct'] *...
Python
1
static_dir, &chunk_dir).await { Ok(meta) => { info!("File {}.{} completed.", file_id, meta.extension); } Err(error) => return Ok(CompleteResult::Err { error }.into()), } Ok::<CompleteReply, Infallible>(CompleteResult::Ok.into()...
Rust
0
x.evaluate(self).value() { modulate::demodulate(&modulated) .expect("Could not demodulate") .1 } else { expr } } Neg => Num(-x.evaluate(self).n...
Rust
0
name>Eric-Arellano/rust // ignore-tidy-linelength // compile-flags:-Zprint-mono-items=eager #![deny(dead_code)] #![feature(start)] trait Trait : Sized { fn foo(self) -> Self { self } } impl Trait for u32 { fn foo(self) -> u32 { self } } impl Trait for char { } fn take_foo_once<T, F: FnOnce(T) -> T>(f: F, a...
Rust
0
conf_cleanup.get("max_cache_size_mb", 1024) if max_size_mb <= 0: continue max_size_bytes = max_size_mb * 1024 * 1024 total_size = sum(os.path.getsize(os.path.join(self.cache_dir, f)) for f in os.listdir(self.cache_dir) if os.path.isfile(os.path.join(self.cache_dir, f))) ...
Python
1
"""Run script for LOLA-DiCE on IPD.""" import click import tensorflow as tf from lola_dice.envs import IPD from lola_dice.policy import SimplePolicy, MLPPolicy, RecurrentPolicy from lola_dice.rpg import train @click.command() @click.option("--use-dice/--no-dice", default=True, help="Whether to use th...
Python
1
#!/usr/bin/python # coding=utf-8 import cv2 import datetime import sys def count_cameras_opencv(): num_cameras = 0 for i in range(10): temp_camera = cv2.VideoCapture(i-1) ret, _ = temp_camera.read() if ret: num_cameras += 1 return num_cameras def main(): # 0 CV...
Python
1
from fastapi import Request from fastapi.exceptions import RequestValidationError from fastapi.responses import JSONResponse async def custom_validation_exception_handler(request: Request, exc: RequestValidationError): for error in exc.errors(): if ( error.get("type") == "int_parsing" ...
Python
1
id: String, channel_id: String, pub activity_at: Option<NaiveDateTime>, } #[derive(Insertable)] #[table_name = "users"] pub struct NewUser<'a> { pub id: &'a str, pub username: &'a str, } #[derive(Insertable)] #[table_name = "channels"] pub struct NewChannel<'a> { pub id: &'a str, } #[derive(Inser...
Rust
0
.path.join(r'J:\AODinversion\辅助数据\筛选数据补\resample\nber\tco', strDate + '_tco3_resample.tif') # demPath = r"J:\机器学习测试文件\dem_tif\nber_dem_no_resample.tif" # if GetImageData.GetAODImgData(tifPath, tcwvPath, tcoPath, demPath) == None: # continue # else: # test_arr, tif_x, tif_...
Python
1
sactionsQueryParams { refresh: Option<bool>, id: Option<u32>, tx_id: Option<String>, } pub fn handle_retrieve_txs(state: &State, _body: &Chunk) -> Result<Response<Body>, Error> { trace_state(state); let &RetrieveTransactionsQueryParams { refresh, id, ref tx_id, } = Retri...
Rust
0
s=30, lw=0, alpha=0.5, color='black') ax2.scatter(tsne_results[:,0], tsne_results[:,1], s=30, lw=0, alpha=0.5, color='black') else: f...
Python
1
,check_status,check_code,check_duration,hrsp_1xx,hrsp_2xx,hrsp_3xx,hrsp_4xx,hrsp_5xx,hrsp_other,hanafail,req_rate,req_rate_max,req_tot,cli_abrt,srv_abrt, // HAProxy 1.5 // pxname,svname,qcur,qmax,scur,smax,slim,stot,bin,bout,dreq,dresp,ereq,econ,eresp,wretr,wredis,status,weight,act,bck,chkfail,chkdown,lastchg,downtime,...
Rust
0
""" Transport Manager for coordinating multiple transport engines. """ import asyncio import logging from pathlib import Path from typing import Dict, Any, Optional from citadel.config import Config from citadel.transport.engines.cli import CLITransportEngine logger = logging.getLogger(__name__) class TransportMan...
Python
1
class Solution: class TrieNode: def __init__(self): # Tracks how many times this substring appears in the Trie. self.frequency = 0 # Maps characters to their respective child nodes. self.child_nodes = {} def stringMatching(self, words: List[str]) -> List...
Python
1
let timeline = Timeline { tracks: vec![track], }; dmo_data.timeline = timeline; // result // ------ //dmo_data.context.build_index(false, false)?; Ok(dmo_data) } /// Ensures implicit builtins are included in the data. Skips them when /// al...
Rust
0
ng()), ) ); } // get the table handle from table_ref emitln!( ctx.writer, "let table_handle := {}", gen.parent.call_builtin_str( ctx, YulFunction::LoadU256, std::iter::once("table_ref".to_string()), ) ); // cre...
Rust
0
DataTransferStats( file_size_mb=size_mb, upload=Stats(min=0, max=0, mean=0, stddev=0, p50=0, p95=0, p99=0), download=Stats(min=0, max=0, mean=0, stddev=0, p50=0, p95=0, p99=0), total_runs=0, successful_runs=0, ) monkeypatch.setattr("syftbox.client...
Python
1
from math import dist def gorod(cluster): dists = [] for dot1 in cluster: sumd = 0 for dot2 in cluster: sumd += dist(dot1, dot2) dists.append([sumd, dot1]) return min(dists)[1] with open('txt/27_A_18884.txt') as file: data = [list(map(int, i.split())) for i in file]...
Python
1
match basket_service.get_product_with_count_one( listing_id.to_string(), user_id.to_string(), ) { Ok(option) => match option { Some(_document) => match basket_service.remove_product(listing_id, user_id) { Ok(_update) => Ok("Product is removed successfuly".to_string()), Err(e) => {...
Rust
0
mpressed_shards = [ Sparse24BitMaskTensor( shape=(expected_shape["bitmask"][0], expected_shape["bitmask"][1] * 8), compressed=shard_values, bitmask=shard_bitmask, ).decompress() for shard_values, shard_bitmask, expected_shape in zip( sharded_compre...
Python
1
# Copyright 2024 Databricks # SPDX-License-Identifier: Apache-2.0 from typing import Union from . import glu, mlp from .arguments import Arguments MlpType = Union[mlp.SparseMLP, glu.SparseGLU] _REGISTRY = { 'mlp': { 'grouped': mlp.GroupedMLP, 'sparse': mlp.SparseMLP, }, 'glu': { ...
Python
1
newalCertificate = *mut ::core::ffi::c_void; pub type IX509Attributes = *mut ::core::ffi::c_void; pub type IX509CertificateRequest = *mut ::core::ffi::c_void; pub type IX509CertificateRequestCertificate = *mut ::core::ffi::c_void; pub type IX509CertificateRequestCertificate2 = *mut ::core::ffi::c_void; pub type IX509Ce...
Rust
0
e registered for "eh" in a given era }) ); assert!(result.is_err()); } #[test] fn test_eras_complete_eagerly() { let mut e = Expectations::new(); // Expectations e.expect::<(), ()>("c").called_any(); e.then(); e.expect::<(), ()>("d").call...
Rust
0
::from_micros(event.srtt.into()), retx: event.retx, }; trace!("{:?}", record); sink.send(record)?; }; } Ok(()) } #[cfg(target_arch = "aarch64")] const BYTECODE: &[u8] = include_bytes!("../bpf/bytecode.arm64.o"); #[cfg(target_arch = "x86_64")] c...
Rust
0
import socket #Import socket library for network communication def start_client(): client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #Create a TCP/IP socket server_ip = input("Enter the server IP address: ") #Prompt for the server IP address server_port = int(input("Enter the server po...
Python
1
whose elements are the elements of trapResult. // 19. For each element key of targetNonconfigurableKeys, do for key in target_nonconfigurable_keys { // a. If key is not an element of uncheckedResultKeys, throw a TypeError exception. // b. Remove key from uncheckedResultKeys. if !uncheck...
Rust
0
#!/usr/bin/env python # Copyright (C) 2015-2021 Swift Navigation Inc. # Contact: https://support.swiftnav.com # # This source is subject to the license found in the file 'LICENSE' which must # be distributed together with this source. All other rights reserved. # # THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT ...
Python
1
_interfaces.append("FTDI") elif each_type == 'UART': list_interfaces.append("UART") elif each_type == 'GPIO': list_interfaces.append("GPIO") elif each_type == 'PYTHON': ...
Python
1
criar os modelos def cria_modelos(): modelo_1 = KNeighborsClassifier(n_neighbors = N_NEIGHBORS) modelo_2 = RandomForestClassifier(random_state = RANDOM_STATE) modelo_3 = LogisticRegressionCV(cv = CV, random_state = RANDOM_STATE) modelos = [("KNN", modelo_1), ("RandomForest", modelo_2), ("LogReg", mod...
Python
1
DCDC_MINPWR_HALF_FETS"] #[inline(always)] pub fn dcdc_minpwr_half_fets(&self) -> DCDC_MINPWR_HALF_FETS_R { DCDC_MINPWR_HALF_FETS_R::new(((self.bits >> 27) & 0x01) != 0) } #[doc = "Bit 30 - DCDC_VDD1P2CTRL_DISABLE_STEP"] #[inline(always)] pub fn dcdc_vdd1p2ctrl_disable_step(&self) -> DCDC_VDD1P2CTRL_DISA...
Rust
0
character_being_worked_on($globals:expr, $k:expr, $bc:expr) { ($k + $bc - $globals.fmem_ptr.get()) as crate::section_0113::quarterword } // @<Check for charlist cycle@>= pub(crate) macro Check_for_charlist_cycle { ($globals:expr, $f:expr, $k:expr, $val:expr, $bc:expr, $ec:expr, $lbl_bad_tfm:lifetime) => {{ ...
Rust
0
# Copyright (C) 2021, 2023 Mitsubishi Electric Research Laboratories (MERL) # # SPDX-License-Identifier: AGPL-3.0-or-later import argparse from examples.config import get_config, get_config_argument from safety_rl.envs.engine_wrapper import EngineWrapper from safety_rl.path_planner.a_star_safety_gym import AStarSafet...
Python
1
r.encoding is None: yield from iterator return decoder = codecs.getincrementaldecoder(r.encoding)(errors="replace") for chunk in iterator: rv = decoder.decode(chunk) if rv: yield rv rv = decoder.decode(b"", final=True) if rv: yield rv def iter_slic...
Python
1
axis by an angle in degrees. pub fn rotate_z_deg(m: &Mat4, deg: f32) -> Mat4 { // Convert to radians. let rad = deg * ONE_DEG_IN_RAD; let mut m_r = Mat4::identity(); m_r.m[0] = f32::cos(rad); m_r.m[4] = -f32::sin(rad); m_r.m[1] = f32::sin(rad); m_r.m[5] = f32::cos(rad); m_r * m ...
Rust
0
.collect::<Result<Vec<String>, _>>()?; let terms: Vec<Vec<T>> = v.iter().map(|x| parse_terms(x)).collect(); println!("{}", solve1(&terms)); println!("{}", solve2(&terms)); Ok(()) } <gh_stars>0 use super::*; #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub(crate) struct DotRule { ...
Rust
0
rows = stmt.query_map(params_from_iter(params), |row| Ok(row.get(0)?))?; Ok(rows.map(|x| x.unwrap()).collect()) } fn get_blob_id(data: &[u8]) -> String { let mut hasher = Sha256::new(); hasher.update(data); hex::encode(hasher.finalize()) } pub fn add_blob(&self, data: ...
Rust
0
as TransferRust, TransferBuilder as TransferBuilderRust, TransferOutput as TransferOutputRust, }, }; use crate::{ types::{output_kind_enum_to_type, IndexationPayload, MessagePayload, OutputKind}, Result, }; use chrono::prelude::{DateTime, Utc}; use std::num::NonZeroU64; pub enum RemainderValueStrategy {...
Rust
0
import requests import json from pywebio.input import * from pywebio.output import * from pywebio.session import * def fun_fact(): clear() # put_html("<p><h2>Fun Fact Genrator</h2></p>") put_html("<p align = 'left'><h2><img src='https://icons.iconarchive.com/icons/icons8/windows-8/512/Messaging-Happy-icon...
Python
1
.0; profile_quiet.len()]; for y in linspace(-1.0, 1.0, config.grid_size) { profile_quiet.shift_into(y * equatorial_velocity, &mut ccf_shifted); let z_bound = sqrt(1.0 - y.powi(2)); if z_bound < std::f64::EPSILON { continue; } let limb_i...
Rust
0