text
stringlengths
8
4.13M
//! Pick command use super::Command; use crate::err::Error; use async_trait::async_trait; use clap::{Arg, ArgAction, ArgMatches, Command as ClapCommand}; /// Abstract pick command /// /// ```sh /// leetcode-pick /// Pick a problem /// /// USAGE: /// leetcode pick [OPTIONS] [id] /// /// FLAGS: /// -h, --help ...
use super::Material; use crate::Scene; use crate::Sphere; use crate::Vec4; use crate::Vec3; #[derive(Debug)] pub struct Ray { pub origin: Vec4, pub dir: Vec4, } #[derive(Debug)] pub struct IntersectionResult<'a> { pub sphere: &'a Sphere, pub point: Vec4, pub normal: Vec4, pub refraction_ratio:...
/* * Datadog API V1 Collection * * Collection of all Datadog Public endpoints. * * The version of the OpenAPI document: 1.0 * Contact: support@datadoghq.com * Generated by: https://openapi-generator.tech */ /// EventListResponse : An event list response. #[derive(Clone, Debug, PartialEq, Serialize, Deserial...
/* * Datadog API V1 Collection * * Collection of all Datadog Public endpoints. * * The version of the OpenAPI document: 1.0 * Contact: support@datadoghq.com * Generated by: https://openapi-generator.tech */ /// FreeTextWidgetDefinition : Free text is a widget that allows you to add headings to your screenboard...
use gfx; pub fn main() { gfx::clear_screen(0xFF, 0xFF, 0xFF); log!("Hello, world!"); for i in 0..10000 { print!("{}", i % 10); } }
use node::Node; use prefix::{Name, Prefix}; use section::Section; /// Network message (RPC). /// Note: these do not necessarily correspond to the RPCs of the real network, /// because this simulation abstracts of the real stuff away. #[derive(Debug)] pub enum Request { /// A node joins the network. Live(Node),...
extern crate hacl_star; use hacl_star::ed25519; const SK11: [u8; 32] = [ 0x9d, 0x61, 0xb1, 0x9d, 0xef, 0xfd, 0x5a, 0x60, 0xba, 0x84, 0x4a, 0xf4, 0x92, 0xec, 0x2c, 0xc4, 0x44, 0x49, 0xc5, 0x69, 0x7b, 0x32, 0x69, 0x19, 0x70, 0x3b, 0xac, 0x03, 0x1c, 0xae, 0x7f, 0x60 ]; const PK11: [u8; 32] = [ ...
use crate::{process::current_process, result::Result, syscalls::SyscallHandler}; impl<'a> SyscallHandler<'a> { pub fn sys_getppid(&mut self) -> Result<isize> { Ok(current_process().ppid().as_i32() as isize) } }
mod app_config; mod args; pub mod cli; mod exit_code; mod sentry_config; pub use app_config::{AppConfig, CKBAppConfig, MinerAppConfig}; pub use args::{ ExportArgs, ImportArgs, InitArgs, MinerArgs, ProfArgs, ResetDataArgs, RunArgs, StatsArgs, }; pub use ckb_tx_pool::BlockAssemblerConfig; pub use exit_code::ExitCode...
extern crate json_schema; extern crate serde_json; use std::str::FromStr; use json_schema::Schema; const SCHEMA: &str = r#" { "type": "array", "items": { "type": "object", "additionalProperties": false, "properties": { "x": {"type": "number", "minimum": 0.0, "maximum": 100...
//! Pre-defined optimization problems //! //! This module relies on dynamic heap allocation. mod lp; // std, Float mod qp; // std, Float mod qcqp; // std, Float mod socp; // std, Float mod sdp; // std, Float pub use lp::ProbLP; pub use qp::ProbQP; pub use qcqp::ProbQCQP; pub use socp::ProbSOCP; pu...
use yew::prelude::*; pub struct Model { link: ComponentLink<Self>, value: i64, } pub enum Msg { AddOne, SubstractOne, Reset, } impl Component for Model { type Message = Msg; type Properties = (); fn create(_: Self::Properties, link: ComponentLink<Self>) -> Self { Self { link, ...
#![feature(proc_macro_hygiene, decl_macro)] extern crate mysql; extern crate time; #[macro_use] extern crate rocket; extern crate dotenv; extern crate rocket_contrib; extern crate serde; use rocket::State; use rocket_contrib::json::Json; use serde::Serialize; mod graph; mod pool; mod result_getter; use crate::graph:...
#[doc = "Register `GPIOA_PUPDR` reader"] pub type R = crate::R<GPIOA_PUPDR_SPEC>; #[doc = "Register `GPIOA_PUPDR` writer"] pub type W = crate::W<GPIOA_PUPDR_SPEC>; #[doc = "Field `PUPDR0` reader - PUPDR0"] pub type PUPDR0_R = crate::FieldReader; #[doc = "Field `PUPDR0` writer - PUPDR0"] pub type PUPDR0_W<'a, REG, const...
table! { posts (id) { id -> Uuid, author -> Uuid, description -> Text, photo -> Uuid, created_at -> Timestamp, } }
use super::column::Column; use super::value::Value; use std::collections::HashMap; use std::collections::HashSet; pub struct Op { column_name: String, operation: Function, } type Function = Box<dyn Fn(&[&str]) -> String>; impl Op { pub fn new(column_name: &str, operation: Function) -> Op { ...
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use typing_collections_rust::Map; #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] pub enum TypingContKey<'a> { Next, ...
use libunftp::auth::{Authenticator, DefaultUser}; use std::path::PathBuf; use unftp_auth_jsonfile::JsonFileAuthenticator; fn input_file_path(filename: String) -> String { let root_dir = std::env::var("CARGO_MANIFEST_DIR").expect("Could not find CARGO_MANIFEST_DIR in environment"); let mut path = PathBuf::from(...
// Note this useful idiom: importing names from outer (for mod tests) scope. use super::*; use chrono::TimeZone; #[test] fn test_spot() { let now = chrono::Local::now(); match blocking::spot(52.520008, 13.404954, 0.0, 100) { Ok(spots) => match find_upcoming(&spots, None, now) { Some(upcomin...
use crate::lib::environment::Environment; use crate::lib::error::DfxResult; use clap::Clap; mod deploy_wallet; mod get_wallet; mod import; mod list; mod new; mod principal; mod remove; mod rename; mod set_wallet; mod r#use; mod whoami; /// Manages identities used to communicate with the Internet Computer network. //...
mod document_spec; use futures::future::{Future, ok, err, result}; use futures::sync::oneshot; use hyper; use hyper::{Get, Post, Head, StatusCode}; use hyper::server::{Request, Response, Service, NewService}; use hyper::header::{Authorization, Bearer}; use serde_json; use slog; use std::marker::PhantomData; use tokio_...
//! Visibility calculation. use crate::{Attribute, Input}; use arctk::{geom::Ray, phys::Crossing}; /// Calculate the occlusion experienced over a distance along ray. /// Zero indicates full occlusion. /// Unity indicates full view. #[inline] #[must_use] pub fn occlusion(input: &Input, mut ray: Ray, mut dist: f64) -> ...
use crate::ftdi::constants::{*}; /// Provide libftdi version information /// major: Library major version /// minor: Library minor version /// micro: Currently unused, ight get used for hotfixes. /// version_str: Version as (static) string /// snapshot_str: Git snapshot version if known. Otherwise "unknown" or empty s...
use default_port::DefaultPort; use string_repr::StringRepr; #[macro_export] macro_rules! scheme { ($scheme:expr) => { Scheme::new($scheme) }; } pub enum Scheme<'a> { HTTP, HTTPS, CUSTOM(&'a str), } impl<'a> Scheme<'a> { /// Create new Scheme. /// # Example: /// ```rust ///...
pub fn goodbye() -> String { "Sayonar~~~~~~".to_string() }
use std::fs::File; use std::io::{BufReader, Read}; use std::path::Path; use github_rs::github::Client as GhClient; pub struct Client; impl Client { pub fn new<P>(config_path: P) -> ::Result<(GhClient, Config)> where P: AsRef<Path>, { let config = Config::new(config_path)?; let gh_clie...
use std::collections::HashSet; fn main() { let mut decks: Vec<Vec<u8>> = String::from_utf8(std::fs::read("input/day22").unwrap()) .unwrap() .split("\n\n") .map(|player| { player .split_terminator('\n') .skip(1) .map(|card| card.par...
use std::any; use serde::{Deserialize, Serialize}; use thiserror::Error; pub enum Commands { GetCount, GetName, MutateCount(Option<i32>), } #[derive(Serialize, Deserialize)] pub struct Payload<T> { pub data: T, } #[derive(Error, Debug)] pub enum QueryError { #[error("missing input value")] M...
#[derive(Debug, Copy, Clone)] struct Foo { caca: i32, pedo: i64, } fn main() { let a = Foo { caca: 1, pedo: 2 }; let b = a; let _c = a; let x = 123; let _y = x; let _z = x; println!("{:?}", b); println!("{:?}", a); }
mod avm2; mod extractor; pub use extractor::*;
use crate::event::key::Key; use crate::event::destination::SDLDestination; use super::*; pub mod imp; pub mod destination; pub mod consuming; pub mod position; pub mod key; pub mod cast; #[derive(Clone)] pub struct Event { pub e: SDLEvent, ws: (f32,f32), } impl Deref for Event { type Target = SDLEvent; ...
#[macro_use] extern crate lazy_static; extern crate chrono; extern crate clap; extern crate dirs; extern crate git2; extern crate hostname; extern crate humantime; extern crate ini; extern crate libc; extern crate regex; extern crate url; #[cfg(not(target_os = "windows"))] extern crate users; #[cfg(target_os = "window...
pub mod blake2b;
extern crate generator; use generator::state_machine_generator; #[cfg(test)] struct MyGenerator { my_state_1: usize, pub my_state_2: usize, pub num: u32, pub num1: u32, } #[cfg(test)] impl MyGenerator { pub fn new() -> MyGenerator { MyGenerator { my_state_1: 0, my_s...
#[cfg(test)] mod test { use crate::SnakeNode; use crate::Game; #[test] fn update_snake_test() { let s = SnakeNode { pos: (7, 7) }; let a = SnakeNode { pos: (-1, -1) }; let b = SnakeNode { pos: (-1, -1) }; ...
#[doc = "Register `HASH_CSR23` reader"] pub type R = crate::R<HASH_CSR23_SPEC>; #[doc = "Register `HASH_CSR23` writer"] pub type W = crate::W<HASH_CSR23_SPEC>; #[doc = "Field `CS23` reader - CS23"] pub type CS23_R = crate::FieldReader<u32>; #[doc = "Field `CS23` writer - CS23"] pub type CS23_W<'a, REG, const O: u8> = c...
/// F must give a semigroup: it is required that F satisfies associativity. /// Commutativity and existence of the identity are not required. /// Reference: https://scrapbox.io/data-structures/Sliding_Window_Aggregation pub struct SWAg<T, F> { back: Vec<T>, back_agg: Vec<T>, front: Vec<T>, front_agg: Ve...
extern crate cgmath; use cgmath::Vector3; use cgmath::prelude::*; extern crate rand; use rand::Rng; mod ray; pub use ray::Ray; mod camera; pub use camera::Camera; mod geometry; pub use geometry::Geometry; mod material; pub use material::Material; #[derive(Copy, Clone, Debug, PartialEq)] pub struct Object { pub ge...
use std::fs::File; use std::io::prelude::*; use serde_derive::Deserialize; /// 部署工具配置 #[derive(Debug, Clone, Deserialize)] pub struct Config { // 源目录 pub src: String, // 目标目录 pub dist: String, // 是否先清除目标目录 pub clear: bool, // 需要排除的目录 pub exclude_dir: Vec<String>, // 要排队的扩展类型 pub...
use crate::{apu, controller as ctrl, cpu, parse, ppu, serialize}; #[macro_use] use crate::bitfield; use super::{CpuAddressBus, CpuAddressBusBase, PpuAddressBus}; #[macro_use] use derive_serialize::Serialize; use std::cell::Cell; use std::{fs, io}; // NOTE: the current implementation ignores open bus behavior // and ...
pub mod calculator { pub fn add_two(a: i32) -> i32 { super::internal_adder(a, 2) } } fn internal_adder(a: i32, b: i32) -> i32 { a + b } #[cfg(test)] mod tests { #[test] fn exploration() { assert_eq!(2 + 2, 4); } #[test] #[should_panic(expected = "Make this test fail!")...
use structs::*; pub trait SSE2 { /// Calculate square root for each element in vector /// /// ```rust /// use simd::*; /// use simd::x86::SSE2; /// /// let f64x2(a, b) = f64x2(4., 9.).sqrt(); /// assert_eq!((a, b), (2., 3.)); /// ``` fn sqrt(self) -> Self; } impl SSE2 for f64x2...
extern crate gio; extern crate gtk; use gio::prelude::*; use gtk::prelude::*; mod config; mod image; mod zigzag; use self::config::Config; use self::image::Image; fn build_ui(application: &gtk::Application) { let config = Config::new(std::env::args()).unwrap_or_else(|err| { eprintln!("Problem parsing ar...
mod world; extern crate glutin; extern crate gl; extern crate nanovg; use glutin::{GlContext, EventsLoop, GlWindow}; use nanovg::{Color, Context}; use world::{Body, Point, Vector}; use std::env; const INIT_WINDOW_SIZE: (u32, u32) = (1024, 720); fn clear_screen(width: i32, height: i32) { unsafe { gl::Vie...
use protocol::serde_am::*; impl Serialize for u8 { fn serialize(&self, ser: &mut Serializer) -> Result<(), SerError> { ser.serialize_u8(*self) } } impl<'de> Deserialize<'de> for u8 { fn deserialize(de: &mut Deserializer<'de>) -> Result<Self, DeError> { de.deserialize_u8() } } impl Serialize for u16 { fn seri...
use svm_types::{Account, Address, SpawnAccount, TemplateAddr}; #[doc(hidden)] pub struct ExtAccount { base: Account, spawner: Address, } #[doc(hidden)] impl ExtAccount { pub fn new(base: &Account, spawner: &Address) -> Self { Self { base: base.clone(), spawner: spawner.clon...
// 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/. use base::prelude::*; use core::{mem}; use cell::cell::{Cell}; use atomic::{Atomic}; use syscall::{futex_wait, futex_...
use std::collections::HashMap; fn main() { let puzzle = Network::from_str(include_str!("../../input/12.txt")); println!("First solution: {}", puzzle.solve(Path::default(), false)); println!("Second solution: {}", puzzle.solve(Path::default(), true)); } type Cave = &'static str; struct Network { conne...
use rsfml::graphics::RenderWindow; pub struct Camera { zoom:int, window:@ mut RenderWindow }
use async_std::net::{TcpListener, TcpStream}; use hreq_h1::server::Connection; use hreq_h1::Error; #[async_std::main] async fn main() -> Result<(), Error> { let mut l = TcpListener::bind("127.0.0.1:3000").await?; println!("Listening to {:?}", l.local_addr().unwrap()); listen(&mut l).await; Ok(()) } ...
use crate::config::CONFIG; use crate::models::file::File; use crate::models::user::UserAuth; use crate::models::DataPoolSqlite; use crate::services::file::*; use actix_files::NamedFile; use actix_multipart::Multipart; use actix_web::{web, HttpResponse}; use actix_web::{HttpRequest, Result}; use futures::StreamExt; use ...
use std::clone::Clone; use std::path::Path; use image::{GenericImageView, DynamicImage, Rgb, Rgba, ImageBuffer}; #[derive(Debug)] pub struct CropResult { crops: Vec<CropInfo>, pub top_crop: CropInfo, } #[derive(Clone, Debug, Default)] struct CropScore { detail: f64, saturation: f64, skin: f64, ...
use std::env; use std::error::Error; use std::fs; pub struct Config { query: String, filename: String, } impl Config { pub fn new(mut args: env::Args) -> Result<Config, &'static str> { args.next(); let query = match args.next() { Some(arg) => arg, None => return Er...
//! //! cd C:\Users\むずでょ\OneDrive\ドキュメント\practice-rust\kirimoti //! cargo new iron //! cd C:\Users\むずでょ\OneDrive\ドキュメント\practice-rust\kirimoti\iron //! cargo check //! cargo run //! //! [crates.io](https://crates.io/) //! rand //! use rand::prelude::*; fn main() { let mut text1 = "アイウエオ カキクケコ サシスセソ タチツテト ナニ...
use cocoa::base::{class, id}; use cocoa::foundation::NSUInteger; use objc::runtime::BOOL; use MTLCompareFunction; pub trait MTLSamplerDescriptor { unsafe fn new(_: Self) -> id { msg_send![class("MTLSamplerDescriptor"), new] } /// The address mode for the texture depth (r) coordinate. /// /...
use std::fs::File; use std::io::prelude::*; struct Policy { min: usize, max: usize, char: char, } fn read_file() -> Vec<(Policy, String)> { let mut file = File::open("./input/input2.txt").unwrap(); let mut contents = String::new(); file.read_to_string(&mut contents).unwrap(); contents.line...
struct Sheep {} struct Cow {} trait Animal { fn noise(&self) -> &'static str; } impl Animal for Sheep { fn noise(&self) -> &'static str { "beh" } } impl Animal for Cow { fn noise(&self) -> &'static str { "muu" } } // returns some struct of animal but we dont know which // one at compile time fn ...
use std::collections::HashMap; use super::util::push_room_pl; use crate::protos::cao_common; use crate::protos::cao_world; use caolo_sim::prelude::*; type StructureTables<'a> = ( View<'a, WorldPosition, EntityComponent>, View<'a, Axial, RoomComponent>, View<'a, EntityId, Structure>, View<'a, EntityId,...
use rand::random; const BUILTIN_SPRITES: [u8; 80] = [ 0xF0, 0x90, 0x90, 0x90, 0xF0, // 0 0x20, 0x60, 0x20, 0x20, 0x70, // 1 0xF0, 0x10, 0xF0, 0x80, 0xF0, // 2 0xF0, 0x10, 0xF0, 0x10, 0xF0, // 3 0x90, 0x90, 0xF0, 0x10, 0x10, // 4 0xF0, 0x80, 0xF0, 0x10, 0xF0, // 5 0xF0, 0x80, 0xF0, 0x90, 0xF...
#[doc = r"Register block"] #[repr(C)] pub struct RegisterBlock { #[doc = "0x00 - Interrupt mask register"] pub imr1: IMR1, #[doc = "0x04 - Event mask register"] pub emr1: EMR1, #[doc = "0x08 - Rising Trigger selection register"] pub rtsr1: RTSR1, #[doc = "0x0c - Falling Trigger selection reg...
use postgres::types::{ToSql, FromSql, Type, SessionInfo, IsNull}; use postgres::error::Error; use postgres::Result; use std::io::{Write, Read}; #[derive(Debug, PartialEq, Eq)] pub enum ChecklistType { Or, And, Req, } impl FromSql for ChecklistType { fn from_sql<R: Read>(_ty: &Type, raw: &mut R, _ctx: ...
#![allow(non_snake_case)] extern crate alloc; use alloc::vec::Vec; use core::iter; use curve25519_dalek::ristretto::{CompressedRistretto, RistrettoPoint}; use curve25519_dalek::scalar::Scalar; use curve25519_dalek::traits::VartimeMultiscalarMul; use merlin::Transcript; use rand_core::{CryptoRng, RngCore}; use crate...
//! Message types for requests sent to the Telebilling bot API. mod get_updates; mod send_message; pub use self::get_updates::GetUpdates; pub use self::send_message::{ChatId,ReplyMarkup,SendMessage};
//! Types used to create and manage widgets. //! //! Limn UIs exist as a tree of `Widget`s, each of which consists of a bounding rectangle, //! a list of references to it's children, a list of `EventHandler`s that receive and send events, //! and optionally a draw state struct that implements `Draw`. //! //! The root w...
mod archive; mod drafts; mod external; mod homepage; mod posts; mod projects; mod series; mod series_archive; mod standalone; mod tags; pub use archive::{post_archives, ArchiveItem}; pub use drafts::{load_drafts, DraftArchiveItem, DraftItem, DraftRef}; pub use external::Sass; pub use homepage::HomepageItem; pub use po...
fn main() { let list: Vec<&str> = include_str!("input.txt") .lines() .collect(); let mut sum = 0; let mut complete_scores = Vec::new(); for i in 0..list.len() { let mut died = false; let line = list[i]; let mut opened_brackets: Vec<char> = Vec::new(); for...
#[doc = "Register `RCC_MC_APB3ENSETR` reader"] pub type R = crate::R<RCC_MC_APB3ENSETR_SPEC>; #[doc = "Register `RCC_MC_APB3ENSETR` writer"] pub type W = crate::W<RCC_MC_APB3ENSETR_SPEC>; #[doc = "Field `LPTIM2EN` reader - LPTIM2EN"] pub type LPTIM2EN_R = crate::BitReader; #[doc = "Field `LPTIM2EN` writer - LPTIM2EN"] ...
#![deny(clippy::all, clippy::pedantic)] use chrono::{DateTime, Duration, Utc}; const ONE_BILLYUN: i64 = 1_000_000_000; // Returns a Utc DateTime one billion seconds after start. pub fn after(start: DateTime<Utc>) -> DateTime<Utc> { start + Duration::seconds(ONE_BILLYUN) }
#[macro_use] extern crate wrest; use wrest::prelude::*; fn main() { let mut reddit = REST::new("http://www.reddit.com"); reddit .register( GET, APIPath::new("/r/rust/top/.json"), "rustsub_top" ); let mut output = reddit .call("rustsub_top") ...
use crate::{serenity, Context, Error, PrefixContext}; /// Deletes the bot's messages for cleanup /// /// ?cleanup [limit] /// /// Deletes the bot's messages for cleanup. /// You can specify how many messages to look for. Only messages from the last 24 hours can be deleted. #[poise::command(prefix_command, on_error = "...
#![cfg_attr(not(test), allow(dead_code))] use std::hash::Hasher; use std::collections::hash_map::DefaultHasher; // All functions are considered dead_code because they're only called in test build fn hash_function(s: &String) -> u64 { let mut hasher = DefaultHasher::new(); hasher.write(s.as_bytes()); hash...
#![no_std] #![no_main] use gba::prelude::*; #[panic_handler] #[allow(unused)] fn panic(info: &core::panic::PanicInfo) -> ! { // This kills the emulation with a message if we're running inside an // emulator we support (mGBA or NO$GBA), or just crashes the game if we // aren't. //fatal!("{}", info); loop { ...
#![no_std] #![feature(asm)] #![feature(start)] #![feature(naked_functions)] use core::panic::PanicInfo; extern "C" { fn _api_openwin( buf_addr: usize, xsize: usize, ysize: usize, col_inv: u8, title_addr: usize, ) -> usize; fn _api_boxfilwin(win: usize, x0: i32, y0: ...
//! My own attempt at making a cat-like tool //! I only made it in order to learn Rust //! If you want to give me some advice or propose a better way of doing something //! just make an issue on the repo. I would be very grateful :D use std::{fs, env, process}; use std::error::Error; use std::io::stdin; use ansi_term...
#![crate_type="dylib"] #![feature(plugin_registrar, quote, slicing_syntax)] extern crate syntax; extern crate rustc; use syntax::codemap::{DUMMY_SP, Span}; use syntax::parse::{mod, token, lexer}; use syntax::parse::lexer::Reader; use syntax::ast::{mod, TokenTree, Expr}; use syntax::ptr::P; use syntax::ext::base::{Ext...
extern crate rosc; use rosc::{OscMessage, OscPacket, OscType}; use errors::RunError; use std::net::{SocketAddr, UdpSocket}; use std::sync::mpsc; use io::Receiver; use dsp::{FilterType, Waveform}; use event::ControlEvent; use types::*; macro_rules! exp_scale { ($val:expr) => { (((Float::from($val)) * ::...
use color_eyre::{Section, SectionExt}; use eyre::{Report, WrapErr}; use tracing as trc; use std::process::Command; use std::{path::PathBuf, process::Stdio}; #[trc::instrument] pub fn build_example(name: &str, headless: bool) -> eyre::Result<String> { let mut args = vec!["build", "--release", "--example", name]; ...
use crate::bimap::BiMap; use crate::conn; use crate::conn::{ChannelType, Completer, ConnEvent, Message, TuiEvent}; use crate::DFAExtension; use log::error; use regex_automata::DenseDFA; use serde::Deserialize; use std::sync::Arc; use futures::channel::mpsc::UnboundedSender; use futures::future::FutureExt; use futures:...
#[macro_use] extern crate rocket; // see <https://github.com/SergioBenitez/Rocket/blob/v0.5-rc/examples/hello/src/main.rs> // in this section, get a route to '/info', and a route to '/version' to work #[get("/")] async fn index() -> &'static str { use rocket::tokio::time::{sleep, Duration}; sleep(Duration...
extern crate cuda; use cuda::driver::*; #[test] fn test_init() { assert!(!cuda_initialized()); cuda_init(); assert!(cuda_initialized()); } #[test] fn test_version_no_init() { let v = get_version(); println!("version? {:?}", v); assert!(v.is_ok()); }
pub fn read<T: std::str::FromStr>() -> T { let mut s = String::new(); std::io::stdin().read_line(&mut s).ok(); s.trim().parse().ok().unwrap() } pub fn read_vec<T: std::str::FromStr>() -> Vec<T> { read::<String>() .split_whitespace() .map(|e| e.parse().ok().unwrap()) .collect() }...
#![cfg(feature = "use-redis")] use { crate::{Backend, RawSession}, cookie::Cookie, futures::try_ready, redis::{r#async::Connection, Client, RedisFuture}, std::time::Duration, std::{borrow::Cow, collections::HashMap, mem, sync::Arc}, tsukuyomi::{ error::{Error, Result}, futur...
pub const PREFIX_MAX_LENGTH: usize = 32; pub const TOOL_VERSION: &str = env!("CARGO_PKG_VERSION");
test_normalize! {" error: `self` parameter is only allowed in associated functions --> /git/trybuild/test_suite/tests/ui/error.rs:11:23 | 11 | async fn bad_endpoint(self) -> Result<HttpResponseOkObject<()>, HttpError> { | ^^^^ not semantically valid as function parameter error: aborting d...
#[derive(Debug, PartialEq)] enum Direction { Forward, Backward, } pub struct Scanner<T> { data: Vec<T>, current: usize, direction: Direction, } impl<T> Scanner<T> { pub fn new(data: Vec<T>) -> Scanner<T> { Scanner { data: data, current: 0, direction:...
#[doc = "Register `CRYP_CSGCM5R` reader"] pub type R = crate::R<CRYP_CSGCM5R_SPEC>; #[doc = "Register `CRYP_CSGCM5R` writer"] pub type W = crate::W<CRYP_CSGCM5R_SPEC>; #[doc = "Field `CSGCM5` reader - CSGCM5"] pub type CSGCM5_R = crate::FieldReader<u32>; #[doc = "Field `CSGCM5` writer - CSGCM5"] pub type CSGCM5_W<'a, R...
use shared::token_permissions; #[derive(Debug)] pub struct Token { pub id: String, pub identifier: String, pub can_add_image_to_item: u8, pub can_add_item_to_comic: u8, pub can_change_comic_data: u8, pub can_change_item_data: u8, pub can_remove_image_from_item: u8, pub can_remove_item_f...
use alloc::arc::Arc; use alloc::boxed::Box; use collections::{String, Vec, VecDeque}; use collections::string::ToString; use core::cell::UnsafeCell; use arch::context::{Context, ContextManager}; use common::event::Event; use common::time::Duration; use disk::Disk; use network::Nic; use fs::{KScheme, Resource, Scheme...
#[doc = "Reader of register PROC0_INTS1"] pub type R = crate::R<u32, super::PROC0_INTS1>; #[doc = "Reader of field `GPIO15_EDGE_HIGH`"] pub type GPIO15_EDGE_HIGH_R = crate::R<bool, bool>; #[doc = "Reader of field `GPIO15_EDGE_LOW`"] pub type GPIO15_EDGE_LOW_R = crate::R<bool, bool>; #[doc = "Reader of field `GPIO15_LEV...
use chrono::NaiveDateTime; use diesel::{insert_into, prelude::*, PgConnection, QueryResult}; use crate::schema::links::{self, dsl::links as all_links, dsl::shortened}; #[derive(Queryable)] pub struct Link { pub id: i32, pub shortened: String, pub original: String, pub created_at: NaiveDateTime, } #[d...
mod front_of_house { pub mod hosting { pub fn add_to_waitlist() { println!("add_to_waitlist: {:?}", "add_to_waitlist") } } } use front_of_house::hosting::add_to_waitlist; // 直接引入最终函数 pub fn eat_at_restaurant() { add_to_waitlist(); // 这里不再需要前缀, 但是 rust 不推荐这样用 add_to_waitlist...
use std::{ iter::Iterator, ops::{Deref, DerefMut}, rc::Rc, }; pub type ModelessId = usize; struct Loc<T> { top: T, left: T, bottom: T, right: T, } pub struct Modeless<T> { z_index: i32, position: Loc<f64>, grabbed: Option<Loc<f64>>, movable: Loc<bool>, parent: Option<R...
use sqlx_helper::{Get, Create, Update, Delete}; use chrono::NaiveDateTime; use serde::{Deserialize, Serialize}; #[derive(Clone, Debug, Serialize, Deserialize, Get, Create, Update, Delete)] pub struct Events { #[get(pk)] #[create(ignore)] pub id: i32, pub guild_id: i64, pub name: String, pub des...
trait SafeOps: Sized { fn safe_div(self, other: Self) -> Result<Self, String>; } impl SafeOps for i32 { fn safe_div(self, other: Self) -> Result<Self, String> { if other == 0 { Err(String::from("Division by zero")) } else { Ok(self / other) } } } fn calc() -...
#[doc = "Register `IWDG_HWCFGR` reader"] pub type R = crate::R<IWDG_HWCFGR_SPEC>; #[doc = "Field `WINDOW` reader - WINDOW"] pub type WINDOW_R = crate::FieldReader; #[doc = "Field `PR_DEFAULT` reader - PR_DEFAULT"] pub type PR_DEFAULT_R = crate::FieldReader; impl R { #[doc = "Bits 0:3 - WINDOW"] #[inline(always)...
use clap::Clap; /// Multiples of 3 and 5 #[derive(Clap)] pub struct Solution { #[clap(short, long, default_value = "1000")] limit: u64, } impl Solution { pub fn run(&self) -> u64 { let mut sum = 0; for i in 1..self.limit { sum += if (i % 3 == 0) || (i % 5 == 0) { i } else { 0 }...
use crate::sys::direct2d::Brush as D2DBrush; use crate::{device::Device, sys, text}; use kurbo::{Affine, PathEl, Rect, Shape, Point}; use piet::{Color, Error, FillRule, Gradient, ImageFormat, InterpolationMode, RoundInto, StrokeStyle}; use winapi::um::d2d1; pub struct Image(sys::direct2d::Bitmap); pub enum Brush { ...
extern crate qrcode; extern crate image; use qrcode::{EcLevel, QrCode, Version}; use qrcode::render::svg; use image::Luma; fn main() { // Encode some data into bits. let code = QrCode::with_version(b"01234567", Version::Micro(2), EcLevel::L).unwrap(); // Render the bits into an image. let image = code...
use crossterm::{ Crossterm, InputEvent, KeyEvent, Terminal, TerminalColor, TerminalCursor, TerminalInput, }; mod art; mod cargo_cmds; mod cursor; mod debouncer; mod events; mod format; mod help; #[cfg(feature = "highlight")] mod highlight; mod history; mod irust_error; pub mod options; mod parser; mod printer; mod...
#![feature(format_args_capture)] use std::fmt::Write; pub struct Generator { gen_addr_traits: bool, } pub fn generator(gen_addr_traits: bool) -> Box<dyn prost_build::ServiceGenerator> { Box::new(Generator { gen_addr_traits }) } impl prost_build::ServiceGenerator for Generator { fn generate(&...