text
string
label_name
string
labels
int64
", err), ContentTypeError::UnknownEncoding => f.write_str("Unable to recognize encoding"), } } } impl From<mime::FromStrError> for ContentTypeError { fn from(err: mime::FromStrError) -> Self { ContentTypeError::Mime(err) } } <gh_stars>0 //! Endpoint to send join events to remote...
Rust
0
import tkinter as tk from tkinter import messagebox from converter import convert def convert_currency(): """ Handle the conversion request from the GUI. Retrieves input, calls the converter, and displays the result. """ try: amount = float(amount_entry.get()) base_currency = base_...
Python
1
FO.fields_by_name['shape'].message_type = tensorboard_dot_compat_dot_proto_dot_tensor__shape__pb2._TENSORSHAPEPROTO _COSTGRAPHDEF_NODE_OUTPUTINFO.fields_by_name['dtype'].enum_type = tensorboard_dot_compat_dot_proto_dot_types__pb2._DATATYPE _COSTGRAPHDEF_NODE_OUTPUTINFO.containing_type = _COSTGRAPHDEF_NODE _COSTGRAPHDEF...
Python
1
subset of the full list) ids_wanted: Vec<String>, currency_val: String, // TODO: we could cache this and only update it every few days rather than every startup? full_coin_list: Vec<CoinListResultItem>, } impl ProviderCoinGecko { // TODO: maybe this could be made generic with dyn and put so...
Rust
0
ust()` constructor to `HostMemoryAllocator` that uses Rusts `std::alloc` methods. Requires `host_allocator` feature. //! //! ### `naive_device_allocator` //! //! Adds a simple memory allocator `NaiveDeviceMemoryAllocator` that allocates memory for each resource separately. //! It should not be used in production applic...
Rust
0
modations in advance, especially when traveling to popular destinations like Tokyo, Kyoto, and Osaka during peak tourist seasons. Here are some reasons why booking ahead is a good idea: 1. **Availability**: Popular hotels and unique accommodations (like ryokans, traditional Japanese inns) can fill up quickly, espe...
Python
1
attribute(tags=tags, ruids=ruids, levels=levels, phases=phases) else: checker.exclude_by_attribute(tags=tags, ruids=ruids, levels=levels, phases=phases) if len(checker.check_func_list) == 0: st.warning("No rule functions found. It appears that you have filtered everything out.") ...
Python
1
# DEMORA TEMPO DEMAIS import math # Função para calcular a distância entre dois pontos def calcular_distancia(p1, p2): return math.sqrt((p2[0] - p1[0]) ** 2 + (p2[1] - p1[1]) ** 2) # Leitura da quantidade de flechas lançadas quantidadeFlechasLancadas = int(input()) # Verificar se a quantidade de flechas está de...
Python
1
} } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: u8) -> LPM_SCALER { match value { 0 => LPM_SCALER::_0000, 1 => LPM_SCALER::_0001, 2 => LPM_SCALER::_0010, 3 => LPM_SCALER::_0011, 4 => LPM_SCALER::_0100, ...
Rust
0
B_TEMPLATE", f"{script.IMDB_TEMPLATE_TXT}") LONG_IMDB_DESCRIPTION = is_enabled(environ.get("LONG_IMDB_DESCRIPTION", "False"), False) SPELL_CHECK_REPLY = is_enabled(environ.get("SPELL_CHECK_REPLY", "True"), True) MAX_LIST_ELM = environ.get("MAX_LIST_ELM", None) INDEX_REQ_CHANNEL = int(environ.get('INDEX_REQ_CHANNEL', LO...
Python
1
(operation_config.token_credential_resource()) .await .map_err(create::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version"...
Rust
0
mut src, mut dst, mut tex) = alloc_rw_2d_u32_rgba::<[u32; 4], Opaque> (&dev, &grid); for src in src.iter_mut() { *src = [1u32, 2, 3, 4, ]; } tex.import_all_packed(&src).expect("texture import"); launch(&dev, tex.as_ref(), &mut dst, &grid, |tex, vp| { let i = (vp.grid_id().x, vp.gri...
Rust
0
t_bc() { let mut r = Registers::new(); assert_eq!(r.get_bc(), 0u16); r.set_bc(0xF00F); assert_eq!(r.b, 0xF0); assert_eq!(r.c, 0x0F); assert_eq!(r.get_bc(), 0xF00F); } #[test] fn get_set_de() { let mut r = Registers::new(); assert_eq!(r.get_de...
Rust
0
max } => { match bids.iter().position(|bid| &bid.0 == key && bid.1 >= min) { Some(val) => { let zero_based_index = bids.len() - val - 1; if zero_based_index < *max { Some(zero_based_index) ...
Rust
0
_marker: PhantomData, }, ICC: ICC { _marker: PhantomData, }, ADC: ADC { _marker: PhantomData, }, E_COMP0: E_COMP0 { _marker: PhantomData, }, E_COMP1: E_COMP1 {...
Rust
0
s.detailed) if not products: logger.warning("No products found") return # Export data if args.export_json or (not args.export_csv and not args.quiet): scraper.export_to_json(args.export_json) if args.export_csv: ...
Python
1
etting = dict( videos_per_gpu=cfg.data.get('videos_per_gpu', 1), workers_per_gpu=0, # save memory and time num_gpus=len(cfg.gpu_ids), dist=distributed, seed=cfg.seed) data_loader_precise_bn = build_dataloader(precise_bn_dataset, ...
Python
1
WHERE artifact.sample_id = samples.sample_1_id AND artifact_kind.name = 'RENDERED_MODEL_GLB_COMPARISON_SAMPLE' LIMIT 1 ) sample_1_data ON samples.sample_1_id = sample_1_data.sample_id JOIN LATERAL ( SELECT artifact.sam...
Python
1
from django.http import JsonResponse from .models import (MedsDrug, MedsAgent, MedsAtc, MedsBg, MedsCountry, MedsDosage, MedsForm, MedsIngredient, MedsManufacturer, MedsName, MedsPresentation, MedsRegnum, MedsResparty, MedsRescountry, MedsStrength, MedsSubsidy) from collections...
Python
1
import pandas as pd import numpy as np # === Step 1: Load CSV and Clean Headers === file_path = "data/thursday_ransomware.csv" df_real = pd.read_csv(file_path, low_memory=False) # Strip whitespace from column names df_real.columns = df_real.columns.str.strip() # Show all column names print("\n📋 Available columns:")...
Python
1
optimizer_config = dict( _delete_=True, grad_clip=dict(max_norm=35, norm_type=2)) # learning policy lr_config = dict( policy='step', warmup='linear', warmup_iters=500, warmup_ratio=1.0 / 3, step=[16, 22]) checkpoint_config = dict(interval=1) # yapf:disable log_config = dict( interval=50, ...
Python
1
208, 224, 240); let src = _mm512_setr_ps( 1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11., 12., 13., 14., 15., 16., ); // A multiplier of 4 is word-addressing _mm512_mask_i32scatter_ps(arr.as_mut_ptr() as *mut u8, mask, index, src, 4); let mut expected = [0f32; 256]; ...
Rust
0
# # Copyright (c) 2023 Airbyte, Inc., all rights reserved. # from .source import SourceVantage __all__ = ["SourceVantage"]
Python
1
import psycopg2 conn = psycopg2.connect( host="1016F610577F391", port=5433, dbname="etl_bronze_db", user="airflow", password="airflow" ) cur = conn.cursor() cur.execute("SELECT * FROM bronze_products LIMIT 10;") print(cur.fetchall()) cur.close() conn.close()
Python
1
from django.contrib import admin from .models import Timetable, Unit, Subscription, PendingTransaction # Unit admin class UnitAdmin(admin.ModelAdmin): list_display = [ 'batch_id', 'unit_code', 'unit_name', 'year', ] # Timetable admin class TimetableAdmin(admin.ModelAdmin): ...
Python
1
j += 1; } j += 1; } let mut i = arr.len() - 1; j -= 1; while j >= 0 { if j < arr.len() as i32 { arr[j as usize] = arr[i]; } if arr[i] == 0 { j -= 1; if j < arr.len() as ...
Rust
0
cuc_time::Time::new_l2_time_4_3_init(1, 2, 3, 4, 10, 0, 0), 0x01020304, 39062500); test_to_timespec( cuc_time::Time::new_l2_time_4_0_init(1, 2, 3, 4), 0x01020304, 0); test_to_timespec( cuc_time::Time::new_l2_time_4_1_init(1, 2, 3, 4, 5), 0x01020304, 19531250); t...
Rust
0
2C_PRD_P_PH_1_R { type Target = crate::FieldReader<u8, u8>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `cr_i2c_prd_p_ph_1` writer - "] pub struct CR_I2C_PRD_P_PH_1_W<'a> { w: &'a mut W, } impl<'a> CR_I2C_PRD_P_PH_1_W<'a> { #[doc = r"Writes raw bits to...
Rust
0
Dollar #[serde(rename = "242")] N242, /// Forint #[serde(rename = "348")] N348, /// Franc Congolais #[serde(rename = "976")] N976, /// French Franc #[serde(rename = "250")] N250, /// Gibraltar Pound #[serde(rename = "292")] N292, /// Gourde #[serde(rename = "332")] N332, /// Guarani #[serde(rename =...
Rust
0
32_Graphics_Dxgi_Common'*"] #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Dxgi_Common"))] pub struct DXGI_SWAP_CHAIN_DESC1 { pub Width: u32, pub Height: u32, pub Format: Common::DXGI_FORMAT, pub Stereo: super::super::Foundation::BOOL, pub SampleDesc: Common::DXGI_SAMPLE_DESC, ...
Rust
0
fn index_index_test() { test(template_json(), "$..book[2].isbn", vec![ &json!("0-553-21311-3"), ]); } #[test] fn index_unit_index_test() { test(template_json(), "$..book[2,4].isbn", vec![ &json!("0-553-21311-3"), ...
Rust
0
); self.rewards.push(reward); } } use clap::{App, Arg}; use std::{ env::current_dir, path::Path, }; use std::fs::OpenOptions; use std::io::{Read, Write}; use ::json2pb::{ Result, pbgen, parser, }; fn main() -> Result<()> { let cmd_opt = cmd_args(); let source_code = read_file(&c...
Rust
0
import networkx as nx # Create a directed graph G = nx.DiGraph() # Edges along with their capacities (maximum passengers) G.add_edge('A', 'B', capacity=30) G.add_edge('A', 'C', capacity=20) G.add_edge('B', 'C', capacity=10) G.add_edge('B', 'D', capacity=20) G.add_edge('C', 'D', capacity=20) # Define the source and s...
Python
1
for parameter in &self.parameters { parameter.write(&mut writer); } writer.push(b']'); } /// syncAccuracy must be 0 if isSynced is false pub fn timeQuality(tzKnown: bool, isSynced: bool, syncAccuracy: u64) -> StructuredDataElement<'a> { debug_assert!(isSynced && syncAccuracy != 0, "syncAccurac...
Rust
0
] array".to_string()))?; let spot_col = marketdata .column(schema.index_of("spot")?) .as_any() .downcast_ref::<Float64Array>() .ok_or_else(|| ArrowError::ParseError("Expects an float array".to_string()))?; let vol_col = marketdata .column(sch...
Rust
0
> Result<DiscordBot, GenericError> { let http = Http::new_with_token(config.token.as_str()); let (owners, bot_id) = match http.get_current_application_info().await { Ok(ini) => { let mut owners = HashSet::new(); if let Some(team) = ini.team { owners.insert...
Rust
0
.x.inner() * MULT) as i32 + SHIFT) as u16)?; ser.serialize_u16(((val.y.inner() * MULT) as i32 + SHIFT) as u16) } pub fn deserialize<'de>(de: &mut Deserializer<'de>) -> Result<Accel, DeError> { let x: f32 = (((de.deserialize_u16()? as i32) - SHIFT) as f32) / MULT; let y: f32 = (((de.deserialize_u16()? as i32) - ...
Rust
0
o ig@sTddlZddlmZddlZddlmZddlmZd ddZe d kr(edSdS) N)Path) __version__) get_includereturncCst}|jddtdd|jdddd|jd dd d|}tjd ds,||jr6t d t |j rLt t d d...
Python
1
#!/usr/bin/env python3 """ Module for concatenating two strings. """ def concat(str1: str, str2: str) -> str: """ Concatenate two strings. Params: str1 (str): The first string. str2 (str): The second string. Returns: str: The concatenated string. """ return str1 + str2
Python
1
seven opcodes that take indirect variable references (inc, dec, inc_chk, dec_chk, // load, store, pull), an indirect reference to the stack pointer does not push or pull the top // item of the stack - it is read or written in place. ReadWriteTopOfStack, Local(Local), Global(Global), } impl Variabl...
Rust
0
#to recompile the code #small optimization to cut down compilation time f = codecs.open( fpath, 'rb', encoding ) fcontent = f.read() f.close() if fcontent == fcontent_new: writer_t.logger.debug( 'file was not changed( content ) - do...
Python
1
form a similarity query. #[args(limit = 10, batch_size = "None")] fn word_similarity( &self, py: Python, word: &str, limit: usize, batch_size: Option<usize>, ) -> PyResult<Vec<PyObject>> { let embeddings = self.embeddings.read().unwrap(); let embeddin...
Rust
0
False elif isinstance( parameter, IECore.ClassVectorParameter ) : if "_classNames_" not in data: return False classNameFilter = "*" try : classNameFilter = parameter.userData()["UI"]["classNameFilter"].value except : pass if classNameFilter != data["_classNameFilter_"].value: return...
Python
1
; Ok(()) } #[test] fn date_proto_get_date_call() -> Result<(), Box<dyn std::error::Error>> { let mut engine = Context::new(); let actual = forward_val( &mut engine, "new Date(2020, 06, 08, 09, 16, 15, 779).getDate()", ); assert_eq!(Ok(Value::Rational(08f64)), actual); let act...
Rust
0
. InOutPowi(i32), /// Causes the [`Tween`] to start slow and speed up. A higher /// value causes the [`Tween`] to speed up more dramatically. /// /// This is similar to [`InPowi`](Easing::InPowi), but allows /// for float intensity values at the cost of being more /// CPU intensive. InPowf(f64), /// Causes the...
Rust
0
# coding: utf-8 """Provides template rendering, using Python standard template engine.""" import shutil import string from typing import Any, Dict from pathlib import Path from buildchain import types from buildchain import utils from . import base # In order to drastically reduce the escaping needs ($ is no fun...
Python
1
32_UI_TabletPC\"`*"] pub const IRM_None: InkRecognitionModes = 0i32; #[doc = "*Required features: `\"Win32_UI_TabletPC\"`*"] pub const IRM_WordModeOnly: InkRecognitionModes = 1i32; #[doc = "*Required features: `\"Win32_UI_TabletPC\"`*"] pub const IRM_Coerce: InkRecognitionModes = 2i32; #[doc = "*Required features: `\"W...
Rust
0
"""Send the evaluation metrics to the result server. Args: metrics (dict): The evaluation metrics. Returns: dict: The response from the server. """ try: context = get_current_context() params = context['params'] model_id = pa...
Python
1
aceSymbol { Clause { items: Vec<ClauseItem>, }, Star { location: Location, namespace_ref: Reference, }, } #[derive(Debug, Clone)] pub struct Catch { pub location: Location, pub binding: Option<Binding>, pub body: Vec<Stmt>, } #[derive(Debug, Clone)] pub struct Final...
Rust
0
i8 = 25; /// Map of objects entry type header pub const OBJECT_MAP_ENTRY: i8 = 26; /// Binary wrapper type header pub const BINARY_OBJECT: i8 = 27; /// Decimal type header pub const DECIMAL: i8 = 30; /// Decimal array type header pub const DECIMAL_ARRAY: i8 = 31; /// Timestamp type header pub const TIMESTAMP: i8 ...
Rust
0
import datetime from typing import Iterator import timezones import functools use_test = False def run(lines: Iterator[str]): observations = [parse_line(line) for line in lines] stations = {station for (station, _) in observations} observations = { station: [ observation for (obs_station, observation) in o...
Python
1
# -*- coding: utf-8 -*- # @Time : 2023/3/13 14:57 # @Author : 蔍鸣霸霸 # @FileName: dy_rpc.py # @Software: PyCharm # @Blog :只因你太美 import json import asyncio import re import time import websockets from openpyxl import Workbook wb = Workbook() ws = wb.active ws.append(['live_data']) async def check_permit(websocke...
Python
1
Option<Vec<Order>> { let data: Vec<Vec<Order>> = ORDERS.iter().map(|v| v.value().clone()).collect(); if data.len() > 0 { Some(data.concat()) } else { None } } pub fn get_transaction(security_id: &String) -> Option<Vec<Transaction>> { if let Some(positions) = TRANSACTIONS.get(securi...
Rust
0
import contextlib import os import platform import shutil import sysconfig from pathlib import Path import setuptools from setuptools.command import build_ext PYTHON_INCLUDE_PATH_PLACEHOLDER = "<PYTHON_INCLUDE_PATH>" IS_WINDOWS = platform.system() == "Windows" IS_MAC = platform.system() == "Darwin" @contextlib.co...
Python
1
g_attr.yaml) which includes configuration settings for the 'wazuh-syscheckd' daemon. That is combined with the testing registry key to be monitored defined in the module. expected_output: - r'.*Sending FIM event: (.+)$' ('added', 'modified', and 'deleted' event...
Python
1
client=self.get_waiter_client(), resource_helper=self, wait_for_states=self.get_action_desired_states( self.module.params.get("action") ), ) OsManagementHubSoftwareSourceActionsHelperCustom = get_custom_class( "OsManagementHubSoftwareSourceActionsHelperC...
Python
1
"""delete view v_synthese_validation_forwebapp Revision ID: 6f7d5549d49e Revises: 9a9f4971edcd Create Date: 2022-01-03 15:36:45.053127 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = "6f7d5549d49e" down_revision = "7471f51011c8" branch_labels = None depends_on...
Python
1
er = send_message() st.session_state.messages.append({"role": "assistant", "message": answer}) st.chat_message("assistant").write(answer) st.session_state.user_voice_value = "" st.rerun() # 语音输入 vocie_result = voice_toolkit() # vocie_result会保存最后一次结果 if ( vocie_re...
Python
1
assert_eq!(literal.as_untrimmed_str(), triplet.extracted); assert_eq!(literal.as_str(), triplet.trimmed); assert_eq!(literal.span(), triplet.trimmed_span); } } } extern crate num_integer; #[derive(Debug)] #[cfg_attr(test, derive(PartialEq))] pub enum SpecPart<T> { Number(T), ...
Rust
0
let mut closest_dist = ::std::f64::INFINITY; for point in &points { let delta = [point[0] - sample_point[0], point[1] - sample_point[1]]; let new_dist = delta[0] * delta[0] + delta[1] * delta[1]; if new_dist < closest_dist { closest_dis...
Rust
0
ut() initial_layout = QGridLayout() self.print_matrix(transition_layout, p_matrix, 'Updated Transition Matrix: ') self.print_matrix(emission_layout, e_matrix, 'Updated Emission Matrix: ') self.print_matrix(initial_layout, i_matrix, 'Updated Initial Distribution: ') main_layout.ad...
Python
1
Ok(Some(T::parse(val)?)) } } <gh_stars>1-10 use crate::geo_builder; use crate::map; use std::collections::HashMap; pub fn run( entity_data: Vec<(map::quake::Entity, geo_builder::entity::Geometry)>, ) -> ( Vec<(map::quake::Entity, geo_builder::entity::Geometry)>, HashMap<String, Vec<geo_builder:...
Rust
0
import secrets import string from fastapi import FastAPI, Query, HTTPException from fastapi.staticfiles import StaticFiles app = FastAPI() from fastapi.middleware.cors import CORSMiddleware app.add_middleware( CORSMiddleware, allow_origins=["*"], # Adjust as needed for production allow_credentials=True,...
Python
1
)) }; module_source_code.push_str(&body); let end = format!("\"##\n}}\n"); module_source_code.push_str(&end); } } } } } let mut module_source_code = String::n...
Rust
0
, stringify!(cl_float8), "::", stringify!(s) ) ); assert_eq!( unsafe { &(*(::std::ptr::null::<cl_float8>())).v2 as *const _ as usize }, 0usize, concat!( "Offset of field: ", stringify!(cl_float8), "::", ...
Rust
0
ne, Copy)] struct RawOverwrite { room_id: Snowflake, user_id: Option<Snowflake>, role_id: Option<Snowflake>, deny: u64, allow: u64, } impl From<RawOverwrite> for Overwrite { fn from(raw: RawOverwrite) -> Self { Overwrite { id: raw.user_id.or(raw.role_id).expect("No valid ID ...
Rust
0
self.shutdown_handler.setup_signal_handlers() return self async def __aexit__(self, exc_type, exc_val, exc_tb): """Exit the context manager.""" # Close all resources for resource in self.resources: try: if hasattr(resource, "close"): ...
Python
1
# SPDX-FileCopyrightText: 2021 Sandy Macdonald # # SPDX-License-Identifier: MIT # A simple example of how to set up a keymap and HID keyboard on Keybow 2040. # You'll need to connect Keybow 2040 to a computer, as you would with a regular # USB keyboard. # Drop the `keybow2040.py` file and `keybow_hardware` folder # ...
Python
1
str(name); let kind = c_str::raw_to_str(kind); let domain = c_str::raw_to_str(domain); let context = AvahiBrowserContext::from_raw(userdata); match event { avahi_sys::AvahiResolverEvent_AVAHI_RESOLVER_FAILURE => { context.invoke_callback(Err(format!( "failed to reso...
Rust
0
list1 = [12, 10, 13, 15, 8, 9] list2 = [12, 10, 13, 15, 8, 9] list3 = [12, 10, 13, 15, 8, 9] set1 = set(list1) while set1: set1.discard(max(set1)) print(set1, end=' ') print('\r') set2 = set(list2) while set2: set2.pop() print(set2, end=' ') print('\r') set3 = set(list3) for i in range(len(set3)...
Python
1
) speeq.durability_down(33) print(speeq.get_basic_status()) print(hero.get_cur_equipment()) cppr=Dart() cppr.max_durability=20 cppr.durability=20 for i in range(20): cppr.durability_down(1) print(cppr.get_basic_status()) print("Success\n") print("耐久度归0时自动破坏测试:\n") ...
Python
1
n = 0 cont = 0 while cont <= 10: cont += 1
Python
1
import random num = int(input("Enter the range : ")) list = [] for i in range(num): list.append(random.randint(1,10)) print(list)
Python
1
'a>>::arbitrary(u)) } #[inline] fn arbitrary_take_rest(mut u: Unstructured<'a>) -> Result<Self> { let mut array = Self::arbitrary(&mut u)?; if let Some(last) = array.last_mut() { *last = Arbitrary::arbitrary_take_rest(u)?; } Ok(array) } #[inline] fn ...
Rust
0
for method2 in y: print('%.2f' % (pvalues[(method1,method2)][it]) + '\t',end='') print() elif by_=='experiment': y = {} for method in results: y[method] = [] for exp in results[method]: y[method].append(n...
Python
1
3_FF, 0x7_FF, 0xF_FF, 0x1F_FF, 0x3F_FF, 0x7F_FF, ); let mask = 0xFF_00; let actual_result = _mm256_maskz_popcnt_epi16(mask, test_data); let reference_result = _mm256_set_epi16(0, 1, 2, 3, 4, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0); assert_eq_m256i(actual_result, reference_re...
Rust
0
i in range(num_labels): # 获取当前超像素的掩码 mask = np.zeros_like(labels, dtype='uint8') mask[labels==i] = 1 mean = np.mean(img[labels==i], axis=0) std = np.std(img[labels==i], axis=0) features[i, 0:img.shape[2]] = mean features[i, img....
Python
1
_test; /// Endpoints in DHCP tests are either /// 1. attached to the server stack, which will have DHCP servers serving on them. /// 2. or attached to the client stack, which will have DHCP clients started on /// them to request addresses. enum DhcpTestEnv { Client, Server, } struct DhcpTestEndpoint<'a> { ...
Rust
0
ed_depth.get_data()) rgb_image = np.asanyarray(color_frame.get_data()) # 获取深度相机内参 current_depth_intrin = filtered_depth.profile.as_video_stream_profile().intrinsics current_depth_scale = depth_scale if depth_scale is not None else depth_fr...
Python
1
**1TYY;+.tvv;tyy+@BBH&,  ii/12 r3c$URU5$)Nr)r<rs r1rinterp1d._call_spline||E""r3cNURU5n[RUS'U$)N.rrZr)...
Python
1
'a, Dom>) -> Result<ResolveFn<'a, Dom>, VarWatch> { let a = resolve_1(&self.a, state)?; let assert = self.f.clone(); Ok(Box::new( move |state| if assert(&*a) { Some(state) } else { None }, )) } } impl<'a, A: Debug> Debug for Assert1<'a, A> { fn fmt(&self, f: &mut fmt...
Rust
0
sum_uvw = u + v + w u = u / sum_uvw v = v / sum_uvw w = w / sum_uvw v0 = vertices[faces[:, 0], :] v1 = vertices[faces[:, 1], :] v2 = vertices[faces[:, 2], :] v0 = v0[weighted_random_indices] v1 = v1[weighted_random_indices] v2 = v2[weighted_random_indices] sampled_v = (v0 ...
Python
1
cal_input_operand, "other": physical_other_operand, "output": physical_output} if "bias" in self.node.kwargs and self.node.kwargs["bias"] is not None: # check if the other operand is a parameter if isinstance(self.node.kwargs["bias"]._meta_data, torch.nn.parameter.Parameter): ...
Python
1
) -> c_int; fn af_rank(rank: *mut c_uint, input: AfArray, tol: c_double) -> c_int; fn af_det(det_real: MutDouble, det_imag: MutDouble, input: AfArray) -> c_int; fn af_norm(out: MutDouble, input: AfArray, ntype: uint8_t, p: c_double, q: c_double) -> c_int; } /// Perform Singular Value Decomposition /// /// ...
Rust
0
{ let this = self.eval_context_mut(); trace!("miri_start_panic: {:?}", this.frame().instance); // Get the raw pointer stored in arg[0] (the panic payload). let &[payload] = check_arg_count(args)?; let payload = this.read_scalar(payload)?.check_init()?; let thread = thi...
Rust
0
from app.core.security.password import get_password_hash, verify_password def test_hashed_password_is_verified() -> None: pwd_hash = get_password_hash("my_password") assert verify_password("my_password", pwd_hash) def test_invalid_password_is_not_verified() -> None: pwd_hash = get_password_hash("my_pass...
Python
1
Abort::SubsystemError(err)) => { tracing::warn!( target: LOG_TARGET, err = ?err, "Shutting down Network Bridge due to error" ); Err(SubsystemError::Context(format!( "Received SubsystemError from overseer: {:?}", err ))) } Err(UnexpectedAbort::EventStreamConcluded) => { tracing::i...
Rust
0
let rel_id = buf.read_u32::<BigEndian>()?; let namespace = buf.read_cstr()?; let name = buf.read_cstr()?; let replica_identity = match buf.read_u8()? { REPLICA_IDENTITY_DEFAULT_TAG => ReplicaIdentity::Default, REPLICA_...
Rust
0
import datetime import uuid import sqlalchemy as sa from sqlalchemy import orm from sqlalchemy.dialects.postgresql import ARRAY, UUID, JSONB from sqlalchemy.sql import func @orm.as_declarative() class Base: __tablename__: str id: orm.Mapped[uuid.UUID] = orm.mapped_column(UUID(as_uuid=True), primary_key=True,...
Python
1
= input.parse()?; let struct_token = input.parse()?; let ident = input.parse()?; let content; let brace = braced!(content in input); let fields = content.parse_terminated(Field::parse_named)?; let mut setters = vec![]; let mut fn_build_fields = vec![]; fo...
Rust
0
nome = "Alice" idade = 30 mensagem = f"Olá, meu nome é {nome} e eu tenho {idade} anos." print(mensagem) # Neste exemplo, as variáveis nome e idade são incorporadas na string usando f-strings, e o resultado seria:
Python
1
nvBind { inv_bind_idx: term.inv_bind_idx }; mat *= term.weight; acc += mat } let mat_idx = self.add_matrix(acc); self.cur_matrix = mat_idx; } // NOTE: Ignored for now, which is incorrect, but they IME don't end up // affecting the final skeleton (because the...
Rust
0
DisequalityConstraint::new(ws); walked_cstore.insert(c); } } walked_cstore } /// Add new constraint `c` while keeping the store normalized pub fn push_and_normalize(&mut self, newc: Rc<dyn Constraint<U, E>>) { if let Some(tree_newc) = newc.downcast_ref::...
Rust
0
EGs") axis.set_ylabel("$E[r^2]$ on DEGs") axis.set_xlabel("Dosage in $\mu$M") axis.set_xscale("log") ax[0, 2].legend( title="Model type", fontsize=18, title_fontsize=24, loc="lower left", bbox_to_anchor=(1, 0.2), ) plt.tight_layout() if SAVEFIG: if BLACK: plt.savefig( ...
Python
1
@testing.numpy_cupy_allclose(atol=1e-5) def test_around_positive2(self, xp): a, decimals = self.value a = xp.asarray(a) return xp.around(a, decimals) @testing.numpy_cupy_allclose(atol=1e-5) def test_around_negative1(self, xp): a, decimals = self.value return xp.a...
Python
1
} hit } } */ use crate::selectors; use crate::CLICKED; use super::*; #[derive(Debug)] pub struct Button { pub(crate) label: String, loc: Loc, } impl Button { #[track_caller] pub fn new(text: impl Into<String>) -> Button { Button { label: text.into(), loc:...
Rust
0
ng(Error::DecodeHash)) } async fn is_block_stored(&self, hash_le: Vec<u8>) -> Result<bool, CoreError<Error>> { let head = self .rpc .get_block_header(H256Le::from_bytes_le(&hash_le)) .await .map_err(|e| CoreError::Issuing(Error::PolkaBtcError(e)))?; ...
Rust
0
K2 = 2, #[doc = "3: Generic clock generator 3"] GCLK3 = 3, #[doc = "4: Generic clock generator 4"] GCLK4 = 4, #[doc = "5: Generic clock generator 5"] GCLK5 = 5, #[doc = "6: Generic clock generator 6"] GCLK6 = 6, #[doc = "7: Generic clock generator 7"] GCLK7 = 7, #[doc = "8: G...
Rust
0
#!/usr/bin/env python3 """Verify the demo user account.""" import asyncio import asyncpg import os from dotenv import load_dotenv load_dotenv() async def verify_demo_user(): """Mark demo user as verified.""" db_url = os.getenv( "DATABASE_URL", "postgresql://loganalyzer:password@localhost:5432/loganal...
Python
1
showerror( self.ui_languages[self.current_ui_lang]['error'], self.ui_languages[self.current_ui_lang]['recording_error'].format(str(e)) ) self.is_recording = False self.record_button.configure(text=self.ui_languages[self.current_ui_lang]['start_record']...
Python
1