text
stringlengths
8
4.13M
use syn::parse::{Parse, ParseStream, Result}; use syn::{braced, token, Ident, Token}; pub struct CodeBlock { pub name: Ident, _colon: Token![:], _brace: token::Brace, pub custom: proc_macro2::TokenStream, _comma: Option<Token![,]> } impl Parse for CodeBlock { fn parse(input: ParseStream) -> Resu...
//! MetroRail related responses from the WMATA API. use crate::{Line, Station}; use chrono::{DateTime, FixedOffset}; use serde::Deserialize; #[derive(Deserialize, Debug)] #[serde(rename_all = "PascalCase")] pub struct Lines { /// See [`Line`]. pub lines: Box<[LineResponse]>, } #[derive(Deserialize, Debug)] #[...
use regex::Regex; #[derive(Debug)] #[derive(PartialEq)] pub enum SExpr<'a> { SInt(i32), SFloat(f32), SSym(&'a str), SStr(&'a str), SList(Vec<SExpr<'a>>) } #[derive(Debug)] #[derive(PartialEq)] struct ParseResult<'a> { parsed: SExpr<'a>, rest: &'a str } // parse 0 or more s-expressions fro...
extern crate bincode_fuzz; use std::env; use bincode_fuzz::corpus::Corpus; use bincode_fuzz::fuzzer::Fuzzer; fn main() { let path = env::args().skip(1).next().unwrap(); let corpus = Corpus::open_or_new(path).unwrap(); let fuzzer = Fuzzer::new(corpus); fuzzer.run().unwrap(); }
use std::time::Instant; use bytes::Bytes; use failure::Error; use futures::prelude::*; use log::info; use srt::{ConnInitMethod, SrtSocketBuilder}; const PACKET_SIZE: usize = 1 << 19; #[tokio::test] async fn message_splitting() -> Result<(), Error> { env_logger::init(); info!("Hi"); let sender = SrtSoc...
use std::fs::File; use std::io::{BufReader, BufRead}; fn main() { let file = File::open("inputs.txt").expect("got an error opening the file"); let buffer = BufReader::new(file); let result: u32 = buffer .lines() .map(|x| { let number: f32 = x.unwrap().parse().unwrap(); ...
#![allow(non_camel_case_types)] pub const CB_PREFIX: u8 = 0xCB; pub enum OpcodeError { InvalidOpcodeInput, } type OpcodeLookupResult = Result<Instruction, OpcodeError>; #[derive(Debug, Clone)] pub enum Instruction { //8 BIT LOAD LD_RR, LD_RN, LD_RHL, LD_HLR, LD_HLN, LD_ABC, LD_AD...
#[doc = "Register `GICH_MISR` reader"] pub type R = crate::R<GICH_MISR_SPEC>; #[doc = "Field `EOI` reader - EOI"] pub type EOI_R = crate::BitReader; #[doc = "Field `U` reader - U"] pub type U_R = crate::BitReader; #[doc = "Field `LRENP` reader - LRENP"] pub type LRENP_R = crate::BitReader; #[doc = "Field `NP` reader - ...
//! This module contains an [`Alignment`] setting for cells on the [`Table`]. //! //! # Example //! #![cfg_attr(feature = "std", doc = "```")] #![cfg_attr(not(feature = "std"), doc = "```ignore")] //! # use tabled::{Table, settings::{Alignment, Modify, object::Rows}}; //! # let data: Vec<&'static str> = Vec::new(); //!...
// This file is part of rdma-core. It is subject to the license terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/rdma-core/master/COPYRIGHT. No part of rdma-core, including this file, may be copied, modified, propagated, or distributed ...
use super::Managable; pub struct ManagedStorage<T> where T: Managable, { heap: Vec<T>, inactive_heap: Vec<T>, } impl<T> ManagedStorage<T> where T: Managable, { pub fn new(size: usize) -> Self { ManagedStorage { heap: Vec::with_capacity(size), inactive_heap: vec![], ...
//! Contains all cryptographic algorithms we need. //! //! This is pretty messy code since we still need openssl to parse PEM-encoded //! keys. Once there's a good Rust crate for that, we should switch to it. use crate::utils::Blob; use crate::{AesKey, Error, ErrorKind, P256KeyPair, P256PublicKey}; use openssl::bn::{...
mod binding_files; mod build_tables; mod char_tree; mod dedup; mod grammars; mod nfa; mod node_types; pub mod parse_grammar; mod prepare_grammar; mod render; mod rules; mod tables; use self::build_tables::build_tables; use self::grammars::{InlinedProductionMap, LexicalGrammar, SyntaxGrammar}; use self::parse_grammar::...
use crate::{resources::prefabs::PrefabRegistry, utils::hierarchy_util}; use amethyst::{ecs::Entity, prelude::*, ui::UiPrefab}; pub struct MenuState { scene_root: Option<Entity>, ui_root: Option<Entity>, } impl Default for MenuState { fn default() -> Self { Self { scene_root: None, ui_root: None,...
//! A module contains [`BufRows`] and [`BufColumns`] iterators. //! //! Almoust always they both can be used interchangeably but [`BufRows`] is supposed to be lighter cause it //! does not reads columns. use crate::grid::records::IntoRecords; use super::either_string::EitherString; /// BufRecords inspects [`IntoReco...
use tokio::time::delay_for; use std::time::Duration; #[tokio::main] async fn main() { println!("start"); delay_for(Duration::from_millis(1000)).await; println!("100 ms have elapsed"); }
use super::*; const EXP_NO_CONFIG_FILE_FOUND_ERROR_CODE: i32 = 3; const EXP_VERSION: &str = env!("CARGO_PKG_VERSION"); const EXP_HOOK_FILE_TEMPLATE: &str = include_str!("hook_files/hook_script.sh"); const EXP_HOOK_CLI_SCRIPT_FILE_TEMPLATE: &str = include_str!("hook_files/cli.sh"); const EXP_HOOK_SEMVER_SCRIPT_FILE_TE...
use hyper::service::{make_service_fn, service_fn}; use hyper::{Body, Client, Request, Response, Server, Uri}; use std::convert::From; use std::convert::Infallible; use std::net::SocketAddr; fn get_dst_host(req: &Request<Body>) -> String { let _dst = req.uri().path_and_query().unwrap().path(); let dst = _dst.to...
// values.rs // // (c) 2017 James Crooks // // Avro Value types for ad-hoc data use super::codec::{AvroCodec, ByteStream}; pub enum AvroValue { Null, Boolean(bool), Int(i32), Long(i64), Float(f32), Double(f64), Bytes(Vec<u8>), String(String), Record(AvroRecord), Fixed(AvroFixed...
use azure_core::AddAsHeader; use http::request::Builder; #[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord)] pub struct SourceContentMD5([u8; 16]); impl From<md5::Digest> for SourceContentMD5 { fn from(md5: md5::Digest) -> Self { Self(md5.0) } } impl AddAsHeader for SourceContentMD5 { fn add_...
use crate::{common::AsyncStream, utils::config::Tls}; use anyhow::{Context, Result}; use futures::TryFutureExt; use log::{debug, trace}; use openssl::ssl::{self, NameType, Ssl}; use std::{env, ops::Deref, path::Path, pin::Pin}; use tokio::{fs::OpenOptions, io::AsyncWriteExt, sync::mpsc}; use tokio_openssl::SslStream; ...
mod assembly; mod compiler; mod scope; pub use self::compiler::Compiler;
#[derive(Clone, Copy, Default, PartialEq, PartialOrd)] #[repr(C, align(16))] pub(crate) struct Align16<T>(pub T); impl<T> Align16<T> { #[allow(dead_code)] pub fn as_ptr(&self) -> *const T { &self.0 } #[allow(dead_code)] pub fn as_mut_ptr(&mut self) -> *mut T { &mut self.0 } } ...
use super::{ arithmetic_operation::ArithmeticOperation, case::Case, comparison_operation::ComparisonOperation, function_application::FunctionApplication, if_::If, let_::Let, let_recursive::LetRecursive, primitive::Primitive, record::Record, record_element::RecordElement, string::ByteString, variable::Va...
use crate::tm::XaError; use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt}; use std::convert::TryInto; use std::io::{Read, Write}; use std::iter::repeat; /// The ID of a distributed transaction, in analogy to the /// [X/Open XA standard](http://pubs.opengroup.org/onlinepubs/009680699/toc.pdf). /// #[derive(Clo...
// Copyright (c) The Starcoin Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::account_config::constants::CORE_CODE_ADDRESS; use crate::{ identifier::{IdentStr, Identifier}, language_storage::{ModuleId, StructTag, TypeTag}, }; use anyhow::Result; use move_core_types::account_address::Account...
use serde::{Deserialize, Serialize}; use serde_repr::{Deserialize_repr, Serialize_repr}; use std::fs::{self, File}; use test_case::test_case; use fnv::FnvHashMap; use std::collections::HashMap; use std::io::{BufRead, BufReader}; use tf_demo_parser::demo::data::DemoTick; use tf_demo_parser::demo::message::packetentitie...
#[doc = "Reader of register CONN_CONFIG_EXT"] pub type R = crate::R<u32, super::CONN_CONFIG_EXT>; #[doc = "Writer for register CONN_CONFIG_EXT"] pub type W = crate::W<u32, super::CONN_CONFIG_EXT>; #[doc = "Register CONN_CONFIG_EXT `reset()`'s with value 0xa000"] impl crate::ResetValue for super::CONN_CONFIG_EXT { t...
use anyhow::{Context, Result}; use std::collections::BTreeMap; use taskpaper::{Database, Position, TaskpaperFile}; pub fn extract_timeline(db: &Database, todo: &mut TaskpaperFile) -> Result<()> { if let Some(path) = db.path_of_common_file(taskpaper::CommonFileKind::Timeline) { taskpaper::mirror_changes(&pa...
use crate::bench_api::{BenchApi, Engine}; use crate::measure::{Measure, Measurements}; use anyhow::Result; use log::info; use sightglass_data::Phase; use std::path::Path; /// Measure various phases of a Wasm module's lifetime. /// /// Provide paths to files created for logging the Wasm's `stdout` and `stderr` /// and ...
extern crate libc; use libc::{c_char, size_t}; use std::{slice, str}; use std::ffi::CStr; #[repr(C)] pub struct RustByteSlice { pub bytes: *const u8, pub len: size_t, } #[no_mangle] pub extern fn rust_hello_world() -> i32 { println!("Hello world from Rust!"); 10 } #[no_mangle] pub extern fn triple_a...
#[doc = "Register `ETH_MACSPI1R` reader"] pub type R = crate::R<ETH_MACSPI1R_SPEC>; #[doc = "Register `ETH_MACSPI1R` writer"] pub type W = crate::W<ETH_MACSPI1R_SPEC>; #[doc = "Field `SPI1` reader - SPI1"] pub type SPI1_R = crate::FieldReader<u32>; #[doc = "Field `SPI1` writer - SPI1"] pub type SPI1_W<'a, REG, const O:...
use std::sync::{mpsc, Arc, Mutex}; use std::thread; pub struct ThreadPool { // La partie émettrice du canal est tenue par le struct Threadpool avec : sender: mpsc::Sender<Message>, // les threads sont contenus dans chaque Worker, qui crée un thread customisé // Chaque Worker s'accorche à la partie réce...
use ::message::{AsDataId, AsDataValue, MsgType, AsMsgType}; use ::{Error, ErrorKind}; use super::application::{ComplexType}; use super::application::SimpleTypeEnum; /// The payload of a data field, or Null of no data was present. #[derive(Clone, Debug, Serialize)] pub enum NullableComplexType { /// No data was pre...
mod challenge17; mod challenge18; mod challenge19; mod challenge20; mod challenge21; mod challenge22; mod challenge23; mod challenge24;
// Test the peek functionality extern crate beanstalkd; use beanstalkd::Beanstalkd; // Delay is in seconds. Use a big delay so the test will finish before the job becomes ready again const RELEASE_DELAY: u32 = 60; #[test] fn no_peek_on_empty_tube() { let tube_name = "no_peek_on_empty_tube"; let mut beanstal...
use std::ffi::{OsStr, OsString}; use std::path::Path; use windows_service::service::{ Service, ServiceAccess, ServiceErrorControl, ServiceInfo, ServiceStartType, ServiceState, ServiceType, }; use windows_service::service_manager::{ServiceManager, ServiceManagerAccess}; use std::thread; use std::time::Duration...
/// This module provides functions and types for window and device management. Window is the main type, providing all functions to create and handle windows. Device creates factories and handles. use ::graphics::*; use ::glutin; use std::error::*; use gfx; use gfx_device_gl; use gfx_window_glutin; use gfx::traits::*; ...
// Copyright 2019, 2020 Wingchain // // 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...
use anyhow::Result; use std::fs; fn do_the_thing(input: &str) -> Result<usize> { let mut joltages = input .lines() .map(|n| n.parse::<usize>().unwrap()) .collect::<Vec<_>>(); joltages.push(0); joltages.sort(); joltages.push(joltages.last().unwrap() + 3); let mut options = jo...
#[doc = "Reader of register RTC_1"] pub type R = crate::R<u32, super::RTC_1>; #[doc = "Reader of field `YEAR`"] pub type YEAR_R = crate::R<u16, u16>; #[doc = "Reader of field `MONTH`"] pub type MONTH_R = crate::R<u8, u8>; #[doc = "Reader of field `DAY`"] pub type DAY_R = crate::R<u8, u8>; impl R { #[doc = "Bits 12:...
#![doc = "generated by AutoRust 0.1.0"] #![allow(non_camel_case_types)] #![allow(unused_imports)] use serde::{Deserialize, Serialize}; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Object {} #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct HyperVCluster { #[serde(default...
extern crate chrono; extern crate reqwest; extern crate serde; extern crate serde_derive; extern crate serde_json; extern crate tokio; use chrono::{prelude::*, Timelike, Utc}; use std::{collections::HashMap, env, thread, time::Duration}; #[tokio::main] async fn main() -> Result<(), String> { let args = env::args...
#![doc = "generated by AutoRust 0.1.0"] #![allow(non_camel_case_types)] #![allow(unused_imports)] use serde::{Deserialize, Serialize}; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Resource { #[serde(default, skip_serializing_if = "Option::is_none")] pub id: Option<String>, #[serde(d...
use std::ops::Index; // It looks like the bit-vec package is better maintained than fixedbitset use fixedbitset::FixedBitSet; #[derive(Clone, Eq, PartialEq, Hash, Debug)] pub struct Bits2D { elem: FixedBitSet, length1: u32, length2: u32, } impl Bits2D { pub fn new(length1: u32, length2: u32) -> Self ...
#[cfg(test)] mod tests { use crate::util::xor; // Second cryptopals challenge - https://cryptopals.com/sets/1/challenges/2 #[test] fn challenge2() { assert_eq!( hex::encode( xor( &hex::decode("1c0111001f010100061a024b53535009181c").unwrap(), ...
use aoc_utils::prelude::*; use std::env; use std::time::Instant; fn sim(mut code: Vec<i32>, noun: i32, verb: i32) -> i32 { code[1] = noun; code[2] = verb; #[inline(always)] fn add(code: &mut Vec<i32>, ip: usize) -> usize { let a = code[ip + 1] as usize; let b = code[ip + 2] as usize; ...
#[cfg(target_board = "mkl43z4")] pub mod mkl43z4; #[cfg(target_board = "mkl43z4")] pub use self::mkl43z4 as target;
use std::fs::File; use std::io::{BufRead, BufReader}; pub fn exercise() { let data = load_data(); let initial_timestamp: i64 = data.get(0).unwrap().parse().unwrap(); let mut bus_ids: Vec<i64> = data.get(1).unwrap().split(',').filter(|c| *c != "x").map(|c| c.parse::<i64>().unwrap() as i64).collect(); bus_ids.so...
use rand::rngs::ThreadRng; use std::rc::Rc; use super::shape_list::ShapeList; use super::xy_rect::XyRect; use super::xz_rect::XzRect; use super::yz_rect::YzRect; use super::{HitRecord, Shape}; use crate::aabb::AABB; use crate::material::Material; use crate::ray::Ray; use crate::vec3::Point3; pub struct Cube { mi...
use crate::primitives::*; pub use crate::primitives::Gwei; pub const BASE_REWARDS_PER_EPOCH: u64 = 4; pub const JUSTIFICATION_BITS_LENGTH: usize = 4; pub const SECONDS_PER_DAY: u64 = 86400; pub const DEPOSIT_CONTRACT_TREE_DEPTH: u64 = 32; pub const FAR_FUTURE_EPOCH: u64 = u64::max_value(); // prideta pub type Deposit...
// Rust style is to indent with four spaces, not a tab. // Rust is an ahead-of-time compiled language, meaning you can compile a program // and give the executable to someone else, and they can run it even without having Rust installed fn main() { // ! indicates a macro println!("Hello world"); }
use std::io; #[derive(Debug)] enum Input { Number, Letters, Symbol } fn kinda(s: String) -> Result<Input, String> { if s.len() < 1 { Err("Empty String".to_string()) } else { match s.parse::<i32>() { Ok(_) => Ok(Input::Number), Err(_) => if s.chars().all(char...
use std::env; use std::process; use std::sync::{Mutex,Arc}; use std::thread; //cargo run 127.0.0.1 20 22 //参见视频:https://www.youtube.com/watch?v=AMyiLHRWPG0 // use std::io::prelude::*; use std::net::TcpStream; // 检测 端口是否打开. TODO 这里还没实现 fn port_fake (host:String, port:u16) -> bool{ println!(" 检测 {} :{} 端口是否...
use std::collections::LinkedList; pub trait Actor { fn handle_message(&self, message: Message); } #[derive(Debug)] pub struct Message { data: String, } impl Message { pub fn new(data: String) -> Self { Self { data } } } struct PingActor {} impl Actor for PingActor { fn handle_message(&s...
extern crate sys; use sys::*; use std::mem; use std::ptr; use std::ffi::CString; const PHP_MODULE_NAME : &str = "hello"; const PHP_HELLO_VERSION : &str = "0.1.0"; extern "C" fn zif_confirm_hello_compiled(_execute_data: *mut zend_execute_data, _return_value: *mut zval) { // void println!("Congratulations! Module ...
/** A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, a2 + b2 = c2 For example, 32 + 42 = 9 + 16 = 25 = 52. There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc. */ pub fn execute(){ let pythagorean: Pythagorean = Pythagorean::new(); let...
//! CLI tool to use the functions provided by the [cranelift-llvm](../cranelift_llvm/index.html) crate. //! //! Reads LLVM IR files, translates the functions' code to Cranelift IL. use cranelift_codegen::binemit::Reloc; use cranelift_codegen::isa::TargetIsa; use cranelift_llvm::{create_llvm_context, read_llvm, transla...
use std::fs::File; use std::io::prelude::*; fn read_file() -> Vec<i32> { let mut file = File::open("./input/input1.txt").unwrap(); let mut contents = String::new(); file.read_to_string(&mut contents).unwrap(); contents.lines().map(|n| n.parse().unwrap()).collect() } fn solve_part_1(v: Vec<i32>) -> i32...
extern crate game_of_life; use game_of_life::parsers::plaintext::*; #[test] fn test_plaintext_is_plaintext_file() { assert!(is_plaintext_file(&"!Name: My name")); assert!(!is_plaintext_file(&"No name")); } #[test] fn test_plaintext_correct_file() { let file = "!Name: My name\n.O\n..O\nOOO"; assert!(pa...
pub use registry::Registry; pub use template::Template; mod registry; mod template;
use crate::body::PollCapacity; use crate::conn::Socket; use crate::{LolbResult, RecvBody}; /// Holder of the actual connection to the service. #[derive(Debug, Clone)] pub struct ServiceConnection(pub h2::client::SendRequest<bytes::Bytes>); impl ServiceConnection { /// Send request + request body to service. p...
pub mod binding; pub mod frame; pub mod grid; pub mod model; pub mod renderpass; pub mod state; pub mod texture; pub mod traits; pub struct Layouts { pub material: wgpu::BindGroupLayout, pub uniforms: wgpu::BindGroupLayout, pub light: wgpu::BindGroupLayout, pub frame: wgpu::BindGroupLayout, pub gri...
pub mod api; use bc::block::LightBlock; use bc::{BlockChain, BLOCKCHAIN}; use clap::Values; use colored::*; use ctx::CONTEXT; use serde_json; use std::sync::{mpsc, Arc, Mutex}; use std::thread; use url; use ws; lazy_static! { pub static ref CHANNEL: ( Arc<Mutex<mpsc::Sender<String>>>, Arc<Mutex<mp...
use std::ptr; use std::mem; use std::marker::PhantomData; type NodeLink<T> = *mut Node<T>; struct Node<T> { data: T, next: NodeLink<T>, prev: NodeLink<T>, } pub struct List<T> { head: NodeLink<T>, tail: NodeLink<T>, marker: PhantomData<T>, } unsafe fn raw_into_box<T>(r: *mut T) -> Box<T> { ...
#![allow(clippy::derive_partial_eq_without_eq)] tonic::include_proto!("api");
pub fn solve_puzzle_part_1(input: &str) -> String { puzzle(input, 1).to_string() } pub fn solve_puzzle_part_2(input: &str) -> String { puzzle(input, input.len() / 2).to_string() } fn puzzle(input: &str, skip: usize) -> u32 { input .chars() .zip(input.chars().cycle().skip(skip)) .fi...
mod state; mod actions; use state::State; use actions::Actions; fn main() { let mut state = State::new(); let actions = Actions::new(); actions.frontload_root_dirs(&mut state); actions.grab_path_meta_data(&mut state); println!("{:?}", state); } #[test] fn integration_test() { let mut state =...
use core::fmt; use core::marker::PhantomData; use core::mem::ManuallyDrop; use core::ptr; use conquer_pointer::{MarkedNonNull, MarkedPtr}; use crate::retired::Retired; use crate::traits::Reclaim; use crate::Unlinked; /********** impl inherent *************************************************************************...
#[test] fn all_frames_have_symbols() { println!("{:?}", backtrace::Backtrace::new()); let mut missing_symbols = 0; let mut has_symbols = 0; backtrace::trace(|frame| { let mut any = false; backtrace::resolve_frame(frame, |sym| { if sym.name().is_some() { any =...
//! # The XML formats //! //! The game client uses XML for a lot of data storage. This module contains helpers for //! typed access to these files. #![warn(missing_docs)] pub use quick_xml as quick; pub mod all_settings; pub mod behavior; pub mod block_library; pub mod common; pub mod credits; pub mod database; pub m...
// =============================================================================== // 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 crate::{components::Position, traits::*}; #[derive(Default)] pub struct Building { texture_index: usize, position: Position, } impl IsDrawable for Building { fn render_info(&self) -> (usize, &Position) { (self.texture_index, &self.position) } fn set_texture_index(&mut self, texture_in...
use crate::exchange::trades::history::OrderBookDiff; use crate::order::{LimitOrder, MarketOrder}; use crate::trader::subscriptions::OrderBookSnapshot; use crate::types::{OrderID, Price, Size}; #[derive(Debug, Eq, PartialEq, Ord, PartialOrd)] pub enum TraderRequest { CancelLimitOrder(OrderID), CancelMarketOrder...
use std::collections::{HashMap, HashSet, VecDeque}; use crate::util::lines_from_file; pub fn day12() { println!("== Day 12 =="); let input = lines_from_file("src/day12/input.txt"); let a = part_a(&input); println!("Part A: {}", a); let b = part_b(&input); println!("Part B: {}", b); } fn part_...
pub mod bcache; pub mod ide; pub mod inode; const BLK_SIZE: usize = 512; const N_DIRECT: usize = 12; const N_INDIRECT: usize = BLK_SIZE / core::mem::size_of::<u32>(); // Directory is a file containing a sequence of dirent structures. const DIR_SIZE: usize = 14; type BlockNum = u32; struct SuperBlock { /// Size ...
extern crate dmbc; extern crate exonum; pub mod utils; use exonum::blockchain::Transaction; use exonum::crypto::{PublicKey, SecretKey}; use exonum::encoding::serialize::FromHex; use dmbc::currency::assets::{AssetBundle, AssetId}; use dmbc::currency::transactions::builders::transaction; #[test] fn capi_transfer() { ...
use nalgebra::Vector3; use rand_distr::{Distribution, UnitDisc}; use crate::ray::Ray; use crate::RNG; pub struct Camera { horizontal: Vector3<f64>, vertical: Vector3<f64>, origin: Vector3<f64>, direction: Vector3<f64>, right: Vector3<f64>, up: Vector3<f64>, lens_radius: f64, } impl Camera...
extern crate system; use system::syscall::sys_iopl; use power::reset; mod power; fn main() { unsafe { sys_iopl(3).unwrap() }; println!("Performing reset"); reset(); }
use rand::distributions::Uniform; use rand::prelude::*; /// A trait that represents a perfect hash function [`Wikipedia`](https://en.wikipedia.org/wiki/Perfect_hash_function) /// pub trait PerfectHash { /// Hashes a key to find its positional index #[inline] fn hash<K: AsRef<[u8]>>(&self, key: K) -> usize ...
// Copyright 2020 <盏一 w@hidva.com> // 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 writing,...
//! Run by: //! adb push target/arm-linux-androideabi/debug/android_logger_demo /data/ //! adb shell /data/android_logger_demo #[macro_use] extern crate log; extern crate android_logger; fn main() { android_logger::init().unwrap(); error!("This is an example message."); warn!("This is an example message.")...
//! Key-value abstractions mod mock; mod traits; pub use mock::FakeKV; pub use traits::StatefulKV;
// Copyright 2018 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. //! Serialization and deserialization of wire formats. //! //! This module provides efficient serialization and deserialization of the //! various wire for...
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use std::collections::{BTreeMap, BTreeSet}; use std::mem; use ocaml::caml; use ocamlrep::OcamlRep; use ocamlrep_derive::OcamlRep; fn v...
/// # How Functions Work - see official document [here](/Users/yukoga/.rustup/toolchains/nightly-x86_64-apple-darwin/share/doc/rust/html/book/second-edition/ch03-03-how-functions-work.html) fn main() { println!("Hello, world!"); another_function(); func_add(5, 6); my_greeting(); my_adding(); ...
// https://www.codewars.com/kata/summy/rust fn summy(strng: &str) -> i32 { strng.split(' ').map(|n| { n.parse::<i32>().unwrap() }).sum() } #[test] fn sample_tests() { assert_eq!(summy("1 2 3"), 6); assert_eq!(summy("1 2 3 4"), 10); assert_eq!(summy("1 2 3 4 5"), 15); assert_eq!(summy("10 10"),...
use nu_engine::{eval_block, CallExt}; use nu_protocol::ast::Call; use nu_protocol::engine::{CaptureBlock, Command, EngineState, Stack}; use nu_protocol::{ Category, Example, IntoInterruptiblePipelineData, PipelineData, Signature, SyntaxShape, Value, }; #[derive(Clone)] pub struct Where; impl Command for Where { ...
const LIB_PATH: &str = "cadical-rel-1.2.1/src"; fn main() { // delete ipasir.cpp cadical.cpp mobical.cpp let src_files = [ "cadical-rel-1.2.1/src/analyze.cpp", "cadical-rel-1.2.1/src/arena.cpp", "cadical-rel-1.2.1/src/assume.cpp", "cadical-rel-1.2.1/src/averages.cpp", "c...
// Copyright 2019-2020 Parity Technologies (UK) Ltd. // This file is part of Substrate. // Substrate 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 Software Foundation, either version 3 of the License, or // (at your option) a...
use super::*; use indicatif::{ProgressIterator}; use std::{fs::File, io::BufWriter, io::prelude::*}; /// Structure that saves the common parameters for reading csv files. /// /// # Attributes /// * path: String - The path where to save the file. E.g. "/tmp/test.csv" /// * verbose: bool - If the progress bars and loggi...
use crate::{Body, Context, Middleware, Response}; use futures::future::BoxFuture; use http::status::StatusCode; #[derive(Debug, Clone, Default)] pub struct NotFound; impl NotFound { pub fn new() -> Self { Self::default() } } impl<State: Send + Sync + 'static> Middleware<Context<State>> for NotFound {...
use crate::errors::*; use crate::types::*; use uuid::Uuid; /// Contains a list of messages found by a search #[derive(Debug, Clone, Default, Serialize, Deserialize)] pub struct FoundMessages { #[doc(hidden)] #[serde(rename(serialize = "@type", deserialize = "@type"))] td_name: String, #[doc(hidden)] ...
#[doc = "Register `ALRM%sSSR` reader"] pub type R = crate::R<ALRMSSR_SPEC>; #[doc = "Register `ALRM%sSSR` writer"] pub type W = crate::W<ALRMSSR_SPEC>; #[doc = "Field `SS` reader - Sub seconds value"] pub type SS_R = crate::FieldReader<u16>; #[doc = "Field `SS` writer - Sub seconds value"] pub type SS_W<'a, REG, const ...
// Copyright (C) 2020 Sebastian Dröge <sebastian@centricular.com> // // Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT> use super::*; use crate::Method; /// `Allow` header ([RFC 7826 section 18.6](https://tools.ietf.org/html/rfc7826#section-18.6)). #[derive(Debug, Clone)] ...
use crate::days::day25::{Keys, parse_input, default_input}; pub fn run() { println!("{}", room_str(default_input()).unwrap()) } pub fn room_str(input : &str) -> Result<i64, ()> { room(parse_input(input)) } pub fn room(keys : Keys) -> Result<i64, ()> { let mut value = 1; let mut loop_size = 0; whi...
use super::LeaseId; use crate::{headers, AddAsHeader}; use http::request::Builder; #[derive(Debug, Clone, Copy)] pub struct ProposedLeaseId(LeaseId); impl From<LeaseId> for ProposedLeaseId { fn from(lease_id: LeaseId) -> Self { Self(lease_id) } } impl AddAsHeader for ProposedLeaseId { fn add_as_h...
pub mod actions; pub mod chains; pub mod context; pub mod json; pub mod tables; pub use self::actions::*; pub use self::chains::*; pub use self::context::*; pub use self::tables::*;
use fuse::{FileAttr, FileType}; use serde::{Deserialize, Serialize}; use time::Timespec; #[derive(Serialize, Deserialize)] #[serde(remote = "FileAttr")] pub struct FileAttrDef { pub ino: u64, pub size: u64, pub blocks: u64, #[serde(with = "TimeSpecDef")] pub atime: Timespec, #[serde(with = "Tim...
/* https://projecteuler.net 145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145. Find the sum of all numbers which are equal to the sum of the factorial of their digits. Note: As 1! = 1 and 2! = 2 are not sums they are not included. NOTES: */ fn solve() -> u64 { // factorials for digits 0 to 9 ...