text
string
label_name
string
labels
int64
.header().path_bytes(), b"a"); let mut s = String::new(); t!(a.read_to_string(&mut s).await); assert_eq!(s, "a\na\na\na\na\na\na\na\na\na\na\n"); s.truncate(0); t!(a.read_to_string(&mut s).await); assert_eq!(s, ""); let mut b = t!(entries.next().await.unwrap()); assert_eq!(&*b.header()....
Rust
0
123, ProtoType::Udp, ), ( "turn:google.de", "turn:google.de:3478?transport=udp", SchemeType::Turn, false, "google.de", 3478, ProtoType::Udp, ), ( "turns:google.de", ...
Rust
0
max(self.start.x, self.end.x); let y = self.start.y; return (x..=x_end).map(|x| Point::new(x, y)).collect(); } let mut x = self.start.x as isize; let mut y = self.start.y as isize; let x_step = if self.end.x > self.start.x { 1 } else { -1 }; let y_step =...
Rust
0
.compute(v + a * dt); step.compute(s + v1 * dt); } } #![warn(missing_docs)] //! Uniffi based bindings for the `matrix-sdk-crypto` crate. //! //! This crate can be used to introduce E2EE support into an existing Matrix //! client or client library in any of the language targets Uniffi supports. mod backup_...
Rust
0
--lenient / -l -- additionally search of some common, but non-standard\n types.\n --extension / -e -- guess extension instead of type\n\nMore than one type argument may be given.\n' def usage(code, msg=''): print USAGE if msg: print msg sys.exit(...
Python
1
# Copyright (c) Sebastian Raschka under Apache License 2.0 (see LICENSE.txt). # Source for "Build a Large Language Model From Scratch" # - https://www.manning.com/books/build-a-large-language-model-from-scratch # Code: https://github.com/rasbt/LLMs-from-scratch # Plot KV-cache vs context length for different n_kv_gr...
Python
1
structopt(short="d", long="dir", default_value=".")] pub dir: String, #[structopt(long="get", default_value="/")] pub get_path: String, #[structopt(long="post", default_value="/{pg_function_name}")] pub post_path: String, #[structopt(long="postgres", default_value="postgres://postgres:rei@loc...
Rust
0
bpy.types.SpaceView3D.draw_handler_remove(focusHUD, 'WINDOW') focusHUD = None @persistent def surface_slide_HUD(scene): global surfaceslideHUD if surfaceslideHUD and "RNA_HANDLE_REMOVED" in str(surfaceslideHUD): surfaceslideHUD = None active = getattr(bpy.context, 'active_object', No...
Python
1
= insert_points events[:, 2] = label_id_func(marker_names) annot = mne.annotations_from_events( events, raw.info['sfreq'], id_binding) raw.set_annotations(annot) raw.plot(scalings='auto', events=events, block=True) # sa...
Python
1
print("Invalid option") sleep(0.2) failMenu(input_box) def main(): message = True c = True while c: try: openUnread() c = False except Exception as e: print(f"error {e}, trying again") openUnread() i = 0 wh...
Python
1
from PIL import Image, ImageFilter, ImageChops import numpy as np import random import math # Filtro negativo def filtro_negativo(img): matriz = img.load() largura, altura = img.size for i in range(largura): for j in range(altura): pixel = ((255 - matriz[i,j][0]), (255 - matriz[i,j][1])...
Python
1
from starrealms.runner.controller import apply_command def _ship(name, on_play_effects): return { "name": name, "type": "ship", "on_play": list(on_play_effects), # e.g., [{"type":"trade","amount":3}] } def test_full_turn_play_buy_attack_end(game): p1, p2 = game.players[0], game.pl...
Python
1
!(once.try_lock().is_none()); assert_eq!(once.atom.load(Ordering::SeqCst), *FREE); assert!(once.try_lock().is_none()); } #[test] fn just_once_atom() { let once1 = Arc::new(Lock::new("Lock")); let once2 = once1.clone(); thread::spawn(move || { let lock = once2.try_lock(); let store...
Rust
0
import os import pandas as pd dfs = pd.DataFrame() # os.walk(file_path) 深度遍历file_path下的所有子文件夹及文件 for root_dir, sub_dir, files in os.walk(r"C:\Users\luming\Desktop\15分钟出门挑战"): for file in files: if file.endswith(".xlsx"): # 构造绝对路径 file_name = os.path.join(root_dir, file) ...
Python
1
from dojo.models import Test from dojo.tools.rapplex.parser import RapplexParser from unittests.dojo_test_case import DojoTestCase, get_unit_tests_scans_path class TestRapplexParser(DojoTestCase): def test_rapplex_parser_with_no_findings(self): with (get_unit_tests_scans_path("rapplex") / "rapplex_zero_...
Python
1
import networkx as nx # Создаем граф с семью узлами G = nx.Graph() G.add_nodes_from([0, 1, 2, 3, 4, 5, 6]) # Добавляем ребра, создающие "яму" и "горбик" G.add_edges_from([ (0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (1, 4) # Добавляем ребро для создания "ямы" ]) # Вычисляем центральность узлов centr...
Python
1
# Пользователь вводит с клавиатурыдва числа. Нужно # посчитать отдельно сумму четных, нечетных и чисел, # кратных 9 в указанном диапазоне, а также среднеарифметическое каждой группы start = int(input("Введите начало диапазона: ")) end = int(input("Введите конец диапазона: ")) sum_even = 0 count_even = 0 sum_odd = ...
Python
1
e; len must be b.len() * 2 /// n - the scrypt parameter N /// log_f - a factor that reduces memory usage at the cost of computation; must always be less than or equal to log_n /// To get a sense of how log_f works, the following formula calculates the total number /// of operations performed for a given n and log_f: //...
Rust
0
ticks(poisson_ticker::SpinTicker::new(d)).await; let sum: Duration = durs.iter().sum(); let mean: Duration = sum / durs.len() as u32; println!("spin mean: {:?} vs {:?}", mean, d); for o in durs { write!(&mut f, "spin {} {}\n", d.as_micros(), o.as_micros())?; } } ...
Rust
0
encryption => "1.2.840.113549.1.1.5", SHA256_WITH_RSA_ENCRYPTION => sha256_with_rsa_encryption => "1.2.840.113549.1.1.11", SHA384_WITH_RSA_ENCRYPTION => sha384_with_rsa_encryption => "1.2.840.113549.1.1.12", SHA512_WITH_RSA_ENCRYPTION => sha512_with_rsa_encryption => "1.2.840.113549.1.1.13", SHA224_WITH...
Rust
0
th of a parameter. Args: param_name (str): The name of the parameter. prefix (str): The prefix for the parameter. Defaults to an empty string. Returns: Tuple[int, int]: The layer-wise depth and the num of layers. Note: The first ...
Python
1
enerator code = ConcreteBytecode() code.append(ConcreteInstr("YIELD_VALUE")) for f, expected in ( (CompilerFlags.COROUTINE, CompilerFlags.ASYNC_GENERATOR), (CompilerFlags.ASYNC_GENERATOR, CompilerFlags.ASYNC_GENERATOR), (CompilerFlags.I...
Python
1
artialEq)] pub struct rte_flow_action_of_set_nw_ttl { pub nw_ttl: u8, } #[repr(C)] #[derive(Debug, Default, Copy, Clone, PartialEq)] pub struct rte_flow_action_of_push_vlan { pub ethertype: rte_be16_t, } #[repr(C)] #[derive(Debug, Default, Copy, Clone, PartialEq)] pub struct rte_flow_action_of_set_vlan_vid { ...
Rust
0
/ Tags for this metric datum pub tags: &'a Tags, } impl<'a> Datum<'a> { /// Creates a new metric datum with a specified timestamp in ms. pub fn new(metric: &'a str, timestamp: i64, value: &'a str, // TODO: make me use refs tags: &'a Tags) ...
Rust
0
class Team: def __init__(self, id, abbrev, name): self.id = id self.abbrev = abbrev self.name = name class TeamScore(Team): def __init__(self, id, abbrev, name, goals=0, sog=0, penalties=None, powerplay=False, num_skaters=0, pulled_goalie=False, goal_plays=None): super().__init...
Python
1
(); println!("new addr {}",&newaddr); let contract = ContractABI::new_by_name("HelloWorld", bcossdk.config.contract.contractpath.as_str(), &bcossdk.hashtype).unwrap(); //let to_address = String::from("882be29b2d5ac85d6c...
Rust
0
if ultimo: match = re.search(r'(\d+)$', ultimo.folio) numero = int(match.group(0)) + 1 if match else 1 else: numero = 1 while True: nuevo_folio = f"{base}{numero:04d}" if not Folio.objects.filter(folio=nuev...
Python
1
# -*- coding: utf-8 -*- # @Author : llc # @Time : 2022/5/15 14:19 import pytest from flask_openapi3 import APIBlueprint, OpenAPI app = OpenAPI(__name__) app.config["TESTING"] = True def get_operation_id_for_path_callback(*, name: str, path: str, method: str) -> str: print(name, path, method) return nam...
Python
1
oup_status_list, columns=[net_field.NODE_ID_FIELD, 'status']) node_group_status_df = pd.merge(node_group_status_df, node_gdf[[net_field.NODE_ID_FIELD, net_field.GEOMETRY_FIELD]], on=net_field.NODE_ID_FIELD, ...
Python
1
import argparse import os from xml.dom.minidom import parse def main(rspec_path: str, output_path: str, keypath: str, identifier: str = "node"): if not os.path.exists(rspec_path): raise FileNotFoundError("No rspec found at " + rspec_path) # parse rspec document rspec_document = parse(rspec_path) ...
Python
1
command to run. E.g. `./deqp-vk --deqp-caselist-file` /// /// A filename with the tests cases that should be run is appended to the command. pub run_command: Vec<String>, } /// Different results from running a deqp test. #[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)] pub enum TestResu...
Rust
0
pub fn is_potentially_mutated<'a, 'tcx: 'a>( variable: &'tcx Path, expr: &'tcx Expr, cx: &'a LateContext<'a, 'tcx>, ) -> bool { let id = match variable.def { Def::Local(id) | Def::Upvar(id, ..) => id, _ => return true, }; mutated_variables(expr, cx).map_or(true, |mutated| mutate...
Rust
0
tional[int] = None, redirect: Optional[int] = None, status: Optional[int] = None, status_forcelist: Optional[List[int]] = None, backoff_factor: float = 0, backoff_max: Optional[float] = None, pool_connections: Optional[int] = None, pool_maxsize: Optional[int] = None, config: Optional[Any...
Python
1
gs.is_yookassa_enabled(): webhook_lines.append( f"YooKassa: {settings.WEBHOOK_URL}:{settings.YOOKASSA_WEBHOOK_PORT}{settings.YOOKASSA_WEBHOOK_PATH}" ) if settings.is_pal24_enabled(): webhook_lines.append( f"PayPalych: {settings.WEBHOOK_URL}:{se...
Python
1
ime; define_command_option!( id: EventId, name: "event_id", description: "Event ID", required: true, option_type: OptionType::String(&[]), ); <gh_stars>0 #[doc = r"Register block"] #[repr(C)] pub struct RegisterBlock { #[doc = "0x00 - DMA2D control register"] pub cr: crate::Reg<cr::CR_SPEC>...
Rust
0
fn reset_value() -> Self::Ux { 0xffff_ffff } } pub mod logger; use async_trait::async_trait; use crate::app::EndpointExecutor; use crate::context::Context; use crate::router::ContextResult; #[async_trait] pub trait Middleware: Send + Sync + 'static { async fn handle<'a>( &'a self, con...
Rust
0
from manim import * class DragonCurve(Scene): def construct(self): self.camera.frame_height = 8 iterations = 12 start = np.array([-3, 0, 0]) end = np.array([3, 0, 0]) line = Line(start, end, color=BLUE) self.play(Create(line)) self.wait(0.5) lines...
Python
1
loss".format(split): nll_loss.detach().mean(), "{}/rec_loss".format(split): rec_loss.detach().mean(), "{}/d_weight".format(split): d_weight.detach(), "{}/disc_factor".format(split): torch.tensor(disc_factor), "{}/g_loss".format(split): g_loss.detach().mean...
Python
1
dictionary .combine(&extra_dictionary) .combine(&square_dictionary); let mut dictionary = UniversalDictionary::new(); dictionary.set_arpabet_dictionary(arpabet.to_dictionary()); let dictionary = Arc::new(dictionary); info!("Reading Abbreviations Map..."); let abbreviations = Arc::new(Abbreviati...
Rust
0
85encode(data), res, data) eq(base64.a85encode(data, adobe=False), res, data) eq(base64.a85encode(data, adobe=True), b'<~' + res + b'~>', data) self.check_other_types(base64.a85encode, b"www.python.org", b'GB\\6`E-ZP=Df.1GEb>') self.assertRaises(T...
Python
1
#!/bin/python3 # Colores básicos black = "\u001b[0;30m" red = "\u001b[0;31m" green = "\u001b[0;32m" yellow = "\u001b[0;33m" blue = "\u001b[0;34m" magenta = "\u001b[0;35m" cyan = "\u001b[0;36m" white = "\u001b[0;37m" # Colores brillantes (intensos) bright_black = "\u001b[0;90m" bright_red = "\u001b[0;91m" bright_gree...
Python
1
import pandas as pd from transformers.pipelines import pipeline from posts__util_root_dir import root_dir # Load Excel file file_path = f"{root_dir}/data/raw/gmail_messages.xlsx" text_column = "body" df = pd.read_excel(file_path) # Initialize sentiment analysis pipeline sentiment_pipeline = pipeline( "text-class...
Python
1
buf_x); let x_inv = x.inverse().unwrap(); x_sq_vec.push(x * &x); x_inv_sq_vec.push(x_inv * &x_inv); allinv = allinv * &x_inv; } // Compute s values inductively. Here adpots optimization from Dalek. let mut s: Vec<G::Fr> = Vec::with_capacity(n); s.push(allinv); for i ...
Rust
0
tring::from("Root")); let navbar = self.generate_navbar(breadcrumb, list_key); data += &format!(r#"<tr><td><a href="../{}">..</a></td></tr>"#, list_key); data += &self .prefixes .iter() .map(|(key, _)| { format!( ...
Rust
0
), String(String, String), None, } impl CompareValues { pub fn compare(&self) -> Option<std::cmp::Ordering> { match self { CompareValues::Ints(left, right) => Some(left.cmp(right)), _ => None, } } } use hone::expression::*; use hone::query::*; use crate::query::...
Rust
0
=1, z_center=1) Car_res = res['detail'][cls] for k in Car_res.keys(): print(k, Car_res[k]) # cared_result.append(Car_res['3d@0.50'][1]) log_.info(str(Car_res)) print('\n') # log_.info(str(cared_result)) return Car_res def do_repo3d_eval(logger,label_dir,det_d...
Python
1
} } } &VarInputPreproc::RandomFlipX{ref phases} => { if phases.contains(&phase) { for idx in 0 .. batch_size { let out_dim = self.tmp_dims[idx]; let out_len = out_dim.flat_len(); let bernoulli = self.rng.gen_range(0, 2); ...
Rust
0
[cfg(any(feature = "rustls", feature = "native-tls"))] pub fn from_conf(conf: crate::Config) -> Self { let client = aws_hyper::Client::https(); Self { handle: std::sync::Arc::new(Handle { client, conf }), } } } extern crate image; use image::{GenericImage, ImageBuffer}; use ...
Rust
0
syncing()).unwrap(); let _sync_info_sub = subscription.next_item().unwrap(); assert!(true); } <filename>build/classes/visao/jasperreports-6.15.0/src/net/sf/jasperreports/engine/JRBoxPenProvider.rs net.sf.jasperreports.engine.JRBoxPenProvider use nalgebra::{DVector, Vector3}; pub fn vec_to_dvec(x: &Vec<f64>) ->...
Rust
0
rder_unconfirmed payment_txn_preauth.order = order payment_txn_preauth.captured_amount = order.total.gross.amount payment_txn_preauth.total = order.total.gross.amount payment_txn_preauth.save(update_fields=["order", "captured_amount", "total"]) address_data = graphql_address_data invalid_postal...
Python
1
debug_state(&self, data: &(f64, f64)) -> DebugState { DebugState { display_name: self.short_type_name().to_string(), main_value: format!("{:?}", data), ..Default::default() } } } impl<T, W: Widget<T>> Annotated<T, W> { pub fn new( inner: W, m...
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
as!(i32, i64, u64, i128, u128, f64); one_way_as_check!(i32, f32); one_way_try!(u32, i8, u8, i16, u16, i32); one_way_as!(u32, i64, u64, i128, u128, f64); one_way_as_check!(u32, f32); one_way_try!(i64, i8, u8, i16, u16, i32, u32, u64); one_way_as!(i64, i128, u128); one_way_as_check!(i64, f32, f64); one_way_try!(u64, i...
Rust
0
e, 'value': current_value, 'tw20': df['tw20'].iloc[i], 'th200': df['th200'].iloc[i] }) return trades, equity_curve def analyze_enhanced_results(trades, equity_curve, df): """分析增强版策略结果""" print("\n" + "="*60) print("📊 QQQ策略 v1.6 真实市场宽度版 - 回测结果") prin...
Python
1
ly_fortune() fortune_y = 290 if streak > 0 else 240 draw_text_with_shadow(draw, (60, fortune_y), f"✨ 今日提醒: {fortune}", content_font, (138, 43, 226), (255, 255, 255), (1, 1)) # 紫色 # 创建励志语录区域 quote_y = 350 quote_card = create_rounded_rectangle((680, 16...
Python
1
nk.name + ' = ' + link.portMap + '\n' ' ' + link.subNetName + '.netInput.' + link.name + '.mInitialNodeMap = map_' + link.subNetName + '_' + link.name + '\n' '\n') r = r + ( '\n' '# This is the all-in-one call to configure and finalize this super-network and updated the link\n' '# c...
Python
1
ight = widgetContainer.offsetHeight; currentX = Math.max(0, Math.min(currentX, viewportWidth - widgetWidth)); currentY = Math.max(0, Math.min(currentY, viewportHeight - widgetHeight)); xOffset = currentX; y...
Python
1
""Create a unique label for each user based on their username.""" return hash(username) # Create a label based on the username hash def on_pin_created(self, instance): """Handle the PIN input and combine it with the private key (pk).""" sk = self.pin_input.text.strip() if len(sk) !...
Python
1
# **************************************************************************** # # # # ::: :::::::: # # users.py :+: :+: :+: ...
Python
1
self.assertTrue(df.equals(df_base)) def check_compute_op_per_rank_stats_by_opname_data_when_given_cluster_data(self): query = f"select * from {ComputeOpSum.TABLE_PER_RANK_STATS_BY_OPNAME}" df = pd.read_sql(query, self.conn) df_base = pd.read_sql(query, self.conn_base) self.ass...
Python
1
unbounded(); let (_, server, _) = server::new(nodes_addr[0], msg_tx, spread::Spreader::Default, mempool.clone()).unwrap(); // Fake let port = p2p_addr.port(); let key_pair = Arc::new(key_pair::random()); // Fake let account = Arc::new(Account::new(port, key_pair.clone())); // Fake let (_, transa...
Rust
0
From<&'a mut SystemContext<'_>> for TaskContext<'a> { fn from(cx: &'a mut SystemContext<'_>) -> Self { TaskContext { world: cx.world, res: cx.res, spawner: cx.spawner, assets: cx.assets, scope: &*cx.scope, #[cfg(feature = "visible")] ...
Rust
0
t will generate code for a "target" /// machine; otherwise "target" will coincide with "host". /// /// Hence Rust's `host` corresponds to Gnu autotools' "build" and Rust's /// `target` corresponds to their "host" (though the relevant names will sometimes /// differ slightly). /// /// The `host` and `target` methods on ...
Rust
0
::*; #[derive(Debug, Clone)] pub struct Module { pub sections: Vec<Section>, } /// Just a marker; does not save the size itself since that changes during transformations anyway. #[derive(Debug, Clone)] pub struct WithSize<T>(pub T); /// Just a marker to indicate that parallel decoding/encoding is possible #[deri...
Rust
0
refinement.push(r); i += 1; } if let Some(r) = rhs_remnant { refinement.push(r); j += 1; } while i < end_i { refinement.push(self.partitions[i]); i += 1; } while j < end_j { refinement.pus...
Rust
0
import cv2 import numpy as np import json def undistort_points(image_points, mtx, dist): image_points = np.array(image_points, dtype=np.float32) image_points = image_points.reshape(-1, 1, 2) undistorted_points = cv2.undistortPoints(image_points, mtx, dist, None, mtx) return undistorted_points.reshape(-...
Python
1
{ &rook_moves } } #[inline(always)] pub fn get_bishop_moves() -> &'static[BitBoard; 5248] { unsafe { &bishop_moves } } #[inline(always)] pub fn get_rook_mob() -> &'static[u8; 102400] { unsafe { &rook_mob } } #[inline(always)] pub fn get_bishop_mob() -> &'static[u8; 5248] { unsafe { &bishop_mob } } #[in...
Rust
0
from stelarys.src.utiles.imports import * minecraft_color_codes = { '0': '\033[30m', '1': '\033[34m', '2': '\033[32m', '3': '\033[36m', '4': '\033[31m', '5': '\033[35m', '6': '\033[33m', '7': '\033[37m', '8': '\033[90m', '9': '\033[94m', 'a': '\033[92m', 'b': '\033[96m', 'c': '\033[91m', 'd': '\033[95...
Python
1
: RSAPublicKey, ) -> Result<String, ProviderFailure> { let mut rng = OsRng; let padding = PaddingScheme::new_oaep::<Sha1>(); let encrypted = match public_key.encrypt(&mut rng, padding, password.as_bytes()) { Err(error) => return Err(ProviderFailure::Other(error.to_string())), Ok(ok) => ok, ...
Rust
0
# # -------------------------------------------------------------------------- # Gurux Ltd # # # # Filename: $HeadURL$ # # Version: $Revision$, # $Date$ # $Author$ # # Copyright (c) Gurux Ltd # # --------------------------------------------------------------------------- # # ...
Python
1
import os import gc import arcpy from arcpy import env from arcpy.sa import * env.overwriteOutput = True gc.disable() arcpy.CheckOutExtension("Spatial") env.workspace = "GENERAL WORKSPACE" ##SET AS PARAMETER #Sum rasters #change projection #add color ramp i = 0 j = 1 k = 2 dsilist = arcpy.ListRasters("*scaled.tif"): ...
Python
1
e to sign' # signature with garbage byte at the end sig = (b'\x30\x2d\x02\x14\x1a\x6e\x40\x15\x68\xe5\xbd\x02\x65\xc2\x76\xf0\x97\x0a\xab' b'\x4a\xb0\xb6\xc8\x43\x02\x15\x00\x9f\x0b\x26\xa0\xbc\x40\xe4\x80\xae\x67\x1e' b'\xab\x1c\x69\x89\x45\xdf\x67\xa4\x47') self....
Python
1
parent_id = 202304120188 old_permission_overwrites = [ PermissionOverwrite(202304120189, target_type = PermissionOverwriteTargetType.user) ] old_position = 7 old_nsfw = False new_name = 'emotion' new_parent_id = 202304120190 new_permission_overwrites = [ PermissionOverwr...
Python
1
1.ranges(), it2.ranges()) } } // - moc pub struct CellCellRangeMOC2ToRangeMOC2< T: Idx, Q: MocQty<T>, I: CellOrCellRangeMOCIterator<T, Qty=Q>, U: Idx, R: MocQty<U>, J: CellOrCellRangeMOCIterator<U, Qty=R>, K: CellOrCellRangeMOC2ElemIt<T, Q, U, R, It1=I, It2=J>, L: CellOrCellRangeMOC2Iterator<T, Q, I, U, R, J...
Rust
0
_status: i32) -> ! { unsafe { libc::_exit(exit_status) } } pub(crate) fn getpid() -> io::Result<u32> { cvt(unsafe { libc::getpid() }).map(|pid| pid as u32) } pub(crate) fn kill(pid: u32, signal: i32) -> io::Result<()> { cvt(unsafe { libc::kill(pid as pid_t, signal as c_int) }).and(Ok(())) } pub(crate) fn killpg(...
Rust
0
# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT from ..connectivity import LabelConfig def test_LabelConfig_inputs(): input_map = dict( args=dict( argstr="%s", ), environ=dict( nohash=True, usedefault=True, ), in_config=dict( ...
Python
1
one_result = one.get(); println!("`one` value after `set`: {:?}", one_result); assert_eq!(one_result, Value::F32(1.0)); // Setting the values of globals can be done in two ways: // 1. Through an exported function, // 2. Using the Global API directly. // // We will use both for the `som...
Rust
0
"""Model mixins.""" from __future__ import annotations from typing import TYPE_CHECKING import numpy as np from maml.utils import DummyScaler if TYPE_CHECKING: from ._model import BaseModel class TargetScalerMixin: """Mixin class for models with target scaler.""" def __init__(self, *args, **kwargs):...
Python
1
, T2) where T0: IntoDelta, T1: IntoDelta, T2: IntoDelta, { fn into_delta(self) -> DeltaResult<Self::Delta> { Ok(( Some(self.0.into_delta()?), Some(self.1.into_delta()?), Some(self.2.into_delta()?), )) } } impl<T0, T1, T2, T3> Core for (T0, T1, ...
Rust
0
#!/usr/bin/env python """ Miscellaneous functions/objects used by Cheetah but also useful standalone. """ import os # Used in mkdirsWithPyInitFile. import sys # Used in die. ################################################## ## MISCELLANEOUS FUNCTIONS def die(reason): sys.stderr.write(reason...
Python
1
from datetime import timedelta from django.conf import settings from django.db import models from django.utils import timezone class PIIModel(models.Model): """Abstract base model for PII data synchronized between networks""" session_id = models.CharField(max_length=100, db_index=True) data_expires_at =...
Python
1
irection pub fn reverse(&self) -> Heading { match self { Heading::East => Heading::West, Heading::South => Heading::North, Heading::West => Heading::East, Heading::North => Heading::South, } } } impl Step { /// Parse a vector of steps from an ...
Rust
0
Freeman-Roommate-Is-Arriving.wav"}} }, "data_template": {"message": "Test 123 {{ 2 + 2 }}\n"}, } await async_setup_component( hass, "script", {"script": {"test": {"sequence": step}}} ) await hass.services.async_call("script", "test") await hass.async_block_till_done() ass...
Python
1
) -> (C, GpioPin<Input<T>>) { let m = ManuallyDrop::new(self); let ch = unsafe { ptr::read(&m.ch) }; let pin = unsafe { ptr::read(&m.pin) }; (ch, pin) } pub async fn wait(&self) { let index = self.ch.number(); CHANNEL_SIGNALS[index].wait().await; } pub f...
Rust
0
url::Position; // Resolve URL to a host and port #[cfg(feature = "socks")] let to_addr = || { let addrs = url .socket_addrs(|| match url.scheme() { "socks5" | "socks5h" => Some(1080), _ => None, }) ...
Rust
0
fluxguidance = NODE_CLASS_MAPPINGS["FluxGuidance"]() fluxguidance_26 = fluxguidance.append(guidance=30, conditioning=get_value_at_index(cliptextencode_23, 0)) imageandmaskresizenode = NODE_CLASS_MAPPINGS["ImageAndMaskResizeNode"]() imageandmaskresizenode_58 = imageandmaskresizenode.resi...
Python
1
import csv with open("TP5/contacts.csv", "r") as file: reader = csv.DictReader(file) for row in reader: print(f"Nom: {row['Nom']}, Age: {row['Age']}, Ville: {row['Ville']}")
Python
1
4D", "rgb": [122, 46, 77], "hsl": [-17, 115, 84], "shade": "Red" }, { "name": "<NAME>", "hex": "FFFAF0", "rgb": [255, 250, 240], "hsl": [28, 255, 247], "shade": "White" }, { "name": "Foam", "hex": "D0EAE8", "rgb": [208, 234, 232], "hsl": [124, 97, 221], "shade...
Rust
0
s /// any 16-bit character code. (Since the Unicode code space extends only to U+1FFFFF, a potential /// conflict exists only for characters U+0000 to U+001F, which are non-printing control /// characters.) This means that the determination as to whether a particular 16-bit value is a /// standalone character code or t...
Rust
0
.zip(iter_a) .enumerate() .for_each(|(_, (c_slice, a_slice))| { c_slice.iter_mut().enumerate().for_each(|(col, c)| { *c = a_slice .iter() .enumerate() .map(|(index, addr)| *addr * m_b[RM!(index, col as usize...
Rust
0
impl Environment { pub fn from_env() -> &'static Self { static ENV: OnceCell<Environment> = OnceCell::new(); ENV.get_or_init(|| Self::read_env().unwrap()) } fn read_env() -> Result<Self> { let json_rpc_url = env::var(JSON_RPC_URL)?; let coffer = env::var(FAUCET_URL) ...
Rust
0
> </EX_GeographicBoundingBox> <BoundingBox CRS="EPSG:4326" minx="-90.0" miny="-180.0" maxx="90.0" maxy="180.0"/> </Layer> </Capability> </WMS_Capabilities>"#, wms_url = wms_url, workflow = workflow_id, srs_authority = spatial_reference.authority(), srs...
Rust
0
:rtype: str """ return self._Remark @Remark.setter def Remark(self, Remark): self._Remark = Remark def _deserialize(self, params): self._NationCountryName = params.get("NationCountryName") self._NationCountryInnerCode = params.get("NationCountryInnerCode") ...
Python
1
0/?method=artist.getinfo&artist={}&api_key={}&format=json",artist, std::env!("FM_KEY"))).await? .json().await?; Ok(FmArtist{ bio: result.artist.bio.summary, tags: result.artist.tags.tag.into_iter().map(|t| t.name).collect::<Vec<_>>(), similar: result.artist.similar.artist.into_iter().map...
Rust
0
# This file is not meant for public use and will be removed in SciPy v2.0.0. # Use the `scipy.sparse` namespace for importing the functions # included below. import warnings from . import _spfuncs __all__ = [ # noqa: F822 'isspmatrix_csr', 'csr_matrix', 'isspmatrix_csc', 'csr_count_blocks', 'estimate_blocks...
Python
1
from math import * def main(): n = int(input()) a = [[0]*n for _ in range(n)] st = 0 for i in range(n): x = input().split() for j in range(n): a[i][j] = int(x[j]) if i!=j: st += int(x[j]) so = 0 for i in range(n): for j in range(i,n...
Python
1
Deserialize, Deserializer, Serializer}; pub fn serialize<S: Serializer>(x: &Scalar, s: S) -> Result<S::Ok, S::Error> { let bytes = x.to_bytes(); if s.is_human_readable() { s.serialize_str(&hex::encode(&bytes)) } else { s.serialize_bytes(&bytes) } } pub fn deserialize<'d, D: Deserialize...
Rust
0
# Copyright (c) 2023-2024, ETH Zurich (Robotics Systems Lab) # Author: Pascal Roth # All rights reserved. # # SPDX-License-Identifier: BSD-3-Clause from .path_follower_command_generator import PathFollowerCommandGenerator from .path_follower_command_generator_cfg import PathFollowerCommandGeneratorCfg from .path_foll...
Python
1
() # Create document repository repo = DocumentRepository(storage_dir=args.storage_dir) # Force refresh index if requested if args.refresh_index: repo.build_index(refresh=True) # List topics if requested if args.list_topics: topics = repo.get_topics() print...
Python
1
rmission_identity { fn test<'ctx>(#subject_var_name: &Self::Subject, #resource_var_name: &Self::Resource, #context_var_name: Self::Context<'ctx>) -> dacquiri::prelude::AttributeResult<Self::Error> #subject_check_impl } }); } } }<reponame>XuhuaHuang/LearnRust /...
Rust
0