text
stringlengths
8
4.13M
/* * Copyright 2019 Bitwise IO, Inc. * Copyright 2019 Cargill Incorporated * * 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 * * Unl...
mod module_1; mod module_2; mod module_3; // module fn test1() { assert_eq!(module_1::func1(), 42); assert_eq!(module_1::func2(), 65); assert_eq!(module_1::inner_module_1::func1(), 17); assert_eq!(module_1::inner_module_1::func2(), 23); } // nested module fn test2() { assert_eq!(module_2::func1(),...
use rendy::graph::{NodeId,ImageId}; use std::collections::{HashMap}; pub struct RenderPlan { pub node_passes:HashMap<String,NodeId>, pub outputs:HashMap<String,ImageId>, pub depths:HashMap<String,ImageId>, } impl RenderPlan { pub fn new() -> Self { RenderPlan { node_passes: HashMap...
mod balance_activities; mod balance_max_load;
struct Solution; use util::*; trait Preorder { fn preorder(&self, level: usize, levels: &mut Vec<Vec<i32>>); } impl Preorder for TreeLink { fn preorder(&self, level: usize, levels: &mut Vec<Vec<i32>>) { if let Some(node) = self { let node = node.borrow(); let val = node.val; ...
#[allow(unused_imports)] use serde_json::Value; #[derive(Debug, Serialize, Deserialize)] pub struct NetworkExternalExtended { /// Enable or disable Source Based Routing (Defaults to false) #[serde(rename = "sbr")] pub sbr: Option<bool>, /// Delay in seconds for IP rebalance. #[serde(rename = "sc_re...
use std::collections::HashMap; use std::i32; #[derive(Default)] struct TwoSum { numbers: HashMap<i32, usize>, max: i32, min: i32, } impl TwoSum { fn new() -> Self { TwoSum { numbers: HashMap::new(), max: i32::MIN, min: i32::MAX, } } fn add(&...
use chrono::{Datelike, Local, NaiveDate}; use std::cmp::{max, min}; use std::fs::File; use std::io::{self, BufRead}; use std::path::Path; #[derive(PartialEq, Eq, PartialOrd, Ord)] struct Birthday { month: u8, day: u8, year: Option<u16>, name: String, } impl Birthday { fn from(s: &str) -> Self { ...
/* * @lc app=leetcode.cn id=98 lang=rust * * [98] 验证二叉搜索树 */ // @lc code=start // Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] // pub struct TreeNode { // pub val: i32, // pub left: Option<Rc<RefCell<TreeNode>>>, // pub right: Option<Rc<RefCell<TreeNode>>>, // } // // impl TreeNode ...
use std::{ fs, path, }; use amethyst::{ assets::{Handle, Loader, AssetStorage}, ecs::prelude::*, prelude::*, core::transform::Transform, renderer::{Camera, SpriteSheet, Texture, ImageFormat, SpriteSheetFormat, SpriteRender}, utils::application_root_dir, }; pub const VIEWBOX_WIDTH: f32 ...
use rand::{self, Rng}; use crate::model::{ board::{Board, IntersectionIndex}, generate::stateless::StatelessModelGenerationSettings, stateless::{City, Intersection, Road}, }; mod fix; pub mod intersection; pub mod road; pub const MIN_LANE_LENGTH: f64 = 50.0; pub const MAX_LANE_LENGTH: f64 = 100.0; pub f...
use crate::server_configuration::Configuration; use self::schema::movies; use self::schema::movies::dsl::*; use diesel::prelude::*; use diesel::result::Error; use diesel::{Queryable, Insertable}; use diesel::pg::PgConnection; use std::result::Result; mod schema; fn establish_connection(config: &Configuration) -> Pg...
extern crate regex; use regex::Regex; use std::option::Option; use std::iter::*; use ast::*; use std::rc::Rc; #[derive(Debug, PartialEq)] pub enum Token<'a> { Char(char), String(&'a str), SpecialChars(&'a str) } //@todo refactor. Regex should be staticly allocated. fn advance(rest_input: &str) -> (usize, ...
use crate::counts::{Counts, PackedNumberCounts}; use serde::Serialize; #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)] pub enum BlockType { #[serde(rename = "kotsu")] Kotsu, #[serde(rename = "shuntsu")] Shuntsu, #[serde(rename = "ryammen")] Ryammen, #[serde(re...
use crate::{device::DevicePath, ffi::NonNull}; use libfido2_sys::*; use std::{ffi::CStr, str}; /// Owns a list of [information] about found devices. /// /// [information]: struct.DeviceInformation.html #[derive(PartialEq, Eq)] pub struct DeviceList { pub(crate) raw: NonNull<fido_dev_info>, // Length of allocat...
#[allow(deref_nullptr)] fn main() { unsafe { *std::ptr::null_mut() = 0i32 }; //~ ERROR: null pointer is a dangling pointer }
//! //! This file implements operations to the child bdevs from the context of its //! parent. //! //! `register_children` and `register_child` are should only be used when //! building up a new nexus //! //! `offline_child` and `online_child` should be used to include the child into //! the IO path of the nexus curren...
use std::any::Any; use std::cell::Ref; use std::ops::Deref; use bit_set::BitSet; use crate::atn_config_set::ATNConfigSet; use crate::dfa::DFA; use crate::errors::ANTLRError; use crate::lexer::Lexer; use crate::parser::Parser; use crate::recognizer::Recognizer; use crate::token::Token; use crate::token_factory::TokenF...
#![allow(dead_code)] use std::cmp; use std::convert; #[derive(Copy, Clone, PartialEq, Eq, Debug)] pub struct RGB { pub red: u16, pub green: u16, pub blue: u16, } // Constructor and some useful "constants" impl RGB { pub const WHITE: RGB = RGB { red: 255, green: 255, blue: 255,...
use std::sync::Arc; use std::slice; use super::XConnection; #[derive(Clone)] pub struct MonitorId { /// The actual id id: u32, /// The name of the monitor name: String, /// The size of the monitor dimensions: (u32, u32), /// The position of the monitor in the X screen position: (i32, i...
use crate::shared::auth::{account_can_modify_calendar, protect_route}; use crate::shared::usecase::{execute, UseCase}; use crate::{error::NettuError, shared::auth::protect_account_route}; use actix_web::{web, HttpRequest, HttpResponse}; use nettu_scheduler_api_structs::get_calendar_events::{APIResponse, PathParams, Que...
use super::{ build_nfa::{Action, Edge, NFA}, InfraredData, Vartable, }; use crate::{Event, Message}; use log::trace; use std::{collections::HashMap, fmt, fmt::Write}; /// NFA Decoder state #[derive(Debug)] pub struct NFADecoder<'a> { pos: Vec<(usize, Vartable<'a>)>, abs_tolerance: u32, rel_toleranc...
#[allow(unused_imports)] use tracing::{info, warn, debug, error, trace, instrument, span, Level}; use ate::{compact::CompactMode, prelude::*}; use std::time::Duration; use url::Url; use clap::Parser; mod flow; use crate::flow::ChainFlow; #[derive(Parser)] #[clap(version = "1.4", author = "John S. <johnathan.sharrat...
pub use afio::AfioExt as _stm32f103xx_hal_afio_AfioExt; pub use dma::DmaExt as _stm32f103xx_hal_dma_DmaExt; pub use flash::FlashExt as _stm32f103xx_hal_flash_FlashExt; pub use gpio::GpioExt as _stm32f103xx_hal_gpio_GpioExt; pub use hal::prelude::*; pub use pwm::PwmExt as _stm32f103xx_hal_pwm_PwmExt; pub use rcc::RccExt...
use crate::io::PgBufMutExt; use crate::io::{BufMutExt, Encode}; pub struct SaslInitialResponse<'a> { pub response: &'a str, pub plus: bool, } impl Encode<'_> for SaslInitialResponse<'_> { fn encode_with(&self, buf: &mut Vec<u8>, _: ()) { buf.push(b'p'); buf.put_length_prefixed(|buf| { ...
// Time: O(1) // Space: O(1) pub struct Solution1 {} impl Solution1 { pub fn hamming_distance(x: i32, y: i32) -> i32 { let mut distance: i32 = 0; let mut z: i32 = x ^ y; while z != 0 { distance += 1; z &= z - 1; } distance } } pub struct Solutio...
extern crate tiff; use tiff::decoder::{ifd, Decoder, DecodingResult}; use tiff::ColorType; use std::fs::File; use std::path::PathBuf; const TEST_IMAGE_DIR: &str = "./tests/images/"; macro_rules! test_image_sum { ($name:ident, $buffer:ident, $sum_ty:ty) => { fn $name(file: &str, expected_type: ColorType,...
use serde_json::{json, Value}; use svm_types::RuntimeError; use svm_types::{BytesPrimitive, CallReceipt, DeployReceipt, Receipt, ReceiptLog, SpawnReceipt}; use crate::api::json::serde_types::{AddressWrapper, HexBlob, TemplateAddrWrapper}; use crate::api::json::{self, get_field, parse_json, JsonError}; use crate::Code...
use udev::Device as UdevDevice; use crate::{ device::{Device, DeviceBuilder, PwmMode}, types::TempCelsius, }; use std::io::{Error, Result}; pub struct Builder; impl DeviceBuilder for Builder { fn from_udev(&self, name: String, device: UdevDevice, dryrun: bool) -> Box<dyn Device> { Box::new(HwmonDe...
use std::{str::FromStr, sync::atomic::AtomicBool}; use sha1::Sha1; use sha2::{Sha224, Sha256, Sha384, Sha512}; #[cfg(target_arch = "wasm32")] use wasm_bindgen::prelude::*; use super::{identify_iterations, identify_iterations_threaded}; /// A list of the hash algorithms to try pub static PRIMITIVES: &'static [HashPr...
//@only-target-windows: Uses win32 api functions // We are making scheduler assumptions here. //@compile-flags: -Zmiri-preemption-rate=0 use std::ffi::c_void; use std::ptr::null_mut; use std::thread; #[derive(Copy, Clone)] struct SendPtr<T>(*mut T); unsafe impl<T> Send for SendPtr<T> {} extern "system" { fn Ini...
use std::fs::File; use std::io; use std::io::prelude::*; use std::io::BufReader; fn get_input_reader() -> io::Result<BufReader<File>> { let file = File::open("data.txt")?; let reader = BufReader::new(file); Ok(reader) } fn part_one() -> i32 { let input_reader = get_input_reader().expect("Could not re...
use error::Error; use libnl::nl_sock::NlSock; #[derive(Debug)] pub struct Socket { pub nl_sock: NlSock, } impl Socket { pub fn new() -> Result<Socket, Error> { match NlSock::new() { Ok(nl_sock) => Ok(Socket { nl_sock: nl_sock }), Err(err) => Err(Error::SocketInitializationFaile...
use lumol::energy::{Potential, PairPotential}; #[derive(Clone, Copy)] pub struct Mie { /// Distance constant sigma: f64, /// Exponent of repulsive contribution n: f64, /// Exponent of attractive contribution m: f64, /// Energetic prefactor computed from the exponents and epsilon prefact...
/*! # Build system metadata This module provides deserialization and convenience methods for build system metadata located in `Cargo.toml`. Cargo ignores the `package.metadata` table in its manifest, so it can be used to store configuration for other tools. We recognize the following keys. ## Metadata for packages ...
fn fcn(n: i32) -> i64 { 2i64.pow(n as u32) }
use std::io; use std::path::Path; use mp3_metadata::MP3Metadata; use crate::util::Duration; use crate::util::duration::DurationExtractor; pub struct Mp3DurationExtractor; impl DurationExtractor for Mp3DurationExtractor { fn supports_ext(&self, ext_lowercase: &str) -> bool { "mp3" == ext_lowercase } ...
/** * [682] Baseball Game * * You are keeping score for a baseball game with strange rules. The game consists of several rounds, where the scores of past rounds may affect future rounds' scores. At the beginning of the game, you start with an empty record. You are given a list of strings ops, where ops[i] is the ith...
use std::collections::HashMap; use std::fmt::Write; use super::super::util::knot_hash::KnotHash; #[derive(Debug, PartialEq, Eq)] pub struct DiskGrid { grid: HashMap<(u8, u8), Status>, regions: usize, } #[derive(Debug, PartialEq, Eq)] enum Status { Free, Used, Region(usize), } impl Status { p...
// Copyright (c) The Starcoin Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::cli_state::CliState; use crate::StarcoinOpt; use anyhow::Result; use clap::Parser; use scmd::{CommandAction, ExecContext}; #[derive(Debug, Parser, Default)] #[clap(name = "add_peer")] ///Add a known peer pub struct AddPe...
//! This module contains commonly-used events in covalent. //! You can create custom events by implementing the `covalent::scene::Event` trait, and then //! creating an event handler for it with `covalent::scene::EventHandler::<YourEventType>::new()`. use std::sync::{Arc, RwLock}; mod common; pub use common::*; mod ...
use http; use std::io; pub const FAVICON_RESOURCE: StaticResource = StaticResource { content: include_bytes!("../ui/_dist/favicon.ico"), etag: include_str!("../ui/_dist/favicon.ico.md5"), content_type: "image/vnd.microsoft.icon", gzipped: false, }; pub const INDEX_HTML_RESOURCE: StaticResource = Stati...
use std::io; use std::io::Write; use csv_core::{ self, WriteResult, Writer as CoreWriter }; use serde::Serialize; use crate::error::{Error, ErrorKind, Result}; use crate::serializer::{serialize, serialize_header}; use crate::AsyncWriterBuilder; /// A helper struct to synchronously perform serialization of struct...
use std::vec; use quill::{PluginBuilder, ecs::Query}; fn main() { PluginBuilder::new("hello world") .add_rpc(|name: String| println!("hello {}!", name)) // .add_system(foo_system) .init() .expect("could not initlize plugin"); } fn foo_system(mut query: Query<(&(), &mut u32)>) { ...
use plastic_core::{ nes_controller::{StandardNESControllerState, StandardNESKey}, nes_display::{Color as NESColor, TV_HEIGHT, TV_WIDTH}, BackendEvent, UiEvent, UiProvider, }; use std::sync::{ mpsc::{Receiver, Sender}, Arc, Mutex, }; use sfml::{ graphics::{Color, FloatRect, Image, RenderTarget,...
use serde::{ Deserialize, Serialize, }; use super::expr::Expr; use super::stmt::Stmt; use super::types::Type; use crate::source::Pos; use crate::token::TokenType; use std::fmt::{ Display, Formatter, Result as FmtResult, }; #[derive( Debug, Clone, PartialEq, Eq, Ord, PartialOrd, Hash, Seriali...
//! //#![deny(warnings, /*missing_docs,*/ unused)] use std::io; use std::sync::mpsc; use std::sync::Arc; use std::thread; use std::time::Duration; use std::time::Instant; use crossterm::event; use crossterm::event::DisableMouseCapture; use crossterm::event::EnableMouseCapture; use crossterm::event::KeyCode; use cros...
extern mod rsfml; use rsfml::window::{event, keyboard, mouse}; use rsfml::graphics::{RenderWindow, FloatRect}; pub fn exit(window: &mut RenderWindow) { loop { match window.poll_event() { event::Closed => window.close(), event::NoEvent => break, _ => {} } } } pub fn menu() -> uint { let mut screen:u...
#[macro_use] extern crate enum_response_derive; #[derive(EnumResponse)] enum Error { #[response(reason_field = 1)] Tuple(String) }
// vim: tw=80 use crate::common::{*, label::*, vdev::*}; /// The public interface for all leaf Vdevs. This is a low level thing. Leaf /// vdevs are typically files or disks, and this trait is their minimum common /// interface. I/O operations on `VdevLeaf` happen immediately; they are not /// scheduled. pub trait V...
use crate::raw::{OriginalRoad, RawMap}; use crate::{ osm, Area, AreaID, Building, BuildingID, BuildingType, BusRoute, BusRouteID, BusStop, BusStopID, ControlStopSign, ControlTrafficSignal, Intersection, IntersectionID, Lane, LaneID, LaneType, Map, MapEdits, MovementID, OffstreetParking, ParkingLot, ParkingL...
extern crate adivon; use adivon::suffix_tree::SuffixTree; fn main() { let s = "apple".chars().collect::<Vec<char>>(); let s2 = "apple_tree".chars().collect::<Vec<char>>(); let mut st = SuffixTree::new(&s); st.add(&s2); println!("{}", st.to_dot()); }
use imperative_rs::InstructionSet; #[derive(InstructionSet)] enum Instructionset { #[ opcode = "0xff_vv_ff" ] A(u8), } fn main() {}
use crate::reflect::EnumDescriptor; use crate::reflect::EnumValueDescriptor; use crate::Enum; /// Trait is implemented for all enum types if lite runtime is not requested. /// /// This trait provides access to runtime reflection. pub trait EnumFull: Enum { /// Get enum value descriptor. fn descriptor(&self) ->...
use crate::parsing::{Parser, Expr, Precedence, ExprKind}; use regexlexer::{Token, TokenKind}; use crate::error::Error; use crate::typechecking::Ty; /// Returns the precedence accounting for associativity /// If an operator is right-associative, recursively parse expression with precedence of one less so it will parse ...
fn if_statement() { let temp = 35; if temp > 30 { // curly braces are mandatory! println!("really hot outside!"); } else if temp < 10 { println!("really cold, don't go out!"); } else { println!("temperature is OK"); } // if is an expression! let day = if temp > 20 {"sunny"} else {"c...
use serde::Deserialize; #[derive(Deserialize)] pub struct PageCreationRequest { pub url_path: String, pub content: String, } #[derive(Deserialize)] pub struct PageUpdateRequest { pub url_path: String, pub content: String, }
#![feature(min_const_generics)] #![feature(trait_alias)] mod field; mod group; mod operators; mod polynomial; mod ring; #[cfg(test)] mod tests { #[test] fn it_works() { type Z11 = crate::group::CyclicGroupElement<11>; let a = Z11::new(18); let b = Z11::new(8); assert_eq!(&a*&b,...
#![warn(missing_docs)] //! Control Plane Services library with emphasis on the message bus interaction. //! //! It's meant to facilitate the creation of services with a helper builder to //! subscribe handlers for different message identifiers. /// wrapper for mayastor resources pub mod wrapper; use async_trait::asyn...
use crate::{ global::SAVES_OPEN_OPTIONS, helpers::{ alloc::alloc, manifest::{get_manifest_path, read_manifest, write_manifest}, save::{get_saves, read_save, remove_save, write_save}, }, models::manifest::{Manifest, Save}, types::{ list::{List, UplayList}, over...
use crate::{APIResponse, BaseClient}; use nettu_scheduler_api_structs::*; use reqwest::StatusCode; use std::sync::Arc; #[derive(Clone)] pub struct AccountClient { base: Arc<BaseClient>, } impl AccountClient { pub(crate) fn new(base: Arc<BaseClient>) -> Self { Self { base } } pub async fn get(...
#![allow(proc_macro_derive_resolution_fallback)] use crate::customers::{Customer, InsertableCustomer}; use crate::mongo_connection::Pool; use r2d2_mongodb::mongodb::db::ThreadedDatabase; use mongodb::{bson, coll::results::DeleteResult, doc, error::Error, oid::ObjectId}; use mongodb as bson; const COLLECTION: &str = "...
//! Bit Manipulation Instruction (BMI) Set 2.0. //! //! The reference is [Intel 64 and IA-32 Architectures Software Developer's //! Manual Volume 2: Instruction Set Reference, //! A-Z](http://www.intel.de/content/dam/www/public/us/en/documents/manuals/64-ia-32-architectures-software-developer-instruction-set-reference-...
#[macro_use] extern crate log; extern crate log4rs; #[macro_use] extern crate clap; extern crate time; use clap::App; use std::process::{Command, Output, Stdio, ExitStatus}; use std::fs::{read_dir, DirEntry, copy, remove_file}; use std::path::Path; use std::io::{BufReader, BufRead, Read, Result}; use std::ffi::OsStr...
pub fn solve(input: &str) -> usize { let amount_recipes = input.replace("\r\n", "").parse::<usize>().unwrap(); let mut scoreboard = Vec::new(); scoreboard.push(3); scoreboard.push(7); let mut elf_1_index = 0; let mut elf_2_index = 1; for _ in 0..amount_recipes + 10 { let new_recipe...
use std::{ collections::{ hash_map::Entry::{Occupied, Vacant}, HashMap, }, fmt::Debug, sync::Arc, }; use iox_object_store::{IoxObjectStore, ParquetFilePath, TransactionFilePath}; use snafu::ResultExt; use crate::{ catalog::{ api::{CatalogParquetInfo, CatalogState, Checkpoin...
use std::cmp::{max, min}; use std::iter::FromIterator; use std::mem::size_of_val; use std::sync::mpsc::{sync_channel, Receiver}; use std::sync::{Arc, Mutex}; use std::thread::{self, spawn}; use std::time::{Duration, SystemTime, UNIX_EPOCH}; use futures::channel::mpsc::{unbounded, UnboundedSender}; use futures::channel...
// https://github.com/morkt/GARbro/blob/f8761f4a961330c6cba1bb0bf964d3249e7843a7/ArcFormats/ShiinaRio/WarcEncryption.cs pub(super) fn decrypt_helper1(a: f64) -> f64 { if a < 0.0 { return -decrypt_helper1(-a); } let mut v0: f64; let mut v1: f64; if a < 18.0 { v0 = a; v1 = a...
// //! 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 ...
// This file is part of Substrate. // Copyright (C) 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 // // http://www.a...
#![allow(unused_imports)] #![allow(unused_macros)] #![allow(non_snake_case)] #![allow(dead_code)] #![allow(unused_variables)] #![allow(unused_mut)] #![allow(unused_assignments)] use proconio::input; use proconio::marker::Usize1; use std::collections::*; use std::cmp::*; use std::f64::consts::*; const MOD: u64 = 100000...
mod settings; pub use self::settings::OidosSettings; use super::AudioSynthesizer; use crate::build::BuildOptions; use crate::compilation::CompilationJobEmitter; use crate::compilation_data::{Compilation, CompilationJob, CompilationJobKind}; use crate::hash_extra; use crate::paths::BUILD_ROOT_DIRECTORY; use crate::proj...
//! A module that conatins represenations of various parameters for use in invoking mpesa API products //! and handling responses received. //! The enum variants should always be used with the `to_String()` method or `format!()` macro so as to get the correct value as defined in the [official Mpesa Api Documenation](ht...
use heck::ToSnakeCase; use proc_macro::TokenStream; use quote::{format_ident, quote}; use syn::parse::{Parse, ParseStream, Result}; use syn::{parse_macro_input, Attribute, Ident, Token, Visibility}; struct Input { attrs: Vec<Attribute>, vis: Visibility, ident: Ident, } impl Parse for Input { fn parse(...
use std::cmp::Ordering; use std::collections::HashSet; use futures::future::join_all; use itertools::Itertools; use log::{debug, error, info, warn}; use crate::pg::config::{PgConfig, PgInfo}; use crate::pg::config_function::{FuncInfoSources, FunctionInfo}; use crate::pg::config_table::{TableInfo, TableInfoSources}; u...
// Copyright (c) The Libra Core Contributors // SPDX-License-Identifier: Apache-2.0 use std::collections::HashMap; use vm::file_format::SignatureToken; /// The BorrowState denotes whether a local is `Available` or /// has been moved and is `Unavailable`. #[derive(Debug, Clone, PartialEq)] pub enum BorrowState { A...
use std::time::Duration; use reqwest::{ self, blocking::{ Client as ReqwestClient, ClientBuilder as ReqwestClientBuilder, Request as ReqwestRequest, RequestBuilder as ReqwestRequestBuilder, Response as ReqwestResponse, }, IntoUrl, }; #[cfg(feature = "send3")] use websocket::{ self, ...
use crate::functions::analyse::*; use crate::functions::analyse_final::*; use crate::functions::dpll::*; use crate::functions::new_clause::*; use crate::functions::propagate::*; use crate::functions::reduce_db::*; use crate::functions::simplify_db::*; use crate::functions::solve::*; use crate::models::lbool::*; use cra...
use rand::{Rng, SeedableRng, XorShiftRng}; use entities::deciduous_tree::DeciduousTree; use entities::entity_manager::EntityManager; use resources::Resources; use registry::terrain::Terrain; use tiles::TILE_SCALE; use worldgen::{WORLD_SIZE, WORLD_SIZE_HALF}; const DIVISOR: i32 = 105; const BOUND: i32 = WORLD_SIZE as i...
#[doc = "Register `CFG` reader"] pub struct R(crate::R<CFG_SPEC>); impl core::ops::Deref for R { type Target = crate::R<CFG_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<CFG_SPEC>> for R { #[inline(always)] fn from(reader: crate::R<CFG_SPEC>) ...
/** * The main lexer library that connects with the derive library for the * derive-macro. */ extern crate yk_lexer_derive; mod position; mod lexer; mod token; pub use yk_lexer_derive::Lexer; pub use position::Position; pub use lexer::{LexerState, Lexer, StandardLexer, Modification}; pub use token::{TokenType, T...
struct Solution; impl Solution { fn find_poisoned_duration(time_series: Vec<i32>, duration: i32) -> i32 { let n = time_series.len(); if n == 0 { return 0; } let mut start = time_series[0]; let mut res = 0; for i in 1..n { let end = time_series...
use crate::repositories::WithId; use bson::DateTime; use serde::{Deserialize, Serialize}; pub const ID_TYPE_PRINT_ID: &str = "ORIGINAL_PRINT_ID"; pub const ID_TYPE_ORIG_MATTER: &str = "ORIGINATING_MATTER"; #[derive(Serialize, Deserialize)] pub struct AwardAlternateId { pub id: String, #[serde(rename = "type")] ...
mod de; mod error; mod parse; mod ser; pub use crate::de::{from_str, Deserializer}; pub use crate::error::{Error, Result}; pub use crate::parse::parse; pub use crate::ser::{to_string, Serializer};
pub mod grpc_streams { tonic::include_proto!("grpc_streams"); } use grpc_streams::grpc_streams_client::GrpcStreamsClient; use grpc_streams::{Message, Consumer}; #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> { let mut client = GrpcStreamsClient::connect("http://[::1]:10000").await?; ...
/* * Rust tiene un atributo llamado cfg, * el cual nos permite condicionar la compilación * dependiento del sistema operativo ejemplo * */ #[cfg(target_os = "linux")] fn estamos_en_linuuuux(){ println!("Estas dentro del pingüino!!"); } #[cfg(not(target_os = "linux"))] fn estamos_en_linuuuux(){ print!("Dim...
//! Solution to the first puzzle day 2 variant. //! //! Unfortunately, the functionality for day 1 of this puzzle was not retained //! when the solution for day 2 was designed. This problem does not/ will not //! occur in future puzzles. use std::fs::File; use std::io::prelude::*; use regex::Regex; /// Returns the f...
/* --- Day 12: Subterranean Sustainability --- The year 518 is significantly more underground than your history books implied. Either that, or you've arrived in a vast cavern network under the North Pole. After exploring a little, you discover a long tunnel that contains a row of small pots as far as you can see to ...
use winapi::um::wincon::CONSOLE_CURSOR_INFO; /// Represents a `CONSOLE_CURSOR_INFO` which contains information about the console cursor. /// /// link: `https://docs.microsoft.com/en-us/windows/console/console-cursor-info-str` pub struct ConsoleCursorInfo{ /// The percentage of the character cell that is filled by ...
// https://stackoverflow.com/questions/26915472/how-do-i-return-a-reversed-string-from-a-function pub fn reverse(input: &str) -> String { return input .chars() .rev() .collect(); }
struct Solution {} impl Solution { pub fn is_isomorphic(s: String, t: String) -> bool { if s.len() != t.len() { return false; } let s = s.chars().collect::<Vec<char>>(); let t = t.chars().collect::<Vec<char>>(); let mut s_m = std::collections::HashMap::new(); ...
use crate::file::File; use std::path::Path; /// An embedded Directory #[derive(Debug, Copy, Clone, PartialEq)] pub struct Dir { path: &'static str, #[cfg(any(not(debug_assertions), feature = "embed"))] files: &'static [File], } impl Dir { #[cfg(any(not(debug_assertions), feature = "embed"))] #[inl...
#![allow(dead_code, unused_imports, unused_must_use)] use wasmedge_quickjs::*; fn args_parse() -> (String, Vec<String>) { use argparse::ArgumentParser; let mut file_path = String::new(); let mut res_args: Vec<String> = vec![]; { let mut ap = ArgumentParser::new(); ap.refer(&mut file_pat...
#![allow(clippy::unused_io_amount)] #![allow(clippy::map_entry)] use crate::error::*; use crate::program::{ Access as CoreAccess, BlockOp as CoreBlockOp, Extern as CoreExtern, Function as CoreFunction, Number as CoreNumber, OpsDescriptor, Program as CoreProgram, Struct as CoreStruct, Type as CoreType, Valu...
use std::collections::HashMap; pub fn run() { let content = include_str!("input.txt").trim().split("\n"); let mut graph = Graph::new(); for req in content.map(Req::from_line) { graph.add_req(req); } let mut available = graph.init(); while !available.is_empty() { available.sort(); let next = availab...
#![allow(non_upper_case_globals)] #![allow(non_camel_case_types)] #![allow(non_snake_case)] #![feature(static_nobundle)] include!("bindings.rs"); // #[cfg(test)] // mod tests { // use crate::get_tensorrt_version; // }
// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not...
use crate::{chunk::Chunk, chunk_map::ChunkMap}; use cgmath::Vector3; use specs::{Entities, Join, Read, System, WriteStorage}; pub struct UpdateNeighbouringChunks; impl<'a> System<'a> for UpdateNeighbouringChunks { type SystemData = (Read<'a, ChunkMap>, Entities<'a>, WriteStorage<'a, Chunk>); fn run(&mut self...
use cb_rs::cb::client::CbClient; use std::env; fn setup() -> CbClient { let key = String::from("AAAA/AAAAAAAAAAAAAAAA BEES"); let url = env::var("TESTURL").unwrap(); CbClient::new(&key, &url).unwrap() } #[test] fn get_all_device_status() { let client = setup(); let r = client.get_all_devices_stat...
fn main() { aoc_2019_06::part1() }