text
stringlengths
8
4.13M
use lazy_static::lazy_static; use std::cmp::{max, min}; use std::collections::HashMap; use std::convert::TryFrom; use std::convert::TryInto; use std::fmt; type Offsets = (i32, i32); /// Assuming each piece pseudo-occupies a 4x4 square, then these 4 /// offsets gives the cells that are actually occupied in that 4x4 //...
use super::input::CmdInput; use std::error::Error; use std::fs; fn get_file_content(input: &CmdInput) -> Result<String, Box<dyn Error>> { Ok(fs::read_to_string(&input.path[..])?) } fn is_query_in_content(content: String, input: &CmdInput) -> bool { let query = &input.query[..]; if input.is_case_sensitive...
#[doc = "Reader of register ADDR"] pub type R = crate::R<u32, super::ADDR>; #[doc = "Writer for register ADDR"] pub type W = crate::W<u32, super::ADDR>; #[doc = "Register ADDR `reset()`'s with value 0"] impl crate::ResetValue for super::ADDR { type Type = u32; #[inline(always)] fn reset_value() -> Self::Typ...
#[allow(unused_variables)] fn main() { let x = 6; println!("The value of x is: {}", x); another_function(3,4); } fn another_function(x: i32, y: i32) { println!("The value of x is: {}", x); println!("The value of y is: {}", y); }
use std::sync::Arc; use rosu_v2::prelude::{GameMode, OsuError}; use twilight_model::{ application::interaction::{ application_command::{CommandDataOption, CommandOptionValue}, ApplicationCommand, }, id::{marker::UserMarker, Id}, }; use crate::{ commands::{ check_user_mention, ...
fn main() { proconio::input! { r: f64, x: f64, y: f64, } let distance:f64 = x*x + y*y; let mut upper_limit: f64 = distance.sqrt(); let mut count = 1; let ep = 0.000000001; // println!("{}", upperLimit); while upper_limit > r + ep { upper_limit -= r; ...
use crate::prelude::*; use azure_core::prelude::*; use http::StatusCode; use std::convert::TryInto; #[derive(Debug, Clone)] pub struct CreateReferenceAttachmentBuilder<'a, 'b> { attachment_client: &'a AttachmentClient, user_agent: Option<UserAgent<'b>>, activity_id: Option<ActivityId<'b>>, consistency_...
#[macro_export] macro_rules! make_id_type { ($type:ident, $int_type:ident) => { #[repr(transparent)] #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord)] pub struct $type($int_type); impl $type { pub const fn from(id: $int_type) -> Self { Self(id) } pub const fn into(self) -> $...
extern crate libc; extern crate term; use std::io; use std::str; use std::process; use std::io::BufReader; use std::io::prelude::*; use std::mem::transmute; use std::collections::LinkedList; use std::collections::HashSet; mod terminal_control; pub struct OptionStore { pub key: String, pub value: String, } #...
//! `x86_64` intrinsics #[path = "../x86/mod.rs"] mod x86; pub use self::x86::*; mod abm; pub use self::abm::*; mod avx; pub use self::avx::*; // mod avx2; // pub use self::avx2::*; // mod bmi1; // pub use self::bmi1::*; // mod bmi2; // pub use self::bmi2::*; mod bswap; pub use self::bswap::*; // mod fxsr; // ...
macro_rules! path { ($($tt:tt)+) => { tokenize_path!([] [] $($tt)+) }; } // Private implementation detail. macro_rules! tokenize_path { ([$(($($component:tt)+))*] [$($cur:tt)+] /) => { crate::directory::Directory::new(tokenize_path!([$(($($component)+))*] [$($cur)+])) }; ([$(($($co...
const MAX_POINT: u32 = 100000; fn main() { //1 .ๅ˜้‡ๅฎšไน‰ let // ๅฆ‚ๆžœๅ˜้‡ๆฒกๆœ‰็”จ mut, ้‚ฃไนˆๆ˜ฏไธๅฏๅ˜็š„ let a = 1; let mut b: u32 = 1; println!("a = {}, b = {}", a, b); b = 2; println!("b = {}", b); // 2.้š่—ๆ€ง // ๅŒๅๅ˜้‡้š่—ๅ‰้ขๅฎšไน‰็š„ๅ˜้‡ let b: f32 = 1.1; println!("b = {}", b); // 3.ๅธธ้‡ println!("MAX_PO...
use std::sync::mpsc::{Sender}; use messages::{Message}; use ws; use errors; pub struct Connection { tx_to_game_state : Sender<Message>, connection_id : u64, } impl Connection { pub fn new(connection_id : u64, tx: Sender<Message> ) -> Self { Self { tx_to_game_state: tx, connection_id } } f...
extern crate sys_info; use sys_info::*; fn main() { println!("OS type : {}", os_type().unwrap_or("Error".to_owned())); println!("OS release : {}", os_release().unwrap_or("Error".to_owned())); println!(); println!("System uptime : {} seconds", uptime().unwrap_or(-1)); println!...
use pasts::prelude::*; #[test] fn join6() { static EXECUTOR: pasts::CvarExec = pasts::CvarExec::new(); let future = async { ( async { 1i32 }, async { 'a' }, async { 4.0f32 }, async { "boi" }, async { [4i32, 6i32] }, async { (2i32, ...
extern crate daemonize; use clap::{App, Arg}; use easy_cron::{current_jobs, delete_all_jobs, process_cron}; fn main() { let matches = App::new("Easy Cron") .version("0.1.1") .author("Sanskar Jethi <sansyrox@gmail.com>") .about("Easily schedule your task") .arg( Arg::new...
#[doc = "Register `DDRCTRL_MRSTAT` reader"] pub type R = crate::R<DDRCTRL_MRSTAT_SPEC>; #[doc = "Field `MR_WR_BUSY` reader - MR_WR_BUSY"] pub type MR_WR_BUSY_R = crate::BitReader; impl R { #[doc = "Bit 0 - MR_WR_BUSY"] #[inline(always)] pub fn mr_wr_busy(&self) -> MR_WR_BUSY_R { MR_WR_BUSY_R::new((s...
use netlify_lambda_http::{handler, lambda::{self, Context}, IntoResponse, Request, RequestExt}; use serde_json::{json}; use http::{header::HeaderValue, HeaderMap}; use std::collections::HashMap; type Error = Box<dyn std::error::Error + Send + Sync + 'static>; fn convert(headers: &HeaderMap<HeaderValue>) -> HashMap<St...
extern crate libc; use tspi::*; #[link(name = "tspi")] extern "C" { pub fn Trspi_Error_String(result: TSS_RESULT) -> *mut libc::c_char; }
/// An enum to represent all characters in the Avestan block. #[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)] pub enum Avestan { /// \u{10b00}: '๐ฌ€' LetterA, /// \u{10b01}: '๐ฌ' LetterAa, /// \u{10b02}: '๐ฌ‚' LetterAo, /// \u{10b03}: '๐ฌƒ' LetterAao, /// \u{10b04}: '๐ฌ„' LetterA...
use indexmap::IndexMap; use serde::{Deserialize, Serialize}; use std::collections::BTreeMap; use std::cmp::Ordering; use crate::primitives::*; #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub enum CustomType { Enum { variant: EnumVariant, variants: BTreeMap<VariantKey, CustomType>...
use ofborg::ghevent::{Comment, Repository, Issue}; #[derive(Serialize, Deserialize, Debug)] pub struct IssueComment { pub comment: Comment, pub repository: Repository, pub issue: Issue, }
pub mod interface; pub mod apu; pub mod cassette; pub mod cpu; pub mod cpu_instruction; pub mod cpu_register; pub mod pad; pub mod ppu; pub mod system; pub mod system_apu_reg; pub mod system_ppu_reg; pub mod video_system; pub use apu::*; pub use cassette::*; pub use cpu::*; pub use pad::*; pub use ppu::*; pub use sys...
use std::{fmt::Write, sync::Arc}; use eyre::Report; use rosu_v2::prelude::{ GameMode, GameMods, OsuError, RankStatus::{Approved, Loved, Qualified, Ranked}, Score, User, }; use tokio::time::{sleep, Duration}; use twilight_model::application::{ command::CommandOptionChoice, interaction::{ app...
//! RolesCache is a module that caches received from db information about user and his roles use failure::Fail; use stq_cache::cache::Cache; use stq_types::{DeliveryRole, UserId}; pub struct RolesCacheImpl<C> where C: Cache<Vec<DeliveryRole>>, { cache: C, } impl<C> RolesCacheImpl<C> where C: Cache<Vec<De...
pub enum List { Cons(i32, Box<List>), Nil, } use List::{Cons, Nil}; fn main() { // smart pointer is data structure which consists of additional meta data and ability, not only // simple pointer let list = Cons(1, Box::new(Cons(2, Box::new(Cons(3, Box::new(Nil)))))); }
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under both the MIT license found in the * LICENSE-MIT file in the root directory of this source tree and the Apache * License, Version 2.0 found in the LICENSE-APACHE file in the root directory * of this source tree. */ use a...
use crate::core::clients::StorageAccountClient; use crate::table::prelude::*; use crate::table::requests::*; use bytes::Bytes; use http::method::Method; use http::request::{Builder, Request}; use std::sync::Arc; pub trait AsPartitionKeyClient<PK: Into<String>> { fn as_partition_key_client(&self, partition_key: PK)...
use proconio::{fastout, input}; #[fastout] fn main() { input! { mut x: i64, mut k: i64, d: i64, }; if x < 0 { x *= -1; }; let alpha = x / d; // let beta = x % d; let beta = x - alpha * d; println!( "{}", if k <= alpha { x - k *...
use std::collections::HashMap; use std::fmt; use std::process::Command; extern crate time; struct Commit { author: String, tm: time::Tm } impl fmt::Debug for Commit { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Commit: {{ author: {}, tm: {:?} }}", self.author, self.tm) } ...
use auto_impl::auto_impl; #[auto_impl(&, &mut)] trait MyTrait<'a, T> { fn execute<'b, U, const N: usize>(&'a self, arg1: &'b T, arg2: &'static str, arg3: U) -> Result<(), String>; } fn main() {}
use std::env; pub fn run(){ let args: Vec<String> = env::args().collect(); let command = args[1].clone(); let name = "Rana Usama Ali"; if command == "hello" { println!("hi {}, how you are you", name); } // println!("Args : {:?}", command); }
/// Url of the website pub const BUTTERFLY_URL: &str = "http://biokite.com/worldbutterfly/"; /// Directory which stores the downloaded files pub const ASSET_DIRECTORY: &str = "./assets"; /// Directory which stores the images pub const IMAGE_DIRECTORY: &str = "images"; /// Directory which store the pdf files pub const P...
use aoc_runner_derive::*; struct Ticket { row: [bool; 7], col: [bool; 3], } macro_rules! binary_search { ($arr:expr, $start:expr, $end:expr) => {{ let len = $arr.len(); let mut a = $start; let mut b = $end; for i in 0..(len - 1) { let mid = (a + b) / 2; ...
// Copyright (c) Microsoft. All rights reserved. use std; use std::borrow::Cow; use std::ffi::{CStr, OsStr, OsString}; use std::fs::File; use std::io::{Read, Write}; use std::net::TcpStream; use std::path::PathBuf; use std::process::Command; use failure::Fail; use failure::{self, Context, ResultExt}; use futures::fut...
import option::{option,some,none}; import geom::*; import mine::*; enum cmd { move(dir), wait, shave } type score = i64; type state = { mine: mine, rloc: point, time: area, lgot: area, wdmg: area, water: coord, razors: area, rolling: area, rollrect: rect, collected: bool, c...
use super::*; use std::fs::{read, read_to_string}; #[test] fn affect_err() { test("affect-err"); } #[test] fn affect() { test("affect"); } #[test] fn boucle() { test("boucle"); } #[test] fn expression() { test("expression"); } #[test] fn max() { test("max"); } #[test] fn tri() { test("tri"...
// pub mod app; pub mod common; pub mod ecs; pub mod graphics; use futures::executor::block_on; use winit::{ event::*, event_loop::{ControlFlow, EventLoop}, window::WindowBuilder, }; use crate::graphics::{GraphicsConfig, State}; pub fn main() -> anyhow::Result<()> { let event_loop = EventLoop::new();...
use crate::TypeInfo; /// A constant value. #[derive(Debug, Clone)] pub enum ConstValue { /// A constant unit. Unit, /// A boolean constant value. Bool(bool), /// A string constant designated by its slot. String(Box<str>), /// An integer constant. Integer(i64), /// An float constant....
use std::rc::Rc; use std::fmt; use std::convert::TryFrom; use super::GreyError; #[derive(Clone,Debug)] pub enum GreyType { List(Vec<Rc<GreyType>>), RawList(Vec<super::Token>), Number(f64), Boolean(bool), String(String), Nil, Callable(Box<super::Callable>) } impl GreyType { pub fn to_ve...
mod route_map; mod routes; mod util; pub use route_map::service_handler;
use crate::db::cf_handle; use crate::{ internal_error, Col, Result, RocksDB, RocksDBSnapshot, RocksDBTransaction, RocksDBTransactionSnapshot, }; use rocksdb::{ops::IterateCF, ReadOptions}; pub use rocksdb::{DBIterator as DBIter, Direction, IteratorMode}; pub type DBIterItem = (Box<[u8]>, Box<[u8]>); pub trait...
//! This example demonstrates how to define run-time resources, i.e. multiple //! resources with the same static type. Such a pattern is useful for scripting, //! but it's generally not recommended to use this to define multiple //! resources of a standard Rust type. //! //! For Specs (https://github.com/slide-rs/specs...
use failure::Error; use futures::future::{self, Either}; use futures::prelude::*; use reqwest::StatusCode; use reqwest::header; use reqwest::unstable::async::Response; use serde_json::{self, Value}; use slog::Logger; use github::notification::Notification; pub struct NotificationsResponse { pub notifications: Vec...
use amethyst::prelude::*; use amethyst::{SimpleState, StateData, GameData}; use amethyst_imgui::imgui; use amethyst::input; use std::time::Instant; use crate::entities::ball; use crate::entities::player; pub struct GameState{ last_spawn_time : Instant, ball_count : i32 } impl Default for GameState { fn defaul...
use amethyst::{ assets::PrefabData, derive::PrefabData, ecs::{Component, DenseVecStorage, Entity, WriteStorage}, Error, }; use serde::{Deserialize, Serialize}; #[derive(Clone, Copy, Debug, Default, Serialize, Deserialize, PrefabData)] #[prefab(Component)] pub struct Human; impl Component for Human { ...
extern crate nalgebra as na; use macroquad::prelude::*; mod fiz; mod game; mod thing; use crate::game::Game; fn conf() -> Conf { Conf { window_title: String::from("Macroquad"), window_width: 1260, window_height: 768, fullscreen: false, ..Default::default() } } #[macr...
use log::warn; use std::collections::HashMap; use std::error::Error; use std::fs; use std::path::{Path, PathBuf}; #[derive(Debug)] pub struct File { /// Full path of the current directory pub path: PathBuf, } #[derive(Debug)] pub struct DirTree { /// Full path of the current directory pub path: PathB...
use std::path::Path; use std::fs::File; use std::io::{self, BufReader}; use std::io::prelude::*; use std::process::Command; pub fn get_type_by_magic(filename: &str) -> Result<String, io::Error> { if let Ok(output) = Command::new("file") .arg("-E") .arg("-b") .arg("--mime-type") .arg...
use crate::client::html_client::Client; use clap::App; use clap::SubCommand; use clap::Arg; use clap::ArgMatches; use crate::cli::HnCommand; use crate::error::HnError; /// Login with a given username and password pub struct Login; impl HnCommand for Login { const NAME: &'static str = "login"; fn parser<'a...
#![feature(test)] extern crate test; use rand::{prelude::random, rngs::SmallRng, Rng, SeedableRng}; use test::Bencher; use ppar::arc::Vector; #[bench] fn bench_prepend(b: &mut Bencher) { let seed: u128 = random(); println!("bench_prepend seed:{}", seed); let mut rng = SmallRng::from_seed(seed.to_le_byte...
use super::*; use super::types::*; use lib::*; #[cfg(feature = "std")] mod hextest { use super::super::*; use lib::*; #[test] fn bytes() { let encoded = hex!(" 0000000000000000000000000000000000000000000000000000000000000020 0000000000000000000000000000000000000000000000000000000000000002 1234000000000...
// (C) Copyright 2019-2020 Hewlett Packard Enterprise Development LP use std::convert::TryFrom; use crate::Span; use crate::dockerfile_parser::Instruction; use crate::error::*; use crate::util::*; use crate::parser::*; /// A Dockerfile [`ENTRYPOINT` instruction][entrypoint]. /// /// An entrypoint may be defined as e...
pub mod client; pub mod server; pub mod packet; pub mod analyzer; pub mod analyzer_event;
use crate::player::{db_to_ratio, ratio_to_db}; use super::mappings::{LogMapping, MappedCtrl, VolumeMapping}; use super::{Mixer, MixerConfig, VolumeCtrl}; use alsa::ctl::{ElemId, ElemIface}; use alsa::mixer::{MilliBel, SelemChannelId, SelemId}; use alsa::{Ctl, Round}; use std::ffi::CString; #[derive(Clone)] #[allow(...
use std::{collections::HashMap, convert::TryInto}; use crate::parsers::{ common::{FormId, TypeCode}, records::{record, Record}, }; use byteorder::{LittleEndian, ReadBytesExt}; use nom::{ bytes::complete::take, combinator::map, number::complete::{le_u16, le_u32}, sequence::{delimited, tuple}, }...
use std::io::{self}; fn to_binary(c: char) -> &'static str { match c { '0' => "0000", '1' => "0001", '2' => "0010", '3' => "0011", '4' => "0100", '5' => "0101", '6' => "0110", '7' => "0111", '8' => "1000", '9' => "1001", 'A' =>...
use std::process::Command; pub fn encode_u16(num: u16) -> [u8; 2] { num.to_le_bytes() } pub fn decode_u16(bytes: &[u8]) -> String { let mut buf = [0u8; 2]; buf[0..2].copy_from_slice(bytes); u16::from_le_bytes(buf).to_string() } pub fn need_dep(name: &str) { Command::new(name) .arg("--vers...
#[macro_export] macro_rules! configurator { ($config_name:ident { $($attr_fixed:ident : $attr_fixed_type:ty, $fixed_doc:expr),*; $($attr_def:ident : $attr_def_type:ty = $def:expr, $def_doc:expr),* }) => { #[derive(Debug)] pub struct $config_name { $(#[doc = $fixed_doc...
use std::collections::HashMap; pub type Ini = HashMap<String, HashMap<String, Option<String>>>; pub fn to_ini(ini: &Ini) -> String { let mut s = String::new(); for (section, v) in ini { s += &format!("[{}]\n", section); for (key, value) in v { match value { Some(v...
pub trait Mem { fn new(len: usize) -> Self; unsafe fn from_raw(base: *mut usize, len: usize) -> Self; fn into_raw(self) -> (*mut usize, usize); } impl Mem for Box<[usize]> { fn new(len: usize) -> Self { vec![0; len].into_boxed_slice() } unsafe fn from_raw(base: *mut usize, len: usize) ...
use core::*; use std::*; use std::any::*; use std::cmp::*; use std::collections::*; use std::iter::*; use std::rc::*; use std::cell::*; use std::sync::*; use std::mem::*; pub struct World { /// A scene consists of a list of entities. entities: Vec<Entity>, /// Each Entity has components. Components are ra...
#![allow(dead_code, unused_imports)] extern crate futures; extern crate tokio_core; extern crate tokio_io; extern crate hyper; #[macro_use] extern crate log; extern crate env_logger; extern crate threadpool; #[macro_use] extern crate chan; use std::thread; use std::env; use std::net::SocketAddr; use std::str::FromStr;...
use super::utils::parse_string; use crate::ast::rules; // or // and // < > <= >= ~= == // | // ~ // & // << >> // .. // + - // * / // % // ^ #[test] fn test_operator_simple() { assert_eq!( parse_string("1 ^ 5", rules::exp), "[Single(Binop(POW, Number(1.0), Number...
#[macro_use] extern crate bitmask; bitmask! { mask BitMask: u32 where flags Flags { Flag1 = 1, Flag2 = 2, Flag3 = 4, Flag4 = 8 } } struct FakeMask { mask: u32 } impl ::std::ops::Deref for FakeMask { type Target = u32; fn deref(&self) -> &Self::Target { &sel...
use serenity::{ framework::standard::{ macros::{command, group}, Args, CommandResult, }, model::channel::Message, prelude::*, }; #[group] #[commands(sum, sub, mul, div, md)] #[prefixes("math")] struct Math; #[macro_export] macro_rules! math_fn { ($name: ident,$ctx: ident, $msg: ide...
use actix_web::HttpResponse; use futures::lock::Mutex; use serde::Serialize; use libapi_net::client::Client; use libapi_http::api::ValueResponse; pub struct State { pub rover_client: Mutex<Client> } pub fn map_rover_status_to_response<T, E: std::error::Error>(r: Result<T, E>) -> HttpResponse { match r { ...
mod uvec2; mod uvec3; mod uvec4; pub use uvec2::{uvec2, UVec2}; pub use uvec3::{uvec3, UVec3}; pub use uvec4::{uvec4, UVec4}; #[cfg(not(target_arch = "spirv"))] mod test { use super::*; mod const_test_uvec2 { #[cfg(not(feature = "cuda"))] const_assert_eq!( core::mem::align_of::<u32...
use std::str::FromStr; use anyhow::Result; use nom::sequence::tuple; use nom::{ bytes::complete::tag, character::complete::{alphanumeric1, anychar, char, digit1}, combinator::map_res, IResult, }; use advent20::input_string; struct ParsedInput<'a> { pub min: usize, pub max: usize, pub c: c...
#[cfg(not(windows))] fn main() {} #[cfg(windows)] fn main() { windows::build!( Windows::Win32::System::SystemServices::{ HANDLE, TRUE, FALSE }, Windows::Win32::System::WindowsProgramming::{ GetStdHandle, STD_OUTPUT_HANDLE, ...
#![cfg(target_os = ["linux", "macos"])] //! Self Grading Tool // MEASURE and enforce Constraints // Runtime // Memory used by process // TEST // Algorithm correctness use std::env; use std::process::{Command, Stdio}; use std::time::Instant; extern crate stress; // use std::fs; // use std::str::from_utf8; fn main() ...
use std::{ env, fs::File, io::{self, BufRead, BufReader}, process::Command, }; pub struct CustomCommand { pub shortcut: String, pub command: String, pub args: Vec<String>, } impl CustomCommand { pub fn load_custom_commands() -> Vec<CustomCommand> { Self::try_load_custom_command...
/// An enum to represent all characters in the Cuneiform block. #[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)] pub enum Cuneiform { /// \u{12000}: '๐’€€' SignA, /// \u{12001}: '๐’€' SignATimesA, /// \u{12002}: '๐’€‚' SignATimesBad, /// \u{12003}: '๐’€ƒ' SignATimesGan2Tenu, /// \u{12004...
use auto_impl::auto_impl; #[auto_impl(Box)] trait BoxTrait1<'a, T: for<'b> Into<&'b str>> { type Type1; type Type2; const FOO: u32; fn execute1<'b>(&'a self, arg1: &'b T) -> Result<Self::Type1, String>; fn execute2(&mut self, arg1: i32) -> Self::Type2; fn execute3(self) -> Self::Type1; f...
use log::{error, info}; use rand::{seq::IteratorRandom, thread_rng}; use std::collections::HashMap; use std::sync::{atomic::Ordering, Arc}; use std::time::Duration; use crate::app_state::AppState; use crate::config_store::{ConfigStoreFunc, Monitor}; use crate::file_store::FileStoreFunc; use crate::http_requests::{dist...
extern crate rand; use rand::Rng; use std::env; use std::thread; use std::net::{TcpListener, TcpStream, Shutdown}; use std::io::{Read, Write}; use std::str::from_utf8; fn client(ip: &String) { match TcpStream::connect(ip) { Ok(mut stream) => { let s_hash: String = get_hash(); let mut s_key: S...
use rusttype::*; static ROBOTO_REGULAR: &[u8] = include_bytes!("../fonts/Roboto-Regular.ttf"); #[test] fn consistent_bounding_box_subpixel_size_proxy() { let font = Font::try_from_bytes(ROBOTO_REGULAR).unwrap(); let height_at_y = |y| { font.glyph('s') .scaled(rusttype::Scale::uniform(20.0)...
use crossterm::{ cursor, event::{KeyCode, KeyEvent, KeyModifiers}, queue, style::{ Attribute, Color, Print, ResetColor, SetAttribute, SetBackgroundColor, SetForegroundColor, }, terminal::{self, Clear, ClearType}, QueueableCommand, Result, }; use std::io::Write; use crate::{...
//! Simplifies branches and removes empty basic blocks. //! //! # Optimizations //! //! Branching simplify performs the follow optimizations: //! //! - Replaces `brif _ bbI bbI` into `br bbI`. //! //! - Replaces `brif 0 bbI bbJ` into `br bbJ`; replaces `brIf x bbI bbJ` into //! `br bbI` where `x` is an immediate and ...
fn main() { println!("Hello, world from Cargo! :-)"); }
//! Raw, unparsed ROTMG packets. //! //! Raw packets represent packets that have been framed and decrypted so that //! the binary payload and ID can be accessed, but aren't necessarily parsed. //! These are primarily intended as an intermediary form, for cases where a //! packet may not need to be parsed, or parsing ma...
use super::models::{CrateInfo, IndexMetadata}; use crate::config::Config; use anyhow::{anyhow, bail, Context, Result}; use log::debug; use semver::Version; use std::{path::PathBuf, sync::Arc}; use tokio::{ fs::{self, File, OpenOptions}, io::AsyncBufReadExt, io::{AsyncWriteExt, BufReader}, sync::RwLock, ...
#[path = "./alphabet.rs"] mod alphabet; // calculate the correct index when shifting to the left fn get_left_idx(idx: usize, offset: usize) -> usize { if idx >= offset { return idx - offset; } else { return 26 - (offset - idx); } } // caesar chipher implementation pub fn encode_text(input_te...
//! Filters, Approximate Membership Queries (AMQs). #[cfg(feature = "fixedbitset")] pub mod bloomfilter; pub mod compat; #[cfg(all(feature = "rand", feature = "succinct"))] pub mod cuckoofilter; #[cfg(all(feature = "fixedbitset", feature = "succinct"))] pub mod quotientfilter; use std::fmt::Debug; use std::hash::H...
use crate::association::RtxTimerId; use async_trait::async_trait; use std::sync::Arc; use tokio::sync::{mpsc, Mutex}; use tokio::time::Duration; pub(crate) const RTO_INITIAL: u64 = 3000; // msec pub(crate) const RTO_MIN: u64 = 1000; // msec pub(crate) const RTO_MAX: u64 = 60000; // msec pub(crate) const RTO_ALPHA: u64...
#![recursion_limit = "512"] use wasm_bindgen::prelude::*; use anyhow::Error; use serde_json::Value; use yew::format::Json; use yew::prelude::*; use yew::services::websocket::{WebSocketService, WebSocketStatus, WebSocketTask}; use yew_router::{route::Route, switch::Permissive}; mod components; mod scenes; use scenes...
use sled; use std::env; use std::path; use std::io; use std::io::Write; static USAGE: &str = r#"sled-dump - dump a sled database to stdout Usage: sled-dump DATABASE "#; fn main() { let mut args: Vec<String> = env::args().skip(1).collect(); if args.len() != 1 { println!("expected exactly one arg:...
use itertools::Itertools; use num::Integer; use regex::Regex; use std::collections::HashSet; #[derive(Debug, Clone, Hash, PartialEq, Eq)] struct Moon { position: [i32; 3], velocity: [i32; 3], } #[aoc_generator(day12)] fn load_moons(input: &str) -> Vec<Moon> { let re = Regex::new(r"<x=(-?\d+), y=(-?\d+), z...
// Copyright (c) 2017 King's College London // created by the Software Development Team <http://soft-dev.org/> // // The Universal Permissive License (UPL), Version 1.0 // // Subject to the condition set forth below, permission is hereby granted to any person obtaining a // copy of this software, associated documentati...
#![feature(proc_macro_hygiene)] use anchor_lang::prelude::*; use anchor_spl::token::{self, Burn, MintTo, TokenAccount, Transfer}; mod math; use math::*; use oracle::PriceFeed; // TODO add liquidation method #[program] pub mod system { use super::*; #[state] pub struct InternalState { pub nonce: u...
use crate::lexer::LexicalError; use crate::parser::ParseError; use codespan::{ByteIndex, FileMap, Span}; use codespan_reporting::{Diagnostic, Label, Severity}; use failure::Fail; use std::fmt::Write; pub trait AsDiagnostic { fn as_diagnostic(&self, file_map: &FileMap) -> Option<Diagnostic>; } impl AsDiagnostic fo...
use sdl2::rect::{Point, Rect}; use std::sync::*; use crate::app::UpdateResult as UR; use crate::renderer::renderer::Renderer; use crate::ui::file::editor_file_token::EditorFileToken; use crate::ui::text_character::TextCharacter; use crate::ui::*; use rider_config::Config; use rider_config::ConfigHolder; use rider_lexe...
// The str type, also called a 'string slice', is the most primitive string // type. It is usually seen in its borrowed form, &str. It is also the type of // string literals, &'static str. const GLOB_STR: &str = "global str"; fn strs() { // uh, how does && work, and how come they all print? maybe just println. ...
//! A performant rust implementation of recurrence rules as defined in the iCalendar RFC. //! //! RRule provides two types for working with recurrence rules: //! - `RRule`: For working with a single recurrence rule without any exception dates (exdates / exrules) and no additonal dates (rdate). //! - `RRuleSet`: For wor...
use std::collections::HashMap; use std::collections::HashSet; use std::hash::Hash; pub fn anagrams_for<'a>(word: &str, possible_anagrams: &'a [&str]) -> HashSet<&'a str> { let normalized_word = word.to_lowercase(); let word_histogram = Histogram::new(normalized_word.chars()); possible_anagrams .it...
//! futures 0.2.x compatibility. use std::io; use std::sync::Arc; use futures::{Async as Async01, Future as Future01, Poll as Poll01, Stream as Stream01}; use futures::task::{self as task01, Task as Task01}; use futures_core::{Async as Async02, Future as Future02, Never, Stream as Stream02}; use futures_core::task::{...
extern crate libc; #[macro_use] extern crate whack; mod bw; pub unsafe fn init(patcher: &mut whack::ModulePatcher) { bw::init_vars(patcher); } unsafe fn get(dat: &bw::DatTable, id: u32) -> u32 { assert!(dat.entries > id); match dat.entry_size { 1 => *(dat.data as *const u8).offset(id as isize) as...
use hex; use std::fs::File; use std::io::prelude::*; use std::io::BufReader; fn main() { let input = File::open("8.txt").unwrap(); &BufReader::new(input) .lines() .map(|x| detect_ecb(&hex::decode(x.unwrap()).unwrap())) .enumerate() .filter(|(_, x)| *x == true) .for_each(...
use crate::util::{Argument, AsOption, Parenthesised}; use proc_macro2::{Span, TokenStream as TokenStream2}; use quote::{quote, ToTokens}; use syn::{ braced, parse::{Error, Parse, ParseStream, Result}, parse_quote, spanned::Spanned, Attribute, Block, FnArg, Ident, Pat, ReturnType, Stmt, Token, Type,...
use std::fs; #[derive(Debug, Clone, PartialEq, Eq)] pub struct CrabCups { cups: Vec<u8> } impl CrabCups { pub fn new(cups: Vec<u8>) -> CrabCups { CrabCups { cups } } pub fn parse(line: &str) -> CrabCups { let cups = line.chars().map(|c| c.to_string().parse::<u8>().unwrap()).collect()...