text
stringlengths
8
4.13M
use std::hashmap::{HashMap, HashSet}; use statemachine::{StateMachine, StateId, Epsilon, StateSet, ToDfaResult, Partitioning}; use regex::{Regex}; struct ScannerDefinition<TokenType> { prioritized_rules: ~[(Regex, TokenType)] } impl<TokenType: Pod+IterBytes+Eq+Clone> ScannerDefinition<TokenType> { pub fn to_...
use crate::post::Post; use async_trait::async_trait; use mockall::predicate::*; use mockall::*; #[automock] #[async_trait] pub trait PostDb { async fn get_post_by_id(&self, post_id: i32) -> DomainResult<Option<Post>>; async fn get_posts(&self, show_all: bool) -> DomainResult<Vec<Post>>; async fn ...
use std::error::Error; use std::sync::mpsc; use log::{error, info}; use neovim_lib::neovim::Neovim; use neovim_lib::session::Session; use simplelog::{Config, Level, LevelFilter, WriteLogger}; pub mod event; pub mod event_handlers; pub mod handler; use crate::event::Event; use crate::event_handlers::search::search; u...
use super::status; use actix_web::{HttpMessage, HttpRequest, HttpResponse, dev::HttpResponseBuilder, State, Json, AsyncResponder, FutureResponse}; use futures::Future; use share::state::AppState; use model::user::{SignupUser, SigninUser}; pub fn signup((signup_user, state): (Json<SignupUser>, State<AppState>)) -> Fut...
#[doc = "Reader of register CFGR"] pub type R = crate::R<u32, super::CFGR>; #[doc = "Writer for register CFGR"] pub type W = crate::W<u32, super::CFGR>; #[doc = "Register CFGR `reset()`'s with value 0"] impl crate::ResetValue for super::CFGR { type Type = u32; #[inline(always)] fn reset_value() -> Self::Typ...
use yew::prelude::*; use yew_router::components::RouterAnchor; use crate::app::AppRoute; use super::applications::SocialApplications; use super::tab_settings::TabSettings; pub enum Content { Settings, Applications } pub struct SocialSettings { content: Content, link: ComponentLink<Self> } pub enum Ms...
mod requests; fn main() { // grab the top posts let arr = requests::top(); // then iterate `up to a limit` and grab links println!("this is my first post {}\n\n", *arr.get(0).unwrap()); let post_id: u64; post_id = arr[0].as_u64().unwrap(); requests::call_item(post_id); }
extern crate clonedir_lib; use self::clonedir_lib::clonedir; use flate2::read::GzDecoder; use reqwest; use serde_json; use std::fs; use std::fs::File; use std::io; use std::path::{Path, PathBuf}; use tar::Archive; pub fn extract_tarball<P: AsRef<Path>, Q: AsRef<Path>>(url: &str, cache: P, to: Q) { extract_tarball...
// 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. //! Test tools for serving TUF repositories. use { crate::repo::{get, Repository}, failure::Error, fidl_fuchsia_pkg_ext::RepositoryConfig, ...
#![feature(async_await)] use lambda::lambda; type Err = Box<dyn std::error::Error + Send + Sync + 'static>; #[lambda] #[runtime::main] async fn main(s: String) -> Result<String, Err> { Ok(s) }
#![feature(lang_items)] // required for defining the panic handler #![no_std] // don't link the Rust standard library #![no_main] // disable all Rust-level entry points #![feature(try_trait)] #![feature(asm)] #![feature(const_fn)] #![feature(global_asm)] #[macro_use] extern crate bitflags; extern crate x86_64; extern ...
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // 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 ...
#[doc = "channel x configuration register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#re...
use quote::ToTokens; use syn::{ visit_mut::{self, VisitMut}, *, }; use crate::utils::*; pub(super) fn collect_impl_trait(args: &mut Vec<Path>, ty: &mut Type) { fn to_trimed_string(path: &Path) -> String { path.to_token_stream().to_string().replace(" ", "") } let mut traits = Vec::new(); ...
mod string_decode; mod string_encode; mod wire_decode; mod wire_encode; pub use string_decode::*; pub use string_encode::*; pub use wire_decode::*; pub use wire_encode::*;
use std; use na::*; use math::*; use renderer::*; use alga::general::*; use std::rc::Rc; use std::cell::RefCell; use num::PrimInt; use std::collections::HashMap; use qef_bindings::*; //uniform manifold dual contouring is a modification to dual marching cubes (hermite extension to dual marching cubes) //dual marching ...
use proconio::input; fn gcd(x: u32, y: u32) -> u32 { if y == 0 { x } else { gcd(y, x % y) } } fn main() { input! { n: usize, mut a: [u32; n], }; a.sort(); let mut g = 0; for w in a.windows(2) { g = gcd(g, w[1] - w[0]); } if g == 1 { ...
// Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved // use sha1::Sha1; use gltf::json::texture; use gltf::json::Mesh; use gltf::json::{material::NormalTexture, material::OcclusionTexture}; use gltf::json::{texture::Sampler, Image, Index, Material, Texture}; use crate::{MeldKey, Result, WorkAsset}...
use crate::particles::VectorField; use crate::{FieldProvider, GPUFieldProvider, State}; #[cfg(target_arch = "wasm32")] use std::path::PathBuf; #[cfg(target_arch = "wasm32")] use stdweb::*; pub enum FileResult { OptionsFile(reparser::Options), VectorField((FieldProvider, GPUFieldProvider)), } pub fn reload_fil...
use termion::color; use termion::cursor; use termion::style; use std::collections::HashSet; use std::fmt; use std::fmt::Write; use std::ops::Index; pub mod square; pub use self::square::Square; pub mod generator; const BORDER_COLOR: color::Fg<color::Rgb> = color::Fg(color::Rgb(220, 220, 220)); const BORDER_TOP: &'...
extern crate olin; use log::{error, info}; use olin::env; use std::str; /// This tests for https://github.com/CommonWA/cwa-spec/blob/master/ns/env.md pub extern "C" fn test() -> Result<(), i32> { info!("running ns::env tests"); info!("env[\"MAGIC_CONCH\"] = \"yes\""); let envvar_name = "MAGIC_CONCH"; ...
#[cfg(test)] mod tests { #[test] fn it_works() { assert_eq!(2 + 2, 4); } } pub fn say() { println!("Hi!"); #[cfg(feature = "gpu")] println!("Hi! feature: gpu"); #[cfg(feature = "opencl")] println!("Hi! feature: opencl"); }
use std::num::Float; #[derive(Clone)] pub struct Vec2 { pub x: f32, pub y: f32, } #[derive(Clone)] pub struct Point { pub x: f32, pub y: f32, } #[derive(Clone)] pub struct Line { pub start: Point, pub end: Point, } pub struct Circle { pub center: Point, pub radius: f32, pub veloc...
extern crate basics; extern crate networking; extern crate iterator_example; fn main() { // run function in basics //basics::read_file::run().unwrap(); //basics::little_endian_int::run().unwrap(); //basics::random_numbers::run_basic().unwrap(); //basics::random_numbers::run_with_a_range(); //b...
use crate::codec::{Decode, Encode}; use crate::spacecenter::Part; use crate::{remote_type, RemoteObject}; remote_type!( /// Represents a servo. object InfernalRobotics.Servo { properties: { { Name { /// Returns the name of the servo. /// /// **Gam...
use super::*; #[test] fn part_one_discussion() { let prog = vec![1, 9, 10, 3, 2, 3, 11, 0, 99, 30, 40, 50]; let m = one_off_machine(&prog, None); assert_eq!(m.read_addr(3), 70); assert_eq!(m.read_addr(0), 3500); } #[test] fn part_one_example_one() { let prog = vec![1, 0, 0, 0, 99]; let m = one...
mod ingame_bindings; mod menu_bindings; pub mod prelude { pub use super::ingame_bindings::{ IngameActionBinding, IngameAxisBinding, IngameBindings, }; pub use super::menu_bindings::{ MenuActionBinding, MenuAxisBinding, MenuBindings, }; } pub use ingame_bi...
use serde::{Deserialize, Serialize}; use std::path::PathBuf; type V3 = [f64; 3]; #[derive(Copy, Clone, Debug, Serialize, Deserialize)] pub struct Camera { pub pos: V3, pub look_at: V3, pub up: V3, pub focus_distance: Option<f64>, #[serde(default = "default_aperture")] pub aperture: f64, #...
use crate::Counter; use num_traits::Zero; use std::hash::Hash; use std::ops::{Sub, SubAssign}; impl<T, N> Sub for Counter<T, N> where T: Hash + Eq, N: PartialOrd + PartialEq + SubAssign + Zero, { type Output = Counter<T, N>; /// Subtract (keeping only positive values). /// /// `out = c - d;`...
pub use {chunk_render_mesher::*, chunk_render_mesher_system::*, chunk_render_mesher_worker::*}; mod chunk_render_mesher; mod chunk_render_mesher_system; mod chunk_render_mesher_worker;
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // 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 ...
#[doc = "Reader of register SR"] pub type R = crate::R<u32, super::SR>; #[doc = "Reader of field `CTEF`"] pub type CTEF_R = crate::R<bool, bool>; #[doc = "Reader of field `CTCF`"] pub type CTCF_R = crate::R<bool, bool>; #[doc = "Reader of field `CSMF`"] pub type CSMF_R = crate::R<bool, bool>; #[doc = "Reader of field `...
use std::convert::TryFrom; #[derive(Debug, Clone, PartialEq, Eq)] pub struct UbloxRawMsg { class: u8, id: u8, payload: Vec<u8>, checksum: [u8; 2], } impl UbloxRawMsg { pub fn new(class: u8, id: u8, payload: Vec<u8>) -> Self { let checksum = Self::calc_checksum(class, id, &payload); ...
use core::fmt; use core::str::FromStr; use crate::term::Atom; use super::FunctionSymbol; /// This struct is a subset of `FunctionSymbol` that is used to more /// generally represent module/function/arity information for any function /// whether defined or not. #[derive(Clone, Copy, PartialEq, Eq, Hash)] pub struct M...
extern crate oxygengine_animation as anims; extern crate oxygengine_core as core; extern crate oxygengine_utils as utils; pub mod component; pub mod composite_renderer; pub mod font_asset_protocol; pub mod font_face_asset_protocol; pub mod jpg_image_asset_protocol; pub mod map_asset_protocol; pub mod math; pub mod mes...
use std::collections::HashMap; fn interpret_with(expr: &str, env: &HashMap<String, i32>) -> i32 { let mut stack: Vec<i32> = Vec::new(); let tokens: Vec<i32> = expr.split(" ").map(|t| match t { "+" => { let l = stack.pop().expect("To few variables"); let r = ...
// Copyright 2023 Datafuse Labs. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to ...
use crate::component_registry::ComponentRegistry; use crate::SpatialComponent; use hibitset::{BitSet, BitSetAnd, BitSetLike}; use spatialos_sdk::worker::component::Component as WorkerComponent; use spatialos_sdk::worker::Authority; use specs::join::BitAnd; use specs::prelude::{ Component, Entity, Join, Read, ReadSt...
use crate::enums::{TypeHolder, Types}; use crate::types_structs::{Enum, ItemInfo, Struct, Trait, TYPE_CASE}; use crate::{Language, TypeCases}; use derive_new::new; use std::collections::{HashMap, VecDeque}; use std::fs::{DirEntry, File}; use std::io::Write; use std::path::PathBuf; use std::rc::Rc; use syn::__private::T...
use anchor_lang::prelude::*; use yta_token::{YTAToken,Increase}; #[program] pub mod yta_demo { use super::*; pub fn initialize(ctx: Context<Initialize>,total:u64,authority:Pubkey) -> ProgramResult { let yta_config = &mut ctx.accounts.yta_config; yta_config.authority = authority; yta_con...
use ast::{self, AsStatement, Program}; use lexer::Lexer; use token::{self, Token}; struct Parser<'a> { l: &'a mut Lexer, cur_token: Token, peek_token: Token, } impl<'a> Parser<'a> { fn new(l: &'a mut Lexer) -> Self { let tok1 = l.next_token().clone(); let tok2 = l.next_token().clone();...
#[doc = "Reader of register COMP_ID_2"] pub type R = crate::R<u32, super::COMP_ID_2>; #[doc = "Reader of field `PREAMBLE`"] pub type PREAMBLE_R = crate::R<u8, u8>; impl R { #[doc = "Bits 0:7 - Preamble bits 12 to 19"] #[inline(always)] pub fn preamble(&self) -> PREAMBLE_R { PREAMBLE_R::new((self.bit...
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)] #[link(name = "windows")] extern "system" { #[cfg(feature = "Win32_Foundation")] pub fn AllJoynAcceptBusConnection(serverbushandle: super::super::Foundation::HANDLE, abortevent: super::super::Found...
use chrono::prelude::*; use diesel::sql_types::{Nullable, Text, Timestamp, Uuid as dUuid}; use uuid::Uuid; #[derive(Queryable, QueryableByName, Serialize, Deserialize)] pub struct RedeemableTicket { #[sql_type = "dUuid"] pub id: Uuid, #[sql_type = "Text"] pub ticket_type: String, #[sql_type = "dUui...
#[doc = "Reader of register RAM0CTRL"] pub type R = crate::R<u32, super::RAM0CTRL>; #[doc = "Writer for register RAM0CTRL"] pub type W = crate::W<u32, super::RAM0CTRL>; #[doc = "Register RAM0CTRL `reset()`'s with value 0"] impl crate::ResetValue for super::RAM0CTRL { type Type = u32; #[inline(always)] fn re...
use State::*; enum State { Start, Group, Garbage, Escape, } pub fn get_score(input: &str) -> usize { let mut analyzer = StreamAnalyzer::new(); input.chars() .for_each(|ch| analyzer.next_char(ch)); analyzer.get_score() } pub fn count_garbage(input: &str) -> usize { let mut anal...
use std::thread; struct Philosopher{ name: String, } impl Philosopher{ fn new(name: &str) -> Philosopher{ Philosopher{ name: name.to_string(), } } fn eat(&self){ println!("{} is eating", self.name); thread::sleep_ms(10); println!("{} is done eatin...
fn add_one(x: i32) -> i32 { x + 1 } /// fn is a concrete type and implements all of Fn, FnOnce and FnMut /// So below we dont have to mark the param fn /// By doing so users cannot pause closures to the function fn do_twice(f: fn(i32) -> i32, arg: i32) -> i32 { f(arg) + f(arg) } fn returns_closure() -> Box<d...
// Copyright 2019 The vault713 Developers // // 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 a...
use std::io; // use rand::Rng; use std::time::Duration; use std::thread; const CORRELATIVE_STARTS:[&'static str; 5] = ["ki","ti","i","neni","ĉi"]; const CORRELATIVE_ENDS: [&'static str; 9] = ["a","al","am","om","el","es","o","u","e"]; const UI_DELAY: u64 = 20; fn ui_delay(m: u64) { thread::sleep(Duration::from_mi...
#[doc = r" Value read from the register"] pub struct R { bits: u32, } impl super::SEMSTAT { #[doc = r" Reads the contents of the register"] #[inline] pub fn read(&self) -> R { R { bits: self.register.get(), } } } #[doc = "Possible values of the field `SEMSTAT`"] #[derive(...
// The code below is a stub. Just enough to satisfy the compiler. // In order to pass the tests you can add-to or change any of this code. #[derive(Debug)] pub struct Duration { seconds: u64, } impl From<u64> for Duration { fn from(s: u64) -> Self { return Duration { seconds: s }; } } pub trait P...
#[derive(Deserialize, Debug)] #[serde(rename_all = "camelCase")] pub struct Character { pub name: String, pub league: String, pub class_id: i32, pub class: String, pub level: i32, } #[derive(Deserialize, Debug)] pub struct CharacterWindowGetItems { pub items: Vec<Item>, pub character: Chara...
use error; pub fn solve_puzzle(puzzle: &mut [[u32; 9]; 9]) { puzzle_loop(puzzle, 0, 0); if validate_puzzle(puzzle) == true { print_puzzle(puzzle); println!("Puzzle complete!"); } else { println!("Puzzle cannot be solved"); } } //The recursive loop that solves the puzzle fn puzzle_loop(puzzle: &mut [[u32;...
pub mod core; pub use crate::core::*; pub mod debug; pub mod disassembly;
use crate::{error::Error, resource::Resource}; use log::error; use std::io::{self, Read, Write}; use std::net::{Shutdown, TcpStream}; use url::Url; pub struct Http { stream: TcpStream, } impl Resource for Http { fn new(u: Url) -> Result<Http, Error> { if let None = u.host() { return Err(Er...
// 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. pub const FONTS_CMX: &str = "fuchsia-pkg://fuchsia.com/fonts#meta/fonts.cmx"; mod experimental_api; mod old_api; mod reviewed_api;
use std::{borrow::Cow, pin::Pin}; use futures_util::stream::{Stream, StreamExt}; use crate::{ parser::types::Selection, registry, registry::Registry, Context, ContextSelectionSet, PathSegment, Response, ServerError, ServerResult, }; /// A GraphQL subscription object pub trait SubscriptionType: Send + Sync { ...
pub mod handler; pub mod model; use crate::batch::model::{AutoCancel, ComeFind}; use crate::models::{AppStateWithTxt, DbExecutor}; use actix::prelude::*; use futures::Future; use std::time::Duration; use crate::errors::ServiceError; use crate::fcm::model::*; use crate::fcm::router::to_user; use crate::utils::client::S...
pub struct Point { pub x: i32, pub y: i32, } impl Clone for Point { fn clone(&self) -> Self { Point { x: self.x, y: self.y, } } } impl Eq for Point {} impl PartialEq for Point { fn eq(&self, other: &Point) -> bool { self.x == other.x && self.y == ot...
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)] #[link(name = "windows")] extern "system" {} #[repr(transparent)] pub struct CellularClass(pub i32); impl CellularClass { pub const None: Self = Self(0i32); pub const Gsm: Self = Self(1i32); pu...
use std::os::unix::net::UnixStream; use std::io::{BufWriter, Write}; fn main() { let mut stream = UnixStream::connect("/home/majortom/tmp/can.sock").unwrap(); let mut bf = BufWriter::new(&stream); let mut n = 0; while n < 200 { n+=1; let mut s = String::new(); s.push_str(format...
use std::ops::Range; #[derive(Debug, Copy, Clone)] enum CardinalDirection { North, West, South, East } impl CardinalDirection { fn turn(self, td: TurnDirection) -> CardinalDirection { match td { TurnDirection::Right => { match self { Cardinal...
#[doc = "Reader of register CSR"] pub type R = crate::R<u32, super::CSR>; #[doc = "Writer for register CSR"] pub type W = crate::W<u32, super::CSR>; #[doc = "Register CSR `reset()`'s with value 0"] impl crate::ResetValue for super::CSR { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { ...
use binary_search_range::BinarySearchRange; use proconio::input; fn main() { input! { n: usize, a: [usize; n], q: usize, lrx: [(usize, usize, usize); q], }; let mut positions = vec![vec![]; n]; for i in 0..n { positions[a[i] - 1].push(i); } for i in 0..n...
use std::sync::{Arc, mpsc, Mutex, RwLock}; use crate::event::Event; use crate::event::core::ShutdownEvent; use crate::event::scene::SnapshotEvent; use crate::scene::SceneStack; pub fn scene_manager_event_thread( snapshot_queue: Arc<Mutex<Vec<SnapshotEvent>>>, scene_stack: Arc<RwLock<SceneStack>>, events_...
// Inspired from https://github.com/jgallagher/rusqlite/blob/master/libsqlite3-sys/build.rs fn main() { build::build_and_link(); bindings::add_bindings(); } #[cfg(feature = "vendored")] mod build { use std::path::PathBuf; pub fn build_and_link() { let basedir = PathBuf::from(env!("CARGO_MANIF...
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // 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 ...
use std::io; use serde_json; use websocket::result::WebSocketError; use websocket::client::ParseError; #[derive(Debug)] pub enum MessageError { WebSocket(WebSocketError), Json(serde_json::Error), } impl From<WebSocketError> for MessageError { fn from(e: WebSocketError) -> Self { return MessageErr...
//! This module contains DataFusion utility functions and helpers use std::{ cmp::{max, min}, convert::TryInto, sync::Arc, }; use arrow::{ array::TimestampNanosecondArray, compute::SortOptions, datatypes::{DataType, Schema as ArrowSchema}, record_batch::RecordBatch, }; use data_types::Tim...
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // 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 ...
//! https://github.com/lumen/otp/tree/lumen/lib/tftp/src use super::*; test_compiles_lumen_otp!(tftp imports "lib/kernel/src/application", "lib/tftp/src/tftp_engine", "lib/tftp/src/tftp_sup"); test_compiles_lumen_otp!(tftp_app imports "lib/tftp/src/tftp_sup"); test_compiles_lumen_otp!(tftp_binary); test_compiles_lume...
#[doc = "Reader of register CSGCM0R"] pub type R = crate::R<u32, super::CSGCM0R>; #[doc = "Writer for register CSGCM0R"] pub type W = crate::W<u32, super::CSGCM0R>; #[doc = "Register CSGCM0R `reset()`'s with value 0"] impl crate::ResetValue for super::CSGCM0R { type Type = u32; #[inline(always)] fn reset_va...
#[macro_export] macro_rules! timerchannel_pin { ($TimerN: ident, $ChannelX: ident, $Pin: ident, $locI: ident, $ccXloc: ident, $ccXpen: ident) => { impl super::HasLocForFunction<$TimerN, $ChannelX> for crate::gpio::pins::$Pin<crate::gpio::Output> { unsafe fn configure() { // FIXME https://github.com/chr...
use std::sync::RwLock; use wapc_guest::prelude::*; use wasmcolonies_protocol as protocol; use wasmcolonies_protocol::{deserialize, serialize}; lazy_static! { #[doc(hidden)] static ref PLAYER_TICK: RwLock<Option<fn(protocol::PlayerTick) -> HandlerResult<protocol::PlayerTickResponse>>> = RwLock::new(None...
use std::fmt; use std::thread; use std::time::Duration; use core::fmt::Debug; use rppal::gpio::{Gpio, OutputPin, Level}; /// GPIO BCM pin number for DAT. pub const GPIO_DAT: u8 = 10; /// GPIO BCM pin number for CLK. pub const GPIO_CLK: u8 = 11; /// GPIO BCM pin number for CS. pub const GPIO_CS: u8 = 8; /// Number o...
/* * @lc app=leetcode id=1006 lang=rust * * [1006] Clumsy Factorial */ impl Solution { pub fn clumsy(n: i32) -> i32 { let mut f = 0; let mut i = n; while i > 0 { let mut a = i; if i > 1 { a *= i-1; } if i > 2 { a /= i-2; } if i == n { f +=...
use crate::{integer::Integer, rational::Rational}; use core::ops::DivAssign; // DivAssign The division assignment operator /=. // ['Rational', 'Rational', 'Rational::divide_assign', 'no', [], ['ref']] impl DivAssign<Rational> for Rational { fn div_assign(&mut self, rhs: Rational) { Rational::divi...
use input_i_scanner::InputIScanner; fn main() { let stdin = std::io::stdin(); let mut _i_i = InputIScanner::from(stdin.lock()); macro_rules! scan { (($($t: ty),+)) => { ($(scan!($t)),+) }; ($t: ty) => { _i_i.scan::<$t>() as $t }; (($($t: ty),...
use std::io; fn main() { // "!" - signifies a macro prntln! is a macro because it can take a different // number of arguments println!("Enter your weight (kg): "); let mut input = String::new(); //Strings live on the heap io::stdin().read_line(&mut input).unwrap(); let weight: f32 = input.tri...
use super::{tls_connector, MaybeTlsSettings, MaybeTlsStream, Result, TlsError}; use futures01::{Async, Future}; use openssl::ssl::{ConnectConfiguration, HandshakeError}; use std::net::SocketAddr; use tokio01::net::tcp::{ConnectFuture, TcpStream}; use tokio_openssl03::{ConnectAsync, ConnectConfigurationExt}; enum State...
macro_rules! arr { ($type: ty, $value: expr, $long: expr) => { Arr::new([$value as $type; $long]) as Arr<$type, [$type; $long]>; } } macro_rules! gethead { ($self:ident, $index: expr) => { $self.head[$index] } } macro_rules! headlen { ($self:ident) => { $self.head.len() } } macro_rules! get { ($self:ide...
use schemars::JsonSchema; use serde::{Deserialize, Serialize}; /// card stats #[derive(Serialize, Deserialize, JsonSchema, Clone, Debug)] pub struct Stats { /// the card's skills at time of minting pub base: Vec<u8>, /// the card's current skills pub current: Vec<u8>, }
mod common; mod create; mod error; mod getattr; mod lookup; mod mkdir; mod mknod; mod read; mod readdir; mod release; mod rename; mod rmdir; mod unlink; mod write; mod virtualdir; pub use common::MenmosFS; pub use error::{Error, Result}; use crate::constants; use async_fuse::{FileAttr, FileType}; use menmos_client::...
use criterion::*; use itertools::*; use legion::*; #[derive(Copy, Clone, Debug, PartialEq)] struct A(f32); #[derive(Copy, Clone, Debug, PartialEq)] struct B(f32); #[derive(Copy, Clone, Debug, PartialEq)] struct C(f32); #[derive(Copy, Clone, Debug, PartialEq)] struct D(f32); #[derive(Copy, Clone, Debug, PartialEq)]...
extern crate proconio; use proconio::input; fn main() { input! { mut s: String, } let s = s.chars().collect::<Vec<_>>(); let mut ans = 0; if s[0] == 'R' || s[1] == 'R' || s[2] == 'R' { ans = 1; } if s[0..2] == ['R', 'R'] || s[1..3] == ['R', 'R'] { ans = 2; } if...
use wayland_client::{ protocol::wl_registry::WlRegistry, AnonymousObject, Attached, DispatchData, GlobalEvent, Main, RawEvent, }; pub fn print_global_event( event: GlobalEvent, _registry: Attached<WlRegistry>, _data: DispatchData, ) { match event { GlobalEvent::New { id, ...
use std::collections::HashMap; use std::io::{BufRead, BufReader, Read}; const REQUIRED_KEYS: [&str; 7] = ["byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid"]; const VALID_KEYS: [&str; 8] = ["byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid", "cid"]; struct ID(HashMap<String, String>); impl From<String> for ID { fn from...
fn main() { let stdin = std::io::stdin(); let mut rd = ProconReader::new(stdin.lock()); let n: usize = rd.get(); let _: usize = rd.get(); let a: Vec<Vec<char>> = (0..n).map(|_| rd.get_chars()).collect(); if !reachable(0.0, &a) { println!("-1"); return; } let mut ng = 1...
// Copyright 2022 Datafuse Labs. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to ...
fn main() { let input = include_str!("../input.txt"); println!("{}", day_10_part_1(input)); day_10_part_2(input); } fn day_10_part_1(input: &str) -> usize { let mut list = (0..256).collect::<Vec<usize>>(); let mut skip_size = 0; let mut curr_pos = 0; let input_lengths = input .split...
use directories::{BaseDirs, ProjectDirs}; use std::path::PathBuf; use std::sync::OnceLock; pub struct Dirs; impl Dirs { /// Project directory specifically for Vim Clap. /// /// All the files created by vim-clap are stored there. pub fn project() -> &'static ProjectDirs { static CELL: OnceLock<...
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // 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 ...
#[inline] pub fn clamp<T: PartialOrd>(input: T, min: T, max: T) -> T { debug_assert!(min <= max, "min must be less than or equal to max"); if input < min { min } else if input > max { max } else { input } }
use std::env; use std::fmt::Write; use std::fs; use std::path::Path; use stark_curve::*; fn generate_consts(bits: u32) -> Result<String, std::fmt::Error> { let mut buf = String::with_capacity(10 * 1024 * 1024); write!(buf, "pub const CURVE_CONSTS_BITS: usize = {bits};\n\n")?; push_points(&mut buf, "P1",...
extern crate regex; use std::io::prelude::*; use std::io::BufReader; use std::fs::File; use regex::Regex; #[derive(PartialEq)] enum OpType { AND, OR, LSHIFT, RSHIFT, NOT, } struct LogicSimulator { evaluated:bool, name:String, value:u16, left_identifier:String, right_identifier:String, } impl Default for ...
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)] #[link(name = "windows")] extern "system" { #[cfg(feature = "Win32_Foundation")] pub fn AddDllDirectory(newdirectory: super::super::Foundation::PWSTR) -> *mut ::core::ffi::c_void; #[cfg(feature...
use crypto::sha2::Sha256; use crypto::digest::Digest; use std::ops::{Index, Range, RangeFull}; use std::fmt::{Debug, Display, Formatter}; use std::io::{Write}; use serde::{ser, de}; use common::ValidityErr; use rustc_serialize::hex::FromHex; #[derive(RustcEncodable, RustcDecodable, Copy, Clone, Hash, Eq, Part...
/* * @lc app=leetcode.cn id=49 lang=rust * * [49] 字母异位词分组 * * https://leetcode-cn.com/problems/group-anagrams/description/ * * algorithms * Medium (54.26%) * Total Accepted: 11.8K * Total Submissions: 21.7K * Testcase Example: '["eat","tea","tan","ate","nat","bat"]' * * 给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同...
pub fn example3() { xprintln!("5 + 4 = {}", 5 + 4); xprintln!("5 - 4 = {}", 5 - 4); xprintln!("5 * 4 = {}", 5 * 4); xprintln!("5 / 4 = {}", 5 / 4); xprintln!("5 % 4 = {}", 5 % 4); let neg_4 = -4i32; xprintln!("abs(-4) = {}", neg_4.abs()); xprintln!("4 ^ 6 = {}", 4i32.pow(6)); xprintln!("sqrt 9 = {}", 9f64.sq...