text
stringlengths
8
4.13M
// Copyright (c) The diem-devtools Contributors // SPDX-License-Identifier: MIT OR Apache-2.0 //! Generate and read JUnit reports in Rust. mod report; mod serialize; pub use report::*; // Re-export `quick_xml::Result` so it can be used by downstream consumers. pub use quick_xml::Result;
use crate::models::task::{Task, TaskState}; pub struct TaskStack { tasks: Vec<Task>, } impl TaskStack { pub fn new() -> TaskStack { TaskStack { tasks: Vec::new() } } pub fn add(&mut self, task: Task) { self.tasks.push(task); } pub fn remove(&mut self, task_index: usize) -> Ta...
use beryllium::*; fn main() { let sdl = Sdl::init(InitFlags::EVERYTHING).unwrap(); let rend_win = sdl .new_renderer_window( "Event Test", None, [800, 600], WindowCreationFlags::default(), ) .unwrap(); let mut controllers = vec![]; let joystick_count = sdl.get_number_of_joyst...
use std::char; #[aoc(day14, part1)] fn solve_part1(input: &str) -> String { let NUM_RECIPES: usize = input.trim().parse().unwrap(); let mut recipes = vec![3, 7]; let (mut elf_1, mut elf_2) = (0, 1); loop { let mut sum = recipes[elf_1] + recipes[elf_2]; if sum < 10 { ...
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT license. */ #![warn(missing_debug_implementations, missing_docs)] //! Aligned allocator use std::collections::VecDeque; use std::ops::Deref; use std::sync::{Arc, Condvar, Mutex, MutexGuard}; use std::time::Duration; use crate:...
/*! # HTML Escape This library is for encoding/escaping special characters in HTML and decoding/unescaping HTML entities as well. ## Usage ### Encoding This crate provides some `encode_*` functions to encode HTML text in different situations. For example, to put a text between a start tag `<foo>` and an end tag `<...
use serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize, Clone, Debug)] pub struct BankResponse { pub bank_transfer: BankTransfer, /// A unique identifier for the request, which can be used for /// troubleshooting. This identifier, like all Plaid identifiers, is case /// sensitive. pu...
use std::collections::HashMap; use std::convert::TryInto; use std::fmt; use once_cell::sync::Lazy; use crate::error::RSocketError; use crate::Result; #[derive(PartialEq, Eq, Debug, Clone, Hash)] pub enum MimeType { Normal(String), WellKnown(u8), } static U8_TO_STR: Lazy<HashMap<u8, &'static str>> = Lazy::ne...
use crate::prelude::*; pub fn pt1(input: Vec<(u32, u32, u32)>) -> Result<usize> { Ok(input .into_iter() .filter(|&(a, b, c)| a + b > c && a + c > b && b + c > a) .count()) } pub fn pt2(input: Vec<(u32, u32, u32)>) -> Result<usize> { let mut new_input = Vec::new(); for i in 0..input...
#![allow(unused_imports)] use std::cmp::{max, min}; use std::collections::{HashMap, HashSet}; use std::fs; use std::io::{self, Write}; use std::process::{Command, Stdio}; use std::str; struct Scanner<R> { reader: R, buf_str: Vec<u8>, buf_iter: str::SplitAsciiWhitespace<'static>, } impl<R: io::BufRead> Sca...
use crate::schema::access_tokens; use compat_uuid::Uuid; use diesel::{ self, delete, insert_into, prelude::*, result::Error, update, Associations, FromSqlRow, Identifiable, Insertable, Queryable, }; use postgres_resource::*; use rocket::{http::Status, response::status::Custom}; use rocket_contrib::json::JsonVa...
use bevy::{prelude::*, render::render_graph::base::MainPass}; pub mod objects; pub mod primitives; pub use objects::*; pub use primitives::*; /////////////////////////////////////////////////////////////////////////////// /// Equivalent to [`PbrBundle`] but without the transforms, mesh and material components #[der...
#![cfg_attr(feature="nightly", feature(integer_atomics))] #![allow(unused_imports)] #![cfg_attr(feature="nightly", feature(test))] #![deny(warnings)] extern crate serde; #[macro_use] extern crate serde_derive; #[cfg(feature="nightly")] extern crate test; extern crate savefile; #[macro_use] extern crate savefile_deriv...
//! An expression that evaluates a sub-expression and rejects successful results. //! //! See [`crate::Parser::reject`]. use crate::parser::Parser; use crate::span::Span; /// The struct returned from [`crate::Parser::reject`]. pub struct Reject<P>(pub(crate) P); impl<P> Parser for Reject<P> where P: Parser, { ...
extern crate cc; extern crate fs_extra; extern crate metadeps; use std::env; #[cfg(not(feature = "build-cmake"))] use std::ffi::OsString; use std::fs; use std::path::PathBuf; #[cfg(not(feature = "build-cmake"))] use std::process::Command; fn main() { // Rerun if the c-ares source code has changed. println!("c...
#![allow(unused_imports)] #![allow(dead_code)] use std::convert::TryFrom; use std::fmt::{self, Formatter}; use std::str::FromStr; use crate::quickfix_errors::*; #[derive(Debug, Clone, Copy)] pub enum FixType { INT, FLOAT, STRING, BOOL, CHAR, } // seems unnecessaery // #[derive(Debug)] // pub stru...
/*===============================================================================================*/ // Copyright 2016 Kyle Finlay // // 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 // // ...
use bytes::{Buf, BufMut, Bytes, BytesMut}; use super::{utils, Body, Frame, REQUEST_MAX}; use crate::error::RSocketError; use crate::utils::Writeable; #[derive(Debug, Eq, PartialEq)] pub struct RequestN { n: u32, } pub struct RequestNBuilder { stream_id: u32, flag: u16, value: RequestN, } impl Reques...
pub mod post; pub mod settings; pub mod typer; use crate::application::App; use crossterm::event::KeyEvent; pub type KeyHandler = fn(KeyEvent, &mut App);
#![allow(warnings)] extern crate failure; extern crate rusqlite; use failure::{Error, err_msg}; extern crate pretty_env_logger; extern crate ctrlc; extern crate chrono; #[macro_use] extern crate lazy_static; #[macro_use] extern crate log; use std::collections::HashMap; use std::io; extern crate fern; extern crat...
use std::collections::HashSet; use utils; pub fn problem_032() -> u32 { // 2 possible multipulcation setups // 2 * 3 * 4 // 1 * 4 * 4 // # 2 * 3 let mut pandigital = HashSet::new(); let zero: u32 = 0; for a in 12..99{ for b in 123..(10000/a){ let m = a * b; ...
#[doc = r"Register block"] #[repr(C)] pub struct RegisterBlock { #[doc = "0x00 - SYSCFG secure configuration register"] pub seccfgr: SECCFGR, #[doc = "0x04 - configuration register 1"] pub cfgr1: CFGR1, #[doc = "0x08 - FPU interrupt mask register"] pub fpuimr: FPUIMR, #[doc = "0x0c - SYSCFG ...
#[doc = "Register `OAR2` reader"] pub type R = crate::R<OAR2_SPEC>; #[doc = "Register `OAR2` writer"] pub type W = crate::W<OAR2_SPEC>; #[doc = "Field `ENDUAL` reader - Dual addressing mode enable"] pub type ENDUAL_R = crate::BitReader<ENDUAL_A>; #[doc = "Dual addressing mode enable\n\nValue on reset: 0"] #[derive(Clon...
#[cfg(test)] #[macro_use] extern crate yaserde_derive; pub mod discovery; pub mod soap; pub use schema; mod utils;
#![allow(unused_macros)] macro_rules! gen_hashmap { (@single $($e: tt)*) => (()); (@count $($e: expr)*) => (<[()]>::len(&[$(gen_hashmap!(@single $e)),*])); ($($key: expr => $value: expr,)+) => (gen_hashmap!($($key => $value),+)); {$($key: expr => $value: expr),*} => { { let cou...
use ComponentWeak; #[derive(Debug)] pub enum Error { #[allow(dead_code)] Unknown, HighVoltage(HighVoltage), } impl Error { pub fn is_high_voltage_error(&self) -> bool { match *self { Error::HighVoltage(_) => true, _ => false, } } } #[derive(Debug)] pub stru...
use std::iter::Iterator; use std::collections::HashMap; fn sum(spiral: &HashMap<(isize, isize), usize>, x: isize, y: isize) -> usize { let mut sum = 0usize; for i in x-1..x+2 { for j in y-1..y+2 { sum += match spiral.get(&(i, j)) { Some(value) => *value, Non...
//! Deserializing CDR into Rust data types. use std::{self, io::Read, marker::PhantomData}; use byteorder::{BigEndian, ByteOrder, LittleEndian, ReadBytesExt}; use serde::de::{self, IntoDeserializer}; use crate::{ error::{Error, Result}, size::{Infinite, SizeLimit}, }; /// A deserializer that reads bytes fro...
use crate::{Net, Spec, DEFAULT_TX_PROPOSAL_WINDOW}; use log::info; pub struct PoolReconcile; impl Spec for PoolReconcile { crate::name!("pool_reconcile"); crate::setup!(connect_all: false, num_nodes: 2); fn run(&self, net: &mut Net) { let node0 = &net.nodes[0]; let node1 = &net.nodes[1];...
extern crate rustc_serialize; extern crate rand; pub mod wrap_koh; pub mod koh;
use std::str::FromStr; use std::env; use std::process::*; #[derive(Debug)] pub enum SupportedLanguage { Rust, Typescript, } impl FromStr for SupportedLanguage { type Err = (); fn from_str(s: &str) -> Result<Self, Self::Err> { match s { "rust" => Ok(SupportedLanguage::Rust), ...
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #![feature(cell_extras)] #![feature(plugin)] #![feature(plugin_registrar)] #![feature(rustc_private)] #![plugin(c...
//! # Async GraphQL Telemetry Extension //! //! The `Extensions` trait in [async-graphql](https://github.com/async-graphql/async-graphql) essentially mimics traditional //! middleware in HTTP servers (although arguably more powerful due to the //! ability to hook into various stages of the query resolution). This exten...
use std::cell::Cell; use std::cell::RefCell; use std::f64; use std::rc::Rc; use wasm_bindgen::prelude::*; use wasm_bindgen::JsCast; use web_sys::{CanvasRenderingContext2d, HtmlCanvasElement, MouseEvent}; use crate::state::State; // setup mouse event listener for drawing and start pub fn canvas_draw_start( canvas:...
#![allow(non_snake_case)] extern crate bulletproofs; extern crate curve25519_dalek; extern crate merlin; extern crate rand; use bulletproofs::r1cs::*; use bulletproofs::{BulletproofGens, PedersenGens}; use curve25519_dalek::ristretto::CompressedRistretto; use curve25519_dalek::scalar::Scalar; use merlin::Transcript; ...
use std::collections::HashMap; use crate::{ ast::{Expr, FunctionStmt, Stmt}, interpreter::Interpreter, token::Token, }; pub struct Resolver<'interp> { interpreter: &'interp mut Interpreter, scopes: Vec<HashMap<String, bool>>, current_function: FunctionType, current_class: ClassType, } impl...
// Copyright 2018 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use async::Interval; use futures::prelude::*; use zx; pub fn retry_until<T, E, FUNC, FUT>(retry_interval: zx::Duration, mut f: FUNC) -> impl Future<It...
use crate::http; use crate::settings::global_user::GlobalUser; use crate::settings::target::Target; use crate::terminal::{emoji, message}; use serde::{Deserialize, Serialize}; #[derive(Serialize)] pub struct Subdomain { subdomain: String, } impl Subdomain { pub fn get(account_id: &str, user: &GlobalUser) -> ...
// Copyright (C) 2019 Boyu Yang // // 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 // except according t...
mod gen_network; use actix_rt::System; use bus::{Bus, BusActor}; use chain::ChainActor; use config::{get_available_port, NodeConfig}; use consensus::dev::DevConsensus; use crypto::{hash::PlainCryptoHash, keygen::KeyGen}; use futures_timer::Delay; use gen_network::gen_network; use libp2p::multiaddr::Multiaddr; use logg...
use crate as mongodb; // begin lambda connection example 2 use async_once::AsyncOnce; use lambda_runtime::{service_fn, LambdaEvent}; use lazy_static::lazy_static; use mongodb::{ bson::doc, options::{AuthMechanism, ClientOptions, Credential}, Client, }; use serde_json::Value; // Initialize a global static ...
#[doc = "Register `ICR` writer"] pub type W = crate::W<ICR_SPEC>; #[doc = "compare match Clear Flag\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum CMPMCFW_AW { #[doc = "1: Compare match Clear Flag"] Clear = 1, } impl From<CMPMCFW_AW> for bool { #[inline(always)] fn from(var...
use super::*; use math::*; use std::marker::PhantomData; pub enum Item<'a, T: Clone + 'a> { Text(T, &'a str, &'a str), Separator, Menu(&'a [Item<'a, T>]), } pub struct ItemStyle<D: ?Sized + Graphics> { pub label: D::Color, pub shortcut: D::Color, pub bg: D::Color, } pub struct MenuStyle<D: ?...
use imgui::*; use crate::{element::{EleAddr, Element}, entity::*}; fn find_entities(man: &mut Manager, name: &str) -> Vec<EntAddr> { let mut res = Vec::new(); for b in man.all_entities().iter() { let ent_name = b.get_ref().unwrap().name.clone(); if ent_name.contains(name) { res.push...
#[macro_use] extern crate buildinfo; fn main() { let info = buildinfo!(); println!("Target triple: {}", info.target_triple()); println!("Host triple: {}", info.host_triple()); println!("Opt level: {}", info.opt_level()); println!("Debug: {}", info.debug()); println!("Profile: {}", info.profile...
#[doc = "Reader of register MBIST_STAT"] pub type R = crate::R<u32, super::MBIST_STAT>; #[doc = "Reader of field `SFP_READY`"] pub type SFP_READY_R = crate::R<bool, bool>; #[doc = "Reader of field `SFP_FAIL`"] pub type SFP_FAIL_R = crate::R<bool, bool>; impl R { #[doc = "Bit 0 - Flag indicating the BIST run is done...
use std::path::PathBuf; fn main() -> anyhow::Result<()> { if !PathBuf::from("./minecraft").exists() { vanilla_assets::download_vanilla_assets(&PathBuf::from("../"))?; } Ok(()) }
use std::io::Cursor; use bitcoinrs_bytes::decode::ReadBuffer; use bitcoinrs_bytes::encode::WriteBuffer; use bitcoinrs_bytes::endian::{u32_b, u64_b}; type Word = u32; type HashValue = [Word; 8]; type MsgBlock = [Word; 16]; type ExpandedMsgBlock = [Word; 64]; // aka message schedule. pub fn sha256(msg: &[u8]) -> [u8; ...
#[macro_export] macro_rules! cast { ($e:expr) => { match $e.dyn_into() { Ok(casted) => Ok(casted), Err(_original) => Err(JsValue::from_str("failed to cast JsValue to given type")), } }; } #[macro_export] macro_rules! map_err_to_anyhow { ($e:expr) => { match $...
use aoc::read_data_space_saperator2; use std::collections::HashMap; use std::convert::Infallible; use std::error::Error; use std::str::FromStr; #[derive(Clone, Debug, PartialEq)] enum D { /// . D, /// # H, } impl std::fmt::Display for D { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt:...
use crate::cast_slice::cast_slice; use gl; use gl::types::{GLuint, GLint, GLchar, GLenum, GLsizeiptr, GLsizei}; use std; use std::ffi::CString; use std::error::Error; pub struct GlShader { pub handle: GLuint, } impl GlShader { pub fn new(shader_type: GLuint) -> GlShader { unsafe { GlShader { handle: gl::Creat...
use std::process::Command; use std::env; use std::path::Path; fn main() { let out_dir = env::var("OUT_DIR").ok().expect("can't find out_dir"); Command::new("windres").args(&["src/hello.rc", "-o"]) .arg(&format!("{}/hello.rc.o", out_dir)) .status().unwrap(); C...
use std::collections::HashSet; use std::fs::{self, File}; use std::io::{self, Read, Write}; use std::net::{SocketAddr, UdpSocket}; use std::path::Path; use std::str::{self, FromStr}; use std::sync::mpsc; use std::thread; use client::*; use wa_fsp::*; struct FspClient { socket: UdpSocket, server: SocketAddr, ...
use std::sync::Arc; use eyre::Report; use rosu_v2::prelude::GameMode; use twilight_model::application::{ command::CommandOptionChoice, interaction::{ application_command::{CommandDataOption, CommandOptionValue}, ApplicationCommand, }, }; use crate::{ commands::{MyCommand, MyCommandOpti...
// 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 { crate::story_manager::StoryManager, failure::{Error, ResultExt}, fidl_fuchsia_app_discover::{ SessionDiscoverContextRequest, Sess...
#![feature(duration_as_u128)] #![feature(fn_traits)] #![feature(unboxed_closures)] extern crate piston_window; extern crate piston; extern crate rand; extern crate euclid; extern crate conrod; extern crate rosrust; #[macro_use] extern crate rosrust_codegen; rosmsg_include!(); extern crate roadsim2dlib; use roadsim2...
//! Defines data structures of command line arguments. use clap; #[derive(Debug)] pub struct Config { pub src_path: Option<String>, pub main_path: Option<String>, pub install_mod_names: Vec<String>, } impl Config { pub fn from_matches(gm: &clap::ArgMatches) -> Self { let install_mod_names = m...
use crate::{ atlas::SpriteSheetInfo, tiled::{ map::{TiledMap, TiledMapLayerType}, tileset::TiledTileset, }, }; use serde::Serialize; use std::{ collections::HashMap, fs::{read_to_string, write}, io::{Error, ErrorKind}, path::Path, }; pub mod map; pub mod tileset; #[derive(D...
#![cfg_attr(not(feature = "with-syntex"), feature(rustc_private, plugin))] #![cfg_attr(not(feature = "with-syntex"), plugin(quasi_macros))] #![deny(missing_docs)] //! nue derive syntax extension. //! //! Provides the `#[derive(PodPacked, Pod, NueEncode, NueDecode)]` extensions documented in `nue-macros`. //! //! ## St...
pub use { any_bin::*, bin::*, bin_builder::*, bin_segment::*, excess_shrink::*, factory::*, into_iter::*, s_bin::*, }; mod any_bin; mod bin; mod bin_builder; mod bin_segment; mod excess_shrink; mod factory; mod into_iter; mod s_bin;
use std::collections::HashMap; fn play(input: &[i32], final_turn: usize) -> i32 { let mut seen: HashMap<i32, usize> = input[..input.len()-1].iter().enumerate() .map(|(t, &n)| (n, t)) .collect(); let mut last_spoken = *input.last().unwrap(); for turn in input.len()..final_turn { if ...
use structopt::StructOpt; use std::{fs::File, io::prelude::*, io::BufReader, io::Write}; use failure::ResultExt; use exitfailure::ExitFailure; #[derive(StructOpt, Debug)] struct Cli { /// The pattern to look for pattern: String, /// The path to the file to read #[structopt(parse(from_os_str))] path:...
use {data::semantics::Semantics, proc_macro2::TokenStream, quote::quote}; impl Semantics { pub fn runtime_render_functions() -> TokenStream { quote! { fn render_elements( group: &Group, parent: &mut HtmlElement, classes: &mut HashMap<&'static str, Group>, ) { let window = web_sys::window().unw...
impl Solution { pub fn first_bad_version(&self, n: i32) -> i32 { let (mut l,mut r) = (1,n); while l < r { let mid = ((l as i64 + r as i64) >> 1) as i32; if self.isBadVersion(mid){ r = mid; }else{ l = mid + 1; } }...
#[doc = "Register `OFR2` reader"] pub type R = crate::R<OFR2_SPEC>; #[doc = "Register `OFR2` writer"] pub type W = crate::W<OFR2_SPEC>; #[doc = "Field `OFFSET2` reader - Data offset 2 for the channel programmed into bits OFFSET2_CH"] pub type OFFSET2_R = crate::FieldReader<u16>; #[doc = "Field `OFFSET2` writer - Data o...
use crate::circular_buffer::CircularBuffer; use std::fmt; struct Indexes { i: usize, match_count: usize, min_match: usize, } pub struct Pattern<'a> { pattern: &'a [u8], lookback: CircularBuffer, idx: Indexes, } impl<'a> Pattern<'a> { pub fn new(pattern: &'a [u8]) -> Self { Pattern...
#[no_mangle] pub extern fn physics_single_chain_swfjc_thermodynamics_isotensional_end_to_end_length(number_of_links: u8, link_length: f64, well_width: f64, force: f64, temperature: f64) -> f64 { super::end_to_end_length(&number_of_links, &link_length, &well_width, &force, &temperature) } #[no_mangle] pub exte...
use crate::rtb_type_strict; rtb_type_strict! { SizeUnit, Dips=1; Inches = 2; Centimeters = 3 } impl Default for SizeUnit { fn default() -> Self { Self::Dips } }
//! src/models.rs use serde::{Deserialize, Serialize}; use uuid::Uuid; #[derive(Debug, Serialize, Deserialize)] pub struct Recipe { id: uuid::Uuid, title: String, content: String, author: User, published: bool, } #[derive(Debug, Serialize, Deserialize)] pub struct RecipeOut { pub id: uuid::Uuid, pub ti...
use dashmap::DashMap; use serenity::prelude::TypeMapKey; use std::sync::Arc; #[derive(Clone, Default)] pub struct GameState { pub channel: Arc<DashMap<u64, bool>>, } impl GameState { pub fn new() -> Self { Self::default() } } impl TypeMapKey for GameState { type Value = GameState; }
pub fn salary() { println!("Welcome in HR -> Salary ") }
use std::ops::ControlFlow; use std::time::Instant; const INPUT: &str = include_str!("../input.txt"); fn part1() -> i64 { INPUT.chars().fold(0, |acc, c| match c { ')' => acc - 1, '(' => acc + 1, _ => unreachable!(), }) } fn part2() -> usize { let result: ControlFlow<usize, i64> = I...
fn square_sum(vec: Vec<i32>) -> i32 { let mut sum: i32 = 0; for i in vec { sum += i.pow(2); } return sum; }
use smol::channel::{Receiver, Sender}; use std::fmt::{Debug, Formatter, Result as FmtResult}; use std::net::SocketAddr; /// Endpoint can receied this message channel. #[derive(Clone, Debug, PartialEq, Eq)] pub enum EndpointSendMessage { /// connect to a socket address. /// params is `socket_addr`, `remote_pk_i...
// #![crate_type="lib"] pub mod Hangman{ // use std::io; pub struct Hangman{ word: String, } pub fn new(word: String) -> Hangman{ Hangman{ word:word, } } // pub fn get_input() -> String{ // let mut input = String::new(); // println!...
use crate::error::{from_protobuf_error, NiaServerError, NiaServerResult}; use crate::protocol::Serializable; use protobuf::Message; #[derive(Clone, Debug, PartialEq, Eq)] pub struct ActionMouseAbsoluteMove { x: i32, y: i32, } impl ActionMouseAbsoluteMove { pub fn new(x: i32, y: i32) -> ActionMouseAbsolute...
// Handles config related to the workspace // Current use case is setting up a git repo // for the workspace use crate::er::{self, Result}; use crate::git; use crate::utils::{self, CliEnv}; use futures::{ future::{self, Either}, Future, }; /// Initializes a git repo for the workspace, using /// defined git ac...
use byteorder::{ByteOrder, LittleEndian}; use ckb_chain_spec::consensus::Consensus; use ckb_dao_utils::{extract_dao_data, pack_dao_data, DaoError}; use ckb_error::Error; use ckb_script_data_loader::DataLoader; use ckb_store::{data_loader_wrapper::DataLoaderWrapper, ChainStore}; use ckb_types::{ bytes::Bytes, co...
mod commands; mod events; // mod server; use commands::math::*; use commands::music::*; use commands::reply::*; use serenity::{framework::standard::StandardFramework, http::Http, Client}; use songbird::SerenityInit; use std::{collections::HashSet, thread}; // Start //////////////////////////////////////////////////////...
/* chapter 4 syntax and semantics */ fn main() { let a = vec![1, 2, 3, 4, 5]; // works let b: usize = 0; println!("the first element of n is {}", a[b]); // doesn't /* let c: i32 = 0; a[c]; */ } // output should be: /* the first element of n is 1 */
pub fn run() { let closures_var = |x: i32| { println!("{}", x); }; closures_var(2019); }
#[doc = r"Register block"] #[repr(C)] pub struct RegisterBlock { #[doc = "0x00..0x40 - DMAMux - DMA request line multiplexer channel x control register"] pub ccr: [CCR; 16], _reserved1: [u8; 0x40], #[doc = "0x80 - DMAMUX request line multiplexer interrupt channel status register"] pub csr: CSR, ...
#[doc = "Register `CFR` writer"] pub type W = crate::W<CFR_SPEC>; #[doc = "Field `CSOF0` writer - Clear synchronization overrun event flag Writing 1 in each bit clears the corresponding overrun flag SOFx in the DMAMUX_CSR register."] pub type CSOF0_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field ...
extern crate reqwest; extern crate web3; #[macro_use] extern crate serde_derive; extern crate serde_json; use std::env; use web3::futures::Future; use web3::types::BlockId; const DEFAULT_NUM_BLOCKS: usize = 5; #[derive(Deserialize, Debug)] struct BlockNumber { jsonrpc: String, id: String, result: String ...
mod actions; use yew::prelude::*; pub struct Body; impl Component for Body { type Message = (); type Properties = (); fn create(_: Self::Properties, _: ComponentLink<Self>) -> Self { Body } fn update(&mut self, _: Self::Message) -> ShouldRender { false } } impl Renderable<B...
/// An enum to represent all characters in the Sharada block. #[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)] pub enum Sharada { /// \u{11180}: '𑆀' SignCandrabindu, /// \u{11181}: '𑆁' SignAnusvara, /// \u{11182}: '𑆂' SignVisarga, /// \u{11183}: '𑆃' LetterA, /// \u{11184}: '𑆄...
use lexer::{Input, State, Reader}; use super::super::utils; use super::super::token::{Token, TokenKind}; #[derive(Debug, Clone, Eq, PartialEq, Hash)] pub struct WhitespaceReader; impl Reader<TokenKind> for WhitespaceReader { #[inline(always)] fn priority(&self) -> usize { 0usize } fn read(&self, input...
use super::*; #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] #[repr(transparent)] pub struct WaveControl(u8); impl WaveControl { const_new!(); bitfield_bool!(u8; 5, two_banks, with_two_banks, set_two_banks); bitfield_bool!(u8; 6, use_bank1, with_use_bank1, set_use_bank1); bitfield_bool!(u8; 7, playing, ...
use std::fs::File; use std::io::{BufRead, BufReader}; fn main() { let path = "input.txt"; let input = File::open(path).expect("Unable to open file!"); let buffered = BufReader::new(input); let mut list = buffered .lines() .map(|word| word.unwrap().parse::<i32>().unwrap()) .coll...
extern crate rand; extern crate sdl2; mod mmu; mod cpu; mod gfx; mod term_gfx; use std::time::Duration; use std::thread; use mmu::Mmu; use cpu::Cpu; use gfx::Gfx; fn main() { let filename = String::from("./roms/UFO"); let mut mmu = Mmu::new(); mmu.load_rom(filename); let mut cpu = Cpu::new(mmu); ...
#![feature(test)] extern crate funnel; #[macro_use] extern crate lazy_static; extern crate rand; extern crate test; use rand::{ distributions::{Alphanumeric, Standard}, thread_rng, Rng, }; use test::Bencher; use funnel::{ bit, signs::{self, Signs}, }; const MAX: u64 = 10_000_000; lazy_static! { ...
use config_rs; use std::collections::HashMap; type Config = HashMap<String, String>; pub fn load(config_file: String) -> Config { // create config object let mut settings = config_rs::Config::default(); // check if config_file was supplied, if it was then load it if config_file != "" { set...
use rustc_serialize::base64; use rustc_serialize::base64::{ToBase64, FromBase64, FromBase64Error}; use std::convert::AsRef; fn config_base64() -> base64::Config { base64::Config { char_set: base64::CharacterSet::Standard, newline: base64::Newline::LF, pad: false, line_length: None,...
enum MessageType { Error, // 1 Warning, // 2 Info, // 3 Log, // 4 } struct ShowMessageNotificationParams { type: MessageType, message: String, } impl Notification for ShowMessageNotificationParams { method = "window/showMessage" } struct MessageActionItem { title: String, } struct Sh...
use aes_soft::Aes256; use block_modes::block_padding::Pkcs7; use block_modes::{BlockMode, Cbc}; use ed25519_dalek::{ Keypair as Ed25519_Keypair, PublicKey as Ed25519_PublicKey, Signature as Ed25519_Signature, Signer, Verifier, KEYPAIR_LENGTH, PUBLIC_KEY_LENGTH, SECRET_KEY_LENGTH, SIGNATURE_LENGTH, }; use postca...
//! Timers // TODO: on the h7x3 at least, only TIM2, TIM3, TIM4, TIM5 can support 32 bits. // TIM1 is 16 bit. use crate::hal::timer::{CountDown, Periodic}; use crate::stm32::{LPTIM1, LPTIM2, LPTIM3, LPTIM4, LPTIM5}; use crate::stm32::{ TIM1, TIM12, TIM13, TIM14, TIM15, TIM16, TIM17, TIM2, TIM3, TIM4, TIM5, TI...
//! Defines how the chess board is represented in memory. use std::fmt; use utils::parse_fen; /// `WHITE` or `BLACK`. pub type Color = usize; pub const WHITE: Color = 0; pub const BLACK: Color = 1; /// `KING`, `QUEEN`, `ROOK`, `BISHOP`, `KINGHT`, `PAWN` or `PIECE_NONE`. pub type PieceType = usize; pub const KING...
use criterion::{criterion_group, criterion_main, Bencher, Criterion}; use rand::{ distributions::{Distribution, Standard, Uniform}, Rng, SeedableRng, }; use rand_distr::Alphanumeric; use rand_regex::Regex; use rand_xorshift::XorShiftRng; fn alphanumeric_baseline(b: &mut Bencher<'_>) { let mut rng = XorShif...
pub fn get_row(r: i32) -> Vec<i32> { let r = r as usize; let mut result = Vec::with_capacity(r+1); let mut c = 1; result.push(c as i32); for i in 0..r { c *= r - i; c /= i + 1; result.push(c as i32); } result }
use crate::system::System; use imgui::{im_str, Condition, Slider, Window}; use std::f32::consts::PI; mod simulation; mod system; fn main() { println!("Hello, world!"); let system = System::init("Slime Simulation"); // ---- Computing to an image buffer ---- let sim = simulation::Simulation::init(sys...