text
stringlengths
8
4.13M
use std::convert::TryFrom; use shared::error; use shared::error::Error; #[derive(Debug, PartialEq, Clone)] enum RawTokenKind { ParenLeft, ParenRight, Dot, String, Quote, // Quasiquote Quasi, Comma, // ,@ SeqComma, // Identifiers and non-string literals. Stuff, } #[deri...
//! Parse the command line options. //! use clap::{App, Arg, ArgMatches, SubCommand}; use lib_goo::config::db::PasswordSource; use lib_goo::config::file_utils::set_app_location; use lib_goo::config::{db, ServerConfig}; const VERSION: &str = env!("CARGO_PKG_VERSION"); const DESCRIPTION: &str = env!["CARGO_PKG_DESCRIPTI...
use crate::issues::{Issue, IssueType, Severity}; use gtfs_structures::{Gtfs, Route, RouteType}; pub fn validate(gtfs: &Gtfs) -> Vec<Issue> { gtfs.routes .iter() .filter_map(|(_, route)| get_non_standard_route_type(route)) .map(|(route, route_type)| { Issue::new_with_obj(Severity...
use rand::Rng; use crate::vec3::Point3; const POINT_COUNT: usize = 256; #[derive(Clone, Debug, PartialEq)] pub struct Perlin { random_floats: Box<[f64]>, perm_x: Box<[usize]>, perm_y: Box<[usize]>, perm_z: Box<[usize]>, } impl Perlin { pub fn new() -> Self { Perlin::with_rng(rand::thread...
// Copyright (c) The Libra Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::hasher::{ HashValue,AccountStateBlobHasher, CryptoHash, CryptoHasher}; use hex; use crate::failure::prelude::*; use serde::{Deserialize, Serialize}; use std::{collections::BTreeMap, convert::TryFrom, fmt}; #[derive(Clone, E...
pub mod utils; use argparse::{ArgumentParser, Store, StoreTrue}; use pbr::{MultiBar, ProgressBar}; use smoltcp::socket::{SocketSet, UdpPacketMetadata, UdpSocket, UdpSocketBuffer}; // use smoltcp::iface::{InterfaceBuilder, NeighborCache, Routes}; use smoltcp::wire::IpEndpoint; use socket2::{Domain, Socket, Type}; use s...
//! This module provides tools and utilities for handling SIMPLE-TLV data as //! defined in [ISO7816-4][iso7816-4]. //! //! //! //! //! [iso7816-4]: https://www.iso.org/standard/54550.html //! use alloc::vec::Vec; use core::convert::TryFrom; use untrusted::{Input, Reader}; use crate::{Result, TlvError}; /// Tag for ...
impl Solution { pub fn running_sum(nums: Vec<i32>) -> Vec<i32> { let mut v: Vec<i32> = Vec::new(); let mut prev = 0; for num in nums.iter(){ prev += num; v.push(prev); } v } }
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //! Utilities to handle reusing connections. //! //! Creating a single new connection requires significant //! memory allocations (about 50-60 KB, according to some tests). //! Instead of allocating memory for ...
//! Collecting live statistics from an event stream. //! // standard library use std::fmt; use std::fmt::{Debug, Formatter}; // third party // local use crate::error::Result; use crate::stream::{Element, Handler, Meta, ResOpt, Stream}; use crate::{Event, Trace}; /// Count element types in an extensible event stream...
use crate::intcode::Intcode; pub fn part1(input: &str) -> Result<u64, String> { let mut intcode = input.parse::<Intcode>()?; intcode.input.push(1); intcode.run(); println!("Output: {:?}", intcode.output); intcode .output .pop() .ok_or_else(|| "No output.".to_string()) ...
use crate::{Action, FrameFlags, FrameHeader, FramePayload, FrameType, Varint}; #[derive(Debug)] pub struct AckFrame { pub stream_id: Varint, pub frame_id: Varint, pub payload: AckFramePayload, } impl AckFrame { pub fn new(stream_id: Varint, frame_id: Varint, payload: AckFramePayload) -> Self { ...
//! Command trait and helper functions. //! //! use crate::{ error::{ErrorCode, Result}, parser::{parameters::Parameters, response::ResponseUnit}, Context, Device, }; /// Marks the command as query only by creating a stub for [Command::meta]. /// /// ``` /// # use scpi::{cmd_qonly, tree::prelude::*}; /// ...
mod front_of_house { mod hosting { fn add_to_waitlist() {} fn seat_at_table() {} } mod serving { fn take_order() {} fn serve_order() {} fn take_payment() {} } } mod back_of_house { mod cooking { fn select_ingredients() {} fn cut_vegetable...
// Copyright (c) 2022 PHPER Framework Team // PHPER is licensed under Mulan PSL v2. // You can use this software according to the terms and conditions of the Mulan // PSL v2. You may obtain a copy of Mulan PSL v2 at: // http://license.coscl.org.cn/MulanPSL2 // THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WIT...
use core::{ fmt::{Display, Write}, time::Duration, }; use crate::rtc::RTC; use ssd1306::{displaysize::DisplaySize128x64, mode::TerminalMode, prelude::I2CInterface}; use stm32f3_discovery::stm32f3xx_hal::{ delay::Delay, gpio::{ gpiob::{PB6, PB7}, AF4, }, i2c::I2c, pac::I2C1, ...
const DAY_9: &str = include_str!("resources/9a.txt"); use crate::intcode::{str_to_ints, RunResult, VM}; pub fn a() { let code = str_to_ints(DAY_9); let mut vm = VM::new(&code); vm.give_input(1); let run_result = vm.run(); assert_eq!(run_result, RunResult::Stopped); let outputs = vm.get_all_...
use std::fs; use sol6::{calc_checksum, calc_transfers}; #[cfg(test)] mod tests { use super::*; #[test] fn test() { let file_string = fs::read_to_string("test.txt").unwrap(); let file_string = file_string.trim(); let lines: Vec<&str> = file_string.split("\n").collect(); le...
#![allow(clippy::needless_range_loop)] use crate::utils::HasLen; use num::traits::{float::Float, identities::zero}; use std::marker::Copy; use std::ops::IndexMut; pub fn eval<T, V>(x: T, p: &V) -> T where T: Float + Copy, V: Clone + IndexMut<usize, Output = T> + HasLen, { let mut result = zero::<T>(); ...
mod utils; use wasm_bindgen::prelude::*; use std::collections::HashSet; // When the `wee_alloc` feature is enabled, use `wee_alloc` as the global // allocator. #[cfg(feature = "wee_alloc")] #[global_allocator] static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT; #[derive(Debug, Copy, Clone, Eq, PartialEq,...
use zi::Colour; /// Represents a base16 theme. /// /// Colours base00 to base07 are typically variations of a shade and run from /// darkest to lightest. These colours are used for foreground and background, /// status bars, line highlighting and such. Colours base08 to base0F are /// typically individual colours used...
use bitvec::prelude::*; use std::cell::RefCell; use std::cmp::Ordering; use std::collections::BinaryHeap; use std::collections::HashMap; use std::error::Error; use std::fs::File; use std::io; use std::io::prelude::*; use std::path::Path; use std::rc::Rc; #[derive(Clone, Eq, PartialEq)] pub enum Node { Nil, Tre...
use super::PutBack; use crate::stream::{Context, Contexted}; use crate::token::Token; use crate::Result; #[derive(Debug, Clone, PartialEq, Eq)] pub struct Constructor<I>(I, Vec<Token>); impl<I> Constructor<I> { pub fn new(iter: I) -> Self { Constructor(iter, vec![]) } } impl<I: Iterator<Item=Result<Token>>> PutB...
#[macro_use] extern crate clap; #[macro_use] extern crate log; use clap::ArgMatches; use lal::{self, *}; use std::{env::current_dir, ops::Deref, path::Path, process}; fn result_exit<T>(name: &str, x: LalResult<T>) { let _ = x.map_err(|e| { println!(); // add a separator error!("{} error: {}", name...
use std::fs; fn star1((min, max, c, s) : (usize, usize, char, &str)) -> bool { let o = s.chars().filter(|x| *x == c).count(); o <= max && o >= min } fn star2((min, max, c, s) : (usize, usize, char, &str)) -> bool { (s.chars().nth(min-1).unwrap() == c) ^ (s.chars().nth(max-1).unwrap() == c) } fn convert(s...
#[macro_use] extern crate conrod; extern crate conrod_derive; extern crate audioengine; mod event_loop; mod types; mod ui; #[allow(unused_imports)] use audioengine::types::KeyAction; #[allow(unused_imports)] use ui::Ui; #[allow(unused_imports)] use std::f64::consts::PI; use std::sync::mpsc::channel; #[derive(Cop...
extern crate rand; extern crate sha3; use rand::{CryptoRng, RngCore}; use crate::constants::{ BarrettRedc_FM_k, BarrettRedc_FM_u, BarrettRedc_FM_v, BigNumBits, CurveOrder, Ell, FieldElement_SIZE, FieldModulus, DNLEN, }; use crate::types::{BigNum, DoubleBigNum, FP}; use amcl::hmac; use amcl::rand::RAND; use s...
#[repr(C)] pub struct TaskContext { ra: usize, s: [usize; 12], } impl TaskContext { pub fn goto_restore() -> Self { extern "C" { fn __restore(); } Self { ra: __restore as usize, s: [0; 12], } } }
struct Solution; impl Solution { fn triangle_number(mut nums: Vec<i32>) -> i32 { let mut res = 0; let n = nums.len(); nums.sort_unstable(); for i in (2..n).rev() { let mut l = 0; let mut r = i - 1; while l < r { if nums[l] + nums[r...
extern crate cryptolib; use cryptolib::convert::Buf; use cryptolib::xor; fn main() { let hexstr = "1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736"; let bytes: Vec<u8> = Buf::from_hex(hexstr).bytes().to_vec(); let decoded = xor::decrypt_xor_byte(&bytes).1; println!("Similarity: {}"...
pub mod asciiboard; pub mod bitboard; pub mod gm; pub mod player; pub mod rand; pub mod util; /// Height of board. pub const H: usize = 8; /// Width of board. pub const W: usize = 8;
use crate::{get_attr_meta, CompileError, IdentCtx, MacroAttr, UnnamedInnerField}; use itertools::Itertools; use proc_macro2::{Ident, TokenStream as TokenStream2}; use quote::quote; use syn::Meta::Path; use syn::{NestedMeta, Variant}; impl CompileError { /// This error constructor is involved to be used on `EnumFro...
use crate::parse::NomParse; use std::{io, ops::Range}; use nom::{bytes::complete as bytes, combinator as comb, sequence, IResult}; fn parse_range(s: &str) -> IResult<&str, Range<u32>> { comb::map( sequence::separated_pair(u32::nom_parse, bytes::tag("-"), u32::nom_parse), |(least, most)| least..mo...
#[cfg(test)] mod tests { use super::super::common::*; use hyper::status::StatusCode; use serde_json; #[derive(Deserialize)] struct Configuration { locales: Vec<String>, } #[test] fn test_get_configuration_without_token() { let (response, content) = get("/api/v1/configu...
use image::DynamicImage; pub mod resize; pub mod utils; pub fn resize( raw: Vec<u8>, origin_width: u32, origin_height: u32, dist_width: u32, dist_height: u32, ) -> DynamicImage { resize::resize( utils::load_image_by_image_data(raw, origin_width, origin_height), origin_width, ...
use rand::prelude::*; pub struct VM { // Memory memory: [u8; 4096], // Stack stack: [u16; 16], stack_pointer: u8, // Program counter program_counter: u16, // Registers registers: [u8; 16], index_register: u16, // Graphics framebuffer: Framebuffer, // Timers ...
#![crate_type = "dylib"] #![feature(quote, plugin_registrar, rustc_private)] extern crate rustc_plugin; extern crate syntax; extern crate regex; use syntax::ast; use syntax::codemap; use syntax::print; use syntax::ext::base::{ExtCtxt, MacResult, DummyResult}; use syntax::parse::token; use std::ops::Deref; use rustc_pl...
//! A collection of resources to use with the api use serde::{de::DeserializeOwned, Deserialize, Serialize}; pub mod account_alert; pub mod advertiser; mod any_resource; pub mod authenticate; pub mod campaign; pub mod common; pub mod creative; pub mod creative_line_item; pub mod line_item; pub mod view; pub mod view_l...
use thiserror::Error; /// Errors that can occur during caching. #[derive(Error, Debug)] pub enum Error { /// Arises when the resource looks like a local file but it doesn't exist. #[error("Treated resource as local file, but file does not exist ({0})")] ResourceNotFound(String), /// Arises when the re...
use std::thread; use std::sync::mpsc; use youtube_dl::YoutubeDl; pub async fn fetch_audio_url(url: String) -> Result<String, ()> { let (tx, rx) = mpsc::channel(); thread::spawn(move || { let ytdl = YoutubeDl::new(&url) .socket_timeout("15") .run() .unwrap(); ...
use crate::error::Result; use crate::io::{BufExt, BufMutExt, Decode, Encode}; use sqlx_core::bytes::{Buf, BufMut, Bytes}; use std::ops::Deref; /// The same structure is sent for both `CopyInResponse` and `CopyOutResponse` pub struct CopyResponse { pub format: i8, pub num_columns: i16, pub format_codes: Vec...
use std::str; use std::fmt; pub struct Radix10Error { pub message: String } impl fmt::Display for Radix10Error { fn fmt(&self, f: &mut fmt::Formatter ) -> fmt::Result { write!(f, "Error in Radix10 {} " , self.message) } } impl fmt::Debug for Radix10Error { fn fmt(&self, f: &mut fmt::Formatter )...
mod sys; pub mod device; pub mod tokio; pub use self::device::{Device, create}; #[cfg(test)] mod tests;
use sqlx::PgPool; use uuid::Uuid; use crate::project::Project; use super::error::DatabaseError; #[derive(Debug, sqlx::FromRow)] pub struct User { pub id: Uuid, pub username: String, pub password: String, pub email: String, } impl User { pub async fn create(pool: &PgPool, username: String, passw...
use crate::vec::*; use crate::ray::*; use crate::hittable::*; use crate::material::*; #[derive(Clone, Copy)] pub struct Metallic{ albedo: Color, fuzz: f64, } impl Metallic{ pub fn new(albedo: Color, fuzz: f64) -> Metallic { Metallic { albedo: albedo, fuzz: fuzz.clamp(0.0,1.0)...
extern crate hyper; extern crate inth_oauth2; extern crate libc; extern crate log; extern crate serde_json; extern crate yup_oauth2; use self::inth_oauth2::token::Token; use common; use std; use std::error::Error; use std::sync; use std::thread; pub use self::yup_oauth2::GetToken; pub type GoogleToken = inth_oauth2:...
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 use crate::{ callbacks::VerifyHostNameCallback, config::*, connection, enums::Blinding, security, testing::s2n_tls::Harness, }; use alloc::{collections::VecDeque, sync::Arc}; use bytes::Bytes; use core:...
use std::io::{BufRead, BufReader, BufWriter, Write}; use std::net::TcpStream; use std::str::SplitWhitespace; use crate::game::base::{Color, GameResult}; use crate::game::square::Square; use crate::message::ServerMessage; pub struct Client { reader: BufReader<TcpStream>, writer: BufWriter<TcpStream>, } impl C...
//! RIFF WAV Chunks. //! //! # Key //! - **Required** - Count must be exactly one. //! - **Optional** - Count must be exactly one or zero. //! - **Multiple** - Count can be any number, including zero. //! //! # Order //! The RIFF WAV chunk order must be as follows: //! - **Required**: Constant RIFF header (abstracted ...
#![feature(test)] use std::net::{TcpStream, UdpSocket}; use std::sync::{Arc, Mutex}; use std::thread; use std::time::Duration; mod aggregator; mod config; mod statsd; fn main() { let cfg = config::Config::load("config.toml").unwrap(); let mut carbon = TcpStream::connect(cfg.carbon_addr).unwrap(); let mu...
// 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 ...
pub use self::album::{Album, AlbumId, AlbumKind, NewAlbum}; pub use self::album_name::{AlbumName, AlbumNameId, NewAlbumName}; pub use self::artist::{Artist, ArtistId, ArtistKind, NewArtist}; pub use self::artist_credit::{ArtistCredit, ArtistCreditId, NewArtistCredit}; pub use self::artist_credit_name::{ArtistCreditName...
use std::fmt::{Debug, Formatter}; use anyhow::{anyhow, Result}; use daggy::{Dag, NodeIndex, Walker}; use rmp_serde::{decode, encode}; use serde::{Deserialize, Serialize}; use sled::Db; use crate::network::{Hash, Transaction}; fn walk_recursive<T>( dag: &Dag<Transaction, Transaction>, idx: NodeIndex<u32>, ...
mod s_render; mod shared; mod chunk; mod block; pub use self:: { s_render::*, shared::*, chunk::*, block::*, };
use unqlite::{UnQLite, KV}; use chrono::{DateTime, Utc}; use super::linggle; lazy_static! { static ref TOKEN_CACHED: Option<linggle::CSRF> = get_csrf_token(); static ref DB: UnQLite = UnQLite::create(db_path()); } fn db_path() -> String { let mut path = dirs::home_dir().unwrap(); path.push(".linggle")...
use iron::modifier::Modifier; use iron::prelude::*; use iron::AfterMiddleware; /// Applies a modifier to every request. pub struct ModifyWith<M> { modifier: M, } impl<M> ModifyWith<M> { pub fn new(modifier: M) -> ModifyWith<M> { ModifyWith { modifier } } } impl<M> AfterMiddleware for ModifyWith<M...
mod common; use common::filled_project; fn assert_changed(expected: Vec<&str>, execution: rit::Execution) { match execution { rit::Execution::Status(res) => { let names: Vec<String> = res .modified .iter() .map(|entry| format!("{}", entry)) ...
pub mod mapped; pub use mapped::*;
// //! Copyright 2020 Alibaba Group Holding Limited. //! //! Licensed under the Apache License, Version 2.0 (the "License"); //! you may not use this file except in compliance with the License. //! You may obtain a copy of the License at //! //! http://www.apache.org/licenses/LICENSE-2.0 //! //! Unless required by a...
use futures::stream::{SplitSink, SplitStream}; use futures::{SinkExt, StreamExt}; use hyper::http::request::Parts; use hyper::http::Extensions; use hyper::upgrade::Upgraded; use screw_components::dyn_fn::{AsDynFn, DFn}; use screw_components::dyn_result::{DError, DResult}; use serde::{Deserialize, Serialize}; use std::f...
//! Functionality for evaluating *Breakpad //! [RPN](https://en.wikipedia.org/wiki/Reverse_Polish_notation) expressions*. //! //! These expressions are defined by the following //! [BNF](https://en.wikipedia.org/wiki/Backus%E2%80%93Naur_form) specification: //! ```text //! <rule> ::= <identifier>: <expr> //! <as...
use std::path::PathBuf; #[derive(Debug)] pub struct Source { pub source: String, pub kind: SourceKind, } #[derive(Debug)] pub enum SourceKind { File { relative_path: PathBuf }, Raw, }
use std::collections::BTreeMap; use num::integer::sqrt; use proconio::{fastout, input}; fn prime_factor(mut n: u128) -> BTreeMap<u128, u128> { let mut fs = BTreeMap::new(); let mut count = 0; while n % 2 == 0 { count += 1; n /= 2; } if count > 0 { fs.insert(2, count); ...
fn getline() -> String{ let mut __ret=String::new(); std::io::stdin().read_line(&mut __ret).ok(); return __ret; } fn main() { let mut bs: Vec<usize> = getline().trim().split(' ').map(|x| x.parse().unwrap()).collect(); bs.sort(); let mut res = 10; for (i, b) in bs.into_iter().enumerate() { if b != i + 1 { ...
#[doc = "Reader of register PIDR0"] pub type R = crate::R<u32, super::PIDR0>; #[doc = "Bits\\[7:0\\] of the 12-bit part number of the component. The designer of the component assigns this part number\n\nValue on reset: 33"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum PART_0_A { #[doc = "33: Indicates bits\\[7...
extern crate rusttype; use img_buffer::{ImgBuffer, ColorRGBA}; use self::rusttype::{ScaledGlyph}; #[derive(Debug, Clone, Copy, Eq, PartialEq)] pub enum TextAlignHorizontal { Left, Right, Center, Justify, } #[derive(Debug)] pub enum FormatChunks { Chunk(FormatChunk), String(String), } #[derive(Debug)] pub st...
//! # Unique Assets Interface //! //! This trait describes an abstraction over a set of unique assets, also known as non-fungible //! tokens (NFTs). //! //! ## Overview //! //! Unique assets have an owner, identified by an account ID, and are defined by a common set of //! attributes (the asset info type). An asset ID ...
#[macro_use] extern crate log; extern crate env_logger; extern crate futures; extern crate grpc; mod test_misc; use grpc::*; use grpc::rt::*; use test_misc::*; fn echo_fn(_: RequestOptions, req: String) -> SingleResponse<String> { SingleResponse::completed(req) } fn reverse_fn(_: RequestOptions, req: String)...
use lib::logger::{ErrorType, LoggerInner}; use lib::sourcemap::SourceMapInner; use lib::typecheck::TypeCheckModule; use std::path; use std::rc::Rc; macro_rules! set_up_typecheck { ($code: expr) => {{ let filename = path::PathBuf::from("this_is_another_filename_test.fl"); let sourcemap = SourceMapI...
pub mod reverse_or_rotate; pub mod count_bits; pub mod good_vs_evil; pub mod buying_a_car; pub mod decode_the_morse_code;
#![allow(unstable)] use std::os; use std::str::FromStr; mod raiden; fn print_usage() { println!("Usage:"); println!(" raiden split [file] [disks]"); println!(" raiden merge [file] [disks]"); } macro_rules! try_arg_parse( ($arg:ident, $err:expr) => (match FromStr::from_str($arg.as_slice()) { ...
fn main() { println!("David Cameron!") }
use crate::error::Error; use flate2::read::GzDecoder; use std::fs::{self, File}; use std::path::Path; use tempfile::tempdir_in; /// Supported archive types. pub(crate) enum ArchiveFormat { TarGz, Zip, } impl ArchiveFormat { /// Parse archive type from resource extension. pub(crate) fn parse_from_exten...
use crate::connection::ConnectOptions; use crate::error::Error; use crate::mssql::{MssqlConnectOptions, MssqlConnection}; use futures_core::future::BoxFuture; impl ConnectOptions for MssqlConnectOptions { type Connection = MssqlConnection; fn connect(&self) -> BoxFuture<'_, Result<Self::Connection, Error>> ...
use serde::Deserialize; use std::{future::Future, pin::Pin, sync::Arc}; use tokio::{ self, sync::{broadcast, mpsc}, }; use crate::{ dataflow::{ operator::{OperatorConfig, Source}, stream::WriteStreamT, Data, Message, Timestamp, WriteStream, }, node::{ lattice::Execut...
pub use self::meme::MemePlugin; pub use self::viper::ViperPlugin; mod meme; mod viper; /// All plugins must implement the `Plugin` trait. A plugin is a user defined /// bot function that handles certain messages it receives. pub trait Plugin: Send + ::std::fmt::Debug { /// Creates a new `Plugin` in a `Box` contai...
use anyhow::bail; use indicatif::{ProgressBar, ProgressStyle}; use rayon::prelude::*; use std::{ fs::File, io::{BufRead, BufReader}, path::PathBuf, time::SystemTime, }; pub struct CmdBatchExecution { name: String, file_path: PathBuf, batch_size: usize, } struct ExecutionResult { succee...
use crate::consts::consts::*; use crate::bot_req::tg_req::*; use serde_json::{Result, Value}; use crate::consts::classes::*; pub async fn start_command(res:TgJsonData<'_>){ match res.getParams() { Some(vec) => { println!("Параметры пригли {}", vec.len()); start_with_paramet...
use external_crate::get_included_str; #[test] fn test_lib_with_include() { assert_eq!(get_included_str(), "I love veggies!\n") }
fn do_twice<F>(mut func: F) where F: FnMut() { func(); func(); } fn main() { let mut x: usize = 1; let add_two_to_x = || x += 2; do_twice(add_two_to_x); assert_eq!(x, 5); }
// This file is part of Substrate. // Copyright (C) Parity Technologies (UK) Ltd. // SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 // This program 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 Softwa...
pub fn build_proverb(list: &[&str]) -> String { if list.is_empty() { return String::new(); } let mut proverb: String = list .iter() .zip(list.iter().skip(1)) .map(|(want, lost)| format!("For want of a {} the {} was lost.\n", want, lost)) .collect(); proverb.push...
mod ball_system; mod paddle; pub use self::ball_system::BallSystem; pub use self::paddle::PaddleSystem;
use crate::controller::il0371::*; use crate::controller::display_connector::Result; #[derive(Debug)] pub enum DisplayError { } pub trait EPaperDisplay { fn init(&mut self) -> Result<()>; fn push_image_with<F>(&mut self, source: F) -> Result<()> where F: Fn(u32, u32) -> u8; fn clear(&mut self) -> Result<(...
use std::str::FromStr; use structopt::StructOpt; #[derive(Debug, StructOpt)] pub enum Command { /// Write the default YAML configuration to the configuration directory InstallConfiguration, } #[derive(Debug)] pub enum Format { Standard, Csv, Json, } impl FromStr for Format { type Err = String...
mod config; mod errors; use config::{Config, Ip, ProviderMode, TwoDNSConfig, UpdateConfig}; use errors::*; use clap::{App, Arg}; use env_logger; use env_logger::Env; use log::*; use rand::Rng; use std::collections::HashMap; use std::iter::Cycle; use std::path::PathBuf; use std::thread; use std::time::Duration; fn ma...
// Copyright 2020 Parity Technologies // // 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. This file may not be copied, modified, or distributed // except accor...
use super::*; use super::chunk::*; use super::user_space_vm::USER_SPACE_VM_MANAGER; use super::vm_area::VMArea; use super::vm_perms::VMPerms; use super::vm_util::{ FileBacked, VMInitializer, VMMapAddr, VMMapOptions, VMMapOptionsBuilder, VMRemapOptions, }; use crate::config; use crate::ipc::SHM_MANAGER; use crate::...
use crate::oops::class::Class; use crate::runtime::thread::JavaThread; use std::cell::RefCell; use std::rc::Rc; pub fn init_class(thread: Rc<RefCell<JavaThread>>, class: Rc<RefCell<Class>>) { (*class).borrow_mut().set_initialized(); schedule_clinit(thread.clone(), class.clone()); init_super_class(thread, c...
use std::borrow::{Borrow, ToOwned}; use std::fmt; use std::fmt::{Display, Formatter}; use crate::symbol_table::Symbol; #[derive(Debug, PartialEq)] pub struct KnownPos<'arena> { pub file: Symbol<'arena>, pub line: usize, pub column: usize, } impl Display for KnownPos<'_> { fn fmt(&self, f: &mut Format...
/** * [1948] Delete Duplicate Folders in System * * Due to a bug, there are many duplicate folders in a file system. You are given a 2D array paths, where paths[i] is an array representing an absolute path to the ith folder in the file system. For example, ["one", "two", "three"] represents the path "/one/two/thre...
use web_sys::MouseEvent; use yew::prelude::*; use crate::{resources::*, ECS}; pub(crate) struct NewGameView { model: ECS, } pub(crate) struct DiedView { model: ECS, } #[derive(Clone, Properties)] pub(crate) struct EcsProps { pub(crate) ecs: ECS, } #[derive(Copy, Clone)] pub(crate) enum NoMsg {} #[deri...
use std::sync::{Arc, RwLock}; use tokio::sync::{mpsc, watch}; use tonic::{transport::Server, Request, Response, Status}; use uuid::Uuid; use oxydoro::oxydoro_server::{Oxydoro, OxydoroServer}; use oxydoro::{ CreateTaskReply, CreateTaskRequest, GetAllTasksReply, GetAllTasksRequest, SubscribeToTaskUpdatesReply, S...
use futures::prelude::*; use std::marker::Unpin; use crate::impl_packet; use crate::packets::Packet; use crate::stream::ReadExtension; use crate::types::{self, Send, Size}; use anyhow::{anyhow, ensure, Result}; use serde::Serialize; use serde_json::json; pub struct StatusRequest {} impl StatusRequest { pub cons...
#[doc = "Writer for register PROFILINGCLEAR"] pub type W = crate::W<u32, super::PROFILINGCLEAR>; #[doc = "Register PROFILINGCLEAR `reset()`'s with value 0"] impl crate::ResetValue for super::PROFILINGCLEAR { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Clear...
#![allow(unused)] use std::boxed::Box; fn main() { copy_type(); non_copy_type(); } fn copy_type() { let the_tuple = (1, 2, 3); // Elements are copied out of the tuple let (x, y, z) = the_tuple; // Can use the tuple again let (x, y, z) = the_tuple; } fn non_copy_type() { let the_tup...
#![feature(drain_filter)] mod sfu; mod metrics; mod storage; mod server; use clap::Clap; use native_tls::{Identity, TlsAcceptor, TlsStream}; use influx_db_client::UdpClient; use std::net::{TcpListener, TcpStream}; use std::io::Read; use std::fs::File; #[derive(Clap)] #[clap(version = "1.0")] struct Options { #[...
use ::ShipTypeId; #[derive(Clone, Debug, PartialEq)] pub struct Cell { ship_type_id: Option<ShipTypeId>, shot: bool, } impl Cell { pub fn new() -> Self { Cell { ship_type_id: None, shot: false, } } pub fn shoot(&mut self) { self.shot = true; } ...
struct Solution; use std::collections::HashMap; impl Solution { fn str_2_hs(s: &str) -> HashMap<char, i32> { let mut hs: HashMap<char, i32> = HashMap::new(); for c in s.chars() { *hs.entry(c).or_default() += 1; } hs } fn count_characters(words: Vec<String>, cha...
/// Utilities for formatting the spouting frog. use itertools::Itertools; use textwrap::Wrapper; /// Return a string with a frog spouting the given `text` in a speech bubble. The speech /// text will be wrapped to the current terminal width. Distinct paragraphs are supported and /// can be specified by inserting newl...