text
string
label_name
string
labels
int64
class Solution: def numberGame(self, nums: list[int]) -> List[int]: arr = [] while nums: alice_min = min(nums) nums.remove(alice_min) bob_min = min(nums) nums.remove(bob_min) arr.append(bob_min) arr.append(alice_min) ret...
Python
1
ints and weights. It must be >= 1. Returns ------- x : ndarray 1-D ndarray containing the sample points. y : ndarray 1-D ndarray containing the weights. Notes ----- .. versionadded:: 1.7.0 The results have only been tested up to degree 100, higher degrees may be p...
Python
1
from astropy import units as u, constants as c from astropy.time import Time import numpy as np from pint.models import get_model, get_model_and_toas import pytest import os from io import StringIO from pinttestdata import datadir par1 = """ RAJ 17:48:04.53480592 0 0.00005548 DECJ -24:46:34.6586741...
Python
1
import os import sys music_tag_dir = os.path.join(os.path.dirname(__file__), '..') sys.path.append(os.path.join(music_tag_dir)) from music_tag import load_file sample_dir = os.path.join(music_tag_dir, 'sample') f = load_file(os.path.join(sample_dir, '440Hz.m4a')) # getting tags print('track title:', f['title']) as...
Python
1
ta'), ('typoscripthtmldata', 'TypoScriptHtmlData'), ('ucode', 'ucode'), ('ul4', 'UL4'), ('unicon', 'Unicon'), ('unixconfig', 'Unix/Linux config files'), ('urbiscript', 'UrbiScript'), ('urlencoded', 'urlencoded'), ('usd', 'USD'), ('vala', 'Vala'), ('vb.net', 'VB.net'), ('vbscript', 'VBScript'), ('vcl', 'VCL'), ('vclsnip...
Python
1
false }), // Assume that control characters aren't from actual typing and are instead generated by Ctrl + a printable character Codepoint(chr) if (chr as u32) > 0 && (chr as u32) < 27 && chr != '\t' && chr != '\n' && chr != '\u{8}' => return Ok(KeyPress { modifiers: C...
Rust
0
register_extra_symbolics except ModuleNotFoundError: raise NotImplementedError('please update mmcv to version>=v1.0.4') register_extra_symbolics(args.opset_version) cfg = Config.fromfile(args.config) if args.cfg_options is not None: cfg.merge_from_dict(args.cfg_options) if args.sha...
Python
1
x, y, radius, ball_id, ball_type = ball_data ball = (x, y, radius, ball_id) # Get the current state from ball_states current_state = self.ball_states.get(ball_id, "on_playfield") previous_state = self.previous_ball_states.get(ball_id, "on_playfield") ...
Python
1
import asyncio from typing import List from app.db import reserverDb from app.models.stay import Stay from app.services.quote_provider import QuoteProvider class AvailableStaysService: available_stays_offers: List[Stay] = [] keep_quote_loop_alive = True quote_loop_interval = 10 providers: List[str] =...
Python
1
_X_vector_double_X_double_Size_Size_const_vector_Point_X" => "+_weights", // 3.2 3.4 "cv_HOGDescriptor_detect_const_const__InputArrayX_vector_Point_X_vector_double_X_double_Size_Size_const_vector_Point_X" => "+_weights", // 4.x "cv_HOGDescriptor_setSvmDetector_vector_float_" => "+_vec", "cv_groupRectangles_vector_Re...
Rust
0
"""Tests for the YouTube integration.""" from collections.abc import AsyncGenerator import json from youtubeaio.models import YouTubeChannel, YouTubePlaylistItem, YouTubeSubscription from youtubeaio.types import AuthScope from tests.common import load_fixture class MockYouTube: """Service which returns mock ob...
Python
1
[doc = "Bits 0:1 - Port x configuration bits (y = 0..15)"] #[inline(always)] pub fn ospeedr0(&mut self) -> _OSPEEDR0W { _OSPEEDR0W { w: self } } } // Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/C...
Rust
0
// height as f64 - MARGIN as f64 - scale_y( element.1 as f64, 0.0, height_per_plot as f64, 0.0, y_max as f64 + subplot_gap ...
Rust
0
Kind::Other, "unable to get account id")); tracing::debug!(kid = ?kid, "account created"); kid } <filename>platform/terminus_cosim/terminus_cosim_tests/src/bin/trap/main.rs #![no_std] #![no_main] #![feature(asm)] extern crate platform; extern crate compiler_builtins; use platform::*; use riscv::register::{mcau...
Rust
0
<(), Self::Error>; } #[cfg(feature = "usb")] pub mod usb { use super::*; use usb_device::bus::{UsbBus, UsbBusAllocator}; use usb_device::device::UsbDevice; use usb_device::UsbError; use usbd_hid::descriptor::{KeyboardReport, SerializedDescriptor}; use usbd_hid::hid_class::HIDClass; pub str...
Rust
0
ox::new([self.0, self.1, self.2, self.3]) } pub fn create() -> Quaternion { Quaternion(0., 0., 0., 1.) } pub fn identity(out: &mut Quaternion) { out.0 = 0.; out.1 = 0.; out.2 = 0.; out.3 = 1.; } pub fn setAxisAngle(out: &mut Quaternion, axis: &Vector3, ...
Rust
0
Some(calc_encoder_output.hidden_state), calc_encoder_output.all_hidden_states, calc_encoder_output.all_attentions, ) } else { (None, None, None) }; let encoder_output = encoder_output.unwrap_or_else(|| ...
Rust
0
lygon(legged_model_type=legged_model_type), expected_foot_polygon, ) def test_add_legged_model_to_plant_and_finalize() -> None: for legged_model_type in LeggedModelType: # With parser. plant = MultibodyPlant(time_step=0.001) model = add_legged_model_to_plant_and_finalize( ...
Python
1
map.borrow_mut(); if skid_map.contains_key(hex_skid) { return Ok(&self.tas[skid_map[hex_skid]]); } Err(Error::Unrecognized) } fn get_trust_anchor_by_name(&'_ self, name: &'_ Name<'_>) -> Result<&PDVTrustAnchorChoice<'_>> { #[cfg(feature = "std")] let name_ma...
Rust
0
ue: &str) -> u128 { let mut id = [0 as u8; 16]; id.copy_from_slice(&Md5::new().chain(value).result()); u128::from_le_bytes(id) } const TYPE_DEFAULT_GRAPH_ID: u8 = 0; const TYPE_NAMED_NODE_ID: u8 = 1; const TYPE_BLANK_NODE_ID: u8 = 2; const TYPE_LANG_STRING_LITERAL_ID: u8 = 4; const TYPE_TYPED_LITERAL_ID: u...
Rust
0
anced[:, l, :] X_test_layer = X_test_balanced[:, l, :] # Build the classifier classifier, criterion, optimizer = build_classifier( emb_dim, num_labels, device ) # Train t...
Python
1
string(&x)).collect::<Vec<String>>(), vec![ ". . . . \n \ . . . .\n\ .W. . . \n \ . . . .\n\ . . . . \n \ . . . .\n\ . . . . \n \ . . . .\n", ". . . . \n \ . . . .\n\ . . . . \n \ . . . .\n\ .W. . . \n \ . . . .\n\ . . . . \n \ . ....
Rust
0
"""The Coordinator for EnergyZero.""" from __future__ import annotations from datetime import timedelta from typing import NamedTuple from energyzero import ( Electricity, EnergyZero, EnergyZeroConnectionError, EnergyZeroNoDataError, Gas, ) from homeassistant.config_entries import ConfigEntry fro...
Python
1
extures) - 1), metallicFactor=0, roughnessFactor=1), alphaMode=pygltflib.OPAQUE) mat.extensions = { 'KHR_materials_unlit': {} } materials += [mat] gltf = pygltflib.GLTF2( scene=0, scenes=[pygltflib.Scene(nodes=[0])], nodes=[pygltflib.Node...
Python
1
from odoo import models, fields class ResConfigSettings(models.TransientModel): _inherit = 'res.config.settings' product_surcharge_id = fields.Many2one( related='company_id.product_surcharge_id', readonly=False, )
Python
1
crossing_point, start_angle, sweep_angle.signum() * consts::FRAC_PI_2, scaled_radii, x_axis_rotation, builder, ); if sweep_angle > 0.0 { sweep_angle -= consts::FRAC_PI_2; start_angle += consts::FRAC_PI_2; ...
Rust
0
self.w } } #[doc = "Secure mask for pin P0_2\n\nValue on reset: 1"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum PIO0_PIN2_SEC_MASK_A { #[doc = "0: Pin state is blocked to non-secure world."] BLOCKED = 0, #[doc = "1: Pin state is readable by non-secure world."] READABLE = 1, } impl From<PIO0_PI...
Rust
0
uld work but doesn't (model diverges) #Verror -= sketched_update # instead, zero out Verror with sketched_update.nonzero() nz = sketched_update.nonzero() Verror[nz[:, 0], nz[:, 1]] = 0 # momentum factor masking is annoying for sketched # to do it properly, we'd have to: # fi...
Python
1
from typing import Dict from ...utils import physics from ...utils import vector from . import base class Comment(base.Pattern): regex = r"(\\\\|//) .*" ValueType = str class Everything(base.Pattern): regex = r".*" ValueType = str class TrailingComment(base.MetaPattern): spec = r"line \\ comm...
Python
1
imer /// /// Generates an overflow event at the `timeout` frequency. fn timer<T>(self, timeout: T, prec: Self::Rec, clocks: &CoreClocks) -> TIM where T: Into<Hertz>; /// Configures the timer to count up at the given frequency /// /// Counts from 0 to the counter's maximum value, the...
Rust
0
update_menu(self, menu_id: int, menu_data: Dict[str, Any]) -> Menu: """ 更新菜单 Args: menu_id (int): 菜单ID menu_data (Dict[str, Any]): 菜单数据 - title (Optional[str]): 菜单标题 - path (Optional[str]): 菜单路径 - icon (Optional[st...
Python
1
= self.flow_model.compute_field(); for x in 0..self.flow_model.field_width { for y in 0..self.flow_model.field_height { let vector = vector_field[&(x, y)]; let canvas_x = x * self.flow_model.vector_size; let canvas_y = y * self.flow_model.vector_siz...
Rust
0
def FC_16bit(bs,time_steps,alphabet_size): k.set_floatx('float16') model = Sequential() init = keras.initializers.lecun_uniform(seed=0) model.add(embedding(alphabet_size, 32, batch_input_shape=(bs, time_steps))) model.add(flatten()) model.add(dense(1024, activation='relu'...
Python
1
""" GUI Utils for CrackSeg Application This package contains all GUI utilities organized in a modular structure: - core/: Core utilities (session, config, validation) - ui/: UI utilities (theme, styling, dialogs) - ml/: ML utilities (training, tensorboard, architecture) - data/: Data utilities (parsing, export, repor...
Python
1
4, 5, 7, 8, 9]; let _ = set.remove(list_index, 6); let result: Vec<usize> = set.iter(list_index).copied().collect(); assert_eq!(result, expected); } /// Removing an item from an empty list should yield nothing. #[test] fn test_list_remove_at_empty() { let mut set = LinkedListSet::new(); let list_...
Rust
0
?GetStateStorage@ImGui@@YAPEAUImGuiStorage@@XZ"] pub fn GetStateStorage() -> *mut ImGuiStorage; /// * items_count: /// * items_height: /// * out_items_display_start: /// * out_items_display_end: #[link_name = "?CalcListClipping@ImGui@@YAXHMPEAH0@Z"] pub fn CalcListClipping( item...
Rust
0
#[cfg(any(feature = "v1_2", feature = "dox"))] pub fn nm_device_vxlan_get_learning(device: *mut NMDeviceVxlan) -> gboolean; #[cfg(any(feature = "v1_2", feature = "dox"))] pub fn nm_device_vxlan_get_limit(device: *mut NMDeviceVxlan) -> c_uint; #[cfg(any(feature = "v1_2", feature = "dox"))] pub f...
Rust
0
PLAYFIELD_VERTICAL_PADDING, LEVEL_TEXT_WIDTH + 1, // the array has an extra space, hence +1 TEXT_HEIGHT); self.lcd.draw_pixels(&LEVEL_TEXT); // 4. draw level number (we always start on level 1) self.draw_level(1); ...
Rust
0
import pyttsx3 def speak_text(text): """ Convert text to speech and play it aloud using pyttsx3. """ try: engine = pyttsx3.init() engine.setProperty('rate', 150) # set speaking rate (words per minute) # Optionally, change voice if multiple voices are available: # voices...
Python
1
acc_offset: usize, key: &[u8], key_offset: usize) -> u64 { folded_mult_128( acc[acc_offset + 0] ^ read64(key, key_offset), acc[acc_offset + 1] ^ read64(key, key_offset + 8), ) } /// /// Combines 8 accumulators with keys into 1 finalized 64-bit hash. /// #[inline] fn merge_accs(acc: &[u64; 8], ...
Rust
0
clippy::pedantic, clippy::nursery)] #![allow(clippy::missing_errors_doc)] mod client; pub mod error; pub mod model; mod transport; pub use crate::client::{websocket::BinanceWebsocket, Binance}; use crate::updater::GroupUpdate; use crate::updater::UpdateMessage; use crate::updater::UpdaterClient; use actix_cors::Cors...
Rust
0
ntisch") return is_change def get_stored_sensor_id(persist_data: dict, hp_idx: int) -> str: """Hole die gespeicherte Sensor-ID für eine Wärmepumpe aus den persistierten Daten. Args: persist_data: Die persistierten Daten aus cycle_energy_persist.json hp_idx: Der Index der Wärmepum...
Python
1
# -*- coding: utf-8 -*- # (C) Copyright 2020, 2021, 2022, 2023, 2024 IBM. All Rights Reserved. # # Licensed under the MIT license. See LICENSE file in the project root for details. """Configurations for resistive processing units.""" from aihwkit.simulator.parameters import ( IOParameters, IOParametersIRDrop...
Python
1
ath="model_weights/wd_out"), ] metrics = [Accuracy] trainer = Trainer( model, objective="binary", optimizers=optimizers, lr_schedulers=schedulers, initializers=initializers, callbacks=callbacks, metrics=metrics,...
Python
1
HubMsg::FileReadResponse {uid, data, ..} => { for (path, tb_id) in &mut self.text_buffer_path_to_id { let mtb = &mut self.text_buffers[tb_id.as_index()]; if let Some(cth_msg) = &mtb.read_msg { if let HubMsg::FileReadRequest {uid: read_uid, ...
Rust
0
# Copyright (c) Alibaba, Inc. and its affiliates. import numpy as np from transformers import TrainerCallback, TrainerControl, TrainerState, TrainingArguments from swift.utils import get_logger logger = get_logger() class EarlyStopCallback(TrainerCallback): """An early stop implementation""" def __init__(s...
Python
1
# -*- coding: utf-8 -*- import arcpy class DistrictDivid(object): def __init__(self): """Define the tool (tool name is the name of the class).""" self.label = "District Divid" self.description = "Add district classification result into the database." def getParameterInfo(self): ...
Python
1
ptSourceOverride => 10, IcsType::NmiSource => 8, IcsType::LocalApicNmi => 6, IcsType::LocalApicAddressOverride => 12, IcsType::PlatformInterruptSource => 16, IcsType::ProcessorLocalX2Apic => 16, IcsType::LocalX2ApicNmi => 12, } } /...
Rust
0
upload_token::OwnedUploadTokenProviderOrReferenced, ObjectParams, UploadManager, }, SinglePartUploader, }; use qiniu_apis::{ credential::AccessKey, http::{ResponseErrorKind as HttpResponseErrorKind, ResponseParts}, http_client::{ ApiResult, BucketRegionsProvider, CallbackResu...
Rust
0
acc, x| acc + x); println!("Chars in code: {}", total_and_decoded.0); println!("Chars in memory when decoded: {}", total_and_decoded.1); println!("Diff with decoded: {}", total_and_decoded.0 - total_and_decoded.1); println!("Chars when encoded: {}", encoded); println!("Diff with encoded: {}", enco...
Rust
0
is not a valid float value. pub fn double(field_name: &str, field_value: &str) -> anyhow::Result<MessageFieldValue> { let v: f64 = field_value.parse()?; Ok(MessageFieldValue { name: field_name.to_string(), raw_value: Some(field_value.to_string()), rtype: RType::Double(v) }) } /// C...
Rust
0
import open3d as o3d import numpy as np # 定义降采样函数 def downsample_point_cloud(pcd, voxel_size=0.1, target_points=100): """使用体素网格和均匀采样对点云进行降采样""" # 获取点云的边界框 min_bound = pcd.get_min_bound() # 将点分配到体素中 voxel_dict = {} for point in pcd.points: idx_x = int((point[0] - min_bound[0]) / vox...
Python
1
QK)X2P RGF)9FR 9KL)L48 7FG)PS3 2V1)7BJ TFW)X4T WHD)7ZF YNY)72H 78D)9MZ LG9)YBL 5BT)725 6B1)81D MPD)MZN KJM)YLS XTS)GBK MD5)RDS 2QV)8P3 45V)LTG 8KR)GYW H9J)7V5 MJL)FFN 5SB)JD3 L7N)GDY J1M)HSF FVN)LTQ NCN)T2H R3X)C1Q YFJ)S54 WXJ)HN7 38T)JNF 9RM)RBN WCP)9M8 PZ9)BB4 RBM)9X7 CGM)8PQ GQG)5G9 968)D3N YKB)C59 JWT)MLP RDD)XNY K...
Rust
0
Choice::VARIANTS), default_value("auto") )] pub color: AnsiColorChoice, /// Dry run #[structopt(long)] pub dry_run: bool, /// Key (Package **name**) pub package: String, } #[derive(Debug)] pub struct Context<W, I, P> { pub cwd: PathBuf, pub home_dir: Option<PathBuf>, pub...
Rust
0
bleMethod> { debug("Called set_jni_call_double_method"); JNI_CALL_DOUBLE_METHOD.with(|opt| { *opt.borrow_mut() = j; }); get_jni_call_double_method() } pub(crate) fn get_jni_call_double_method() -> Option<JniCallDoubleMethod> { JNI_CALL_DOUBLE_METHOD.with(|opt| { *opt.borrow() })...
Rust
0
import pandas as pd from constants import GROUP_LABELLING_ERROR, RSI_PERIOD def get_rsi_group_label(row: pd.Series) -> str: if (row[f"RSI_{RSI_PERIOD}"] >= 0) and (row[f"RSI_{RSI_PERIOD}"] <= 5): return "0_5" if (row[f"RSI_{RSI_PERIOD}"] > 5) and (row[f"RSI_{RSI_PERIOD}"] <= 10): return "5_10...
Python
1
ent_id": deployment_id, "timestamp": datetime.now().isoformat(), "message": "Deployment completed", "stage": "completed", "progress": 100, "result": { "success": response.success, ...
Python
1
6nQ[[]337N a &q!, , 6 " "-a3 3-a3 3 a rwc([U[5(a URnOUn[U[5(a URn[U[R5(dz[ R ...
Python
1
ata = list(dsgd512_seed666_data.loc[:,'Step']) y_data = smooth(list(np.array(dsgd512_seed666_data.loc[:,'Value'].rolling(rolling_step).mean())), smooth_rate) plt.plot(x_data, y_data, linestyle='-', linewidth=1.5, color=sns.color_palette(n_colors=10)[3], label='D-SGD(Grid)_8192') csgd64_seed666_data = pd.read_csv(csgd...
Python
1
from enum import Enum as PyEnum from sqlalchemy import Column, Integer, String, DateTime, ForeignKey, Text, Enum from sqlalchemy.orm import relationship from sqlalchemy.sql import func from backend.api.database.db import Base # Перечисление для тональности новости class Tonality(PyEnum): POSITIVE = "POSITIVE" ...
Python
1
"Rundi", "rup": "Romanian; Macedo-", "rus": "Russian", "sad": "Sandawe", "sag": "Sango", "sah": "Yakut", "sam": "Aramaic; Samaritan", "san": "Sanskrit", "sas": "Sasak", "sat": "Santali", "scn": "Sicilian", "sco": "Scots", "s...
Python
1
d.mtz" % (n+1) params.mtz_file.output_file = os.path.abspath(params.mtz_file.output_file) process = process_arrays(params, input_files=input_files, log=out) if params.dry_run : print("# showing final parameters", file=out) master_phil.format(python_object=params).show(out=out) if params.verbose : ...
Python
1
tralAttention', 'transformers.models.mixtral.modeling_mixtral.MixtralModel': f'{LMDEPLOY_PYTORCH_MODEL_PATH}.mixtral.PatchedMixtralModel', 'transformers.models.mixtral.modeling_mixtral.MixtralBLockSparseTop2MLP': f'{LMDEPLOY_PYTORCH_MODEL_PATH}.mixtral.PatchedMixtralBLockSparseTop2MLP', 'transformer...
Python
1
flags |= TcpFlags::PSH; } if self.tcp_flag_rst { flags |= TcpFlags::RST; } if self.tcp_flag_syn { flags |= TcpFlags::SYN; } if self.tcp_flag_urg { flags |= TcpFlags::URG; } tcp_header.set_flags(flags); ip_...
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
mut fmt::Formatter) -> fmt::Result { fmt::Debug::fmt(self, f) } } #[cfg(test)] mod buffer_tests { use super::*; use time::now_utc; #[test] fn set_changed_sets_changed_flag_and_changed_time() { let mut fac = BufferFactory::new(); let mut b = fac.new_empty_buffer(); b...
Rust
0
index_status: FileStatus::Renamed, working_copy_status: FileStatus::Deleted, path: "new_file.rs".into(), orig_path: Some("old_file.rs".into()), working_copy_file_mode: FileMode::Blob, } ); assert_eq!( ...
Rust
0
.filter_map(move |val| { if val == equals { Some(((), NextIdx(range.0))) } else { None } }) }) .collect() } fn next_attr<T: 'static>(&...
Rust
0
interpolate_replace_nans(err, Gaussian2DKernel(1), boundary='extend') rmse = interpolate_replace_nans(rmse, Gaussian2DKernel(1), boundary='extend') if 0: #FIXME: Always check if this is needed <<<<<< for k in range(fac.shape[0]): fac[k,:,:] = np.flipud(fac[k,:,:]) Y_fac...
Python
1
eption as e: messagebox.showerror("Error", f"Failed to export settings:\n{e}") def show_system_info(self): """Show system information dialog""" import platform import sys info = f"""System Information: OS: {platform.system()} {platform.release()} Python: {sy...
Python
1
from django.contrib.auth.models import Permission,Group def Create_Group(sender,**kwargs): try: reader_group,created = Group.objects.get_or_create(name = "Reader") writer_group,created = Group.objects.get_or_create(name = "Writer") editor_group,created = Group.objects.get_or_create(name =...
Python
1
import fused from fused.models.udf import Header from fused.models import Schema @fused.udf def parks_vancouver(): """ UDF to get the polygon geometries of parks in Vancouver based on Open Data Portal """ import requests import geopandas as gpd import pandas as pd from shapely.geometry impo...
Python
1
cord.birthday.value.strftime('%d.%m.%Y') if record.birthday else "No birthday" result.append(f"Name: {record.name}, Phones: {phones}, Birthday: {birthday}") return '\n'.join(result) def main(): book = AddressBook() print("Welcome to the assistant bot!") while True: user_input = input("E...
Python
1
is=health_kis_all, # shield=shield_all, shield_kis=shield_kis_all, # attack=attack_all, attack_kis=attack_kis_all): # """ # 属性: # 生命基础值、生命系数 # 护盾基础值,护盾系数 # 攻击基础值,攻击系数 # 状态: # 攻击状态,格挡状态,连击状态 # 各种状态下所需要的参数 # ...
Python
1
ser = self.users_repository.get_by_username(username) query = self.users_repository.get_friends(user) if relation: if relation == 'followers': query = self.users_repository.get_followers_without_friends(user) elif relation == 'following': query = s...
Python
1
.map_err(|_| Error::<T>::BalanceLow)?; Ok(Some(imbalance)) } fn correct_and_deposit_fee( who: &H160, corrected_fee: U256, already_withdrawn: Self::LiquidityInfo, ) { if let Some(paid) = already_withdrawn { let account_id = T::AddressMapping::into_...
Rust
0
_eq!(x, (i + 1) as i32); }); } #[wasm_bindgen_test] fn from() { let x: Vec<i32> = vec![1, 2, 3]; let array = Int32Array::from(x.as_slice()); assert_eq!(array.length(), 3); array.for_each(&mut |x, i, _| { assert_eq!(x, (i + 1) as i32); }); } #[wasm_bindgen_test] fn copy_to() { let m...
Rust
0
shows this in action: /// /// ``` /// use varlen::prelude::*; /// /// define_varlen_newtype! { /// #[repr(transparent)] /// /// A string which counts UTF8 code points. /// pub struct TwoArrays<(T: Copy), (U: Clone = u16)>( /// pub Tup2< /// Array<T>, /// Array<U>, /// ...
Rust
0
# Python bytecode 2.7 (decompiled from Python 2.7) # Embedded file name: scripts/client/web/web_client_api/ui/clan.py from gui.Scaleform.daapi.settings.views import VIEW_ALIAS from gui.shared.event_dispatcher import showClanProfileWindow, showClanInvitesWindow, showClanSearchWindow, showClanPersonalInvitesWindow, showB...
Python
1
'''ManagementInterface class''' # metaparser from genie.metaparser.util.exceptions import SchemaEmptyParserError class ManagementInterface(object): """ManagementInterface class `ManagementInterface` class the functionality to retrieve the given ip address corresponding interface name. Args: ...
Python
1
import sys sys.path.insert(1,"../../../") import h2o from tests import pyunit_utils from h2o.estimators.gbm import H2OGradientBoostingEstimator def test_gbm_train_segments_multi(): response = "survived" segment_columns = ["pclass", "sex"] titanic = h2o.import_file(path=pyunit_utils.locate("smalldata/gbm_t...
Python
1
# gradients.py import jax import jax.numpy as jnp import jax.scipy as jsp import matplotlib.pyplot as plt class GradientsEval: def __init__(self) -> None: return def function_eval(self, x0: jnp.array) -> jnp.array: """ Input: x0 [jax.Array]: 2D vector consisting of [x, y] O...
Python
1
from pzem import PZEM import machine import time sleep = 3 * 1000 uart = machine.UART(0, baudrate=9600) # define PZEM device [UART, ADDR = 0xF8 (default)] dev = PZEM(uart=uart) # Set new address if dev.setAddress(0x05): print("New device address is {}".format(dev.getAddress())) # Buzzer configuration buzzer_pi...
Python
1
def shopping_cart(*args): cart = {"Soup": [], "Pizza": [], "Dessert": []} for arg in args: if arg == "Stop": break meal, ingredient = arg[0], arg[1] if meal == "Soup" and len(cart["Soup"]) == 3: continue if meal == "Pizza" and len(cart["Pizza"]) == 4: ...
Python
1
ux::WithdrawUnbondedStakeTx(tx.clone()), tx.id()), }; (txaux, tx, witness, account, secret_key, storage) } #[test] fn existing_account_withdraw_tx_should_verify() { let (txaux, _, _, _, _, storage) = prepare_app_valid_withdraw_tx(0); let extra_info = get_chain_info_enc(&txaux); verify_enclave_tx( ...
Rust
0
the same topic)") parser.add_option("-u", "--unassign", dest="unassign", help="unassign method (all/doc/term/none)", default="none") (options, args) = parser.parse_args() numpy.random.seed(options.seed) if options.model and os.path.exists(options.model): with open(options.model, "rb") as f: ...
Python
1
pub fn from_x_forwarded_for( header_value: &str, ) -> Result<Self, ForwardedHeaderValueParseError> { values_from_header(header_value) .map(|address| { let a = address.parse::<IpAddr>()?; Ok(ForwardedStanza { forwarded_for: Some(Ide...
Rust
0
> 14, -1 => 15, 0 => 0, 1 => 1, 2 => 2, 3 => 3, 4 => 4, 5 => 5, 6 => 6, 7 => 7, _ => { return Err(Error::new( ErrorKind::InvalidInput, format!("Unexpected offset: {}", input), )) ...
Rust
0
"), ('𨺵', "zhuì"), ('𨺸', "mǎo"), ('𨺹', "jiǎo"), ('𨺿', "zhǎn"), ('𨻀', "pí,bī"), ('𨻁', "xī"), ('𨻂', "yàn"), ('𨻃', "fèi"), ('𨻄', "niè"), ('𨻆', "zhì"), ('𨻈', "suǒ"), ('𨻊', "yì"), ('𨻌', "lěi"), ('𨻍', "xù"), ('𨻏', "yì"), ('𨻒', "wēi"), ('𨻕', ...
Rust
0
in all_nodes if p.test_query_glob is None or n.info['path'] not in test_sql_set ] test_nodes = [n for n in all_nodes if n.info['path'] in test_sql_set] assert len(train_nodes) > 0 return all_nodes, train_nodes, test_nodes class RunningStats(object): """Computes runni...
Python
1
() { let exp = read_to_string("regression/v17/module_with_case.v"); let mut nop = CaseBranch::new(Expr::new_ulit_dec(5, "0")); nop.add_seq(Sequential::new_display("nop")); let mut add = CaseBranch::new(Expr::new_ulit_dec(5, "1")); add.add_seq(Sequential::new_display("add")); let mut sub = CaseBr...
Rust
0
)); } } self.inner } /// Update the stored lines with the next cell info. pub fn update_lines(&mut self, cell: &RenderableCell) { for (flag, start_cell) in self.last_starts.iter_mut() { let flag = *flag; *start_cell = match *start_cell { ...
Rust
0
+ h / 2, y + h - 4); draw_yxline(x + w - 2, y + h / 2, y + h - 4); // top corners set_draw_color(activated_color(Color::from_rgb(0x79, 0x81, 0xBC))); draw_arc(x, y, 8, 8, 90.0, 180.0); draw_arc(x + w - 8, y, 8, 8, 0.0, 90.0); // bottom corners set_draw_color(activated_color(Color::from_rgb(0...
Rust
0
e for the inverse CxyCxxi = np.linalg.solve((Cxx + N).T, Cxy.T) # Predicted value zi[i] = np.dot(CxyCxxi, zc) + (1 - np.sum(CxyCxxi)) * m0 # Predicted error ei[i] = np.sqrt(np.abs(c0 - np.dot(CxyCxxi, Cxy.T))) # Number of data used for prediction ni[i] = len(zc...
Python
1
platform.python_version() hash_keys = await get_all_hash_keys() pipe = await r.pipeline() for hash_key in hash_keys: await pipe.hgetall(hash_key) # type: ignore[no-untyped-call] hash_data = await pipe.execute() result = dict(zip(hash_keys, hash_data)) result = await decode_dictionary(...
Python
1
e")] pub class_def: Option<super::class::ClassDef>, #[serde(skip_serializing_if = "Option::is_none")] pub type_alias_def: Option<super::type_alias::TypeAliasDef>, #[serde(skip_serializing_if = "Option::is_none")] pub namespace_def: Option<super::namespace::NamespaceDef>, #[serde(skip_serializing_if = "Op...
Rust
0
type=self.ITEM_TYPE.type, hash=new_boefje_task.hash, data=new_boefje_task.model_dump(), ) task.priority = self.ranker.rank(task) tasks.append(task) return tasks @override def calculate_deadline(self, schedule: models.Sch...
Python
1
break try: data = json.loads(line[6:]) content = ( data.get("choices", [{}])[0] .get("delta", {}) ...
Python
1
t_affect_every_byte() { test_input_affect_every_byte(AHasher::test_with_keys); } #[test] fn aes_keys_affect_every_byte() { test_keys_affect_every_byte(AHasher::test_with_keys); } #[test] fn aes_finish_is_consistant() { test_finish_is_consistant(AHasher::test_with_keys) ...
Rust
0
borrow().name()); reader.reset(bytecode, pc); let opcode = reader.read_u8(); let mut inst = new_instruction(opcode); inst.fetch_operands(&mut reader); (*current_frame).borrow_mut().set_next_pc(reader.pc()); inst.execute((*current_frame).borrow_mut().deref_mut()); ...
Rust
0