text
string
label_name
string
labels
int64
ueSlot, id: ExprId) -> Result<Value, Error> { let value = self.check_expr_inner(slot, id)?; return Ok(value); } fn check_expr_inner(&mut self, slot: ValueSlot, id: ExprId) -> Result<Value, Error> { use ExprKind::*; let expr = &*id; match *expr { Procedure(...
Rust
0
print(f"[DEBUG][Rank 0][Day {day}] Received home arrival status {status_from_rank} from rank {source_rank}") all_statuses.append(status_from_rank) # 모든 프로세스가 완료되었는지 확인 all_arrived = all(all_statuses) ...
Python
1
t_user_logout_href ) trans.handle_user_logout() if success: return {"redirect_uri": redirect_uri} else: return {"message": message} @web.expose def get_logout_url(self, trans, provider=None, **kwargs): idp_provider = provider if provider else tran...
Python
1
basic_sport_event_item['participant_away'] = participant_2 basic_sport_event_item['bet_1'] = bet_1 basic_sport_event_item['bet_0'] = bet_0 basic_sport_event_item['bet_2'] = bet_2 basic_sport_event_item['bet_10'] = bet_10 ...
Python
1
tensionOID.PRECERT_SIGNED_CERTIFICATE_TIMESTAMPS ) assert isinstance(ext.value, x509.UnrecognizedExtension) @pytest.mark.requires_backend_interface(interface=RSABackend) @pytest.mark.requires_backend_interface(interface=X509Backend) class TestInvalidExtension(object): def test_invalid_certificate_...
Python
1
} }), Operator::MultiAggregate(MultiAggregateOperator { key_col_headers: vec!["foo".to_string(), "foo == 123".to_string()], key_cols: vec![ Expr::column("foo"), Expr::Binar...
Rust
0
for i in range(0, 3): if content[0] & (1 << (4 + i)): size |= content[data_ptr] << (i * 8) data_ptr += 1 # do something with offset and size ...
Python
1
""" API URL configuration for cases app. """ from django.urls import path from . import api_views app_name = 'cases_api' urlpatterns = [ # Case CRUD endpoints path('', api_views.CaseListCreateAPIView.as_view(), name='case_list_create'), path('<int:pk>/', api_views.CaseRetrieveUpdateDestroyAPIView.as_view...
Python
1
return Err(Error::FdtGuestMemoryWriteError); } Ok(fdt_data_size) } //! `start` subcommand - example of how to write a subcommand use crate::{application::app_config, block::write_genesis}; /// App-local prelude includes `app_reader()`/`app_writer()`/`app_config()` /// accessors along with logging macros. Cu...
Rust
0
key): if key in ['typing_intervals', 'active_hours', 'session_gaps', 'reply_response_times', 'anomaly_flags']: # 列表类型追加数据 getattr(behavior, key).append(value) if isinstance(value, (int, float, str)) else getattr(behavior, key).extend(val...
Python
1
'/' else: raise Exception("invalid options: [" + opts + ": " + arg + "]") if not os.path.exists(self.proto_file): raise Exception("Generate error, not exist protobuf file: " + self.proto_file) if ".proto" not in self.proto_file: raise Exception("Gen...
Python
1
class Node: def __init__(self, value, next=None): self.value = value self.next = next def get_tail(head): current = head while current: current = current.next if current.next == None: tail = current return tail # linked list: num1->num2->num3 num3 = Node(3) num2 = ...
Python
1
64 {}, %work_t* \ %cur.work, i32 0)", bld_tmp, bld_ty_str, bld_prefix, builder_size )); self.gen_store_var(&bld_tmp, &llvm_symbol(output), &bld_ty_str, ctx); } ...
Rust
0
: ' else: prefix = '' s += '=' * 10 + f'[{prefix}hyper parameters]' + '=' * 10 + '\n' s += json.dumps(self.hyperparas, indent=4) + '\n' if hasattr(self, 'optimizer_config'): s += '=' * 10 + f'[{prefix}optimizer config]' + '=' * 10 + '\n' s += json.du...
Python
1
from typing import Optional from fastapi import APIRouter, Depends, HTTPException, Header from app.controllers.itinerary_controller import ItineraryController from app.schemas.itinerary_schema import ItineraryRequest from app.core.database import get_async_db from sqlalchemy.ext.asyncio import AsyncSession router = ...
Python
1
utex::new( event_loop.create_proxy(), ))); let mut painter = crate::Painter::new(&display); let mut integration = egui_tao::epi::EpiIntegration::new( "egui_glium", painter.max_texture_side(), display.gl_window().window(), repaint_signal, persistence, ...
Rust
0
: [(2, int(*viettelpost_service))] }) def viettelpost_get_default_custom_package_code(self): raise (_('This feature is not available for Viettelpost carrier')) def synchronize_viettelpost_resources(self): try: self.env['viettelpost.province'].sync_provinces() se...
Python
1
import matplotlib.pyplot as plt import numpy as np # Set the style plt.style.use('seaborn') plt.rcParams['font.family'] = 'sans-serif' plt.rcParams['font.sans-serif'] = ['Arial'] # Create figure and axis with a larger size fig, ax = plt.subplots(figsize=(12, 8)) # Sample data structure (you'll need to replace this w...
Python
1
donlyObject::new() }; /// Kernel PD struct. pub static KERNEL_PD: ExternReadonlyObject<PD> = unsafe { ExternReadonlyObject::new() }; /// Guard page virtual address after switching to the new page table. fn kernel_stack_guard_page_vaddr() -> VAddr { unsafe { VAddr::from((&kernel_stack_guard_page as *const _) as...
Rust
0
# 요격 시스템 def solution(targets): answer = 0 bound = 0 for s, e in sorted(targets): if bound > s: bound = min(bound, e) else: bound = e answer += 1 return answer
Python
1
ang) // // Core/async-v3/buffer.rs //! Asynchronous buffer handles /* /// Buffer providing a location for read data (incoming / mutable) pub struct ReadBuffer<'a> { } /// Buffer providing a location for data to be written (outgoing / immutable) pub struct WriteBuffer<'a> { } pub struct ReadBufferHandle<'a> { // Need...
Rust
0
mal(shape=[1, 2]))] source_variables = [tf.Variable(tf.random_normal(shape=[1, 2]))] self.assertRaises(ValueError, target_update_ops.update_target_variables, target_variables, source_variables, -0.1) self.assertRaises(ValueError, target_update_ops.update_target_variables, ...
Python
1
import tensorflow as tf import tensorflow.contrib.layers as layers from datetime import datetime # MNIST input data from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("/tmp/data/", one_hot=True) def multilayer_perceptron(x): fc1 = layers.fully_connected(x, 256, activation...
Python
1
rrV)rs r r8SubplotSpec.__repr__"c$$&'q<<%%&a (9(9':"<<%%&a (9(9':!= >r$c[U5S:Xa]Uun[U[5(aU$[U[5(d[ SU<35e[ ...
Python
1
# Copyright (c) 2022 Horizon Robotics and ALF Contributors. 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...
Python
1
import pandas as pd import dataset_helper def get_round(val, n=2): return round(val, n) def _area_fraction(w_bbx, h_bbx, w, h): a_factor = (w_bbx * h_bbx) / (w * h) a_factor = get_round(a_factor, 4) return a_factor def _scale_factor(w_bbx, h_bbx, resized_dim=256): s_factor = (pd.DataFrame({'...
Python
1
rgs.gpus_per_node, args.time_limit, args.container_image, custom_mounts=args.custom_mounts, custom_env_vars={}, hf_token=args.hf_token, nemo_home=args.nemo_home, wandb_key=args.wandb_key, network='sharp' if args.use_sharp else None, ) plugins = [b...
Python
1
# nopep8 return self._cards[3].get_value("es5") @es5.setter def es5(self, value: float) -> None: """Set the es5 property.""" self._cards[3].set_value("es5", value) @property def es6(self) -> typing.Optional[float]: """Get or set the Corresponding yield stress value to E...
Python
1
import re from library.textutils.utils import despace def reduce_br(soup_str): soup_str = soup_str.replace("<br>", "<br/>").replace('<p><br/>', '<p>').replace('<br/></p>', '</p>') soup_str = re.sub(r'([^.>])<br/>([^(<br/>)])', r'\g<1> \g<2>', soup_str) soup_str = re.sub(r'(?:<br/>\s*)+([^(<br/>)])', r'<b...
Python
1
features: `\"Win32_Storage_FileServerResourceManager\"`*"] pub const FsrmClassificationLoggingFlags_ClassificationsInLogFile: FsrmClassificationLoggingFlags = 1i32; #[doc = "*Required features: `\"Win32_Storage_FileServerResourceManager\"`*"] pub const FsrmClassificationLoggingFlags_ErrorsInLogFile: FsrmClassification...
Rust
0
pace.name] = namespace # Consume all <page> and <logitem> items = cls.load_items(first_item_element, element, namespace_map) return cls(site_info, items) @classmethod def from_file(cls, f): """ Constructs a :class:`~mwxml.iteration.dump.Dump` from a `file` pointer. ...
Python
1
### freeze original encoder and decoder self.freeze_UVit = UViT(img_size, patch_size, in_chans, embed_dim, depth, num_heads, mlp_ratio, qkv_bias, qk_scale, norm_layer, mlp_time_embed, use_checkpoint, clip_dim, num_clip_token, conv, skip) #### weights proces...
Python
1
assert!(s.len() <= 8); let s = s.as_bytes(); 0 | (u64::from(*s.get(0).unwrap_or(&0))) << 00 | (u64::from(*s.get(1).unwrap_or(&0))) << 8 | (u64::from(*s.get(2).unwrap_or(&0))) << 16 | (u64::from(*s.get(3).unwrap_or(&0))) << 24 | (u64::from(*s.get(4).unwrap_or(&0))) << 32 | (u64::from...
Rust
0
PTIC_SEG_DATASET = ( _build_waymo_image_panoptic_seg_dataset( dataset_name=_WOD_PVPS_DEPTH_VIDEO_PANOPTIC_SEG, is_depth_dataset=True, ignore_depth=0)) WOD_PVPS_IMAGE_PANOPTIC_SEG_MULTICAM_DATASET = ( _build_waymo_image_panoptic_seg_dataset( dataset_name=_WOD_PVPS_IMAGE_PANOPTIC_S...
Python
1
import os import json import glob import tensorflow as tf import numpy as np from PIL import Image from model import resnet50 def main(): im_height = 224 im_width = 224 num_classes = 5 _R_MEAN = 123.68 _G_MEAN = 116.78 _B_MEAN = 103.94 # load images # 指向需要遍历预测的图像文件夹 imgs_root =...
Python
1
ame] = tool.to_api_func() self.toolcount += 1 tool = Tool(tool_count=self.toolcount, category='Indicator Evaluator', type='Anomaly') self.toolinfo[tool.name] = tool.to_info_dict() self.tooldes[tool.name] = tool.to_des_dict() self.toolbox[tool.name...
Python
1
OpenVX context that had been loaded from"] #[doc = " the module using the \\ref vxLoadKernels function."] #[doc = ""] #[doc = " The kernel unloading is performed by calling the <tt>vxUnpublishKernels</tt>"] #[doc = " exported function of the module."] #[doc = " \\note <tt>vxUnpublishKernels</tt> is...
Rust
0
eN\xbey\xbf+2\x88p\x90\x06\x1eW\x0b,J\ \x00\x1a\x12\xec\xc4\x0b\xcb\xa4y\x1c\xf3~\xf3\xb6\xf1$\ j\xcfKW\x81\xbf.\x1d\xeb\x13L#\x08E^\xc7\ \xe9\x09\xf4\x99G\xb0\xcb\xcb\xc6\xa8\xb0\x9a\x88G\x17\xae\ \x8dQ\xe8\xb0K\xd6h\xe2\x09\xe65\xce\x90.Z\xc1\ \x83\xcb\x83\x1c,\xa1\xa2\x80\xfa@\x8f\xcd\xccc]q\ =\x99\x90\x82%\x89H\x04...
Python
1
} } Ok(msg) } } impl MessageWrite for BatchGetRowResponse { fn get_size(&self) -> usize { 0 + self.tables.iter().map(|s| 1 + sizeof_len((s).get_size())).sum::<usize>() } fn write_message<W: WriterBackend>(&self, w: &mut Writer<W>) -> Result<()> { for...
Rust
0
# WARNING: Please don't edit this file. It was generated by Python/WinRT v0.9.210202.1 import typing, winrt _ns_module = winrt._import_ns_module("Windows.System.Display") DisplayRequest = _ns_module.DisplayRequest
Python
1
"zwar", "darauf", "Arbeit", "", "Beispiel", "September", "zusammen", "einige", "Land", "allen", "fast", "Frauen", "März", "Namen", "Unternehmen", "ihrem", "davon", "Mann", "Mai", "Platz", "deutsche", "werde", "Oktober", "muß", ...
Rust
0
import datetime import logging from sqlalchemy import func from datetime import datetime from src.commands.base_command import BaseCommand from src.errors.errors import BadRequest, SesionYaAgendada from src.models.db import db_session from src.models.sesion import EstadoSesionEnum, Sesion from src.utils.seguridad_util...
Python
1
essage = FlexSendMessage( alt_text= '有人在抽撲克牌!', contents={ "type": "carousel", "contents": flex_message_contents } ) # 發送訊息 line_bot_api.reply_message(event.reply_token, flex_message) # 取得卡片名稱 def get_poker...
Python
1
lse: return ",".join(str(server.error) for server in servers if server.error) def __repr__(self) -> str: msg = "" if not self._opened: msg = "CLOSED " return f"<{self.__class__.__name__} {msg}{self._description!r}>" def eq_props(self) -> tuple[tuple[_Address...
Python
1
ome(new_value.into()); hub.borrow_mut().wakers.values().for_each(|w| w.wake_by_ref()); hub.borrow_mut().wakers.clear() } /// Watches the value stored in this hub, resolving when the /// stored value differs from `last_value`. pub fn watch_for_change<S>(&self, last_value: Option<S>) -> P...
Rust
0
settings.clone(), pool.clone(), openid::build_client(settings, pool).await, ) .into_make_service(), ) .await?; Ok(()) } // rustfmt-short_array_element_width_threshold: 20 fn main() { pub const FORMAT_TEST: [u64; 5] = [...
Rust
0
p: browser = await p.chromium.launch(headless=False, args=['--start-maximized']) # headless=False 便于调试 gcontext = await browser.new_context(viewport={"width": 1920, "height": 1080}, no_viewport=True) stealth = os.path.join(script_dir, 'stealth.min.js') await gcontext.add_init_script(pat...
Python
1
end]), usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, }); device.create_bind_group(&wgpu::BindGroupDescriptor { layout: &object_texture_bindgroup_layout(device), entries: &[ wgpu::BindGroupEntry { binding: 0, resource: blen...
Rust
0
import numpy maxbytes = 4*1024**3 # 4 GB content = numpy.empty(maxbytes // numpy.dtype(numpy.float32).itemsize, dtype=numpy.float32) for i in range(0, len(content), len(content) // 8): content[i : i + len(content) // 8] = numpy.random.normal(0, 1, len(content) // 8) content.tofile(open("sample-content.float32",...
Python
1
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.response.AlipayResponse import AlipayResponse from alipay.aop.api.domain.PayForPrivilegeUserRelation import PayForPrivilegeUserRelation class AlipayMerchantPayforprivilegeUserrelationQueryResponse(AlipayResponse): def __init__(self): ...
Python
1
<String>, } #[derive(Debug, Default, Clone, PartialEq, Serialize, Deserialize)] pub struct TechnologyStack { pub name: String, pub link: Option<String>, pub description: Option<String>, } #[derive(Debug, Clone, PartialEq, Serialize)] pub struct Works { pub repositories: Vec<Repository>, ...
Rust
0
, 16).ok() } }<filename>src/math/newlib/acosf.rs /* ef_acos.c -- float version of e_acos.c. * Conversion to float by <NAME>, Cygnus Support, <EMAIL>. */ /* * ==================================================== * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. * * Developed at SunPro, a Sun...
Rust
0
ify(|_, w| { w.moder9().bits(0b10) .moder10().bits(0b10) }); gpioc.moder.modify(|_, w| { w.moder2().bits(0b10) .moder3().bits(0b10) }); gpiob.afrh.modify(|_, w| { w.afrh9().bits(0b1...
Rust
0
example, for listing resources, a *read-only* scope will be /// sufficient, a read-write scope will do as well. pub fn add_scope<T, S>(mut self, scope: T) -> CommentSuggestscoreCall<'a, C, A> where T: Into<Option<S>>, ...
Rust
0
#[doc = " size, see the largest_free_block member returned by multi_heap_get_heap_info()."] #[doc = ""] #[doc = " @param heap Handle to a registered heap."] #[doc = " @return Number of free bytes."] pub fn multi_heap_free_size(heap: multi_heap_handle_t) -> size_t; } extern "C" { #[doc = " @brief R...
Rust
0
() } } } #[repr(C)] #[derive(Clone, Copy)] pub struct VREvent_TouchPadMove { pub bFingerDown: bool, pub flSecondsFingerDown: f32, pub fValueXFirst: f32, pub fValueYFirst: f32, pub fValueXRaw: f32, pub fValueYRaw: f32, } impl Default for VREvent_TouchPadMove { fn default() -> VREvent_To...
Rust
0
Cost Time: {(end - start):.2f}s') edge_list = sorted(edge_list, key=lambda x: x['loss'], reverse=True) # Rank the results based on edge losses for e in edge_list: log.write(str(e)) log.write("\n") event_count = 0 total_loss = 0 ...
Python
1
def maiusculas(texto): texto_corrigido = "" maiuscula = True for char in texto: if maiuscula and char.isalpha(): texto_corrigido += char.upper() maiuscula = False else: texto_corrigido += char if char in ".!?": mai...
Python
1
#!/usr/bin/env python3 """ Startup script for Medical AI System This script will: 1. Check dependencies 2. Test the trained model 3. Start the FastAPI server """ import sys import subprocess import importlib import os from pathlib import Path def check_dependencies(): """Check if required packages are installed""...
Python
1
# * * * * * # * * # * * # * * # * * * * * n=int(input()) for i in range(n): if i==0 or i==n-1: print('* * * * *') else: print('* *')
Python
1
; /// Thread Status characteristic definition. pub mod thread_status; /// Transmit Power characteristic definition. pub mod transmit_power; /// Tunnel Connection Timeout characteristic definition. pub mod tunnel_connection_timeout; /// Tunneled Accessory Advertising Status characteristic definition. pub mod tunneled_ac...
Rust
0
_set_max_write_buffer_number(self.inner, nbuf); } } /// Sets the amount of data to build up in memory (backed by an unsorted log /// on disk) before converting to a sorted on-disk file. /// /// Larger values increase performance, especially during bulk loads. /// Up to max_write_buffer_...
Rust
0
I had this python script write them all out to a file // // i = 0; // for h in range(0, 24): // for m in range(0, 60): // for s in range(0, 60): // for f in range(0, 30): # 60 for 59.94 // if f < 2 and s == 0 and m % 10 != 0: # f < 4 for 59.94 // ...
Rust
0
import numpy as np from tensorflow.keras.models import load_model from sklearn.metrics import confusion_matrix, classification_report import matplotlib.pyplot as plt import seaborn as sns if __name__ == "__main__": # اینجا دیتای تست رو لود میکنیم و میدیم به مدل X_test = np.load("scripts/X_test.npy") y_test...
Python
1
ions_cond = torch.as_tensor([0] * self.num_views).float() # fixed only use 4 views to train camera_embeddings = torch.stack([elevations_cond, elevations, azimuths], dim=-1) # (Nv, 3) normal_class = torch.tensor([1, 0]).float() normal_task_embeddings = torch.stack([normal_class]*self.num_views...
Python
1
import traceback from rich.console import Console import tqdm import supervisely as sly from supervisely.io.fs import dir_exists def upload_run(src_dir: str, workspace_id: int, project_name: str = None) -> bool: console = Console() api = sly._handle_creds_error_to_console(sly.Api.from_env, console.print) ...
Python
1
# File: main.py # Author: Armstrong Subero # Platform: Python (Standard or MicroPython) # Program: P47_BinaryTree # Interpreter: Python 3.x / MicroPython # Program Version: 1.0 # # Program Description: This program demonstrates the creation of a binary tree # and implements basic tree traversal met...
Python
1
ance 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, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either ex...
Rust
0
enum Result<T, E> { Ok(T), Err(E), } let mut deserializer = serde_json::Deserializer::from_str(&output); deserializer.disable_recursion_limit(); Result::deserialize(&mut deserializer) .map_err(Error::JSONError)? .map_err(Error::P...
Rust
0
NP_TypeKeys::Int64 => { i64::set_from_json(depth, apply_null, cursor, memory, json) }, NP_TypeKeys::Uint8 => { u8::set_from_json(depth, apply_null, cursor, memory, json) }, NP_TypeKeys::Uint16 => { u16::set_from_json(depth, apply_null, cursor, memo...
Rust
0
gramError::IllegalOwner); } let receiving_account_amount = receiving_account.lamports(); **receiving_account.lamports.borrow_mut() = receiving_account_amount .checked_add(target_account.lamports()) .unwrap(); **target_account.lamports.borrow_mut() = 0; sol_memset( *target_acc...
Rust
0
__author__ = 'ericvergnaud'
Python
1
atalog())); assert_eq!(search_index.search_by_term("").len(), 5); assert_eq!(search_index.search_by_term(" ").len(), 5); assert_eq!(search_index.search_by_term(" \t \n ").len(), 5); } } <filename>crates/varcon/codegen/src/main.rs use structopt::StructOpt; const DICT: &[u8] = include_b...
Rust
0
# Copyright 2021 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
Python
1
import sqlite3 from pathlib import Path ROOT_PATH = Path(__file__).resolve().parent conn = sqlite3.connect(ROOT_PATH/"teste.db") cursor = conn.cursor() cursor.execute(""" CREATE TABLE IF NOT EXISTS treino ( id INTEGER PRIMARY KEY AUTOINCREMENT, nome VARCHAR(100) NOT NULL ); """) cursor.execute(""" CREATE TABLE IF...
Python
1
lock(); if let Some(mut comb) = lock_comb { let mut split_remainder = logger_data.split_off(i+1); comb.as_mut().unwrap().append(&mut logger_data); *logger_data = split_remainder; } i = 0; ...
Rust
0
t', required=True, help='Bağlantı string’i, örn. udp:127.0.0.1:14550') args = parser.parse_args() print("Connecting to", args.connect, flush=True) vehicle = connect(args.connect, wait_ready=True) # SITL’de gyro vb. ön-arm hatalarını atla vehicle.parameters['ARMING_CHECK'] =...
Python
1
"\u{178F}\u{17D2}\u{179A}\u{17D2}\u{179F}\u{17C5}", "", ), "uni17C1=0+288|\ uni17D2179A=0+287|\ uni178F=0+635|\ uni17D2179F17C5=0+584" ); } #[test] fn khmer_misc_055() { assert_eq!( shape( "tests/fonts/in-house/3998336402905...
Rust
0
import re import logging from typing import List, Dict # Настройка логирования logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') # Определяем конкретные технические навыки SKILLS = { # Языки программирования и основные библиотеки 'python': { 'category': 'Progr...
Python
1
-> &Arc<IndexMap<String, String>> { &self.labels } pub fn response_classes(&self) -> &ResponseClasses { &self.response_classes } } // === impl RequestMatch === impl RequestMatch { fn is_match<B>(&self, req: &http::Request<B>) -> bool { match self { RequestMatch::M...
Rust
0
d(suggestions_by_chain[chain_id], key=lambda x: x['apr'], reverse=True) for suggestion in sorted_suggestions: final_suggestions_lines.append(suggestion['text']) return "\n".join(final_suggestions_lines) async def generate_staking_opportunities_content(staking_opportunities_list): """Format...
Python
1
fn display_op(&self, _: bool) -> String { format!("{} {} {}", self.lhs, Op::symbol(), self.rhs) } } pub struct BinarySVOperator<LHS, RHS, Out, Op> { pub lhs: BufferRef<Scalar<LHS>>, pub rhs: BufferRef<RHS>, pub output: BufferRef<Out>, pub op: PhantomData<Op>, } impl<'a, LHS, RHS, Out...
Rust
0
let m = xs.len() as f64; let n = params.len(); xs.iter() .zip(ys.iter()) .map(|(x,&y)| x.scalar_mul((x.mul(&params) - y) / m)) .fold(Vector::zeros(n), |acc, x| acc.add(&x)) } fn extend_feature_vector(&self, xs: &[Vector]) -> Vec<Vector> { let mut xs_ext ...
Rust
0
import re def clean_cnl_payload(raw_text: str) -> str: # If it starts and ends with quotes, and contains \\n, treat it as escaped JSON string if raw_text.startswith('"') and raw_text.endswith('"') and '\\n' in raw_text: # Unescape \n, \", \t, etc. try: import json cleane...
Python
1
) -> ErrorIterator<'a> { if self.is_valid(schema, instance) { no_error() } else { error(ValidationError::enumeration( self.schema_path.clone(), instance_path.into(), instance, &self.options, )) } ...
Rust
0
#latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to app...
Python
1
context.pcr_read(&pcr_selection_list).unwrap(); // Verify that the selected slots have been read. assert_ne!(update_counter, 0); let output: TPML_PCR_SELECTION = pcr_selection_list_out.into(); assert_eq!(output.count, input.count); assert_eq!( output.pcrSelecti...
Rust
0
{active:Cell::new(false), transitions:Vec::new()}; // let state2 = State{active:Cell::new(false), transitions:vec![&state1]}; // println!("{:?}", state2); // for yada in state2.transitions.iter() { // yada.active.set(true); // } // println!("{:?}", state2); for line in reader.lines() { ...
Rust
0
e to an expose event #[derive(Copy, Clone, Debug, PartialEq)] pub struct ExposeArea { /// The view relative coordinate pub pos: Coord, /// The size pub size: Size, } impl From<p::PuglEventExpose> for ExposeArea { fn from(e: p::PuglEventExpose) -> ExposeArea { ExposeArea { pos: C...
Rust
0
= self.start % 8; // let end_byte = (self.start + 32 - 1).div(8); // // let mut slice = [0u8,0u8,0u8,0u8,0u8,0u8,0u8,0u8]; // let s = start_byte..=end_byte; // for (i, byte_index) in s.into_iter().enumerate().filter(|(i,_)| *i < 8) { // ...
Rust
0
), 0x0); let cartridge_rom: Vec<u8> = get_file_as_byte_vec(&config.cartridge_rom_filename); chip8.init_memory(cartridge_rom.iter().as_ref(), 0x200); let sdl_context = sdl2::init().unwrap(); let video_subsystem = sdl_context.video().unwrap(); let window = video_subsystem .window("Rusty Chip...
Rust
0
um! { ChatPosition (i8) { 0 = Chat, 1 = SystemMessage, 2 = Hotbar, } } packets! { MultiBlockChange { chunk_section_coordinate u64; dont_trust_edges bool; records VarIntPrefixedVec<VarLong>; } TabComplete { id VarInt; start VarInt; ...
Rust
0
let recovered = decrypt_combined(&key, encrypted_result.as_slice(), &iv, None)?; assert_eq!(bytes, recovered); // additional data let ad = cs_rng.generate_random_bytes(42); let encrypted_result = encrypt_combined(&key, &bytes, &iv, Some(&ad))?; assert_ne!(encrypted_result...
Rust
0
. #![allow(unused)] mod iomuxc { #[cfg(feature = "imxrt1060")] pub use imxrt_iomuxc::imxrt1060::*; pub use imxrt_iomuxc::prelude::*; } /// Ensure that prelude modules are re-exported as expected #[test] fn use_prelude() { use iomuxc::{ consts, flexpwm, gpio, lpi2c, lpspi, lpuart, Daisy, Erase...
Rust
0
utContainer, misc::{Alignment, Length}, picture::Picture, slider::Slider, }; use std::f32; use std::rc::Rc; static MOON: &[u8] = include_bytes!("../../resource/moon.png"); static LIGHT: &[u8] = include_bytes!("../../resource/light.png"); static QUESTION_BUTTON: &[u8] = include_bytes!("../../resource/question_button...
Rust
0
from collections import Counter T = int(input().strip()) for _ in range(T): N, K = map(int, input().strip().split()) A = list(map(int, input().strip().split())) B = sorted(A[:N]) c = Counter(B) a1 = [] a2 = [] in_b = [] not_in_b = [] in_both = [] for i in range(1, N + 1): ...
Python
1
, $i, $j, $k, 27, $m, $n, $o, 31), } }; } macro_rules! shuffle2 { ($a:expr, $b:expr, $e:expr, $f:expr, $i:expr, $j:expr, $m:expr, $n:expr) => { match (imm8 >> 4) & 0x3 { 0 => shuffle3!($a, $b, 16, $e, $f, 20, $i, $j, 24, $m, $n, 28), 1 => s...
Rust
0
self.file_handle.flush() @rank_zero_only def on_train_batch_end(self, trainer, pl_module, *args, **kwargs): self.write( f"Generation progress: {pl_module.true_global_step / trainer.max_steps * 100:.2f}%" ) @rank_zero_only def on_validation_start(self, trainer, pl_modul...
Python
1
# This file was auto-generated by Fern from our API Definition. from ...core.unchecked_base_model import UncheckedBaseModel import typing import pydantic from ...core.pydantic_utilities import IS_PYDANTIC_V2 class TextToSpeechStreamWithTimestampsResponseAlignment(UncheckedBaseModel): characters: typing.Optional[...
Python
1
import os.path as op import numpy as np import openmeeg as om def test_sensors(data_path): # Test creating sensors from numpy arrays labels = ["toto", "tata"] positions = np.array([[0, 1, 2], [0, 1, 2]], order="F") orientations = np.array([[-1, -1, -2], [-1, -1, -2]], order="F") weights = np.arr...
Python
1