text
stringlengths
3.09k
13.9k
// Copyright Rivtower Technologies LLC. // // 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 ...
use crate::base58; use crate::constant::*; use crate::secret::SecretKey; use crate::signature::Signature; use crate::{error, hash}; use alloc::format; use alloc::string::String; use alloc::vec::Vec; use bitcoin_hashes::{sha256, Hash as HashTrait}; use core::{fmt, str::FromStr}; /// A Secp256k1 public key #[derive(Clon...
// 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. use { anyhow::{Context as _, Error}, async_trait::async_trait, fidl_fidl_test_components as ftest, fidl_fuchsia_io as fio, fuchsia_async as fas...
use crate::{ config::Config, database::{DbConn, schema::users}, errors::*, i18n::L10n, models::user::AvatarProvider, routes::web::{context, Rst, OptionalWebUser, Session}, utils::{email, AcceptLanguage, HashedPassword, Validator}, }; use chrono::Utc; use diesel::{dsl::count, prelude::*}; use rocket::{ ...
mod utils; use bitcoincore_rpc::RpcApi; use tracker::bag_id::BagId; use tracker::bitcoin_client::BitcoinMintExt; use tracker::record::BidProof; use tracker::storage::memory::BidMemoryStorage; use tracker::storage::BidStorage; use tracker::Index; use utils::*; const GENERATED_BLOCKS: u64 = 120; // Wait 2 seconds or un...
use crate::builders::{CrateBuilder, VersionBuilder}; use crate::util::{MockAnonymousUser, RequestHelper, TestApp}; use cargo_registry::views::EncodableVersionDownload; use chrono::{Duration, Utc}; use http::StatusCode; #[derive(Deserialize)] struct Downloads { version_downloads: Vec<EncodableVersionDownload>, } f...
use std::cmp::Ordering; use std::collections::BTreeMap; use std::collections::HashMap; use std::error::Error; use std::fmt; use scraper::{Html, Selector}; pub type RssIndexResult<T> = Result<T, Box<dyn Error>>; #[derive(Debug)] pub enum RssIndexError { ArgsError, UrlError, ScraperError, } impl fmt::Disp...
//! A convenient position + orientation + scale container, backed by two `Vec3` and a `Quaternion.` macro_rules! transform_complete_mod { ($mod:ident) => { // WISH: // forward_rh, forward_lh, etc etc // look_at // rotate_around use std::ops::{Add, Mul}; use $crate:...
use ic_certified_vars::{verify_certificate, CertificateValidationError}; use ic_crypto_tree_hash::{LabeledTree, MixedHashTree}; use ic_interfaces::registry::RegistryTransportRecord; use ic_registry_transport::pb::v1::{ registry_mutation::Type, CertifiedResponse, RegistryAtomicMutateRequest, }; use ic_types::{crypto...
use log::debug; use crate::durability::Durability; use crate::runtime::ActiveQuery; use crate::runtime::Revision; use crate::Cycle; use crate::DatabaseKeyIndex; use std::cell::RefCell; use std::sync::Arc; /// State that is specific to a single execution thread. /// /// Internally, this type uses ref-cells. /// /// **...
use mlua::{prelude::LuaResult, Lua}; use neovim::Api; use crate::completion::CompletionItem; use crate::settings::ui::border::Border; use crate::ui::WindowPosition; #[derive(Debug)] pub struct CompletionMenu { /// The handle of the buffer used to show the completion items. It is set /// once on initialization...
// Same as contour7 but using RidgedMulti noise function for the elevation map // // cargo run --release --example contours9 -- --loops 10 // cargo run --release --example contours9 -- --grid 400 --octaves 2 --frequency 1.1 --lacunarity 4.0 --persistence 0.3 --noise-scale 1000 --n-contours 80 --seed 44132.94229140888 -...
use crate::utils::read_from_file; use anyhow::Result; use itertools::{iproduct, Itertools}; use regex::Regex; // https://adventofcode.com/2021/day/22 type Point = (i64, i64, i64); type Cube = (Point, Point); type Command = (bool, Cube); pub fn read_input(args: &crate::File) -> Result<Vec<Command>> { let line_par...
use std::fs; use std::path::PathBuf; use std::time::Duration; use clap::Clap; use rand::distributions::Alphanumeric; use rand::Rng; use tokio::task::LocalSet; use orion::kdf::SecretKey; use std::future::Future; use std::net::SocketAddr; use std::pin::Pin; use std::sync::Arc; use tako::common::error::DsError; use tako...
//! This bit of code is used to generate the expansion tests for the crate. It it also a good //! example of what the crate is capable of. //#![feature(proc_macro_hygiene)] #[macro_use] extern crate log; extern crate stderrlog; extern crate iref; #[macro_use] extern crate static_iref; #[macro_use] extern crate iref_e...
//! unicode_divide module use std::io; use std::io::{Seek, SeekFrom}; use unicode_width::UnicodeWidthChar; /// Unicode String Divider pub struct UnicodeStrDivider<'a> { inner: &'a str, // raw str prev_pos: usize, pos: usize, // array index width: usize, // display width at once } impl<'a> UnicodeSt...
//! To run this code in your own project, first install it: //! //! cargo install rusty_engine --example collider //! //! Then run it in your own project (with the asset pack present) with an image //! placed somewhere in your `assets/` directory. //! //! collider assets/some_image.png //! //! Of course, you co...
use std::io::BufReader; use std::io::BufRead; use std::fs::File; use std::vec::Vec; fn main() { let v = read_basic_info(); for e in v { println!("{:?}", e); } } #[derive(Debug)] struct Cpuinfo { n : u32, vendor : String, cpu_family : u32, model : u32, model_name : String, ...
use clap::{App, Arg, SubCommand}; use policyd_rate_limit::queries; use std::error::Error; use std::io::Write; use std::io::{BufRead, BufReader}; use std::os::unix::net::{UnixListener, UnixStream}; use std::process; use std::thread; #[derive(Debug, Default, Clone)] pub struct CreateUser { limit: Option<usize>, ...
//! Convenience methods for a `SenderQueue` wrapping a `DynamicHoneyBadger`. use std::collections::BTreeSet; use std::result; use crate::crypto::PublicKey; use rand::Rng; use serde::{de::DeserializeOwned, Serialize}; use super::{ Error, Message, SenderQueue, SenderQueueableConsensusProtocol, SenderQueueableMessa...
extern crate argparse; use argparse::{ArgumentParser, Store}; extern crate tiny_http; use std::str::FromStr; use std::fs::{self, File}; use std::path::{self}; use std::vec::Vec; struct Config { port_number: u16, working_dir: path::PathBuf, } fn main() { let config = init_config(); match check_conf...
use std::collections::BTreeSet; use std::sync::Arc; use std::time::Duration; use maplit::btreeset; use openraft::Config; use openraft::NodeId; use openraft::State; use tracing_futures::Instrument; use crate::fixtures::RaftRouter; #[tokio::test(flavor = "multi_thread", worker_threads = 6)] async fn change_membership_...
use core::ops::RangeInclusive; /// Information associated with a sketch parameter. /// /// This metadata can be used to set sketch parameter values, generate controls /// in other crates, etc. #[derive(Clone)] pub struct ParamMetadata { /// A unique id that can be used in the mut accessor funtions pub id: u64,...
#![deny(overflowing_literals)] #![feature(proc_macro, proc_macro_gen, lang_items)] #![no_std] // For custom start #![feature(start)] extern crate panic_abort; extern crate cortex_m; extern crate cortex_m_rtfm as rtfm; extern crate cortex_m_semihosting; extern crate lpc1347_rtfm3 as lpc; #[macro_use(exception)] exter...
//! OpenGL implementation of a device, striving to support OpenGL 2.0 with at //! least VAOs, but using newer extensions when available. #![allow(missing_docs, missing_copy_implementations)] #[macro_use] extern crate log; extern crate gfx_gl as gl; extern crate gfx_hal as hal; extern crate smallvec; #[cfg(feature = "...
// Copyright 2020-2021, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME> // SPDX-License-Identifier: MIT OR Apache-2.0 use std::{ net::{IpAddr, Ipv4Addr, Ipv6Addr}, ops::Deref, }; use chrono::{NaiveDateTime, Utc}; use namib_shared::{ macaddr::{MacAddr, SerdeMacAddr}, models::{DhcpLeaseInformation, DhcpL...
mod gen; use std::collections::HashMap; use std::fs::File; use std::hash::BuildHasher; use std::io::{self, BufWriter}; use std::path::Path; use std::rc::Rc; use std::str::FromStr; use ast::{BuiltinFn, StorageClass, VarQualifier}; use clap::Parser; use eyre::{bail, eyre}; use hashers::fx_hash::FxHasher; pub use gen::...
extern crate regex; use rt::{JsEnv, JsValue, JsString, GC_REGEXP}; use rt::validate_walker_field; use gc::*; use self::regex::Regex; use util::manualbox::ManualBox; use ::{JsResult, JsError}; use std::mem::{transmute, zeroed, size_of}; // Modifications to this struct must be synchronized with the GC walker. #[repr(C)...
use beacon_chain::{BeaconChain, BeaconChainTypes}; use bls::PublicKey; use futures::Future; use grpcio::{RpcContext, RpcStatus, RpcStatusCode, UnarySink}; use protos::services::{ActiveValidator, GetDutiesRequest, GetDutiesResponse, ValidatorDuty}; use protos::services_grpc::ValidatorService; use slog::{trace, warn}; us...
// Copyright (c) SimpleStaking and Tezedge Contributors // SPDX-License-Identifier: MIT use std::fs::File; use std::io::BufRead; use std::path::Path; use std::{collections::HashMap, convert::TryFrom}; use std::{env, io}; use itertools::Itertools; use lazy_static::lazy_static; use crypto::hash::{BlockHash, HashType};...
//! Types and functions for building transparent transaction components. use std::fmt; use crate::{ legacy::TransparentAddress, transaction::components::{ amount::Amount, transparent::{self, Authorization, Authorized, Bundle, TxIn, TxOut}, }, }; #[cfg(feature = "transparent-inputs")] use ...
// This file is part auf the dual-kawase-demo package. // // (c) 2019 <NAME> // // For the full copyright and license information, please view the README.md file // that was distributed with this source code. // use std::ops::{Deref, DerefMut}; use gl::types::{GLint, GLuint, GLvoid}; use super::{ArrayBuffer, Element...
use std::cmp::min; use std::intrinsics::copy_nonoverlapping; use std::ops::Deref; use crate::errors::ANTLRError; use crate::int_stream::{IntStream, IterWrapper}; use crate::token::{OwningToken, Token, TOKEN_EOF, TOKEN_INVALID_TYPE}; use crate::token_source::TokenSource; pub trait TokenStream: IntStream { fn lt(&m...
use crate::runtime::execution::Execution; use crate::runtime::task::TaskId; use crate::runtime::thread::continuation::{ContinuationPool, CONTINUATION_POOL}; use crate::scheduler::metrics::MetricsScheduler; use crate::scheduler::{Schedule, Scheduler}; use crate::Config; use std::cell::RefCell; use std::panic; use std::r...
use proc_macro2::{Span, TokenStream}; use quote::{quote, ToTokens}; use syn::{ parse::{Parse, ParseStream, Result}, parse_quote, token::{Colon, Pub}, Field, Fields, Ident, ItemEnum, ItemStruct, Token, Type, VisPublic, Visibility, }; use crate::fsm::{ events::Events, machine_context::MachineContext,...
#![allow(dead_code)] use std::{ fs::File, io::{Read, Seek, Write}, path::Path, sync::mpsc, vec, }; use reqwest::{ blocking::{Client, Response}, header::*, }; use threadpool::ThreadPool; pub struct ConfigBuilder { url: reqwest::Url, connections: usize, threads: u8, singleco...
use rand::Rng; use crate::ball::{Ball, Direction}; use crate::paddle::Paddle; pub struct Manager { widht: i32, height: i32, ball: Ball, player1: Paddle, player2: Paddle, score1: u32, score2: u32, quit: bool, } const OFFSET_PADDLE: i32 = 2; const OFFSET_WITH_PADDLE_LENGTH: i32 = 8; con...
#[macro_use] extern crate enum_primitive; #[macro_use] extern crate serde_derive; extern crate slog; #[macro_use] extern crate slog_scope; mod context; mod controller; mod diagnostics; mod editor_transport; mod general; mod language_features; mod language_server_transport; mod position; mod project_root; mod session; ...
// (C) COPYRIGHT 2018 TECHNOLUTION BV, GOUDA NL // 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 // exce...
use {anyhow::Context, url::Url}; use zkabacus_crypto::{CustomerBalance, MerchantBalance, PaymentAmount}; use zeekoe::merchant::config::Approver; /// Ask the specified approver to approve the payment amount and note (or not), returning either /// `Ok` if it is approved, and `Err` if it is not approved. /// /// Approv...
#![cfg_attr(feature = "cargo-clippy", allow(mut_from_ref, wrong_self_convention))] pub extern crate libweston_sys; pub extern crate wayland_sys; pub extern crate wayland_server; pub extern crate input_sys; pub extern crate xkbcommon; pub extern crate libc; pub extern crate vsprintf; #[macro_use] extern crate foreign_ty...
use std::path::Path; use std::io::BufWriter; use std::io::Write; use std::fs::File; use byteorder::{WriteBytesExt, NativeEndian as NE}; use crate::util::*; use crate::dictionary::build::*; use log::debug; /// 形態素の連接コスト表のバイナリデータを作成する /// # Arguments /// * `input_dir` - ソース辞書があるディレクトリ。input_dir+"/matrix.def" ファイルが使用され...
#![feature(result_flattening)] #![feature(is_some_with)] mod tester; use same_file::is_same_file; use tester::TestError; use tr_lang::mem::Map; use tr_lang::mem::Object; use std::process::exit; use std::collections::HashMap; use std::error::Error; use bunt; use serde::Deserialize; use serde_yaml as yml; use serde_y...
extern crate piston_window; extern crate libnx_rs_window; extern crate input as einp; mod support; use self::libnx_rs_window::NxGlWindow; use self::libnx_rs_window::LibnxButtonId; use self::piston_window::{PistonWindow, UpdateEvent, Window, WindowSettings}; use self::piston_window::{Flip, G2d, G2dTexture, Texture, T...
/***************************************************************************************************************** This source file implements Plonk prover polynomial evaluations primitive. *****************************************************************************************************************/ use ark_ff::...
extern crate clap; extern crate rust_decimal; use std::{fs::File, path::Path}; use crate::{ config::{self, ClientConfig, Config, UserConfig}, db::{self, AmsInfo, TaxDb}, error::{self, Error, UserErrorKind}, format::printer::{FdfPrinter, JsonPrinter, PdfPrinter, Printer, XfdfPrinter}, format::Outpu...
#![warn( clippy::cast_lossless, clippy::checked_conversions, clippy::copy_iterator, clippy::default_trait_access, clippy::doc_markdown, clippy::empty_enum, clippy::enum_glob_use, clippy::expl_impl_clone_on_copy, clippy::explicit_into_iter_loop, clippy::explicit_iter_loop, cli...
//! # Manage persistence of sandboxes //! This module gives basic helpers to save / load your sandboxes //! in a `.ai` file. //! This is very much WIP and subject to change. use std::path::Path; use std::path::PathBuf; use crate::config; use crate::config::CONDUCTOR_CONFIG; /// Save all sandboxes to the `.ai` file in...
//! An interface for dealing with the kinds of parallel computations involved in //! `bellman`. It's currently just a thin wrapper around [`rayon`] but may be //! extended in the future to allow for various parallelism strategies. #[cfg(feature = "multicore")] mod implementation { use std::sync::atomic::{AtomicUsi...
#![feature(test)] extern crate test; #[macro_use] extern crate lazy_static; use intcode; use std::cmp::Ordering; use std::convert::TryFrom; use std::fmt; use std::iter; lazy_static! { pub static ref ISTRUCTIONS: Vec<intcode::Memory> = intcode::parse(include_str!("../data.txt")); } #[derive(Debug, PartialEq)] pu...
use std::cmp::Ordering; use std::collections::HashSet; use std::convert::TryInto; use std::fmt::Write; use crate::GenericIfDataTaggedItem; use crate::specification::BlockInfo; #[derive(Debug)] pub(crate) struct Writer { indent: usize, outstring: String, } pub(crate) struct TaggedItemInfo<'a> { tag: &'a s...
use futures::future; use std::io::prelude::*; use std::io::Result; use tokio_modbus::prelude::*; use tokio_modbus::server::*; use std::sync::{Arc, Mutex}; type Address = u16; type Coil = bool; type Word = u16; pub struct MbServer { pub coils: Vec<Coil>, pub discrete_inputs: Vec<Coil>, pub input_registers...
use crate::deck::{Card, Rank}; use std::default::Default; pub const DECK_LEN: u16 = 52; pub trait CountSystem { fn card_value(&self, card: Card) -> i16; fn cards_value(&self, cards: &[Card]) -> i16 { cards.iter().fold(0, |acc, &c| acc + self.card_value(c)) } } #[derive(Default)] pub struct HiLo; ...
// Test helper to create a temporary k3d cluster for kube-rs. // https://github.com/clux/kube-rs/issues/382 #![allow(dead_code)] use std::{convert::TryFrom, process::Command}; use kube::{config::Kubeconfig, Client, Config}; #[derive(Debug, Default)] pub struct TestEnv { // The name of the temporary cluster. ...
use crate::errors::AppError; use crate::ConnType; use crate::models::schema::{ cpustats::dsl::*, cputimes::dsl::*, disks::dsl::*, hosts::{ self, dsl::{hosts as dsl_host, uuid, *}, }, ioblocks::dsl::*, ionets::dsl::*, loadavg::dsl::*, memory::dsl::*, swap::dsl::*,...
use std::collections::HashMap; use vek::Vec3; type TParsed = Vec<TParsedSub>; type TParsedSub = Vec<Step>; pub fn day(input: String) -> (i32, usize) { let parsed_input = parse(&input); let (p1_result, p1_output) = part_1(&parsed_input); (p1_result, part_2(p1_output)) } fn part_1(input: &TParsed) -> (i32,...
use bevy::prelude::Color; use rand::{rngs::StdRng, Rng}; #[derive(Debug)] pub struct Star { // 1.0 = Mass of our sun pub mass: f32, } #[derive(Debug, PartialEq, Eq, Hash, Copy, Clone, PartialOrd, Ord)] pub enum StarClass { O, B, A, F, G, K, M, WhiteDwarf, } #[allow(dead_code)]...
use anyhow::Result; use cookie::Cookie as RawCookie; use cookie_store::{Cookie, CookieStore, CookieStoreRwLock}; use openapiv3::{OpenAPI, Operation, Parameter as OParameter, ReferenceOr, SecurityScheme}; use reqwest::Url; use specifications::common::Value; use std::{collections::HashMap, sync::Arc}; use crate::{build, ...
use std::{ collections::hash_map::RandomState, hash::{BuildHasher, Hash, Hasher}, marker::PhantomData, }; use crate::linked_map::LinkedHashMap; use crate::{cache::Cache, null_hasher::BuildNullHasher}; /// Stores an element in the cache with the handle to its position in /// the eviction queue. struct Sto...
use crate::verifications::context::{verify_tx_context, TxContext, TxContextInput}; use crate::verifications::eip712::{traits::EIP712Encode, types::EIP712Domain}; use alloc::vec; use core::result::Result; use gw_state::{ckb_smt::smt::Pair, constants::GW_MAX_KV_PAIRS, kv_state::KVState}; use gw_types::{ packed::{Chal...
use {Ctx, Handler}; use anymap::AnyMap; use futures::{Future, IntoFuture}; use hyper::{Method, Request, Response}; use param::FromParameters; use pattern::{CompiledPatternSet, Pattern, PatternSet}; use std::error::Error; use std::sync::Arc; use util::{Control, HttpMethodMap}; use vec_map::VecMap; macro_rules! check_pa...
use std::io; use crate::common::{BinarySerializable, FixedSize}; use crate::directory::FileSlice; use crate::directory::OwnedBytes; use crate::positions::COMPRESSION_BLOCK_SIZE; use crate::positions::LONG_SKIP_INTERVAL; use crate::positions::LONG_SKIP_IN_BLOCKS; use bitpacking::{BitPacker, BitPacker4x}; /// Positions...
extern crate pest; use pest::iterators::Pair; use pest::Parser; use self::pest::iterators::Pairs; use Node::*; // *** Rules *** enum RuleType { Parser(ParserRule), Token(TokenRule), } impl From<ParserRule> for RuleType { fn from(rule: ParserRule) -> Self { RuleType::Parser(rule) } } impl F...
use std::time::SystemTime; use argon2::{password_hash::SaltString, Argon2, PasswordHash, PasswordHasher, PasswordVerifier}; use axum::{ async_trait, extract::{Extension, FromRequest, RequestParts, TypedHeader}, headers::Cookie, headers::{authorization::Bearer, Authorization}, http::{header, StatusC...
use std::iter::Iterator; /// A trait that extends [`Iterator`] with `chunks` method. pub trait IterChunks: Sized + Iterator { /// Create an iterator-liked struct that yields elements by chunk every n /// elements, or fewer if the underlying iterator ends sooner. /// /// [`Chunks`] is not a real Iterato...
use { FuzzyEq, Transform, WriteBuffer, WriteOptions, }; impl WriteBuffer for Transform { fn write_buf_opt(&self, opt: &WriteOptions, buf: &mut Vec<u8>) { if opt.simplify_transform_matrices { write_simplified_transform(self, opt, buf); } else { write_matrix_tr...
use reqwest::blocking::Client; use reqwest::Url; use serde::Deserialize; use serde_json::value::RawValue; // --- // --- LazyEs // --- /// Computation result that may lazily rely on an elasticsearch "search" /// request. pub enum LazyEs<'p, T> { /// The result of the computation is ready. Value(T), /// The...
pub static INDEX_FOR_MIX: &'static [u32] = &[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3, 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4, 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8, 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 1...
//! trainers //! //! Trainers for models use super::models::ModelBase; use super::util::*; use ndarray::{prelude::*, RemoveAxis}; use rand::prelude::*; use std::time::Instant; #[derive(Clone)] pub struct TrainResult<T: CrateFloat> { train_loss_list: Vec<T>, train_acc_list: Vec<T>, test_acc_list: Vec<T>, }...
// // Copyright (c) 2017 10x Genomics, Inc. All rights reserved. // use std::io::{Read}; use std::hash::Hash; use std::fmt::Debug; use fnv::FnvHashSet; use bio::io::{fasta}; use debruijn::{Kmer, Vmer}; use debruijn::dna_string::DnaString; use itertools::Itertools; use pdqsort; use bincode; use serde::de::DeserializeO...
use log::{info, warn, LevelFilter, Record}; use std::io::Write; use std::thread; use chrono::prelude::*; use clap::{App, Arg}; use csv::ReaderBuilder; use env_logger::fmt::Formatter; use env_logger::Builder; use rdkafka::client::ClientContext; use rdkafka::config::{ClientConfig, RDKafkaLogLevel}; use rdkafka::consumer...
use std::net::TcpStream; use std::io::{Write, Read}; use byteorder::{WriteBytesExt, LittleEndian}; /// Client for BouyomiChan /// using App Collaboration function (TCP) /// default: 127.0.0.1:50001 pub struct Client { host: String, port: String, } type RequestResult<T> = Result<T, Box<dyn std::error::Error>>...
use std::borrow::Cow; use futures_util::{stream::iter, SinkExt, StreamExt, TryStreamExt}; use maybe_owned::MaybeOwned; use tokio::{ io::{AsyncRead, AsyncWrite}, net::TcpStream, }; use tokio_util::codec::{Decoder, Framed}; use crate::{ config::replication::Primary, node::{ event::Event, ...
/// Built-in tic-tac-toe support /// pub mod tic_tac_toe; pub use self::tic_tac_toe::{ TicTacToeRuleSet, TicTacToeState, TicTacToeTeam, }; use std::{ collections::{ HashMap, VecDeque, }, fmt::Debug, hash::Hash, marker::PhantomData, }; /// An abstract set of rules for a ...
/* Copyright 2016 <NAME> * * Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or * http://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 according to those terms...
use nix::sys::termios; use std::io::{Read, Write}; use std::sync::mpsc::channel; use std::thread; use std::time::{Instant, Duration}; use std::borrow::Borrow; mod board; mod block; mod generator; use board::{Board, BlockPosition}; use block::Block; use generator::BlockGenerator; const TICK_DURATION: u64 = 500; #[...
use crate::identity::error::SigningError; use crate::identity::Keypair; use crate::signed_envelope::SignedEnvelope; use crate::{peer_record_proto, signed_envelope, Multiaddr, PeerId}; use instant::SystemTime; use std::convert::TryInto; use std::fmt; const PAYLOAD_TYPE: &str = "/libp2p/routing-state-record"; const DOMA...
use crate::engine::timeout; use async_trait::async_trait; use error_chain::bail; use fxhash::FxHashMap; use std::ops::Rem; use std::sync::Mutex as StdMutex; use std::sync::RwLock as StdRwLock; use std::time::Duration; use std::time::Instant; use std::{sync::Arc, sync::Weak}; use tokio::sync::broadcast; use tokio::sync:...
//! Handles the force quitting of FileMaker before building the plug-in. //! This serves two purposes: //! 1. Allowing you to re-load the plug-in in FileMaker. //! 2. Sometimes FileMaker locks a `.dll` in the target folder during testing and prevents cargo from building. //! //! # Example //! `Cargo.toml` //! ```toml /...
//! [Single-pair list](https://en.wikipedia.org/wiki/Church_encoding#One_pair_as_a_list_node) use lambda_calculus::*; use combinators::{I, Z}; use data::num::church; use data::pair; use data::option; pub use lambda_calculus::data::list::pair::*; /// Applied to a pair-encoded list it returns an `Option` containing i...
use alphred::Item; use chrono::prelude::*; use reqwest; use errors::*; use forecast; use location; use sparkline; use theme::Theme; #[derive(Debug)] pub struct PirateWeather { pub pirate_weather_endpoint: String, pub pirate_weather_api_key: String, pub location: location::Location, pub theme: Theme, ...
use bevy::prelude::*; use ttf2mesh::{TTFFile, Value}; use crate::{ mesh_cache::{CacheKey, MeshCache}, text_mesh::{FontStyle, TextMesh}, }; pub(crate) struct MeshData { pub vertices: Vec<[f32; 3]>, pub normals: Vec<[f32; 3]>, pub indices: Vec<u32>, pub uvs: Vec<[f32; 2]>, } // FIXME: add valid...
//! Planet Earth properties use crate::conversions::z_from_p; use crate::gsw_internal_const::{DEG2RAD, GAMMA}; use crate::{Error, Result}; /// Coriolis parameter (f) /// /// # Example /// ``` /// use gsw::earth::coriollis_parameter; /// let f = coriollis_parameter(5.0).unwrap(); /// assert!((f - 1.2710993980526786e-0...
/// A runtime module template with necessary imports use parity_codec::Encode; use runtime_primitives::traits::{CheckedAdd, CheckedSub, Hash, Zero}; use support::{decl_module, decl_storage, dispatch::Result, StorageValue}; // Enables access to account balances and interacting with signed messages use { balances, ...
//! # 面试题 02.05. 链表求和 //! //! 难度 中等 //! //! 给定两个用链表表示的整数,每个节点包含一个数位。 //! //! 这些数位是反向存放的,也就是个位排在链表首部。 //! //! 编写函数对这两个整数求和,并用链表形式返回结果。 //! //! //! //! ## 示例: //! //! ```text //! 输入:(7 -> 1 -> 6) + (5 -> 9 -> 2),即617 + 295 //! 输出:2 -> 1 -> 9,即912 //! ``` //! //! 进阶:思考一下,假设这些数位是正向存放的,又该如何解决呢? //! //! ## 示例: //! //! ```tex...
extern crate proc_macro; extern crate syn; #[macro_use] extern crate quote; use proc_macro::TokenStream; use proc_macro2::TokenTree; use syn::parse::{Parse, ParseStream}; use syn::punctuated::Punctuated; use syn::token::Comma; use syn::{buffer::Cursor, DataStruct, DeriveInput, Field, Ident, LitStr}; #[proc_macro_deri...
// Descriptor wallet library extending bitcoin & miniscript functionality // by LNP/BP Association (https://lnp-bp.org) // Written in 2020-2021 by // Dr. <NAME> <<EMAIL>> // // To the extent possible under law, the author(s) have dedicated all // copyright and related and neighboring rights to this software to // t...
mod key_code; pub use self::key_code::KeyCode; use mio::unix::EventedFd; use mio::{Events, Poll, PollOpt, Ready, Registration, SetReadiness, Token}; use promising_future::{future_promise, Promise}; use std::collections::hash_map::{Entry, HashMap}; use std::os::raw::{c_int, c_uint}; use std::sync::mpsc::{channel, Sende...
extern crate utilities; use std::path::PathBuf; use structopt::StructOpt; #[derive(StructOpt, Debug)] #[structopt(name = "day3", version = "1.0.0")] struct Args { // The number of occurrences of the `v/verbose` flag /// Verbose mode (-v, -vv, -vvv, etc.) ///#[structopt(short, parse(from_occurrences))] ...
use std::time::Instant; use std::cell::RefCell; use pancurses::noecho; use std::thread::JoinHandle; use pancurses::Window; use std::time::Duration; use pancurses::{endwin, initscr, Input}; use crossbeam::channel::{unbounded as unbound_channel, Receiver}; pub struct Progress { title: String, progress: f64, y...
use colored::Colorize; use difference::{Changeset, Difference}; use std::fmt; /// Track the mode of difference printing. #[derive(PartialEq, Debug, Clone)] enum Mode { Same, Add, Rem, } // ======== line number display ========== #[derive(PartialEq, Debug, Clone)] struct Lineno(Option<usize>); impl fmt::D...
use crate::sparse::*; ///Set of nodes defined implicitly as all integers between ///`beg` and `end` not including `end` #[derive(Eq,PartialEq,Ord,PartialOrd,Clone,Copy,Hash,Debug)] pub struct Grid1D{ pub beg : i64, pub end : i64 } ///Graph defined by a 1D stencil. The stencil offsets ///are contained in a v...
use vm::{ commands::{self, Source}, gapi, module::{Module, ModuleState, CLIENT_ID}, }; use vm_math::*; pub struct QuadsModule { camera_matrices: CameraMatrices, camera_transform: OthroCameraTransforms, quad_transforms: Transforms2D, text_transforms: Transforms2D, text2_transforms: Tran...
use std::collections::{HashMap, HashSet}; use std::iter::FromIterator; use std::str; /* Mirror the product(repeat=n) iter from Python itertools https://github.com/python/cpython/blob/234531b4462b20d668762bd78406fd2ebab129c9/Modules/itertoolsmodule.c#L2095 https://dev.to/naufraghi/procedural-macro-in-rust-101-k...
//! Test for the TCP client. use std::io::{self, Read, Write}; use std::time::Duration; use crate::test::{config_test_server, ServerOpts}; use crate::{AmsAddr, AmsNetId, Client, Device, Error, Timeouts}; fn run_test(opts: ServerOpts, f: impl Fn(Device)) { let timeouts = if let Some(tmo) = opts.timeout { ...
use crate::constants::*; use crate::convert::bytes::TxBytes; use crate::convert::luts::*; use crate::convert::trytes::TxTrytes; pub type Trit = i8; pub type Trits243 = [i8; 243]; pub type TxTrits = [i8; TRANSACTION_SIZE_TRITS]; pub fn from_tx_bytes_2enc9(bytes: &[u8]) -> TxTrits { let mut trits = [0_i8; TRANSACTI...
// Copyright (c) The cargo-guppy Contributors // SPDX-License-Identifier: MIT OR Apache-2.0 use crate::{errors::TripleParseError, Platform}; use cfg_expr::{ expr::TargetMatcher, target_lexicon, targets::{get_builtin_target_by_triple, TargetInfo}, TargetPredicate, }; use std::{borrow::Cow, cmp::Ordering...
use std::{ future::Future, net::{IpAddr, Ipv4Addr}, sync::{Arc, Mutex}, time::{Duration, SystemTime}, }; use chrono::{DateTime, Utc}; use rocket::{ get, launch, routes, serde::{json::Json, Deserialize, Serialize}, State, fs::{FileServer, Options}, }; mod ip_pool; use ip_pool::IPAddrPool; ...
use crate::EnvVar; use std::path::PathBuf; use std::process::Command; #[derive(Debug, Clone)] pub enum BubMount { DevBind { src: PathBuf, dest: PathBuf }, BindRO { src: PathBuf, dest: PathBuf }, BindRW { src: PathBuf, dest: PathBuf }, Symlink { src: PathBuf, dest: PathBuf }, TmpFs { path: PathB...
// vim: tw=80 //! Generates extended attribute names that result in hash collisions in the //! B-Tree use bfffs::common::fs_tree::*; use chashmap::CHashMap; use lazy_static::lazy_static; use rand_xorshift::XorShiftRng; use rand::{ FromEntropy, Rng, SeedableRng, distributions::Alphanumeric, seq::Sli...