text
stringlengths
8
4.13M
use nom::{bytes::complete::tag, IResult}; use std::fmt; #[derive(Debug)] pub enum FileType { BUILDER012, //monomakh-SAPR 2016 BUILDER011, //monomakh-SAPR 2013 CHARGE37, //monomakh 4.5 ERROR, //another title } impl fmt::Display for FileType { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Resu...
use crate::controller::migrate::Migration; use crate::startup::Event; use dataflow::prelude::*; use futures::try_ready; use noria::consensus::Authority; use noria::prelude::*; use noria::SyncControllerHandle; use std::collections::HashMap; use std::ops::{Deref, DerefMut}; use std::sync::Arc; use stream_cancel::Trigger;...
use ic_cdk::api::call::CallResult; use ic_cdk::call; use ic_cdk::export::candid::Principal; use crate::types::{ BurnRequest, DequeueRecurrentTaskRequest, DequeueRecurrentTaskResponse, GetBalanceOfRequest, GetBalanceOfResponse, GetControllersResponse, GetInfoResponse, GetRecurrentMintTasksResponse, GetRecur...
use crate::SPEED; use crate::Input; use crate::{math, DrawCall}; use crate::{Vector2, Vector3, GenericObject, ObjectData, Bullet}; const WEAPON_COOLDOWN: f64 = 0.06; #[derive(Serialize, Deserialize, PartialEq, Debug, Clone)] pub struct Character { pub data: ObjectData, weapon_cooldown: f64, } impl Character { ...
use std::collections::HashMap; use serde::{Deserialize, Deserializer}; use serde::de::Error; use crate::ident::Identifier; use crate::types::{Direction, DisplayTransformation, Vec3}; #[derive(Clone, Debug, Deserialize)] pub struct Model { pub parent: Option<Identifier>, pub ambientocclusion: Option<bool>, ...
// Copyright 2019 The vault713 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 a...
pub mod bitboard; pub mod ffi; pub mod game; pub mod test_utils;
use rand::prelude::*; pub fn get_one_gaussion_by_box_muller() -> f64 { let mut x: f64; let mut y: f64; let mut rng = thread_rng(); let mut size_squared: f64; loop { x = 2.0 * rng.gen::<f64>() - 1.0; y = 2.0 * rng.gen::<f64>() - 1.0; size_squared = x * x + y * y; if ...
use crate::context::Ctx; use thruster::MiddlewareReturnValue; use crate::models::users::NewUser; use crate::users::user_service; use crate::util::error::HttpError; use crate::util::query_string; use futures::future; use std::boxed::Box; use uuid::Uuid; pub fn get_users( mut context: Ctx, _next: impl Fn(Ctx) -...
#[macro_use] extern crate slog; #[macro_use] extern crate serde_derive; extern crate serde_json; extern crate serde; extern crate toml; extern crate iron; pub mod config; pub mod configmisc;
extern crate hilbert_curve; extern crate test; use test::Bencher; use hilbert_curve::BytewiseHilbert; #[bench] fn encode_decode_byte(bencher: &mut Bencher) { let hilbert = hilbert_curve::BytewiseHilbert::new(); let mut index = 0; bencher.iter(|| { let z = hilbert.entangle((index, 7u32)); ...
use filebuffer::FileBuffer; use std::{ fs::File, io::{BufRead, BufReader}, string::String, vec::Vec, }; pub trait FileProcessor { fn process(&self) -> Vec<u8>; fn name(&self) -> String; } pub struct ChunkFileProcessor { file: File, buff_size: usize, name: String, } impl ChunkFileP...
use std::collections::HashMap; fn get_input() -> Vec<i32> { include_str!("../input.txt") .lines() .map(|s| s.parse::<i32>().unwrap()) .collect() } #[allow(dead_code)] fn part_one() { let mut input = get_input(); input.sort_unstable(); let mut prev_adapter = 0i32; let mut d...
use crate::{backend, io}; /// `GRND_*` constants for use with [`getrandom`]. pub use backend::rand::types::GetRandomFlags; /// `getrandom(buf, flags)`—Reads a sequence of random bytes. /// /// This is a very low-level API which may be difficult to use correctly. Most /// users should prefer to use [`getrandom`] or [`...
use std::borrow::Cow; use std::error; use std::fmt; use std::str::Utf8Error; use percent_encoding::percent_decode; use regex::Captures; use errors::ParamError; pub struct Params<'a> { captures: Captures<'a>, } impl<'a> Params<'a> { pub(crate) fn new(captures: Captures<'a>) -> Self { Params { capture...
use common; use std::collections::HashMap; #[derive(Debug)] enum Error { CouldNotParseStep(String) } type Program = char; enum Move { Spin(usize), Exchange(usize, usize), Partner(char, char) } impl Move { pub fn parse(s: &str) -> Result<Move, Error> { return match s.chars().next() { ...
// Copyright 2022 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 ...
//! A stage to broadcast data from a leader node to validators //! use crate::blockBufferPool::Blocktree; use crate::clusterMessage::{ClusterInfo, ClusterInfoError, DATA_PLANE_FANOUT}; use crate::entryInfo::EntrySlice; use crate::expunge::CodingGenerator; use crate::packet::index_blobs_with_genesis; use crate::waterClo...
use crate::account::data::{Account, AccountType, DetailedAccount}; use rusqlite::{params, Result, NO_PARAMS}; use std::ops::DerefMut; // Single Account Operations pub fn get_account( conn: r2d2::PooledConnection<r2d2_sqlite::SqliteConnectionManager>, id: i32, ) -> Result<Account> { let mut stmt = conn.pre...
fn main() { let v: Vec<i32> = Vec::new(); println!("{:#?}", v); let v = vec![1, 2, 3]; println!("{:#?}", v); let mut v2 = Vec::new(); v2.push(5); v2.push(6); v2.push(7); v2.push(8); println!("{:#?}", v2); { let v3 = vec![1, 2, 3, 4]; println!("{:#?}", v3); ...
macro_rules! fmt_impl { ($trait:ident, $Trait:ident, [$($name:expr),*]) => { pub(crate) mod $trait { use crate::utils::*; pub(crate) const NAME: &[&str] = &[$($name),*]; pub(crate) fn derive(data: &Data, items: &mut Vec<ItemImpl>) -> Result<()> { derive_...
//! TTY related functionality. use std::path::PathBuf; use std::{env, io}; use crate::config::Config; #[cfg(not(windows))] mod unix; #[cfg(not(windows))] pub use self::unix::*; #[cfg(windows)] pub mod windows; #[cfg(windows)] pub use self::windows::*; /// This trait defines the behaviour needed to read and/or writ...
//! WebSocket Events /// This is created from [`ErrorEvent`][web_sys::ErrorEvent] received from `onerror` listener of the WebSocket. #[derive(Clone, Debug)] pub struct ErrorEvent { /// The error message. pub message: String, } /// Data emiited by `onclose` event #[derive(Clone, Debug)] pub struct CloseEvent {...
use std::collections::BTreeMap; use std::fmt; use super::fmt::FmtGuard; use super::node::Node; use super::uses::Use; pub struct File { pub uses: BTreeMap<String, Use>, pub node: Node, } impl fmt::Debug for File { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { for u in self.uses.values...
use std::fmt; use std::fmt::Debug; extern crate prusti_contracts; use prusti_contracts::*; #[derive(Copy, Clone, Eq, Hash, PartialEq, PartialOrd, Ord)] pub struct Height(u64); impl Debug for Height { #[trusted] fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "block::Height({})",...
use yew::prelude::*; pub struct TabPermissions {} pub enum Msg {} impl Component for TabPermissions { type Message = Msg; type Properties = (); fn create(_: Self::Properties, _: ComponentLink<Self>) -> Self { TabPermissions {} } fn update(&mut self, _msg: Self::Message) -> ShouldRender ...
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // 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 ...
use std::io::{self, Read}; use std::result::Result as StdResult; use std::num::{ParseFloatError, ParseIntError}; use std::path::PathBuf; use base64; use sxd_document::dom::Element; use sxd_document::parser::{parse as parse_xml, Error as XmlError}; use chrono::{DateTime, ParseError as ChronoError, TimeZone, Utc}; use su...
use brainfuck_lexer::BFT; use config::{get_config, ConfigStruct, OutputType}; use std::env; use std::io::{self, stdout, Write}; use std::num::Wrapping; use std::time::Instant; mod brainfuck_lexer; mod loop_cache; use loop_cache::{loop_cache_control, LoopCacheStatus}; mod config; mod util; use util::{log, log_withou...
//! Main module of way-cooler #[macro_use] extern crate lazy_static; extern crate bitflags; extern crate dbus_macros; #[cfg(not(test))] extern crate rustwlc; extern crate getopts; #[cfg(test)] extern crate dummy_rustwlc as rustwlc; #[macro_use] extern crate log; extern crate env_logger; extern crate rlua; extern crate...
// Copyright (c) 2016 The Rouille developers // Licensed under the Apache License, Version 2.0 // <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT // license <LICENSE-MIT or http://opensource.org/licenses/MIT>, // at your option. All files in the project carrying such // notice may not be co...
use std::fs::{create_dir_all, File}; use std::io::prelude::*; use std::path::{Path}; use crate::error::Result; pub fn create_file(path: &Path, content: &str) -> Result<()> { if let Some(p) = path.parent() { create_dir_all(p)?; } let mut file = File::create(&path)?; file.write_all(content.as_by...
use std::io::{Read, Seek, SeekFrom}; use std::error::Error; use byteorder::{ReadBytesExt, LE}; use image::{DynamicImage, SubImage}; use image::codecs::dds::DdsDecoder; use image::imageops::crop_imm; use std::collections::HashMap; pub struct Anim { layers: HashMap<String, DynamicImage>, frames: Vec<FrameInfo>, ...
//! Tests auto-converted from "sass-spec/spec/css/media" #[allow(unused)] use super::rsass; #[allow(unused)] use rsass::precision; // Ignoring "range", start_version is 3.7.
use std::error; use std::fs::{OpenOptions}; use std::io::{self, Read}; use crate::asset::{AssetPathBuf, AssetPath, ASSET_MANAGER_INSTANCE}; use crate::render::shader::{ShaderProgram, Shader, ShaderCode, ProgramLinkOptions, ShaderStage, ShaderCompileOptions, ShaderCompileStatus, ProgramLinkStatus}; use crate::render::sh...
#[cfg(not(windows))] pub(crate) mod syscalls; pub(crate) mod types;
extern crate stdweb; use stdweb::web::document; use stdweb::web::INode; use stdweb::web::IElement; pub fn run() { stdweb::initialize(); let doc = document(); let val = doc.create_element("p").unwrap(); val.set_attribute("innerHTML", "IT IS ALIVE").unwrap(); doc.body().unwrap().append_child(&val);...
use std::borrow::Borrow; use std::cell::RefCell; use std::collections::HashMap; use std::fmt; use std::fmt::{Display, Formatter}; use std::hash::Hash; use std::rc::{Rc, Weak}; use crate::safe_tree::NodeRc; type NodeWeak<K, V> = Weak<Node<K, V>>; #[derive(Debug)] pub struct Node<K, V> { pub value: RefCell<V>, ...
#![feature(conservative_impl_trait)] extern crate futures; extern crate tokio_core; extern crate tokio_proto; extern crate tokio_service; mod codec; use codec::IrcCodec; use futures::{BoxFuture, Future, Sink, Stream, stream}; use futures::stream::BoxStream; use futures::sync::mpsc::channel; use std::net::ToSocketAddr...
extern crate bindgen; extern crate gcc; use gcc::Config; use std::env; use std::path::PathBuf; fn main() { let mut c = Config::new(); c.flag("-std=c99"); c.file("src/c/YGEnums.c"); c.file("src/c/YGNodeList.c"); c.file("src/c/Yoga.c"); c.compile("libyoga.a"); let bindings = bindgen::Builder::default() .no_u...
struct Point{ x:i32, y:i32 } fn main(){ let mut y = &0; //0というデータのラベルくんが暗黙のうちに作成?されている。 // そのラベルくんの身代わりを、yくんというmutなラベルくんが請け負った。yは走り回れることに注意せよ println!("{}",y); { //ここでlifetime ブロックがつくられる let a = Point{x:100,y: 230}; //今、aをPointデータのimmutなラベルくんとする y = &a.y; //aくんというラベルの身代わりを作成。その中...
use { crate::modules::{ Module, sway, Clock, }, std::{ error::Error, result::Result, }, gdk::Monitor, gtk::{ prelude::*, Box as WidgetBox, CssProvider, Orientation, StyleContext, WidgetExt, Window, ...
use uuid::Uuid; use crate::value_objects::title::Title; use crate::value_objects::content_type::ContentType; use std::str::FromStr; use std::convert::TryFrom; use crate::survey::Content::Youtube; use crate::dtos::ChoiceDTO; #[derive(Entity)] pub struct Choice { pub(super) id: Uuid, pub(super) content: Option<C...
// 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. use failure::{format_err, Error}; use fidl::endpoints::{create_endpoints, create_request_stream}; use fidl_fuchsia_auth::{ AuthStateSummary, Authentica...
use tree_sitter::{Node, QueryCapture}; use guarding_core::domain::code_function::CodeFunction; use guarding_core::domain::code_file::CodeFile; use guarding_core::domain::Location; pub trait CodeIdent { fn parse(code: &str) -> CodeFile; fn insert_location<T: Location>(model: &mut T, node: Node) { mode...
fn split_input(input: &str) -> Vec<usize> { let v: Vec<&str> = input.split(",").collect(); v.into_iter().map( |num| { num.parse::<usize>().unwrap() } ).collect() } fn intcode(mut input: Vec<usize>) -> usize { let mut pos = 0; loop { let curr = input[pos]; ...
//! The debug runner. use luminance::context::GraphicsContext; use luminance::framebuffer::Framebuffer; use luminance_glfw::surface::{ Action, GlfwSurface, Key as GlfwKey, Surface, WindowDim, WindowEvent, WindowOpt }; use structopt::StructOpt; use warmy::{Store, StoreOpt}; use crate::app::demo::Demo; use crate::app...
use libtest_mimic::{Outcome, Test}; use serde::Deserialize; use std::fmt::Write; use std::fs; use std::path::{Path, PathBuf}; use std::process::Command; use walkdir::WalkDir; /// Recursively walk over test files under a file path. pub fn walk_files(root: impl AsRef<Path>) -> impl Iterator<Item = PathBuf> { WalkDir...
use crate::rtrs::objects::Aabb; use crate::HitRecord; use crate::Hitable; use crate::Material; use crate::Point; use crate::Ray; use crate::Vector; use std::sync::Arc; #[derive(Debug)] pub struct MovingSphere { pub center0: Point, pub center1: Point, pub time0: f64, pub time1: f64, pub radius: f64,...
extern crate durationfmt; use std::time::Duration; fn main() { let d = Duration::new(0, 0); println!("{}", durationfmt::to_string(d)); // 0s let d = Duration::new(90, 0); println!("{}", durationfmt::to_string(d)); // 1m30s let d = Duration::new(209, 1_000); println!("{}", durationfmt::to_string(d)); ...
use std::rc::Rc; use regex_syntax; use regex_syntax::hir::GroupKind as LibGroup; use regex_syntax::hir::HirKind as LibHir; use regex_syntax::hir::RepetitionKind as LibRepKind; use regex_syntax::hir::RepetitionRange as LibRepRange; use super::super::automaton::atom::Atom; use super::super::automaton::Label; use super:...
use super::VarResult; use crate::ast::syntax_type::{FunctionType, FunctionTypes, SyntaxType}; use crate::helper::err_msgs::*; use crate::helper::str_replace; use crate::helper::{move_element, pine_ref_to_bool, pine_ref_to_i64, pine_ref_to_string}; use crate::runtime::context::{downcast_ctx, Ctx}; use crate::runtime::{S...
use gl_bindings::gl; use crate::render::shader::{Shader, ShaderStage}; use std::mem; pub struct ShaderProgram { vertex_shader: Option<Shader>, fragment_shader: Option<Shader>, tess_control_shader: Option<Shader>, tess_eval_shader: Option<Shader>, geometry_shader: Option<Shader>, compute_shader: Option<Shader>, ...
extern crate sdl2; extern crate rand; use std::fs::File; use std::io::{BufReader, Error, BufRead, ErrorKind}; use sdl2::render::Renderer; use sdl2::rect::{Rect, Point}; use sdl2::pixels::Color; use rand::distributions::{IndependentSample, Range}; use rand::{Rng, Rand}; #[derive(Clone, Copy, PartialEq)] pub enum Direc...
use std::marker::PhantomData; use super::heap::RegionHeap; use crate::algorithm::Sorted; use crate::properties::{WithRegion, WithRegionCore}; use crate::ChromName; pub(super) struct Context<C: ChromName, I: Iterator + Sorted> where I::Item: WithRegion<C> + Clone, { iter: I, peek_buffer: Option<I::Item>, ...
use collections::HashMap; use std::rc::Rc; use sdl2::render; use sdl2::pixels; use sdl2::video; use sdl2::surface; pub struct Graphics { screen: ~render::Renderer, sprite_sheets: HashMap<~str, Rc<~surface::Surface>> } static WINDOW_HEIGHT: int = 480; static WINDOW_WIDTH: int = 640; impl Graphics { pub fn...
// Copyright 2019 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. #![recursion_limit = "256"] mod controller; mod error; mod filter; mod serialization; mod session; mod state; mod types; mod utils; use fidl_fuchsia_ledg...
mod sorting; mod strings;
#[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::FAULT { #[doc = r"Modifies the contents of the register"] #[inline(always)] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'...
use crate::core::colors::RgbaColor; use crate::core::window::WindowDim; use crate::render::ui::{Color, Position, Vertex}; /// A flat zone of same color. pub struct Panel { /// Top-left corner pub(crate) anchor: glam::Vec2, /// width and height of the panel pub(crate) dimensions: glam::Vec2, /// col...
use add_one; // This can be run at the root of the workspace with this command : cargo run -p adder // The rand crate is imported by the 2 projects but the workspace lock in the same version for them // We can run tests for all projects by executing "cargo test" in the workspace folder // Or run tests for a specific...
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)] #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct BarcodeScannerDisableScannerRequest(pub ::wind...
#[macro_use] extern crate criterion; mod projective { use algebra::curves::mnt4753::G1Projective as MNT4Projective; use blake2::Blake2s; use criterion::Criterion; use primitives::signature::{schnorr::*, SignatureScheme}; use rand::{self, Rng}; type SchnorrMNT4Affine = SchnorrSignature<MNT4Proj...
#![crate_name="capstone"] #![crate_type="rlib"] extern crate libc; #[macro_use] extern crate bitflags; use libc::{c_int, c_void, size_t}; use std::ffi::CStr; mod ll; #[cfg(test)] mod tests; #[derive(Clone, Copy, Debug)] pub enum Arch { Arm = 0, Arm64, MIPS, X86, PowerPC, Sparc, SystemZ...
// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. pub fn serialize_operation_clone_backend( input: &crate::input::CloneBackendInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectW...
extern crate rand; use wasm_bindgen::prelude::*; use rand::Rng; pub fn generate_rgb(max: i32) -> String { let mut colors: Vec<String> = Vec::new(); let mut rgb: Vec<String> = Vec::new(); for _ in 0..max { for _ in 0..3 { let new: i32 = rand::thread_rng().gen_range(0, 255); ...
use std::borrow::Cow; fn get_name() -> Cow<'static, str> { std::env::var("YOUR_NAME") //.map(|v| Cow::Owned(v)) .map(|v| v.into()) //.unwrap_or(Cow::Borrowed("whoever you are")) .unwrap_or("whoever you are".into()) } #[test] fn cow_owned_test() { std::env::set_var("YOUR_NAME", ...
use super::*; /// Defines a segment of something that may be interpolated #[derive(Debug, PartialEq)] pub enum Segment { Char(char), String(String), Expr(Box<Node>), } impl Segment { pub fn expr(v: Node) -> Self { Self::Expr(Box::new(v)) } }
//! A lexer for the Elella format. //! //! ``` //! use elella::lexer::*; //! //! let mut l = Lexer::new("[:a 1]".as_bytes()); //! assert_eq!(l.lex().ok(), Some(Token::LBrack)); //! assert_eq!(l.lex().ok(), Some(Token::Lit(Lit::Keyword(String::from("a"))))); //! assert_eq!(l.lex().ok(), Some(Token::Lit(Lit::Int(1)))); /...
pub type StockId = String; pub type Quantity = u32; #[derive(Debug, Clone)] pub enum Stock { Nothing, OutOfStock { id: StockId }, InStock { id: StockId, qty: Quantity }, } pub trait CommandHandle<S, E> { fn handle(&self, state: S) -> Option<E>; } pub trait EventApply<S> { fn apply(&self, state: ...
extern crate telegram_codegen; use std::env; use std::path::Path; fn main() { let out_dir = env::var("OUT_DIR").unwrap(); let dest_path = Path::new(&out_dir).join("schema.rs"); telegram_codegen::translate("schema/schema.json", &dest_path).unwrap(); let dest_path = Path::new(&out_dir).join("mtproto_s...
use serde::{Deserialize, Serialize}; #[derive(PartialEq, Eq, Hash, Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct TracingConfig { pub register_fuzzables: TracingMode, pub calls: TracingMode, pub evaluated_expressions: TracingMode, } impl TracingConfig { pub const f...
use std::io::{Read, Result as IOResult, Error as IOError, ErrorKind}; use crate::lump_data::{LumpData, LumpType}; use crate::PrimitiveRead; pub enum FaceType { Polygon = 1, Patch = 2, Mesh = 3, Billboard = 4 } pub struct Face { pub texture: i32, pub effect: i32, pub face_type: FaceType, pub vertex_cou...
extern crate dht11_22_pi; use dht11_22_pi::{Sensor, read}; pub fn main() { let result = read(Sensor::Dht22, 14); println!("{:?}", result); }
use chrono::prelude::*; use clap::{App, Arg}; use heapquery::{ exec_query, init_schema, insert_edges, insert_locations, insert_nodes, open_assoc_db, read_heap_file, setup_db_if_needed,calculate_distance, }; use serde_json::Value; fn main() { let matches = App::new("heapquery") .version("0.0.1") .author("...
#[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::SPC { #[doc = r"Modifies the contents of the register"] #[inline(always)] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'w ...
use procon_reader::ProconReader; fn main() { let stdin = std::io::stdin(); let mut rd = ProconReader::new(stdin.lock()); let q: usize = rd.get(); use std::collections::{BTreeMap, VecDeque}; let mut freq = BTreeMap::new(); let mut tail = VecDeque::new(); for _ in 0..q { let c: u8 = ...
use proconio::input; fn main() { input! { n: usize, p: u32, q: u32, d: [u32; n], }; let ans = p.min(q + d.iter().min().unwrap()); println!("{}", ans); }
extern crate diesel; use diesel::prelude::*; use crate::api::model::User; use crate::config::db::connection; use crate::config::db::schema::users::dsl::*; pub fn list() -> Vec<User> { let connection = connection().unwrap(); users .order(id.desc()) .load::<User>(&connection) .expect("r...
/// The original Chip-8 would increment `I` after executing `READ` or `WRITE`. /// /// Most modern games assume that `I` is _not_ incremented as that's what Super Chip-8 1.1 does. #[derive(PartialEq, Debug)] pub enum ReadWriteIncrementQuirk { /// Do nothing to `I` after executing `READ` or `WRITE` InvariantInde...
use std::collections::HashMap; use std::env; use std::fs::File; use std::io::BufRead; use std::io::BufReader; extern crate itertools; use itertools::Itertools; fn main() { let args: Vec<String> = env::args().collect(); let filename = &args[1]; let file = File::open(filename).expect("Could not read file")...
use std::thread; use std::sync::{Arc, Mutex}; extern crate num_cpus; pub fn hello_thread(a: &Vec<i32>) -> Option<Vec<i32>>{ let c = Arc::new(Mutex::new(vec![0;a.len()])); let mut handle = Vec::new(); //let a = [3,2,1,1,0,2]; let ma = Arc::new(a.clone()); let max_num_threads = num_cpus::get...
use serde::{Deserialize, Serialize}; use n3_machine_ffi::{MachineId, Program, Query, WorkId}; #[derive(Debug, Serialize, Deserialize)] pub enum Request { Load { work: WorkId, query: Vec<Query>, }, Spawn { id_primaries: Vec<MachineId>, program: Program, }, Status { ...
use crate::ast::*; use crate::error::*; use crate::lexer::Lexer; use crate::precedence::Precedence; use crate::token::Token; use crate::token_type::TokenType; pub struct Parser { lexer: Lexer, current_token: Option<Box<Token>>, peek_token: Option<Box<Token>>, pub errors: Vec<ParseError>, } impl Parser...
use mock; fn main() { mock::substrate_block::generate_substrate_block(); }
use std::rc::Rc; use crate::vec3::Vec3; use std::f32::consts::PI; use rand::{self, Rng}; use crate::hittable::{HitRecord, Hittable}; use crate::ray::Ray; use crate::vec3::{Point3}; use crate::material::Material; use crate::aabb::{AABB, surrounding_box}; pub struct Sphere { pub center: Point3, pub radius: f32...
use spin::Mutex; use core::mem; extern "C" { fn idt_flush(ptr: u32); } const MAX_ENTRIES: usize = 256; #[repr(C, packed)] #[derive(Copy, Clone, Default)] struct IdtEntry { base_low: u16, sel: u16, always0: u8, flags: u8, base_high: u16, } #[repr(C, packed)] #[derive(Default)] struct IdtDescriptior { l...
// // This module is responsible for locating and loading paths in a local setup. // // Now it also provides init method which acts like a stub for proper installation // script which will use local paths. // use anyhow::{Context, Result}; use serde::{Deserialize, Serialize}; use std::env; use std::fs; use std::path::P...
extern crate iso8601; use iso8601::iso8601; #[test] fn iso8601_1() { let mut buffer = String::new(); iso8601(&mut buffer, 1497866183, -4 * 60 * 60).unwrap(); assert_eq!(&buffer, "2017-06-19T05:56:23-04:00"); } #[test] fn iso8601_2() { let mut buffer = String::new(); iso8601(&mut buffer, 149826...
struct S; fn main() { let [x, y] = &mut [S, S]; let eq = x as *mut S == y as *mut S; println!("{}", eq as u8); println!("{:?}", std::mem::size_of::<[S; 2]>()); } /* In this code, S is a zero sized type or ZST. Zero sized types are compile-time concepts that disappear during compilation and have a runti...
use super::*; use std::mem; use std::str; #[test] fn io_read_can_read_from_drive() { let first_sector = io_read(r#"\\.\PHYSICALDRIVE1"#, 0, 1); assert_eq!(first_sector.len(), 512); } #[test] fn check_if_mbr_has_valid_signature() { let mut first_sector = io_read(r#"\\.\PHYSICALDRIVE1"#, 0, 1); let mut ...
// Copyright 2022 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 ...
extern crate monkey; use std::vec; use monkey::lexer::*; use monkey::token::*; #[test] fn lexer_1_next_token() { let input: &str = "=+(){},;"; let input: Vec<char> = input.chars().collect(); let expected_tokens = vec![ Token::ASSIGN, Token::PLUS, Token::LPAREN, Token::RPA...
//! Provides the Segment struct. use shape::coord::Coord; use std::cmp::max; use std::cmp::min; use shape::orientation::Orientation; use std::collections::HashSet; use shape::polygon::Polygon; use std::cmp::Ordering; /// Represents a line segment AB. #[derive(Serialize, Deserialize, Debug, Copy, Clone, Eq, PartialEq,...
use rocket::http::Status; use rocket::request::{self, FromRequest, Request}; use rocket::Outcome; #[derive(Debug)] pub enum GitLabTokenError { InvalidToken, } #[derive(Debug)] pub enum RequestError { BadCount, Missing, } pub struct XGitLabEvent(pub String); impl<'a, 'r> FromRequest<'a, 'r> for XGitLabEv...
use crate::prelude::*; pub fn add_models(mut models: Models<Model>) -> Models<Model> { use CreatureModels::*; models.insert(None, Some(Model::Creatures(Slime)), load_scene("Square"), Template::Scene); models.insert(None, Some(Model::Creatures(Zombie)), load_scene("Rectangle"), Template::Scene); model...
use std::fs::OpenOptions; use std::io::{self, Write as _}; use std::path::{Path, PathBuf}; use filetime::{set_file_mtime, FileTime}; use flate2::write::ZlibEncoder; use flate2::Compression; use thiserror::Error; use crate::object::database::ObjectReader; use crate::object::Id; const OBJECTS_FOLDER: &str = "objects";...
test_stdout!( without_integer_returns_false, "false\nfalse\nfalse\nfalse\nfalse\nfalse\nfalse\nfalse\nfalse\nfalse\n" ); test_stdout!(with_integer_returns_true, "true\ntrue\n");
use thiserror::Error; type RgbArray = [u8; 3]; #[derive(Error, Debug, PartialEq)] pub enum ParserError { #[error("Incomplete input")] Incomplete, #[error("Invalid input")] Invalid, } /// Accepts RGB colours of the form ab7c01 (no # at the start) pub fn parse_rgb(input: &str) -> Result<RgbArray, Parse...
use test_deps::deps; use tokio::time::{self, Duration}; static mut BOOL_IGN_OK: bool = false; #[deps(IGN_OK_000)] #[tokio::test] async fn tokio_with_ignore_attribute_000() { time::sleep(Duration::from_millis(250)).await; unsafe { assert!(!BOOL_IGN_OK); BOOL_IGN_OK = true; } } #[deps(IGN_O...