text
string
label_name
string
labels
int64
.collect::<Vec<TagName>>() } pub(super) fn encrypt_tags( tags: &HashMap<String, String>, tag_name_key: &chacha20poly1305_ietf::Key, tag_value_key: &chacha20poly1305_ietf::Key, tags_hmac_key: &hmacsha256::Key, ) -> Vec<Tag> { tags.iter() .map(|(tag_name, tag_value)| { if ...
Rust
0
{ span }) => Ast::StrLit(span.as_str().to_string()), Obj::Quote(Quote { inner, .. }) => Ast::Quote(Box::new((&(**inner)).into())), Obj::Quasiquote(Quasiquote { inner, .. }) => { Ast::Quasiquote(Box::new((&(**inner)).into())) } Obj::Unq...
Rust
0
crop_chunk, crop_chunk_size, true); let next_seg = (*seg).next; let after_rem_pinuse = to_pinuse(after_seg_size > 0 && Chunk::pinuse((*seg).info_chunk())); let success = sys::free(mem_to_free, mem_to_free_size); dlassert!(success); if before_seg_size != 0 { let bef...
Rust
0
lit: String::from("+"), start_offset: 44, end_offset: 45, start_pos: Position { line: 7, column: 7 }, end_pos: Position { line: 7, column: 8 }, comments: vec![], } ); assert_eq!(44, s.offset(&Position { line: 7, column: 7 })); assert_...
Rust
0
nfigs { print!("{:?} ", config.output_device.unwrap().name()); println!("{:?}", config.output_config); } } #[test] fn collection_output_from_devices() { let output_configs = OutputConfig::retrieve_from_devices(); assert!(!output_configs.is_empty()); ...
Rust
0
from fastapi import APIRouter from fastapi.responses import JSONResponse from pagermaid.common.plugin import plugin_manager from pagermaid.common.reload import reload_all from pagermaid.web.api.utils import authentication route = APIRouter() @route.get( "/get_local_plugins", response_class=JSONResponse, depende...
Python
1
id_code: str): ''' NCXファイルを作成 ''' file = self.work_dir / EPUB_NCX_PATH page = Template(file.read_text(encoding='utf-8')) page = page.safe_substitute(title=title, uuid_code=uuid_code) file.write_text(page, encoding='utf-8') def _format_content(self, headlines:...
Python
1
= unicase::Ascii::new("TIMEOUT"); const OPT_WINDOWSIZE: unicase::Ascii<&'static str> = unicase::Ascii::new("WINDOWSIZE"); /// TFTP Options. /// /// TFTP options are introduced in [RFC 2347]. /// /// [RFC 2347]: https://datatracker.ietf.org/doc/html/rfc2347 #[derive(Debug, Eq, PartialEq, Clone)] pub enum TftpOption { ...
Rust
0
is not None: for wwise_object in objects: match wwise_object: case WwiseObjectInfo(): args["objects"].append(wwise_object.guid) case GUID() | ProjectPath() | Name(): args["objects"].append(wwise_object) ...
Python
1
#!/usr/bin/python3 # Copyright 2010 Google Inc. # Licensed under the Apache License, Version 2.0 # http://www.apache.org/licenses/LICENSE-2.0 # Google's Python Class # http://code.google.com/edu/languages/google-python-class/ # Additional basic list exercises # D. Given a list of numbers, return a list where # all a...
Python
1
_ => Err(Error::InvalidSchema { value: value.clone(), }), } } } impl TryFrom<json::Value> for Schema { type Error = Error; fn try_from(value: json::Value) -> Result<Self> { let value: Value = value.into(); value.try_into() } } extern crate osmpb...
Rust
0
end); Self { origin, direction, t_start, t_end, } } /// Creates a new ray with the `direction` constraints being from `0` to `infinity`. /// /// # Constraints /// * `origin` - All values should be finite (neither infinite nor `NaN`). ...
Rust
0
from .audio_video_model import *
Python
1
import cv2 import pygame import time pygame.init() x1,y1= 10,10 #coordinates for the drums x2,y2=100,300 x3,y3=465,10 x4,y4=365,300 w,h=160,160 def draw(frame): cv2.rectangle(frame,(x1,y1),(x1+w,y1+h),(0,255,0),2) #drawing the drums cv2.rectangle(frame,(x2,y2),(x2+w,y2+h),(255,255,0),2) cv2.rectang...
Python
1
def test_stable_diffusion_2_non_square(self): sag_pipe = StableDiffusionSAGPipeline.from_pretrained( 'stabilityai/stable-diffusion-2-1-base') sag_pipe = sag_pipe.to(torch_device) sag_pipe.set_progress_bar_config(disable=None) prompt = '.' generator = torch.manual_seed(0) output = sag_pip...
Python
1
nownJobState => "Unknown Job State", Error::UnknownPackage => "Unknown Package", Error::Zmq(ref err) => err.description(), Error::ChannelCreate(ref err) => err.description(), Error::PackagePromote(ref err) => err.description(), } } } impl From<r2d2::GetTimeou...
Rust
0
c: *mut u8, m: *const u8, mlen: c_ulonglong, n: *const [u8; crypto_secretbox_xsalsa20poly1305_NONCEBYTES], k: *const [u8; crypto_secretbox_xsalsa20poly1305_KEYBYTES]) -> c_int; pub fn crypto_secretbox_xsalsa20poly1305_open( m: *mut u8, c: *const u8, cl...
Rust
0
more info [menu] # name = "command" say-hi = "echo 'Hello, world!'" # name = { run = "command", group = <number> } first = { run = "echo 'first!'", group = 1 } [config] dmenu.prompt = "example:" "#; static HELP_FOOTER: &str = "Use `-h` for short descriptions, or `--help` for more detail....
Rust
0
L/Element/summary) /// element. summary {}; // Web components /// Build a /// [`<slot>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/slot) /// element. slot {}; /// Build a /// [`<template>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/template) ///...
Rust
0
for i in range(repeats - 1): seq.append(inverted_residual(output_channels, output_channels, 1)) setattr(self, name, nn.Sequential(*seq)) input_channels = output_channels output_channels = self._stage_out_channels[-1] self.conv5 = nn.Sequential( nn....
Python
1
, Err(_) => return None }; let (shape, grid) = match (Shape::from_str(shape).ok(), Grid::from_str(grid).ok()) { (Some(shape), Some(grid)) => (shape, grid), (Some(shape), None) => (shape, Grid::from(shape)), (None, Some(grid)) => (Shape::from(grid), grid), (None, None) =>...
Rust
0
from symfit import variables, Parameter, Fit, D, ODEModel import numpy as np import matplotlib.pyplot as plt # First order reaction kinetics. Data taken from # http://chem.libretexts.org/Core/Physical_Chemistry/Kinetics/Rate_Laws/The_Rate_Law tdata = np.array([0, 0.9184, 9.0875, 11.2485, 17.5255, 23.9993, 27.7949, ...
Python
1
quick_chat response = await quick_chat("Hello!") print(response) ``` """ ) async def main(): """Main entry point for the Talk SDK demo application.""" parser = argparse.ArgumentParser( description="Gaia Talk SDK Demo - Examples of voice and text chat integration", formatter_class=argparse...
Python
1
// Iterate through and transform x into y, and generate z for i in 0..len { y[i] = 0.5 * ((16.0 * x[i] + 1.0).sqrt() - 1.0); // Define pdf to be plotted (correctly scaled with (N/no.bins) * P(y)) z[i] = len as f64/10.0 * (x[i]/2.0 + 0.25); } /* 4. Produce a histogram showing...
Rust
0
= HelloWorld::default().create(None).spawn_global(); make_endpoint([ ("/hello-world/1.0.0", hello_world_handler.clone_channel()), ("/hello-world/1.0.0", hello_world_handler.clone_channel()), ]); } #[tokio::test] async fn falls_back_to_next_protocol_if_unsupported() { let alice_hello_world_...
Rust
0
(dist, idx)) in nns_dist.iter().take(p) { distances.push(D::normalized_distance(T::to_f64(dist).unwrap())); result.push(*idx) } (result, distances) } fn _get(&self, i: i64) -> &D::Node { &self._nodes[&i] } pub fn get_distance(self, i: i64, j: i64) -> f6...
Rust
0
::marker::PhantomData) } } /// CGlue compatible object. /// /// This trait allows to retrieve the container of the `this` object on the structure. pub trait CGlueObjOwned<S>: CGlueObjMut<S> { fn cobj_owned(self) -> Self::ContType; } impl< 'a, T: ContextRef<ObjType = F> + ContextMut + ContextOw...
Rust
0
ハセガワ", "Hasegawa"), 69201), (("村上", "ムラカミ", "Murakami"), 68606), (("近藤", "コンドウ", "Kondo"), 68297), (("石井", "イシイ", "Ishii"), 67079), (("遠藤", "エンドウ", "Endo"), 62620), (("斉藤", "サイトウ", "Saito"), 62540), (("坂本", "サカモト", "Sakamoto"), 62308), ...
Python
1
bool { matches!(self, OwnedSegment::Index(_)) } pub fn is_invalid(&self) -> bool { matches!(self, OwnedSegment::Invalid) } } impl<'a, 'b: 'a> From<&'b OwnedSegment> for BorrowedSegment<'a> { fn from(segment: &'b OwnedSegment) -> Self { match segment { OwnedSegment::...
Rust
0
-> (String, u32) { let mut buf = String::new(); let mut count = 0; self.diag(|d| { // We want to filter diagnostics by the particular one we are testing for, to // avoid surprising results in tests. if d.downcast_ref::<D>().is_some() { format_...
Rust
0
} #[inline] pub fn node_to_index(&self, dep_node: &DepNode) -> SerializedDepNodeIndex { self.index[dep_node] } #[inline] pub fn fingerprint_of(&self, dep_node: &DepNode) -> Option<Fingerprint> { self.index .get(dep_node) .map(|&node_index| self.data.nod...
Rust
0
iffs, opts.significance)?; stdout.clear()?; stdout.buf = out; stdout.print()?; // // Check to see if we're finished // if let Some(threshold) = opts.threshold { // let worst = diff // .diffs // .iter() ...
Rust
0
ITHER_BE_Span_OR_IMPLEMENT_ToTokens_OR_BE_SpanRange(&self) -> SpanRange; } pub trait SpanRangeAsSpanRange { #[allow(non_snake_case)] fn FIRST_ARG_MUST_EITHER_BE_Span_OR_IMPLEMENT_ToTokens_OR_BE_SpanRange(&self) -> SpanRange; } impl<T: ToTokens> ToTokensAsSpanRange for &T { fn F...
Rust
0
#!/usr/bin/env python import optparse import numpy as np import scipy.signal import scipy.fftpack as fft import gnsstools.galileo.e5ai as e5ai import gnsstools.nco as nco import gnsstools.io as io import gnsstools.util as util # # Acquisition search # def search(x,prn,doppler_search,ms): fs = 3*10230000.0 n = ...
Python
1
d or kernel_size_to_std(r) imgs = gaussian_blur2d(imgs, (r,) * 2, (std,) * 2) # downsample if resolution exceeds the limit given with maxres if maxres < max(imgs.shape[2:]): assert imgs.shape[-2] == imgs.shape[-1], "Image provided is no square!" imgs = F.interpolate(...
Python
1
/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limit...
Rust
0
serial::Config::default().baudrate(115200.bps()), clocks, &mut rcc.apb2, ); let sensor = IaqCore::new(i2c); let mut gpioc = device.GPIOC.split(&mut rcc.apb2); let mut led = gpioc .pc13 .into_push_pull_output_with_state(&mut gpioc.crh...
Rust
0
name = input('What is your name? ') print('Hi ' + name)
Python
1
* `hpow` - The power at which the heater should be activated /// * `hdur` - The duration for which the heater should be active. The /// longest (HeaterDuration::PulseLong) is ~ 1s. After this /// duration, the heater is automatically deactivated. /// pub fn set_heater_then_me...
Rust
0
# Diccionario para datos de la seleccion Argentina seleccionArgentina = { 10: {"Nombre": "Lionel Messi", "Edad": 37, "Altura": 1.70, "Precio": "50 millones", "Posicion": "Extremo Derecho"}, 11: {"Nombre": "Ángel Di María", "Edad": 36, "Altura": 1.80, "Precio": "5 millones", "Posicion": "Extremo Izquierdo"}, ...
Python
1
# cognisphere_adk/tools/emotion_tools.py from google.adk.tools.tool_context import ToolContext def analyze_emotion(text: str, tool_context: ToolContext = None) -> dict: """ Analyzes the emotional content of text. Args: text: The text to analyze tool_context: Tool context for accessing se...
Python
1
ect::<Vec<_>>(), expected.collect::<Vec<_>>()); } } #![feature(drain_filter)] use std::cmp::max; use std::error::Error; use std::fmt::Debug; use std::io::Read; use std::time::Instant; fn bench<T, F>(name: &str, f: F) -> T where F: FnOnce() -> T, { let start = Instant::now(); let res = (f)(); let e...
Rust
0
import evdev 摇杆精度 = 65535 扳机精度 = 1023 """手柄连接程序""" def connect_gamepad(): global 摇杆精度, 扳机精度 devices = [evdev.InputDevice(path) for path in evdev.list_devices()] for device in devices: print(device.name) for device in devices: if "XBOX" in device.name.upper(): print("Gamepa...
Python
1
import numpy as np import matplotlib.pyplot as plt ## 速度\加速度Q值分開調整 def AKF_2(dt, Pos, PosCmd, VelCmd, AccCmd): A = np.array([[1, dt, 0.5*dt**2], [0, 1, dt], [0, 0, 1 ]]) B = np.array([[0.5*dt**2], [dt], [1]]) u = AccCmd C = np.arra...
Python
1
dle(), start_key.as_ptr() as *const c_char, start_key.len() as size_t, end_key.as_ptr() as *const c_char, end_key.len() as size_t, ); Ok(()) } } /// Remove database entries in column family from start key to end key...
Rust
0
://postgres:postgres@localhost:5432/postgres" /// roles: [] /// users: [] /// "#, /// ) /// .unwrap(); /// let mut db = DbConnection::new(&config); /// db.query("SELECT 1", &[]).unwrap(); /// ``` pub fn new(config: &Config) -> Self { match config.c...
Rust
0
f64)>, h_star: &TRS, lex: &Lexicon, params: &Params, rng: &mut R, ) -> Result<(), String> { if data.is_empty() { return Err(String::from("Not enough data")); } println!("n_data,generation,id,llikelihood,lprior,score,difference,description"); for n_data in 0..(data.len() - 1) { ...
Rust
0
# Multi-HMR # Copyright (c) 2024-present NAVER Corp. # CC BY-NC-SA 4.0 license import torch def rebatch(idx_0, idx_det): # Rebuild the batch dimension : (N, ...) is turned into (batch_dim, nb_max, ...) # with zero padding for batch elements with fewer people. values, counts = torch.unique(idx_0, sorted=T...
Python
1
import ee from ee_plugin import Map # Load the Sentinel-1 ImageCollection. sentinel1 = ee.ImageCollection('COPERNICUS/S1_GRD') \ .filterBounds(ee.Geometry.Point(-122.37383, 37.6193)) # Filter by metadata properties. vh = sentinel1 \ .filter(ee.Filter.listContains('transmitterReceiverPolarisation', 'VV')) \ ...
Python
1
ARRAY3D_DESCRIPTOR as Descriptor; /// This specifies the number of packed elements per "CUDA array element". /// /// - The CUDA array element approach is useful e.g. for [RGBA color model], /// which has 4 values at each point of figures. /// - For example, When `T=f32` and `NumChannels::Two`, /// the size of "CUD...
Rust
0
{ let mut temp = vec![]; for role in &emoji.roles { temp.push( guild .get_role(role) .await .map_or("Unknown role".to_string(), |r| r.name.clone()), ) } ...
Rust
0
import os class Config: SECRET_KEY = os.environ.get('SECRET_KEY') or 'you-will-never-guess' SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or \ 'mysql+pymysql://root:@localhost/event_manager_db' SQLALCHEMY_TRACK_MODIFICATIONS = False
Python
1
import pygame from pygame.locals import * from OpenGL.GL import * from OpenGL.GLU import * import numpy as np pygame.init() screen_width = 800 screen_height = 600 screen = pygame.display.set_mode((screen_width, screen_height),DOUBLEBUF|OPENGL) pygame.display.set_caption("3D Transformations") glClearColor(0.0, 0.0, 0.0,...
Python
1
} } impl<ProgramId: Ord, Balance> PartialOrd for Program<ProgramId, Balance> { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.program_id.cmp(&other.program_id)) } } impl<ProgramId: Eq, Balance> PartialEq for Program<ProgramId, Balance> { fn eq(&self, other: &Self) -> bool { ...
Rust
0
_imitator = st.checkbox( "Abilita Style Imitator", help="Imita lo stile di un testo di esempio.", key="enable_style_imitator", value=False ) style_imitator_example_text = "" if enable_style_imitator: style_imitator_example_text = st.te...
Python
1
::Unbounded => true } { Some(g) } else { None } }) ) } else { ...
Rust
0
__init__( self, version: Version, time: int, value: int, ) -> None: super().__init__( version=version, time=time, value=value, ) @classmethod def from_matchline( cls, matchline: str, version: Versio...
Python
1
-> Self { let worker = Worker::new(machine_node.machine_id, machine_node.node_id); Self { machine_node, worker, marker: PhantomData } } pub fn next_id(&mut self) -> Id { G::next_id(&mut self.worker) } } impl<G> PartialEq for SnowflakeIdGenerator<G> { fn eq(&self, other: &Self)...
Rust
0
hidden_width=hidden_width, ), convert_inputs=convert_inputs, convert_outputs=convert_outputs, mixed_precision=mixed_precision, grad_scaler=grad_scaler, ) ] def pairwise_bilinear_forward(model: Model, X, is_train: bool): return mode...
Python
1
# Copyright (c) Microsoft. All rights reserved. from typing import Annotated from ai_code_sandbox import AICodeSandbox from semantic_kernel.functions import kernel_function class CodeExecutionPlugin: """A plugin that runs Python code snippets.""" @kernel_function(description="Run a Python code snippet. You ...
Python
1
radius = input("Enter the sphere's radius: ") radius = float(radius) diameter = 2 * radius circumfrence = 2 * 3.14 * radius surfaceArea = 4 * 3.14 * radius**2 volume = (4/3)*3.14 * radius**3 print ("The diameter is: ", diameter, "\nThe circumfrence is: ", circumfrence, "\nThe surfaceArea is: ", surfaceAre...
Python
1
""" .. _ex-kernel-opm-phantom: Kernel OPM phantom data ======================= In this dataset, a Neuromag phantom was placed inside the Kernel OPM helmet and stimulated with 7 modules active (121 channels). Here we show some example traces. """ # Authors: The MNE-Python contributors. # License: BSD-3-Clause # Copyr...
Python
1
.pages[page_num] if page_num < len(highlight_pdf.pages): highlight_page = highlight_pdf.pages[page_num] source_page.merge_page(highlight_page) output_pdf.add_page(source_page) # 返回合并后的 PDF 内容 output_stream = BytesIO() output_pdf.write(output_stream) output_stream...
Python
1
eln!(&mut stage, "READ {:?} {}", infn, in_hash)?; writeln!(&mut stage, "HASH {}", out_hash)?; // All done! Record success and exit. stage.end(&Some(out_hash))?; Ok(()) } } use serde::Serialize; use crate::syscall::{self, SyscallResult}; /// Send an unreliable (fire-and-forget) message to a topic pu...
Rust
0
ager=self.file_manager) # Generate very quiet audio (simulating background noise) audio_data = recorder.generate_test_audio(frequency=0, duration=1.0, amplitude=0.001) # Should be very quiet but not exactly zero (due to numerical precision) rms = np.sqrt(np.mean(audio_d...
Python
1
#!/usr/bin/env python3 """ This Python script is used to validate the format of an email address. """ __author__ = 'John Bumgarner' __date__ = 'February 09, 2023' __status__ = 'Production' __license__ = 'MIT' __copyright__ = "Copyright (C) 2023 John Bumgarner" #########################################################...
Python
1
_bytes())).collect(); // keys must be in canonical ordering first keys_bytes.sort_by(|lhs, rhs| match lhs.1.len().cmp(&rhs.1.len()) { std::cmp::Ordering::Equal => lhs.1.cmp(&rhs.1), len_order => len_order, }); serializer.write_map(cbor_event::Len::Len(self.0.len()...
Rust
0
/// /// # let connection_string = "HostName=cool-iot-hub.azure-devices.net;SharedAccessKeyName=iothubowner;SharedAccessKey=<KEY>; /// let iothub = ServiceClient::from_connection_string(connection_string, 3600).expect("Failed to create the ServiceClient!"); /// let twin = iothub.get_module_twin("some-device"...
Rust
0
ndow_title if cursor_pos else None, "application": cursor_pos.application if cursor_pos else None } if cursor_pos else None, "clipboard_available": self.clipboard_manager is not None } # Global input handler instance _input_handler = None def get_input_handler() -> In...
Python
1
/// The `XF86Dri::DestroyDrawable` request. #[derive(Copy, Clone, Debug)] #[repr(C)] pub struct xcb_xf86dri_destroy_drawable_request_t { pub major_opcode: u8, pub minor_opcode: u8, pub length: u16, pub screen: u32, pub drawable: u32, } impl Default for xcb_xf86dri_destroy_drawable_request_t { f...
Rust
0
, 'b> State<GameData<'a, 'b>, StateEvent> for Startup { fn on_start(&mut self, mut data: StateData<GameData<'a, 'b>>) { insert_resources(&mut data.world); } fn update( &mut self, data: StateData<GameData<'a, 'b>>, ) -> Trans<GameData<'a, 'b>, StateEvent> { data.data.upda...
Rust
0
from .tensor import Tensor import math class Linear: def __init__(self, in_features, out_features, requires_grad=True): self.requires_grad = requires_grad # Crear el tensor de entrada input_tensor = Tensor.tensor((in_features, out_features)) scale_factor = math.sqrt(2. / in...
Python
1
from whad.device import WhadDevice from whad.rf4ce import Controller from whad.dot15d4.address import Dot15d4Address from whad.common.monitors import WiresharkMonitor from whad.rf4ce.stack.apl.profiles import MSOProfile from whad.exceptions import WhadDeviceNotFound from scapy.compat import raw from random import randi...
Python
1
nsional affine space over a three-element field with no three elements in a line. Args: n: an integer, number of copies. Returns: A set of tuples in {0, 1, 2}. """ ) body = textwrap.dedent( """\ capset = set() for i in range...
Python
1
.get_data(); let can_store = can_store.borrow_mut(); let columns = data.get_data().len(); let len = data.get_data().len() as u8; let (fil,parsed,color) = if filter_cont_clone.get_active() { ...
Rust
0
from dateutil.tz import tzutc import datetime from tileserv.tools.s3 import get_hfi_objects utc = tzutc() test_objects = [ {'Key': 'sfms/uploads/forecast/2022-09-03/hfi20220903.tif', 'LastModified': datetime.datetime( 2022, 9, 7, 18, 6, 26, 556000, tzinfo=utc)}, {'Key': 'sfms/uploads/forecast/2022-09...
Python
1
# This file is part of django-ca (https://github.com/mathiasertl/django-ca). # # django-ca is free software: you can redistribute it and/or modify it under the terms of the GNU General # Public License as published by the Free Software Foundation, either version 3 of the License, or (at your # option) any later version...
Python
1
"""Backfill notes collection Revision ID: 6cfc8bf6afac Revises: 055389992beb Create Date: 2023-08-25 08:49:24.309162 """ from alembic import op # revision identifiers, used by Alembic. revision = "6cfc8bf6afac" down_revision = "055389992beb" branch_labels = None depends_on = None def upgrade(): op.execute( ...
Python
1
import re from typing import Literal MINIMAL_QUOTE_PATTERN = re.compile(r"""([&<>])(?!(amp|lt|gt|quot|#39);)""") MINIMAL_QUOTE_REPLACE_WITH = { "<": "&lt;", ">": "&gt;", "&": "&amp;", } NORMAL_QUOTE_PATTERN = re.compile("|".join(map(re.escape, ['"', "'"]))) NORMAL_QUOTE_REPLACE_WITH = { '"': "&quot;",...
Python
1
0>::repeat(false, 50); /// let ones = BitVec::<u16, Lsb0>::repeat(true, 50); /// ``` pub fn repeat(bit: bool, len: usize) -> Self { let mut out = Self::with_capacity(len); unsafe { out.set_len(len); out.as_raw_mut_slice().fill_with(|| { BitStore::new(if bit { !<T::Mem>::ZERO } else { <T::Mem>::ZERO }) ...
Rust
0
middle_rotor = Rotor::new(b, j, 0); let right_rotor = Rotor::new(c, k, 0); let key = EnigmaKey::new(left_rotor, middle_rotor, right_rotor, plugboard); let mut e = Enigma::new(key, ReflectorId::B); buf.clear(); buf.extend(cipher.chars().ma...
Rust
0
!(sigmoid.mix(1000, 1000).unwrap(), 178); assert_eq!(sigmoid.mix(1000, 100000).unwrap(), 999); assert_eq!(sigmoid.mix(100000, 100000).unwrap(), 1000); // Rounding down (697.8821566) assert_eq!(sigmoid.mix(100, 100000).unwrap(), 697); // Overflow checks let err = sigmoid...
Rust
0
pub mod counter; pub mod dispatcher; pub mod mpsc; pub mod task; pub mod timeout; <reponame>c0dearm/piss<gh_stars>10-100 #[derive(Debug)] pub enum Error { SecretReadError, SecretTooLarge, InvalidNumberOfBits, ImageReadWriteError, } impl std::error::Error for Error {} impl std::fmt::Display for Error ...
Rust
0
#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requir...
Python
1
.ok_or_else(|| ErrorKind::InconsistentState.error()))?; if reply.header.seq_no <= follower.obsolete_seq_no { // 平行度が高くなりすぎるのを防止するために、 // propose(broadcast)が重なった場合には、 // `obsolete_seq_no`以前のbroadcastに対する応答は古いものとして処理を省く. return Ok(()); } follower.obs...
Rust
0
; let mut payload = Vec::new(); if let Err(e) = params.write_to(&mut payload) { return Box::new(err(e.into())); } self.send_message(CowRpcMessage::Call(header, msg, payload)) } else { Box::new(err(CowRpcError::Proto("Proc not found".t...
Rust
0
uccessfully updated entity with id: {entity_id}") return updated_entity except ValidationException: raise except BusinessException: raise except Exception as e: logger.error(f"Error updating entity with id {entity_id}: {st...
Python
1
_urls_from_file(file_path) if video_urls: for url in video_urls: download_single_instagram_video_or_image(url) else: print("[Error] No URLs found in the file.") elif choice == '5': video_url = input("Enter t...
Python
1
rKind::{ InvalidData, }}; let mut p = &buf[..]; let prefix = p.read_u8()?; match prefix & 0b11000000 { 0b00000000 => { let e = (prefix & 0b100000) != 0; let m = (prefix & 0b010000) != 0; let o = (prefix & 0b001000) != 0; let sss = (pref...
Rust
0
# To test: # curl -g 'http://127.0.0.1:9090/api/v1/query?query=sum(rate(kepler_container_joules_total[1m]))' from flask import Flask, jsonify, request import random import time app = Flask(__name__) # Synthetic data generation def generate_synthetic_data(start_time, end_time, step): data = [] current_time =...
Python
1
4., -13.], self.evaluate(var0)) self.assertAllClose([-6., -5.], self.evaluate(var1)) @test_util.run_in_graph_and_eager_modes def testComputeGradientsWithTensors(self): x = ops.convert_to_tensor(1.0) def f(): return x * x sgd_op = gradient_descent.GradientDescentOptimizer(3.0) grads_and_...
Python
1
esents the total number of *batches* computed, not the total number of epochs computed. When last_epoch=-1, the schedule is started from the beginning. Default: -1 verbose (bool): If ``True``, prints a message to stdout for each update. Default: ``False``. ...
Python
1
nd an empty `LineString` is `0.0` /// /// # Examples /// /// `Point` to `Point`: /// /// ``` /// use approx::assert_relative_eq; /// use geo::algorithm::euclidean_distance::EuclideanDistance; /// use geo::point; /// /// let p1 = point!(x: -72.1235, y: 42.3521); /// let p2...
Rust
0
eral.get_server_time(); match result { Ok(answer) => println!("Server Time: {}", answer.server_time), Err(e) => println!("Error: {}", e), } let result = general.exchange_info(); match result { Ok(answer) => println!("Exchange information: {:?}", answer), Err(e) => printl...
Rust
0
let not_primes = (1_u32..71) .map(|x| BigUint::from(x)) .filter(|x| known_primes.binary_search(x).is_err()); for not_a_prime in not_primes { assert_eq!(is_prime_6kp1(&not_a_prime), false); } } #[test] fn egcd_test() { use num::bigint::ToBig...
Rust
0
are not supported yet. // Ignoring "green_and_whiteness", error tests are not supported yet. // Ignoring "lightness_and_whiteness", error tests are not supported yet. // Ignoring "red_and_blackness", error tests are not supported yet. // Ignoring "red_and_saturation", error tests are not supported ...
Rust
0
lee", &self.pollee) .finish() } } // Implement the common methods required by FileHandle impl EpollFile { pub async fn read(&self, buf: &mut [u8]) -> Result<usize> { return_errno!(EINVAL, "epoll files do not support read"); } pub async fn readv(&self, bufs: &mut [&mut [u8]]) -> Res...
Rust
0
itude'], xlim=[4, 5], xlabel=None, ax=axs[0]) plot_instantaneous_measure(times, [sig_filt, amp], 'amplitude', labels=['Filtered Signal', 'Amplitude'], colors=['b', 'r'], xlim=[4, 5], ax=axs[1]) ############################################...
Python
1
for Linux only. `Libusb` is portable to many platforms including Linux, Windows, and OSX. //! * This crate requires no initialization, no `context` structure, and has less coupling. //! * This crate externalizes event loop support. The `AsyncDevice` has traits //! [`AsRawFd`](https://doc.rust-lang.org/std/os/unix/...
Rust
0
__author__ = 'armartin' import argparse USAGE = """ lai_global.py --bed_list --ind_list --pops --out """ parser = argparse.ArgumentParser() parser.add_argument('--bed_list') parser.add_argument('--ind_list') parser.add_argument('--pops', default='AFR,EUR,NAT,UNK', ...
Python
1