text
stringlengths
8
4.13M
use super::game::Game; use chashmap::CHashMap; use std::sync::Arc; use std::sync::Mutex; use uuid::Uuid; #[derive(Clone)] pub struct State { games: Arc<CHashMap<Uuid, Game>>, stack: Arc<Mutex<Vec<Uuid>>>, size: usize, } impl State { pub fn insert_and_evict(&self, game: Game) -> Uuid { let uuid...
use bson::{Bson, Document}; use curl::easy::{Easy, List}; use proddle::ProddleError; use std::collections::HashMap; use std::time::Duration; static PREFIXES: [&'static str; 2] = ["", "www."]; pub fn execute(domain: &str, parameters: &HashMap<String, String>) -> Result<Document, ProddleError> { let mut easy: Opt...
use crate::ast::*; use crate::parsing::{ParseError}; use std::cmp::{max}; use Type::*; // TODO: we should probably automatically insert type promotions // and type casting operations in assignments /// Check if a value of one type can be assigned to another fn assign_compat(lhs_type: &Type, rhs_type: &Type) -> bool {...
fn is_congruent(left: i128, right:i128, modulus:i128) -> bool{ (left - right) % modulus == 0 } #[test] fn test_is_congruent() { assert_eq!(is_congruent(3, 0,3), true); } fn main() { println!("congruent - {}", is_congruent(3,0,3)); let heart_eyed_cat = '😻'; println!("cat: {}",heart_eyed_cat)...
pub struct Solution {} impl Solution { pub fn num_islands(grid: Vec<Vec<char>>) -> i32 { if grid.is_empty() { return 0; } let mut grid = grid; let mut cnt = 0; for i in 0..grid.len() { for j in 0..grid[0].len() { if Self::_is_island_th...
struct Solution; impl Solution { fn string_shift(s: String, shift: Vec<Vec<i32>>) -> String { let v: Vec<char> = s.chars().collect(); let mut res = "".to_string(); let n = s.len(); let mut first = 0; for x in shift { let direction = x[0]; let amount =...
//! This crate provides the `jmespath!` macro used to statically //! compile JMESPath expressions. //! //! By statically compiling JMESPath expressions, you pay the cost of //! parsing and compiling JMESPath expressions at compile time rather //! than at runtime, and you can be sure that the expression is valid //! if ...
use tavern_core::{Slot}; use tavern_core::game::santorini::{Move, State, StandardBoard, AIProfile, Depth, HeuristicName}; use aphid::{Milliseconds}; use board_state::BoardState; use tentative::TentativeState; use ai::StateAnalysis; use psyk::game::{Player, Human}; use tavern_core; pub type PlayerSlot = tavern_c...
extern crate cc; extern crate glob; #[cfg(not(feature = "orangepi"))] const TARGET: &'static str = "wiringPi"; #[cfg(feature = "orangepi")] const TARGET: &'static str = "WiringOP"; fn main() { if cfg!(feature = "development") { return; } // only build wiringpi/wiringop for arm/armv7 platforms ...
// Copyright 2020 WHTCORPS INC // // 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 in writing, sof...
ApBegin(RS,CLSID_CALLERLOCATIONAPP) WndBegin(CALLERLOCATIONAPP_WND_MAIN) WdgBegin(CLSID_VTMMENU,MainMenu) VtmCreateMenuRC({IMG_NULL_ID,TXT_LIL_N_CALLER_LOCATION,WDG_MENU_TYPE_NORMAL,WDG_MENU_ITEM_TYPE_TEXT_THEMETEXT,WDG_MENU_CHECK_STYLE_NONE,0,0,0}) VtmCreateMenuDataRC(4,{{{MENUMODEL_ITEM_VI...
use std::ops; use reg::Reg64; mod private { use common::{Rex, Args}; pub trait MemSealed: Clone + Rex + Args {} impl<M> MemSealed for M where M: Clone + Rex + Args {} } pub trait Mem: private::MemSealed {} impl Mem for Pointer {} impl Mem for Ptr<(), (), i8> { } impl Mem for Ptr<(), (), i32> {} impl ...
#[macro_use] extern crate log; use actix_diesel_actor as db; use actix_web::http::{header, Method, NormalizePath}; use actix_web::middleware::identity::{CookieIdentityPolicy, IdentityService}; use actix_web::middleware::session::{CookieSessionBackend, SessionStorage}; use actix_web::{fs, middleware, server, App, HttpR...
#![feature(proc_macro_hygiene, decl_macro)] use std::collections::HashMap; use std::path::{Path, PathBuf}; use include_dir_macro::include_dir; // proc-macro use rocket::{Response, State}; use rocket::http::{ContentType, Status}; struct StaticFiles { files: HashMap<&'static Path, &'static [u8]> } fn expected_...
use serde::{Deserialize, Serialize}; use std::collections::HashMap; #[derive(Deserialize, Debug)] pub struct Paging<T> { pub items: Vec<T>, pub next: Option<String>, } #[derive(Clone, Deserialize, Debug)] pub struct SavedAlbum { pub album: Album, } #[derive(Clone, Deserialize, Debug)] pub struct Album {...
pub type Response = hyper::Response<hyper::Body>; pub struct ResponseBuiler; impl ResponseBuiler { pub fn with_text(text: impl ToString) -> Response { hyper::Response::builder() .header( "Content-type".parse::<hyper::header::HeaderName>().unwrap(), "text/plain; c...
/** * [794] Valid Tic-Tac-Toe State * * Given a Tic-Tac-Toe board as a string array board, return true if and only if it is possible to reach this board position during the course of a valid tic-tac-toe game. The board is a 3 x 3 array that consists of characters ' ', 'X', and 'O'. The ' ' character represents an em...
use ark_mnt6_753::{constraints::G1Var, G1Projective}; use nimiq_pedersen_generators::DefaultWindow; use crate::gadgets::pedersen::{PedersenHashGadget, PedersenParametersVar}; pub type DefaultPedersenParametersVar = PedersenParametersVar<G1Projective, G1Var>; pub type DefaultPedersenHashGadget = PedersenHashGadget<G1P...
/* TODO Increase test coverage */ //use type_name; use token; use common::ParseError as ParseError; use constant::Constant as Constant; use parameter; use parameter::Parameters as Parameters; use parameter::ParameterDefaultValue as ParameterDefaultValue; #[test] fn one_parameter() { let tokens = token...
pub mod tcp; use std::io::{Error, Result}; use std::os::unix::io::{RawFd, AsRawFd, FromRawFd, IntoRawFd}; use std::net::{TcpListener as StdTcpListener, TcpStream as StdTcpStream}; use std::net::{ToSocketAddrs, SocketAddr}; use std::future::Future; use std::pin::Pin; use std::task::{Context, Poll}; use std::rc::Rc; use...
mod heap_allocator; pub fn init() { heap_allocator::init_heap(); }
use crate::{ datastructure::generic::Vec2i, opengl::types::{RGBAColor, RGBColor}, ui::{ frame::{make_inner_frame, Frame}, inputbox::TextRenderSetting, ACTIVE_VIEW_BACKGROUND, }, }; /// POD data type LineTextBox. These do not define behavior in any real sense. They just hold the ...
use crate::utils::tree::TreeNode; use std::cell::RefCell; use std::rc::Rc; pub struct Solution {} impl Solution { pub fn kth_smallest(root: Option<Rc<RefCell<TreeNode>>>, k: i32) -> i32 { let (mut k, mut result) = (k, 0); Self::_kth_smallest(root, &mut k, &mut result); result } fn...
#[macro_use] extern crate diesel; #[macro_use] extern crate diesel_migrations; use std::path::PathBuf; use eyre::{Report, Result, WrapErr}; use futures::stream::{StreamExt, TryStreamExt}; use google_photoslibrary1::PhotosLibrary; use log::LevelFilter; use structopt::StructOpt; use yup_oauth2::{ authenticator::Def...
use chain_core::property::BlockDate as _; use chain_impl_mockchain::{ block::BlockDate, certificate::{Proposal, Proposals, VoteAction, VotePlan}, testing::VoteTestGen, tokens::identifier::TokenIdentifier, vote::{Options, PayloadType}, }; use chain_vote::MemberPublicKey; use std::str::FromStr; pub st...
struct Player{ first_name: String, last_name: String, } impl Player{ fn new(first_name: String, last_name: String) -> Player{ Player{ first_name: first_name, last_name: last_name, } } fn full_name(&self) -> String{ format!("{} {} ", self.first_name, ...
//! Library for spawning pre-configured processes. mod daemon; pub mod logging; pub use daemon::{Daemon, DaemonProcess};
#[derive(Debug,Clone,Copy)] enum Unit { Unknown, Tera, Giga, Mega, Kilo, Byte, } impl Into<&'static str> for Unit { fn into(self) -> &'static str { match self { Unit::Unknown => "??", Unit::Tera => "TB", Unit::Giga => "GB", Unit::Mega ...
use crate::instructions::base::bytecode_reader::BytecodeReader; use crate::instructions::base::instruction::{ Instruction, LocalVarsInstruction, NoOperandsInstruction, }; use crate::runtime::frame::Frame; fn i_load(frame: &mut Frame, index: usize) { let val = frame .local_vars() .expect("local_...
use rayon::prelude::*; use shipyard::*; #[derive(PartialEq, Eq, Debug, Clone, Copy)] struct U32(u32); impl Component for U32 {} #[test] fn filter() { let mut world = World::new_with_custom_lock::<parking_lot::RawRwLock>(); world.track_all::<U32>(); let (mut entities, mut u32s) = world .borrow::<(E...
// Copyright (c) The Libra Core Contributors // SPDX-License-Identifier: Apache-2.0 mod definition; use crate::account::AccountStateBlob; use crate::Result; use crate::hasher::{ CryptoHash, CryptoHasher, SparseMerkleInternalHasher, SparseMerkleLeafHasher, SPARSE_MERKLE_PLACEHOLDER_HASH, HashValu...
// use example::kinds::PrimaryColor; // use example::utils::mixed; // 使用pub use重新导出包结构后,就可以使用直接使用一级目录的结构,不用关心原包中的结构了 use example::PrimaryColor; use example::mixed; fn main(){ let red = PrimaryColor::Red; let yellow = PrimaryColor::Yellow; mixed(red, yellow); }
// Copyright 2015-2019 Parity Technologies (UK) Ltd. // This file is part of Parity Ethereum. // Parity Ethereum 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 Software Foundation, either version 3 of the License, or // (at yo...
use ezmath::*; /// rotation component, to be used(optionally) with the /// Rotation component #[derive(Debug, Clone, Default)] pub struct CRotation(pub float3);
// 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...
/// A rectangle of `f32`s. #[derive(Debug, Copy, Clone, PartialEq)] pub struct Rectangle { /// The X co-ordinate of the rectangle. pub x: f32, /// The Y co-ordinate of the rectangle. pub y: f32, /// The width of the rectangle. pub width: f32, /// The height of the rectangle. pub heigh...
use merkle::{MerkleValue, MerkleNode}; use merkle::nibble::{NibbleVec, Nibble}; use {Change, DatabaseHandle, Error}; use rlp::Rlp; fn find_and_remove_child<'a, D: DatabaseHandle>( merkle: MerkleValue<'a>, database: &'a D ) -> Result<(MerkleNode<'a>, Change), Error> { let mut change = Change::default(); l...
fn test_vec(){ let v = vec![1,2,3,4,5]; /* let first = match v.get(0) { Some(value) => value , _ => 0 , // not works Option<&T> -> &T -> &i32 }; println!("{}", first ); */ if let Some(value) = v.get(0) { println!("{}", value ); } let mut v = vec![1,2,3,4,5]; ...
ApBegin(RS,CLSID_DIALOGAPP) WndBegin(CLSID_DLGCONFIRM) WdgBegin(CLSID_IMAGEWIDGET,ComfirmBgWdg) WdgImageCreateForWndRC({{COMMON_DIALOG_LAYOUT_BG_VER_X,COMMON_DIALOG_LAYOUT_BG_VER_Y},{COMMON_DIALOG_LAYOUT_BG_WIDTH, COMMON_DIALOG_LAYOUT_BG_HEIGHT},IMAGE_STYLE_COMMON, {TRUE, NOTICE_IMG_BG}}) ...
mod utils; use wasm_bindgen::prelude::*; // A macro to provide `println!(..)`-style syntax for `console.log` logging. macro_rules! log { ( $( $t:tt )* ) => { #[cfg(feature = "debug_logging")] web_sys::console::log_1(&format!( $( $t )* ).into()); }; } #[derive(Copy, Clone, Debug, PartialEq, Pa...
use error_chain::error_chain; use ate::prelude::*; use crate::request::*; error_chain! { types { CreateError, CreateErrorKind, ResultExt, Result; } links { QueryError(super::QueryError, super::QueryErrorKind); AteError(::ate::error::AteError, ::ate::error::AteErrorKind); Ch...
use alloc::vec::Vec; use alloc::{alloc::Layout, boxed::Box}; use core::convert::TryFrom; use core::iter::FromIterator; use core::marker::PhantomData; use core::mem::{ManuallyDrop, MaybeUninit}; use core::ops::{Deref, DerefMut}; use core::ptr::{self, NonNull}; use core::sync::atomic::AtomicUsize; use crate::iterator_as...
#[macro_use] extern crate afl; extern crate sacn; use sacn::packet::*; fn main() { fuzz!(|data: &[u8]| { // Key aim is to check that parse does not crash given a wide variety of data. // The specific error or packet produced is not the aim of these tests. let _ = AcnRootLayerP...
use crate::{ core::{algebra::Vector4, color::Color, pool::Handle}, define_constructor, grid::{Column, GridBuilder, Row}, message::{MessageDirection, UiMessage}, numeric::{NumericType, NumericUpDownMessage}, vec::{make_mark, make_numeric_input}, BuildContext, Control, NodeHandleMapping, UiNod...
use std::iter::Iterator; use peekmore::{PeekMore, PeekMoreIterator}; use super::{Token, Primitive, Complex, Real, Located, Location, LexerError, ToLocated}; pub struct Lexer<CharIter: Iterator<Item = char>> { char_stream: PeekMoreIterator<CharIter>, advance_location: Location, peek_location: Location, } ...
use color::{Color, rgba}; use units::{Length, Px, Em, Pt}; use netsurfcss::util::css_fixed_to_float; use core::either::{Either, Left, Right}; use n; use values::*; pub struct ComputedStyle { inner: n::c::CssComputedStyle<'self> } pub impl<'self> ComputedStyle<'self> { // CSS 2.1, Section 8 - Box model p...
#[doc = "Register `CFG2` reader"] pub struct R(crate::R<CFG2_SPEC>); impl core::ops::Deref for R { type Target = crate::R<CFG2_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<CFG2_SPEC>> for R { #[inline(always)] fn from(reader: crate::R<CFG2_SP...
// Copyright (c) IxMilia. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. extern crate dxf; use self::dxf::*; use self::dxf::entities::*; use self::dxf::enums::*; use self::dxf::objects::*; extern crate image; use self::image::{ ...
use std::{ future::Future, pin::Pin, sync::Arc, task::{Context, Poll, RawWaker, RawWakerVTable, Waker}, }; pub struct EmulatorWaker {} fn emulatorwaker_wake(s: &EmulatorWaker) {} fn emulatorwaker_clone(s: &EmulatorWaker) -> RawWaker { let arc = unsafe { Arc::from_raw(s) }; std::mem::forget(ar...
#[macro_use] extern crate serde_derive; extern crate rmp_serde as rmps; use std::collections::BTreeMap; use serde_bytes::ByteBuf; use rmpv::decode; use rmpv::ext::deserialize_from; use rmpv::ValueRef; /// Tests that a `ValueRef` is properly decoded from bytes using two different mechanisms: direct /// deserializati...
use super::*; use super::super::super::core::memory::*; use super::super::super::core::memory::ioreg::IORegister16; use super::super::super::core::memory::ioreg::IORegister32; use ::util::measure::*; // This is here temporarily so that I don't lose my mind. macro_rules! kbytes { ($n: expr) => ($n * 1024) } // BG M...
use clap::*; use colored::*; use std::collections::HashMap; use std::fs::File; use std::io::SeekFrom; use std::io::{self, prelude::*, BufReader, Seek}; use std::{thread, time}; const APP_VERSION: &str = "0.5.1"; pub enum PrintColor { Black, Red, Green, Yellow, Blue, Magenta, Cyan, Whit...
use crate::dtos::{ServiceDTO, ServiceResourceDTO, ServiceWithUsersDTO}; use nettu_scheduler_domain::{ BusyCalendar, Service, ServiceResource, ServiceWithUsers, TimePlan, Tz, ID, }; use serde::{Deserialize, Serialize}; #[derive(Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct ServiceResponse {...
use std::sync::Arc; use rand::thread_rng; use crate::bounding_box::BBox; use crate::bvh::BVHNode; use crate::material::Material; use crate::point3::Point3; use crate::ray::Ray; use crate::vec3::Vec3; pub struct HitRecord { pub point: Point3, pub normal: Vec3, pub t: f64, pub front_face: bool, pub...
use chrono::{DateTime, Utc}; use serde::{Deserialize, Serialize}; use std::collections::HashMap; #[derive(Debug, Clone, Default, Deserialize, Serialize)] pub struct UpdateChannelRequest { pub channel: UpdateChannel, } #[derive(Debug, Clone, Default, Deserialize, Serialize)] pub struct UpdateChannel { #[serde(...
use log::debug; use std::fs::File; use std::io::{BufRead, BufReader}; use std::result::Result as StdResult; type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>; #[derive(PartialEq)] enum Valid { Invalid, Present, Valid, } impl std::default::Default for Valid { fn default() -> Self { ...
use super::super::{AssignedBits, RoundWord, RoundWordA, RoundWordE, StateWord, ROUND_CONSTANTS}; use super::{compression_util::*, CompressionConfig, State}; use halo2_proofs::{circuit::Region, pasta::pallas, plonk::Error}; impl CompressionConfig { #[allow(clippy::many_single_char_names)] pub fn assign_round( ...
//! //! A collection of light types. //! Currently implemented light types are ambient light, directional light, spot light and point light. //! Directional and spot lights can cast shadows. //! mod directional_light; #[doc(inline)] pub use directional_light::*; mod spot_light; #[doc(inline)] pub use spot_light::*; ...
use thiserror::Error; use crate::common::{ self, Assign, Binary, Call, Expr, Func, If, Logical, Operator, Stmt, Token, TokenKind, Unary, While, }; use std::sync::atomic::{AtomicUsize, Ordering}; #[derive(Debug, Error)] pub enum ParseError<'a> { #[error("Reached end of file")] EOF, #[error("Error...
use crate::error::UserServerError; use chrono::Local; use jsonwebtoken::{decode, encode, Algorithm, DecodingKey, EncodingKey, Header, Validation}; use once_cell::sync::Lazy; use serde::{Deserialize, Serialize}; static JWT_SECRET_KEY: Lazy<String> = Lazy::new(|| std::env::var("JWT_SECRET_KEY").expect("未设置 JWT_SECRE...
use crate::node::discovery::{NodeDiscoveryData, NodeDiscoveryProvider, NodeDiscoveryState}; use crate::utils::path_append; use crate::{actor, utils}; use act_zero::{Actor, ActorError, ActorResult, Addr, Produces, WeakAddr}; use anyhow::Context; use async_trait::async_trait; use futures::TryFutureExt; use std::fmt; use ...
use crate::Error; use super::super::Input; use super::choice::Choice; use super::message::Message; #[derive(Clone, Debug)] pub(crate) enum Segment { Text(Message), Choices(Vec<(Choice, Vec<Segment>)>), } impl Segment { pub(crate) fn is_empty(&self) -> bool { match self { Segment::Text...
use crate::owned; /// Tests if all elements of the iterator are equal to each other. /// /// An empty iterator returns `true`. /// /// `uniform()` is short-circuiting. It will stop processing as soon /// as it finds two pairwise inequal elements. fn uniform<I, E>(iter: I) -> bool where I: IntoIterator<Item = E>, ...
#![no_std] #![warn(missing_docs)] //! This crate gives small utilities for casting between plain data types. //! //! ## Basics //! //! Data comes in five basic forms in Rust, so we have five basic casting //! functions: //! //! * `T` uses [`cast`] //! * `&T` uses [`cast_ref`] //! * `&mut T` uses [`cast_mut`] //! * `&[...
#[doc(hidden)] #[macro_export] macro_rules! uprint_fmt { ($($tt:tt)*) => { { use $crate::_export::{ ufmt_write::uWrite, ufmt, }; // failures aren't interesting to us let _ = $crate::_export::ufmt::uwrite!(&$crate::LOGGER, $($tt)...
fn main() { let mut stri: String = String::new(); std::io::stdin().read_line(&mut stri).unwrap(); let mut stri1: String = String::new(); std::io::stdin().read_line(&mut stri1).unwrap(); let stri: String = stri.trim().to_lowercase(); let stri1: String = stri1.trim().to_lowercase(); use std::{...
use std::io::Write; use serde; use std; #[allow(deprecated)] mod error { use serde; use std; error_chain!{ errors { Unsupported(method: &'static str) } foreign_links { Io(::std::io::Error); Xml(::serde_xml_rs::Error); } } impl serde::ser::Error for Error { fn custom<T: std::fmt::Display>...
use std::ops::{Sub, Mul, Neg}; use num::{Zero, One}; use traits::structure::{Cast, Row, Basis, BaseFloat}; use traits::geometry::{Norm, Cross, CrossMatrix, RotationTo, UniformSphereSample}; use structs::vec::{Vec1, Vec2, Vec3, Vec4}; use structs::mat::Mat3; use structs::rot::{Rot2, Rot3}; impl<N: BaseFloat> RotationTo...
use murundiri::{config::*, hashmap_populate as hashmap}; use serde_json::json; use std::{fs, str::from_utf8}; #[test] fn test_that_config_is_parsed() { let book_rule = Rule { ttl: default_ttl(), action: RuleAction::default(), fields: RuleFields { body: Some(["trx_id".to_string()...
// Copyright 2019-2020 Thales Inc. // This file is part of Thales. // Thales 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 Software Foundation, either version 3 of the License, or // (at your option) any later version. // Th...
/* Copyright © 2020, Jason Ekstrand * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish,...
use docopt::Docopt; use fileinput::FileInput; use libc::consts::os::posix88::STDOUT_FILENO; use libc::funcs::posix88::unistd; use std::io; use std::io::{BufRead, Write, BufReader}; use std::num::ParseIntError; use haproxy::LogEntry; const MAX_LINE_LENGTH: usize = 1024; static USAGE: &'static str = " Print selected ...
use crate::errors::Result; use crate::errors::*; use snafu::{ OptionExt, ResultExt }; use std::env::var; use std::ffi::OsStr; use std::fs::{read_dir, read_to_string}; use std::path::PathBuf; pub fn get_all_sql_paths() -> Result<Vec<PathBuf>> { let path = var("migration_path").unwrap_or("src/migrations".to_string()...
use super::attributes::{ check_strong_enum_attributes, check_struct_attributes, check_transparent_attributes, check_weak_enum_attributes, parse_child_attributes, parse_container_attributes, }; use super::rename_all; use proc_macro2::TokenStream; use quote::quote; use syn::punctuated::Punctuated; use syn::token:...
//! @brief Account state access use { crate::utils::txn_utils::get_account_for, sol_template_shared::unpack_from_slice, solana_client::rpc_client::RpcClient, solana_sdk::{commitment_config::CommitmentConfig, signature::Keypair, signer::Signer}, std::{collections::BTreeMap, error::Error}, }; /// Un...
fn main() { println!("cargo:rustc-flags=-lgcc_s"); cc::Build::new() .file("src/img/crc.c") .compile("crc"); }
//extern crate libc; #[macro_use] extern crate lazy_static; extern crate time; extern crate toml; #[macro_use] extern crate serde_derive; extern crate serde_json; extern crate serde; #[macro_use] extern crate log; extern crate env_logger; extern crate resp; extern crate chrono; extern crate websocket; ext...
// 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...
#![cfg_attr(not(feature = "std"), no_std)] pub use pallet::*; #[frame_support::pallet] pub mod pallet { //! A demonstration of an offchain worker that sends onchain callbacks use core::{convert::TryInto}; use parity_scale_codec::{Decode, Encode}; use frame_support::pallet_prelude::*; use frame_system::{ pallet...
use std::fmt::Debug; fn print_slice<T: Debug>(slice: &[T]) { println!("{:?}", slice); } fn main() { println!("{:?}", "array_slicing"); let array:[u8; 5] = [1,2,3,4,5]; println!("{:?}", "whole array just burrowed"); print_slice...
// Copyright 2020 WHTCORPS INC // // 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 in writing, sof...
// OpenAOE: An open source reimplementation of Age of Empires (1997) // Copyright (c) 2016 Kevin Fuller // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including wi...
use std::io::*; use std::str::FromStr; // Quoted from https://qiita.com/penguinshunya/items/cd96803b74635aebefd6 fn input<T: FromStr>() -> T { let mut s = String::new(); stdin().read_line(&mut s).ok(); s.trim().parse().ok().unwrap() } fn main() { let n: String = input(); let mut digsum: i64 = 0; for cha i...
pub mod registry_list; pub mod spsc_queue;
#[test] fn test_zip_writer() -> Result<(), crate::error::OoxmlError> { use std::io::Write; // We use a buffer here, though you'd normally use a `File` //let mut buf = [0; 65536]; //let mut zip = zip::ZipWriter::new(std::io::Cursor::new(&mut buf[..])); let file = std::fs::File::create("tests/test.zi...
use std::cmp::Ordering; struct Node<K, V> where K: Ord, { key: K, value: V, left: Option<Box<Node<K, V>>>, right: Option<Box<Node<K, V>>>, } #[derive(Default)] pub struct Tree<K, V> where K: Ord, { root: Option<Node<K, V>>, } impl<K, V> Tree<K, V> where K: Ord, { pub fn insert(&mu...
use std::io; // allows us to take user input using the `io` library fn main() { println!("Guess the number!"); println!("Pleae inpurt your guess."); let mut guess = String::new(); // :: denotes that new() is a associated function/static method/class method of String class io::stdin().read_line(&mut ...
/** * [934] Shortest Bridge * * You are given an n x n binary matrix grid where 1 represents land and 0 represents water. An island is a 4-directionally connected group of 1's not connected to any other 1's. There are exactly two islands in grid. You may change 0's to 1's to connect the two islands to form one islan...
//@compile-flags: -Zmiri-permissive-provenance #![feature(ptr_sub_ptr)] use std::{mem, ptr}; fn main() { smoke(); test_offset_from(); test_vec_into_iter(); ptr_arith_offset(); ptr_arith_offset_overflow(); ptr_offset(); } fn smoke() { // Smoke-test various offsetting operations. let ptr...
use std::ops::Deref; use super::*; #[derive(Clone, Copy, Debug)] pub struct RotScale3(Option<A3<F3>>); impl One for RotScale3 { const ONE: Self = Self(None); } impl RotScale3 { #[inline(always)] pub const fn new(r1: F3, r2: F3, r3: F3) -> Self { Self(Some(A3(r1, r2, r3))) } #[inline(alw...
use std::fmt; use std::cmp; fn main() { let mut seq1: String = String::new(); let mut seq2: String = String::new(); println!("Enter two DNA sequences: "); let stdin = std::io::stdin(); stdin.read_line(&mut seq1) .expect("Failed to read sequence #1 from buffer!"); stdin.read_line(&mut...
extern crate num; extern crate num_complex; extern crate rand; extern crate sample; extern crate rustfft; // Declare local mods pub mod complex; pub mod periodic; pub mod polynomial; pub mod spectrum; pub mod waves; pub mod error; use sample::{Sample, Signal, signal}; use sample::conv::Duplex; use sample::window::Typ...
use tokio::io; use serde::de::DeserializeOwned; use crate::AsyncReaderBuilder; use crate::byte_record::{ByteRecord, Position}; use crate::error::Result; use crate::string_record::StringRecord; use super::{ AsyncReaderImpl, DeserializeRecordsStream, DeserializeRecordsIntoStream, DeserializeRecordsStreamPos,...
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use std::borrow::Cow; use std::ffi::OsStr; use antlir2_compile::plan::Plan; use antlir2_compile::CompileFeature; use clap::Parse...
mod perspective; use crate::geometry::*; use crate::image::*; use crate::sampler::*; pub use perspective::Perspective; pub enum CameraType { Perspective(Perspective), } pub trait CameraModel { fn ray_at(&self, point: F2, sampler: &mut Sampler) -> R; } pub struct Camera { pub resolution: I2, model: ...
use serenity::framework::standard::{macros::command, CommandResult}; use serenity::model::prelude::*; use serenity::prelude::*; use crate::store::message_store::MessageStore; #[command] async fn show_message(ctx: &Context, msg: &Message) -> CommandResult { let message_lock = { let data_read = ctx.data.rea...
use super::{action::*, ai::*, events::*, fov::*, player::*}; use specs::{prelude::*, storage::BTreeStorage}; #[derive(Component, Debug)] #[storage(BTreeStorage)] pub struct HunterBrain { state: HunterState, laziness: u32, } #[derive(Debug)] enum HunterState { Idle, Hunting, Satisfied(u32), } imp...
extern crate proc_macro; #[macro_use] extern crate syn; #[macro_use] extern crate quote; extern crate proc_macro2; extern crate tracing; use proc_macro::TokenStream; use proc_macro2::Span; use syn::token::{Async, Const, Unsafe}; use syn::{Abi, ArgCaptured, Attribute, Block, FnArg, Ident, ItemFn, Pat, PatIdent, Visibil...
pub fn line_search<T>(arr: &[T], target: &T) -> Option<usize> where T: PartialOrd, { for (index, item) in arr.iter().enumerate() { if item == target { return Some(index); } } None } pub fn line_search_v2<T>(arr: &[T], target: &T) -> Option<usize> where T: PartialOrd, { ...
use crate::es::StoredMessage; use crate::opt::{EsConfig, RmqConfig}; use failure::Error; use futures::{future, Future}; use serde_json; use std::convert::AsRef; use std::fs::{create_dir, read_dir, remove_dir_all}; use std::io::Read; use std::path::{Path, PathBuf}; use tokio::fs::file::File; use toml; pub trait Export ...