text
stringlengths
8
4.13M
pub mod lru_list; pub mod object_id; pub const fn align_up(val: usize, align: usize) -> usize { (val + align - 1) / align * align } pub const fn align_down(val: usize, align: usize) -> usize { val / align * align }
use std::sync::Arc; use crossbeam_channel::Receiver; use ring::aead::{Aad, LessSafeKey, Nonce, UnboundKey, CHACHA20_POLY1305}; use zerocopy::{AsBytes, LayoutVerified}; use super::constants::MAX_INORDER_CONSUME; use super::device::Device; use super::messages::{TransportHeader, TYPE_TRANSPORT}; use super::peer::Peer; u...
use std::env; use std::ffi::OsStr; use std::time::{Duration, SystemTime}; use libc::{ENOENT, ENOSYS}; use fuse::{FileType, FileAttr, Filesystem, Request}; use fuse::{ReplyData, ReplyEntry, ReplyAttr, ReplyDirectory}; use fuse::{ReplyWrite, ReplyOpen, ReplyEmpty, ReplyXattr}; mod hello_inode; use hello_inode::{INVALID...
// Copyright (c) 2021 Quark Container Authors / 2018 The gVisor Authors. // // 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 ...
pub fn main() { println!("\n-- 19.2 advanced traits\n"); specifying_placeholder_types_in_trait_defs_with_associated_types(); default_generic_type_parameters_and_operator_overloading(); fully_qualified_syntax_for_disambiguation(); supertraits_to_inception_traits(); newtype_pattern_for_ext_traits_...
use std::net::{IpAddr, SocketAddr}; use uuid::Uuid; #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)] pub struct NetId(Uuid); impl NetId { pub fn new() -> Self { NetId(Uuid::new_v4()) } } /// Network error type #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)] pub enum NetError { UnknownError, ...
use std::rc::Rc; use self::mesh::Mesh; use super::material::Material; pub mod mesh; // TODO: model should be owned by the user not scene. then every rendercomponent has a ref (rc) to the model pub struct Model { pub material: Rc<Material>, pub mesh: Rc<Mesh>, }
use crate::util::IndexDomain; use crate::{Cell, Owner, SearchNode}; use super::NodePool; pub struct IndexPool { search_num: usize, pool: Box<[Cell<SearchNode<usize>>]>, } impl IndexPool { pub fn new(size: usize) -> Self { let mut pool = Vec::with_capacity(size); for id in 0..size { ...
//计算成功概率用的 use std::collections::HashMap; use std::collections::HashSet; use rand::Rng; pub fn b1(a: f64, r: f64) -> f64 { let b = r + 2.0 * a; b } pub fn hb(x: f64) -> f64 { //二元熵函数 let y = -x * (x.log2()) - (1.0 - x) * ((1.0 - x).log2()); y } pub fn creat_permutation(n...
extern crate specs; use crate::types::{GameState}; pub use nalgebra::Vector2; use nphysics2d::math::Velocity; use nphysics2d::object::{ BodyPartHandle, BodyStatus, ColliderDesc, DefaultBodyHandle, DefaultBodySet, DefaultColliderSet, RigidBodyDesc }; use nphysics2d::joint::{DefaultJointConstraintSet}; use nph...
pub type LazyResult<T> = Result<T, Box<dyn std::error::Error>>;
pub enum Operator { Addition, Subtraction, Multiplication, Division, Unknown(char), } pub fn is_operator(symbol: &char) -> bool { match symbol { '+' | '-' | '/' | '*' => true, _ => false, } } pub fn as_operator(symbol: &char) -> Operator { match symbol { '+' => ...
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
use rand::distributions::Distribution; fn generate_random_name() -> String { let mut rng = rand::thread_rng(); let mut res = String::new(); let letter = rand::distributions::Uniform::from(0..26); let number = rand::distributions::Uniform::from(0..1000); for _ in 0..2 { let i: u8 = letter.sa...
use crate::prelude::*; use super::super::raw_to_slice; #[repr(C)] #[derive(Debug)] pub struct VkPhysicalDeviceMemoryProperties { pub memoryTypeCount: u32, pub memoryTypes: [VkMemoryType; VK_MAX_MEMORY_TYPES as usize], pub memoryHeapCount: u32, pub memoryHeaps: [VkMemoryHeap; VK_MAX_MEMORY_HEAPS as usi...
use async_std::{prelude::FutureExt, sync::RwLock, task}; use std::{ops::Deref, sync::Arc, time::Duration}; fn main() { println!("Hello, world!"); env_logger::init(); task::block_on(async { let lock = Arc::new(RwLock::new(true)); { let lock = lock.clone(); task::sp...
mod cli; mod modmg; mod sessionapp; mod sm_xdg; mod wmmanager; use clap::{App, Arg}; use sessionapp::SessionApplication; #[tokio::main] async fn main() { let matches = App::new("LDE SESSION") .version("1.0") .author("KOOMPI. koompi@gmail.com") .about("Sesssion Manager. ") .arg( ...
mod read_util; use std::collections::HashMap; use std::io::{Read, Error as IOError}; use crate::read_util::RawDataRead; pub const SHADER_LIGHT_MAPPED_GENERIC: &str = "lightmappedgeneric"; pub const SHADER_VERTEX_LIT_GENERIC: &str = "vertexlitgeneric"; pub const SHADER_UNLIT_GENERIC: &str = "unlitgeneric"; pub const S...
use crate::utils; use regex::Regex; struct Passport { byr: Option<String>, iyr: Option<String>, eyr: Option<String>, hgt: Option<String>, hcl: Option<String>, ecl: Option<String>, pid: Option<String>, cid: Option<String>, } impl Passport { fn new() -> Passport { return Pass...
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)] #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct FindSimilarFileIndexResults { pub m_FileIndex: u32, pub m_MatchCount: u32, } impl FindSimilarFile...
// This file is part of linux-epoll. It is subject to the license terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/linux-epoll/master/COPYRIGHT. No part of linux-epoll, including this file, may be copied, modified, propagated, or distri...
#![allow(dead_code)] use crate::{aocbail, utils}; use utils::{AOCResult, AOCError}; use std::collections::HashSet; use std::collections::hash_map::DefaultHasher; use std::hash::{Hash, Hasher}; pub struct CombatGame { p1: Vec<usize>, p2: Vec<usize>, cache: HashSet<u64>, recurse: bool, } #[derive(Clon...
use super::*; use miniquad::*; use std::{mem, str}; mod pipeline; #[repr(C)] #[derive(Debug, Clone, Copy)] pub struct Vertex { pos: [f32; 2], uv: [f32; 2], color: [u8; 4], } pub fn vertex(pos: glam::Vec2, uv: glam::Vec2, color: Color) -> Vertex { Vertex { pos: [pos.x, pos.y], uv: [uv....
use crate::{harddisk::pata, svec::SVec}; // Layouts from OSDev wiki: https://wiki.osdev.org/GPT // // GPT partitioned media layout: // LBA0: Protective Master Boot Record. Kept for backward comptibility. // LBA1: Partition header, identified by 8 bytes "EFI PART", [0x45 0x46 0x49 0x20 0x50 0x41 0x52 0x54] // LBA2..33:...
pub mod mutations; pub mod queries; pub mod service; use std::collections::HashMap; use crate::{ datastore::{prelude::*, Value}, users::service::get_user_path, }; use chrono::prelude::*; use juniper::ID; #[derive(juniper::GraphQLObject)] #[graphql(description = "Story contains tasks that needs to be done for...
// Copyright 2017 Dasein Phaos aka. Luxko // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except a...
extern crate dredd_hooks; use std::env; use dredd_hooks::IntegrationServer; fn main() { let arguments: Vec<String> = env::args().collect(); let hookfiles = arguments[1..].to_vec(); let server = IntegrationServer::new(); IntegrationServer::start(server, hookfiles); }
extern crate amethyst; extern crate backtrace; extern crate chrono; extern crate climer; extern crate deathframe; extern crate dirs; extern crate json; extern crate ron; #[macro_use] extern crate serde; extern crate serde_json; extern crate serde_plain; mod audio; mod components; mod helpers; mod input; mod level_mana...
extern crate nalgebra; pub mod clock_tracker; use super::dwt_utils::Timestamp; pub use clock_tracker::{ CONSTRUCTED, INITIALIZED }; pub use clock_tracker::ClockTracker;
use anyhow::bail; use reqwest::multipart; use crate::pushover::{Request, Response}; #[cfg(test)] fn endpoint_url() -> String { mockito::server_url() } #[cfg(not(test))] fn endpoint_url() -> String { "https://api.pushover.net".to_string() } #[derive(Debug)] pub struct Attachment { pub filename: String, ...
#![feature(core)] #![feature(reflect_marker)] #![feature(unboxed_closures)] extern crate lua52_sys as ffi; extern crate libc; use std::ffi::{CStr, CString}; use std::io::Read; use std::io::Error as IoError; use std::borrow::Borrow; use std::marker::PhantomData; pub use functions_read::LuaFunction; pub use functions_...
use libc::{c_int}; use sdl::SDL_bool; // SDL_cpuinfo.h extern "C" { pub fn SDL_GetCPUCount() -> c_int; pub fn SDL_GetCPUCacheLineSize() -> c_int; pub fn SDL_HasRDTSC() -> SDL_bool; pub fn SDL_HasAltiVec() -> SDL_bool; pub fn SDL_HasMMX() -> SDL_bool; pub fn SDL_Has3DNow() -> SDL_bool; pub f...
//! Linux `mount` API. // The `mount` module includes the `mount` function and related // functions which were originally defined in `rustix::fs` but are // now replaced by deprecated aliases. After the next semver bump, // we can remove the aliases and all the `#[cfg(feature = "mount")]` // here and in src/backend/*/...
use crate::geometry::checks::*; use crate::geometry::entities::*; use crate::geometry::traits::rectangable::Rectangable; pub trait Relative: Rectangable { fn relate_entity(&self, entity: &Entity) -> Option<Relation>; fn relate_entities(&self, entities: &Entities) -> Option<Relation>; } #[derive(Debug, Clone, ...
use super::*; #[derive(Serialize, Deserialize, Debug, Clone)] pub struct Host { pub id: Uuid, pub name: String, pub address: String, pub port: i32, pub status: Status, pub host_user: String, #[serde(skip_deserializing)] pub password: String, } #[derive(Serialize, Deserialize, Debug, C...
//! console is a library for Rust that provides access to various terminal //! features so you can build nicer looking command line interfaces. It //! comes with various tools and utilities for working with Terminals and //! formatting text. //! //! Best paired with other libraries in the family: //! //! * [dialoguer]...
//! Definitions for the base Cranelift language. pub mod formats; pub mod immediates; pub mod predicates; pub mod settings; pub mod types;
//! A reference to a channel in a buffer. use std::cmp; use std::fmt; use std::hash; use std::marker; /// A reference to a channel in a buffer. /// /// See [crate::Interleaved::get]. #[derive(Clone, Copy)] pub struct Channel<'a, T> { pub(crate) inner: RawChannelRef<T>, pub(crate) _marker: marker::PhantomData<...
//! @brief Solana Native program entry point use crate::{ account::Account, account::KeyedAccount, instruction::CompiledInstruction, instruction::InstructionError, message::Message, pubkey::Pubkey, }; use std::{cell::RefCell, rc::Rc}; // Prototype of a native program entry point /// /// program_id: Program ID...
#[doc = "Reader of register C1_AHB1LPENR"] pub type R = crate::R<u32, super::C1_AHB1LPENR>; #[doc = "Writer for register C1_AHB1LPENR"] pub type W = crate::W<u32, super::C1_AHB1LPENR>; #[doc = "Register C1_AHB1LPENR `reset()`'s with value 0"] impl crate::ResetValue for super::C1_AHB1LPENR { type Type = u32; #[i...
// Copyright 2022 Datafuse Labs. // // 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 or agreed to ...
pub const REGION_DATA: &'static str = "region_data"; pub const TEST_PASS: &'static str = "test_pass"; pub const TEST_PASS_CAMERA: &'static str = "test_pass_camera"; pub const TEST_PASS_TEXTURE: &'static str = "test_pass_texture"; pub const TEST_PASS_DEPTH_TEXTURE: &'static str = "test_pass_depth_texture";
mod searcher; use self::searcher::{SearchEngine, SearchWorker}; use crate::find_usages::{CtagsSearcher, GtagsSearcher, QueryType, Usage, UsageMatcher, Usages}; use crate::stdio_server::handler::CachedPreviewImpl; use crate::stdio_server::job; use crate::stdio_server::provider::{BaseArgs, ClapProvider, Context}; use cr...
//! Type aliases for using `deadpool-diesel` with MySQL. /// Connection which is returned by the MySQL pool pub type Connection = crate::Connection<diesel::MysqlConnection>; /// Manager which is used to create MySQL connections pub type Manager = crate::manager::Manager<diesel::MysqlConnection>; /// Pool for using `...
use crate::entities::*; use crate::logics::reduce_points; use async_trait::async_trait; use chrono::prelude::{DateTime, Utc}; use failure::Error; use std::collections::HashMap; use uuid::Uuid; #[async_trait] pub trait Filter<T> { type Key; async fn filter(&self, key: &Self::Key) -> Result<Vec<T>, Error>; } #[...
//! Code generation and candidate evaluation for specific targets. pub mod fake; mod argument; mod context; pub use self::argument::{ArrayArgument, ArrayArgumentExt, ScalarArgument}; pub use self::context::{ ArgMap, ArgMapExt, AsyncCallback, AsyncEvaluator, Context, EvalMode, KernelEvaluator, Stabilizer, }; ...
use crate::concmap::*; use crate::memory::*; use crate::program::Program; use crate::{consistency, thread}; use std::sync::atomic::{AtomicU64, Ordering}; pub struct Cache { r: ConcurrentMap<Box<[u32]>, Future<Box<[thread::Promise]>>>, n_hits: AtomicU64, } impl Cache { #[inline] pub fn new() -> Self {...
pub struct CharStream { pub code: Vec<char>, pub index: usize, pub eof: bool } impl CharStream { pub fn peek (&self) -> char { self.code[self.index] } pub fn read (&mut self) -> char { let c = self.code[self.index]; if self.index >= self.code.len() - 1 { se...
use termion::event::Key; use components::App; use models::Mode; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Outcome { Continue, Quit, } #[derive(Debug)] pub struct KeyManager {} impl KeyManager { pub fn new() -> Self { KeyManager {} } pub fn handle_key(&mut self, app: &mut App...
extern crate gl; extern crate gl_loader; extern crate glfw; extern crate stb_image; use glfw::Context; use std::ffi::{c_void, CStr}; use std::ptr::null; use crate::helpers::log; use crate::ui; pub struct App { pub glfw: glfw::Glfw, pub imgui: imgui::Context, pub imgui_glfw: ui::ImguiGLFW, pub window:...
use nabi; use abi; use handle::Handle; pub struct Wasm(pub(crate) Handle); impl Wasm { pub fn compile(wasm: &[u8]) -> nabi::Result<Wasm> { let res: nabi::Result<u32> = unsafe { abi::wasm_compile(wasm.as_ptr(), wasm.len()) }.into(); res.map(|index| Wasm(Handle(index))) } }
//! # [Functions] supported by InfluxQL //! //! [Functions]: https://docs.influxdata.com/influxdb/v1.8/query_language/functions/ use std::collections::HashSet; use once_cell::sync::Lazy; /// Returns `true` if `name` is a mathematical scalar function /// supported by InfluxQL. pub fn is_scalar_math_function(name: &st...
use floor_sqrt::floor_sqrt; use proconio::{input, marker::Usize1}; fn main() { input! { n: usize, q: usize, a: [usize; n], lr: [(Usize1, usize); q], }; let b = 1.max(n / floor_sqrt(q as u64) as usize); let mut lri = lr.into_iter().enumerate().collect::<Vec<_>>(); lr...
pub mod addon; pub mod backup; pub mod cache; pub mod catalog; pub mod config; pub mod curse_api; pub mod error; pub mod fs; pub mod murmur2; pub mod network; pub mod parse; #[cfg(feature = "gui")] pub mod theme; pub mod tukui_api; pub mod utility; pub mod wowi_api; use crate::error::ClientError; pub type Result<T> =...
#[doc = "Reader of register MPCBB1_VCTR34"] pub type R = crate::R<u32, super::MPCBB1_VCTR34>; #[doc = "Writer for register MPCBB1_VCTR34"] pub type W = crate::W<u32, super::MPCBB1_VCTR34>; #[doc = "Register MPCBB1_VCTR34 `reset()`'s with value 0"] impl crate::ResetValue for super::MPCBB1_VCTR34 { type Type = u32; ...
use derive_more::{Display, Error}; use actix_web::{HttpResponse, dev::HttpResponseBuilder, error, http::{StatusCode, header}}; #[derive(Debug, Display, Error)] pub enum MServerError { #[display(fmt = "internal error")] InternalError, #[display(fmt = "bad request")] BadClientData, #[display(fmt = "...
#[doc = "Reader of register OPAMP6_CSR"] pub type R = crate::R<u32, super::OPAMP6_CSR>; #[doc = "Writer for register OPAMP6_CSR"] pub type W = crate::W<u32, super::OPAMP6_CSR>; #[doc = "Register OPAMP6_CSR `reset()`'s with value 0"] impl crate::ResetValue for super::OPAMP6_CSR { type Type = u32; #[inline(always...
// Copyright 2019-2020 PolkaX. Licensed under MIT or Apache-2.0. use super::*; use bytes::Bytes; use cid::{Cid, IntoExt}; use ipld_core::struct_to_cbor_value; #[test] fn test_kv() { let b: Bytes = vec![1_u8, 2, 3].into(); let v = struct_to_cbor_value(&b).unwrap(); let kv: KVT = ("123".to_string(), v); ...
mod arrow_interop; mod clickhouse; mod error; mod frame; mod geom; mod utils; use pyo3::{prelude::*, wrap_pyfunction, Python}; use tracing_subscriber::EnvFilter; use crate::clickhouse::init_clickhouse_submodule; use crate::frame::{PyDataFrame, PyH3DataFrame}; use crate::geom::init_geom_submodule; /// version of the ...
use core::sync::atomic::{AtomicU32, Ordering}; static NEXT: AtomicU32 = AtomicU32::new(1); pub fn rand() -> u32 { loop { let cur = NEXT.load(Ordering::Relaxed); let next = cur * 214013 + 2531011; let old = NEXT.compare_and_swap(cur, next, Ordering::Relaxed); if old == cur { return (next >> 16)...
use std::path::Path; use std::process::Command; fn main() { let files = vec!["Message Passing and PubSub.mp4"]; let src_path = "/home/susilo/Videos"; for x in files { let path = Path::new(x); let path_name = format!("{}/{}", src_path.to_owned(), x); let ext = get_ext(&path); ...
extern crate sfml; use sfml::graphics::{Color, RenderTarget, RenderWindow, Sprite, Texture, Transformable}; use sfml::window::{Event, Key, Style}; use std::thread::sleep; use std::time::Duration; use cpu::CPU; use machine::clock::Clock; mod clock; pub mod io; // 1 Billion nanoseconds divided by 2 million cycles a ...
// This file is part of linux-epoll. It is subject to the license terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/linux-epoll/master/COPYRIGHT. No part of linux-epoll, including this file, may be copied, modified, propagated, or distri...
extern crate game_1; mod game; pub use game::*;
#![feature(test)] #![feature(specialization)] extern crate test; extern crate rand; extern crate num_traits; #[macro_use] mod macros; pub mod arithimpl; pub mod traits; pub mod core; pub mod coding; pub use traits::*; pub use coding::*; pub use core::Keypair; pub use core::standard::EncryptionKey; pub use core::crt...
fn main() { cxx_build::bridge("src/main.rs") .file("src/blobstore.cc") .flag_if_supported("-std=c++14") .compile("cxx-demo") }
// Get Maximum in Generated Array // https://leetcode.com/explore/challenge/card/january-leetcoding-challenge-2021/581/week-3-january-15th-january-21st/3605/ pub struct Solution; const SIZE: usize = 101; impl Solution { pub fn get_maximum_generated(n: i32) -> i32 { let mut nums: [i32; SIZE] = [0; SIZE]; ...
pub enum SVMError { InvalidMemory, InvalidRegister, InvalidOpCode, StackEmpty, WriteError, ReadError, }
use P80::graph_converters::{labeled, unlabeled}; pub fn main() { let g = unlabeled::from_string("[b-c, f-c, g-h, d, f-b, k-f, h-g]"); println!( "unlabeled graph (graph-term form)\n{:?}", unlabeled::to_term_form(&g) ); let g = labeled::from_string("[k, m-p/5, m-q/7, p-q/9]"); printl...
#![no_std] #[macro_use] extern crate crypto_tests; extern crate rc2; use crypto_tests::block_cipher::{BlockCipherTest, encrypt_decrypt}; extern crate block_cipher_trait; use block_cipher_trait::generic_array::GenericArray; use block_cipher_trait::BlockCipher; #[test] fn rc2() { let tests = new_block_cipher_test...
mod buf; pub(crate) mod drain; pub(crate) mod exec; pub(crate) mod io; mod lazy; mod never; pub(crate) use self::buf::StaticBuf; pub(crate) use self::exec::Exec; pub(crate) use self::lazy::{lazy, Started as Lazy}; pub use self::never::Never;
pub struct MemorySet { pub mapping: Mapping, pub segment: Vec<segment>, } impl MemorySet { pub fn new_kernel() -> MemoryResult<MemorySet> { extern "c" { fn text_start(); fn rodata_start(); fn data_start(); fn bss_start(); } let segmen...
use std::ptr; use std::mem; use std::alloc; use libc; fn alloc(size: usize) -> *mut u8 { let align = mem::align_of::<usize>(); let layout = alloc::Layout::from_size_align(size, align).unwrap(); unsafe { alloc::alloc(layout) } } fn dealloc(ptr: *mut u8, size: usize) { let align = mem::alig...
use std::env; use std::fs::File; use std::io; use std::io::Read; fn main() { let file_content = open_file(); lex(&file_content); } fn open_file() -> String { let first_arg: String = env::args().nth(1).expect("Please enter a valid filename"); let file_content: String = read_to_string(&first_arg).expect...
use super::{all_fields, Value}; use std::collections::BTreeMap; /// Iterates over all paths in form "a.b[0].c[1]" in alphabetical order. /// It is implemented as a wrapper around `all_fields` to reduce code /// duplication. pub fn keys<'a>(fields: &'a BTreeMap<String, Value>) -> impl Iterator<Item = String> + 'a { ...
use crate::prelude::*; use std::os::raw::c_void; use std::ptr; #[repr(C)] #[derive(Debug)] pub struct VkRayTracingShaderGroupCreateInfoNV { pub sType: VkStructureType, pub pNext: *const c_void, pub r#type: VkRayTracingShaderGroupTypeNV, pub generalShader: u32, pub closestHitShader: u32, pub an...
use std::{num::NonZeroU32, sync::mpsc, time::Instant}; use vulkayes_core::{ash::vk, log, memory::device::naive::NaiveDeviceMemoryAllocator, prelude::*, resource::image::params::ImageViewRange}; use vulkayes_window::winit::winit; use winit::window::Window; pub mod frame; pub mod input; pub mod setup; use std::ops::De...
use anyhow::Result; use reqwest::Error; use serde::{Deserialize, Serialize}; use std::time::{Duration, Instant}; #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct RootMatcha { pub price: String, pub guaranteed_price: String, pub to: String, ...
/// CBOR len: either a fixed size or an indefinite length. #[derive(Debug, PartialEq, Eq, Copy, Clone)] pub enum Len { Indefinite, Len(u64), } impl Len { pub fn is_null(&self) -> bool { matches!(self, Self::Len(0)) } pub fn non_null(self) -> Option<Self> { if self.is_null() { ...
extern crate jlib; use jlib::api::account_tums::api::request; use jlib::api::account_tums::data::{RequestAccountTumsResponse, AccounTumSideKick}; use jlib::api::config::Config; static TEST_SERVER: &'static str = "ws://101.200.176.249:5040"; fn main() { let config = Config::new(TEST_SERVER, true); let account...
#[doc = "Reader of register DRIM"] pub type R = crate::R<u32, super::DRIM>; #[doc = "Writer for register DRIM"] pub type W = crate::W<u32, super::DRIM>; #[doc = "Register DRIM `reset()`'s with value 0"] impl crate::ResetValue for super::DRIM { type Type = u32; #[inline(always)] fn reset_value() -> Self::Typ...
use crate::metrics::{self, SLASHER_DATABASE_SIZE, SLASHER_RUN_TIME}; use crate::Slasher; use directory::size_of_dir; use slog::{debug, error, info, trace}; use slot_clock::SlotClock; use std::sync::mpsc::{sync_channel, TrySendError}; use std::sync::Arc; use task_executor::TaskExecutor; use tokio::stream::StreamExt; use...
pub mod binary_reader; pub mod binary_writer; pub mod huffman; pub mod compress; pub mod decompress; pub use compress::{compress_file, show_freq_and_dict}; pub use decompress::decompress_file; #[cfg(test)] mod tests { #[test] fn it_works() { assert_eq!(2 + 2, 4); } }
//! //! Utils Module //! pub mod payload; pub mod random_seed;
use rbatis::crud::CRUDTable; use rbatis_macro_driver::CRUDTable; use serde::Deserialize; use serde::Serialize; use strum_macros::EnumIter; use wallets_macro::{db_append_shared, DbBeforeSave, DbBeforeUpdate}; use crate::kits; use crate::ma::dao::{self, Shared}; use crate::ma::MTokenShared; #[derive(PartialEq, Clone, ...
use std::{io, fmt::{self, Display, Formatter}, error::Error}; macro_rules! description { ($err : expr) => ( <String as AsRef<str>>::as_ref(&format!("{}", $err)) ); } #[derive(Debug)] /// The error type for operations of the `Decode` trait. pub enum DecodingError { /// A generic IO error. Io(io::...
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)] #[link(name = "windows")] extern "system" { pub fn NdfCancelIncident(handle: *const ::core::ffi::c_void) -> ::windows_sys::core::HRESULT; pub fn NdfCloseIncident(handle: *mut ::core::ffi::c_void) -...
use std::collections::HashMap; use std::env; use std::ffi::{CStr, CString}; use std::fs::*; use std::io::Write; use std::os::raw::{c_void, c_char}; use std::path::*; use std::io::Read; use build_util::*; use spirv_cross_sys; fn main() { let pkg_dir = env::var("CARGO_MANIFEST_DIR").unwrap(); let shader_dir = Path::...
#![deny(clippy::use_self)] use macros::serialize; #[derive(serialize)] pub enum Direction { East, }
/*! Validates strings and computes check digits using the Luhn algorithm. It's not a great checksum, but it's used in a bunch of places (credit card numbers, ISIN codes, etc.). More information is available on [wikipedia](https://en.wikipedia.org/wiki/Luhn_algorithm). */ use digits_iterator::DigitsExtension; /// Va...
use std::error::Error; use std::fmt; #[derive(Debug)] pub enum GameError { IoError(Box<dyn Error>), InitError(Box<dyn Error>), StateError(Box<dyn Error>), RuntimeError(Box<dyn Error>), NotSupportedError(Box<dyn Error>), } impl Error for GameError { fn source(&self) -> Option<&(dyn Error + 'st...
use std::{fmt, io}; use crate::{tag::Tag, Identifier}; pub type Result<T, E = Error> = ::std::result::Result<T, E>; /// Points to a record data. #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub enum Pointer { /// Points to a record leader. Leader, /// Points to a filed. Field(Tag), /// Points to ...
use std::str::FromStr; use oasis_core_runtime::{ common::{quantity::Quantity, versioned::Versioned}, consensus::{ roothash::{Message, StakingMessage}, staking, }, }; use crate::{ context::{BatchContext, Context}, modules::consensus::Module as Consensus, testing::{keys, mock}, ...
mod solver; mod brute_force; use prob1::solver::Solver; use prob1::brute_force::BruteForceSolver; pub fn demo(upper_limit: u32) { println!("Brute Force answer: {}", BruteForceSolver::new(upper_limit).solve()); }
use std::env; use std::path::PathBuf; use clap::{App, AppSettings, Arg, ArgGroup, ArgMatches, SubCommand}; use crate::templates; const NAME: &str = "cargo-eval"; #[inline(always)] const fn name() -> &'static str { NAME } #[inline(always)] fn subcommand_name() -> &'static str { &name()[6..] } pub fn data_d...
use std::fs; fn main() { let filename = "inputs/q13_input.txt"; let contents = fs::read_to_string(filename) .expect("Could not read the file") .lines() .take(2) .map(String::from) .collect::<Vec<String>>(); let earliest_depart = &contents[0].parse::<f32>().unwrap();...
use crate::backend::c; /// `sysinfo` #[cfg(linux_kernel)] pub type Sysinfo = c::sysinfo; #[cfg(not(target_os = "wasi"))] pub(crate) type RawUname = c::utsname;
use async_graphql::http::MultipartOptions; use poem::{ async_trait, error::BadRequest, http::{header, Method}, FromRequest, Request, RequestBody, Result, }; use tokio_util::compat::TokioAsyncReadCompatExt; /// An extractor for GraphQL request. /// /// You can just use the extractor as in the example be...
use bitvec::prelude::*; use thiserror::Error; #[allow(clippy::identity_op)] // look, the << 0 makes it look neater IMO fn pop_u5_from_bitvec(x: &mut BitVec<Msb0, u8>) -> u8 { let mut v = 0; v |= (*x.get(0).unwrap_or(&false) as u8) << 4; v |= (*x.get(1).unwrap_or(&false) as u8) << 3; v |= (*x.get(2).un...
use std::num::Wrapping; use num::{ Integer, Float, cast, NumCast }; use std::ops::{ Mul, Div }; pub type Timestamp = u64; pub type TimestampDiff = i64; // UWB microsecond (uus) to device time unit (dtu, around 15.65 ps) conversion factor. // 1 uus = 512 / 499.2 µs and 1 µs = 499.2 * 128 dtu. pub const ...