text
stringlengths
8
4.13M
// Copyright 2021 The NATS 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 required by applicable law or agreed to in wr...
pub mod io; pub mod scan; pub mod slagzet; pub mod user;
/** * [704] Binary Search * * Given an array of integers nums which is sorted in ascending order, and an integer target, write a function to search target in nums. If target exists, then return its index. Otherwise, return -1. You must write an algorithm with O(log n) runtime complexity.   Example 1: Input: nums = [...
#[allow(unused_imports)] use serde_json::Value; #[derive(Debug, Serialize, Deserialize)] pub struct JobJob { /// Impact policy of this job instance. #[serde(rename = "policy")] pub policy: Option<String>, /// Priority of this job instance; lower numbers preempt higher numbers. #[serde(rename = "pri...
use crate::reflect::runtime_types::RuntimeTypeTrait; use crate::reflect::ProtobufValue; use crate::reflect::ReflectValueRef; pub(crate) struct ReflectRepeatedIter<'a> { imp: Box<dyn Iterator<Item = ReflectValueRef<'a>> + 'a>, } impl<'a> ReflectRepeatedIter<'a> { pub(crate) fn new( iter: impl Iterator<...
use log::{debug, info, warn}; use notify::{RecommendedWatcher, Watcher}; use std::borrow::Cow; use std::borrow::Cow::*; use std::io::{Read, Seek, SeekFrom}; use std::path::PathBuf; use std::sync::{Arc, Mutex}; use crate::collector::LogData; use crate::log_parser::{LogValue, LogParser, ParseError}; pub struct Filter {...
extern crate rand; use self::rand::{Rng}; use std::iter::{repeat,Iterator}; pub fn rand<R>(size: usize, level: usize, rng: &mut R) -> Vec<i32> where R: Rng { let (nsize, ssize, fsize) = (size*size, size, size*size*size*size); let nums: Vec<i32> = (1..=(nsize as i32)).collect(); let mut working = Vec::...
// -------------------------- // ######### TESTS ########## // -------------------------- use super::*; // check test framework #[test] fn it_works() { assert_eq!(2 + 2, 4); } // example test // check that game state is in progress after initialisation #[test] fn game_in_progress_after_init() { let game = G...
//! Provides a generic decription of basic blocks. use ir; use std; /// Provides a unique identifer for a basic block. #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum BBId { Inst(ir::InstId), Dim(ir::dim::Id) } impl From<ir::InstId> for BBId { fn from(id: ir::InstId) -> Self { BBId::I...
use std::env; use std::io::Read; use std::io::Write; use std::os::unix::io::FromRawFd; use std::os::unix::io::RawFd; use std::os::unix::net::UnixStream; fn main() -> std::io::Result<()> { let args: Vec<String> = env::args().collect(); let socket_fd: RawFd = args[1].parse().unwrap(); println!("[Rust] Connec...
// Topic: User input // // Requirements: // * Verify user input against pre-defined keywords // * The keywords represent possible power options for a computer: // * Off // * Sleep // * Reboot // * Shutdown // * Hibernate // * If the user enters one of the keywords, a message should be printed to // the cons...
use super::*; use anyhow::anyhow; #[test] fn test_ok() { let handle = spawn(|| { thread::sleep(Duration::from_millis(100)); let result: Result<u64, anyhow::Error> = Ok(1); result }); let result = handle.join(Duration::from_millis(1000)); assert!(result.is_ok()); assert_eq!(1...
// This file is part of Substrate. // Copyright (C) Parity Technologies (UK) Ltd. // SPDX-License-Identifier: Apache-2.0 // 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.a...
use gw_types::packed::{ChallengeTarget, ChallengeWitness}; use std::fmt::{self, Display}; #[derive(Debug, Clone, Eq, PartialEq)] pub struct ChallengeContext { pub target: ChallengeTarget, pub witness: ChallengeWitness, } impl Display for ChallengeContext { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt:...
use diesel_derive_enum::DbEnum; use serde::{Deserialize, Serialize}; use std::fmt; /** * Enumeration containing all the kind of food a product can be. */ #[derive(DbEnum, Debug, Clone, Deserialize, Serialize)] #[DieselType = "Product_Kind"] pub enum ProductKind { Other, Vegetables, Fruit, Grain, ...
pub mod ast; pub mod cfg; pub mod frame_object; pub mod peachili_type; pub mod tld; pub mod token;
use winit::{MouseButton, VirtualKeyCode}; use super::controller::ControllerButton; use super::local_mouse_button::LocalMouseButton; use super::local_virtual_key_code::LocalVirtualKeyCode; /// A Button is any kind of digital input that the engine supports. #[derive(Eq, PartialEq, Debug, Copy, Clone, Serialize, Deseria...
#[derive(Debug, Deserialize)] /// A user object returned from the API pub struct User{ /// The username of the user pub username: String } #[derive(Debug, Deserialize)] /// An object containing the ID of something newly created pub struct Id<T> { /// The ID pub id: T } #[derive(Debug, Deserialize)] #[...
#[macro_export] macro_rules! log { (target: $target:expr, $lvl:expr, $($arg:tt)+) => ({ println!("{} - {} - {}", $target, $lvl, format_args!($($arg)*)); }); ($lvl:expr, $($arg:tt)+) => (log!(target: module_path!(), $lvl, $($arg)+)) } // // Hacked from https://doc...
use std::path::PathBuf; use clap::Parser; use log::warn; use crate::args::connections::Arguments; use crate::args::environment::Env; use crate::args::pg::PgArgs; use crate::args::srv::SrvArgs; use crate::args::State::{Ignore, Share, Take}; use crate::config::Config; use crate::file_config::FileConfigEnum; use crate::...
// This file is part of Substrate. // Copyright (C) Parity Technologies (UK) Ltd. // SPDX-License-Identifier: Apache-2.0 // 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.ap...
use rusty_engine::prelude::*; fn main() { let mut game = Game::new(); let mut race_car = game.add_actor("Player", ActorPreset::RacingCarGreen); race_car.translation = Vec2::new(0.0, 0.0); race_car.rotation = UP; race_car.layer = 100.0; race_car.collision = true; let mut actor_presets_iter...
// This file is part of Substrate. // Copyright (C) Parity Technologies (UK) Ltd. // SPDX-License-Identifier: Apache-2.0 // 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.a...
extern crate amethyst; use amethyst::assets::AssetStorage; use amethyst::audio::output::Output; use amethyst::audio::Source; use amethyst::core::timing::Time; use amethyst::core::transform::Transform; use amethyst::ecs::prelude::*; use amethyst::input::InputEvent; use amethyst::input::InputHandler; use amethyst::shrev...
use std::io; use std::cmp::min; use std::io::BufRead; fn parse_line(l : &str) -> (u64, u64, u64) { let v : Vec<&str> = l.split('x').collect(); assert!(v.len() == 3); let w = v[0].parse::<u64>().unwrap(); let h = v[1].parse::<u64>().unwrap(); let l = v[2].parse::<u64>().unwrap(); (w, h, l) } ...
extern crate libloading; extern crate libc; fn callback() -> () { println!("callback()"); } fn main() { println!("main()"); call_dynamic(); } fn call_dynamic() -> Result<u32, Box<dyn std::error::Error>> { unsafe { let lib = libloading::Library::new("lib.dll")?; let foo: libloading::Sy...
use crate::Logger; use colored::*; /// Create a custom logger. /// /// * `tag` - String to use as prefix (after scope). /// * `message` - String to print. /// * `scope` - Preffix to append. /// * `ln` - Use `eprintln` instead `eprint` (default: true). pub fn custom(tag: &ColoredString, message: &str, scope: Option<&st...
use super::shell_proxy; use crate::api::fetch_recommendations; use clipboard::{ClipboardContext, ClipboardProvider}; use crate::display; use lib_error::*; use lib_goo::config::{Destination, Environment, OutputKind}; use std::sync::Arc; pub fn run( destination: &Destination, output_kind: &OutputKind, env: ...
use chargrid_graphical::*; use pager_app::App; use std::io::{self, Read}; fn main() -> io::Result<()> { let mut text = String::new(); io::stdin().read_to_string(&mut text)?; let context = Context::new(ContextDescriptor { font_bytes: FontBytes { normal: include_bytes!("./fonts/PxPlus_IBM...
// // web.rs // pub mod cors; use crate::db; use crate::graphql::{Mutation, Query, Schema}; use kv::Store; use rocket::response::content; use rocket::State; #[get("/graphql/explorer")] fn graphiql() -> content::Html<String> { juniper_rocket::graphiql_source("/graphql") } #[options("/graphql")] fn post_graphql_co...
use rand::Rng; use std::{format}; use std::time::{Duration, SystemTime}; use std::collections::VecDeque; use std::sync::{Arc, Mutex, MutexGuard}; use crossbeam_channel::{Receiver,Sender}; use scheduled_thread_pool::ScheduledThreadPool; use std::io::{BufRead, BufReader, Seek, SeekFrom, BufWriter, Write}; use std::fs::...
use gl; use std::os::raw::c_void; // Note: This should probably be a trait. #[derive(Debug)] pub struct Mesh { pub vertices: Vec<f32>, pub indices: Option<Vec<u32>>, pub normals: Option<Vec<f32>>, pub uv: Option<Vec<f32>>, pub vbo_vertices: Option<u32>, pub vbo_indices: Option<u32>, pub v...
pub mod get_system_stats; pub mod get_cpu_and_mem_usage; pub mod get_cpu_name;
use std::path::Path; use std::fs; use toml; use failure::{Error, err_msg}; pub struct Config { token: String, } impl Config { pub fn load<T: AsRef<Path>>(path: T) -> Result<Self, Error> { let file = fs::read_to_string(path)?; let file: toml::Value = toml::from_str(&file)?; ...
use super::chrome_trace::Trace; use super::types::*; use serde_derive::{Deserialize, Serialize}; use std::sync::Arc; #[derive(Debug, Clone, std::cmp::PartialEq, std::cmp::PartialOrd, Hash, Serialize, Deserialize)] pub enum Source { Value(Id), Fn(usize, Id), } #[derive(Debug, Clone, Serialize, Deserialize)] pu...
use futures::stream::BoxStream; use nimiq_block::{Block, BlockType, MacroBlock}; use nimiq_hash::Blake2bHash; use nimiq_primitives::{ networks::NetworkId, policy::Policy, slots_allocation::{Validator, Validators}, }; use crate::{ error::{BlockchainError, BlockchainEvent, Direction}, ChainInfo, Fork...
struct Context { total: Vec<u32>, // The number of bytes processes state: Vec<u32>, // The intermediate digest state buffer: Vec<u8>, // The data block being processes unsigned char buffer[64]; } fn get_uint32_le(b: &[u8; 4]) -> u32{ return u32::from(b[0]) | u32::from(b[1]) << 8 ...
use ::*; #[derive(Vertex)] struct Vertex { a_pos: Vec2<f32>, } pub struct Game { nick: String, font: codevisual::Font, hex_geometry: ugli::VertexBuffer<Vertex>, quad_geometry: ugli::VertexBuffer<Vertex>, player_colors: HashMap<String, char>, player_hovers: HashMap<String, Vec2<usize>>, ...
use adb_rs::shell::AdbShell; use adb_rs::AdbClient; pub fn run(cmd: &str) { use std::io::{stdout, Write}; let mut conn = AdbClient::new("host::").connect("127.0.0.1:5555").unwrap(); stdout().write_all(&conn.shell_exec(cmd).unwrap()).unwrap(); }
pub use entities::intro::mega_ray::MegaRay; pub use entities::intro::mother::MotherIntro; pub use entities::intro::twin::TwinIntro; pub mod mega_ray; pub mod mother; pub mod twin;
struct Solution; impl Solution { fn reverse_string(s: &mut Vec<char>) { s.reverse(); } } #[test] fn test() { let mut input: Vec<char> = vec![]; let output: Vec<char> = vec![]; Solution::reverse_string(&mut input); assert_eq!(input, output); let mut input: Vec<char> = vec!['h', 'e',...
pub trait Operand : Clone { fn add(&self, other: Self) -> Result<Self, String>; fn subtract(&self, other: Self) -> Result<Self, String>; fn multiply(&self, other: Self) -> Result<Self, String>; fn divide(&self, other: Self) -> Result<Self, String>; fn equals(&self, other: Self) -> bool; fn convert(value: &str) ->...
use self::pointer_tagging::*; use crate::prelude::*; use std::{convert, default, fmt, ops}; pub mod cons; pub mod conversions; pub mod error; pub mod function; pub mod heap_object; pub mod immediate; pub mod list; pub mod namespace; pub mod number; mod pointer_tagging; pub mod reference; pub mod symbol; /// Every Pho...
pub mod amazon; pub mod dev; pub mod docker; pub mod github; pub mod gmail; pub mod google; pub mod reddit; pub mod twitter; pub mod youtube; pub fn get_command_from_query_string(query: &str) -> &str { if query.contains(' ') { let index_of_space = query.find(' ').unwrap_or(0); return &query[..index...
// Copyright 2021 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 ...
#[macro_use] mod macros; mod slateapp; mod newgame; mod tick; mod controller; use libc::{self, c_void, PROT_READ, PROT_WRITE, PROT_EXEC}; pub use self::slateapp::{hook_slateapp, FSlateApplication}; pub use self::newgame::hook_newgame; pub use self::tick::hook_tick; pub use self::controller::{hook_controller, AControl...
// Copyright 2019 WHTCORPS INC Project Authors. Licensed under Apache-2.0. pub mod fixture; mod util; use criterion::measurement::Measurement; use crate::util::scan_bencher::ScanBencher; use crate::util::store::*; use crate::util::BenchCase; const ROWS: usize = 5000; /// 1 interested PrimaryCauset, which is PK (wh...
use std::collections::HashMap; use std::io::{Error, ErrorKind}; pub fn lzw_encode(data: &[u8]) -> Result<Vec<u32>, Error> { // Build initial list. let mut list: HashMap<Vec<u8>, u32> = (0u32..=255).map(|i| (vec![i as u8], i)).collect(); let mut w = Vec::new(); let mut compressed = Vec::new(); for...
use crate::{ContributionMode, ProvingSystem}; #[derive(Debug, Clone)] pub enum CurveKind { Bls12_377, BW6, } pub fn curve_from_str(src: &str) -> Result<CurveKind, String> { let curve = match src.to_lowercase().as_str() { "bls12_377" => CurveKind::Bls12_377, "bw6" => CurveKind::BW6, ...
use crate::cmd::keybindings::KeyBindings; use crate::cmd::{get_command, CommandTag}; use crate::datastructure::generic::{Vec2, Vec2d, Vec2i}; use crate::debugger_catch; use crate::debuginfo::DebugInfo; use crate::opengl::types::RGBAColor; use crate::opengl::{ polygon_renderer::{PolygonRenderer, TextureMap, TextureT...
use candid::{CandidType, Nat}; use serde::Deserialize; /// Create a new batch, which will expire after some time period. /// This expiry is extended by any call to create_chunk(). /// Also, removes any expired batches. #[derive(CandidType, Debug)] pub struct CreateBatchRequest {} /// The response to a CreateBatchRequ...
use std::io::Read; use std::io; use std::env; use std::fs::File; use std::process::exit; struct Engine { dp: usize, // data pointer ip: usize, // instruction pointer memory: Vec<u8>, // memory buffer code: Vec<u8>, // instructions } impl Engine { fn new() -> Self { ...
//! Sequential stacks. /// A sequential stack. /// /// Represented as a linked list, so all operations are O(1). /// /// # Example /// /// ``` /// use stacks::sequential::Stack; /// /// let mut stack = Stack::new(); /// /// stack.push(3); /// stack.push(4); /// stack.push(5); /// assert_eq!(Some(5), stack.pop()); /// ...
use std::marker::PhantomData; use amethyst_assets::AssetStorage; use amethyst_core::shred::{Resource, Resources}; use amethyst_core::specs::common::Errors; use amethyst_core::specs::prelude::{Read, System, WriteExpect}; use output::init_output; use sink::AudioSink; use source::{Source, SourceHandle}; /// Calls a clo...
fn main() { let mut vector = vec![1, 2, 3]; vector.push(4); vector.push(5); vector.insert(0, -1); vector.insert(1, 0); vector.remove(vector.len() - 1); let primer_elemento = vector[0]; let ultimo_elemento = vector.last().unwrap(); println!("{:?}", vector); println!("primer ...
use std::str::from_utf8; use v_htmlescape::escape; /// ************************************************************* /// utf8 bytes to &str /// ************************************************************* pub fn bytes_to_str(v: &[u8]) -> &str { let v = from_utf8(&v).unwrap_or_default(); if v.len() < 2 { ...
#[test] fn test_dir() { let t = rustix::fs::openat( rustix::fs::CWD, rustix::cstr!("."), rustix::fs::OFlags::RDONLY | rustix::fs::OFlags::CLOEXEC, rustix::fs::Mode::empty(), ) .unwrap(); let dir = rustix::fs::Dir::read_from(&t).unwrap(); let _file = rustix::fs::open...
use hyper::{Body, Request, Response}; use std::future::Future; pub trait Responder { type ResponseFuture: Future<Output = Response<Body>>; fn response(&mut self, request: Request<Body>) -> Self::ResponseFuture; } impl<'a, T> Responder for &'a mut T where T: Responder + 'a, { type ResponseFuture = T::R...
use core::mem; use core::ptr; use core::slice; use crate::environment::Environment; use crate::error::{Error, Result}; use crate::function::Function; use crate::module::{Module, ParsedModule}; #[derive(Debug)] pub struct Runtime<'env> { raw: ffi::IM3Runtime, environment: &'env Environment, } impl<'env> Runti...
/// Clean a given tree-sitter-bash `raw_string` or `string`. /// /// These nodes are wrapped in single or double quotes respectively. To interact with the data, /// we need to clean up these wrapping quotes, which this function can be used for. /// /// Empty `raw_string`s or `string`s just return an empty `&str`. Other...
use crate::attribute_info::AttributeInfo; use crate::class_reader::ClassReader; use crate::constant_pool::ConstantPool; use std::rc::Rc; pub struct SignatureAttribute { cp: Rc<ConstantPool>, signature_index: u16, } impl SignatureAttribute { pub fn signature(&self) -> &str { return self.cp.get_utf8...
use rand::distributions::{Alphanumeric, Standard, Uniform}; use rand::Rng; use rayon::prelude::*; use std::mem; use std::sync::atomic::AtomicUsize; use std::sync::atomic::Ordering::SeqCst; use test::{black_box, Bencher}; fn gen_ascending(len: usize) -> Vec<u64> { (0..len as u64).collect() } fn gen_descending(len:...
use std::{ collections::HashMap, env, fs::File, io::{self, Read}, path::{Path, PathBuf}, process::{Child, Command}, str::FromStr, }; use thiserror::Error; use anyhow::{Context, Result}; use crate::temp_path::TempPath; use config::node_config::NodeConifg; #[derive(Debug)] pub enum SwarmDir ...
// An async task which listens for and processes messages from the server. pub fn start() { }
use crate::message::NotificationChannel; use crate::message::BlockingClientBuilder; use crate::util::env_or_fail; use serde::{Serialize, Deserialize}; #[derive(Serialize, Deserialize, Debug)] struct SendGridMessage { personalizations: [SendGridMessagePersonalizations; 1], from: SendGridMessageAddress, rep...
// Copyright © 2015, Peter Atashian // Licensed under the MIT License <LICENSE.md> //! Procedure declarations, constant definitions, and macros for the NLS component. pub const CP_ACP: ::DWORD = 0; pub const CP_OEMCP: ::DWORD = 1; pub const CP_MACCP: ::DWORD = 2; pub const CP_THREAD_ACP: ::DWORD = 3; pub const CP_SYMBO...
#[allow(dead_code)] use crate::println; use multiboot::{Multiboot, PAddr}; use core::{ slice, mem }; pub mod idt; pub mod gdt; pub mod interrupts; pub mod memmap; pub type MF<'a> = dyn Fn(PAddr, usize) -> Option<&'a [u8]>; pub fn paddr_to_slice<'a>(p: multiboot::PAddr, sz: usize) -> Option<&'a [u8]> { ...
use super::{Error, Func, InterfaceItem, ParamList, ResultList, Span, Value, ValueKind, WorldItem}; use crate::*; use anyhow::Result; use indexmap::IndexMap; use std::collections::{HashMap, HashSet}; use std::mem; #[derive(Default)] pub struct Resolver { type_lookup: IndexMap<String, TypeId>, types: Arena<TypeD...
// This file is part of Substrate. // Copyright (C) Parity Technologies (UK) Ltd. // SPDX-License-Identifier: Apache-2.0 // 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.a...
// * Daily Coding Problem July 29 2020 // * [Medium] -- SalesForce // * The number 6174 is known as Kaprekar's contant, after the // * mathematician who discovered an associated property: for all // * four-digit numbers with at least two distinct digits, repeatedly // * applying a simple procedure eventually results ...
use std::collections::{HashMap, HashSet}; pub struct Solution {} impl Solution { pub fn word_break(s: String, word_dict: Vec<String>) -> Vec<String> { let s = s.as_bytes(); let h = word_dict .into_iter() .map(|s| s.as_bytes().to_owned()) .collect::<HashSet<_>>()...
mod action; mod algorithms; mod analysis; mod common; mod cube2x2x2; mod cube3x3x3; mod cube4x4x4; mod rand; mod request; mod tables; #[cfg(feature = "storage")] mod future; #[cfg(feature = "storage")] mod history; #[cfg(feature = "storage")] mod import; #[cfg(feature = "storage")] mod storage; #[cfg(feature = "storag...
use std::cell::RefCell; use cpython::{PyErr, PyString, PyResult, PyObject}; use cpython::exc::RuntimeError; use edgeql_parser::hash; use crate::errors::SyntaxError; py_class!(pub class Hasher |py| { data _hasher: RefCell<Option<hash::Hasher>>; @staticmethod def start_migration(parent_id: &PyString) -> ...
// Copyright 2020 EinsteinDB Project Authors & WHTCORPS INC. Licensed under Apache-2.0. use crate::edb::PanicEngine; use edb::{Cone, ConePropertiesExt, Result}; impl ConePropertiesExt for PanicEngine { fn get_cone_approximate_tuplespaceInstanton( &self, cone: Cone, brane_id: u64, l...
#![no_main] #[macro_use] extern crate libfuzzer_sys; extern crate dbgen; extern crate tempfile; use std::env; use std::fs::write; use dbgen::cli::{Args, run, RngName}; use tempfile::tempdir; fuzz_target!(|data: &[u8]| { if data.len() < 32 { return; } let mut seed = [0_u8; 32]; seed.copy_from_s...
macro_rules! retry_impl { ($time:expr) => { use crate::{RetryErr, RetryOp, RetryResult}; use std::{future::Future, time::Duration}; /// Retry a future based on an iterator over Duration. A timer will be run for /// each item in the iterator. /// /// ```rust,no_run ...
extern crate bitflags; #[macro_use] extern crate serde_derive; extern crate serde; extern crate serde_json; bitflags::bitflags! { #[derive(Serialize, Deserialize)] struct Flags: u32 { const A = 1; const B = 2; const C = 4; const D = 8; } } #[test] fn serialize() { let ...
extern crate source_map_mappings; use source_map_mappings::parse_mappings; #[test] fn parse_empty_mappings() { let mut mappings = parse_mappings(&[]).expect("should parse OK"); assert!(mappings.by_generated_location().is_empty()); assert!(mappings.by_original_location().is_empty()); } #[test] fn invalid_...
use super::{ reply::Reply, tree::{Parsed, Parser, Segment}, Response, }; use frunk_core::{ coproduct::{CNil, CoprodUninjector, Coproduct}, hlist::{HCons, HNil, Plucker, Sculptor}, }; use futures::future::{ready, FutureExt, Ready, TryFutureExt}; use std::{future::Future, marker::PhantomData, ops::Add...
use protobuf::MessageFull; use super::test_ident_pb::*; #[test] fn test() { let _ = TestType::new(); } #[test] fn test_reflect() { Self_::new(); // instantiate reflection assert_eq!("Self", Self_::descriptor().name()); }
//! Displays a shaded sphere to the user. extern crate amethyst; #[macro_use] extern crate log; use amethyst::assets::{PrefabLoader, PrefabLoaderSystem, Processor, RonFormat}; use amethyst::audio::output::init_output; use amethyst::audio::Source; use amethyst::core::transform::TransformBundle; use amethyst::core::Tim...
use std::fs::File; use std::io::{BufReader, BufRead, Read}; fn hex_to_u8(a: u8) -> u8 { match a { b'0'...b'9' => a - b'0', b'a'...b'h' => a - b'a' + 10, _ => 0 } } fn u8_to_hex(h: u8) -> u8 { match h { 0...9 => h + b'0', 10...15 => h - 10 + b'a', ...
// This file is part of Substrate. // Copyright (C) Parity Technologies (UK) Ltd. // SPDX-License-Identifier: Apache-2.0 // 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.a...
struct Solution; use std::i32; use util::*; trait Inorder { fn inorder(&self, prev: &mut Option<i32>, min: &mut i32); } impl Inorder for TreeLink { fn inorder(&self, prev: &mut Option<i32>, min: &mut i32) { if let Some(node) = self { let node = node.borrow(); Self::inorder(&nod...
use reqwest; use serde::{Deserialize, Serialize}; use lycan::shared::http::{ JoinGameRequest, JoinGameResponse, NewGameRequest, NewGameResponse, UpdateRequest, UpdateResponse, }; type ClientResult<T> = Result<T, Box<dyn std::error::Error>>; fn post<'a, T, S>(url: &str, payload: T) -> Result<S, Box<dyn std::...
#[macro_use] extern crate criterion; extern crate revc; use criterion::Criterion; use revc::reverse_complement; fn bench_reverse_complement(c: &mut Criterion) { let input = "ACGT".repeat(250); c.bench_function("1000 char input", move |b| { b.iter(|| reverse_complement(&input)) }); } criterion_gro...
use std::collections::HashMap; use std::sync::mpsc as chan; use minifb::{Key, Window, WindowOptions}; use clicky_core::gui::{ButtonCallback, RenderCallback, ScrollCallback}; pub struct MinifbControls { pub keymap: HashMap<Key, ButtonCallback>, pub on_scroll: Option<ScrollCallback>, } #[derive(Debug)] pub st...
//! Compaction use super::Database; use leveldb_sys::leveldb_compact_range; use libc::{c_char, size_t}; pub trait Compaction<'a> { fn compact<A: AsRef<[u8]>, B: AsRef<[u8]>>(&self, start: A, limit: B); } impl<'a> Compaction<'a> for Database { fn compact<A: AsRef<[u8]>, B: AsRef<[u8]>>(&self, start: A, limit: ...
pub use self::camera::{Camera, CameraType}; pub use self::compute_handler::ComputeHandler; //pub use self::font::Font; pub use self::model_handler::ModelHandler; pub use self::texture_handler::{ComboVertex, TextureHandler}; mod camera; mod compute_handler; pub mod font; mod model_handler; mod texture_handler;
#![allow(non_snake_case)] /* Opcode LR35902 Z-80 ------ -------------- ---------- F2 LD A,(C) JP P,nn E2 LD (C),A JP NV,nn EA LD (nn),A JP V,nn FA LD A,(nn) JP M,nn 3A LDD A,(HL) LD A,(nn) 32 LDD (HL),A LD (nn),A...
//! Config. extern crate config; use self::config::FileFormat; use serde::Deserialize; use serde::Serialize; use std::path::PathBuf; const DEFAULT_CONFIG: &str = r#" { "timeline_colors": [[183,28,28], [26,35,126], [0,77,64], [38,50,56]], "deny_overlapping": true } "#; type RGB = (u8, u8, u8);...
use std::io; use std::fs; use rand::Rng; use std::io::BufRead; //updates the word shown to the user revealing all characters in the guesses vector fn new_show_word(secret: &str, guesses: &Vec<char>) -> String { let mut result = String::with_capacity(secret.len()); let secret: Vec<char> = secret.chars().collect(...
//! v1 nip object implementation use failure::Error; use std::collections::BTreeSet; use crate::{ constants::NIP_HEADER_LEN, object::{NIPObject as NIPObjectV2, NIPObjectMetadata as NIPObjectV2Metadata}, util::parse_nip_header, }; #[derive(Clone, Debug, Deserialize, Serialize)] /// A nip representation of...
use std::collections::HashMap; pub fn part1(input: &Vec<String>) { let mut maps = vec![HashMap::new(); input[0].len()]; for line in input { let mut chars = line.chars(); for i in 0..line.len() { let character = chars.next().unwrap(); let entry = maps[i].entry(character...
pub enum Coins { Quarter, Dime, Nickel, Penny } impl Coins { pub fn value(&self) -> f32 { match *self { Coins::Penny => 0.01, Coins::Nickel => 0.05, Coins::Dime => 0.1, Coins::Quarter => 0.25 } } pub fn as_enum(&self) -> Coin...
//gcd, gcd test, and a good portion of main are from Programming Rust: Fast, Safe, System Development use std::env; use std::io::Write; use std::str::FromStr; fn gcd(mut n: u64, mut m: u64) -> u64 { while m != 0 { if m < n { let t = m; m = n; n = t; } m =...
// This file is part of Substrate. // Copyright (C) Parity Technologies (UK) Ltd. // SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 // This program 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 Softwa...
use std::collections::{HashMap, HashSet}; use std::fs::File; use std::io::prelude::*; use std::io::BufReader; use std::str::FromStr; use clap::{App, Arg}; fn count_bags<S>(bag_list: &HashMap<String, Vec<(u32, String)>>, start: S) -> u32 where S: ToString, { let start = start.to_string(); let mut total = 0...
use aoc_runner_derive::aoc; #[aoc(day1, part1)] pub fn part1(input: &str) -> i32 { let mut memory = vec![]; let mut output = vec![]; input .lines() .map(|l| { let x = l.parse::<i32>().unwrap(); if memory.contains(&x) { output.push(x); ...
use cbor_enhanced::*; fn main() { let input: &str = r"Hello world"; let mut serializer = Serializer::new(); let deserializer = Deserializer::new(); serializer.write_string(input); let serialized = serializer.get_bytes(); let output: &str = deserializer .take_string(serialized.as_ref()...