text
stringlengths
8
4.13M
#[doc = "Register `CFGR` reader"] pub type R = crate::R<CFGR_SPEC>; #[doc = "Register `CFGR` writer"] pub type W = crate::W<CFGR_SPEC>; #[doc = "Field `SW` reader - System clock switch"] pub type SW_R = crate::FieldReader<SW_A>; #[doc = "System clock switch\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq,...
use serde_json::Value; use crate::error::Result; use crate::operation::Operation; use crate::traits::CanPatch; /// A sequence of JSON Patch operations. #[derive(Clone, Debug, PartialEq, Deserialize, Serialize)] #[repr(transparent)] #[serde(transparent)] pub struct Patch(Vec<Operation>); impl Patch { pub fn len(&se...
use std::io; fn main() -> io::Result<()> { for device in nihao_usb::sys::windows::devices()?.iter() { if let Ok(handle) = device?.open() { let buf_send = [0xF1u8, 0x80]; let mut buf_recv = vec![0u8; 1024]; handle.write_pipe(0x02, &buf_send)?; let len = handle...
//! Contains code pertaining to the communication between the data and control channels. use super::{proxy_protocol::ProxyConnection, session::SharedSession}; use crate::{ auth::UserDetail, server::controlchan::Reply, server::session::TraceId, storage::{Error, StorageBackend}, }; use std::fmt; use toki...
// Commands that are passed over the channel between the client and the server pub const SEND_PAYLOAD:u8 = 0; pub const REQUEST_PAYLOAD:u8 = 1; pub const END_TEST:u8 = 2; pub const PING_TEST:u8 = 3; pub const DISCONNECT:u8 = 255;
// non generic function fn largest_i32(list: &[i32]) -> &i32 { let mut largest = &list[0]; for item in list { if item > largest { largest = item; } } largest } // generic function fn largest<T>(list: &[T]) -> &T { let mut largest = &list[0]; for item in list { ...
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ #![doc = include_str!("../../README.md")] #![deny(missing_docs)] #![deny(rustdoc::broken_intra_doc_...
#[doc = "Register `DCR2` reader"] pub type R = crate::R<DCR2_SPEC>; #[doc = "Register `DCR2` writer"] pub type W = crate::W<DCR2_SPEC>; #[doc = "Field `PRESCALER` reader - Clock prescaler"] pub type PRESCALER_R = crate::FieldReader; #[doc = "Field `PRESCALER` writer - Clock prescaler"] pub type PRESCALER_W<'a, REG, con...
// Problem 3 // The prime factors of 13195 are 5, 7, 13 and 29. // What is the largest prime factor of the number 600851475143 ? fn main() { const VAL: u64 = 600851475143; let mut n = VAL; let mut last_factor: u64 = 1; divide_out(&mut n, 2, &mut last_factor); let mut i = 3; while i <= n { ...
extern crate rand; use std::env; // use std::process; use rand::{thread_rng, Rng}; fn d(sides : i32) -> i32 { let mut random = rand::thread_rng(); (random.gen_range(0, sides) + 1) } fn sum_d(dice : i32, sides : i32) -> i32 { let mut sum : i32 = 0; for x in 1..dice { sum = sum + d(sides); ...
use preexplorer::prelude::*; fn main() -> anyhow::Result<()> { // From coordinate values let xs = vec![1, 10, 100]; let ys = vec![1, 20, 50]; let values = vec![1, 2, 3, 4, 5, 6, 7, 8, 9]; let heatmap = pre::Heatmap::new(xs, ys, values) .set_title("first") .to_owned(); // From a...
// Copyright (c) 2019 - 2020 ESRLabs // // 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 ...
#![forbid(unsafe_code)] use pasts::prelude::*; use pasts::CvarExec; async fn timer_future(duration: std::time::Duration) { pasts::spawn_blocking(move || std::thread::sleep(duration)).await } fn main() { static EXECUTOR: CvarExec = CvarExec::new(); let ret = EXECUTOR.block_on(async { println!("Wai...
std_prelude!(); use crate::{Pet, PetRef, Pred}; /// Convenience extension for `Pred`. pub trait PredExt<T: ?Sized>: Pred<T> { /// Attempts to create a `Pet` of this predicate with the given value. fn pet(t: T) -> Option<Pet<T, Self>> where T: Sized; /// Creates a `Pet` of this predicate with th...
mod auth; mod messages; mod route; mod service; mod wshandler; use dotenv::dotenv; use actix::Actor; use actix_web::{web, App, HttpServer}; use drogue_cloud_service_common::{ config::ConfigFromEnv, health::HealthServer, openid::Authenticator, }; use drogue_cloud_service_common::{defaults, health::HealthServerCon...
#![crate_id="rust-story#0.0.1"] extern crate sdl2; extern crate sdl2_mixer; extern crate sdl2_ttf; extern crate rand; extern crate time; pub mod game; pub fn main() { println!("initalizing sdl ..."); let sdl_context = sdl2::init().unwrap(); let _ttf_context = sdl2_ttf::init(); let mut story = ::game::Game::new(...
use std::error::Error; use std::io; use std::io::prelude::*; use std::fs::File; use std::sync::{Mutex,RwLock,Arc,Barrier,Weak}; use description; pub struct ServerConfig{ pub server_adminPort:u16, pub server_gamePort:u16, pub server_editorPort:u16, pub server_address:String, pub server_connection...
#![doc = "generated by AutoRust 0.1.0"] #![allow(unused_mut)] #![allow(unused_variables)] #![allow(unused_imports)] use super::{models, API_VERSION}; #[non_exhaustive] #[derive(Debug, thiserror :: Error)] #[allow(non_camel_case_types)] pub enum Error { #[error(transparent)] BackupVaults_GetInSubscription(#[from...
#[doc = "Reader of register CH9_DBG_TCR"] pub type R = crate::R<u32, super::CH9_DBG_TCR>; impl R {}
/* ---The Meeting--- John has invited some friends. His list is: s = "Fred:Corwill;Wilfred:Corwill;Barney:Tornbull;Betty:Tornbull;Bjon:Tornbull;Raphael:Corwill; Alfred:Corwill"; Could you make a program that makes this string uppercase gives it sorted in alphabetical order by last name. When the last names are the sa...
pub mod acio; pub mod config; pub mod engine; pub mod threadpool; pub mod util;
use objectkey::ObjectKey; use std::collections::HashMap; use futures::Future; use std::iter::Map; trait Provider { fn get_type(&self) -> String; } struct MyService { database: HashMap<String, String> } impl MyService { fn new() -> MyService { MyService { database: HashMap::new() ...
extern crate guion_sdl2; use guion::{ widgets::textbox::TextBox, id::standard::StdID, validation::{validated::Validated, Validation}, }; use guion_sdl2::*; use simple::Simplion; //minimal example using the simple module fn main() { let mut simplion = Simplion::new(); //build a widget let g = Text...
pub fn length_of_lis(nums: Vec<i32>) -> i32 { if nums.len() <= 1 { return nums.len() as i32; } use std::cmp::*; let n = nums.len(); let mut dp = vec![1; n]; let mut largest = 0; for i in (0..n - 1).rev() { for j in i + 1..n { if nums[i] >= nums[j] { ...
use std::sync::Arc; use async_trait::async_trait; use common::error::Error; use common::event::{Event, EventHandler}; use common::result::Result; use shared::event::CollectionEvent; use crate::domain::catalogue::{CatalogueRepository, CollectionService}; pub struct CollectionHandler { catalogue_repo: Arc<dyn Cat...
use table_to_html::html::{Attribute, HtmlElement, HtmlValue, HtmlVisitor, HtmlVisitorMut}; use testing_table::{assert_table, test_table}; test_table!( html_built_element, HtmlElement::new( "table", vec![], Some(HtmlValue::Elements(vec![HtmlElement::new( "tr", vec...
use neon::vm:: { Call, JsResult }; use neon::mem::Handle; use neon::js:: { JsInteger, JsObject, Object }; pub fn return_js_object_with_integer(call: Call) -> JsResult<JsObject> { let scope = call.scope; let js_object: Handle<JsObject> = JsObject::new(scope); try!(js_object.set("number", JsInteger::new(scop...
extern crate gio; extern crate gtk; use gio::prelude::*; use gtk::prelude::*; use gtk::{Application, ApplicationWindow, Button}; use std::io::Write; use std::fs::File; use std::cell::RefCell; fn main() -> Result<(), Box<dyn std::error::Error>> { let application = Application::new(Some("by.iba.dk"), Default::def...
use crate::{ commands::{check_user_mention, parse_discord, MyCommand}, database::OsuData, embeds::{AvatarEmbed, EmbedData}, error::Error, util::{ constants::{ common_literals::{DISCORD, NAME}, GENERAL_ISSUE, OSU_API_ISSUE, }, ApplicationCommandExt, Int...
trait Person { fn name(&self) -> String; } // `Person` is a supertrait of `Student` trait Student: Person { fn university(&self) -> String; } trait Programmer { fn fav_language(&self) -> String; } // `CompSciStudent` is a subtrait of both `Programmer` and `Student` trait CompSciStudent: Programmer + Stud...
use bitflags::bitflags; use std::marker::PhantomData; use std::os::raw::{c_int, c_void}; use std::ptr; use crate::sys; use crate::{ImStr, ImString, Ui}; bitflags!( /// Flags for text inputs #[repr(C)] pub struct InputTextFlags: u32 { /// Allow 0123456789.+-*/ const CHARS_DECIMAL = sys::ImG...
use crate::{variable_length_crh::VariableLengthCRH, Error}; use ark_ec::{ group::Group, models::TEModelParameters, twisted_edwards_extended::GroupAffine as TEAffine, }; use ark_ff::{PrimeField, ToConstraintField, Zero}; use ark_std::rand::{CryptoRng, Rng, SeedableRng}; use ark_std::{ fmt::{Debug, Formatter, Res...
#![doc = "generated by AutoRust 0.1.0"] #![allow(unused_mut)] #![allow(unused_variables)] #![allow(unused_imports)] use super::{models, API_VERSION}; #[non_exhaustive] #[derive(Debug, thiserror :: Error)] #[allow(non_camel_case_types)] pub enum Error { #[error(transparent)] Capabilities_List(#[from] capabilitie...
use std::borrow::Cow; use std::time::SystemTime; mod header; mod packet; mod reader; mod writer; pub use self::reader::{mmap, open, parse, read, ParsePackets, ReadPackets, Reader}; pub use self::writer::{create, Builder, Writer}; /// The `Packet` struct contains information about a single captured packet. #[derive(C...
use anyhow::Result; use clap::{ app_from_crate, crate_authors, crate_description, crate_name, crate_version, value_t_or_exit, Arg, }; use csv::{StringRecord, Writer}; use itertools::Itertools; use serde::{Deserialize, Serialize}; use std::path::PathBuf; #[derive(Debug, PartialEq, Serialize, Deserialize)] struc...
use std::io; fn main() { loop{ let mut a: String = String::new(); println!("매치할 패턴(exit:종료):"); io::stdin().read_line(&mut a).expect("error"); if a.trim() == "exit" {break;} let mut b: String = String::new(); println!("매치할 문자:"); io::stdin().read_line(&mut b).expect("error"); println!("{:?}",matchStr...
pub fn do_thing() { crate::inner::innerdo(); } mod inner { use common::common_func; pub fn innerdo() { common_func(); } }
pub mod options; use std::{borrow::Borrow, collections::HashSet, fmt, fmt::Debug, str::FromStr, sync::Arc}; use futures_util::{ future, stream::{StreamExt, TryStreamExt}, }; use serde::{ de::{DeserializeOwned, Error as DeError}, Deserialize, Deserializer, Serialize, }; use self::options::*; u...
use chrono::prelude::*; use diesel::prelude::*; use diesel_migrations::embed_migrations; use std::collections::HashSet; use std::error::Error; use std::hash::BuildHasher; use diesel::{ r2d2::{ConnectionManager, Pool}, sqlite::SqliteConnection, }; use crate::feeds::result::{ConditionalGetData, FeedFetchResult,...
use x11::xlib; use error::XError; use window::Window; use std::ptr::{ null }; use std::ffi::{ CStr, CString} ; use libc::{ c_char, c_ulong }; use std::mem::transmute; use std::str::from_utf8; use std::os::unix::io::{ RawFd, AsRawFd }; use Event; use futures::Stream; use futures::Poll; use futures::Async; pub struct Di...
pub mod disk; pub mod allocator; pub mod concurrency;
use rosu_v2::prelude::User; use twilight_model::channel::Message; use crate::{commands::osu::MedalEntryList, embeds::MedalsListEmbed, BotResult}; use super::{Pages, Pagination}; pub struct MedalsListPagination { msg: Message, pages: Pages, user: User, acquired: (usize, usize), medals: Vec<MedalEn...
use anyhow::Context; use serde::Deserialize; use std::fmt; use std::fs; use std::path::{Path, PathBuf}; use std::str; type Result<T> = anyhow::Result<T>; #[derive(Deserialize)] pub struct Config { pub package: Option<Package>, pub lib: Option<Target>, pub bin: Option<Vec<Target>>, pub test: Option<Vec...
pub struct ThreadPool; impl ThreadPool { pub fn new(cnt: usize) -> ThreadPool { ThreadPool } pub fn execute<T>(&self, f: T) where T: FnOnce() + Send + 'static { } }
pub use platform::*; #[cfg(feature = "no-x11")] mod platform { use crate::config::{Side, StrutDefinition}; use anyhow::*; pub fn reserve_space_for(window: &gtk::Window, monitor: gdk::Rectangle, strut_def: StrutDefinition) -> Result<()> { Err(anyhow!("Cannot reserve space on non-X11 backends")) ...
use core::ops::Deref; use litex_pac::oled_spi::RegisterBlock; pub struct SPI { registers: &'static RegisterBlock } impl SPI { pub fn new<SPI: Deref<Target=RegisterBlock>>(spi: SPI) -> Self { Self { registers: unsafe { &*(spi.deref() as *const RegisterBlock) } } } } impl embedd...
use std::net::SocketAddr; use tokio::{ io::{AsyncReadExt, AsyncWriteExt}, net::{TcpListener, TcpStream}, }; async fn serve_client(mut socket: TcpStream, addr: SocketAddr) { eprintln!("New connection from {}", addr); let mut buffer = [0u8; 1024]; while let Ok(n) = socket.read(&mut buffer).await { ...
use std::process; use std::io; use std::error::Error; use colored::*; mod draw_chart; use draw_chart::{save_chart}; fn read_from_csv() -> Result<(Vec<(f64, f64)>, (String, String)), Box<dyn Error>> { let mut records: Vec<(f64, f64)> = Vec::new(); let mut rdr = csv::Reader::from_reader(io::stdin()); for result i...
#![deny(missing_docs)] #![cfg_attr(feature = "unstable", feature(optin_builtin_traits))] //! A safe approach to using `#[repr(packed)]` data. //! //! See `nue_macros` for the automagic `#[packed]` attribute. use std::mem::{transmute, replace, uninitialized, forget}; use std::marker::PhantomData; use std::mem::align_...
use crate::path::ModulePrefix; use proc_macro2::TokenStream; use quote::quote; pub fn generate(embassy_prefix: &ModulePrefix, config: syn::Expr) -> TokenStream { let embassy_rp_path = embassy_prefix.append("embassy_rp").path(); quote!( use #embassy_rp_path::{interrupt, peripherals}; let p = #e...
use crate::statement::Statement; pub struct Module{ pub ident: String, pub statements: Vec<Statement>, }
// q0025_reverse_nodes_in_k_group struct Solution; use crate::util::ListNode; impl Solution { pub fn reverse_k_group(head: Option<Box<ListNode>>, k: i32) -> Option<Box<ListNode>> { let mut tmp = vec![]; let mut buf = vec![]; let mut count = 0; let mut head = head; while le...
pub mod ast; pub mod error; pub mod tools; use crate::lexer::token::Token; use crate::lexer::Lexer; use anyhow::Result; use ast::{Expr, Stmt}; use error::ParserError; #[derive(PartialOrd, PartialEq, Debug)] enum Priority { Lowest, Equals, Lessgreater, Sum, Product, Prefix, Call, Inde...
extern crate chrono_english; use chrono_english::{parse_date_string,Dialect}; extern crate chrono; use chrono::prelude::*; extern crate lapp; use std::fmt::Display; use std::error::Error; type BoxResult<T> = Result<T,Box<dyn Error>>; const USAGE: &str = " Parsing Dates in English -a, --american informal dates are...
use crate::utils::asserts::meta::assert_meta; use crate::utils::asserts::transaction::{test_lock_array, test_transaction_array}; use crate::utils::asserts::wallet::{assert_wallet_data, test_wallet_array}; use crate::utils::mockito_helpers::{mock_client, mock_http_request, mock_post_request}; use serde_json::{from_str, ...
use crate::websocket_msg::{SendResponseMessage, ServerSender}; use actix::{Actor, AsyncContext, StreamHandler}; use actix_session::Session; use actix_web::{web, Error, HttpRequest, HttpResponse}; use actix_web_actors::ws::WebsocketContext; use actix_web_actors::ws::{Message, ProtocolError}; use anyhow::Result; use rus...
//! # Raw Sockets for nrfxlib //! //! Generic socket related code. //! //! Copyright (c) 42 Technology Ltd 2019 //! //! Dual-licensed under MIT and Apache 2.0. See the [README](../README.md) for //! more details. //****************************************************************************** // Sub-Modules //********...
// CONCISE CONTROL FLOW WITH if let /* The if let syntax lets you combine if and let into a less verbose way to handle values that match one pattern while ignoring the rest. */ #[derive(Debug)] enum UsState { Alabama, Alaska, // -- more states -- } #[derive(Debug)] enum Coin { Penny, Nickel, ...
use std::{fmt::Debug, hash::Hash}; use serde::{de::DeserializeOwned, Serialize}; /// ID of Version-Revision Resolver's entry. pub trait VrrId: Clone + Eq + PartialEq + Ord + PartialOrd + Hash + Debug + Serialize + DeserializeOwned + Sized { }
use std::{ collections::BTreeMap, fs, path::PathBuf, }; #[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] pub struct Arch(&'static str); impl Arch { pub fn id(&self) -> &str { &self.0 } pub fn build_all(&self) -> bool { self.id() == "amd64" } pub fn build_...
use generics::{Generic, Prod, Unit}; trait Accumulate { fn acc(self) -> u64; } impl Accumulate for u64 { fn acc(self) -> u64 { self } } impl Accumulate for Unit { fn acc(self) -> u64 { 0 } } impl<A, B> Accumulate for Prod<A, B> where A: Accumulate, B: Accumulate, { fn...
#[doc = r" Value read from the register"] pub struct R { bits: u32, } #[doc = r" Value to write to the register"] pub struct W { bits: u32, } impl super::RSR { #[doc = r" Modifies the contents of the register"] #[inline] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'w mut W...
//! The Sample Manipulation Language, SML for short, is a first-order, total, //! typed programming language for generating and transforming samples. //! //! In this module you can find types for representing SML expressions, and //! functions for analyzing and evaluating them. use std::rc::Rc; pub mod check; /// A ...
use serde::{Deserialize, Serialize}; use crate::CSIStruct; #[derive(Clone, Debug, Serialize, Deserialize)] pub struct ComplexDef<T> { pub re: T, pub im: T, } /// 'Absolute' value of a subcarrier pub fn abs(c: ComplexDef<isize>) -> f64 { ((c.re.pow(2) + c.im.pow(2)) as f64).sqrt() } /// Serialization ty...
use nasa_apod::{Body, E}; #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> { let url = nasa_apod::construct_url(); //requesting data let res = match reqwest::get(&url).await { Ok(response) => { if response.status() == 400 { nasa_apod::print_err(&r...
use crate::graphics::{Vertex, Instance}; pub struct Object { vertex_buffer: wgpu::Buffer, index_buffer: wgpu::Buffer, instance_buffer: wgpu::Buffer, instances: Vec<Instance>, num_indices: u32, instance_buffer_size: usize, } impl Object { pub fn new(device: &wgpu::Device, vertices: &[Vertex...
extern crate bytes; extern crate tokio; use std::io::{BufReader, ErrorKind}; use std::net::SocketAddr; // use std::sync::{Arc, Mutex}; use bytes::BytesMut; use tokio::io::{lines, Lines, ReadHalf, WriteHalf}; use tokio::net::{TcpListener, TcpStream}; use tokio::prelude::*; type TcpLines = Lines<BufReader<ReadHalf<Tc...
extern crate cannyls; extern crate cannyls_rpc; extern crate fibers; extern crate fibers_rpc; extern crate futures; #[macro_use] extern crate slog; extern crate tempdir; #[macro_use] extern crate trackable; use cannyls::device::DeviceBuilder; use cannyls::lump::{LumpData, LumpId}; use cannyls::nvm::MemoryNvm; use cann...
use std::io::{Result, Write}; use pulldown_cmark::{Event, Tag}; use crate::gen::{State, States, Generator, Stack, Document}; #[derive(Debug)] pub struct Rule; impl<'a> State<'a> for Rule { fn new(tag: Tag<'a>, gen: &mut Generator<'a, impl Document<'a>, impl Write>) -> Result<Self> { Ok(Rule) } ...
// This file is part of Substrate. // Copyright (C) 2017-2020 Parity Technologies (UK) Ltd. // SPDX-License-Identifier: Apache-2.0 // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // ht...
use std::convert::TryFrom; use std::hash; use super::prelude::*; use super::{Boolean, Integer, Object, StringLit}; #[derive(Debug, Clone, Eq)] pub enum HashableObject { Integer(Integer), Boolean(Boolean), StringLit(StringLit), } impl Display for HashableObject { fn fmt(&self, f: &mut Formatter<'_>) -...
//#![deny(warnings)] extern crate regex; extern crate reqwest; extern crate serde; extern crate tokio; use finox::{roses, sec}; #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> { let index = roses::read_into::<sec::SecIndex>("../ref_data/sec13f.csv").unwrap(); let urls: Vec<String> = in...
use tone::ToneFormat; use syllable::{ PrimitiveSyllable, NormalSyllable, RhymeSyllable, NasalSyllable }; pub trait Show { fn show(&self, tone_format: ToneFormat) -> Result<(), ()>; } impl Show for PrimitiveSyllable { fn show(&self, _tone_format: ToneFormat) -> Result<(), ()> { unimplemented!() }...
use oxygengine::prelude::*; use serde::{Deserialize, Serialize}; #[derive(Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize)] pub enum AnimalKind { GroundWater, WaterAir, AirGround, } impl Prefab for AnimalKind {} impl PrefabComponent for AnimalKind {} impl AnimalKind { pub fn image(self) -> ...
#![allow(dead_code)] #![feature(const_type_id)] #![feature(portable_simd)] #![feature(test)] extern crate bevy; // #[macro_use] extern crate bevycheck; #[macro_use] extern crate serde; #[macro_use] extern crate derive_new; extern crate bevy_mod_bounding; extern crate bevy_frustum_culling; // extern crate bevy_world_t...
use serde::Serialize; #[derive(Serialize, Default, Debug)] pub struct UListFields { /// User-set notes #[serde(skip_serializing_if = "Option::is_none")] notes: Option<String>, /// YYYY-MM-DD #[serde(skip_serializing_if = "Option::is_none")] started: Option<String>, /// YYYY-MM-DD #[serd...
mod cstring; pub use self::cstring::*; // Re-export the requiste types from libc, all of libc won't work so we expose them in our // FFI module. pub use libc::types::os::arch::c95::*; pub use libc::types::os::arch::c99::*; pub use libc::types::common::c95::*; pub use libc::types::common::c99::*;
// There exists exactly one Pythagorean triplet for which a + b + c = 1000. //Find the product abc. use std::time::Instant; fn main() { let now = Instant::now(); println!("result: {:?}, time: {:?}", e9(), now.elapsed()); let now = Instant::now(); println!("result: {:?}, time: {:?}", e9_i(), now.elapsed...
use std::ops::Range; /////////////////////////////////////////////////////////////////////////////// struct DigitIterator { n: u64, count: u8 } impl DigitIterator { pub fn new(n: u64) -> Self { let count = (n as f64).log10() as u8 + 1; DigitIterator { n, count } } } impl Iterator for...
use ::ftdi_library::ftdi::core::*; use ::ftdi_library::ftdi::ftdi_context::ftdi_context; use ::ftdi_library::ftdi::ftdi_version_info::ftdi_version_info; use log::{info}; use log4rs; use ftdi_library::ftdi::constants::ftdi_chip_type; use ftdi_library::ftdi::ftdi_context::FtdiContextError; // use libc::{c_int}; #[cfg(ta...
#![feature(test)] extern crate test; extern crate graphql_parser; use graphql_parser::{parse_query, parse_schema}; #[bench] fn bench_minimal(b: &mut test::Bencher) { let src = include_str!("../tests/minimal_query.graphql"); b.iter(|| parse_query(src).unwrap()); } #[bench] fn bench_inline_fragment(b: &mut te...
struct Solution; impl Solution { pub fn unique_paths(mut m: i32, mut n: i32) -> i32 { if m <= 1 || n <= 1 { return 1; } if m < n { // 为了让下面的 row 占用的空间少点。 std::mem::swap(&mut m, &mut n); } let n = n as usize; // 第一行的路径数,都是1 ...
use std::{cell::RefCell, fmt::Debug, ops::Deref, rc::Rc}; pub type P<T> = Rc<T>; #[allow(non_snake_case)] pub fn P<T>(val: T) -> P<T> { P::new(val) } pub struct Mut<T>(Rc<RefCell<T>>); pub struct MutWeak<T>(std::rc::Weak<RefCell<T>>); impl<T> Mut<T> { pub fn new(val: T) -> Mut<T> { Mut(Rc::new(RefC...
use uuid::Uuid; use airmash_protocol::{self as protocol, FlagCode}; use specs::*; use types::ConnectionId; use std::time::Duration; pub type Flag = FlagCode; pub type Plane = protocol::PlaneType; pub type Status = protocol::PlayerStatus; pub type Mob = protocol::MobType; #[derive(Clone, Debug, Default, Component, ...
#[doc = "Register `RSR` reader"] pub type R = crate::R<RSR_SPEC>; #[doc = "Register `RSR` writer"] pub type W = crate::W<RSR_SPEC>; #[doc = "Field `RMVF` reader - remove reset flag Set and reset by software to reset the value of the reset flags."] pub type RMVF_R = crate::BitReader; #[doc = "Field `RMVF` writer - remov...
use bosy::specification::Semantics; use cudd::{CuddManager, CuddNode}; use log::info; #[derive(Debug)] pub struct SafetyGame<'a> { pub(crate) manager: &'a CuddManager, pub(crate) controllables: Vec<CuddNode<'a>>, pub(crate) uncontrollables: Vec<CuddNode<'a>>, pub(crate) latches: Vec<CuddNode<'a>>, ...
//! This crate provides the feature of diplaying the information of filtered lines //! by printing them to stdout in JSON format. mod truncation; use icon::{Icon, ICON_LEN}; use types::FilteredItem; use utility::{println_json, println_json_with_length}; pub use self::truncation::{ truncate_grep_lines, truncate_l...
use std::fs; use regex::Regex; use day4::{PassportField, PassportsParser, PassportsValidator}; fn main() { const PASSPORTS_FILENAME: &str = "resources/passports"; let passport_fields = get_passport_fields(); let input = fs::read_to_string(PASSPORTS_FILENAME).unwrap(); let passports = PassportsParser...
use std::collections::HashMap; use crate::execute::{VMError, VMResult}; use crate::value::Value; #[derive(Debug)] pub struct Object { fields: HashMap<String, Value>, } impl Object { pub fn new() -> Self { Object { fields: HashMap::new(), } } pub fn set(&mut self, name: St...
use crate::asset::property::context::*; use crate::asset::*; use crate::reader::*; use anyhow::*; use std::str::FromStr; use strum_macros::{Display, EnumString}; #[derive(Debug, Clone, Copy, PartialEq, Display, EnumString)] pub enum PropType { IntProperty, UInt8Property, FloatProperty, ObjectProperty, SoftOb...
/* * 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 */ /// SyntheticsPrivateLocationSecretsConfigDecryption : Private key for the private location. #[derive...
#[doc = r"Register block"] #[repr(C)] pub struct RegisterBlock { #[doc = "0x00 - memory remap register"] pub memrmp: MEMRMP, #[doc = "0x04 - configuration register 1"] pub cfgr1: CFGR1, #[doc = "0x08 - external interrupt configuration register 1"] pub exticr1: EXTICR1, #[doc = "0x0c - extern...
use std::collections::HashMap; use crate::database::schema::crates; use serde::{Deserialize, Serialize}; #[derive(Queryable, Insertable, Serialize, Deserialize, Debug, Default)] #[table_name = "crates"] pub struct Crates { #[serde(skip_serializing)] pub id: String, pub name: String, #[serde(skip_serial...
// Copyright 2013-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-MI...
#![allow(dead_code)] fn digits_iter(num: usize) -> impl Iterator<Item = u8> + 'static { let mut num = num; [100_000, 10_000, 1_000, 100, 10, 1] .iter() .map(move |base| { let digit = (num / base) as u8; num %= base; digit }) } fn is_valid_pw(pw: usiz...
/// Contains every ppm structure and their implementations pub mod entities;
use crate::compare::{assert_match_exact, find_json_mismatch}; use crate::registry::{self, alt_api_path}; use flate2::read::GzDecoder; use std::collections::{HashMap, HashSet}; use std::fs::File; use std::io::{self, prelude::*, SeekFrom}; use std::path::{Path, PathBuf}; use tar::Archive; fn read_le_u32<R>(mut reader: R...
//! Extracting bitfields from integers. //! //! If `x` is an unsigned integer, `x.bits(lo, hi)` is a number of //! the same type with the bits of `x` in the range [`lo`, `hi`) in //! its low part. //! //! # Examples //! ``` //! let x = 0xabcdef00u32; //! assert_eq!(x.bits(8, 16), 0xef); //! assert_eq!(x.bits(16, 28), 0...
use std::io::{stdin, Read, StdinLock}; use std::str::FromStr; #[allow(dead_code)] struct Scanner<'a> { cin: StdinLock<'a>, } #[allow(dead_code)] impl<'a> Scanner<'a> { fn new(cin: StdinLock<'a>) -> Scanner<'a> { Scanner { cin: cin } } fn read<T: FromStr>(&mut self) -> Option<T> { let t...
#[doc = "Reader of register MS6_CTL"] pub type R = crate::R<u32, super::MS6_CTL>; #[doc = "Writer for register MS6_CTL"] pub type W = crate::W<u32, super::MS6_CTL>; #[doc = "Register MS6_CTL `reset()`'s with value 0x0303"] impl crate::ResetValue for super::MS6_CTL { type Type = u32; #[inline(always)] fn res...