text
stringlengths
8
4.13M
extern crate las; use las::Reader; #[test] fn detect_laszip() { if cfg!(feature = "laz") { assert!(Reader::from_path("tests/data/autzen.laz").is_ok()); } else { assert!(Reader::from_path("tests/data/autzen.laz").is_err()); } } #[cfg(feature = "laz")] mod laz_compression_test { use las...
use actix_web::web; use actix_web::HttpResponse; use crate::db_connection::{SqlitePool, SqlitePooledConnection}; pub fn pool_handler(pool: web::Data<SqlitePool>) -> Result<SqlitePooledConnection, HttpResponse> { pool.get().map_err(|_| { HttpResponse::InternalServerError().body("error") }) }
use serde::{Serialize, Deserialize}; // Maximum number of temp value types we keep track of pub const MAX_TEMP_TYPES: usize = 8; // Maximum number of local variable types we keep track of const MAX_LOCAL_TYPES: usize = 8; // Represent the type of a value (local/stack/self) in YJIT #[derive(Copy, Clone, PartialEq, Eq...
// Get smart pointer for C++ into Rust code so it is usable use cxx::UniquePtr; // C++ <-> Rust Bridge #[cxx::bridge] mod ffi{ // Rust functions which go to C++ header extern "Rust"{ fn robot_init(); fn robot_periodic(); fn autonomous_init(); fn autonomous_periodic(); ...
// Kata: https://www.codewars.com/kata/513e08acc600c94f01000001/train/rust pub fn rgb(r: i32, g: i32, b: i32) -> String { let mut array = [r, g, b]; for n in array.iter_mut() { if *n < 0 { *n = 0; } if *n > 255 { *n = 255; } } format!("{:02X}{:0...
// Copyright (c) 2016 The vulkano developers // 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. All files in the project carrying such // notice may not be co...
use crate::{ cmd::*, result::Result, staking, traits::{TxnEnvelope, TxnSign}, }; #[derive(Debug, StructOpt)] /// Add a hotspot to the blockchain. The original transaction is created by the /// hotspot miner and supplied here for owner signing. Use an onboarding key to /// get the transaction signed by ...
const INPUT: &str = include_str!("../input"); #[derive(Debug, Clone, Copy, PartialEq, Eq)] struct FourDimensionalPoint { x: isize, y: isize, z: isize, t: isize, } impl FourDimensionalPoint { fn from_input(input: &str) -> Self { let values: Vec<_> = input .split(',') ...
// 17.2 Shuffle // Does 51 swaps, similar to quicksort fn shuffle(generator: &dyn Fn() -> usize) -> Vec<usize> { let mut numbers = (0..52).collect::<Vec<_>>(); for i in (1..52).rev() { let chosen_index = generator() % (i + 1); numbers.swap(chosen_index, i); } numbers } #[test] fn test...
pub mod simple; pub mod subpixel;
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the root directory of this source tree. use super::{trace::TraceTable, ProverError, StarkDomain}; mod boundary; use boundary::BoundaryConstraintGroup; mod periodic_table; use p...
extern crate civ; use civ::logger; fn main() { match logger::init() { Ok(_) => {}, Err(e) => println!("Could not init logger: {}", e) } }
use resol_vbus::{Data, Datagram, Header}; use tokio::net::TcpListener; use tokio::prelude::*; use tokio_resol_vbus::{LiveDataStream, Result, TcpServerHandshake}; fn main() -> Result<()> { let addr = "127.0.0.1:7053".parse().expect("Unable to parse address"); let listener = TcpListener::bind(&addr).expect("Una...
use crate::ast::{Statement, Value}; use crate::environment::Environment; use crate::interpreter::{ErrorType, Interpreter}; use crate::token::Token; use std::cell::{Ref, RefCell, RefMut}; use std::fmt; use std::fmt::Debug; use std::rc::Rc; #[derive(Clone, Debug)] pub struct LoxFunction<'a> { data: Rc<RefCell<LoxFun...
#[cfg(feature = "client")] use graphics::Context; #[cfg(feature = "client")] use opengl_graphics::Gl; use battle_state::BattleContext; use module; use module::{IModule, Module, ModuleBase, ModuleRef}; use net::{InPacket, OutPacket}; use ship::{ShipRef, ShipState}; use sim::SimEventAdder; use vec::{Vec2, Vec2f}; #[cfg...
use super::*; use num_traits::{Float}; use num_complex::{Complex as NumComplex}; impl<T: Float> Complex<T> { /// Convert into `num_complex::Complex` struct. pub fn into_num(self) -> NumComplex<T> { Into::<NumComplex<_>>::into(self) } /// Calculate the principal Arg of self. pub fn arg(self...
#![feature(std_misc, negate_unsigned, dynamic_lib)] extern crate gl; extern crate glfw; extern crate libc; #[cfg(windows)] pub mod win32; #[cfg(windows)] use win32 as platform; #[cfg(target_os = "linux")] pub mod linux; #[cfg(target_os = "linux")] use linux as platform; #[cfg(target_os = "macos")] pub mod osx; #[cf...
use crate::AddAsHeader; use bytes::Bytes; use http::request::Builder; use http::HeaderMap; use std::collections::HashMap; #[derive(Debug, Clone)] pub struct Metadata(HashMap<String, Bytes>); impl Default for Metadata { fn default() -> Self { Self::new() } } impl AsMut<HashMap<String, Bytes>> for Meta...
//! This example demonstrates using the powerful [`static_table!`] macro to translate //! a sequence of arrays and several, optional settings to a static [`str`] table representation. //! //! * Note that [`static_table!`] is evaluated at compile time, resulting in highly efficient runtime performance. //! * [`static_ta...
fn last_digit(lst: &[u64]) -> u64 { if lst.len() == 0 { return 1; } let mut n: u128 = 1; for i in (0..lst.len()).rev() { if n < 4 { n = ((lst[i] % 1000) as u128).pow(n as u32); } else { n = ((lst[i] % 1000) as u128).pow((n % 4 + 4) as u32); } } ...
#![feature(rustc_attrs)] #[rustc_layout_scalar_valid_range_start(u32::MAX)] //~ ERROR pub struct A(u32); #[rustc_layout_scalar_valid_range_end(1, 2)] //~ ERROR pub struct B(u8); #[rustc_layout_scalar_valid_range_end(a = "a")] //~ ERROR pub struct C(i32); #[rustc_layout_scalar_valid_range_end(1)] //~ ERROR enum E { ...
//! Different kinds of render passes. // pub use self::flat::DrawFlat; pub use self::pbm::DrawPbm; pub use self::shaded::DrawShaded; mod flat; mod pbm; mod shaded;
// Copyright 2019. The Tari Project // SPDX-License-Identifier: BSD-3-Clause //! Pedersen commitment types and factories for Ristretto use curve25519_dalek::{ ristretto::RistrettoPoint, traits::{Identity, MultiscalarMul}, }; #[cfg(feature = "precomputed_tables")] use crate::ristretto::pedersen::scalar_mul_wi...
//! Floating Point Unit //! //! *NOTE* Available only on targets with a Floating Point Unit (FPU) extension. use volatile_register::{RO, RW}; /// Register block #[repr(C)] pub struct RegisterBlock { reserved: u32, /// Floating Point Context Control pub fpccr: RW<u32>, /// Floating Point Context Addres...
use crate::utils::get_fl_name; use proc_macro::TokenStream; use quote::*; use syn::*; pub fn impl_browser_trait(ast: &DeriveInput) -> TokenStream { let name = &ast.ident; let name_str = get_fl_name(name.to_string()); let remove = Ident::new(format!("{}_{}", name_str, "remove").as_str(), name.span()); ...
/*! The common `ErrorKind`, `Error`, and `Result` types used throughout. */ #![allow(missing_docs)] use crate::shared::{PackageKind, Platform}; use std::process::ExitStatus; // ------------------------------------------------------------------------------------------------ // Public Types // ------------------------...
extern crate hostname; extern crate bufstream; use bufstream::BufStream; use std::io::{self, Write}; use std::net::TcpListener; use std::thread::spawn; use std::{thread, time}; use std::time::{SystemTime, UNIX_EPOCH}; use std::fs::OpenOptions; mod receiver; mod maildir; fn main() { println!("hello, here is main....
use serde::{Deserialize, Serialize}; use std::default::Default; use std::path::{Path, PathBuf}; #[derive(Clone, Debug, Default, Serialize, Deserialize)] pub struct HttpHandlerConfig { /// Instructs the HTTP handler to use the specified port pub port: Option<u16>, /// Instructs the HTTP handler to bind to ...
use lapin::ConnectionProperties; pub trait BastionExt { fn with_bastion(self) -> Self where Self: Sized, { self.with_bastion_executor() } fn with_bastion_executor(self) -> Self where Self: Sized; } impl BastionExt for ConnectionProperties { fn with_bastion_executor...
use bevy::{ core::FixedTimestep, app::{AppExit, ScheduleRunnerPlugin, ScheduleRunnerSettings}, ecs::schedule::ReportExecutionOrderAmbiguities, input::{keyboard::KeyCode, Input}, log::LogPlugin, prelude::*, utils::Duration, }; use rand::random; const ARENA_WIDTH: u32 = 100; const ARENA_HEIGHT: u32 = 100; struct...
//! //! The Moon OS kernel : Rocket //! #![feature(naked_functions)] #![feature(core_intrinsics)] #![feature(const_fn)] #![feature(unique)] #![feature(asm)] #![feature(lang_items)] #![no_std] /// Provides some classic libc functions, like `memset`, `memcpy` etc... extern crate rlibc; #[macro_use] extern crate lazy_s...
// == // https://github.com/json-patch/json-patch-tests // == use serde::Deserialize; use serde_json::from_slice; use serde_json::from_value; use serde_json::Value; use json_patch::Error; use json_patch::Patch; const T1: &[u8] = include_bytes!("fixtures/spec_tests.json"); const T2: &[u8] = include_bytes!("fixtures/te...
#[macro_use(dense_vec, sparse_vec)] extern crate vectors; use vectors::Vector; use vectors::heap::{SparseVector, DenseVector}; fn main() { let sparse_1 = SparseVector::from(vec![(0, 0.1), (2, 0.2), (4, 0.3), (6, 0.4)]); let sparse_2 = SparseVector::from(vec![(0, 0.2), (3, 0.4), (5, 0.2), (6, 0.6)]); let d...
extern crate futures; extern crate hyper; use internaldata::Server; use futures::future::Future; use futures::{Stream}; use hyper::header::ContentLength; use hyper::server::{Request, Response}; pub type BoxFuture = Box<Future<Item = Response, Error = hyper::Error>>; pub trait EchoHandler { fn handle_post(&self,...
#[doc = "Register `CLKCR` reader"] pub type R = crate::R<CLKCR_SPEC>; #[doc = "Register `CLKCR` writer"] pub type W = crate::W<CLKCR_SPEC>; #[doc = "Field `CLKDIV` reader - Clock divide factor"] pub type CLKDIV_R = crate::FieldReader; #[doc = "Field `CLKDIV` writer - Clock divide factor"] pub type CLKDIV_W<'a, REG, con...
use crate::{effects::EffectKind, fyrox::core::math::Vector3Ext, message::Message, GameTime}; use fyrox::{ core::{ algebra::Vector3, pool::{Handle, Pool}, visitor::{Visit, VisitResult, Visitor}, }, engine::resource_manager::ResourceManager, scene::{ base::BaseBuilder, grap...
use specs::prelude::*; use types::*; use component::flag::IsPlayer; use component::time::{LastFrame, ThisFrame}; pub struct EnergyRegenSystem; #[derive(SystemData)] pub struct EnergyRegenSystemData<'a> { pub lastframe: Read<'a, LastFrame>, pub thisframe: Read<'a, ThisFrame>, pub config: Read<'a, Config>, pub en...
//! Functions and types related to windows. use controls::Control; use ffi_utils::{self, Text}; use libc::{c_int, c_void}; use std::cell::RefCell; use std::ffi::CString; use std::mem; use ui_sys::{self, uiControl, uiWindow}; thread_local! { static WINDOWS: RefCell<Vec<Window>> = RefCell::new(Vec::new()) } define...
//! This crate provides simple API to apply [Simple Linear Image Segmentation](http://infoscience.epfl.ch/record/177415/files/Superpixel_PAMI2011-2.pdf) //! on all types of 3-channel images. It also support SLIC0 variation of SLIC, //! with dynamic normalization of spectral distances. extern crate math; use crate::lab...
#![recursion_limit = "256"] #![allow(clippy::expect_fun_call)] #![warn(missing_docs, missing_debug_implementations, rust_2018_idioms)] //! delicate-scheduler. #[macro_use] extern crate diesel; #[macro_use] extern crate serde; #[macro_use] extern crate diesel_migrations; pub(crate) mod actions; pub(crate) mod compone...
fn read<T: std::str::FromStr>() -> T { let mut s = String::new(); std::io::stdin().read_line(&mut s).ok(); s.trim().parse().ok().unwrap() } fn check(v: &Vec<i32>, n: i32, a0: i32, a1: i32) -> Option<Vec<i32>> { let mut a: Vec<i32> = vec![]; a.push(a0); a.push(a1); for i in 0..n { le...
use crate::backend::{DrawBackend, Resources}; use crate::draw::{Color, DrawContext}; use crate::event::{Event, EventDispatcher}; use crate::geometry::{Position, Size}; use crate::toplevel::TopLevel; use crate::widget::Widget; use std::ops; pub const DEFAULT_WINDOW_SIZE: Size = Size::new(320, 240); /// Top level Windo...
pub fn is_cli_colorized() -> bool { if let Some(_) = option_env!("NO_COLOR") { return false; } if let Some(clicolor_force) = option_env!("CLICOLOR_FORCE") { if clicolor_force != "0" { return true; } } false }
use crate::{Net, Spec, DEFAULT_TX_PROPOSAL_WINDOW}; use ckb_types::prelude::Unpack; use log::info; pub struct TemplateSizeLimit; impl Spec for TemplateSizeLimit { crate::name!("template_size_limit"); fn run(&self, net: &mut Net) { let node = &net.nodes[0]; node.generate_blocks((DEFAULT_TX_PRO...
use std::collections::HashMap; use std::fs::File; use std::io::Write; use bio::io::fastq; use fastq_pair; use neighborhood::*; #[derive(Debug)] pub struct Config { pub barcode_fastq: String, pub sequ_fastq: String, pub out_fastq: String, pub out_barcodes: Option<String>, pub out_barcode_freqs: Op...
#![allow(clippy::module_inception)] #![allow(clippy::too_many_arguments)] #![allow(clippy::ptr_arg)] #![allow(clippy::large_enum_variant)] #![doc = "generated by AutoRust 0.1.0"] #[cfg(feature = "package-2021-06.14.0")] pub mod package_2021_06_14_0; #[cfg(all(feature = "package-2021-06.14.0", not(feature = "no-default-...
use serde::Deserialize; use crate::models::media::Media; use crate::models::AniListID; #[derive(Clone, Debug, Deserialize)] #[serde(rename_all = "camelCase")] pub struct AiringSchedule { /// The time the episode airs at airing_at: i64, /// The airing episode number episode: u32, /// The id of the ...
use async_trait::async_trait; use common::result::Result; use crate::domain::role::{Role, RoleId}; #[async_trait] pub trait RoleRepository: Sync + Send { async fn find_all(&self) -> Result<Vec<Role>>; async fn find_by_id(&self, id: &RoleId) -> Result<Role>; async fn save(&self, role: &mut Role) -> Resul...
pub mod player_controller;
use log::{debug, error, warn}; use serde::{Deserialize, Serialize}; use super::InfocomError; use super::memory::{MemoryMap, Version}; use super::state::FrameStack; use super::text::Decoder; #[derive(Serialize, Deserialize, Clone)] struct Property { number: usize, address: usize, size: u16, data_addres...
use youchoose; fn main(){ let mut menu = youchoose::Menu::new(0..100).preview(multiples); let choice = menu.show(); println!("Chose {:?}", choice); } fn multiples(num: i32) -> String { let mut buffer = String::new(); for i in 0..20 { buffer.push_str( &format!("{} times {} ...
use log::info; use std::fs::File; use std::io::Read; use std::path::Path; #[derive(Debug, serde::Deserialize)] pub struct Configuration { #[serde(skip)] pub websites: Vec<String>, pub parallel_fetch: usize, pub interval_between_fetch: u64, pub stop_after_iteration: usize, pub run_forever: bool,...
#[macro_use] extern crate clap; #[macro_use] extern crate failure; #[macro_use] extern crate log; use ark_auth::{cli, core, driver, driver::Driver, server}; use clap::{App, Arg, SubCommand}; use sentry::integrations::log::LoggerOptions; const COMMAND_CREATE_ROOT_KEY: &str = "create-root-key"; const COMMAND_DELETE_ROO...
//! The `retransmit_stage` retransmits shreds between validators #![allow(clippy::rc_buffer)] use { crate::{ ancestor_hashes_service::AncestorHashesReplayUpdateReceiver, cluster_info_vote_listener::VerifiedVoteReceiver, cluster_nodes::ClusterNodesCache, cluster_slots::ClusterSlots, ...
#![cfg_attr(target_arch = "wasm32", no_std)] //! Provide minimalist debug tracing that works even in wasm32. Since wasm //! browser sandboxes currently do not have stderr, debug logging must go //! through a javascript function binding. Passing strings from wasm to //! javascript is possible, but it adds lots of comple...
mod config_files; mod logger; mod test_bins; #[cfg(test)] mod tests; #[cfg(feature = "plugin")] use crate::config_files::NUSHELL_FOLDER; use crate::logger::{configure, logger}; use log::info; use miette::Result; #[cfg(feature = "plugin")] use nu_cli::read_plugin_file; use nu_cli::{ evaluate_commands, evaluate_file...
use crate::api::consts::*; use crate::state::lua_value::LuaValue; use crate::state::math; fn iadd(a: i64, b: i64) -> i64 { a + b } fn fadd(a: f64, b: f64) -> f64 { a + b } fn isub(a: i64, b: i64) -> i64 { a - b } fn fsub(a: f64, b: f64) -> f64 { a - b } fn imul(a: i64, b: i64) -...
extern crate error_chain; extern crate kvdemo; extern crate rand; use rand::prelude::random; use kvdemo::client::{ConnectOptions, KVGrpcClient}; use kvdemo::codec::BytesSerializer; use kvdemo::errors::Result; fn rand_int_array(count: usize) -> Vec<u32> { let mut v: Vec<u32> = (0..100u32).collect(); for i in ...
pub mod iser0 { pub mod setena { pub fn get() -> u32 { unsafe { core::ptr::read_volatile(0xE000E100u32 as *const u32) & 0xFFFFFFFF } } pub fn set(val: u32) { unsafe { let mut reg = core::ptr::read_volatile(0xE000E100u32 as ...
//! clap App for command cli use clap::{App, Arg, ValueHint}; const COMMAND: &str = "cli-completion"; const VERSION: &str = "0.1.0"; pub fn build_app() -> App<'static> { // init Clap App::new(COMMAND) .version(VERSION) .author("linux_china, https://twitter.com/linux_china") .about("CLI...
#[doc = "Register `FDCAN_RWD` reader"] pub type R = crate::R<FDCAN_RWD_SPEC>; #[doc = "Register `FDCAN_RWD` writer"] pub type W = crate::W<FDCAN_RWD_SPEC>; #[doc = "Field `WDC` reader - WDC"] pub type WDC_R = crate::FieldReader; #[doc = "Field `WDC` writer - WDC"] pub type WDC_W<'a, REG, const O: u8> = crate::FieldWrit...
use std; use std::fs::File; use std::io::{self, Read}; pub fn create(filename: String) -> Box<DataReader> { if filename.is_empty() { Box::new(StandardInputReader::new()) } else { Box::new(FileReader::new(filename)) } } pub trait DataReader { fn read_data(&mut self) -> Result<Vec<u8>, s...
use ossdev_01_485516::*; #[test] fn test_basic_primes() { vec![2, 3, 5, 7, 11, 13, 17, 19] .iter() .for_each(|x| assert_eq!(is_prime(*x as u32), true)) } #[test] fn test_not_primes() { vec![4, 6, 9, 15, 27, 81, 64] .iter() .for_each(|x| assert_ne!(is_prime(*x as u32), true)) } ...
#[doc = "Register `CICR` writer"] pub type W = crate::W<CICR_SPEC>; #[doc = "LSI ready interrupt clear\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum LSIRDYC_AW { #[doc = "1: Clear interrupt flag"] Clear = 1, } impl From<LSIRDYC_AW> for bool { #[inline(always)] fn from(vari...
use crate::domain::subscriber_name::SubscriberName; use super::subscriber_email::SubscriberEmail; pub struct NewSubscriber { pub name: SubscriberName, pub email: SubscriberEmail, }
#[doc = "Register `TDR` writer"] pub type W = crate::W<TDR_SPEC>; #[doc = "Field `TD` writer - Transmit data"] pub type TD_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 32, O, u32>; impl W { #[doc = "Bits 0:31 - Transmit data"] #[inline(always)] #[must_use] pub fn td(&mut self) -> TD_W<TDR_SPEC,...
mod brainfuck; use brainfuck::{BrainfuckContext, Instruction}; use std::error::Error; use std::fs; pub fn run(program_path: &str) -> Result<(), Box<dyn Error>> { let program_string = fs::read_to_string(program_path)?; let program_parsed = parse(&program_string)?; let mut bf_context = BrainfuckContext::ne...
// Copyright 2018 Parity Technologies (UK) Ltd. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, mer...
use clap::ArgMatches; use crate::errors::StandardResult; use crate::utils::config::ConfigIO; use crate::INSTALL_DIR; pub fn list(_args: &ArgMatches) -> StandardResult<()> { let io = ConfigIO::new()?; for template in io.iter() { println!("{} {}/{}", template.name, INSTALL_DIR, template.path); } ...
use crate::token:: { TokenKind, Token }; #[derive(Debug, Clone)] pub enum Ast { Program { statements: Vec<Box<Ast>> }, Expression { token: Token, }, Identifier { token: Token, value: String, }, LetStatement { token: Token, ident: Box<As...
/* * Datadog API V1 Collection * * Collection of all Datadog Public endpoints. * * The version of the OpenAPI document: 1.0 * Contact: support@datadoghq.com * Generated by: https://openapi-generator.tech */ /// AwsTagFilterListResponse : An array of tag filter rules by `namespace` and tag filter string. #[d...
mod day01; mod day02; mod day03; fn main() { let _ = day01::main(); let _ = day02::main(); let _ = day03::main(); }
use fnv::FnvHashSet; #[derive(Debug, Serialize, Deserialize, Clone, Copy, Eq, PartialEq, Hash)] pub enum Features { All, TokensToTextID, BoostTextLocality, BoostingFieldData, Search, Filters, Facets, Select, WhyFound, Highlight, PhraseBoost, } impl Features { pub fn get...
use std::ops::Drop; #[derive(Debug)] struct S(i32); impl Drop for S{ fn drop(&mut self){ println!("drop for {}",self.0); } } fn main(){ let x=S(1); println!("create x:{:?}",x); let x=S(2); println!("create shadowing x:{:?}",x); }
/// Activatable data acumulator. pub struct StringAccumulator { acc: Option<String>, } impl StringAccumulator { /// Create a new data accumulator. pub fn new() -> StringAccumulator { StringAccumulator { acc: None } } /// Start accumulating data pub fn activate(&mut self) { self...
use crate::core::{ authentication_barcode, authentication_nfc, authentication_password, fuzzy_vec_match, Account, Money, Permission, Pool, ServiceError, ServiceResult, }; use crate::identity_policy::{Action, RetrievedAccount}; use crate::login_required; use crate::web::utils::{EmptyToNone, HbData, IsJson, Searc...
use crate::{backend::SchemaBuilder, prepare::*, types::*, ColumnDef, SchemaStatementBuilder}; /// Alter a table /// /// # Examples /// /// ``` /// use sea_query::{*, tests_cfg::*}; /// /// let table = Table::alter() /// .table(Font::Table) /// .add_column(ColumnDef::new(Alias::new("new_col")).integer().not_nul...
use super::*; use crate::lexer::Lexer; use crate::parser::Parser; use std::fs::{read, read_to_string}; use std::path::Path; #[test] fn affect() { test("affect"); } #[test] fn boucle() { test("boucle"); } #[test] fn expression() { test("expression"); } #[test] fn max() { test("max"); } #[test] fn tr...
use crate::frontend::layer_panel::LayerPanelEntry; use crate::message_prelude::*; use crate::Color; use serde::{Deserialize, Serialize}; pub type Callback = Box<dyn Fn(FrontendMessage)>; #[impl_message(Message, Frontend)] #[derive(PartialEq, Clone, Deserialize, Serialize, Debug)] pub enum FrontendMessage { CollapseF...
fn main() { println!("{}", factorial_iterative(10)); println!("{}", factorial_recursive(10)); println!("{}", factorial_tail_recursive(10)); } // Using iteration fn factorial_iterative(n: int) -> int { let mut acc: int = 1; for i in range(1, n + 1) { acc *= i; } acc } // Using recur...
//! GoodReads book schemas and record processing. use chrono::NaiveDate; use serde::Deserialize; use crate::arrow::*; use crate::cleaning::isbns::*; use crate::parsing::*; use crate::prelude::*; const ID_FILE: &'static str = "gr-book-ids.parquet"; const INFO_FILE: &'static str = "gr-book-info.parquet"; const SERIES_F...
extern crate proc_macro; use darling::{FromDeriveInput, FromField}; use proc_macro::TokenStream; use proc_macro_error::{abort, proc_macro_error}; use quote::quote; // use proc_macro2::TokenStream as TokenStream2; use syn::{parse_macro_input, spanned::Spanned, DeriveInput, Fields, FieldsNamed, ItemStruct}; macro_rules...
use colored::Colorize; use futures::stream::StreamExt; use serde::{Deserialize, Serialize}; use structopt::StructOpt; use persist_core::error::Error; use persist_core::protocol::{LogStreamSource, LogsRequest, LogsResponse}; use crate::daemon; #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, StructOpt)] pub ...
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. use base::prelude::*; use io::{Read}; use core::{mem, cmp}; use base::{error}; use super::{Zone}; macro_rules! rd {...
use serde::Deserialize; #[derive(Deserialize, Clone, Debug)] #[serde(rename_all = "camelCase")] pub struct Statistics { pub uuid: String, pub player_count: u64, pub mem_mb: u64, pub mc_version: f64, pub os: String, pub java_version: u32, pub ...
use std::any::TypeId; use std::cell::RefCell; use std::collections::HashMap; use std::hash::{BuildHasherDefault, Hasher}; use std::ptr::NonNull; use std::sync::Arc; use crate::coroutine_impl::Coroutine; use crate::join::Join; use generator::get_local_data; // thread local map storage thread_local! {static LOCALMAP: L...
use std::collections::HashMap; pub trait SimpleDB { fn set(&mut self, key: String, value: u32); fn get(&mut self, key: String) -> Option<&u32>; fn unset(&mut self, key: String); fn begin_transaction(&mut self); fn rollback(&mut self) -> Result<(), String>; fn commit(&mut self) -> Result<(), Str...
#[macro_use] extern crate log; mod sshagent; mod rustica; use clap::{App, Arg}; use sshagent::{Agent, error::Error as AgentError, Identity, SSHAgentHandler, Response}; use std::env; use std::os::unix::net::{UnixListener}; use std::process; use rustica::{cert, RusticaServer, Signatory}; use rustica_keys::ssh::{Certi...
#[doc = "Register `EMR` reader"] pub type R = crate::R<EMR_SPEC>; #[doc = "Register `EMR` writer"] pub type W = crate::W<EMR_SPEC>; #[doc = "Field `MR0` reader - Event Mask on line 0"] pub type MR0_R = crate::BitReader<MR0_A>; #[doc = "Event Mask on line 0\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, ...
/// Exchanges a temporary OAuth code for an API token. /// /// Wraps https://api.slack.com/methods/oauth.access #[derive(Clone, Debug, Serialize, new)] pub struct AccessRequest<'a> { /// Issued when you created your application. pub client_id: &'a str, /// Issued when you created your application. pub ...
use criterion::{black_box, criterion_group, criterion_main, Criterion}; use uniform_rand::{ my_blake2b_hash, my_blake2s_hash, my_blake3_hash, my_sha3_hash, rounding_algo, TIME, UPPER, }; pub fn criterion_benchmark(c: &mut Criterion) { c.bench_function("my_sha3_hash", |b| { b.iter(|| rounding_algo(black...
use std::error; use std::fmt; #[derive(Debug)] pub enum Error { CloseNodeError(String, &'static str), /// The list of dependencies is empty EmptyListError, IteratorDropped, NoAvailableNodeError, ResolveGraphError(&'static str), } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::For...
use std::sync::mpsc::channel; use std::thread; let (sender, receiver) = channel(); thread::spawn(move|| { sender.send(expensive_computation()).unwrap(); }); println!("{:?}", receiver.recv().unwrap());
use hymns::p2; use hymns::runner::timed_run; use hymns::vector2::Point2; use std::collections::HashSet; const INPUT: &str = include_str!("../input.txt"); fn reflect_points(axis: char, x_or_y: usize, points: &mut HashSet<Point2<usize>>) { let mut points_to_move = vec![]; for point in points.iter() { i...
// =============================================================================== // 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...
use reqwest::header::HeaderValue; use serde::{Deserialize, Serialize}; #[derive(Clone)] pub struct DockerHub { username: String, password: String, } #[derive(Deserialize, Debug, Clone)] pub struct Token { pub token: String, } impl DockerHub { pub fn new(username: String, password: String) -> DockerHu...
// Tests OP_COMPRESSED. To actually test compression you need to look at // server logs to see if decompression is happening. Even if these tests // are run against a server that does not support compression // these tests won't fail because the messages will be sent without compression // (as indicated in the specs)...
use structopt::StructOpt; use tonic::{transport::Channel, Request, Response}; use pomodoro::session_client::SessionClient; use pomodoro::{ get_state_response::Phase, GetStateRequest, GetStateResponse, StartRequest, StartResponse, StopRequest, StopResponse, }; pub mod pomodoro { tonic::include_proto!("pomo...
extern crate rand; extern crate image; use std::collections::HashMap; use rand::random; use std::fs::File; use std::path::Path; /// Single map point pub struct Field{ state: u32, } impl Field{ pub fn new(state: u32) -> Field{ Field{ state: state, } } } /// Whole map pub stru...
fn main() { let an_integer = 1u32; let a_boolean = true; let unit = (); // copy `an_integer` into `copied_integer` let copied_integer = an_integer; println!("An integer: {:?}", copied_integer); println!("A boolea: {:?}", a_boolean); println!("Meet the unit value: {:?}", unit); ...