text
stringlengths
8
4.13M
use {hyper, mime, serde, serde_json, std, url, uuid}; use transport::{JsonResponse, StatusCode}; /// Contains information for an error originating from or propagated by Chill. #[derive(Debug)] pub enum Error { #[doc(hidden)] ChannelReceive { cause: std::sync::mpsc::RecvError, description: &'sta...
use std::collections::HashMap; use criterion::{black_box, criterion_group, criterion_main, Criterion}; use timely::dataflow::channels::pact::Pipeline; use timely::dataflow::operators::{Operator, ToStream}; trait JoinValue: Clone + std::hash::Hash + Eq { fn name() -> &'static str; fn new(i: usize) -> Self; } ...
use std::rc::Rc; use std::sync::Arc; use std::sync::atomic::AtomicBool; use libbeaglebone::pins::Pin; use crate::benchmarking::ControllerBench; use crate::builder::assembly::RobotAssembler; use crate::builder::factories::digital_monitor::DigitalMonitorFactory; use crate::builder::factories::drive::PrintDriveFactory; ...
use std::borrow::Cow; use std::collections::HashSet; use std::sync::Arc; use tokio::time::Instant; use command_data_derive::CommandData; use discorsd::{async_trait, BotState}; use discorsd::commands::*; use discorsd::errors::BotError; use discorsd::http::channel::MessageChannelExt; use discorsd::model::ids::MessageId...
use super::{ scm::{ Scm, SPECIAL_FALSE, SPECIAL_NULL, SPECIAL_TRUE, SPECIAL_UNINIT, TAG_INTEGER, TAG_MASK, TAG_PAIR, TAG_POINTER, }, ScmBoxedValue, }; impl std::fmt::Display for Scm { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { match (self.ptr, self.ptr & TA...
//! This is the same than alternate_screen but using //! the command API instead of the "old style" direct //! unbuffered API. use std::{ io::{stdout, Write}, thread, time, }; use crossterm::{ cursor::{Hide, MoveTo, Show}, queue, screen::{EnterAlternateScreen, LeaveAlternateScreen}, style::{st...
use crate::consts::TYPENAME_FIELD_NAME; use crate::context::{FieldSet, QueryPlanningContext}; use crate::model::ResponsePath; use graphql_parser::query::FragmentDefinition; use graphql_parser::schema; use graphql_parser::schema::TypeDefinition; use linked_hash_map::LinkedHashMap; #[derive(Debug)] pub(crate) struct Fet...
//! This modules contains code that is to be reused from many tests //! The test here is mostly to silence used code warnings, and to force all utils //! to be compiles and are NOT for testing this module //! extern crate env_logger; extern crate regex; use std::sync::{Once, ONCE_INIT}; use std::sync::Arc; use mongo_...
//! This is the jail crate. //! //! it aims to provide the features exposed by the FreeBSD Jail Library //! [jail(3)](https://www.freebsd.org/cgi/man.cgi?query=jail&sektion=3&manpath=FreeBSD+11.1-stable) extern crate libc; pub mod process; extern crate errno; use errno::errno; use std::ffi::{CStr, CString}; use std...
$NetBSD: patch-vendor_libc_src_unix_solarish_mod.rs,v 1.11 2023/01/23 18:49:04 he Exp $ Fix xattr build. --- vendor/libc/src/unix/solarish/mod.rs.orig 2019-05-20 13:47:24.000000000 +0000 +++ vendor/libc/src/unix/solarish/mod.rs @@ -1215,6 +1215,8 @@ pub const EOWNERDEAD: ::c_int = 58; pub const ENOTRECOVERABLE: ::c_...
pub mod macros; pub mod compositor; pub mod config; pub mod event; pub mod geometry; pub mod input; pub mod output; pub mod output_management_protocol; pub mod output_manager; pub mod shell; pub mod surface; pub mod wayland_timer; pub mod window; pub mod window_management_policy; pub mod window_manager; #[cfg(test)] ...
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ // signal handling related tests. use reverie::syscalls::ExitGroup; use reverie::syscalls::Syscall...
use crate::string::*; #[test] fn unescape_() { assert_eq!(unescape("abc"), Some("abc".to_string())); assert_eq!(unescape("\\0"), Some("\0".to_string())); assert_eq!(unescape("\\a"), Some("\x07".to_string())); assert_eq!(unescape("\\b"), Some("\x08".to_string())); assert_eq!(unescape("\\t"), Some("\...
use std::{ borrow::Cow, collections::VecDeque, convert::{TryFrom, TryInto}, error::Error, fmt::{Debug, Display}, iter::Peekable, }; use itertools::Itertools; use crate::{input::*, prelude::*}; pub fn parse(text: &str) -> Result<InputTerm, ParseErrors> { parse_term(build_token_tree(tokeniz...
#[doc = "Register `STGENC_CNTCVL` reader"] pub type R = crate::R<STGENC_CNTCVL_SPEC>; #[doc = "Register `STGENC_CNTCVL` writer"] pub type W = crate::W<STGENC_CNTCVL_SPEC>; #[doc = "Field `CNTCVL_L_32` reader - CNTCVL_L_32"] pub type CNTCVL_L_32_R = crate::FieldReader<u32>; #[doc = "Field `CNTCVL_L_32` writer - CNTCVL_L...
#![feature(plugin)] #![plugin(rocket_codegen)] extern crate chrono; extern crate rocket; //extern crate clap; extern crate itertools; #[macro_use] extern crate quick_error; extern crate sha2; mod transaction; mod transaction_log; use std::fs::OpenOptions; use std::sync::Mutex; use rocket::response::status; use rocke...
use std::{ ffi::{OsStr, OsString}, str::FromStr, }; use hashbrown::HashMap; use tracing::{info, trace}; //use bumpalo::{boxed::Box as BBox, Bump}; #[derive(Debug, PartialEq, Eq, Clone)] pub enum Perms { Read, Write, } impl Default for Perms { fn default() -> Self { Self::Read } } #[...
pub fn run() -> u64 { (100..1000u64) .flat_map(|x| { (100..1000u64).filter_map(move |y| { let prod = x * y; if is_palindrome(&prod.to_string()) { Some(prod) } else { None } }) }) .max() .unwrap() } fn is_palindrome(string: &str) -> bool { string.chars().eq(string.chars().rev()...
use std::fmt::{Display, Formatter}; use std::sync::mpsc::Sender; use std::thread; use std::time::SystemTime; use std::time::Duration; use std::path::Path; use std::io::prelude::*; use std::io::ErrorKind; use std::collections::VecDeque; use Payload; use sensor_lib::SensorValue; use serial::prelude::*; use serial::uni...
use sdl2::pixels::Color; #[derive(Clone, Debug, PartialEq)] pub struct CaretColor { bright: Color, blur: Color, } impl CaretColor { pub fn new(bright: Color, blur: Color) -> Self { Self { bright, blur } } pub fn bright(&self) -> &Color { &self.bright } pub fn blur(&self) ...
use alloc::string::String; use crate::Client; use chain::names::AccountName; use rpc_codegen::Fetch; use serde::{Deserialize, Serialize}; #[derive(Fetch, Debug, Clone, Serialize)] #[api(path="v1/chain/get_info", http_method="POST", returns="GetInfo")] pub struct GetInfoParams {} pub const fn get_info() -> GetInfoPara...
pub(crate) mod linear;
pub mod repo; pub mod repo_list; pub mod help; use crate::registry::RepoName; use seed::{log, Url}; pub enum Page { RepoList(repo_list::Model), Repo(repo::Model), Help, NotFound, } #[derive(Debug)] pub enum Route { RepoList, Repo(RepoName), Help, NotFound, } pub fn route(mut url: Url...
#[crate_id = "graphics2d"]; #[crate_type = "lib"]; #[warn(non_camel_case_types)]; #[feature(managed_boxes)]; extern mod std; extern mod extra; extern mod rsfml; extern mod nphysics = "nphysics2df32"; extern mod nalgebra; extern mod ncollide = "ncollide2df32"; pub mod simulate; pub mod engine; pub mod camera; pub mo...
use clap::App; use glab::{cmd, toml_string, utils::git, BANNER}; fn main() { let matches = App::new(toml_string("name")) .version(toml_string("version").as_str()) .about(toml_string("description").as_str()) .before_help(BANNER) .long_version(format!("{}\nGit: {}", toml_string("versi...
use crate::system:: { System, SystemError, CommandLineOutput }; use std::fs; use std::io::ErrorKind; use std::path::Path; use std::time::SystemTime; use execute::Execute; #[derive(Debug, Clone)] pub struct RealSystem { } impl RealSystem { pub fn new() -> Self { RealSystem{} } } fn co...
use super::configuration::Configuration; use super::database::DatabaseController; use super::database_errors::DatabaseError; #[derive(Clone)] pub struct Server { pub database: DatabaseController, pub address: [u8; 4], pub port: u16, pub hostname: String } impl Server { pub fn instance(config: &Con...
use std::fmt; use std::rc::Rc; use crate::rt::{Error, Runtime, Value}; use crate::syntax::{ImSymbolMap, Symbol}; #[derive(Clone)] pub struct Builtin(Rc<dyn Fn(Value) -> Result<Value, Error>>); impl Builtin { pub(in crate::rt) fn exec(&self, ctx: &mut Runtime) -> Result<(), Error> { let arg = ctx.pop_stac...
use std::env; use std::io; use std::io::Write; use pickpocket::{BeginAuthentication, Client}; fn consumer_key() -> String { let key = "POCKET_CONSUMER_KEY"; match env::var(key) { Ok(val) => val, Err(_) => { print!("Please, type in your consumer key: "); io::stdout() ...
fn main() { move_string(); move_string_para(); move_box(); } fn move_string() { let s1 = String::from("Hello World"); // string变量类型的赋值是所有权的转移 // // s1转移给s2, s1不再存在 let s2 = s1; assert_eq!(s2.as_str(), "Hello World"); // 编译报错 println!("{}", s1); } fn move_string_para() { l...
use hey_listen::{ sync::{Dispatcher, Listener, SyncDispatcherRequest}, RwLock, }; use std::{ops::Deref, sync::Arc}; #[derive(Clone, Eq, Hash, PartialEq)] enum Event { VariantA, VariantB, } struct EventListener { received_variant_a: bool, received_variant_b: bool, } impl Listener<Event> for Ev...
extern crate clap; use clap::{App, Arg}; use std::fs; use std::io::prelude::{Read, Write}; use std::net::{TcpListener, TcpStream}; mod handlers; pub mod util; fn get_port<'a>() -> u32 { let matches = App::new("web-server-rs") .author("AmirrezaAsk") .about("Simple HTTP web server in rust") ....
use crate::{ tokenizers::FullPathForChars, field_paths::FieldPaths, }; use core_extensions::SelfOps; use proc_macro2::TokenStream as TokenStream2; use quote::quote; use syn::Ident; /// This is the implementation of the FP macro when /// the input isn't space separated characters. #[allow(non_snake_case)]...
mod gen; use crate::gen_three_address_code::gen::{Data, Gen}; use crate::symbol_table::SymbolTable; use crate::three_address_code::ThreeAddressCode; pub trait GenThreeAddressCode { fn gen_three_address_code( &self, symbol_table: &SymbolTable, current_table: usize, ) -> ThreeAddressCode...
enum Foo { Bar, Baz, Quix(u32), } #[cfg(test)] mod tests { use super::*; #[test] fn iffy() { let number = 3; if number < 5 { println!("too true") } else { println!("too not") } } #[test] fn loopy() { let mut counter...
/* * Copyright Stalwart Labs Ltd. See the COPYING * file at the top-level directory of this distribution. * * Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or * https://www.apache.org/licenses/LICENSE-2.0> or the MIT license * <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your * optio...
use std::f64; use wasm_bindgen::prelude::*; use wasm_bindgen::JsCast; pub struct BodyRenderData { pub x: f64, pub y: f64, pub radius: f64 } pub struct RenderData { pub bodies: Vec<BodyRenderData> } pub struct Renderer { context: web_sys::CanvasRenderingContext2d } impl Renderer { pub fn new(...
extern crate libc; use libc::c_char; use libc::c_int; use std::ffi::CStr; use std::ffi::CString; use std::process::Command; use std::process::ExitStatus; use std::ptr; #[derive(Debug, Clone)] #[repr(C)] pub struct Response { pub output: *const c_char, pub err: *const c_char, pub status_code: c_int, } imp...
/// An enum to represent all characters in the Bhaiksuki block. #[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)] pub enum Bhaiksuki { /// \u{11c00}: '𑰀' LetterA, /// \u{11c01}: '𑰁' LetterAa, /// \u{11c02}: '𑰂' LetterI, /// \u{11c03}: '𑰃' LetterIi, /// \u{11c04}: '𑰄' Lette...
//! Tests auto-converted from "sass-spec/spec/values/identifiers/escape" #[allow(unused)] use super::rsass; // From "sass-spec/spec/values/identifiers/escape/normalize" #[test] fn normalize() { assert_eq!( rsass( ".normalize {\ \n // TODO: remove unnecessary parentheses when we\'re...
//! ITP1_7_B の回答 //! [https://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ITP1_7_B](https://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ITP1_7_B) use std::io::BufRead; #[allow(dead_code)] pub fn main() { loop { if let Some(numbers) = read_numbers(std::io::stdin().lock()) { if numbe...
pub fn raindrops(n: u32) -> String { let mut s = String::new(); let plings = [(3, "Pling"), (5, "Plang"), (7, "Plong")]; for (divisor, effect) in plings.iter() { if n % divisor == 0 { s.push_str(effect); } } if s.is_empty() { s.push_str(n.to_string().as_str());...
//! Link: https://adventofcode.com/2019/day/5 //! Day 5: Sunny with a Chance of Asteroids //! //! You're starting to sweat as the ship makes its way toward Mercury. //! The Elves suggest that you get the air conditioner working //! by upgrading your ship computer to support //! the Thermal Environment Supervision Ter...
// Copyright (C) 2015-2021 Swift Navigation Inc. // Contact: https://support.swiftnav.com // // This source is subject to the license found in the file 'LICENSE' which must // be be distributed together with this source. All other rights reserved. // // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ...
use crate::types::Position; use std::cmp::Ordering; #[derive(Debug)] pub struct HeapElement { pub pos: Position, pub dist: f64, } impl Ord for HeapElement { fn cmp(&self, other: &Self) -> Ordering { match self.dist.partial_cmp(&other.dist) { None => Ordering::Equal, Some(o)...
//! This module implements helpers for generating label maps. use std::collections::HashMap; use std::fs::OpenOptions; use std::io::{BufWriter, Error as IoError, Write}; use std::path::Path; use thiserror::Error; use crate::tensorflow_protos::string_int_label_map::{StringIntLabelMap, StringIntLabelMapItem}; #[derive...
// to link a crate to this new library you may use `rustc` `--extern` flag. // All of its items will then be imported under a module named the same // as the library. This module generally behaves the same way as any // other module fn main() { rary::public_function(); rary::indirect_access(); }
static mut LEVELS: u32 = 450; fn main() { let c = 'z'; println!("c is : {}", c); println!("static is : {}", LEVELS) let s = String::from("hello"); println!("String is : {}", s); let mut s1 = String::from(s); s1.push_str(", world!"); // push_str() appends a literal to a String println!("{}", s1)...
use crate::{ models::statement_of_account::{ NewStatementOfAccount, StatementOfAccount, UpdateStatementOfAccount, }, schema::{ statement_of_accounts, statement_of_accounts::dsl::statement_of_accounts as statement_of_accounts_query, }, }; use diesel::prelude::*; pub fn all(conn: ...
use crate::api::models::bridgechain::Bridgechain; use crate::api::models::business::Business; use crate::api::Result; use crate::http::client::Client; use std::borrow::Borrow; use std::collections::HashMap; pub struct Businesses { client: Client, } impl Businesses { pub fn new(client: Client) -> Businesses { ...
use super::*; #[test] fn test_client_empty_endpoint() { let config = Config::default(); let mut client = Client::from_config("test", config); assert!(client.to_info().is_ok()); assert!(client.boot(None).is_err()); assert!(client.get(None).is_err()); } //#[test] //fn test_client_1_no_determinism()...
/* Module: ptr Unsafe pointer utility functions */ #[abi = "rust-intrinsic"] native mod rusti { fn addr_of<T>(val: T) -> *T; fn ptr_offset<T>(ptr: *T, count: ctypes::uintptr_t) -> *T; } /* Function: addr_of Get an unsafe pointer to a value */ fn addr_of<T>(val: T) -> *T { ret rusti::addr_of(val); } /* Funct...
use crate::*; use gl::types::*; use openvr::ControllerState; use std::ops::{Index, IndexMut}; use std::slice::{Iter, IterMut}; pub struct VertexArray { pub vertices: Vec<f32>, pub indices: Vec<u16>, pub attribute_offsets: Vec<i32>, } pub struct MeshData { pub vertex_array: VertexArray, pub geo_bou...
use diesel::prelude::*; use chrono::NaiveDate; use schema::horus_license_keys; use models::License; use dbtools; #[derive(Insertable, Queryable, Serialize)] #[table_name = "horus_license_keys"] pub struct LicenseKey { pub key: String, pub privilege_level: i16, pub issued_on: NaiveDate, // DO NOT MEASURE T...
use std::env; use itertools::Itertools; fn main() { let input_path: &String = &env::args().nth(1).unwrap(); let p = intcode::read_from_path(input_path).unwrap(); let phases: Vec<i64> = vec!(0, 1, 2, 3, 4); let mut best: i64 = 0; for permutation in phases.into_iter().permutations(5) { let r...
// =============================================================================== // Authors: AFRL/RQQA // Organization: Air Force Research Laboratory, Aerospace Systems Directorate, Power and Control Division // // Copyright (c) 2017 Government of the United State of America, as represented by // the Secretary of th...
pub fn test_func() { println!("Test function."); } pub mod nest_module; pub mod inner_call_module;
use crate::{DeviceBox, DevicePtr}; /// Some data able to represent one or more kernel parameters pub trait KernelParameters { fn params(&self, out: &mut Vec<Vec<u8>>); } impl KernelParameters for u8 { fn params(&self, out: &mut Vec<Vec<u8>>) { out.push(vec![*self]); } } impl KernelParameters for ...
//! Largest prime factor //! //! Problem 3 //! //! The prime factors of 13195 are 5, 7, 13 and 29. //! //! What is the largest prime factor of the number 600851475143 ? use utils; fn run(num: u64) -> u64 { (2..num).filter(|i| num % i == 0 && utils::is_prime(*i)).max().unwrap() } #[cfg(test)] mod tests { use...
use std::cell::RefCell; use std::rc::Rc; #[derive(Copy, Clone)] pub enum ChargeCycle { Even, Odd, } impl ChargeCycle { // Note that prev_cycle and next_cycle // do the exact same thing pub fn next_cycle(&self) -> ChargeCycle { self.prev_cycle() } pub fn prev_cycle(&self) -> Charge...
use super::Mmapper; use crate::util::Address; use crate::util::constants::*; use crate::util::conversions::pages_to_bytes; use crate::util::heap::layout::vm_layout_constants::*; use std::fmt; use std::sync::atomic::AtomicU8; use std::sync::atomic::Ordering; use std::sync::Mutex; use crate::util::memory::{dzmmap, mpro...
use std::borrow::Borrow; use std::collections::BinaryHeap; use std::fmt::Debug; use std::fs::read_dir; use std::hash::Hash; use std::ops::Index; use std::path::PathBuf; use std::sync::atomic::{AtomicUsize, Ordering as AtomicOrder}; use std::sync::{Arc, RwLock, RwLockReadGuard}; use codec::BytesSerializer; use errors::...
/*! Traits related to arrays. # `Array*` traits The `Array*` traits alias the accessor traits for arrays, with shared,mutable,and by value access to every element of the array. These traits can be used with any array at least as large as the size indicated by the trait.<br> You can,for example,use `Array3` with any ...
#[doc = "Register `CWSIZE` reader"] pub type R = crate::R<CWSIZE_SPEC>; #[doc = "Register `CWSIZE` writer"] pub type W = crate::W<CWSIZE_SPEC>; #[doc = "Field `CAPCNT` reader - Capture count This value gives the number of pixel clocks to be captured from the starting point on the same line. It value must corresponds to...
fn main() { let distance = 100; println!("You are {} miles away.\n", distance); }
pub fn drop() { let mut s = "govinda".to_string(); println!("{}", s); s = "siddhartha".to_string(); // value "govinda" dropped here println!("{}", s); }
//! Types for interfacing with Python. use libc::{c_char, size_t}; use std::collections::HashMap; use std::convert::AsRef; use std::hash::Hash; #[doc(hidden)] #[inline(never)] #[cold] pub fn abort_and_exit(msg: &str) -> ! { use std::io::{stderr, stdout, Write}; use std::process; fn write<T: Write>(mut h...
#[doc = r"Register block"] #[repr(C)] pub struct RegisterBlock { #[doc = "0x00 - Key register"] pub iwdg_kr: IWDG_KR, #[doc = "0x04 - Prescaler register"] pub iwdg_pr: IWDG_PR, #[doc = "0x08 - Reload register"] pub iwdg_rlr: IWDG_RLR, #[doc = "0x0c - Status register"] pub iwdg_sr: IWDG_S...
//! Tests for the `cargo init` command. use std::process::Command; mod auto_git; mod bin_already_exists_explicit; mod bin_already_exists_explicit_nosrc; mod bin_already_exists_implicit; mod bin_already_exists_implicit_namenosrc; mod bin_already_exists_implicit_namesrc; mod bin_already_exists_implicit_nosrc; mod both_l...
#![warn(unused_crate_dependencies)] #![warn(clippy::pedantic)] #![warn(clippy::cargo)] #![allow(clippy::module_name_repetitions)] pub mod inv; pub mod nodebin_s3; pub mod package_json; pub mod vrs; #[cfg(test)] use ureq as _;
#[derive(Debug, Serialize, Deserialize)] pub struct Tile { pub id: usize, pub value: usize, pub row: usize, pub column: usize, pub old_row: isize, pub old_column: isize, pub merged: bool, pub merged_tiles: Vec<Tile> } impl Tile { pub fn new(id: usize) -> Tile { Tile { ...
mod json; #[cfg(feature = "yaml")] mod yaml; #[cfg(feature = "toml")] mod toml; use crate::{system::PathBuf, Result, Value}; use async_std::fs::{read, write}; pub(self) trait ValueStoreApi { fn load(&mut self, data: &[u8]) -> Result<()>; fn save(&self) -> Result<Vec<u8>>; fn get(&self, path: &[&str]) -...
use assembly_fdb::{ common::{Value, ValueType}, mem::{Database, Tables}, }; use mapr::Mmap; use std::{fs::File, path::PathBuf, time::Instant}; use structopt::StructOpt; #[derive(Debug, StructOpt)] /// Prints statistics on an FDB file struct Options { /// The FDB file file: PathBuf, } fn main() -> colo...
use std::fs::File; use std::io::{self, Error, Read}; use super::token::Position; pub struct Reader { pub filename: String, src: String, pos: usize, next_pos: usize, cur: Option<char>, line: usize, col: usize, tabwidth: usize, } impl Reader { pub fn from_input() -> Result<Reader,...
mod api_tests { use moebius_api::MoebiusApi; #[test] fn test_uniswap_oracle() { let moebius_api = MoebiusApi::new(); let result = moebius_api.uniswap_oracle( "1f9840a85d5af5bf1d1762f925bdaddc4201f984", "c778417e063141139fce010982780140aa0cd5ab", ); ...
#[test] fn test_success() {}
use serenity::{ client::Context, framework::standard::{macros::command, CommandResult}, model::channel::Message, }; use crate::{ common::{get_locale, redis::set, tt}, data::DatabasePool, reply, }; #[command] #[only_in(guilds)] async fn join(ctx: &Context, msg: &Message) -> CommandResult { ...
use super::{Open, Sink, SinkError, SinkResult}; use crate::config::AudioFormat; use crate::convert::Converter; use crate::decoder::AudioPacket; use crate::{NUM_CHANNELS, SAMPLE_RATE}; use sdl2::audio::{AudioQueue, AudioSpecDesired}; use std::thread; use std::time::Duration; pub enum SdlSink { F32(AudioQueue<f32>),...
use std::cmp::min; pub fn reverse_dismantle_vec(mut vector: Vec<i32>) { while vector.len() > 0 { match vector.pop() { Some(value) => println!("Found value: {}", value), None => {} }; } } pub fn forward_dismantle_vec(mut vector: Vec<i32>) { while vector.len() > 0 { ...
/*! The term dictionary main role is to associate the sorted [`Term`s](../struct.Term.html) to a [`TermInfo`](../postings/struct.TermInfo.html) struct that contains some meta-information about the term. Internally, the term dictionary relies on the `fst` crate to store a sorted mapping that associate each term to its ...
use crate::{ error::SendDuccError, util::JsEngine, Quiz, }; #[derive(Debug)] pub enum NonceError { Ducc(SendDuccError), } impl From<ducc::Error> for NonceError { fn from(e: ducc::Error) -> Self { Self::Ducc(SendDuccError::from_ducc_error_lossy(e)) } } #[derive(Debug, Clone, Eq, Partia...
use nannou::prelude::*; use crate::draw::Draw as MazeDraw; use crate::{generate::MazeGenerator, maze::Maze}; use super::Animator; pub struct AnimatorConfig { pub back_color: Rgb8, pub wall_color: Rgb8, pub wall_size: f32, pub y: f32, } pub struct MazeGenerationAnimator<T> { config: AnimatorConfi...
use fst::{self, IntoStreamer, Map, MapBuilder}; use fst_regex::Regex; use log::info; use qp_trie::{wrapper::BString, Trie}; use std::fs::File; use std::io::BufWriter; use std::path::Path; use std::time::Instant; use crate::surface_form::SurfaceForm; /// Build and serialise a FST from a Trie of flat anchors. fn build_...
#![feature(convert, custom_derive)] #[macro_use(bson, doc)] extern crate bson; extern crate mongodb as mongo; use std::sync::{Arc, Mutex}; use std::sync::mpsc::{Sender, Receiver, channel}; use std::cmp::{PartialOrd, PartialEq, Ordering}; use std::fmt::Display; use std::collections::BinaryHeap; use mongo::ThreadedCli...
use criterion::{criterion_group, criterion_main, Criterion}; use tokio::runtime::Runtime; async fn fetch_block(rest: &bitcoin_rest::Context, height: u32) { let blockhash = rest.blockhashbyheight(height).await.unwrap(); let _block = rest.block(&blockhash); } fn bench(c: &mut Criterion) { let rt = Runtime::...
// Iterator doc: https://doc.rust-lang.org/std/iter/trait.Iterator.html // Tterators, although a high-level abstraction, get compiled down to // roughly the same code as if you’d written the lower-level code yourself. // Iterators are one of Rust’s zero-cost abstractions, by which we mean // using the abstraction...
use hydroflow::hydroflow_syntax; use hydroflow::scheduled::graph::Hydroflow; use tokio::sync::mpsc::UnboundedSender; use tokio_stream::wrappers::UnboundedReceiverStream; use crate::protocol::{Timestamp, Token}; pub(crate) fn rga_datalog_agg( input_recv: UnboundedReceiverStream<(Token, Timestamp)>, rga_send: U...
use crate::hittable::{ aabb::Aabb, hittable_list::HittableList, rect::XyRect, rect::XzRect, rect::YzRect, HitRecord, Hittable, Hittables, }; use crate::material::MaterialType; use crate::ray::Ray; use crate::vec::Vec3; use rand::rngs::SmallRng; use std::sync::Arc; #[derive(Debug, Clone)] pub struct Box3D { ...
table! { auth_tokens (uid) { uid -> Int4, token -> Bpchar, expires -> Nullable<Timestamp>, privilege_level -> Int4, } } table! { deployment_keys (key) { key -> Varchar, deployments -> Int4, license_key -> Bpchar, } } table! { horus_files (id)...
wasm_bindgen_test_configure!(run_in_browser); // What's tested: // // Tests send to an echo server which just bounces back all data. // // ✔ Send a WsMessage::Text and verify we get an identical WsMessage back. // ✔ Send a WsMessage::Binary and verify we get an identical WsMessage back. // ✔ Send while closing and...
use crate::source::ByteArray; /// Trait used by the functions contained in the `Lexicon`. /// /// # WARNING! /// /// **This trait, and it's methods, are not meant to be used outside of the /// code produced by `#[derive(Logos)]` macro.** pub trait LexerInternal<'source> { /// Read the byte at current position. ...
#[doc = "Register `OFR1` reader"] pub type R = crate::R<OFR1_SPEC>; #[doc = "Register `OFR1` writer"] pub type W = crate::W<OFR1_SPEC>; #[doc = "Field `OFFSET1` reader - Data offset 1 for the channel programmed into bits OFFSET1_CH"] pub type OFFSET1_R = crate::FieldReader<u16>; #[doc = "Field `OFFSET1` writer - Data o...
use crate::db::*; use crate::parser::*; use std::collections::HashMap; use std::fmt; #[derive(Debug)] pub struct StorageManager { tables: HashMap<String, Table>, } pub enum StorageError { TableNotFound, SchemaMismatch, TypeError, TableNameAlreadyInUse, } impl fmt::Display for StorageError { f...
extern crate nfa; use nfa::*; #[test] fn empty() { let re = Regex::StrLiteral(String::new()); let fa = re.make_fa(); assert!(fa.accepts("")); for c in &['a', ' ', 'é'] { let mut s = String::new(); for _ in 0..100 { s.push(*c); assert!(!fa.accepts(&s)); } } } #[test] fn nonempty() { let re = Regex::...
#![feature(proc_macro_hygiene, decl_macro)] use mimalloc::MiMalloc; use rocket_contrib::json::Json; use serde::*; #[global_allocator] static ALLOC: MiMalloc = MiMalloc; use rocket::*; use crate::utils::{get_public, get_private, decrypt_message, empty_response}; use crate::database::get_database; use rocksdb::Iterator...
use bytes::{BufMut, Bytes, BytesMut}; use indoc::indoc; /// The struct for HTTP Response #[derive(Debug)] pub struct HTTPResponse { /// Status code of the response pub status_code: u32, /// HTTP Headers, represented by key-value pairs pub headers: Vec<(String, String)>, /// Body of the response ...
use std::sync::Arc; use hashring::HashRing; use rand::{prelude::SliceRandom, thread_rng}; use serde::{Deserialize, Serialize}; use vec1::Vec1; use crate::db::class::{ClassType, Object as Class}; #[derive(Debug, Clone, PartialEq, Eq, Hash, Deserialize, Serialize)] pub struct TurnHost(Arc<str>); #[cfg(test)] impl Fro...
use std::{thread, time}; pub mod threadpool; pub mod wsqueue1; #[macro_use] extern crate log; use log::{Level, LevelFilter, Metadata, Record}; struct SimpleLogger; impl log::Log for SimpleLogger { fn enabled(&self, metadata: &Metadata) -> bool { metadata.level() <= Level::Debug } fn log(&self, r...
use std::fs; use std::collections::{HashMap, VecDeque}; const MODE_POS: i64 = 0; const MODE_IMM: i64 = 1; const MODE_REL: i64 = 2; const OP_HALT: i64 = 99; const OP_ADD: i64 = 1; const OP_MULTIPLY: i64 = 2; const OP_INPUT: i64 = 3; const OP_OUTPUT: i64 = 4; const OP_JUMP_IF_TRUE: i64 = 5; const OP_JUMP_IF_FALSE: i64 ...
/// A link. #[derive(Debug)] pub struct Link { /// The link's URL. pub url: String, /// The text for the link. pub text: Content, } /// A table. #[derive(Debug)] pub struct Table { /// The table header. pub header: TableHeader, /// The table body. pub body: TableBody, } impl Table { ...