text
stringlengths
8
4.13M
use structopt::StructOpt; #[derive(Debug, StructOpt)] #[structopt( name = "OctoDeps", about = "Simple tool to track projects dependencies." )] pub struct OctodepsOpt { /// Config: the config file path #[structopt(short, long)] pub config: String, }
extern crate libc; extern crate seccomp_sys as ffi; use std::ffi::CString; use std::fs::File; use std::io; use std::os::unix::io::IntoRawFd; use libc::close; /// A compare operation. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum Op { /// Not equal OpNe, /// Less than OpLt, /// Le...
//! This module contains types used throughout the IMAP protocol. use std::borrow::Cow; /// From section [2.3.1.1 of RFC 3501](https://tools.ietf.org/html/rfc3501#section-2.3.1.1). /// /// A 32-bit value assigned to each message, which when used with the unique identifier validity /// value (see below) forms a 64-bit...
// for windows API // Windows functions use std::ffi::OsStr; use std::iter; use std::os::raw::c_void; use std::os::windows::ffi::OsStrExt; use winapi::um::winuser::SystemParametersInfoW; use winapi::um::winuser::SPIF_SENDCHANGE; use winapi::um::winuser::SPIF_UPDATEINIFILE; use winapi::um::winuser::SPI_SETDESKWALLPAPER...
mod error; pub use error::MetricError; pub use error::MetricResult; use std::fs::OpenOptions; use std::io::Write; use std::path::Path; use std::path::PathBuf; use time::OffsetDateTime; #[derive(Debug)] pub struct Metric { name: String, path: PathBuf, } impl Metric { pub fn new<P>(name: &str, storage_pat...
use std::fs::read_to_string; fn main() { test("src/six-test.txt"); test("src/six.txt"); } fn day(model: &mut Vec<u64>) { let new = model[0]; for v in 0..=7 { model[v] = model[v + 1]; } model[8] = new; model[6] += new; } fn test(f: &str) { let data = read_to_string(f).unwrap();...
fn main() { let mut f0 = 1; let mut f1 = 2; let mut ans = 0; while f1 <= 4000_000 { if f1 % 2 == 0 { ans += f1; } let f2 = f0 + f1; f0 = f1; f1 = f2; } println!("Answer: {}", ans); }
use super::hittable::{Hit, Hittable}; use super::material::Material; use super::vec3::{Point3, Ray, UnitVec3, Vec3}; pub struct Sphere { pub center: Point3, pub radius: f64, pub material: Material, } impl Sphere { pub fn new(center: Point3, radius: f64, material: &Material) -> Self { Sphere { ...
extern crate pancurses; use pancurses::*; mod data; mod listcontroller; mod screen; mod listscreen; mod output; fn main() { let win = output::MyWindow::new(initscr()); start_color(); init_pair(1, COLOR_RED, COLOR_BLACK); init_pair(2, COLOR_GREEN, COLOR_BLACK); init_pair(3, COLOR_WHITE, COLOR_BLUE...
override_1_7_18.M override_1_7_18.R override_1_7_18.Override_1_7_18
//! This library provides enumeration of [`ISO-4217`]. //! //! # Example //! ```rust //! use std::convert::TryFrom; //! use iso_4217::*; //! //! let usd: CurrencyCode = TryFrom::try_from("USD").unwrap(); //! assert_eq!(usd, CurrencyCode::USD); //! //! assert_eq!(usd.alpha(), "USD"); //! assert_eq!(usd.num(), 840); //! ...
// Wrapper macros which allows built-in macros to be recognized as "crate-local". #[doc(hidden)] #[macro_export] macro_rules! __graphql__panic { ($($t:tt)*) => ( panic!($($t)*) ); } #[doc(hidden)] #[macro_export] macro_rules! __graphql__stringify { ($($t:tt)*) => ( stringify!($($t)*) ); } #[doc(hidden)] #[ma...
use yew::prelude::{ Component, ComponentLink, Html, html, ShouldRender, Properties, Children, }; use yew::services::ConsoleService; use crate::components::todo::ListItem; #[derive(Properties, Clone, PartialEq, Debug)] pub struct ListProps { #[prop_or_default] pub children: Children...
extern crate chrono; // DateTime manipulation use std::io; use chrono::*; use io::Error; use crate::{data_defs::*}; // get date into the format we need pub fn format_date( time: DateTime::<Utc> ) -> Result<String, Error> { Ok(time.format("%Y-%m-%dT%H:%M:%S.%3f").t...
use crate::telemetry::ReportingLogger; use log::{Level, Log, Metadata, Record}; use simple_logger::SimpleLogger; use std::env; /// Logger will add 'CUBESTORE_LOG_CONTEXT' to all messages. /// Set it during `procspawn` to help distinguish processes in the logs. pub fn init_cube_logger(enable_telemetry: bool) { let ...
pub fn verse(n: i32) -> String { match n { 0 => String::from("No more bottles of beer on the wall, no more bottles of beer.\nGo to the store and buy some more, 99 bottles of beer on the wall.\n"), 1 => String::from("1 bottle of beer on the wall, 1 bottle of beer.\nTake it down and pass it around, no...
extern crate env_logger; extern crate keypress; use keypress::*; fn main() { env_logger::init(); let config = load_or_create_config(); let tx = websocket::run_in_thread(&config.host); let tx = tx.clone(); Hook::run(config, move |event| { if event.state == KeyState::Pressed { ...
use std::collections::VecDeque; use std::fs; use std::fs::File; use std::io::Read; use amethyst::audio::Mp3Format; use amethyst::ecs::World; use amethyst_extra::AssetLoader; use ron::de::from_str; use data::*; pub fn list_directory(dir: &String) -> Vec<String> { fs::read_dir(dir) .expect(&*format!("Faile...
use proxy_wasm::traits::*; use proxy_wasm::types::*; use primes::is_prime; #[no_mangle] pub fn _start() { proxy_wasm::set_log_level(LogLevel::Trace); proxy_wasm::set_http_context(|context_id, _| -> Box<dyn HttpContext> { Box::new(PrimeAuthorizer { context_id }) }); } struct PrimeAuthorizer { ...
extern crate byteorder; extern crate speexdsp_sys; use byteorder::{BigEndian, ByteOrder}; use speexdsp_sys::preprocess::*; use std::ffi::c_void; use std::io::Read; macro_rules! preprocess_ctl { ($st:ident, $param:ident, $value:expr) => { let v = &mut ($value as f32) as *mut f32 as *mut c_void; uns...
use crate::edits::{EditCmd, EditIntersection, EditRoad, MapEdits}; use crate::raw::OriginalRoad; use crate::{osm, ControlStopSign, IntersectionID, Map}; use abstutil::{deserialize_btreemap, serialize_btreemap}; use geom::Time; use serde::{Deserialize, Serialize}; use std::collections::{BTreeMap, BTreeSet}; // These us...
use scale::Encode; use sp_core::crypto::{Ss58AddressFormatRegistry, Ss58Codec}; use sp_runtime::MultiSigner; use std::str::FromStr; use subxt::{utils::AccountId32, OnlineClient, PolkadotConfig}; use subxt_signer::{bip39::Mnemonic, sr25519::Keypair}; use crate::query::{maybe_leases, paras_registered}; // Rococo types ...
use crate::config::{Config, PayloadConfig, TestConfig}; use crate::interrupt::Interrupted; use crate::reporting::TestReport; use anyhow::Error; use futures::future; use futures::TryFutureExt; use http::header::HeaderValue; use http::HeaderMap; use http::Request; use hyper::{body::Bytes, Body, Error as HyperError}; use ...
use crate::functions::new_clause::*; use crate::functions::propagate::*; use crate::models::clause::*; use crate::models::lit::*; use crate::models::solverstate::*; /*_________________________________________________________________________________________________ | | simplifyDB | | Description: | Simplify the cl...
use classy::Classy; fn main() { let mut app = Classy::new(); app.run(); }
pub struct ArrayIns { a: Box<[i64]>, n_elems: usize } impl ArrayIns { pub fn new(max: usize) -> ArrayIns { ArrayIns { a: vec![0; max].into_boxed_slice(), n_elems: 0 } } pub fn insert(&mut self, value: i64) { self.a[self.n_elems] = value; self...
use std::net::{TcpListener, TcpStream}; use std::io::{Read, Write}; use std::env; use std::thread; fn main() { let args: Vec<String> = env::args().map(|x| x.to_string()) .collect(); let program = &args[0]; if args.len() != 3 { print_usage(program); r...
// These modules contain `compile_fail` doc tests. mod cannot_collect_filtermap_data; mod cannot_zip_filtered_data; mod cell_par_iter; mod must_use; mod no_send_par_iter; mod rc_par_iter;
pub mod core; pub mod hw; pub mod device; pub mod serialization; use time; use std::thread; use std::time::Duration; use ::util::measure::*; use self::core::memory::*; use self::core::cpu::registers; use self::core::cpu::ArmCpu; use self::device::GbaDevice; use self::hw::lcd::GbaLcd; use self::hw::joypad::GbaJoypad; u...
// This file is part of sokoban-rs // Copyright 2015 Sébastien Watteau // // 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 re...
extern crate groupme_bot; use groupme_bot::{Bot, Groupme}; use std::env; fn main() { let group_id = &env::var("GROUPME_BOT_ID").unwrap(); let groupme = Groupme::new(None); let bot: Bot = groupme.bot(group_id); bot.post("Hello from Rust!").unwrap(); }
// Copyright (C) 2021 Scott Lamb <slamb@slamb.org> // SPDX-License-Identifier: MIT OR Apache-2.0 use std::convert::TryFrom; use std::ffi::CStr; use std::ptr; //#[link(name = "avutil")] extern "C" { pub(crate) fn av_version_info() -> *mut libc::c_char; pub(crate) fn avutil_version() -> libc::c_int; pub(cra...
use win32console::console::WinConsole; use win32console::structs::console_color::ConsoleColor; use win32console::input::*; // Virtual key codes // https://docs.microsoft.com/en-us/windows/win32/inputdev/virtual-key-codes const ESCAPE : u16 = 0x1B; const BACKSPACE: u16 = 0x08; const ENTER : u16 = 0x0D; const SPACE : u1...
// Copyright (c) 2016 The vulkano developers // 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 option. All files in the project carrying such // notice may not be ...
use crate::dd_challenge::Solution; impl Solution { pub fn str_str(haystack: String, needle: String) -> i32 { if needle.len() > haystack.len() { - 1 } else if needle.is_empty() { 0 } else { let h_s = haystack.as_bytes(); let n_s = needle.as_byt...
//! Encapsulates error types. use std::result; use std::fmt; pub type Result<T> = result::Result<T, Error>; /// Possible errors produced by syscall collector. #[derive(Deserialize, Debug)] pub enum Error { RingBufferMapping, TooManyCollectors, DeviceError, UnknownConfigPathError, ConfigParseError...
use std::error::Error; use bytes::BytesMut; use tokio::{ prelude::*, codec::{Decoder, Encoder}, }; pub enum ClientMessage { Ping, Send(Vec<u8>), } #[derive(Debug)] pub enum DecodeError { MalformedInput, Tokio(tokio::io::Error), } impl std::fmt::Display for DecodeError { fn fmt(&self, f: ...
use crate::err::XamXamServiceError; use crate::viewmodels::edit_storage::EditStorage; use crate::viewmodels::new_storage::NewStorage; use crate::viewmodels::storage_name::StorageName; use crate::viewmodels::storage_names::StorageNames; use crate::viewmodels::storages::Storages; use crate::PgCon; use xam_xam_dal::models...
use std::fmt; use std::fs::File; use std::io::Read; fn main() { let mut buf = String::new(); let mut file = File::open("input").unwrap(); file.read_to_string(&mut buf).unwrap(); let grid = process_input(&buf); println!("{}", grid); let answer = get_answer(grid.clone()); let grid = process...
use std::ops; #[derive(Copy,Clone,Debug)] pub struct Vec3d { pub x: f64, pub y: f64, pub z: f64, } impl Vec3d { pub fn zero() -> Vec3d { Vec3d{ x: 0., y: 0., z: 0. } } pub fn one() -> Vec3d { Vec3d{ x: 1., y: 1., z: 1. } } pub fn new(x: f64, y: f64, z: f64) -> V...
use amethyst::{ core::Transform, derive::SystemDesc, ecs::{Join, Read, ReadStorage, System, SystemData, WriteStorage}, input::{InputHandler, StringBindings, VirtualKeyCode}, }; use crate::{ components::{ basics::{Player, Obstacle}, grid2d::{Grid2D, Grid2DDelta}, }, ...
fn main() { let x:i64 = 5; let f:i64 = fac(x); println!("{:?}", f); } fn fac(x:i64) -> i64 { if x <= 1 { return 1; } let result: i64 = x * fac(x -1); return result; }
use shogi::*; use std::sync::mpsc::{channel, Receiver, Sender}; use std::sync::{Arc, Mutex}; use std::time::{Duration, Instant}; use crate::config::MatchConfig; use crate::engine::{UsiEngine, WriteHookFn}; use crate::error::Error; use crate::game::{Game, GameOverReason, GameResult}; use crate::reporter::Reporter; use ...
pub struct Intersperse<T, I, F> where F: FnMut() -> T, I: Iterator<Item=T> { buffer: Option<T>, join_with: F, iter: I, do_join: bool, } impl<T, I, F> Intersperse<T, I, F> where F: FnMut() -> T, I: Iterator<Item=T> { pub fn new<V: IntoIterator<Item=T, IntoIter=I>>(iter: V, sep_factory: F) ->...
use super::*; pub struct ProcExeSymINode(ProcessRef); impl ProcExeSymINode { pub fn new(process_ref: &ProcessRef) -> Arc<dyn INode> { Arc::new(SymLink::new(Self(Arc::clone(process_ref)))) } } impl ProcINode for ProcExeSymINode { fn generate_data_in_bytes(&self) -> vfs::Result<Vec<u8>> { O...
use std::path::PathBuf; use gfa::gfa::GFA; use handlegraph::hashgraph::HashGraph; use crate::edges; use super::{load_gfa, Result}; pub fn edge_count(gfa_path: &PathBuf) -> Result<()> { let gfa: GFA<usize, ()> = load_gfa(gfa_path)?; let hashgraph = HashGraph::from_gfa(&gfa); let edge_counts = edges::gr...
use serde_json::Result; use std::io::{BufRead, BufReader, Write}; use std::net::{Shutdown, TcpStream}; use common::ste::STEServer; use common::token::ServerCommand; /// Waits for user commands and dispatches the commands. /// /// # Arguments /// /// * `stream` - TCP stream containing user inputs. pub fn h...
//! Types to manage messages that notify the eww client over the result of a command //! //! Communcation between the daemon and eww client happens via IPC. //! If the daemon needs to send messages back to the client as a response to a command (mostly for CLI output), //! this happens via the DaemonResponse types use ...
// //! Copyright 2020 Alibaba Group Holding Limited. //! //! 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 ...
use chrono::{DateTime, Utc}; use schema::*; #[derive(Clone, Debug, Queryable)] pub struct Account { pub id: i64, pub created_at: DateTime<Utc>, pub email: Option<String>, pub password: String, pub last_ip: String, pub last_seen_at: DateTime<Utc>, pub active: bool, } #[table_name = "tbl_pro...
use serde::{Deserialize, Serialize}; #[derive(Clone, Deserialize, Serialize)] #[cfg_attr( feature = "config-schema", derive(schemars::JsonSchema), schemars(deny_unknown_fields) )] #[serde(default)] pub struct ShellConfig<'a> { pub format: &'a str, pub bash_indicator: &'a str, pub fish_indicator...
pub use self::math::{Math, Swizzle2, Swizzle3, Swizzle4, Vector2, Vector3, Vector4, VectorMath}; pub mod gltf_loader; mod math;
//字符类型 fn main() { let x = 'r'; let x = 'u'; println!("{}",'\''); println!("{}",'\\'); println!("{}",'\n'); println!("{}", '\r'); println!("{}", '\t'); assert_eq!('\x2A', '*'); assert_eq!('\x25', '%'); //assert_eq!('\u{CA0}','') assert_eq!('%' as i8, 37); }
extern crate udev; use super::udev_device::{ get_attribute_value, get_devnode, get_devpath, get_driver, get_parent, get_property_value, get_subsystem, get_sysname, DeviceExt, }; use super::udev_enumerator::Enumerator; use pest::iterators::Pair; use pest::Parser; use regex::Regex; const TAGS: &str = "TAGS"; #...
#[macro_use] extern crate error_chain; #[macro_use] extern crate log; pub mod config; pub mod errors { // Create the Error, ErrorKind, ResultExt, and Result types error_chain!{} } pub use errors::*;
// Copyright (c) The Starcoin Core Contributors // SPDX-License-Identifier: Apache-2.0 const CLIENT_META_WORD: &str = "client"; const SERVER_META_WORD: &str = "server"; #[derive(Debug)] pub struct DeriveOptions { pub enable_client: bool, pub enable_server: bool, } impl DeriveOptions { pub fn new(args: sy...
pub fn bottles(n: u32) -> String { if n == 0 { return String::from("No more bottles"); } else if n == 1 { return String::from("1 bottle"); } else { return format!("{} bottles", n); } } pub fn verse(n: u32) -> String { let mut song: Vec<String> = vec![format!( "{} of ...
use aoc2015::Result; struct Character { hp: i8, damage: i8, armor: i8, cost: u16, } impl Character { fn buy(&mut self, item: &Item) { self.damage += item.damage; self.armor += item.armor; self.cost += item.cost; } fn attack(&self, target: &mut Character) { ...
/** * [235] Lowest Common Ancestor of a Binary Search Tree * * Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST. According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both...
use std::io::{BufRead, BufReader, BufWriter, Write, stdin, stdout}; fn main() { let stdout = stdout(); let mut bw = BufWriter::new(stdout); let stdin = stdin(); let mut br = BufReader::new(stdin); let mut num_tests_str = String::new(); br.read_line(&mut num_tests_str).unwrap(); let num_tes...
// Copyright 2019 WHTCORPS INC Project Authors. Licensed under Apache-2.0. use std::cell::RefCell; use std::f64::INFINITY; use std::fmt; use std::sync::atomic::*; use std::sync::*; use std::{borrow::Cow, time::*}; use interlocking_directorate::ConcurrencyManager; use configuration::Configuration; use engine_lmdb::raw...
mod bucket_limit_rule; mod closure_rule; mod fixed_score_rule; mod mul_rule; mod sum_rule; use crate::bucket_strainer::Bucket; use crate::Scalar; pub use bucket_limit_rule::*; pub use closure_rule::*; pub use fixed_score_rule::*; pub use mul_rule::*; pub use sum_rule::*; /// Trait used to tell how much successfuly bu...
use std::{ ffi::{CStr, CString}, os::raw::c_void, }; use ash::{version::EntryV1_0, vk, Entry}; const VALIDATION_LAYERS: [&str; 1] = ["VK_LAYER_KHRONOS_validation"]; pub fn check_validation_layer_support(entry: &Entry) -> bool { let layer_properties = match entry.enumerate_instance_layer_propert...
// 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...
#[allow(bad_style)] mod ffi; pub use ffi::*; #[test] fn test_aom_binding_abi_ver() { let cfg = aom_codec_dec_cfg { w: 0, h: 0, threads: 1, allow_lowbitdepth: 1, }; let res = unsafe { let mut ctx = std::mem::MaybeUninit::uninit(); aom_codec_dec_init_ver( ...
use std::convert::From; use std::fmt; #[derive(Clone, Debug)] pub struct CustomsSet { bits: u64, } impl CustomsSet { pub fn new() -> CustomsSet { CustomsSet { bits: 0 } } pub fn all() -> CustomsSet { "abcdefghijklmnopqrstuvwxyz".into() } fn within_range(i: u8) -> bool { ...
/* Copyright (c) 2015, Alex Frappier Lachapelle All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this ...
use std::collections::HashMap; pub type ProteinMap = HashMap<&'static str, &'static str>; pub type PResult = Result<&'static str, &'static str>; pub struct Codonator { pm: ProteinMap, } pub fn parse(type_list: Vec<(&'static str, &'static str)>) -> Codonator { Codonator { pm: type_list.into_iter().collect() }...
use std::io; use std::io::prelude::*; #[derive(Debug)] struct Instruction { op: String, val: i32, count: i32, } fn parse(input: &str) -> Vec<Instruction> { input .lines() .map(|f| { let inst = f.split_ascii_whitespace().collect::<Vec<_>>(); Instruction { op: inst[0].to_string(), val: inst[1].par...
use std::collections::HashMap; use std::mem; use std::path::{PathBuf, Path}; use std::fs::read_to_string; use std::str::FromStr; use failure::{Error, ResultExt, err_msg}; use nginx_config; use nginx_config::ast::{self, Listen, Value, Directive, Item}; use nginx_config::{parse_directives, Pos}; use nginx_config::visito...
use aoc_runner_derive::aoc; #[derive(Debug, Copy, Clone)] struct Point { x: f32, y: f32, } impl Point { fn new(x: f32, y: f32) -> Self { Self { x, y } } fn origin() -> Self { Point::new(0.0, 0.0) } fn step(&mut self, dx: f32, dy: f32) { self.x += dx; self....
/*! ```compile_fail,E0524 fn quick_sort<T:PartialOrd+Send>(v: &mut [T]) { if v.len() <= 1 { return; } let mid = partition(v); let (_lo, hi) = v.split_at_mut(mid); rayon_core::join(|| quick_sort(hi), || quick_sort(hi)); //~ ERROR } fn partition<T:PartialOrd+Send>(v: &mut [T]) -> usize { ...
// Copyright 2016 Google Inc. All Rights Reserved. // // Licensed under the MIT License, <LICENSE or http://opensource.org/licenses/MIT>. // This file may not be copied, modified, or distributed except according to those terms. #![feature(plugin, use_extern_macros, proc_macro_path_invoc)] #![plugin(tarpc_plugins)] #[...
use itertools::Itertools; use rustc_hash::FxHashMap; use std::hash::BuildHasherDefault; fn main() { let p1 = part1(29000000); let p2 = part2(29000000, 50); println!("Part 1: {}", p1); println!("Part 2: {}", p2); } fn part1(target: usize) -> usize { let size = target / 10; let mut houses = FxH...
// Copyright 2020 EinsteinDB Project Authors & WHTCORPS INC. Licensed under Apache-2.0. //! Reexports from the lmdb crate //! //! This is a temporary artifact of refactoring. It exists to provide downstream //! crates access to the lmdb API without deplightlikeing directly on the lmdb //! crate, but only until the eng...
//! This module provides an implementation of input forms. use std::rc::Rc; use cursive::{event::Callback, theme::BorderStyle, Cursive, With}; use cursive::{ theme::{BaseColor, Color, PaletteColor, Theme}, view::ViewWrapper, views::{EditView, ThemedView}, }; pub struct TextInputView { view: ThemedVie...
use rand::prelude::*; use rayon::prelude::*; use std::sync::atomic::{AtomicI32, Ordering}; use std::sync::{Mutex, MutexGuard}; fn vector_of_ints() -> Vec<i32> { let len = 100_000; let mut rng = rand::thread_rng(); let mut v = Vec::new(); for _ in 0..len { v.push(rng.gen_range(0..100)); } ...
use super::*; use crate::lightning::ln_errors::{SaveChannelClosingError, SaveChannelClosingResult}; use crate::utxo::rpc_clients::{BestBlock as RpcBestBlock, BlockHashOrHeight, ConfirmedTransactionInfo, ElectrumBlockHeader, ElectrumClient, ElectrumNonce, EstimateFeeMethod, ...
use crate::core::audio_model::Input; use crate::features::Tape; use cpal::traits::DeviceTrait; use cpal::{Device, Stream, StreamConfig}; use ringbuf::{HeapConsumer, HeapProducer}; use std::path::Path; pub const TAPE_COUNT: usize = 8; pub const SAMPLE_GRAPH_SIZE: usize = 100; pub const A_FREQ: f32 = 440.0; pub const C_...
use derive_more::*; use timing_shield::{TpBool, TpCondSwap, TpEq, TpOrd, TpU64}; #[derive(From, BitXor, BitXorAssign, BitOr, BitOrAssign, BitAnd, Not, Clone, Copy)] pub struct TpU128(u128); impl TpU128 { #[inline(always)] pub fn protect(v: u128) -> Self { Self(v) } #[inline(always)] pub f...
use crate::{Pretty, parser::*}; use rstest::rstest; #[rstest( input, case("Arc"), case("sc_client_db::Backend"), case("sc_service::client::Client") )] fn parse_name(input: &str) { let result = ItemParser::new().parse(input); println!("{:#?}", result); assert!(result.is_ok()); println!(...
use crate::{ error::ResponseResult, models, schema::{hardware_specs, program_specs}, server::gql::{ internal::{GenericEdge, NodeType}, program_spec::{ProgramSpecConnection, ProgramSpecNode}, ConnectionPageParams, CreateHardwareSpecPayloadFields, Cursor, HardwareSpecConnec...
extern crate liblyrical; extern crate serde; extern crate tokio; extern crate warp; use std::collections::HashMap; use std::net::SocketAddr; use liblyrical::lyrics::{LyricsFetcher, SongDescriptor}; use liblyrical::word_count; use serde::{Deserialize, Serialize}; use warp::Filter; const SERVER_ADDR: &'static str = "1...
fn find_differences(mut data: Vec<isize>) -> (usize, usize) { data.push(0); // add the outlet so we count that difference, too data.sort(); let result = data.iter() .zip(data.iter().skip(1)) .fold((0,0), |acc, x| { let diff = x.1 - x.0; if diff == 1 { ...
// Copyright 2019 The Gotts Developers // // 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 agre...
#![deny(warnings)] use std::convert::Infallible; use std::net::SocketAddr; use bytes::Bytes; use http_body_util::Full; use hyper::server::conn::http1; use hyper::service::service_fn; use hyper::{Request, Response}; use tokio::net::TcpListener; #[path = "../benches/support/mod.rs"] mod support; use support::TokioIo; ...
#[macro_use] extern crate clap; #[macro_use] extern crate log; extern crate env_logger; use num_cpus; use std::env; use std::fs; use std::net::SocketAddr; use structopt::StructOpt; extern crate kvs; use kvs::network::KvsServer; use kvs::thread_pool::{NaiveThreadPool, SharedQueueThreadPool, ThreadPool}; use kvs::{KvSto...
use bytes::Bytes; use http::response::Builder; use http::{Request, Response, StatusCode}; use serde::{Deserialize, Serialize}; use std::sync::Arc; use voyager::http as myhttp; use voyager::http::HandlerFunc; use voyager::mux::DefaultServeMux; use voyager::server::DefaultServer; fn main() -> Result<(), Box<std::error::...
//! Compiled syntax of the STG machine which is executed directly use super::tags::Tag; use crate::common::sourcemap::Smid; use chrono::{DateTime, FixedOffset}; use std::{fmt, rc::Rc}; /// The unboxed native (non algebraic) data types use serde_json::Number; #[derive(Clone, Debug, PartialEq, Eq)] pub enum Native { ...
use super::plumbing::*; use super::*; /// An [`IndexedParallelIterator`] that iterates over two parallel iterators of equal /// length simultaneously. /// /// This struct is created by the [`zip_eq`] method on [`IndexedParallelIterator`], /// see its documentation for more information. /// /// [`zip_eq`]: trait.Indexe...
#[macro_use] extern crate phoebe; #[test] fn make_and_reference() { test_pairs! { "(make-namespace :name make-and-reference)" => "[namespace make-and-reference]"; "(nref make-and-reference foo)" => "UNINITIALIZED"; "(setf (nref make-and-reference foo) 3)" => "3"; "(nref ...
#![feature(macro_rules)] extern crate libc; extern crate sdl2; use sdl2::{video, event, keycode, timer, render, sdl}; use std::io::BufWriter; use game::Loop; mod game; static MS_PER_FRAME : uint = 15; // About 60fps fn main() { sdl::init(sdl::INIT_AUDIO | sdl::INIT_VIDEO); let window = video::Window::new(...
use serde_json::{Value, Map}; use Segment; use ResultSet; use ConfigMap; use std::env; use themes::*; use prompt::Prompt; #[derive(Debug)] pub struct CwdSegment{ pub options: Option<Map<String, Value>>, pub global_config: Option<ConfigMap> } #[derive(PartialEq, Eq, Debug)] enum Mode { Plain, DirOnly, ...
//! Test suite for the Web and headless browsers. #![cfg(target_arch = "wasm32")] extern crate wasm_bindgen_test; use wasm_bindgen_test::*; wasm_bindgen_test_configure!(run_in_browser); #[wasm_bindgen_test] fn pass() { assert_eq!(1 + 1, 2); } extern crate wasm_game_of_life; use wasm_game_of_life::Universe; #[...
use serde_derive::*; use serde::{Serialize, Deserialize}; use crate::error::BlobError; pub fn read_u64<R: std::io::Read>(r: &mut R) -> Result<u64, BlobError> { let mut buff = [0u8; 8]; //u64 takes 8 bytes r.read_exact(&mut buff)?; Ok(bincode::deserialize(&buff)?) } pub fn write_u64<W: std::io::Write>(w: &mut ...
use cargo_snippet::snippet; #[snippet("grundy_def")] pub fn grundy_def(xs: Vec<i64>) -> i64 { let mut xs = xs; xs.sort(); let mut n = xs.len(); for i in 0..n { if i as i64 != xs[i] { return i as i64 } } n as i64 } #[test] fn test_grundy_def() { assert_eq!(grundy_...
// This file was generated by gir (https://github.com/gtk-rs/gir) // from gir-files // DO NOT EDIT #[cfg(any(feature = "v1_42", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_42")))] use crate::SettingIP4LinkLocal; use crate::{Setting, SettingIPConfig}; use glib::{ prelude::*, signal::{co...
pub mod alu; pub mod csr; pub mod bus; pub mod chip; pub mod instruction; pub mod memory; pub mod register; pub use alu::*; pub use csr::*; pub use bus::*; pub use chip::*; pub use instruction::*; pub use memory::*; pub use register::*;
use md5; fn main() { //let input = "bgvyzdsv"; let input = "bgvyzdsv"; for i in 1.. { let test = format!("{}{}", input, i); let digest = format!("{:x}", md5::compute(&test)); let check = digest .chars() .take(6) .all(|elem| '0' == elem); i...
extern crate rand; use functional::Function; mod functional; mod algorithms; fn main() { let identity = functional::Identity::new(12); println!("{:?}", identity.apply()) }