text
stringlengths
8
4.13M
// Copyright 2020 WHTCORPS INC. Licensed under Apache-2.0. use std::collections::BTreeMap; use std::collections::Bound::{Excluded, Unbounded}; use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}; use std::sync::{Arc, RwLock}; use std::time::{Duration, Instant}; use std::{cmp, thread}; use futures::c...
use std::io::Cursor; use std::sync::atomic::AtomicBool; use std::sync::Arc; use amethyst_core::specs::prelude::Component; use amethyst_core::specs::storage::BTreeStorage; use rodio::{Decoder, SpatialSink}; use smallvec::SmallVec; use source::Source; use DecoderError; /// An audio source, add this component to anythi...
use super::*; pub type EPin<MODE> = ErasedPin<MODE>; macro_rules! impl_pxx { ($(($port_id:literal :: $pin:ident)),*) => { /// Erased pin /// /// `MODE` is one of the pin modes (see [Modes](crate::gpio#modes) section). pub enum ErasedPin<MODE> { $( $pin(P...
use criterion::{criterion_group, criterion_main, Criterion}; use clueengine::ClueEngine; fn simulate_single() { // This is from add_card_expect_no_extras_test let clue_engine = ClueEngine::load_from_string("63FJQ-ABCDEGHIKLMNOPRSTU.3T-CDFHIJKNOPQS.3-CDFHIJKMNOPQST.3NO-CDFHIJKMPQST.3K-CDFHIJNOPQT.3CD-FJNOQT.3-C...
//pub mod http;
// use structopt::StructOpt; // use clap::App; // use crate::config::Config; //// A basic example //#[derive(StructOpt, Debug)] //#[structopt(name = "basic")] //pub struct Opt { // /// A flag, true if used in the command line. // #[structopt(short = "d", long = "debug", help = "Activate debug mode")] // debug...
use crate::test_type; use postgres::{Client, NoTls}; use postgres_types::{FromSql, ToSql, WrongType}; use std::error::Error; #[test] fn defaults() { #[derive(FromSql, ToSql, Debug, PartialEq)] struct SessionId(Vec<u8>); let mut conn = Client::connect("user=postgres host=localhost port=5433", NoTls).unwrap...
use bincode::serde::{DeserializeError, SerializeError}; use email::results::ParsingError as EmailParseError; use notify::Error as NotifyError; use std::error::Error as StdError; use std::fmt::{self, Debug, Display}; use std::io::Error as IoError; use std::result::Result as StdResult; use tryin::Informative; pub type R...
use crate::riichi::fast_hand_calculator::resources::RESOURCES; /// Returns the arrangement value of honors after the execution of a single action. /// actionIds: /// /// 0 draw with 0 of the same type in concealed hand /// 1 draw with 1 /// 2 draw with 2 /// 3 draw with 3 /// /// 4 draw with pon of the same type ...
use hn_api::HnClient; fn print(api: &HnClient, items: &[u32]) { for id in items { let item = api.get_item(*id).unwrap().unwrap(); let author = item.author().map(|username| { let user = api.get_user(username).unwrap().unwrap(); format!("{}, karma {}", username, user.karma) ...
use std::{collections::HashMap, mem::ManuallyDrop}; use crate::{ api::util::{mk_v8_string, v8_deserialize, v8_serialize}, exec::Executor, }; use anyhow::Result; use fraction::GenericFraction; use itertools::Itertools; use serde::{Deserialize, Serialize}; use std::sync::mpsc; use thiserror::Error; use v8; use z3::a...
#![allow(dead_code)] use cargo_snippet::snippet; #[snippet] /* /// a[i] = s[0..i] の最長強境界 fn longest_strong_borders<T: PartialEq>(s: &[T]) -> Vec<Option<usize>> { let mut a = vec![None; s.len()+1]; for i in 1..s.len()+1 { } }*/ #[test] fn test_longest_borders() {} #[snippet] /// a[2*i] = iを中心とし...
// Copyright 2017 ETH Zurich. All rights reserved. // // 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 //...
#![recursion_limit = "256"] extern crate uni_app; // wasm-unknown-unknown #[cfg(target_arch = "wasm32")] #[macro_use] extern crate stdweb; #[cfg(target_arch = "wasm32")] #[path = "web_snd.rs"] pub mod snd; // NOT wasm-unknown-unknown #[cfg(not(target_arch = "wasm32"))] extern crate cpal; #[cfg(not(target_arch = "w...
//! Deserializer for files generated using the wtvr3d Asset Converter mod asset_registry; pub use asset_registry::AssetRegistry; use crate::renderer::{Buffer, Material, MaterialInstance, MeshData, Uniform, UniformValue}; use bincode::deserialize; use web_sys::WebGlRenderingContext; use wtvr3d_file::{FileValue, Materi...
#![feature(seek_convenience)] pub mod error; pub mod pager; pub mod row; pub mod statements; pub mod table;
use std::error::Error; use std::fmt; use std::str; #[derive(Debug, Clone)] pub enum AccessTokenProviderError { /// An invalid request was sent which contains further information. /// No retry necessary. BadAuthorizationRequest(AuthorizationRequestError), /// An error from the client side which does not...
#[doc = "Register `NFCID1_LAST` reader"] pub struct R(crate::R<NFCID1_LAST_SPEC>); impl core::ops::Deref for R { type Target = crate::R<NFCID1_LAST_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<NFCID1_LAST_SPEC>> for R { #[inline(always)] fn f...
use rs_futu_api::client::Client; use actix::System; use actix_rt::time::sleep; use std::time::Duration; use rs_futu_api::commands::GetGlobalState; fn main() { env_logger::init(); System::new().block_on(async { let mut client = Client::connect("127.0.0.1:11111").await; let get_global_state = G...
#![allow(dead_code)] /* This file is responsible for rendering the grid to the screen using Piston. It is also responsible for UI and keyboard controls for interacting with the display. */ use common::LifeAlgorithm; use piston_window::*; pub struct GUI { paused:bool, zoom:f64, offset_x:f64, offset_y:f64, pr...
// The prime factors of 13195 are 5, 7, 13 and 29. // // What is the largest prime factor of the number 600851475143 ? // use std::num; use std::f64; fn main(){ largest_prime_factor(600851475143 ); } fn largest_prime_factor(x: i64){ let z = x as f64; let z = z.sqrt(); let mut upper_limit ...
#[doc = "Reader of register EVENTS_OVERFLOW"] pub type R = crate::R<u32, super::EVENTS_OVERFLOW>; #[doc = "Writer for register EVENTS_OVERFLOW"] pub type W = crate::W<u32, super::EVENTS_OVERFLOW>; #[doc = "Register EVENTS_OVERFLOW `reset()`'s with value 0"] impl crate::ResetValue for super::EVENTS_OVERFLOW { type T...
// 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...
use super::display_info::DisplayInfoWin; use super::util::from_wstr; use crate::displays::EnumeratedDisplayInfo; use crate::{ ConnectionType, Dimensions, DisplayInfo, DisplayMode, DisplayRects, Rectangle, UpscaleMode, }; use winapi::{ shared::{ basetsd::UINT32, minwindef::{BOOL, DWORD, LPARAM, ...
use std::error; use crate::regret::regret_provider::{Response, Request, RegretHandler, RegretRequest, RegretDelta}; use crate::game::{Player}; /// Regret handler for using channels to communicate with a provider pub struct ChannelRegretHandler { pub requester: crossbeam_channel::Sender<Request>, pub receiver:...
extern crate regex; use self::regex::*; use std::collections::HashMap; use std::num::*; use s2::ch11::*; use s1::ch7::*; use std::str::FromStr; pub struct UserProfile { email: String, uid: u32, role: String } static mut NEXT_UID: u32 = 10; fn next_uid() -> u32 { unsafe { let uid = NEXT_UID...
// Copyright (c) 2015 Daniel Grunwald // // 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, // publis...
#[allow(unused_imports)] use serde_json::Value; #[derive(Debug, Serialize, Deserialize)] pub struct CreateSnapshotChangelistResponse { /// The ID of the job which created the changelist. #[serde(rename = "job_id")] pub job_id: i32, /// Number of LIN entries in changelist. #[serde(rename = "num_entr...
use std::borrow::BorrowMut; use std::sync::Arc; use std::time::Duration; use ::function_name::named; use async_trait::async_trait; use http::{HttpServerBuilder, HttpSession, HttpSessionHandler}; use logging::info; // https://stackoverflow.com/a/63190858 // #[test] // fn test_cli() { // let mut path = PathBuf::f...
// Copyright 2020 the Deno authors. All rights reserved. MIT license. use super::Context; use super::LintRule; use derive_more::Display; use std::cell::RefCell; use std::collections::BTreeMap; use std::mem; use std::rc::Rc; use swc_atoms::JsWord; use swc_common::{Span, Spanned}; use swc_ecmascript::ast::{ ArrowExpr, ...
/* * YNAB API Endpoints * * Our API uses a REST based design, leverages the JSON data format, and relies upon HTTPS for transport. We respond with meaningful HTTP response codes and if an error occurs, we include error details in the response body. API Documentation is at https://api.youneedabudget.com * * OpenA...
use std::borrow::Cow; use std::env::var; use std::fmt::{Display, Write}; use std::path::{Path, PathBuf}; pub use ssl_mode::PgSslMode; use crate::{connection::LogSettings, net::tls::CertificateInput}; mod connect; mod parse; mod pgpass; mod ssl_mode; /// Options and flags which can be used to configure a PostgreSQL ...
pub trait Eval<'d> { fn eval(self, engine: Engine<'d>) -> Result<Engine<'d>>; } mod write; pub fn eval<'d, S: Borrow<Script<'d>>>( script: S, engine: Engine<'d>, ) -> Result<Engine<'d>> { Eval::eval(script.borrow(), engine) } impl<'a, 'd> Eval<'d> for &'a Script<'d> { fn eval(self, engine: Engine<...
table! { hardware_specs (id) { id -> Int4, slug -> Varchar, num_registers -> Int4, num_stacks -> Int4, max_stack_length -> Int4, } } table! { program_specs (id) { id -> Int4, slug -> Varchar, hardware_spec_id -> Int4, input -> Array<In...
extern crate advent_of_code; use std::env; fn main() { let mut args = env::args(); args.next(); let mut spoil = false; let mut filters = Vec::new(); while let Some(arg) = args.next() { match arg.as_str() { "--spoil" => spoil = true, arg => filters.push(arg.to_stri...
use std::io::IoResult; use std::io::net::tcp::TcpStream; use std::io::net::ip::SocketAddr; use std::sync::atomic::AtomicBool; use std::sync::Arc; pub struct ClosableTcpStream { stream: TcpStream, end_trigger: Arc<AtomicBool>, close_read: bool, close_write: bool, timeout_ms: u32, } impl ClosableTcp...
pub enum Suit { Hearts, Spades, Clubs, Diamonds, None, } impl Copy for Suit {} impl Clone for Suit { fn clone(&self) -> Self { match self { Suit::Hearts => Suit::Hearts, Suit::Spades => Suit::Spades, Suit::Clubs => Suit::Clubs, Suit::Diam...
pub mod cdx; mod error; mod store; pub mod web; pub use error::Error; pub use store::Store; use chrono::NaiveDateTime; type Result<T> = std::result::Result<T, Error>; #[derive(Clone, Debug, Eq, PartialEq)] pub struct Item { pub url: String, pub archived: NaiveDateTime, pub digest: String, pub mimety...
/* TODO Ass support for AOP (low proiroty) */ use token::Token as Token; use common::ParseError as ParseError; use type_name; use type_name::TypeName as TypeName; mod test; pub struct Def { pub type_name: TypeName, dependencies: Vec<TypeName> } impl Def { pub fn accessor_at(&self, index: usi...
use serde::Serialize; use crate::types::gateway::activity::{StatusUpdate}; use enumflags2::BitFlags; #[derive(Serialize, Deserialize, Eq, PartialEq, Debug)] pub struct IdentifyObject { pub token: String, pub properties: IdentifyProperties, pub compress: bool, pub large_threshold: Option<u8>, pub sh...
use crate::{environment,message,context}; use environment::Population; use context::grid; mod seed; use seed::{spawn,feature}; use super::{agents}; use agents::{Kind, Agent}; use simplelog; use log::*; use std::fs; pub struct EnvironmentFactory; impl EnvironmentFactory { pub fn spawn() -> environment::Enviro...
#[allow(unused_imports)] use serde_json::Value; #[derive(Debug, Serialize, Deserialize)] pub struct HistoryFileStatistic { /// Nodes allocated for the sync action. #[serde(rename = "allocated")] pub allocated: i32, /// An ID for a single performance report. #[serde(rename = "id")] pub id: i32, ...
{{attributes}} {{debug}} pub fn {{identifier}}({{args}}){{return_type}};
#[macro_use] extern crate serde_derive; #[macro_use] extern crate lazy_static; extern crate irc; extern crate toml; extern crate rand; pub mod fifo; pub mod image_size; pub mod link_titles; pub mod quotes; pub mod seddy; use std::io::prelude::*; use irc::client::prelude::*; use std::default::Default; use std::proces...
// Copyright 2019 WHTCORPS INC Project Authors. Licensed under Apache-2.0. use milevadb_query_common::interlock::{ IntervalCone, OwnedKvPair, PointCone, Result as QEResult, interlock, }; use crate::interlock::Error; use crate::interlock::tail_pointer::NewerTsCheckState; use crate::interlock::Statistics; use crate...
use http; use dbms; use super::JsonResponse; use super::JsonpResponse; use super::get_req_credentials; use super::error_response; pub fn handle_tree_req<TDbms: dbms::Dbms>( dbms: &TDbms, parent_obj_path: &[&str], req: &http::Request) -> Box<http::Response> { http::Handler::handle_http_req( ...
// x11-rs: Rust bindings for X11 libraries // The X11 libraries are available under the MIT license. // These bindings are public domain. use libc::{c_char, c_int, c_short, c_uint, c_ulong, c_ushort}; use xlib::{Atom, Bool, Cursor, Display, Pixmap, Status, Time, Window, XRectangle, GC, XID}; // // functions // x11_l...
use std::fs::File; use std::io::{BufRead, BufReader, Result}; pub struct PointPositionConfig { name: i32, id: i32, point_type: i32, lng: i32, } impl PointPositionConfig { pub fn new(name: i32, id: i32, point_type: i32, lng: i32) -> Self { PointPositionConfig { name, ...
//Anything related to PATCH requests for account and it's properties goes here. use super::{Account, AccountFeature, AppTransfer}; use crate::framework::endpoint::{HerokuEndpoint, Method}; /// Account Update /// /// Update account. /// /// [See Heroku documentation for more information about this endpoint](https://de...
use std::collections::VecDeque; use std::io; use std::io::{Read, Write}; use std::time::Duration; use std::net::TcpStream; use std::sync::mpsc::{channel, Receiver, Sender, TryRecvError}; use std::thread; use rml_rtmp::handshake::{Handshake, HandshakeProcessResult, PeerType}; const BUFFER_SIZE: usize = 4096; pub enum ...
use crate::controller::EventQueue; use std::io::Write; impl<W: Write> EventQueue<W> { pub fn do_expand_dir(&mut self) -> Option<()> { let tree_index = self .path_node_root .flat_index_to_tree_index(self.pager.cursor_row as usize); self.path_node_root .expand_dir(...
use crate::rpc::Peer; /// The state of a peer iterator. #[derive(Debug, Clone, PartialEq, Eq)] pub enum PeersIterState { /// The iterator is waiting for results. /// /// `Some(peer)` indicates that the iterator is now waiting for a result /// from `peer`, in addition to any other peers for which it is ...
use clr1::Grammar; pub fn gen_cgrammars() -> Grammar { let mut cases: Vec<(&str, Vec<&str>)> = vec![]; macro_rules! add_case_group { ($head:expr$(,$tail:expr)*) => { $( cases.push(($head,$tail)); )* } } add_case_group!( "primary_expression", ...
use super::pallet_mq; use phala_pallets::phala_legacy::OnMessageReceived; use phala_types::messaging::{self, BindTopic, Lottery, Message, WorkerReportEvent}; use super::pallet_registry::RegistryEvent; type BalanceTransfer = messaging::BalanceTransfer<super::AccountId, super::Balance>; type KittyTransfer = messaging::K...
// Copyright 2021, The Android Open Source Project // // 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...
use crate::{error::ServerError, models, server::Pool}; use actix::{Actor, ActorContext, AsyncContext, StreamHandler}; use actix_web::{get, web, HttpRequest, HttpResponse}; use actix_web_actors::ws; use diesel::{prelude::*, PgConnection}; use gdlk::{ compile_and_allocate, CompileErrors, HardwareSpec, Machine, Progra...
use std::collections::HashMap; pub fn calculate_mean(target_vector: &Vec<i32>) -> f32 { return {let mut sum = 0; for elem in target_vector {sum += elem;} sum} as f32 / target_vector.len() as f32; } pub fn calculate_median(target_vector: &Vec<i32>) -> i32 { let mut reference_vector: Vec<i32> = target_vector.cl...
// #![windows_subsystem = "windows"] extern crate engine; fn main() { cute_log::init().expect("failed to initialize log!"); engine::run(); }
//! Elliptic Curve Digital Signature Algorithm (ECDSA) pub use super::NistP256; /// ECDSA/P-256 signature (fixed-size) pub type Signature = ::ecdsa::Signature<NistP256>; #[cfg(feature = "sha256")] #[cfg_attr(docsrs, doc(cfg(feature = "sha256")))] impl ecdsa::hazmat::DigestPrimitive for NistP256 { type Digest = s...
use super::*; use crate::time::{clockid_t, itimerspec_t, timespec_t, ClockID}; use atomic::{Atomic, Ordering}; use std::time::Duration; /// Native Linux timerfd #[derive(Debug)] pub struct TimerFile { host_fd: HostFd, host_events: Atomic<IoEvents>, notifier: IoNotifier, } impl TimerFile { pub fn new(...
#[doc = "Register `CExIV` reader"] pub struct R(crate::R<CEXIV_SPEC>); impl core::ops::Deref for R { type Target = crate::R<CEXIV_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<CEXIV_SPEC>> for R { #[inline(always)] fn from(reader: crate::R<CEX...
/// Trait对象 /// ## trait 对象是安全的判定原则: /// 1. 返回值类型不为 Self /// 2. 方法没有任何泛型类型参数 /// /// ## 使用泛型限制类型,只能使用单一类型 /// ``` /// pub trait Draw { /// fn draw(&self); /// } /// /// pub struct Screen<T: Draw> { /// pub components: Vec<Box<T>>, /// } /// /// impl<T> Screen<T> /// where /// T: Draw, /// { /// pub fn ru...
use crate::{rt, Message}; use std::{ future::Future, pin::Pin, // marker::Unpin, task::{self, Poll}, }; /// This is the actor trait, but I wasn't sure if it ought to be called that. pub trait Process<M: Message> { type Response: Message; type Error: Message; // TODO: + std::error::Error? ty...
pub mod config; pub mod exceptions;
#![allow(unused_mut, unused_imports, unused_variables, dead_code, unused_must_use)] #![feature(collections)] extern crate rustc_serialize; extern crate type_printer; use rustc_serialize::json; use std::io::prelude::*; use std::fs::File; use std::path::Path; use std::error::Error; use std::fs::OpenOptions; use std::io:...
use crate::units::orbits::Orbit; use crate::vector::Vector; use serde_derive::{Deserialize, Serialize}; #[derive(Debug, Serialize, Deserialize, Clone)] pub struct Buoy { #[serde(default)] pub orbits: Vec<Orbit>, pub message: String, #[serde(default)] pub hints: Vec<Vector>, #[serde(rename = "me...
trait HashComputer { fn compute(&self) ->i64; } trait HashUser { fn use_hash(&self); } struct QuantumHashComputer { } impl HashComputer for QuantumHashComputer { fn compute(&self)->i64 { 100 as i64 } } struct Network<'a, T> where T: HashComputer { hash: &'a T } impl<'a,T> HashUser f...
use crate::helper::tritvector::TritVector; use num_bigint::{BigInt, Sign}; pub const BOOL_FALSE: char = '-'; pub const BOOL_TRUE: char = '1'; pub const TRYTES: &str = "NOPQRSTUVWXYZ9ABCDEFGHIJKLM"; pub const TRYTE_TRITS: [&str; 27] = [ "---", "0--", "1--", "-0-", "00-", "10-", ...
#[allow(unused_imports)] use serde_json::Value; #[derive(Debug, Serialize, Deserialize)] pub struct GroupnetSubnetExtended { /// A description of the subnet. #[serde(rename = "description")] pub description: Option<String>, /// List of Direct Server Return addresses. #[serde(rename = "dsr_addrs")] ...
pub mod shape; pub mod entity; pub mod state;
use vector::{Vector2, Vector3, Vector4}; use std::{mem, ptr}; macro_rules! matrix { ($name:ident : $vec:ident[ $($field:ident = $index:expr),* ] = ($inner:expr, $outer:expr)) => { #[derive(Clone, Copy, Debug, Hash, PartialEq, PartialOrd, Eq, Ord)] #[repr(C)] #[allow(missing_docs)] //TODO: a...
use wgpu::util::DeviceExt; use crate::{camera, create_render_pipeline, texture}; pub struct OctreeGPU { octree_buffer: wgpu::Buffer, input_bind_group: wgpu::BindGroup, pipeline: wgpu::RenderPipeline, camera_buffer: wgpu::Buffer, input_bind_group_layout: wgpu::BindGroupLayout, } impl OctreeGPU { ...
use adventofcode2020::utils::file; use itertools::Itertools; use parse_display::{Display, FromStr}; use std::collections::HashMap; #[derive(Display, FromStr, PartialEq, Debug, Clone)] #[display("mask = {raw}")] struct Mask { raw: String, } #[derive(Display, FromStr, PartialEq, Debug, Clone)] #[display("mem[{addr}] = ...
#![allow(clippy::mutable_key_type)] use crate::{smt_store_impl::SMTStore, traits::KVStore}; use gw_common::h256_ext::H256Ext; use gw_common::{merkle_utils::calculate_state_checkpoint, smt::SMT, H256}; use gw_db::schema::{ Col, COLUMN_ASSET_SCRIPT, COLUMN_BAD_BLOCK_CHALLENGE_TARGET, COLUMN_BLOCK, COLUMN_BLOCK_D...
use super::ast; use super::flatten; use super::make; use super::name::Name; use super::parser::{self, emit_error}; use super::project::Project; use serde::{Deserialize, Serialize}; use std::collections::HashSet; use std::fs; use std::io::{Read, Write}; use std::path::PathBuf; #[derive(Serialize, Deserialize)] pub stru...
use anyhow::{format_err, Error}; use futures::{future::try_join_all, Stream, TryStreamExt}; use itertools::Itertools; use postgres_query::{query, query_dyn, Error as PqError, FromSqlRow}; use serde::{Deserialize, Serialize}; use stack_string::{format_sstr, StackString}; use std::{ collections::{HashMap, HashSet}, ...
use std::fmt; use aoc::get_input; struct Image { width: usize, height: usize, layers: Vec<Layer>, } impl Image { pub fn from_pixels(pixels: &Vec<u8>, width: usize, height: usize) -> Image { let layer_size = width * height; let layer_count = pixels.len() / layer_size; let mut im...
const NO_MORE: i32 = std::i32::MAX; const NOT_READY: i32 = -1; /// idf is log(1 + N/D) /// ``` /// N = total documents in the index /// d = documents matching (len(postings)) /// https://en.wikipedia.org/wiki/tf-idf /// ``` pub fn compute_idf(n: usize, d: usize) -> f32 { let nf = n as f32; let df = d as f32; ...
use std::collections::HashMap; enum Instruction { Mask(String), Mem(u32, String), } #[aoc_generator(day14)] fn input_generator(input: &str) -> Vec<Instruction> { let mut res = vec![]; for l in input.lines() { let mut t = l.split(" = "); let i = match t.next() { Some("mask")...
use crate::Color; use crate::Units; #[derive(Copy, Clone, Debug, PartialEq)] pub(crate) struct BoxShadow { pub horizontal_offset: Units, pub vertical_offset: Units, pub blur_radius: Units, pub color: Color, } impl Default for BoxShadow { fn default() -> Self { BoxShadow { hor...
use futures::future::{err, Either, Future}; use rayon::prelude::*; use sqlparser::ast::Expr; use std::sync::Arc; use tokio_postgres::{ tls::{MakeTlsConnect, TlsConnect}, Socket, }; use super::{ foreign_keys::{fk_columns_from_where_ast, ForeignKeyReference}, postgres_types::TypedColumnValue, select_...
use std::collections::HashSet; pub fn part_one(s: &str) -> i64 { s.split("\n\n") .map(|group| { let answers: HashSet<char> = group .chars() .filter(|c| *c != '\n') .collect(); answers.len() }) .fold(0, |acc, v| acc + v) as i64 } pub fn part_two(s: &str) -> i64 { s.s...
//! Values use chrono::{Duration, NaiveDateTime, TimeZone}; use chrono_tz::Tz; use num_traits::FromPrimitive; use std::{ cmp::Ordering, fmt, io::Write, ops, str::{from_utf8, from_utf8_unchecked}, }; use crate::{ error::{Error, ErrorKind}, parser::Function, }; /// The string format of an S...
/** * [260] Single Number III * * Given an integer array nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once. You can return the answer in any order. You must write an algorithm that runs in linear runtime complexity and us...
use crate::render_gl; // This is how we get access to the stuff from `render_gl.rs` pub struct Program { id: gl::types::GLuint, } impl Program { #[allow(dead_code)] pub fn id(&self) -> gl::types::GLuint { self.id } pub fn set_used(&self) { unsafe { gl::U...
// Copyright 2019-2020 Conflux Foundation. All rights reserved. // Conflux is free software and distributed under GNU General Public License. // See http://www.gnu.org/licenses/ // Copyright 2015-2019 Parity Technologies (UK) Ltd. // This file is part of Parity Ethereum. // Parity Ethereum is free software: you can r...
use std::{ collections::HashMap, fs::{self, File, OpenOptions}, path::{Path, PathBuf}, process::Command, }; use clap::Parser; use flate2::{write::GzEncoder, Compression}; use fs_extra::dir::{self, CopyOptions}; use glob; use itertools::Itertools; use tar; use tempfile; use toml_edit::{self, value, Array, Item, Tab...
use crate::text::EncodingMaps; use itertools::Itertools; use nom::{ bytes::complete::is_not, character::complete::{char, line_ending, not_line_ending}, combinator::{map, map_opt, map_res, opt}, multi::separated_list0, sequence::{delimited, pair, preceded, tuple}, IResult, }; use rust_embed::Rust...
use std::io; use std::sync::mpsc::{self, Receiver, SyncSender}; use std::sync::Arc; use mio::{Registry, Token, Waker}; /// Maximum signal channel size. /// /// Any signal received after this bound has been reached will be silently dropped, while `mio` /// will still be woken up to allow processing the remaining signa...
#[derive(Clone, PartialEq, ::prost::Message)] pub struct C2s { ///客户端版本号,clientVer = "."以前的数 * 100 + "."以后的,举例:1.1版本的clientVer为1 * 100 + 1 = 101,2.21版本为2 * 100 + 21 = 221 #[prost(int32, required, tag="1")] pub client_ver: i32, ///客户端唯一标识,无生具体生成规则,客户端自己保证唯一性即可 #[prost(string, required, tag="2")] ...
use super::*; ast_enum_of_structs! { /// Things that can appear directly inside of a module or scope. /// /// # Syntax tree enum /// /// This type is a [syntax tree enum]. /// /// [syntax tree enum]: enum.Expr.html#syntax-tree-enums pub enum Item { /// An `extern crate` item: `e...
use crate::error::*; use std::env; pub fn parse_mem(mem: &str) -> Result<usize> { let (num, postfix): (String, String) = mem.chars().partition(|&x| x.is_numeric()); let num = num.parse::<usize>().map_err(|_| Error::ParseMemory)?; let factor = match postfix.as_str() { "E" | "e" => 1 << 60 as usize, "P" | "p" =>...
//! This test file ensures that all of the lifetimes work the way we //! want, and that there are no regressions. It's a "does this compile?" //! test. extern crate ropey; use ropey::{Rope, RopeSlice}; const TEXT: &str = include_str!("test_text.txt"); fn main() { if cfg!(miri) { return; } let r...
fn main(){ // let test_b: bool = true; // let test_c: char = 's'; // TODO: start code }
pub type Int = i64; mod cpu; pub mod io; mod memory; mod ops; pub mod vm;
use crate::tryte::*; fn _print_all_trytes() { for num in -364..364 { let a = num / 27; let b = num % 27; println!("{} = {} r {}", num, a, b) } } fn assert_tryte_from_i16(number: i16, hi: u8, lo: u8) { let tryte = Tryte::from(number); println!(" -- LO --\nExpected: {:06b}\n Got: {:06b}", lo, tr...
#[doc = "Reader of register FILTER01_CFG"] pub type R = crate::R<u16, super::FILTER01_CFG>; #[doc = "Writer for register FILTER01_CFG"] pub type W = crate::W<u16, super::FILTER01_CFG>; #[doc = "Register FILTER01_CFG `reset()`'s with value 0"] impl crate::ResetValue for super::FILTER01_CFG { type Type = u16; #[i...
use std::collections::HashMap; // region [[Skończone]] pub fn smaller_numbers_than_current(nums: Vec<i32>) -> Vec<i32> { let mut map = HashMap::new(); let mut sorted_nums = nums.clone(); sorted_nums.sort(); for (i, num) in sorted_nums.into_iter().enumerate() { if !map.contains_key(&num) { map.i...
use amqp_utils::{AmqpRequest, AmqpResponse}; use futures::channel::mpsc::{Receiver, Sender}; use futures::{SinkExt, StreamExt, TryFutureExt}; use serde::{Deserialize, Serialize}; use std::collections::btree_map::BTreeMap; use std::path::PathBuf; use std::process::{Command, Stdio}; use std::sync::Arc; use tokio::sync::S...
extern crate word_count; #[allow(dead_code)] fn main() { let result = word_count::word_count("car : carpet as java : javascript!!&@$%^&"); println!("{:?}", result); }