text
stringlengths
8
4.13M
use wasm_bindgen::prelude::*; use web_sys::{OffscreenCanvas, WebGlRenderingContext}; use crate::simulations::{Boid, FallingSand, Flock, GoL, Simulation}; // use crate::simulations::GoL; type GL = web_sys::WebGlRenderingContext; mod common_funcs; mod gl_setup; mod quadtree; mod rendering; mod shaders; mod simulations...
use std::sync::Arc; use eyre::Report; use rosu_pp::{ Beatmap as Map, CatchPP, CatchStars, ManiaPP, OsuPP, PerformanceAttributes, TaikoPP, }; use rosu_v2::prelude::{Beatmap, GameMode, GameMods, OsuError, Score, User}; use twilight_model::{ application::interaction::{application_command::CommandOptionValue, Appl...
use crate::codec::*; use crate::error::*; use crate::*; use crate::{SocketType, ZmqResult}; use async_trait::async_trait; use crossbeam::atomic::AtomicCell; use crossbeam::queue::SegQueue; use dashmap::DashMap; use futures::lock::Mutex; use futures::stream::FuturesUnordered; use futures_util::sink::SinkExt; use std::sy...
#[macro_use] mod utils; pub mod dl_cache; pub mod dynamic; pub mod elf; pub mod error; pub mod header; pub mod ld_so_cache; pub mod ldd; pub mod section; pub mod segment; pub mod strtab; pub mod types; pub use dynamic::{Dynamic, DynamicContent}; pub use elf::Elf; pub use error::Error; pub use header::Header; pub use s...
// Import hacspec and all needed definitions. use hacspec_lib::*; // Import chacha20 and poly1305 use hacspec_chacha20::*; use hacspec_poly1305::*; #[derive(Debug)] pub enum Error { InvalidTag, } pub type ChaChaPolyKey = ChaChaKey; pub type ChaChaPolyIV = ChaChaIV; pub type ByteSeqResult = Result<ByteSeq, Error>...
use super::*; pub struct TimTicketQueue { pub ticket_queue: Arc<Mutex<Vec<Ticket>>>, } pub struct TimScheduler { pub should_run: Arc<Mutex<Option<Uuid>>>, } #[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] pub enum SchedulerCommand { Start, Stop, } pub trait TicketQueue { fn add(&mut s...
#![warn( clippy::all, clippy::nursery, clippy::pedantic, missing_copy_implementations, missing_debug_implementations, rust_2018_idioms, unused_qualifications )] #![allow( clippy::doc_markdown, clippy::enum_glob_use, clippy::module_name_repetitions, clippy::must_use_candidate,...
// error-pattern: mismatched types enum a { A(int), } enum b { B(int), } fn main() { let x: a = A(0); alt x { B(y) { } } }
use color_eyre::Report; use reqwest::Client; use tracing::info; use tracing_subscriber::EnvFilter; pub const URL_1: &str = "https://fasterthanli.me/articles/whats-in-the-box"; pub const URL_2: &str = "https://fasterthanli.me/series/advent-of-code-2020/part-13"; #[tokio::main] async fn main() -> Result<(), Report> { ...
fn main(){ let a = "hi"; let b = a.to_string(); println!("{}", b); }
// Copyright 2021 The MWC 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 agreed to...
use crate::config::ApiList; use crate::equity::Equity; use serde_json::Value; use std::collections::HashMap; use std::error; use std::io; // Stores a HashMap of all the platforms and their JSON API pairings. // Fetcher is the object to interact with external API interfaces. #[derive(Debug)] pub struct Fetcher { //...
trait LiveBeing { fn create(name: &'static str) -> Self; fn name(&self) -> &'static str; fn talk(&self) { println!("{} can not talk", self.name()) } } #[derive(Debug)] struct Cat { name: &'static str, } impl LiveBeing for Cat { fn create(name: &'static str) -> Cat { ...
use deadpool_postgres::Client; pub async fn db_query<F>(client: &Client, mut read: F) where F: FnMut(&str), { // http://blog.cleverelephant.ca/2019/03/geojson.html let stmt = client .prepare( &"SELECT rowjsonb_to_geojson(to_jsonb(ne.admin_0_countries.*), 'wkb_geometry') \ FROM n...
use futures::executor::block_on; use rocket_contrib::json::Json; use rocket::{Route, State}; use crate::libs::database_client::DatabaseClient; use crate::libs::models::Podcast; use crate::libs::repositories::{insert_podcast, podcast_list, find_podcast_by_id}; use crate::libs::guards::AuthorizationGuard; #[get("/pod...
extern crate rustc_serialize; extern crate csv; extern crate clap; use clap::App; use clap::Arg; use csv::Writer; use rustc_serialize::json::Json; use std::fs::File; use std::cmp::Ordering::*; mod colony; use colony::Colony; type ColonySet = std::collections::HashMap<u32, Colony>; fn main() { let matches = App::...
mod audio_loading; mod info; mod websocket; mod utils; use actix_web::web; pub(super) fn config(cfg: &mut web::ServiceConfig) { audio_loading::scoped_config(cfg); info::scoped_config(cfg); websocket::scoped_config(cfg); }
//! Utility items use regex::Regex; use rocket::http::Status; use rocket::request::Request; use rocket::response::{self, Responder, Response}; use rocket_contrib::json::Json; use serde::Serialize; use std::fmt; /// Rgex pattern for converting special characters to spaces const TO_SPACE_REGEX: &str = r"(\.|-| )+"; //...
/* * 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 */ /// UsageCustomReportsPage : The object containing page total count. #[derive(Clone, Debug, PartialEq...
use super::physics_collider::PhysicsCollider; use ptgui::prelude::*; pub trait PhysicsBody: PhysicsCollider { fn try_fall<T>(&mut self, others: &[T]) where T: PhysicsCollider; fn try_move<T>(&mut self, deltas: Point, others: &[T]) where T: PhysicsCollider; fn move_pos(&mut self, de...
fn make_bins(limits: &Vec<usize>, data: &Vec<usize>) -> Vec<Vec<usize>> { let mut bins: Vec<Vec<usize>> = Vec::with_capacity(limits.len() + 1); for _ in 0..=limits.len() {bins.push(Vec::new());} limits.iter().enumerate().for_each(|(idx, limit)| { data.iter().for_each(|elem| { if i...
#[doc = "Register `RF%sR` reader"] pub type R = crate::R<RFR_SPEC>; #[doc = "Register `RF%sR` writer"] pub type W = crate::W<RFR_SPEC>; #[doc = "Field `FMP` reader - FMP0"] pub type FMP_R = crate::FieldReader; #[doc = "Field `FULL` reader - FULL0"] pub type FULL_R = crate::BitReader; #[doc = "Field `FULL` writer - FULL...
use quix::node::{NodeConfig, NodeController, Connect}; use actix::{SystemService, Message, Actor, Handler, Running}; use std::time::Duration; use quix::{Process}; use std::thread::JoinHandle; use quix::global::{Global, Set}; use quix::util::RpcMethod; use bytes::{Buf, BufMut}; use quix::process::DispatchError; use qui...
use azure_core::headers::CommonStorageResponseHeaders; use bytes::Bytes; use http::Response; use serde::de::DeserializeOwned; use std::convert::{TryFrom, TryInto}; #[derive(Debug, Clone)] pub struct GetEntityResponse<E> where E: DeserializeOwned, { pub common_storage_response_headers: CommonStorageResponseHead...
use std::collections::HashMap; use std::io::BufRead; fn parse_guard(line: &String, start: usize) -> i32 { let start = start + 1; let mut end = start; for (i, c) in line[start + 1..].chars().enumerate() { if !c.is_digit(10) { end = start + i + 1; break; } } li...
// Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution. // // 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>,...
use cpu::Cpu; pub struct TermGfx { } impl TermGfx { pub fn new() -> TermGfx { TermGfx { } } pub fn composite(&self, buffer: Vec<u8>) { for row in buffer.chunks(64) { println!("{}", ""); for byte in row.iter() { match *byte { 0x0 ...
mod parser; mod generator; pub use parser::SpecFieldType as FieldType; pub use generator::Generator as SerdeBuilder;
mod sprite; mod player; mod directions; use tetra::graphics::{self, Color, DrawParams, Texture}; use tetra::{Context, ContextBuilder, State, input}; use tetra::input::Key; use tetra::math::Vec2; use crate::sprite::SpriteSheet; use crate::player::Player; use crate::directions::{MoveDirection, TrunDirection}; struct G...
use std::process; use what_time::*; fn main() { // get command line args: let CmdLineArgs { config_path_or_url, name, } = get_cmd_line_args(); // read and parse config file: let config = get_config(&config_path_or_url).unwrap_or_else(|err| { println!("{}: {:?}", err, err); ...
use gotham::state::State; use hyper::server::Response; use hyper::StatusCode; use hyper::Uri; use hyper::header::Location; use state::AppConfig; use oauth; use errors::*; use gotham::middleware::session::SessionData; use gotham::state::FromState; pub fn handler(mut state: State) -> (State, Response) { let token_res ...
// q0169_majority_element struct Solution; use std::collections::HashMap; impl Solution { pub fn majority_element(nums: Vec<i32>) -> i32 { let mut map = HashMap::new(); let cpr = |c| { if nums.len() % 2 == 0 { c >= nums.len() / 2 } else { c >...
//use super::*; //use cgmath::Vector2; //use std::f64::INFINITY; // //type Subject = ImageWriter; // //mod write { // use super::*; // // #[test] // fn it_writes_the_image_to_a_file() { // let resolution = Vector2::new(20, 20); // // let image = Image::new(resolution); // let name = Name::...
use crate::Pred; use num_integer::Integer; std_prelude!(); #[derive(Clone, Copy, Debug, Default)] /// Accepts even integers. pub struct Even; #[derive(Clone, Copy, Debug, Default)] /// Accepts odd integers. pub struct Odd; impl<T: Integer> Pred<T> for Even { fn accept(t: &T) -> bool { t.is_even() } }...
use std::fmt::Debug; #[cfg(test)] pub fn assert_sorted_vec_eq<T>(a: &Vec<T>, b: &Vec<T>) where T: PartialEq + Ord + Clone + Debug, { let mut a: Vec<T> = (*a).clone(); let mut b: Vec<T> = (*b).clone(); a.sort(); b.sort(); assert_eq!(a, b) }
use std::fs; use std::io::Write; #[allow(dead_code)] pub fn write_text_to_file(path: String, text: &[u8]) -> std::io::Result<()> { let mut file = fs::File::create(path)?; file.write_all(text)?; Ok(()) }
#[doc = "Reader of register FREQA"] pub type R = crate::R<u32, super::FREQA>; #[doc = "Writer for register FREQA"] pub type W = crate::W<u32, super::FREQA>; #[doc = "Register FREQA `reset()`'s with value 0"] impl crate::ResetValue for super::FREQA { type Type = u32; #[inline(always)] fn reset_value() -> Sel...
use super::prelude::*; use glib::clone; use super::super::ui; fn connect_signals(state: &ui::State) { let about_menu_item: gtk::MenuItem = state.get_about_menu_item(); let about_dialog: gtk::AboutDialog = state.get_about_dialog(); about_menu_item.connect_activate(move |_| { about_dialog.run(); ...
use super::libs::tex_table::TexTable; use super::libs::webgl::WebGlRenderingContext; use crate::libs::random_id::U128Id; pub struct Idmap { depth_buffer: web_sys::WebGlRenderbuffer, screen_tex: (web_sys::WebGlTexture, U128Id), frame_buffer: web_sys::WebGlFramebuffer, } impl Idmap { pub fn new( ...
#[doc = "Register `SECCFGR1` reader"] pub type R = crate::R<SECCFGR1_SPEC>; #[doc = "Register `SECCFGR1` writer"] pub type W = crate::W<SECCFGR1_SPEC>; #[doc = "Field `TIM2SEC` reader - secure access mode for TIM2"] pub type TIM2SEC_R = crate::BitReader; #[doc = "Field `TIM2SEC` writer - secure access mode for TIM2"] p...
#[doc = r"Register block"] #[repr(C)] pub struct RegisterBlock { #[doc = "0x00 - IPCC Processor 1 control register"] pub ipcc_c1cr: IPCC_C1CR, #[doc = "0x04 - IPCC Processor 1 mask register"] pub ipcc_c1mr: IPCC_C1MR, #[doc = "0x08 - Reading this register will always return 0x0000 0000."] pub ip...
#[doc = r"Register block"] #[repr(C)] pub struct RegisterBlock { #[doc = "0x00 - Ethernet MMC control register"] pub mmccr: MMCCR, #[doc = "0x04 - Ethernet MMC receive interrupt register"] pub mmcrir: MMCRIR, #[doc = "0x08 - Ethernet MMC transmit interrupt register"] pub mmctir: MMCTIR, #[do...
//! Utilities for pinning #![no_std] #![warn(missing_docs, missing_debug_implementations, rust_2018_idioms)] #[macro_use] mod stack_pin; #[macro_use] mod projection; // Not public API. #[doc(hidden)] pub mod __private { pub use core::pin::Pin; }
use std::sync::atomic::{AtomicUsize, Ordering}; use std::time::Duration; // atomic duration in milli seconds #[derive(Debug)] pub struct AtomicDuration(AtomicUsize); impl AtomicDuration { pub fn new(dur: Option<Duration>) -> Self { let dur = match dur { None => 0, Some(d...
#![allow(dead_code)] mod controls; mod generator; mod render; use render::State; use winit::{ event, event_loop::{ControlFlow, EventLoop}, window::WindowBuilder, }; use iced_wgpu::{window::SwapChain, Primitive, Renderer, Settings, Target}; use iced_winit::{Cache, Clipboard, MouseCursor, Size, UserInterfa...
use crate::day9::{intcode_computer, parse_program}; use std::collections::HashMap; #[aoc_generator(day11, part1)] fn p1_generator(input: &str) -> Vec<i64> { parse_program(input) } #[derive(Debug)] pub enum Direction { Up, Down, Left, Right, } impl Direction { pub fn rotate_right(&self) -> Sel...
impl Solution { pub fn search_insert(nums: Vec<i32>, target: i32) -> i32 { for i in 0..nums.len() { if nums[i] >= target { return i as i32; } } nums.len() as i32 } }
use crate::compiler::InterpreterCompiler; use cranelift::prelude::*; pub struct AddStub; impl AddStub { pub fn generate( ic: &mut InterpreterCompiler<'_>, frame: Value, left: Value, right: Value, ) -> Value { let left_not_int = ic.create_block(); let right_not_...
// Copyright 2021 The Matrix.org Foundation C.I.C. // // 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 bevy::prelude::{Handle, Texture, TextureAtlas, Vec2}; use bevy::sprite::Rect; pub fn from_grid_with_offset( texture: Handle<Texture>, tile_size: Vec2, offset: Vec2, rows: usize, columns: usize, ) -> TextureAtlas { let mut sprites = Vec::new(); for y in 0..columns { for x in 0..rows { let r...
#[derive(Debug, Copy, Clone)] pub struct Point { pub x: i64, pub y: i64, pub z: i64, } impl Point { pub fn new(x: i64, y: i64, z: i64) -> Point { Point{x, y, z} } }
extern crate sdl2; use sdl2::event::Event; use sdl2::keyboard::Keycode; pub fn run(mut render: &sdl2::render::Renderer, mut event_pump: sdl2::EventPump) { println!("Game is running!"); 'running: loop { for event in event_pump.poll_iter() { match event { Event::Quit {..} | ...
use std::sync::Arc; use eyre::Report; use prometheus::core::Collector; use twilight_model::application::interaction::ApplicationCommand; use crate::{ commands::MyCommand, embeds::{CommandCounterEmbed, EmbedData}, pagination::{CommandCountPagination, Pagination}, util::{numbers, MessageExt}, BotRes...
#[doc = r" Value read from the register"] pub struct R { bits: u32, } #[doc = r" Value to write to the register"] pub struct W { bits: u32, } impl super::FIFOPTR { #[doc = r" Modifies the contents of the register"] #[inline] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'w m...
use {DocumentId, DocumentPath, Error, IntoDatabasePath, Revision, serde, std}; use document::WriteDocumentResponse; use transport::{JsonResponse, JsonResponseDecoder, Request, StatusCode, Transport}; pub struct CreateDocument<'a, T, P, C> where C: serde::Serialize + 'a, P: IntoDatabasePath, T: Transport + ...
/// CreateLabelOption options for creating a label #[derive(Debug, Default, Clone, Serialize, Deserialize)] pub struct CreateLabelOption { pub color: String, pub description: Option<String>, pub name: String, } impl CreateLabelOption { /// Create a builder for this object. #[inline] pub fn bui...
use super::{chunk_type::*, *}; use bytes::{Buf, BufMut, Bytes, BytesMut}; use std::fmt; ///chunkHeader represents a SCTP Chunk header, defined in https://tools.ietf.org/html/rfc4960#section-3.2 ///The figure below illustrates the field format for the chunks to be ///transmitted in the SCTP packet. Each chunk is form...
extern crate rand; use rand::Rng; use std::io; struct Hand { name: String, cards: Vec<u8> } impl Hand { fn new(name: String) -> Hand { let mut cards: Vec<u8> = Vec::new(); for _ in 0..2 { cards.push(rand::thread_rng().gen_range(2, 10)); } Hand { name, cards } ...
use std::collections::HashMap; use rocket::response::status; use rocket_contrib::Json; use db::project::{Project, ProjectWithStaff}; use db::session::Session; use db::staff::{NewStaff, Staff}; use db::student::Student; pub type ErrorResponse = status::Custom<Json<GenericMessage>>; pub type V1Response<T> = Result<Jso...
pub struct RailFence { rails: u32 } impl RailFence { pub fn generate_zig_zag(n: u32, length: u32) -> Vec<(u32, u32)> { let mut col_down = (0..n).collect::<Vec<u32>>(); let mut col_up = (1..n-1).collect::<Vec<u32>>(); let mut counter = 0; let mut output: Vec<(u32, u32)> = Vec::ne...
// This file is part of Substrate. // Copyright (C) 2017-2020 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 // // ht...
use anyhow::Result; use sqlx::{mysql::MySqlPool, MySql}; pub type DbPool = sqlx::Pool<MySql>; pub async fn new_pool(database_url: &str) -> Result<DbPool> { let pool = MySqlPool::connect(database_url).await?; Ok(pool) } #[cfg(feature = "db_test")] #[cfg(test)] mod test { use super::*; use crate::config...
// Packages: A Cargo feature that lets you build, test, and share crates // Crates: A tree of modules that produces a library or executable // Modules and use: Let you control the organization, scope, and privacy of paths // Paths: A way of naming an item, such as a struct, function, or module // use将路径带入范围的关键字;以及将pub...
#![deny(warnings)] extern crate extra; use std::env; use std::fs; use std::io::{stderr, stdout, Write}; use extra::option::OptionalExt; const MAN_PAGE: &'static str = /* @MANSTART{mv} */ r#" NAME mv - move files SYNOPSIS mv [ -h | --help ] SOURCE_FILE DESTINATION_FILE DESCRIPTION The mv utility renames...
use iced::{button, container, Background, Color, Vector}; const SURFACE: Color = Color::from_rgb( 0xF2 as f32 / 255.0, 0xF3 as f32 / 255.0, 0xF5 as f32 / 255.0, ); const ACTIVE: Color = Color::from_rgb( 0x72 as f32 / 255.0, 0x89 as f32 / 255.0, 0xDA as f32 / 255.0, ); const HOVERED: Color = C...
use fancy_slice::FancySlice; use crate::util; use crate::resources; use crate::chr0::*; use crate::mdl0::*; use crate::plt0::*; pub(crate) fn bres(data: FancySlice) -> Bres { let endian = data.u16_be(0x4); let version = data.u16_be(0x6); //let size = data.u32_be(0x8); let root_o...
#![deny(unsafe_code)] #![deny(rust_2018_idioms)] // NOTE only these two modules can and do contain unsafe code. #[allow(unsafe_code)] mod high; #[allow(unsafe_code)] mod indexing_str; #[forbid(unsafe_code)] pub mod generate; #[forbid(unsafe_code)] pub mod grammar; #[forbid(unsafe_code)] pub mod proc_macro; #[forbid(u...
#[macro_use(try_f)] extern crate susanoo; extern crate r2d2; extern crate r2d2_sqlite; extern crate rusqlite; use susanoo::{Context, Server, Response, AsyncResult}; use susanoo::contrib::hyper::{Get, StatusCode}; use susanoo::contrib::futures::{future, Future}; use susanoo::contrib::typemap::Key; use std::ops::Deref;...
pub use environment::Environment; pub use flappy::FlappyEnvironment; pub use jump::JumpEnvironment; mod environment; mod flappy; mod jump;
use std::env::Args; use rustybox::Function; pub fn binding() -> (&'static str, Function) { ("false", Box::new(false_fn)) } fn false_fn(_: Args) -> i32 { 1 }
#[doc = "Reader of register TIMEOUT_CTL"] pub type R = crate::R<u32, super::TIMEOUT_CTL>; #[doc = "Writer for register TIMEOUT_CTL"] pub type W = crate::W<u32, super::TIMEOUT_CTL>; #[doc = "Register TIMEOUT_CTL `reset()`'s with value 0xffff"] impl crate::ResetValue for super::TIMEOUT_CTL { type Type = u32; #[in...
use enumset::EnumSet; use crate::{ args, track::{Duration, Track}, }; fn command_line(line: &str) -> args::Command { let arguments = shell_words ::split(line) .expect("failed to shell parse test command line"); args ::parse(arguments) .expect("failed to parse test command line") } #[test] fn test_debu...
fn a(x: bool, y: bool) -> bool { if x && y { let a: bool = true; y || a } else { x && false } } fn b(x: bool, y: bool) -> i32 { let a: bool = a(x, y || false); let mut b: i32 = 0; if a && y { let a: bool = true; if y || a { b = b + 1; }...
use packed_secret_sharing::*; use packed_secret_sharing::packed::*; use rand::{thread_rng, Rng}; use criterion::{black_box, Bencher}; pub fn share_bench(bench: &mut Bencher, _i: &()) { let prime = 4610415792919412737u128; let root2 = 1266473570726112470u128; let root3 = 2230453091198852918u128; let mut...
#![no_std] #[allow( non_camel_case_types, non_snake_case, non_upper_case_globals, dead_code )] #[allow(clippy::all)] mod binding { include!(concat!(env!("OUT_DIR"), "/bindings.rs")); } mod blake2b; #[cfg(test)] extern crate std; pub use crate::blake2b::{blake2b, Blake2b, Blake2bBuilder};
mod table; mod table_theme; mod textstyle; mod width_control; pub use table::{Alignments, Table}; pub use table_theme::TableTheme; pub use textstyle::{Alignment, StyledString, TextStyle};
use bytes::Bytes; use rml_rtmp::sessions::StreamMetadata; pub enum RtmpInput { Media(Media), Metadata(StreamMetadata), } pub struct Media { pub media_type: MediaType, pub data: Bytes, pub timestamp: u32, pub can_be_dropped: bool, } pub enum MediaType { Video, Audio, }
#[macro_use] extern crate text_io; fn main() { let (i, f): (i32, f64); scan!("{}, {}", i, f); let a: u32 = read!("{}\n"); println!("{} {} enter and {} here", i + 11, f - 20.0, a + 10); }
use failure::Error; use futures::prelude::*; use futures::stream; use slog::Logger; use std::cell::Cell; use std::rc::Rc; use tokio_retry::{self, Retry, strategy::ExponentialBackoff}; use github::{GithubClient, PullRequest}; pub fn poll_notifications( client: GithubClient, logger: Logger, ) -> impl Stream<Ite...
#[macro_use] extern crate serde_json; #[macro_use] extern crate serde_derive; extern crate rmp_serde; extern crate byteorder; extern crate indy; #[macro_use] mod utils; use indy::did::Did; use indy::ErrorCode; use std::sync::mpsc::channel; use std::time::Duration; use utils::b58::{FromBase58}; use utils::constants::{ ...
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under both the MIT license found in the * LICENSE-MIT file in the root directory of this source tree and the Apache * License, Version 2.0 found in the LICENSE-APACHE file in the root directory * of this source tree. */ exter...
use fixed_hash::*; use impl_codec::impl_fixed_hash_codec; use impl_rlp::impl_fixed_hash_rlp; use impl_serde::impl_fixed_hash_serde; construct_fixed_hash! { pub struct H768(96); } impl_fixed_hash_rlp!(H768, 96); impl_fixed_hash_serde!(H768, 96); impl_fixed_hash_codec!(H768, 96);
use anyhow::{Context, Result}; use console::style; use log::*; use std::env; use std::io; use std::path::{Path, PathBuf}; use std::process; use structopt::{ clap::arg_enum, clap::crate_authors, clap::crate_description, clap::crate_version, clap::AppSettings, StructOpt, }; use uvm_cli::{options::ColorOption, set...
use { crate::{ client::{self, RequestType}, entities::*, Client, }, std::error::Error, }; /// Get the metadata of every song on listen.moe pub async fn get(listen_moe_client: &Client) -> Result<Vec<SongAPI>, Box<dyn Error>> { Ok(client::perform_request::<GeneralMessage>( ...
use crate::exactstreamer::ExactStreamer; use crate::gen::Generator; use cpal::traits::DeviceTrait; use cpal::traits::EventLoopTrait; use cpal::traits::HostTrait; use cpal::{Format, Host, SampleRate, StreamData, UnknownTypeOutputBuffer}; use parking_lot::RwLock; use std::sync::Arc; pub const GENERATOR_BUFFER_SIZE: usiz...
#[derive(Debug)] pub struct Args { pub file_name: String, } pub fn get_args() -> Result<Args, String> { let raw_args = std::env::args().collect::<Vec<_>>(); match &raw_args[..] { [_, file] => Ok(Args { file_name: file.to_string(), }), [_] => Err("Missing file argument"....
use domain_client_block_preprocessor::runtime_api::StateRootExtractor; use domain_client_block_preprocessor::xdm_verifier::verify_xdm; use sc_transaction_pool::error::Result as TxPoolResult; use sc_transaction_pool_api::error::Error as TxPoolError; use sc_transaction_pool_api::TransactionSource; use sp_api::ProvideRunt...
use async_trait::async_trait; use common::result::Result; use crate::domain::catalogue::Publication; #[async_trait] pub trait PublicationService: Sync + Send { async fn get_by_id(&self, id: &str) -> Result<Publication>; }
// Added as part the code review and testing // by ChainSafe Systems Aug 2021 use crate::cmix::{Scheduling, SoftwareHashes}; use super::*; use mock::*; use frame_support::{assert_noop, assert_ok}; type SoftwareHash = <mock::Test as frame_system::Config>::Hash; /////////////////////////////// // set_cmix_hashe...
#[allow(unused_imports)] use super::prelude::*; use super::intcode::IntcodeDevice; type Input = IntcodeDevice; pub fn input_generator(input: &str) -> Input { input.parse().expect("Error parsing the IntcodeDevice") } pub fn part1(input: &Input) -> i64 { let mut devices = (0..50).map(|ip| { let mut devi...
use crate::geometry::{Position, Rect, Size}; /// Defines the drawing bounds of an object. pub trait Bounds { /// Gets the object position. fn get_position(&self) -> Position; /// Gets the object size. fn get_size(&self) -> Size; // Gets bounds as a Rect. fn get_bounds(&self) -> Rect { ...
use crate::{error::ProcessingError, fuzzers, search::read_runs}; use indicatif::ParallelProgressIterator; use rayon::iter::{IntoParallelRefIterator, ParallelIterator}; use serde_json::Value; use std::{ fs::{read_dir, DirEntry, File}, path::{Path, PathBuf}, time::Instant, }; use url::Url; /// A separate str...
use std::fs::File; use std::io::Read; #[derive(PartialEq, Clone, Debug)] enum GridElement { Empty, Tree, } fn solve_part1(map: &[Vec<GridElement>]) -> usize { tree_in_slope(map, 3, 1) } fn solve_part2(map: &[Vec<GridElement>]) -> usize { tree_in_slope(map, 1, 1) * tree_in_slope(map, 3, 1) ...
pub mod protobuf_types; mod adler_read; mod adler_write; mod backup_format; mod bundle_format; mod encryption_key_info; mod file_format; mod header_format; mod index_format; mod instruction_format; mod protobuf_message; mod storage_info_format; pub use self::adler_read::AdlerRead; pub use self::adler_read::adler_veri...
use std::net::Ipv4Addr; use api::start_server; use shared::Settings; #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> { pretty_env_logger::init(); let settings = Settings { address: Ipv4Addr::new(0, 0, 0, 0), port: 8080, }; start_server(settings).await }
//! Halstead complexity metrics use std::collections::HashMap; use std::fmt::Write; use sqlparser::ast::*; use crate::visitor::{ Visitor, Acceptor }; /// Our definition of "operators" in SQL. #[derive(Clone, Debug, PartialEq, Eq, Hash)] enum Operator { /// A Common table Expression Cte, /// A table alias ...
use std; use std::sync::Arc; use warp; use warp::Filter; use super::Result; use crate::controller::{SimpleWishlistController, WishlistController}; use crate::reject::handle_rejection; macro_rules! reply_future { ($controller:ident, $method:ident) => {{ |controller: Arc<dyn $controller>| async move { ...
fn main() { proconio::input! { n: usize, x: i32, a: [i32; n], } let vec:Vec<String> = a.iter() .filter(|&e| e != &x) .cloned() .map(|x| x.to_string()) .collect(); print!("{}", vec.join(" ")); }
use crate::types::linalg::dimension::Dimension; use std::ops::{Add, Mul, Sub}; #[derive(Clone, PartialEq)] #[repr(C)] pub struct Matrix<T> { pub data: Vec<T>, pub dimension: Dimension, } impl Matrix<f32> { pub fn zero4() -> Matrix<f32> { Matrix::from_data(vec![0.; 16], Dimension::new(4, 4)) } ...
use crate::error_system::OsuKeyboardError; pub mod keyboard_processor; pub trait Processor { fn setup(&self) -> Result<(), OsuKeyboardError>; fn run(&self) -> Result<!, OsuKeyboardError>; }