text
stringlengths
8
4.13M
#[macro_use] extern crate failure; pub mod benchmark; pub mod database; pub mod dynamic_smt; pub mod hashtree; pub mod merkletrie; pub mod merkletrie_interface; pub mod smt;
//! All errors related to Conventional Commits. use std::fmt; /// The error returned when parsing a commit fails. #[derive(Clone, Debug, Eq, PartialEq)] pub struct Error { kind: ErrorKind, commit: Option<String>, } impl Error { /// Create a new error from a `ErrorKind`. pub(crate) fn new(kind: Error...
use std::convert::{Infallible, TryInto}; use std::ops::FromResidual; /// FFI representation for function result type. /// /// [`svm_result_t`] effectively has three variants: /// /// - Error variant. /// - Receipt variant. /// - No data, just okay state. /// /// Please note that [`svm_result_t`] implements [`std::ops:...
#[allow(unused_imports)] use serde_json::Value; #[derive(Debug, Serialize, Deserialize)] pub struct ProvidersFileFileItem { /// Enables authentication and identity mapping through the authentication provider. #[serde(rename = "authentication")] pub authentication: Option<bool>, /// Automatically create...
/* ----------------------------------------------------------------------------------- * src/lib.rs - Root of the Beetle library. * porcupine - Safe wrapper around the graphical parts of Win32. * Copyright © 2020 not_a_seagull * * This project is licensed under either the Apache 2.0 license or the MIT license, at ...
pub mod config; pub mod request_data; pub mod auth_data;
extern crate binjs_meta; extern crate itertools; use binjs_meta::export::{TypeDeanonymizer, TypeName}; use binjs_meta::spec::*; use binjs_meta::util::*; use std::borrow::Cow; use std::collections::{HashMap, HashSet}; use std::rc::Rc; use itertools::Itertools; /// Source code produced by exporting a spec to Rust. pu...
use sc_cli::RunCmd; #[derive(Debug, clap::Parser)] pub struct Cli { #[command(subcommand)] pub subcommand: Option<Subcommand>, #[clap(flatten)] pub run: RunCmd, } #[derive(Debug, clap::Subcommand)] #[allow(clippy::large_enum_variant)] pub enum Subcommand { /// Key management cli utilities #[command(subcommand)...
#![allow(dead_code)] use std::mem; mod sh; mod pm; mod combination_locks; mod data_structures; mod collections; mod strings; mod functions; mod methods; mod traits; mod trait_params; mod into_trait; mod drop_trait; const MEANING_OF_LIFE: u8 = 42; static mut Z: i32 = 123; fn scope_and_shadowing() { let a = 123; ...
#[derive(Clone, Copy, Debug)] pub struct Payload { pub content: [u8; 5], pub padding: u8, } impl Payload { pub fn new(content: [u8; 5]) -> Self { Payload { content, padding: 0, } } } pub fn split_data(data: &[u8]) -> Vec<Payload> { // TODO: Don't hardcode 5 ...
use crate::intcode::IntcodeMachine; use itertools::iproduct; struct BeamDetector { program: IntcodeMachine, } impl BeamDetector { fn within_beam(&self, x: i64, y: i64) -> bool { let mut program = self.program.clone(); let mut input = vec![x, y]; let mut out = None; program.run_...
#[doc = "Reader of register X2"] pub type R = crate::R<u32, super::X2>; #[doc = "Writer for register X2"] pub type W = crate::W<u32, super::X2>; #[doc = "Register X2 `reset()`'s with value 0"] impl crate::ResetValue for super::X2 { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { ...
use crate::utils::string_from_file; use itertools::Itertools; pub fn run() { let input = string_from_file("src/09input"); println!("{}", solve(input, 25)); } pub fn solve(input: String, window: usize) -> usize { let data = input .lines() .map(|l| l.trim().parse::<usize>().unwrap()) ...
use crate::util::mem_util::from_user; use super::time::{timespec_t, OcclumTimeProvider}; use super::*; use rcore_fs::dev::TimeProvider; const UTIME_NOW: i64 = (1i64 << 30) - 1i64; pub const UTIME_OMIT: i64 = (1i64 << 30) - 2i64; bitflags! { pub struct UtimeFlags: i32 { const AT_SYMLINK_NOFOLLOW = 1 << 8...
#![feature(box_syntax)] #[macro_use] extern crate lalrpop_lambda; fn main() { dbg!(app!(abs!{x.app!(x,y)}, abs!{y.app!(x,y)}).free_variables()); dbg!(app!(abs!{f.abs!{x.app!(f,x)}}, abs!{x.x}).free_variables()); }
#[macro_use(bson, doc)] extern crate bson; #[macro_use] extern crate chan; #[macro_use] extern crate clap; extern crate curl; extern crate proddle; extern crate rand; #[macro_use] extern crate slog; #[macro_use] extern crate slog_scope; extern crate slog_term; extern crate time; use bson::Document; use clap::{App, Arg...
use std::collections::HashMap; pub fn run(vs: Vec<String>) { let (twice, thrice) = star1(vs.clone()); println!("{} * {} = {}", twice, thrice, twice*thrice); println!("{}", star2(vs.clone())); } fn star1(vs: Vec<String>) -> (usize, usize) { let (mut twice, mut thrice) = (0, 0); for line in vs.iter(...
use std::io::Write; use std::{ collections::HashSet, fs::File, path::{Path, PathBuf}, process::{Command, Stdio}, time::Duration, }; use anyhow::bail; use colored::Colorize; use serde::{Deserialize, Serialize}; use serde_json::Value; use types::{Recording, RecordingInner, Season}; use valico::json_s...
mod tiles; mod items; mod enemies; mod world; mod player; mod actions; mod game; fn main() { game::play(); }
use bincode; use path_clean::PathClean; use pathdiff; use serde::{ Deserialize, Serialize, }; use crate::ast::{ File, Scope, }; use crate::check::Checker; use crate::compiler::compile; use crate::error::SyntaxError; use crate::parser::Parser; use crate::runtime::inst::Inst; use crate::source::Code; us...
use anyhow::{Result,anyhow}; use iota_streams::app::transport::{ tangle::{ client::{Client}, PAYLOAD_BYTES, MsgId, } }; use iota_streams::app_channels::api::tangle::{Address, Author, ChannelAddress}; use iota_streams::core_edsig::signature::ed25519::PublicKey; use std::str::FromStr; pu...
use std::iter::FromIterator; use super::token::TokenMetaData; pub struct SlidingWindow { characters: Vec<char>, current_pos: usize, offset: usize, file_len: usize, current_line: usize, relative_line_pos: usize } impl SlidingWindow { pub fn new(source_code: &str) -> SlidingWindow { ...
//! Device configuration abstraction use std::slice; use std::marker::PhantomData; use tokio::prelude::*; use tokio::sync::mpsc as tokio_mpsc; use std::sync::mpsc as std_mpsc; use arrayvec; use device; use device::{AsyncHidDevice, MidiFader, MidiFaderExtensions, ParameterValue, GetParameter}; // Overall, the code in ...
use crate::{ error::{Error, Result}, util::handle_oauth2_error_response, }; use reqwest::Client; use serde::Deserialize; use url::Url; /// A list of the Microsoft Graph permissions that you want the user to consent to. /// /// # See also /// [Microsoft Docs](https://docs.microsoft.com/en-us/graph/permissions-r...
use serde::ser::{Serialize, Serializer}; use crate::list::List; use crate::map::{Map, BloomMap}; use crate::set::{Set, BloomSet}; impl<'arena, T> Serialize for List<'arena, T> where T: Serialize { #[inline] fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer ...
#[doc = "Register `IEN` reader"] pub struct R(crate::R<IEN_SPEC>); impl core::ops::Deref for R { type Target = crate::R<IEN_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<IEN_SPEC>> for R { #[inline(always)] fn from(reader: crate::R<IEN_SPEC>) ...
use num::FromPrimitive; use num_derive::FromPrimitive; use serdine::derive::{Deserialize, Serialize}; #[derive(Clone, Copy, Default, Deserialize, FromPrimitive, PartialEq, Serialize)] #[repr(u16)] pub enum soundtype { sdlib = 2, spkr = 1, #[default] off = 0, } // For readability. Possibly, only a refe...
pub use defer::defer; pub use error::{Ignore, SafeUnwrap}; pub use input::{input, input_string, prompt, Prompt}; mod defer; mod error; mod input;
use std::cmp::Ordering; use std::path::Path; use serde::Deserialize; use crate::util::Util; fn name_cmp<P: AsRef<Path>>(abs_path_a: &P, abs_path_b: &P) -> Ordering { let file_name_a = abs_path_a.as_ref().file_name(); let file_name_b = abs_path_b.as_ref().file_name(); file_name_a.cmp(&file_name_b) } fn m...
use ast::{Ident, Type, Expr, ArithBinOp, ArithOp, CmpBinOp, CmpOp, If, Apply, Fun, LetFun, LetRec}; pub fn arith_op(l: Expr, op: ArithOp, r: Expr) -> Expr { ArithBinOp { kind: op, lhs: l, rhs: r, } .into() } pub fn cmp_op(l: Expr, op: CmpOp, r: Expr) -> Expr { CmpBinOp { ...
use crate::Vec3 as Point3; use crate::Vec3; use crate::ray::Ray; use crate::rtweekend; use crate::vec3::random_in_unit_disk; pub struct Camera { origin: Point3, horizontal: Vec3, vertical: Vec3, lower_left_corner: Vec3, u: Vec3, v: Vec3, w: Vec3, lens_radius: f32 } impl Camera { p...
use std::net::{TcpListener, TcpStream, SocketAddr, Shutdown}; use std::io::{Write,Read}; use std::time::Duration; use std::thread; use base64::{decode,encode}; mod crypt; pub mod auth; #[derive(Debug,Clone)] pub struct Request { pub r#type:String, pub req_id:String, pub data:String, pub peer:SocketAdd...
extern crate hyper; #[macro_use] extern crate log; extern crate sxd_document; pub mod requests; pub mod properties; pub mod responses; pub mod xml; #[test] fn it_works() { }
use super::buffer::Buffer; use super::racer::Cycle; use crate::irust::printer::{Printer, PrinterItem, PrinterItemType}; use crate::irust::{IRust, IRustError}; use crate::utils::StringTools; use crossterm::{ClearType, Color}; impl IRust { pub fn handle_character(&mut self, c: char) -> Result<(), IRustError> { ...
use wasmer::WasmTypeList; use std::marker::PhantomData; /// A [`wasmer`] function with a checked type signature and name. pub struct Function<'a, Args, Rets> where Args: WasmTypeList, Rets: WasmTypeList, { func: &'a wasmer::Function, name: &'a str, phantom: PhantomData<(Args, Rets)>, } impl<'a, A...
#[derive(Clone)] pub struct SimpleLinkedList<T> { head: Option<Box<Node<T>>>, } #[derive(Clone)] pub struct Node<T> { data: T, next: Option<Box<Node<T>>> } impl<T> SimpleLinkedList<T> { pub fn new() -> Self { SimpleLinkedList::<T>{ head: Option::None } } pub fn len(&self) -> usize { ...
use std::collections::VecDeque; enum ProgramResult { WaitForInputAt, Output(i32), Halted, } struct ProgramState { program: Vec<i32>, inputs: VecDeque<i32>, pc: usize, } impl ProgramState { fn get_param(&self, p: usize) -> i32 { let pmode = self.program[self.pc] / (100 * 10i32.pow(...
use std::sync::mpsc::Receiver; use std::thread::Builder; use serde::Serialize; use serde_json; use ws::{self, Handler, Message, Sender, WebSocket}; /// A WebSocket client connection struct Client { sender: Sender, } impl Handler for Client { fn on_message(&mut self, message: Message) -> Result<(), ws::Error>...
use crate::native::registry::Registry; use crate::runtime::frame::Frame; pub fn init() { Registry::register("java/io/FileDescriptor", "initIDs", "()V", init_ids); Registry::register("java/io/FileDescriptor", "set", "(I)J", set); } pub fn init_ids(frame: &mut Frame) {} pub fn set(frame: &mut Frame) { let ...
use std::future::Future; use std::time::Instant; use crate::pool::{CheckOut, Dependencies}; pub enum Status { Valid, Invalid, } /// A trait for managing the lifecycle of a resource. pub trait Manage: Sized { type Resource: Send; type Dependencies: Dependencies; type CheckOut: From<CheckOut<Self...
pub use crate::adc::ChannelTimeSequence as _stm32_hal_adc_ChannelTimeSequence; pub use crate::afio::AfioExt as _stm32_hal_afio_AfioExt; pub use crate::crc::CrcExt as _stm32_hal_crc_CrcExt; pub use crate::dma::CircReadDma as _stm32_hal_dma_CircReadDma; pub use crate::dma::DmaExt as _stm32_hal_dma_DmaExt; pub use crate::...
use serialisation::f1_2018::packets::PacketHeader; #[derive(Serialize, Deserialize, PartialEq, Debug, Clone)] pub struct PacketLapData { pub m_header: PacketHeader, pub m_lapData: [LapDataItem; 20], // Lap data for all cars on track } #[derive(Serialize, Deserialize, PartialEq, Debug, Clone)] pub struct LapD...
use std::ops::Sub; use std::cmp::{PartialEq, PartialOrd}; use std::default::Default; use std::iter::Sum; use std::marker::Copy; pub struct Triangle<T> { sides: [T; 3] } impl<T> Triangle<T> where T: Sub<Output = T> + PartialOrd + PartialEq + Default + Copy + Sum { pub fn build(sides: [T; 3]) -> Opt...
#![cfg_attr(feature = "cargo-clippy", allow(unused_parens))] #[macro_use] extern crate error_chain; #[macro_use] extern crate nom; #[macro_use] extern crate quote; #[macro_use(parse_quote)] extern crate syn; #[cfg(feature = "serde-json")] extern crate serde; #[cfg(feature = "serde-json")] extern crate serde_json; pu...
// Copyright 2019 Conflux Foundation. All rights reserved. // Conflux is free software and distributed under GNU General Public License. // See http://www.gnu.org/licenses/ /// The trait for database manager of Snapshot. pub trait SnapshotDbManagerTrait { type SnapshotDb: SnapshotDbTrait<ValueType = Box<[u8]>>; ...
use libflate::zlib::{Decoder, Encoder}; use std::fs; use std::fs::File; use std::io::{Read, Write}; use std::path::Path; use std::process::Command; pub struct Repo { git_root: String, } impl Repo { pub fn new() -> Self { Self { git_root: Self::git_root(), } } pub fn read(&...
// stroke.rs extern crate footile; use footile::{PathBuilder,Plotter}; fn main() -> Result<(), std::io::Error> { let path = PathBuilder::new().relative().pen_width(5.0) .move_to(16.0, 48.0) .line_to(32.0, 0.0) .line_to(-16.0, -32.0) ...
use core::fmt; pub trait HasEndianness: Eq + PartialEq + Copy + Clone + Default { fn from_be(self) -> Self; fn from_le(self) -> Self; fn to_be(self) -> Self; fn to_le(self) -> Self; } macro_rules! impl_has_endianness { ($t: ty) => { impl HasEndianness for $t { fn from_be(self) ...
use console::Emoji; crate static ERROR: Emoji<'_, '_> = Emoji("\u{26d4} ", ""); crate static INFO: Emoji<'_, '_> = Emoji(" \u{2139}\u{fe0f} ", " -> ");
use lib_goo::config::OutputKind; use lib_goo::entities::FormattedAction; mod history_view; pub mod main_screen; mod output_selector; mod processor; pub struct UserSelection { pub action: Option<FormattedAction>, pub kind: Option<OutputKind>, }
#![feature(box_syntax)] #![recursion_limit="128"] extern crate email; extern crate maildir; extern crate tempdir; extern crate time; #[macro_use] extern crate tryin; pub mod util; use email::{Header, Mailbox, MimeMessage}; use maildir::*; use maildir::raw::*; use util::*; fn test_mime_msg() -> MimeMessage { let...
use std::error::Error; use std::marker::PhantomData; use std::path::Path; use std::sync::Arc; use std::time::Instant; use derive_more::{Display, From}; use rocksdb::{ColumnFamily, DBIterator, Options, WriteBatch, DB}; use async_trait::async_trait; use common_apm::metrics::storage::on_storage_put_cf; use protocol::co...
#[derive(Debug)] enum Person { Name(String), Age(i32) } fn main() { let mut v1 : Vec <i32> = Vec::new(); let mut v2 = vec![1, 2, 3]; v1.push(4); v1.push(5); v1.push(6); //check if 3rd index is present in v2 let third : &i32 = &v2[2]; println! ("Third elemement = {}", third); ...
extern crate mustache; #[macro_use] extern crate serde_json; #[test] fn it_template() { let msg = mustache::compile_str("Hello, {{name}}!") .unwrap() .render_to_string(&json!({"name":"arete"})) .unwrap(); println!("{}", msg); assert_eq!("Hello, arete!", msg); }
#[derive(Debug, PartialEq, Eq)] pub enum Classification { Abundant, Perfect, Deficient, } pub fn classify(num: u64) -> Option<Classification> { if num == 0 { return None; } let mut sum = 0_u64; for i in 1..=(num / 2) { if num % i == 0 { sum += i; } } ...
// This file is part of tmx // Copyright 2017 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 required ...
use std::io::Write; use events::Event; use std::error::Error; use templates; pub struct PlainTextFormatter {} impl PlainTextFormatter { pub fn new() -> PlainTextFormatter { PlainTextFormatter{} } } impl super::WriteEvent for PlainTextFormatter { fn write_event(&self, event: &Event<'static>, to: &...
//! # Lock-free Bounded Non-Blocking Pub-Sub Queue //! //! This is a publish subscribe pattern queue, where the publisher is never blocked by //! slow subscribers. The side effect is that slow subscribers will miss messages. The intended //! use-case are high throughput streams where receiving the latest message is pri...
extern crate jobserver; use std::env; use std::io::prelude::*; use std::io::BufReader; use std::process::{Command, Stdio}; use std::sync::mpsc; use std::thread; use jobserver::Client; macro_rules! t { ($e:expr) => { match $e { Ok(e) => e, Err(e) => panic!("{} failed with {}", stri...
use rom::{Cartridge}; use ppu::{PpuInterface}; pub struct Memory { ram: [u8; 0x2000], cartridge: Cartridge, ppu_interface: PpuInterface, } impl Memory { pub fn new(cartridge: Cartridge) -> Memory { Memory { ram: [0; 0x2000], cartridge: cartridge, ppu_interfa...
//! Points with dimensions known at compile-time. #![allow(missing_docs)] // we allow missing to avoid having to document the point components. use std::marker::PhantomData; use std::mem; use std::slice::{Iter, IterMut}; use std::iter::{Iterator, FromIterator, IntoIterator}; use std::ops::{Add, Sub, Mul, Div, Neg, In...
use anchor_lang::prelude::*; declare_id!("Fg6PaFpoGXkYsidMpWTK6W2BeZ7FEfcYkg476zPFsLnS"); #[program] pub mod registration { use super::*; pub fn initialize(ctx: Context<Initialize>, price: u8) -> ProgramResult { let my_account = &mut ctx.accounts.my_account; my_account.price = price; ...
use crate::lightning::ln_serialization::ClaimableBalance; use crate::{lp_coinfind_or_err, CoinFindError, MmCoinEnum}; use common::{async_blocking, HttpStatusCode}; use http::StatusCode; use mm2_core::mm_ctx::MmArc; use mm2_err_handle::prelude::*; type ClaimableBalancesResult<T> = Result<T, MmError<ClaimableBalancesErr...
#[macro_use] extern crate lazy_static; extern crate nmea; extern crate libc; extern crate chrono; #[macro_use] extern crate log; #[cfg (not(target_os = "android"))] extern crate env_logger; #[cfg(target_os = "android")] extern crate android_logger; use std::sync::Mutex; use std::sync::{Once, ONCE_INIT}; use chrono::...
#[cfg(target_os = "macos")] fn main() { println!("cargo:rustc-link-lib=framework=JavaScriptCore"); } #[cfg(target_os = "linux")] fn main() { println!("cargo:rerun-if-env-changed=DOCS_RS"); if std::env::var("DOCS_RS").is_ok() { return; } let r = pkg_config::probe_library("javascriptcoregtk-4...
use crate::config::Config; use crate::query; use crate::repo_config::RepoConfig; use crate::util::{escape_markdown, extract_urls}; use failure::{format_err, Error, ResultExt}; use std::collections::{HashMap, HashSet, VecDeque}; use std::fmt; use std::fs::{self, File}; use std::io::Write; use std::mem; use std::path::Pa...
use dxgi::adapter::{Adapter4, IAdapter4}; use dxgi::enums::GpuPreference; use dxgi::factory::{Factory6, IFactory6}; fn main() { let factory: Factory6 = match dxgi::factory::create() { Ok(factory) => factory, Err(_) => { eprintln!("You can't have a Factory6 :("); return; ...
use tcod::Color; use crate::traits::Collidable; use super::palette::Palette; #[derive(Clone, Copy, Debug)] pub struct Tile { pub blocked: bool, pub explored: bool, pub transparent: bool, visible: bool, } impl Tile { pub fn empty() -> Self { Tile { blocked: false, ...
#![recursion_limit = "1024"] #![feature(try_from)] #[macro_use] extern crate error_chain; mod errors { error_chain! { foreign_links { Io(::std::io::Error); Reqwest(::reqwest::Error); Url(::reqwest::UrlError); } errors { SpecParseError(t : St...
//! Functions to download stuff into destinations use futures::{SinkExt, StreamExt}; use std::fmt::Write; use std::path::Path; use std::str::FromStr; use tokio::io::{AsyncReadExt, AsyncWriteExt}; use tokio::process::Command; #[derive(Debug)] pub struct GitCloneOptions { pub repo: String, pub revision: String, ...
use super::Float; use super::{WtOsc, WtOscData}; use wavetable::WavetableRef; use serde::{Serialize, Deserialize}; #[derive(Serialize, Deserialize, Clone, Copy, Debug)] pub enum OscType { Wavetable, Noise } impl OscType { pub fn from_int(param: usize) -> OscType { match param { 0 => O...
#![deny( // missing_docs, // not compatible with big_array trivial_casts, trivial_numeric_casts, unsafe_code, unused_import_braces, unused_qualifications, warnings )] pub mod erc20; pub mod bonding_contract; pub mod common; #[cfg(test)] mod tests { use super::bonding_con...
#[macro_use] extern crate rocket; use rocket::http::ContentType; use rocket::response::Content; use rocket::tungstenite::WsUpgrade; #[get("/echo", data = "<data>")] async fn echo(data: rocket::Data, upgrade: WsUpgrade<'_>) -> rocket::Response<'_> { tokio::spawn(async move { let ws_stream = rocket::tungste...
/// This is the module that has all the executor functions /// i.e. the functions that have the responsibility of parsing and executing functions. use std::sync::Arc; use anyhow::Result; use log::debug; use pyo3::prelude::*; use pyo3_asyncio::TaskLocals; use crate::types::{ function_info::FunctionInfo, request::R...
use crate::access_control; use serum_common::pack::*; use serum_common::program::invoke_token_transfer; use serum_registry_rewards::accounts::{vault, Instance}; use serum_registry_rewards::error::RewardsError; use solana_program::msg; use solana_sdk::account_info::{next_account_info, AccountInfo}; use solana_sdk::progr...
/// 6. /// /// 将一个给定字符串根据给定的行数,以从上往下、从左到右进行 Z 字形排列。 /// /// 比如输入字符串为 "LEETCODEISHIRING" 行数为 3 时,排列如下: /// /// L C I R /// E T O E S I I G /// E D H N /// 之后,你的输出需要从左往右逐行读取,产生出一个新的字符串,比如:"LCIRETOESIIGEDHN"。 /// /// 请你实现这个将字符串进行指定行数变换的函数: /// /// string convert(string s, int numRows); /// 示例 1: /// /// 输入: s ...
struct Solution; #[allow(dead_code)] impl Solution { pub fn length_of_longest_substring(s: String) -> i32 { let (mut h, mut t, mut res, mut set, len) = (0, 0, 0, std::collections::HashSet::new(), s.len()); let s = s.chars().collect::<Vec<char>>(); while h < len && t < len { ...
// Copyright (c) The Starcoin Core Contributors // SPDX-License-Identifier: Apache-2.0 use move_core_types::resolver::MoveResolver; use move_table_extension::TableResolver; use std::fmt::Debug; pub trait MoveResolverExt: MoveResolver<Err = Self::ExtError> + TableResolver { type ExtError: Debug; } impl<E: Debug, ...
use std::fmt; // 1. function pointer fn add_one(x: i32) -> i32 { x + 1 } fn do_twice(f: fn(i32) -> i32, x: i32) -> i32 { f(x) + f(x) } // `fn` is a type rather than a trait, so we specify `fn` as the parameter type directly // // rather than declaring a generic type parameter and one of `Fn` trait as a trait ...
// Copyright (c) The Starcoin Core Contributors // SPDX-License-Identifier: Apache-2.0 pub mod error; pub mod message; mod provider; mod rich_wallet; mod service; mod types; pub use provider::*; pub use rich_wallet::*; pub use service::*; pub use types::*; pub type AccountResult<T> = std::result::Result<T, error::Acco...
pub mod app; pub mod vban;
// 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 ...
//! OAuth module for the Fractal API. //! //! contains the required structs and enums for a typesafe OAuth with the API. use std::slice::Iter; use std::result::Result as StdResult; use std::io::Read; use hyper::header::Bearer; use hyper::method::Method; use hyper::header::{Headers, Authorization, Basic}; use chrono::...
//! Embedding matrix representations. use ndarray::{Array2, ArrayView2, ArrayViewMut2, CowArray, Ix1}; mod array; #[cfg(feature = "memmap")] pub use self::array::MmapArray; pub use self::array::NdArray; mod quantized; #[cfg(feature = "memmap")] pub use self::quantized::MmapQuantizedArray; pub use self::quantized::{Q...
// https://gamedevelopment.tutsplus.com/tutorials/how-to-use-bsp-trees-to-generate-game-maps--gamedev-12268 use rand::rngs::StdRng; use rand::Rng; use serde_json::from_str; use std::fs; use crate::level::Level; use crate::room::Room; use crate::tile::Tile; type RoomJson = Vec<Vec<Tile>>; fn load_rooms() -> std::io::...
//! //! # Send Request to Kafka server //! use std::net::SocketAddr; use std::io::Error as IoError; use std::io::ErrorKind; use log::{trace, debug}; use utils::generators::rand_correlation_id; use kf_socket::KfSocket; use kf_protocol::api::RequestMessage; use kf_protocol::api::Request; use crate::error::CliError; /...
extern crate triangle; use triangle::*; pub fn main() { println!("Triangle::build([4, 3, 4]), result: {:?}", Triangle::build([4, 3, 4])); let triangle = Triangle::build([10, 10, 10]).unwrap(); println!("Triangle::build([10, 10, 10]), result: {:?}", triangle); println!("Triangle::build([10, 10, 10]), is...
#![feature(test)] // These benchmarks can be run from the project root with: // > cargo bench --package mentat_tx_parser extern crate test; extern crate edn; extern crate mentat_tx_parser; use test::Bencher; use mentat_tx_parser::Tx; #[bench] fn bench_parse1(b: &mut Bencher) { let input = r#"[[:db/add 1 :test/v...
use intcode_computer::Computer; use num_derive::{FromPrimitive, ToPrimitive}; use num_traits::{FromPrimitive, ToPrimitive}; use std::cmp::{max, min}; use std::collections::{HashMap, HashSet, VecDeque}; use std::fmt; use std::io::Write; use std::thread::sleep; use std::time::Duration; const ROWS: usize = 1000; const CO...
use std::thread; use std::time::Duration; use futures::executor::ThreadPool; use std::io::Read; fn main() { let pool = ThreadPool::new().unwrap(); let task = async { let mut id = 0; for j in 1..6 { // let id = j * 10; id += 10; // async ブロックの外側にる変数を使う場合は ...
fn fat (n: u64) -> u64 { if (n == 0) { return 1; } return n*fat(n-1); } fn main() { let n = std::env::args().nth(1).and_then(|n| n.parse().ok()).unwrap_or(10); let f; f = fat(n); println!("Fatorial de {} é {}", n, f); }
use std::ops::{Deref, DerefMut}; use super::Opened; use crate::{codec::Context, util::format, AudioService, ChannelLayout}; pub struct Audio(pub Opened); impl Audio { pub fn sample_rate(&self) -> u32 { unsafe { (*self.as_ptr()).sample_rate as u32 } } pub fn channels(&self) -> u16 { unsafe { (*self.as_ptr())....
use buffer::Buffer; use buffer::BufferRef; use buffer::with_buffer; use common::num::Cast; use common::pretty; use huffman::instances::TEEWORLDS as HUFFMAN; use huffman; use std::cmp; use std::fmt; use warn::Ignore; use warn::Warn; pub const CHUNK_HEADER_SIZE: usize = 2; pub const CHUNK_HEADER_SIZE_VITAL: usize = 3; p...
// Copyright 2014 Google Inc. All rights reserved. // // 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...
use std::error::Error; use std::fs::File; use std::io::{Read, Seek, SeekFrom}; use std::path::PathBuf; use std::vec::Vec; use image::{ImageBuffer, Rgba, RgbaImage}; use super::directory::Asset; use super::utils::buf_to_le_u32; // Asset header: 10 bytes const HEADER_LEN: usize = 10; pub fn extract_img( res_file: ...
use failure::Error; use futures::{Async, Future, Poll, Stream}; use futures::sync::mpsc::{UnboundedReceiver}; use tokio::io; use xrl::{Client, ClientError, XiNotification}; use crate::core::Command; use crate::core::window::Window; pub enum CoreEvent { Notify(XiNotification), } pub struct Stadui { exit: bool...
use std::fs; use std::fs::File; use std::io; use std::error::Error; use std::io::Read; fn main() -> Result<(),Box<dyn Error>> { // recover able error // using Result<T,E> for recoverable errors { // file not found? report and retry } // un recover able error // using panic! macro that...
use ffi::*; use format::Format; use status::Status; use status::Status::{ InvalidStatus, Success }; use surface::Surface; /// Internally, this wraps a ```*mut cairo_surface_t``` pub struct ImageSurface { ptr : *mut cairo_surface_t, } impl ImageSurface { pub fn new(format : Format, width : i32, height : i32) -...
// Copyright 2019 WHTCORPS INC Project Authors. Licensed under Apache-2.0. //! Procedural macros used in the milevadb_query component; part of the interlock //! subsystem. //! //! For an overview of the interlock architecture, see the documentation on //! [edb/src/interlock](https://github.com/edb/edb/blob/master/src/...
use std::fs::File; use std::io::Read; use std::fmt; use std::error::Error; const BUFFER_SIZE: usize = 1024; pub struct BufferedReader{ file: File, buffer_lines: Vec<String>, unresolved_line: String, eof: bool } impl BufferedReader{ pub fn new(file_name: &str) -> Result<BufferedReader, IOError>{...