text
stringlengths
8
4.13M
#[doc = "Register `CR` reader"] pub type R = crate::R<CR_SPEC>; #[doc = "Register `CR` writer"] pub type W = crate::W<CR_SPEC>; #[doc = "Field `ENABLE` reader - LPTIM Enable"] pub type ENABLE_R = crate::BitReader<ENABLE_A>; #[doc = "LPTIM Enable\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub en...
#[doc = "Reader of register MMMS_ADVCH_NI_ENABLE"] pub type R = crate::R<u32, super::MMMS_ADVCH_NI_ENABLE>; #[doc = "Writer for register MMMS_ADVCH_NI_ENABLE"] pub type W = crate::W<u32, super::MMMS_ADVCH_NI_ENABLE>; #[doc = "Register MMMS_ADVCH_NI_ENABLE `reset()`'s with value 0"] impl crate::ResetValue for super::MMM...
use board::Board; use marker::Marker; use marker; pub fn expand_board(board: &Board) -> Vec<String> { let spaces = board.get_spaces(); let number_of_spaces = board.get_size() * board.get_size(); let mut expanded_board: Vec<String> = vec![" ".to_string(); number_of_spaces as usize]; for (index, space) i...
use super::data::*; use nom::{ character::complete::{digit1, hex_digit1, line_ending, not_line_ending, space1}, bytes::complete::tag, delimited, do_parse, eof, many0, map, map_res, named, opt, preceded, return_error, separated_list, switch, take, value, }; pub struct ParseError; fn from_hex(input: &st...
use std::rc::Rc; use std::sync::Arc; use crate::builder::factories::SubsystemFactory; use crate::mechatronics::dumper::Dumper; use crate::motor_controllers::motor_group::MotorGroup; use crate::motor_controllers::print_motor::PrintMotor; use crate::motor_controllers::roboclaw::RoboClaw; use crate::motor_controllers::te...
#[doc = "Register `CCSWCR` reader"] pub type R = crate::R<CCSWCR_SPEC>; #[doc = "Register `CCSWCR` writer"] pub type W = crate::W<CCSWCR_SPEC>; #[doc = "Field `SW_ANSRC1` reader - NMOS compensation code for VDD power rails This bitfield is written by software to define an I/O compensation cell code for NMOS transistors...
//! Handles COM initialization and cleanup. use super::helpers::*; use winapi::um::combaseapi::{CoInitializeEx, CoUninitialize}; use winapi::um::objbase::COINIT_MULTITHREADED; use std::ptr; /// RAII object that guards the fact that COM is initialized. /// // We store a raw pointer because it's the only way at the m...
#[doc = "Register `TZC_CID3` reader"] pub type R = crate::R<TZC_CID3_SPEC>; #[doc = "Field `COMP_ID_3` reader - COMP_ID_3"] pub type COMP_ID_3_R = crate::FieldReader; impl R { #[doc = "Bits 0:7 - COMP_ID_3"] #[inline(always)] pub fn comp_id_3(&self) -> COMP_ID_3_R { COMP_ID_3_R::new((self.bits & 0xf...
extern crate byteorder; use std::env::args; use std::fs::File; use std::io::Read; use std::io::Write; use std::io::stdin; use std::io::stdout; use std::path::Path; /// The virtual machine memory is 0x8000 elements followed by 8 registers. type Memory = [u16; 0x8008]; /// The default memory image name used when no ar...
/// A node property. /// /// # Semantics /// /// A property contained in a [`greater_elements::PropertyDrawer`]. /// /// # Syntax /// /// Follows one of these patterns: /// /// - `:NAME: VALUE` /// - `:NAME+: VALUE` /// - `:NAME:` /// - `:NAME+:` /// /// `NAME` can contain any non-whitespace character but can't be an e...
use std::{fs::File, io::{BufRead, BufReader}}; fn main() { let file = File::open("inputs/input-11.txt").unwrap(); let mut seats: Vec<Vec<char>> = BufReader::new(file).lines().map(|l| l.unwrap().chars().collect::<Vec<char>>()).collect(); let mut seats2 = seats.clone(); let mut change = true; while ...
extern crate irc; use irc::client::prelude::*; fn main() { let server = IrcServer::new("config.json").unwrap(); server.identify().unwrap(); for message in server.iter() { let message = message.unwrap(); // We'll just panic if there's an error. println!("{}", message.into_string()); ...
//! TODO docs use crate::{Read, ReadError, Write, WriteError}; use std::ops::Deref; /// A stream of bytes pub struct DataStream { /// TODO docs bytes: Vec<u8>, /// TODO docs pos: usize, } impl DataStream { /// Read something from the stream #[inline] pub fn read<T: Read>(&mut self) -> Resu...
fn main() { // Define y of type reference to // an immutable int. let y: &i32; { let x = 5; // This is not allowed. y = &x; // x is freed here. } // We would now have a reference to an invalid // memory location. println!("{}", y); // y is freed here. ...
//给定一个字符串 s,找到 s 中最长的回文子串。你可以假设 s 的最大长度为 1000。 // //示例 1: // //输入: "babad" //输出: "bab" //注意: "aba" 也是一个有效答案。 //示例 2: // //输入: "cbbd" //输出: "bb" use std::cmp::max; type MaxStr = (usize, String); struct Solution { } impl Solution { fn longest_palindrome(s:&String) -> String { let mut max_str:MaxStr = (0, ...
extern crate pest; extern crate rust_orgmode; use pest::Parser; use rust_orgmode::parsing::{OrgModeParser, Rule}; use std::fs::{self, File}; use std::io::Read; fn test_files() -> impl Iterator<Item = File> { fs::read_dir("tests/correct").unwrap().filter_map(|entry| { let entry = match entry { ...
use std::os::raw::{c_double, c_int, c_uint}; use crate::point::Point; use crate::size::WorldSize; use crate::game::{Game, GameEvent, GameState}; use crate::bullet::BulletType; use crate::swarm::Swarm; use crate::shield::Shield; use crate::particle::{make_explosion, Particle}; use std::sync::mpsc; use std::sync::mpsc:...
use std::collections::HashMap; 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() } fn read_vec<T: std::str::FromStr>() -> Vec<T> { read::<String>().split_whitespace().map(|e| e.parse().ok().unwrap()).collect() } fn...
// Copyright 2015-2020 Parity Technologies // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except ...
use libc::{c_void, c_char, c_int, c_uint}; use std::{mem, ptr}; use nix::sys::socket; use std::net::{SocketAddr, SocketAddrV4, SocketAddrV6, Ipv4Addr, Ipv6Addr}; // nix doesn't have this const pub const AF_PACKET: i32 = 17; #[allow(dead_code)] #[repr(C)] pub enum SIOCGIFFLAGS { IFF_UP = 0x1, /* Interface is up....
use core::{marker::PhantomData, pin::Pin}; use std::{ collections::HashSet, sync::{ atomic::{AtomicU64, Ordering}, Arc, }, }; use futures::{Future, FutureExt}; use tokio::sync::Mutex; use crate::{ error::StdSyncSendError, receiver::{ BusPollerCallback, Receiver, ReciveType...
use ring::rand::{SecureRandom, SystemRandom}; use ring::{digest, pbkdf2}; use std::num::NonZeroU32; static DIGEST_ALG: pbkdf2::Algorithm = pbkdf2::PBKDF2_HMAC_SHA256; const CREDENTIAL_LEN: usize = digest::SHA256_OUTPUT_LEN; pub fn hash_password(secret: &[u8], salt: &[u8], iterations: u32) -> Vec<u8> { let mut out...
#![allow(dead_code)] extern crate fantoccini; extern crate futures_util; use fantoccini::{error, Client}; use std::future::Future; use std::net::{IpAddr, Ipv4Addr, SocketAddr}; use std::path::PathBuf; use warp::Filter; pub async fn select_client_type(s: &str) -> Result<Client, error::NewSessionError> { match s ...
use clap::Clap; use futures::future::join_all; use rayon::prelude::*; use std::fs::File; use std::io::copy; use std::io::{self, BufRead}; use std::path::Path; #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> { let opts: Opts = Opts::parse(); let urls: Vec<String> = match read_lines(opt...
use futures::{ future::{self, Ready}, prelude::*, }; use service::World; use std::{ io, net::{IpAddr, SocketAddr}, }; use tarpc::{ context, server::{self, Channel, Handler}, }; use tokio_serde::formats::Json; #[derive(Clone)] pub struct HelloServer(SocketAddr); impl World for HelloServer { ...
// #[cfg(test)] // mod tests { // #[test] // fn it_works() { // assert_eq!(2 + 2, 4); // } // } pub fn add_two(a:i32) -> i32{ internal_adder(a,2) } fn internal_adder(a:i32,b:i32) -> i32 { a + b } #[cfg(test)] mod tests{ use super::*; #[test] fn internal(){ // assert_e...
use std::convert::Infallible; use syscall::{ Result, Error, close, EIO, pipe2, read, write, SchemeMut, Packet, O_CREAT, O_RDWR, O_CLOEXEC, EINTR, }; #[must_use = "Daemon::ready must be called"] pub struct Daemon { write_pipe: usize, } impl Daemon { pub fn new<F...
use axum::response::IntoResponse; use miette::Diagnostic; use reqwest::StatusCode; use thiserror::Error; #[derive(Debug, Diagnostic, Error)] #[error("MietteError")] pub struct MietteError(pub(crate) miette::Report); impl IntoResponse for MietteError { fn into_response(self) -> axum::response::Response { s...
mod database; mod model; pub use self::database::Database; pub use self::model::{CustomEmoji, Emoji};
{ "id": "7d304d1d-da59-4419-9d97-af59fb4cb5e7", "$type": "BaseTypesResource", "BoolField": "true", "ByteField": "123", "DoubleField": "123", "FloatField": "1231.2211", "IntField": "123", "LongField": "123", "StringField": "21312dsadas" }
use std::fs::File; use std::io::Read; use zip::ZipArchive; pub struct ArchiveFile {} pub struct ArchiveManager { pub files: ZipArchive<File>, } impl ArchiveManager { pub fn new(files: ZipArchive<File>) -> ArchiveManager { ArchiveManager { files } } pub fn get(&mut self, name: String) -> Vec<...
use std::fmt::Debug; use std::fs::File; use std::io::BufRead; use std::io::BufReader; use std::io::Error; use std::str::FromStr; pub fn read_data<T>(filename: &str) -> Result<Vec<T>, Error> where T: FromStr, <T as FromStr>::Err: Debug, { let file = File::open(filename)?; let v = BufReader::new(file) ...
pub mod board; pub mod nodeman; pub mod nodelet; #[cfg(test)] mod tests { use crate::nodeman::NodeMan; use crate::nodelet::Nodelet; use crate::board::Board; use bitop::b16::B16; #[test] fn test_board_16() { let mut board : Board<B16> = Board::<B16>::new(); //初手から実行 let r...
//! A simple Driver for the Waveshare 2.9" E-Ink Display via SPI //! //! //! # Example for the 2.9 in E-Ink Display //! //!```rust, no_run //!# use embedded_hal_mock::*; //!# fn main() -> Result<(), MockError> { //!use embedded_graphics::{ //! pixelcolor::BinaryColor::On as Black, prelude::*, primitives::{Line, Prim...
use storm::{Entity, MssqlDelete}; #[derive(MssqlDelete)] #[storm(table = "t", keys = "id", no_test = true)] pub struct EntityWithDuplicateKey { pub name: String, pub id: i32, } impl Entity for EntityWithDuplicateKey { type Key = i32; type TrackCtx = (); }
use crate::defs::*; use crate::exceptions; use crate::symbols; use crate::error::RuntimeError; use libc::{c_char, c_void}; use std::ffi::{CStr, CString}; use std::io::Write; use std::mem; fn arr_to_raw(arr: &[&str]) -> *const *const c_char { let vec: Vec<_> = arr .iter() .map(|s| CString::new(*s)....
use std::collections::hash_map::Entry; use std::collections::{HashMap, VecDeque}; use std::iter::FromIterator; use anyhow::*; use bevy_asset::{Handle, LoadContext, LoadedAsset}; use bevy_ecs::{ bundle::Bundle, entity::Entity, reflect::ReflectComponent, system::{Commands, Query}, world::{EntityMut, ...
#![doc = include_str!("../README.md")] use std::iter::Iterator; use proc_macro::TokenStream; use quote::{quote, quote_spanned}; #[derive(Clone, Copy)] enum Platform { Default, Tokio, AsyncStd, Hydroflow, Wasm, EnvLogging, EnvTracing, } impl Platform { // All platforms. const ALL: ...
use nannou::prelude::*; fn main() { nannou::sketch(view).run() } fn view(app: &App, frame: Frame) { // Begin drawing let draw = app.draw(); // Clear the background to blue. draw.background().color(BLACK); let win = app.window_rect(); // Draw an ellipse to follow the mouse. let t = ap...
//! JSON API mod call; mod deploy; mod error; mod inputdata; mod receipt; mod spawn; pub(crate) mod serde_types; pub use call::{decode_call, encode_call, encode_call_raw}; pub use deploy::deploy_template; pub use error::JsonError; pub use inputdata::{decode_inputdata, encode_inputdata}; pub use receipt::decode_recei...
#[macro_use] extern crate log; extern crate async_std; extern crate getopts; extern crate stunnel; use std::env; use std::net::Shutdown; use std::net::ToSocketAddrs; use std::str::from_utf8; use std::vec::Vec; use async_std::net::TcpListener; use async_std::net::TcpStream; use async_std::prelude::*; use async_std::ta...
use super::super::HasTable; use super::{Component, FromWorldMut, TableId}; use crate::prelude::World; use std::ops::{Deref, DerefMut}; use std::ptr::NonNull; /// Fetch read-write table reference from a Storage. /// This is a pretty unsafe way to obtain mutable references. Use with caution. /// Do not store UnsafeViews...
#![feature(test)] extern crate test; extern crate delight_book; extern crate rand; use delight_book::chapter15::*; use rand::Rng; #[bench] fn bench_hamming_code(b: &mut test::Bencher) { b.iter(|| for i in 0..(39 * 40) / 2 + 1 { let us = rand::thread_rng().gen::<i64>() * 3; // Generate...
use std::{ convert::{TryFrom, TryInto}, fmt::Display, io::{BufReader, Read}, }; use thiserror::Error; use super::{ lookup::{LookupError, LookupRef, LookupValue}, raw::{CelesteIo, NonRleString, RleString, StringReadError}, }; #[derive(Clone, Debug)] pub enum Value { Bool(bool), Int(i32), ...
use anyhow::Error; use anyhow::Result; const RAM_SIZE: usize = 4096; #[derive(PartialEq, Eq, Debug)] pub struct Memory([u8; RAM_SIZE]); impl Memory { pub fn new() -> Self { let mut mem = [0; RAM_SIZE]; Self::load_font(&mut mem); Self(mem) } pub fn get_byte(&self, addr: u16) -> Re...
mod p1qa; use p1qa::build_vector_verbose; fn main() { let n = build_vector_verbose(); println!("{:?}", n) }
use super::helpers::edits::get_random_edit; use super::helpers::fixtures::{fixtures_dir, get_language, get_test_language}; use super::helpers::random::Rand; use crate::generate::generate_parser_for_grammar; use crate::parse::perform_edit; use std::fs; use tree_sitter::{Node, Parser, Point, Tree}; const JSON_EXAMPLE: &...
use std::sync::{ Arc, Weak, // Mutex, MutexGuard }; use parking_lot::{ Mutex, MutexGuard }; use serenity::prelude::*; use serenity::model::channel::Message; use serenity::framework::{ Framework, standard::{ StandardFramework, Configuration, } }; use c...
use std::fs; use std::io::{self, Write}; use std::collections::HashMap; const MODE_POS: i64 = 0; const MODE_IMM: i64 = 1; const MODE_REL: i64 = 2; const OP_EXIT: i64 = 99; const OP_ADD: i64 = 1; const OP_MULTIPLY: i64 = 2; const OP_INPUT: i64 = 3; const OP_OUTPUT: i64 = 4; const OP_JUMP_IF_TRUE: i64 = 5; const OP_JUM...
// Copyright 2019 EinsteinDB Project Authors. Licensed under Apache-2.0. use criterion::{BatchSize, Bencher, BenchmarkId, Criterion, Throughput}; use violetabft::evioletabftpb::{ConfState, Entry, Message, Snapshot, SnapshotMetadata}; use violetabft::{storage::MemStorage, Config, RawNode}; use std::time::Duration; pub...
//! Clients for services. mod device_auth; mod user_auth; pub use device_auth::*; pub use user_auth::*; use drogue_client::error::{ClientError, ErrorInformation}; use http::StatusCode; use reqwest::Response; pub(crate) async fn default_error<T>( code: StatusCode, response: Response, ) -> Result<T, ClientErr...
#![deny(rustdoc::broken_intra_doc_links)] use partition::Partition; use proc_macro::TokenStream; use syn::{parse_macro_input, ItemMod, TypePath}; mod generate; mod parse; mod partition; /// Convenience macro for simpler partition development with less pitfalls /// /// For using this macro a module is annotated with t...
extern crate libc; use libc::{c_int, c_void, c_char, time_t, ssize_t, size_t, uint8_t, uint32_t}; pub type Tls = *mut c_void; pub type Config = *mut c_void; pub const WANT_POLLIN: i64 = -2; pub const WANT_POLLOUT: i64 = -3; extern "C" { pub fn tls_init() -> c_int; pub fn tls_free(ctx: Tls); pub fn tls_er...
use std::path::PathBuf; use crate::{ HttpdArgs, Result, mqtt::{self, Mqtt}, }; use std::{ collections::HashMap, sync::{Arc, Mutex} }; use async_std::{fs as async_fs, io as async_io, task as async_task}; use log::{debug, info}; type ServerState = Arc<Mutex<Mqtt>>; pub fn start(args: HttpdArgs, mut...
use crate::hal::{ gpio::{p0, Floating, Input, Output, Pin, PushPull}, gpiote::GpioteChannel, prelude::{InputPin, OutputPin}, }; use rtic::time::duration::Milliseconds; pub type ButtonEnablePin = p0::P0_15<Output<PushPull>>; pub type ButtonPin = p0::P0_13<Input<Floating>>; pub struct Button { _enable_p...
#![no_std] #![no_main] #![feature(lang_items)] #![feature(alloc_error_handler)] #![feature(panic_info_message)] // Import from `core` instead of from `std` since we are in no-std mode use core::result::Result; // Import heap related library from `alloc` // https://doc.rust-lang.org/alloc/index.html use alloc::vec::Ve...
use std::borrow::Cow; use std::cmp; use std::io::Write; use std::mem; use byteorder::{ByteOrder, WriteBytesExt}; use nom::*; use errors::{PcapError, Result}; use pcapng::options::pad_to; use pcapng::{Block, BlockType}; use traits::WriteTo; pub const BLOCK_TYPE: u32 = 0x0000_0003; /// The Simple Packet Block (SPB) i...
use crate::fungible_token::FungibleToken; use crate::storage_management::{StorageBalance, StorageBalanceBounds, StorageManagement}; use near_sdk::json_types::{ValidAccountId, U128}; use near_sdk::{assert_one_yocto, env, log, AccountId, Balance, Promise}; impl FungibleToken { /// Internal method that returns the Ac...
#![feature(proc_macro_hygiene, decl_macro)] mod auth; mod controller; mod model; mod repository; mod service; mod db; #[macro_use] extern crate rocket; use crate::controller::*; use crate::repository::{CommentsRepository, PostsRepository, UserRepository}; use rocket::http::Method; use rocket::response::{NamedFile, R...
use crate::rand3; fn smoothstep (edge0: f64, edge1: f64, mut x: f64) -> f64{ // Scale, bias and saturate x to 0..1 range x = clamp((x - edge0) / (edge1 - edge0), 0.0, 1.0); // Evaluate polynomial return x * x * (3.0 - 2.0 * x); } fn clamp(x: f64, lowerlimit: f64, upperlimit: f64) -> f64 { if x < lowerlimit...
pub mod neuron; pub mod rl;
use gtk::prelude::GtkMenuItemExt; use gtk::prelude::MenuShellExt; use gtk::prelude::WidgetExt; use gtk; use clipboard::{ClipboardContext, ClipboardProvider}; use libappindicator::{AppIndicator, AppIndicatorStatus}; use super::super::seeds::Seeds; pub struct Applet { seeds: Seeds, } impl Applet { pub fn new(...
#[macro_export] macro_rules! typed_index { (@base_no_salsa $outer_vis:vis $name:ident $max_u32:expr) => { #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] #[repr(transparent)] $outer_vis struct $name(core::num::NonZeroU32); $crate::debug_fallback_impl!($name); i...
//! Zellij utilities. pub mod consts; pub mod logging; pub mod shared;
struct Kagome{ }
use player::*; use slog::Logger; pub struct InternalState { pub players: Vec<Player>, pub mafia_kill: isize, pub first_night: bool, pub logger: Logger, }
// compile-args: --crate-type lib #![deny(broken_intra_doc_links)] //~^ WARNING renamed //! [x] //~^ ERROR unresolved link
extern crate ocl; use ocl::prm::{Uchar8, Float16}; pub trait SceneObject{ fn get_integer_data(&self) -> Uchar8; fn get_float_data(&self) -> Float16; }
extern crate bytecodec; #[macro_use] extern crate clap; extern crate fibers; extern crate fibers_http_client; extern crate futures; #[macro_use] extern crate trackable; extern crate url; use bytecodec::bytes::Utf8Decoder; use clap::Arg; use fibers::sync::oneshot::MonitorError; use fibers::{Executor, InPlaceExecutor, S...
#[doc = "Register `DINR11` reader"] pub type R = crate::R<DINR11_SPEC>; #[doc = "Field `DIN11` reader - Input data received from MDIO Master during write frames"] pub type DIN11_R = crate::FieldReader<u16>; impl R { #[doc = "Bits 0:15 - Input data received from MDIO Master during write frames"] #[inline(always)...
use crate::container::Container; use azure_core::incompletevector::IncompleteVector; use azure_core::RequestId; #[derive(Debug, Clone)] pub struct ListContainersResponse { pub incomplete_vector: IncompleteVector<Container>, pub request_id: RequestId, } impl ListContainersResponse { pub fn is_complete(&sel...
extern crate extended_collections; extern crate rand; use extended_collections::radix::RadixMap; use self::rand::{thread_rng, Rng}; use std::iter; use std::vec::Vec; const NUM_OF_OPERATIONS: usize = 100_000; #[test] fn int_test_radix_map() { let mut rng: rand::XorShiftRng = rand::SeedableRng::from_seed([1, 1, 1,...
fn main() { let mut s = String::new(); std::io::stdin().read_line(&mut s).ok(); let v: Vec<i32> = s .trim() .split_whitespace() .map(|e| e.parse().ok().unwrap()) .collect(); let n = v[0]; let m = v[1]; let mut a: Vec<Vec<char>> = Vec::new(); for _i in 0..n { ...
#[doc = "Register `EECR3` reader"] pub type R = crate::R<EECR3_SPEC>; #[doc = "Register `EECR3` writer"] pub type W = crate::W<EECR3_SPEC>; #[doc = "Field `EE6F` reader - EE6F"] pub type EE6F_R = crate::FieldReader<EE6F_A>; #[doc = "EE6F\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[repr(u8)] pu...
#[doc = r" Register block"] #[repr(C)] pub struct RegisterBlock { #[doc = "0x00 - Pad Configuration Register A (Pads 0-3)"] pub padrega: PADREGA, #[doc = "0x04 - Pad Configuration Register B (Pads 4-7)"] pub padregb: PADREGB, #[doc = "0x08 - Pad Configuration Register C (Pads 8-11)"] pub padregc...
// 10 and 100 don't change the sum. // 2, 20 doubles the first digit // 3, 30 triples the first digit // 4, 40 quadruples ... // combinatorics is lost on me... use num::{BigUint}; fn main() { let result = factorial(BigUint::from(100_u32)); let sum: u32 = result .to_string() .chars() .m...
pub(crate) use super::prelude; pub(crate) mod base; pub(crate) mod helper; pub(crate) mod session;
//! A camera for viewing our world. use crate::{ ray::Ray, util::deg_to_rad, vec3, vec3::{Axis::*, Vec3}, }; use rand::Rng; /// A simple axis-aligned camera. #[derive(Debug, Copy, Clone)] pub struct Camera { /// The lower-left corner of our "screen", in relation the the camera's /// `origin`. ...
extern crate serde_json; use std::env; use std::fs; use std::io::prelude::*; use std::io::BufReader; use std::process::Command; use self::serde_json::{Error, Value}; pub fn run(tx_name: &str) -> String { let current_dir = env::current_dir().unwrap(); let current_dir = current_dir.as_path(); let input_fil...
use std::fs::File; use std::io::ErrorKind; use std::io; use std::io::Read; use std::fs; fn main() { println!("{}", read_username_shortest("hello.txt").expect("Failed to read username")); } fn call_panic() { panic!("Crash and burn!"); } fn panic_index() -> i32 { let v = vec![1, 2, 3]; v[42] } fn ope...
use socketcan_isotp::{self, IsoTpSocket, StandardId}; fn main() -> Result<(), socketcan_isotp::Error> { let mut tp_socket = IsoTpSocket::open( "vcan0", StandardId::new(0x123).expect("Invalid rx id"), StandardId::new(0x321).expect("Invalid tx id"), )?; let buffer = tp_socket.read()?...
use pattern::{file_name_only, strip_grep_filepath, tag_name_only}; /// A tuple of match text piece (matching_text, offset_of_matching_text). pub type FuzzyText<'a> = (&'a str, usize); #[derive(Debug, Clone, Copy)] pub enum MatchType { Full, TagName, FileName, IgnoreFilePath, } impl std::str::FromStr ...
// Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>,...
pub fn abbreviate(phrase: &str) -> String { let mut result = String::new(); if phrase.len() == 0 { return result; } let s = phrase.as_bytes(); for (i, &ch) in s.iter().enumerate() { if i == 0 { result.push(ch as char); } else if s[i - 1] == b' ' || s[i - 1] == b...
/* these are some handy x86 functions that do important, manipulat-y hardware-y things */ pub unsafe fn outportb(port: u16, val: u8) { asm!("outb %al, %dx" : : "{dx}"(port), "{al}"(val)); } pub unsafe fn inportb(port: u16) -> u8 { let ret: u8; asm!("inb %dx, %al" : "={ax}"(ret): "{dx}"(port)); ret }
#[doc = "RCB control 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/#read--modify-...
#![no_std] #![allow(clippy::unused_unit)] extern crate alloc; use rand_core::{CryptoRng, RngCore}; use wasm_bindgen::prelude::*; use alloc::{boxed::Box, string::ToString}; use pwbox::{pure::PureCrypto, ErasedPwBox, Eraser, Suite}; // Binding to a JavaScript CSPRNG. #[wasm_bindgen] extern "C" { pub type Rng; ...
#![feature(core_intrinsics, custom_derive, plugin, custom_attribute, box_syntax)] #![allow(unused_variables, unused_imports)] #[macro_use] extern crate serde_derive; extern crate serde_json; extern crate serde; extern crate time; #[macro_use] extern crate itertools; extern crate permutohedron; pub mod traffic_protoco...
#![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)] NetworkFunctions_Get(#[from] network_...
use super::build::BuildSystem; use super::build::BuildSystemBase; use super::file; use fs::File; use std::env; use std::fs; use std::io::Write; use std::path::PathBuf; #[derive(Debug, Clone)] pub struct BluePrint { /// The base build system struct pub build_system: BuildSystemBase, } impl BluePrint { pub ...
use std::collections::HashMap; // think I should've used a heap here struct Vertex<'a> { id: u64, edges: Vec<Edge<'a>>, } struct Edge<'a> { first: &'a Vertex<'a>, second: &'a Vertex<'a>, } struct AdjacencyList<'a> { vertices: HashMap<u64, &'a Vertex<'a>>, //Vec<Vertex<'a>>, edges: Vec<Edge<'a>>, } ...
use ::errors::*; use config::Config; pub fn load_config_from_file(path: &str) -> Result<Config> { use std::fs::File; use std::io::Read; let mut file = File::open(path).chain_err(|| "Failed to open config file")?; let mut contents = String::new(); file.read_to_string(&mut contents).chain_err(|| "F...
use libc::c_int; use H5public::herr_t; extern "C" { pub fn H5PLset_loading_state(plugin_flags: c_int) -> herr_t; pub fn H5PLget_loading_state(plugin_flags: *mut c_int) -> herr_t; }
use amethyst::ecs::{storage::NullStorage, Component}; #[derive(Component, Default)] #[storage(NullStorage)] pub struct Selected; #[derive(Component, Default)] #[storage(NullStorage)] pub struct Controllable;
use crate::gui::ImCgVec2; use cgmath::num_traits::zero; use cgmath::Vector2; use imgui_inspect_derive::*; use serde::{Deserialize, Serialize}; use specs::{Component, VecStorage}; #[derive(Component, Debug, Inspect, Clone, Serialize, Deserialize)] #[storage(VecStorage)] pub struct Kinematics { #[inspect(proxy_type ...
use anyhow::Result; use sightglass_analysis::{effect_size, summarize}; use sightglass_data::Format; use std::{ fs::File, io::{self, BufReader}, }; use structopt::StructOpt; /// Calculate the effect size (and associated confidence interval) between the /// results for two different engines. #[derive(Debug, Stru...
use super::api::{Project, Sample}; use console::style; use failure::bail; use number_prefix::NumberPrefix; use std::io::{Read, Write}; use tabwriter::TabWriter; /// Return the top 5 closest matching hits for a given query /// /// derived from clap/src/parse/features/suggestions.rs pub fn did_you_mean<T, I>(v: &str, po...
use proconio::{fastout, input}; const MOD: i64 = 1_000_000_000 + 7; #[fastout] fn main() { input! { n: i64, }; let ans = mpow(10, n as u64) - mpow(9, n as u64) - mpow(9, n as u64) + mpow(8, n as u64); let ans = ans % MOD; let ans = (ans + MOD) % MOD; println!("{}", ans); } fn mpow(n: ...
use franz::Client; #[tokio::test] async fn client_simple() { let mut client = Client::connect("127.0.0.1:9092").await.unwrap(); client.send_api_version_request().await.unwrap(); client.wip_recv().await.unwrap(); }
mod artifact; mod compiler; mod console; mod diagnostic; mod directory; mod extensions; mod hasher; mod processor; mod refs; mod result; mod rule; mod scope; mod store; pub mod system; mod utils; mod variable; pub use refs::*; pub use result::*; pub use utils::*; pub use rquickjs as qjs; pub use std::time::{Duration,...