text
string
label_name
string
labels
int64
{ unsafe { *EXECUTOR = &exec as *const (); } } pub fn create_task<E: GlobalExec>(exec: &E) { } } //! # EEP: EEP Embeddable Profiler //! //! TODO FITZGEN: more docs here #![deny(missing_debug_implementations)] #![deny(missing_docs)] // extern crate leb128; pub mod ring_buffer...
Rust
0
perf_monitor.start_timer("complex_matching") K = build_matching_graph(odd, dist) maxw = max((data['weight'] for _, _, data in K.edges(data=True)), default=0.0) for _, _, data in K.edges(data=True): data['wtrans'] = maxw - data['weight'] if start is None or start not in odd: if start...
Python
1
push_column(read_u16(&rgce[6..8]) as u32, &mut formula); formula.push('$'); formula.push_str(&format!("{}", read_u16(&rgce[2..4]) as u32 + 1)); formula.push(':'); formula.push('$'); push_column(read_u16(&rgce[8..10]) as u32, &mut formu...
Rust
0
)); } } } } all_rel_paths }) } fn hash_file_content(hash: &mut Digest, path: &Path, stat: &Metadata) -> Result<(), io::Error> { if stat.file_type().is_file() { let mut file = try!(File::open(&path)); try!(hash.stream(&mut file)...
Rust
0
ode error: {}", source))] BsonDecodeError { source: bson::DecoderError, }, #[snafu(display("mongo error: {}", source))] MongoError { source: mongodb::Error, }, // insert error InsertError, /// update error UpdateError, #[snafu(display("generic error: {}", desc...
Rust
0
(None), OktaUserGroupMember.ended_at > ownership_time_limit_from_now, ) ).update( {OktaUserGroupMember.ended_at: ownership_time_limit_from_now}, synchronize_session="fetch", ) # Reduce all role ownerships for the giv...
Python
1
# -*- coding: utf-8 -*- """ Created on Sun Jun 2 17:56:58 2024 @author: CNN-Visualization """ # load vgg modela from keras.applications.vgg19 import VGG19 # load the model model=VGG19() # summarize the model model.summary() # show the layer numbers # n=0 # # for layer in model.layers: # # print(n,layer.name) # #...
Python
1
}; use crate::{memory::global::Global, private::Private}; use jl_sys::{ jl_array_typename, jl_llvmpointer_typename, jl_namedtuple_typename, jl_pointer_typename, jl_tuple_typename, jl_type_typename, jl_typename_t, jl_typename_type, jl_vecelement_typename, }; use std::{marker::PhantomData, ptr::NonNull}; /// Des...
Rust
0
&self.activation.forward(&self.label_head.forward(&hidden))?, train, )?; // From from these representations, compute the label score matrix. let relation_score_logits = self .bilinear_label .forward(&label_head, &label_dependent)? // ...
Rust
0
Ok(aws_smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_crate_operation_describe_replace_root_volume_tasks( input: &crate::input::DescribeReplaceRootVolumeTasksInput, ) -> Result<aws_smithy_http::body::SdkBody, aws_smithy_http::operation::SerializationError> { let mut out = String::new(...
Rust
0
usize { encoding_rs::mem::utf8_latin1_up_to(::std::slice::from_raw_parts(buffer, len)) } /// Returns the index of first byte that starts a non-Latin1 byte /// sequence, or the length of the string if there are none. /// /// # Undefined behavior /// /// UB ensues if `buffer` and `buffer_len` don't designate a vali...
Rust
0
import os import json from datetime import datetime # Set the path to current directory, or specify an absolute path repo_path = '.' def generate_file_structure(repo_path): file_structure = {} for root, dirs, files in os.walk(repo_path): for file in files: if file.endswith('.json'): ...
Python
1
ude::*; #[wasm_bindgen(module = "./array")] extern "C" { fn topArray() -> f64; fn getNumber() -> i32; fn lowerCase(str: &str) -> String; } #[wasm_bindgen] pub fn sum_of_square_root() -> f64 { let n = getNumber(); let mut sum = 0; for _ in 0..n { sum = sum + (topArray().sqrt() as i64);...
Rust
0
T: ToOwned<Owned = U> + ?Sized, T::Owned: BorshDeserialize, { fn deserialize(buf: &mut &[u8]) -> Result<Self> { Ok(T::Owned::deserialize(buf)?.into()) } } #[cfg(feature = "rc")] impl<T, U> BorshDeserialize for Arc<T> where U: Into<Arc<T>> + Borrow<T>, T: ToOwned<Owned = U> + ?Sized, T::...
Rust
0
metric) runner_state = (train_state, env_state, last_obs, rng, prev_done) return runner_state, (metric, traj_batch.obs, traj_batch.action) if log_timestep_returns: runner_state, (metric, actor_obs, actor_actions) = jax.lax.scan( _update_step, runner_state, ...
Python
1
import os import mxnet as mx # path source_root = os.path.abspath(os.path.join(os.getcwd(), os.path.pardir)) data_root = os.path.join(source_root, 'IWSLT') model_root = os.path.join(source_root, 'IWSLT', 'model') log_root = os.path.join(source_root, 'IWSLT', 'log') if not os.path.exists(model_root): os.makedirs(m...
Python
1
signd_7() { run_test(&Instruction { mnemonic: Mnemonic::PSIGND, operand1: Some(Direct(XMM6)), operand2: Some(Direct(XMM1)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 56, 10, 241], OperandSize::Qword) } #[test] fn psignd...
Rust
0
#!/usr/bin/env python import sys import argparse parser = argparse.ArgumentParser(description= """ Reformat a space or tab separated file to have each column aligned by inserting the appropriate number of spaces E.g. from fc.enriched.bed 314660500 mc.enriched.bed 49501300 18811600 ...
Python
1
>, { pub fn new<G>(g: G) -> Self where G: GraphRef + Visitable<NodeId = N, Map = VM>, { DfsSpace { dfs: Dfs::empty(g) } } } impl<N, VM> Default for DfsSpace<N, VM> where VM: VisitMap<N> + Default, { fn default() -> Self { DfsSpace { dfs: Dfs { ...
Rust
0
in_id(false).unwrap(), "test-chain-id"); /// /// # } /// ``` /// /// Which will expand to: /// /// ```ignore /// impl CliConfiguration for Subcommand { /// fn base_path(&self) -> Result<Option<PathBuf>> { /// match self { /// Subcommand::Variant1(cmd) => cmd.base_path(), /// Subcomma...
Rust
0
:rustc-link-search=native=test"); } "#) .file("c/src/lib.rs", ""); assert_that(p.cargo_process("build").arg("-v"), execs().with_status(0).with_stdout(&format!("\ {compiling} c v0.5.0 ([..] {running} `rustc [..]` {running} `[..]` {running} `rustc [..]` {compiling} b v0.5....
Rust
0
d\xaay\ A\xc5KJE\xb7\x9b\xaeQ\x15!\xd4\xba\xefl\xa5\ \xbd\x94gU\xfa\x88\xb9\x95\xfb\xb4\xe6\xcb\xa1y\xe7\xef\ \xb8\x98\x03fm\x1c/N\x9a\x17\xfe\xfe<2`\x83\ \x22\xfdjc\x15g-ib\xa9\xe7O\xf9\x93\xff\xc2\ ?\x8d&\xc1NW\x80\x84<\xf3p\xae\x13@\x00\xc3\ \x0d\xe2\xeb\xbb\xf4vn\x13'\x09\xc3\xc1\x90N\xdaa\ \x7fs\x8b\xef}\xf8=\x16'...
Python
1
getFps', methods=['POST']) def getFPS(): try: log.info("START get FPS") req = request.json req = req[0] out = [] for data in req: videoPath = data["PATH"] fileName = data["FILE_NAME"] fps = getFps(videoPath) out.append({"PATH":...
Python
1
batch_box_preds, local_rois).reshape([-1, code_size]) batch_box_preds = rotate_points_along_z( batch_box_preds.unsqueeze(axis=1), roi_ry).squeeze(axis=1) batch_box_preds[:, 0:3] += roi_xyz batch_box_preds = batch_box_preds.reshape([batch_size, -1, code_size]) return batch_cl...
Python
1
ndom.randrange(arr.shape[0] - image_size + 1) crop_x = random.randrange(arr.shape[1] - image_size + 1) return arr[crop_y : crop_y + image_size, crop_x : crop_x + image_size] def random_crop_two_arr(pil_image, pil_label, image_size, min_crop_frac=0.8, max_crop_frac=1.0): assert pil_image.shape == pil_label...
Python
1
, HashMap}; use std::io::Write; use std::path::Path; use std::process::exit; const EXCLUDE_DEFAULT: [&str; 9] = [ r#"^\.git/"#, r#"(^|/)Cargo\.lock$"#, r#"\.dat$"#, r#"\.log$"#, r#"\.pcap$"#, r#"\.png$"#, r#"\.woff$"#, r#"\.woff2$"#, r#"^LICENSE$"#, ]; #[derive(Default, Deserialize...
Rust
0
_precision = precision_score(y_true, y_pred, average='macro', labels=labels_to_consider) macro_recall = recall_score(y_true, y_pred, average='macro', labels=labels_to_consider) macro_f1 = f1_score(y_true, y_pred, average='macro', labels=labels_to_consider) micro_precision = precision_score(y_tr...
Python
1
n", map_datatype); //println!("map_pto: {:?}\n\n", map_pto); // map_datatype 可以有多层嵌套,但我们得有个层数限制,并且防范环形引用 //println!("\nmap_datatype:"); for (_k, v) in map_datatype.iter() { let parentname = v.borrow_mut().name.clone(); for lineinfo in v.borrow_mut().members.iter_mut() { recu...
Rust
0
class Jugador: def __init__(self, nombre, edad, equipo): self.__nombre = nombre self.__edad = edad self.__equipo = equipo #Aquí usamos el metodo del encapsulamiento para que no varie el nombre , la edad y el equipo # Métodos 'get' para acceder a los atributos def get_nombr...
Python
1
ures_io::SeekFrom, ) -> Poll<futures_io::Result<u64>> { self.project().reader.poll_seek(cx, pos) } } <filename>src/api/domain/show_gluerecords.rs //! [Show domain information](https://api.gandi.net/docs/domains/#v5-domain-domains-domain) route binding use clap::{App, ArgMatches, SubCommand}; use reqwes...
Rust
0
} } impl ToSrc for ParseNodeKind { fn to_src(&self) -> Src { let ident = self.ident(); quote!(_P::#ident) } } quotable_to_src!(ParseNodeKind); impl ToSrc for ParseNodeShape<ParseNodeKind> { fn to_src(&self) -> Src { let variant = match self { ParseNodeShape::Opaque...
Rust
0
import os import aiobcrypt import base64 # Class that provides general utils. class GeneralUtils: def convert_object_id_to_str(self, object): object['id'] = str(object['_id']) del object['_id']
Python
1
let serialized = bincode::serialize(&msg).unwrap(); self.client_protocol.write(&serialized).await?; Ok(()) } } <filename>src/protos/trd_modify_order.rs<gh_stars>0 #[derive(Clone, PartialEq, ::prost::Message)] pub struct C2s { ///交易写操作防重放攻击 #[prost(message, required, tag="1")] pub packet_...
Rust
0
fF"2dZddlZddlZddlZddlZddlmZmZddlm Z gdZ ejejdjdZdZGd d eZeZd eed <d ZdZdZdZdZeedZdZeedZeedZddZ...
Python
1
pub fn search_in(&self, haystack: &[u8]) -> bool { self.inlined_search_in(haystack) } } /// Represents a generic SIMD register type. trait Vector: Copy { const LANES: usize; type Mask; unsafe fn splat(a: u8) -> Self; unsafe fn load(a: *const u8) -> Self; unsafe fn lanes_eq(a: Se...
Rust
0
let type // This is a placeholder to implement traits and methods. #[pallet::pallet] #[pallet::generate_store(pub(super) trait Store)] pub struct Pallet<T>(PhantomData<T>); // 3. Runtime Configuration Trait // All types and constants go here. // Use #[pallet::constant] and #[pallet::extra_constants] // to pass ...
Rust
0
pub fn sam_hdr_destroy(h: *mut sam_hdr_t); } extern "C" { #[doc = " Duplicate a header structure."] #[doc = "*!"] #[doc = "* @return A valid pointer to new header on success, NULL on failure"] #[doc = "*/"] pub fn sam_hdr_dup(h0: *const sam_hdr_t) -> *mut sam_hdr_t; } pub type samFile = htsFile...
Rust
0
. type Balance: Parameter + Member + AtLeast32Bit + Codec + Default + Copy + MaybeSerializeDeserialize + Debug; /// The minimum amount required to keep an account open. type ExistentialDeposit: Get<Self::Balance>; /// The means of storing the balances of an account. type AccountStore: StoredMap<Self::AccountId, ...
Rust
0
onses={ 403: _generic_descriptions.ERROR_403, 404: _generic_descriptions.ERROR_404, }, ) def get( clinical_programme_uid: Annotated[str, ClinicalProgrammeUID], ) -> ClinicalProgramme: service = ClinicalProgrammeService() return service.get_clinical_programme_by_uid(clinical_programme_uid...
Python
1
用户索引数据 UserOrderIndex::<T>::insert(&who,&user_order_index,order_index); //订单长度+1 OrderCount::<T>::put(order_index + 1); //用户索引个数+1 UserOrderCount::<T>::insert(&who,user_order_index + 1); //添加块高存储订单集合 let mut order_set = OrderSetOfBlock::<T>::get(&block_number).unwrap_or(Vec::<u64>::new()); order...
Rust
0
test_almost(0.3, 10, 0.1493083459, 1e-14, cdf(1)); test_case(0.3, 10, 1.0, cdf(10)); test_case(1.0, 1, 0.0, cdf(0)); test_case(1.0, 1, 1.0, cdf(1)); test_case(1.0, 3, 0.0, cdf(0)); test_case(1.0, 3, 0.0, cdf(1)); test_case(1.0, 3, 1.0, cdf(3)); test_case(...
Rust
0
logger.info(f"Пропуск прогноза для {symbol} на {timeframe}: тейк-профит слишком близко") return None message = ( f"📌 {symbol} {timeframe} | {position_type}\n" f"💰 Цена: ${entry_price:.3f}\n" f"📈 Точка входа: ${entry_range_max:.3...
Python
1
try!(write!(f, " rxfrq"))} if self.mmrq() != 0 { try!(write!(f, " mmrq"))} if self.sbkrq() != 0 { try!(write!(f, " sbkrq"))} if self.abrrq() != 0 { try!(write!(f, " abrrq"))} try!(write!(f, "]")); Ok(()) } } #[doc="Interrupt & status register"] #[derive(Default, Clone, Copy,...
Rust
0
from collections import deque from copy import deepcopy def solve(stacks): costs = {0: 5, 1: 8, 2: 1, 3: 6, 4: 8, 5: 2, 6: 1, 7: 8} initial_state = tuple(tuple(stack) for stack in stacks) queue = deque([(initial_state, [])]) visited = set([initial_state]) while queue: state, moves = queue...
Python
1
if !dts_file.exists() { let mut c = Command::new( Path::new(env!("CARGO_MANIFEST_DIR")) .join("node_modules") .join(".bin") .join("tsc"), ); c.arg(path) .arg("--jsx") .a...
Rust
0
import Euler import Euler_melhorado import Euler_ponto_medio import Original import matplotlib.pyplot as plt import numpy as np # PVI inicial = (1, 0) intervalo = (0, 5) # n_interaçoes passos = 10 # Obtendo valores de cada metodo Xval_Euler, Yval_Euler= Euler.Euler(inicial, intervalo, passos) Xval_Euler_M, Yval_Eule...
Python
1
import json import re from typing import Any, Dict def extract_and_inject_json(completion: Dict[str, Any]) -> Dict[str, Any]: """ Extracts the valid JSON portion from the 'content' field in the first choice's message of the completion object and injects the parsed JSON back into that message. This...
Python
1
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Изучить возможности модуля logging. Добавить для предыдущего задания вывод в файлы лога # даты и времени выполнения пользовательской команды с точностью до миллисекунды. import json import logging from datetime import datetime from pathlib import Path from validation ...
Python
1
closest_screwdriver = None closest_diff = float("inf") screw_shape = state.get(screw, "shape") for obj in state: if obj.type != self._screwdriver_type: continue if state.get(obj, "size") > 0.5: # Ignore non-graspable screwdrivers ...
Python
1
# # Copyright (C) 2020-2024 Intel Corporation # SPDX-License-Identifier: Apache-2.0 # import json from pathlib import Path import pytest def pytest_addoption(parser): parser.addoption("--data", action="store", help="data folder with dataset") parser.addoption( "--model_data", action="store", ...
Python
1
from django.urls import path, include from rest_framework.routers import DefaultRouter from .views import LogAcaoViewSet router = DefaultRouter() router.register('logs', LogAcaoViewSet, basename='logs') urlpatterns = [ path('', include(router.urls)), # O endpoint admin será acessível em /api/auditoria/logs/ad...
Python
1
map.insert(42, x); } assert_eq!(map.get(&42), Some(&29)); assert_eq!(map.len(), 31); assert_eq!(map.tree.nodes.len(), 31); map.clear(); } #[test] fn test_insert_2n_remove_n_random() { for k in 1..4 { let mut map: TreeMap<u32, u32> = Tree...
Rust
0
ment let top_left = *pattern4 .iter() .find(|c| ![middle, top_right, bottom_right].contains(c)) .unwrap(); // remaining = bottom middle segment let bottom_mid = *pattern0 .iter() .find(|c| ![top_left, top_mid, top_right, bottom_left, bottom_right].contains(c)) ...
Rust
0
pub struct Status(u8); impl Status { pub const AVALID: u8 = 0b0000_0001; pub const PVALID: u8 = 0b0000_0010; } impl_bitflags!(Status, STATUS); #[derive(Debug, Default)] pub struct GConfig4(u8); impl GConfig4 { pub const GMODE: u8 = 0b0000_0001; pub const GIE...
Rust
0
(&args[2]).unwrap(), _ => panic!("Not implemented") }; println!("Base: {}", base); println!("Extra: {}", extra); } <filename>datatypes/src/lib.rs // configure default clippy lints #![deny(clippy::correctness)] #![warn(clippy::complexity, clippy::style, clippy::perf, clippy::pedantic)] // disable s...
Rust
0
line.unwrap().parse::<i32>().unwrap(); sum += fuelneed(num); }); println!("Part 2: {}", sum); } pub mod hello_test; pub mod message_test;pub fn opcodes(numbers: &mut Vec<i32>) -> i32 { let mut idx: usize = 0; loop { if numbers[idx] == 99 { break; } let fir...
Rust
0
# Método Python String find() txt = 'Olá, Bem-vindo ao meu mundo' print(txt.find('mundo')) # Onde no texto é a primeira ocorrência da letra "e"?: texto = 'Hello, welcome to my word.' print(texto.find('e')) # Onde no texto é a primeira ocorrência da letra "e" quando Você só procura entre as posições 5 e 10?: texto2...
Python
1
#! /usr/bin/python # vim: tabstop=8 shiftwidth=8 expandtab # $Id: setup.py,v 1.9 2012/05/23 08:50:10 nanard Exp $ # the MiniUPnP Project (c) 2007-2017 Thomas Bernard # http://miniupnp.tuxfamily.org/ or http://miniupnp.free.fr/ # # python script to build the miniupnpc module under unix # # Uses MAKE environment variable...
Python
1
import os import shutil from loguru import logger from modules import site_config def clean_website_build(): """Clean content directory and remove output directory.""" # Clean content directory logger.info(f"Deleting content directory: {site_config.content_dir}") if os.path.isdir(site_config.content...
Python
1
lect find_in_set("Beijing", enname) from {self.tbname}') tdSql.checkData(0, 0, 1) tdSql.query(f'select find_in_set("Chaoyang", enname) from {self.tbname}') tdSql.checkData(0, 0, 2) tdSql.query(f'select find_in_set("Wangjing", enname) from {self.tbname}') tdSql.checkData(0, 0, 3) ...
Python
1
entry_out { nodeid: attr.ino, generation: generation, entry_valid: ttl.sec, attr_valid: ttl.sec, entry_valid_nsec: ttl.nsec, attr_valid_nsec: ttl.nsec, attr: fuse_attr_from_attr(attr), }, fuse_open_out { fh: fh, ...
Rust
0
from playwright.sync_api import Page from shiny.playwright import controller from shiny.pytest import create_app_fixture from shiny.run import ShinyAppProc app = create_app_fixture(["app-core.py", "app-express.py"]) def test_task_button_demo(page: Page, app: ShinyAppProc) -> None: page.goto(app.url) # Get ...
Python
1
] = T.load("float32", B_new, i1 * 17 + j) * 2.0 @T.prim_func def annotated_loops(a: T.handle) -> None: A = T.match_buffer(a, (16,), "float32") for i in range(0, 16, annotations={"pragma_1": "str_value", "pragma_2": 1, "pragma_3": 0.0}): A[i] = 0.0 def test_elementwise(): _check(compacted_element...
Python
1
), this is always `const fn`. #[inline] #[must_use] pub const fn const_new(v: MaybeUninit<$ty>) -> Self { Self { v: UnsafeCell::new(v), _align: [] } } } static_assert!(mem::size_of::<AtomicMaybeUninit<$ty>>() == mem::size_of::<$ty>()); ...
Rust
0
ns. Args: round_datum: Current round information Returns: get_attribute_matches: Information attributes """ user_annotation = ast.literal_eval(round_datum["transcript_annotated"]) # assistant_annotation = ast.literal_eval( # round_datum["system_transcript_annotated"] # ...
Python
1
(_match.unwrap(), plaintext); let _no_match = decrypt(&keygen(&pk, &msk, &att_not_matching).unwrap(), &ct_cp); assert_eq!(_no_match.is_ok(), false); } #[test] fn and10() { // setup scheme let (pk, msk) = setup(); // a set of two attributes matching the policy ...
Rust
0
>>() } use byteorder::{LittleEndian, WriteBytesExt}; use std::{mem, slice}; fn main() { let i: i64 = 12345; let mut bs = [0u8; mem::size_of::<i64>()]; bs.as_mut() .write_i64::<LittleEndian>(i) .expect("Unable to write"); for i in &bs { println!("{}", i); } println!("ne...
Rust
0
_cputype=x86_64 fi fi case "$_ostype" in Android) _ostype=linux-android ;; Linux) _ostype=unknown-linux-$_clibtype _bitness=$(get_bitness) ;; FreeBSD) _ostype=unknown-freebsd ;; ...
Rust
0
#[doc = "0x1076 - TCD Current Minor Loop Link, Major Loop Count (Channel Linking Disabled)"] #[inline(always)] pub fn dma_tcd3_citer_elinkno( &self, ) -> &crate::Reg<dma_tcd3_citer_elinkno::DMA_TCD3_CITER_ELINKNO_SPEC> { unsafe { &*(((self as *const Self) as *const u8).add(42...
Rust
0
import time from django.core.management.base import BaseCommand from posthog.models import Plugin, PluginConfig class Command(BaseCommand): help = "Set the plugin_id of a given config or set of configs to something else" def add_arguments(self, parser): parser.add_argument( "target_ids"...
Python
1
art={pre}_{key}") except UserIsBlocked: await query.answer('Uɴʙʟᴏᴄᴋ ᴛʜᴇ ʙᴏᴛ ᴍᴀʜɴ !', show_alert=True) except PeerIdInvalid: await query.answer(url=f"https://telegram.me/{temp.U_NAME}?start=sendfiles3_{key}") except Exception ...
Python
1
]) # Create the model and check m = make_model(g, opset_imports=[make_opsetid('', TARGET_OPSET)]) checker.check_model(m) sess = OnnxInference(m, runtime="onnxruntime1") optimized_model = onnx_remove_node_identity(m) sess_opt = OnnxInference(optimized_model, runtime="on...
Python
1
um_skip}") return indices def __getitem__(self, idx): start, num_before_start = self.indices[idx] end = start + self.horizon_steps states = self.states[(start - num_before_start) : (start + 1)] actions = self.actions[start:end] rewards = self.rewards[start : (start +...
Python
1
len(results) > 0: for result in results: boxes = result.boxes masks = result.masks for i, box in enumerate(boxes): x1, y1, x2, y2 = box.xyxy[0].cpu().numpy() conf = box.conf[0].item() cls = box.cls[0]...
Python
1
= "Upper Position Counter Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--mo...
Rust
0
ING, EQUATORIAL_EARTH_RADIUS, POLAR_EARTH_RADIUS}; use num_traits::FromPrimitive; use std::{error, fmt}; /// Determine the distance between two geometries using [Vincenty’s formulae]. /// /// [Vincenty’s formulae]: https://en.wikipedia.org/wiki/Vincenty%27s_formulae pub trait VincentyDistance<T, Rhs = Self> { /// ...
Rust
0
str(s: &str) -> Result<HttpDate, Self::Err> { let utc_sec = chrono::DateTime::parse_from_rfc2822(s).map(|dt| dt.timestamp() as u64)?; Ok(HttpDate(utc_sec)) } } impl HttpDate { /// Convert HttpDate to i64 timestamp (seconds since EPOCH in UTC) pub fn timestamp(&self) -> u64 { self.0 ...
Rust
0
from woningwaardering.vera.bvg.generated import Referentiedata from woningwaardering.vera.referentiedatasoort import Referentiedatasoort class PrijscomponentwijzigingsredenReferentiedata(Referentiedata): pass class Prijscomponentwijzigingsreden(Referentiedatasoort): jaarlijkse_huuraanpassing_inkomensafhanke...
Python
1
let c_password = std::ffi::CString::new(password.unwrap_or("")).unwrap(); unsafe { self.extern_FPDF_LoadMemDocument().unwrap()( bytes.as_ptr() as *const std::ffi::c_void, bytes.len() as ::std::os::raw::c_int, c_password.as_ptr(), ) ...
Rust
0
st] self.assertLessEqual( len(set(labels_flat)), 4, msg="number of ct labels <= number of labels in the task training data", ) def test_uniform_distribution_matches(self): """Regardless of the label distribution in the training data, the control task labe...
Python
1
// s signature[64] = input[63]; // v ecrecover(H256::from_slice(&hash), &signature).unwrap_or_else(|_| Address::zero()) } #[allow(dead_code)] pub(crate) fn ecverify(hash: H256, signature: &[u8], signer: Address) -> bool { matches!(ecrecover(hash, signature), Ok(s) if s == signer) } /// See: https://ethe...
Rust
0
fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<AHB1LPENR_SPEC>> for R { #[inline(always)] fn from(reader: crate::R<AHB1LPENR_SPEC>) -> Self { R(reader) } } #[doc = "Register `AHB1LPENR` writer"] pub struct W(crate::W<AHB1LPENR_SPEC>); impl core::ops::Deref for W { ...
Rust
0
# -*- coding: utf-8 -*- from odoo.addons.sale_stock.tests.test_anglo_saxon_valuation_reconciliation import TestValuationReconciliation from odoo.tests import tagged @tagged('post_install', '-at_install') class TestAngloSaxonAccounting(TestValuationReconciliation): def test_cogs_should_use_price_from_the_right_com...
Python
1
Ok(Op::Operand(Operand::Real(Real(slice.to_owned())))) } impl<'a> ReadFrom<'a> for Range<u8, u8> { type ReadType = (U8, U8); fn from((first, n_left): (u8, u8)) -> Self { Range { first, n_left } } } impl<'a> WriteBinary for Range<u8, u8> { type Output = (); fn write<C: WriteContext>(ct...
Rust
0
t]] = [] for indice in range(len(matrice[indice_sommet])): if matrice[indice_sommet][indice]: dico_voisins[sommets[indice_sommet]].append(sommets[indice]) return dico_voisins matrice_to_dico = staticmethod(matrice_to_dico) def dico_to_matrice(dico): ...
Python
1
unsafe { &*self.registers }; match regs.lfclkstat.get() & (LowClockSource::MASK as u32) { 0b1 => LowClockSource::XTAL, 0b10 => LowClockSource::SYNTH, _ => LowClockSource::RC, } } pub fn low_running(&self) -> bool { let regs = unsafe { &*self.register...
Rust
0
// not surrogate string.push_wtf8(w(b"\xED\xB2\xA9")); // trail assert_eq!(string.bytes, b"\xED\xA0\xBD \xED\xB2\xA9"); let mut string = Wtf8Buf::new(); string.push_wtf8(w(b"\xED\xA0\x80")); // lead string.push_wtf8(w(b"\xED\xAF\xBF")); // lead assert_eq!(string.bytes, b"\xED\xA0\x80\xED...
Rust
0
use_full_group=use_full_group) if report is not None: print("Symmetrisation done") VarList = set() for P in OUT.gens(): if P._p != 0: if P.is_unit(): return Sequence([PARENT(1)], PARENT, check=False) V...
Python
1
ent `InputLength` from nom to be able to use the `Span` /// structure as an input of the parsers. /// /// This trait aims at computing the length of the input. impl<'a> InputLength for Span<'a> { /// Compute the length of the slice in the span. /// /// # Examples /// /// ``` /// # extern crate t...
Rust
0
import os import unittest from pyats.topology import loader from genie.libs.sdk.apis.iosxe.igmp_snooping.configure import configure_ip_igmp_snooping_vlan_query_version class TestConfigureIpIgmpSnoopingVlanQueryVersion(unittest.TestCase): @classmethod def setUpClass(self): testbed = f""" devic...
Python
1
self.temp_file.as_ref().context(error::MissingTempFile {})?; Ok(write_path.as_ref()) } // persist file to destination fn finalize(&mut self) -> Result<()> { let temp_file = self.temp_file.take().context(error::MissingTempFile {})?; let path = self.as_ref(); temp_file ...
Rust
0
from detectron2.config import CfgNode as CN def add_centernet_config(cfg): _C = cfg _C.MODEL.CENTERNET = CN() _C.MODEL.CENTERNET.NUM_CLASSES = 80 _C.MODEL.CENTERNET.IN_FEATURES = ["p3", "p4", "p5", "p6", "p7"] _C.MODEL.CENTERNET.FPN_STRIDES = [8, 16, 32, 64, 128] _C.MODEL.CENTERNET.PRIOR_PROB ...
Python
1
mined distribution match detected_package_manager: case "apk": setup_cmd = "apk update && apk add --no-cache openssh" case "apt": setup_cmd = "apt update && apt install -y openssh-server" case "apt-get": setup_cmd = "apt-get update && apt-get install -y op...
Python
1
ey2 = task_to_keys[self.name] input = self.hf_dataset[key1][idx] if key2 is not None: input = input + self.tokenizer.sep_token + self.hf_dataset[key2][idx] label = self.hf_dataset["label"][idx] return input, label def compute_metrics(self, eval_preds): if...
Python
1
user_info1={ "name": "leila", "last_name": "weisi", "age": "23" } user_info2={ "name": "hesam", "last_name": "shakiba", "age": "27" } user_info1["age"]="22" print(user_info1, user_info2) user_infos=[] user_infos.append(user_info1) user_infos.append(user_info2) print(user_infos) for key, value in user_infos.item():...
Python
1
print ray fileray = self.show3d(ray=ray, bdis=False, bstruc=False, col=col, id=k) k += 1 fo.write("{< " + fileray + " }\n") if bbasi: for inter in range(i): ...
Python
1
Empty, /// Name the `DamlLfArchive` with the archive hash. Hash, /// Name the `DamlLfArchive` with a `uuid`. Uuid, } /// Return the id of a package which contains a given module name or en error if no such package exists. /// /// The supplied `module_name` name is assumed to be in `DottedName` format, ...
Rust
0
when dropping an ADT, multiple fields may be /// joined together under the `rest` subpath. They are all controlled /// by the primary drop flag, but only the last rest-field dropped /// should clear it (and it must also not clear anything else). // // FIXME: I think we should just control the flags...
Rust
0
nn); let len = table.len(); table.clear(); Ok(len as u64) } async fn delete_by_id<'a, ID: Into<&'a IdType> + Send>( &'a self, conn: &mut InMemoryConnection, id: ID, ) -> Result<u64, C3p0Error> { let table = self.get_or_create_table(&self.qualified_tab...
Rust
0
n.dump(user_inputs, f, indent=4) # indent makes it human-readable print(f"Step by step progress can be checked in {output_filepath.replace('.csv', '.log')}...") print(f"Final output catalog file will be saved as {output_filepath}...") # In[13]: log_file = output_filepath.replace('.csv', '.log') # In[15]: if ...
Python
1