text
stringlengths
8
4.13M
use std::collections::VecDeque; use std::iter::Iterator; pub type Price = i32; pub type Size = u32; pub type Meta = u128; #[derive(Debug)] pub struct Basket { inner: Vec<(Price, VecDeque<(Size, Meta)>)>, } impl Basket { pub fn new() -> Basket { Basket { inner: Vec::new() } } pub fn put(&mut ...
use core::cmp::{max, min}; use crate::memory::{MemMan, MEMMAN_ADDR}; use crate::mt::{TaskManager, TASK_MANAGER_ADDR}; use crate::vga::{Color, SCREEN_HEIGHT, SCREEN_WIDTH, VRAM_ADDR}; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum SheetFlag { AVAILABLE, USED, } #[derive(Debug, Clone, Copy, PartialEq, E...
use ab_glyph::{Font, FontRef, PxScale, ScaleFont}; use once_cell::sync::Lazy; use unicode_normalization::UnicodeNormalization; static FONT: Lazy<FontRef<'static>> = Lazy::new(|| { let font_data: &[u8] = include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/resx/Verdana.ttf")); FontRef::try_from_slice(font_data)...
use std::collections::HashMap; use std::path::{Path, PathBuf}; use std::time::{Duration, SystemTime}; use std::{fs, io}; use rand::{self, seq::SliceRandom}; use uuid::Uuid; #[derive(Default)] pub struct FileLister { files: Vec<PathBuf>, lock_acq: HashMap<PathBuf, SystemTime>, security: HashMap<PathBuf, St...
// Copyright 2012-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-MI...
#![no_std] extern crate x86_64; pub unsafe fn exit_qemu() { debug!("Closing VM"); use x86_64::instructions::port::Port; let mut port = Port::<u32>::new(0xf4); port.write(0); }
//! This crate provides the feature of filtering a stream of lines. //! //! Given a stream of lines: //! //! 1. apply the matcher algorithm on each of them. //! 2. sort the all lines with a match result. //! 3. print the top rated filtered lines to stdout. mod dynamic; mod source; use anyhow::Result; use rayon::prelu...
use crate::components::Position; pub trait IsDrawable { fn render_info(&self) -> (usize, &Position); fn set_texture_index(&mut self, texture_index: usize); } pub trait NeedsFood { fn eat(&mut self, food: f32) -> f32; fn burn_calories(&mut self, burn: f32); fn hunger_index(&self) -> f32; } pub tra...
use std::time::{Duration, Instant}; use glium::Display; use crate::canvas::{CanvasError, CanvasObject, DrawingContext}; use crate::geometry::{CanvasSpace, Line}; use crate::graphics::dyn_vertex_buffer::DynVertexBuffer; use crate::graphics::primitives::{Color, Line as GLLine}; pub struct DebugGeometry { line_buff...
#[macro_use] extern crate nom; use nom::{line_ending,space,digit}; use nom::types::CompleteStr; const INPUT: &'static str = include_str!("day3.txt"); named!(integer<CompleteStr, u64>, map!(digit, |s| s.parse::<u64>().unwrap()) ); named!(triangle<CompleteStr, (u64, u64, u64)>, do_parse!( space >> ...
use std::collections::{HashSet, VecDeque}; use crate::solutions::Solution; pub struct Day13 {} impl Solution for Day13 { fn part1(&self, input: String) { let fav_num = input.parse().unwrap(); println!("{}", bfs(fav_num)); } fn part2(&self, input: String) { let fav_num = input.par...
/* Copyright (c) 2023 Uber Technologies, Inc. <p>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 <p>http://www.apache.org/licenses/LICENSE-2.0 <p>Unless required by applicable law or agreed to ...
use coinbase_pro_rs::{Private, Sync, SANDBOX_URL}; static KEY: &str = "1d0dc0f7b4e808d430b95d8fed7df3ea"; static SECRET: &str = "dTUic8DZPqkS77vxhJFEX5IBr13FcFHTzWYOARgT9kDWGdN03uvxBbH/hVy8f4O5RDmuf+9wNpEfhYhw2FCWyA=="; static PASSPHRASE: &str = "sandbox"; fn main() { let client: Private<Sync> = Private::new(...
use std::fmt; #[derive(Debug)] struct MinMax(i64,i64); impl fmt::Display for MinMax{ fn fmt(&self,f: &mut fmt::Formatter)-> fmt::Result{ write!(f,"({},{})",self.0,self.1) } } fn main() { let minmax =MinMax(0,14); println!("Display: {}",minmax); println!("Debug: {:?}",minmax); }
mod binary_tree; mod macros; pub use crate::binary_tree::{BinaryNodeMut, BinaryNodeRef, BinaryTree};
//! Validate input data against schemas. //! //! This module contains logic related to *validation*, the process of taking a //! piece of input data (called an "instance") and checking if it's valid //! according to a schema. //! //! See the docs for [`Validator`](struct.Validator.html) for more. use crate::schema::Sc...
mod custom_distribution; pub use custom_distribution::CustomDistribution; pub type FitFunc<T> = Box<dyn Fn(&T) -> f64>;
/* * @author :: Preston Wang-Stosur-Bassett <p.wanstobas@gmail.com> * @date :: October 8, 2020 * @description :: Return HSK Level for Simplified Chinese Characters */ //! ### About //! Return HSK Level for Simplified Chinese Characters //! //! ### Usage //! ```rust //! extern crate hsk; //! //! use hsk::Hsk; //...
#[doc = "Register `MACSPI2R` reader"] pub type R = crate::R<MACSPI2R_SPEC>; #[doc = "Register `MACSPI2R` writer"] pub type W = crate::W<MACSPI2R_SPEC>; #[doc = "Field `SPI2` reader - Source Port Identity 2 This field indicates bits \\[79:64\\] of sourcePortIdentity of PTP node."] pub type SPI2_R = crate::FieldReader<u1...
// Copyright 2017 Dmitry Tantsur <divius.inside@gmail.com> // // 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 ap...
use dotenv::dotenv; use std::env; use rocket::config::ConfigError; pub struct AuthSettings { client_id: String, client_secret: String, redirect_uri: String, auth0_domain: String, } impl AuthSettings { pub fn from_env () -> Result<AuthSettings, String> { dotenv().ok(); let client_i...
extern crate cribbage; use std::sync::mpsc; use std::{thread, time}; // TODO Handle all the unwraps and do proper error handling and all #[derive(PartialEq, Debug)] enum GciState { // The state given to a client that has just connected and who has yet to send the greeting Connecting, // Any clients that ...
extern crate json_tools; use json_tools::{Lexer, Token, Span, TokenType, BufferType, Buffer}; #[test] fn string_value() { let src = r#"{ "face": "😂" }"#; let mut it = Lexer::new(src.bytes(), BufferType::Span); assert_eq!(it.next(), Some(Token { kind: TokenType::CurlyOpen, ...
use compression::BlockDecoder; use compression::COMPRESSION_BLOCK_SIZE; use compression::compressed_block_size; use directory::{ReadOnlySource, SourceRead}; /// Reads a stream of compressed ints. /// /// Tantivy uses `CompressedIntStream` to read /// the position file. /// The `.skip(...)` makes it possible to avoid /...
mod bounce; mod explode; mod missile; mod plane; mod player_missile; mod register; pub use self::register::register; pub use self::bounce::BounceSystem; pub use self::explode::MissileExplodeSystem; pub use self::missile::MissileTerrainCollisionSystem; pub use self::plane::PlaneCollisionSystem; pub use self::player_m...
// use std::env; use std::io; fn main() { // pre-defined variables let secret = "Password1"; let mut str = String::from(secret); str.push_str("\n"); // read from command line // let args: Vec<_> = env::args().collect(); // let max_guess: i32 = args[1].parse().unwrap(); // start while loop let mut x = 1; // w...
use crate::Chip8; impl std::fmt::Debug for Chip8 { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { writeln!( f, "Chip8 {{ \tV Registers: {registers:02x?} \tIndex Register: {index_register:#06x?} \tMemory val at Index Register: {mem_at_idx:#04x?} \tProgram Counte...
#![deny(unreachable_patterns)] #![feature(const_fn)] use bevy::prelude::*; use crate::game_speed::{GameSpeed, GameSpeedRequest}; use crate::physics::ContactType; use crate::teams::*; pub mod combat; pub mod game_speed; pub mod physics; pub mod teams; pub mod ui; pub mod units; pub mod user_input; const WALKING_SPEED...
#![allow(unused)] extern crate bytes; pub extern crate conduit_proxy_controller_grpc; extern crate conduit_proxy; pub extern crate convert; extern crate futures; extern crate h2; pub extern crate http; extern crate hyper; extern crate prost; extern crate tokio_connect; extern crate tokio_core; pub extern crate tokio_i...
fn main() { let number: usize = 50; //println!("The {}th fibonacci number is: {}\n - Calculated using a recursive algorithm.", number, recursive_fibonacci(number)); println!("The {}th fibonacci number is: {}\n - Calculated using a iterative algorithm.", number, iterative_fibonacci(number)); } fn recursive...
use super::*; use dispatch::Builder; pub fn register<'a, 'b>(disp: Builder<'a, 'b>) -> Builder<'a, 'b> { disp.with::<PlaneCollisionSystem>() .with::<MissileTerrainCollisionSystem>() .with::<PlayerMissileCollisionSystem>() .with::<BounceSystem>() .with::<MissileExplodeSystem>() }
use rosu_pp::{Beatmap, BeatmapExt as rosu_v2BeatmapExt, DifficultyAttributes, ScoreState}; use rosu_v2::model::GameMods; use crate::{ error::PpError, util::{osu::prepare_beatmap_file, ScoreExt}, core::Context, }; enum ScoreKind<'s> { Mods(GameMods), Score(&'s dyn ScoreExt), } impl ScoreKind<'_> { ...
fn convert(n: i64, k: i64) -> String { let mut s = "".to_string(); for i in 1..(k + 1) { s += &(n * i).to_string(); } s } fn check(s: String) -> bool { if s.len() != 9 { return false; } for x in vec!['1', '2', '3', '4', '5', '6', '7', '8', '9'] { let mut flag = fal...
// --- paritytech --- use pallet_multisig::Config; // --- darwinia-network --- use crate::{weights::pallet_multisig::WeightInfo, *}; frame_support::parameter_types! { // One storage item; key size is 32; value is size 4+4+16+32 bytes = 56 bytes. pub const DepositBase: Balance = constants::deposit(1, 88); // Additio...
use core::ops::RangeBounds; use ssd1963::Display; pub trait FullscreenVerticalScroller<Disp> where Disp: Display, { fn scroll_area<X, Y>(&mut self, disp: &mut Disp, y: Y, vert_by: i16) -> Result<(), Disp::Error> where X: RangeBounds<u16>, Y: RangeBounds<u16>; }
use std::fs; use std::path::Path; use std::io; use self::scanning::scan_tokens; use self::parser::Parser; use self::interpreter::LoxValue; use self::interpreter::Interpreter; mod n_peekable; mod scanning; mod expr; mod parser; mod interpreter; mod native_functions; pub fn run_file(path: &Path) { let file_content...
use serde::{Deserialize, Serialize}; use serde_json::Value; use std::io::Cursor; use svm_types::{Account, SpawnAccount}; use super::call::EncodedOrDecodedCalldata; use super::inputdata::DecodedInputData; use super::serde_types::{EncodedData, TemplateAddrWrapper}; use super::{JsonError, JsonSerdeUtils}; use crate::sp...
use self::aes::{HarmonyAes, KeySize}; use crate::{api::secret, bail}; use error::{E2EEError, E2EEResult, FanoutError, ImpureError}; use std::{collections::HashMap, convert::TryInto}; use async_trait::async_trait; use hmac::{Hmac, Mac, NewMac}; use rand::rngs::OsRng; use rsa::{ Hash, PaddingScheme, PrivateKeyPemEn...
//! CramJam documentation of python exported functions for (de)compression of bytes //! //! The API follows `<<compression algorithm>>_compress` and `<<compression algorithm>>_decompress` //! //! Python Example: //! //! ```python //! data = b'some bytes here' //! compressed = cramjam.snappy_compress(data) //! decompres...
// Copyright 2018-2019 Mozilla // // 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 in writing, sof...
use super::*; #[derive(Clone, Debug, PartialEq, PartialOrd)] pub enum ProteinFilter { Reverse, Spectra(usize), ExcludeMatch(String), } /// A collection of information about a set of ratios /// INVARIANT: The sum of twenties + liganded + not_liganded must equal /// the total number of quantified ratios #[d...
#[doc = "Register `I2SPR` reader"] pub type R = crate::R<I2SPR_SPEC>; #[doc = "Register `I2SPR` writer"] pub type W = crate::W<I2SPR_SPEC>; #[doc = "Field `I2SDIV` reader - I2S Linear prescaler"] pub type I2SDIV_R = crate::FieldReader; #[doc = "Field `I2SDIV` writer - I2S Linear prescaler"] pub type I2SDIV_W<'a, REG, c...
use particle::decay::decay::Decayer; use sack::{SackType, SackStorable, SackBacker, TokenLike}; pub trait Emitter<'a, C1: 'a, C2: 'a, D1: 'a, D2: 'a, B1: 'a, B2: 'a, T1: 'a, T2: 'a> : Decayer<'a, C1, C1, C2, D1, D1, D2, B1, B1, B2, T1, T1, T2> where C1: SackStorable, C2: SackStorable, D1: S...
use actix_web::{ get, middleware, web::{self, Data}, App, HttpRequest, HttpResponse, HttpServer, Responder, }; use serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize)] struct Health { status: String, } #[get("/health")] pub async fn health(_: HttpRequest) -> impl Responder { HttpRes...
use std::{ io, pin::Pin, task::{Context, Poll}, }; use pin_project::pin_project; use crate::thread_guard::ThreadGuard; #[pin_project] pub struct Compat<T> { #[pin] inner: ThreadGuard<T>, } impl<T> Compat<T> { pub fn new(inner: T) -> Self { Self { inner: ThreadGuard::new(i...
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 4.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! Macros for `uniffi`. //! //! Currently this is just for easily generating integration tests, but maybe //! we'...
use std::net::SocketAddr; use std::path::Path; use hydroflow::hydroflow_syntax; use hydroflow::scheduled::graph::Hydroflow; use hydroflow::util::{UdpSink, UdpStream}; use crate::helpers::decide; use crate::protocol::{CoordMsg, MsgType, SubordResponse}; use crate::{Addresses, GraphType}; pub(crate) async fn run_subor...
#[derive(Copy, Clone)] pub enum FieldType { Water, Food, Land, Dead, MyAnt, EnemyAnt } struct UpdateCommand { update_type: String, x: i64, y: i64, owner: Option<i64> } #[derive(Copy, Clone)] pub struct Tile { visible: bool, field_type: FieldType...
//! Serial data transfer support. use crate::io; /// A peripheral that can perform serial read operations. pub trait SerialRead: io::Read {} /// A peripheral that can perform serial write operations. pub trait SerialWrite: io::Write {}
use super::{Conn, Core}; use crate::error::Error; use futures::Stream; use std::fmt::Debug; use xactor::Addr; /// Represents a connection listener. /// /// Produces a stream of `Conn`s. /// /// Provided by core /// /// ? Handle<...> #[async_trait::async_trait] pub trait Listener<C: Core>: Debug + Sized where Self:...
#![feature(alloc)] use std::hash::Hash; use std::collections::HashMap; use std::cell::RefCell; use std::rc::Rc; use std::rc::Weak; /// Struct that represents the [Disjoint-Set](http://en.wikipedia.org/wiki/Disjoint-set_data_structure) data structure. #[derive(Clone)] pub struct DisjointSet<T> { elements: HashMap...
#![allow(dead_code, unused_imports, unused_variables)] use std::collections::*; const DATA: &'static str = include_str!("../../../data/XX"); fn main() { let input = read_input(); println!("{:?}", input); // println!("Part 1: {:?}", process(&grid, carts.clone(), true)); // println!("Part 2: {:?}", p...
//! Derive standardized scancodes based on per platform definitions. //! //! Linux definitions: <https://github.com/torvalds/linux/blob/master/include/uapi/linux/input-event-codes.h> //! Windows definitions: <https://download.microsoft.com/download/1/6/1/161ba512-40e2-4cc9-843a-923143f3456c/scancode.doc> //! Macos defi...
//! # taquin //! //! Command line utility to solve fifteen puzzle instances. //! //! --- //! //! Uses BFS. //! #![deny(missing_docs, missing_debug_implementations, missing_copy_implementations, trivial_casts, trivial_numeric_casts, unsafe_code, unstable_features, unused_import_braces, u...
mod shader_utils; mod background_helper; mod sprites_helper; mod particles_helper; mod post_process_effect; use crate::view_models::{SpritesViewModel, LevelViewModel, ParticlesViewModel, PostProcessViewModel, PostProcessEffects}; use image; use cgmath; use web_sys::{WebGlProgram, WebGl2RenderingContext, WebGlTexture,...
/// An export snippet. /// /// # Semantics /// /// These snippets are only exported in the specified format. E.g. there can be an export /// snippet that is only exported in html. /// /// # Syntax /// /// ```text /// @@BACKEND:VALUE@@ /// ``` /// /// `BACKEND` can contain any alpha-numeric character and hyphens. /// //...
use std::fs::read_dir; use std::io::{Error, ErrorKind, Result}; use std::path::{Path, PathBuf}; pub fn read_files_in_dir_sorted<P: AsRef<Path>>(path: P) -> Result<impl Iterator<Item = PathBuf>> { let mut entries = read_dir(path)? .filter_map(|r| r.ok()) .map(|d| d.path()) .filter(|p| p.is_f...
use lexer::Token; #[derive(Debug, PartialEq)] pub enum Error { ExpectedEOF(Token), // Carries illegal token UnexpectedEOF, IntegerParseError, IllegalToken(Token), // Carries illegal token ExpectedToken(Token, Token) // Carries expected, actual }
use crate::{Aggregate, Texture}; /// Container for a scene. pub struct Scene { pub aggregate : Aggregate, pub environment: Texture, }
// Copyright (c) 2017 oic developers // // 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. All files in the project carrying such notice may not be copied, // mo...
fn main() { let hello = "Hello World!"; println!("{}", hello); println!("{}", hello.to_string()); hello .chars() .enumerate() .for_each(|(i, c)| println!("{}:{}", i, c) ); let rev = hello .chars() .into_iter() .rev() .coll...
use std::fmt; use std::process::exit; #[derive(Debug)] pub enum Errcode { ArgumentInvalid(&'static str), NotSupported(u8), ContainerError(u8), SocketError(u8), ChildProcessError(u8), HostnameError(u8), RngError, MountsError(u8), NamespacesError(u8), CapabilitiesError(u8), Sy...
use std::io::{self, Read, ErrorKind}; use std::fs::{self, File}; use std::error::Error; fn main() -> Result<(), Box<dyn Error>> { // open_hello_file(); println!("*******************"); // open_hello2_file(); println!("*******************"); // open_hello3_file(); println!("*******************")...
/* * 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 */ /// UsageMetricCategory : Contains the metric category. /// Contains the metric category. #[derive(Clon...
#![feature(specialization)] pub mod error; mod queries; use crate::error::SourceError; use hashbrown::HashMap; use std::{fs::read_to_string, path::Path, sync::Arc}; use valis_ds_macros::DebugWith; pub const SOURCE_EXTENSION: &str = "va"; pub const SOURCE_GLOB: &str = "*.va"; #[salsa::query_group(SourceStorage)] pub...
#[doc = "Reader of register STATUS"] pub type R = crate::R<u32, super::STATUS>; #[doc = "Writer for register STATUS"] pub type W = crate::W<u32, super::STATUS>; #[doc = "Register STATUS `reset()`'s with value 0"] impl crate::ResetValue for super::STATUS { type Type = u32; #[inline(always)] fn reset_value() ...
use super::*; use net::{IoEvent, PollEventFlags}; use util::ring_buf::*; // TODO: Add F_SETPIPE_SZ in fcntl to dynamically change the size of pipe // to improve memory efficiency. This value is got from /proc/sys/fs/pipe-max-size on linux. pub const PIPE_BUF_SIZE: usize = 1024 * 1024; pub fn pipe(flags: StatusFlags) ...
#[doc = "Reader of register RSLV_LIST_ENABLE[%s]"] pub type R = crate::R<u32, super::RSLV_LIST_ENABLE>; #[doc = "Writer for register RSLV_LIST_ENABLE[%s]"] pub type W = crate::W<u32, super::RSLV_LIST_ENABLE>; #[doc = "Register RSLV_LIST_ENABLE[%s] `reset()`'s with value 0"] impl crate::ResetValue for super::RSLV_LIST_E...
#![deny(clippy::all)] use config::*; //use http::response::*; use openssl::asn1::Asn1Time; use openssl::hash::MessageDigest; use openssl::pkey::PKey; use openssl::rsa::Rsa; use std::net::{IpAddr, SocketAddr}; use warp::Filter; #[cfg(unix)] #[tokio::main] async fn main() { let mut settings = config::Config::defau...
//#![deny(warnings)] //#![allow(unused)] //#![feature(conservative_impl_trait)] #![cfg_attr(feature="clippy", feature(plugin))] #![cfg_attr(feature="clippy", plugin(clippy))] #[macro_use] extern crate log; #[macro_use] extern crate serde_derive; extern crate hyper; extern crate serde_json; extern crate tokio_core; ext...
use regex::Regex; use grex::{Feature, RegExpBuilder}; #[rustler::nif] fn build_expression( query: String, digits: bool, spaces: bool, words: bool, repetitions: bool, ignore_case: bool, capture_groups: bool, verbose: bool, escape: bool ) -> String { let lines: Vec<&str> = query....
use rand::Rng; pub fn build_random_array(size: u8, max_value: u8) -> Vec<u8> { let mut rng = rand::thread_rng(); let mut values = Vec::new(); for _i in 0..size { values.push(rng.gen_range(0, max_value)); } values }
//! Terminal implementation for all non-Redox operating systems. use crate::{ terminal::{ event::{Event, EventKind, KeyEvent, KeyModifier, MouseButton, MouseEvent}, Size, Terminal, SIZE, }, util::{Color, Point}, }; use crossterm::{cursor, event, style, terminal, QueueableCommand}; impl Ter...
extern crate rand; extern crate minifb; mod ops; mod screen; use std::{ io, thread, time, fs::File, io::prelude::*, }; use rand::{Rng, rngs::ThreadRng}; use minifb::{Key, WindowOptions, Window, Scale, KeyRepeat}; use screen::{Point, Buffer, Screen}; const MEMORY: usize = 4096; const WIDTH: usize = 64; co...
use itertools::Itertools; use std::iter; #[aoc_generator(day04)] pub fn day04_gen(input: &str) -> (u32, u32) { input .split('-') .take(2) .map(|n| n.parse().unwrap()) .collect_tuple() .unwrap() } #[derive(Debug, Clone)] struct Digits { n: u32, divisor: u32, } impl ...
pub use self::arch::*; #[cfg(target_arch = "x86")] #[path="x86/gdt.rs"] mod arch; #[cfg(target_arch = "x86_64")] #[path="x86_64/gdt.rs"] mod arch;
//! Quaternion use super::common::{Quat, Vec4, Vec3, Mat3, random_f32, EPSILON, PI}; use super::{vec3, vec4, mat3}; /// Creates a new identity quat. /// /// [glMatrix Documentation](http://glmatrix.net/docs/module-quat.html) pub fn create() -> Quat { let mut out: Quat = [0_f32; 4]; out[3] = 1.; out } ...
pub async fn initialise_tables() { let conn = super::get_connection().await; info!("Initialising tables"); conn.client .batch_execute( " CREATE TABLE IF NOT EXISTS permission_roles ( server_id bigint NOT NULL, role_id bigint NOT NULL, permission_level smallint NOT NULL, P...
use pcap::*; fn main() { let name = pcap_lookupdev().unwrap(); match pcap_open_live(&name, 100, 0, 1000) { Ok(handle) => { let datalink = pcap_datalink(&handle); let name = pcap_datalink_val_to_name(datalink).unwrap(); let val = pcap_datalink_name_to_val(&name); ...
use crate::geometry::{Displacement, Point, Rectangle, Size, TransformMatrix}; use crate::window::Window; use crate::window_management_policy::WmPolicyManager; use crate::{ event::{Event, EventOnce}, window_manager::WindowManager, }; use std::cell::RefCell; use std::pin::Pin; use std::ptr; use std::rc::{Rc, Weak}; u...
//! # Unstorable //! This crate provides a type that is meant to be used with config that can be updated. The Unstorable type //! is meant to only be referenced on the stack and made very hard to store in any struct or on the heap. It is //! an unnamed type which makes it impossible to declare as part of a struct witho...
use byteorder::{BigEndian, LittleEndian}; use crate::{ Endianness, errors::*, pcap::Packet, pcap::PcapHeader }; /// Parser for a Pcap formated stream. /// /// # Examples /// /// ```no_run /// use pcap_file::pcap::PcapParser; /// use pcap_file::PcapError; /// /// let pcap = vec![0_u8; 0]; /// let mut ...
extern crate convey; extern crate failure; extern crate rand; use convey::{human, json}; use rand::distributions::Distribution; use rand::distributions::Range; use rand::thread_rng; use std::thread; use std::time::Duration; fn main() -> Result<(), failure::Error> { let out = convey::new() .add_target(json...
mod file; use file::Fileinfo; use std::io::*; fn main() { let mut buf = String::new(); stdin().read_line(&mut buf).ok().unwrap(); match Fileinfo::new( String::from(buf.trim()) ) { Ok(info) => { println!("{}", info) }, Err(e) => println!("{}", e) } }
//! Tests SDRAM pin constraints apply correctly mod dummy_pins; use dummy_pins::*; use stm32_fmc::*; /// Dummy FmcPeripheral implementation for testing struct DummyFMC; unsafe impl FmcPeripheral for DummyFMC { const REGISTERS: *const () = 0 as *const (); fn enable(&mut self) {} fn source_clock_hz(&self) ...
use crossterm::Result; mod editor; use editor::Editor; mod line; mod modes; fn main() -> Result<()> { Editor::init() }
use std::path::PathBuf; pub struct Pathfinder { pub config_dir: PathBuf, pub private_mix_key: PathBuf, pub public_mix_key: PathBuf, } impl Pathfinder { pub fn new(id: String) -> Pathfinder { let os_config_dir = dirs::config_dir().unwrap(); // grabs the OS default config dir let config_...
use std::panic; fn main() { println!("add!"); let nums = [2,3,5]; let total = sum(&nums); println!("{:?}", total); } fn sum(arrays: &[u32]) -> Option<u32> { let result = panic::catch_unwind(|| { let mut total = 0; for a in arrays.iter() { total += a; } t...
use scanlex::{Scanner,Token}; use errors::*; use types::*; // when we parse dates, there's often a bit of time parsed.. #[derive(Clone,Copy,Debug)] enum TimeKind { Formal, Informal, AmPm(bool), Unknown, } pub struct DateParser<'a> { s: Scanner<'a>, direct: Direction, maybe_time: Option<(u3...
use super::{content::ContentSize, SvgPath}; use crate::badge::BadgeContentType; use crate::{Color, Icon}; use maud::PreEscaped; use maud::{html, Markup}; fn content_template<'a>( height: usize, font_size: f32, x_offset: usize, icon: Option<(&'a Icon<'a>, &'a Color)>, icon_width: usize, color...
use rand::Rng; use regex::Regex; use std::fmt::{Display, Formatter}; use std::num::ParseIntError; use twilight_model::application::interaction::application_command::CommandDataOption; use twilight_model::application::interaction::ApplicationCommand; pub struct Roll { die: u16, count: u16, modifier: u16, ...
use std::cell::RefCell; use std::rc::Rc; use super::super::{Env, InterpreterError}; use super::super::super::Expr; pub fn print(args: &[Expr], _: Rc<RefCell<Env>>) -> Result<Expr, InterpreterError> { let all_strs = args.iter().all(|expr| { if let &Expr::String(_) = expr { true } else { ...
#[doc = "Register `FGCOLR` reader"] pub type R = crate::R<FGCOLR_SPEC>; #[doc = "Register `FGCOLR` writer"] pub type W = crate::W<FGCOLR_SPEC>; #[doc = "Field `BLUE` reader - Blue Value"] pub type BLUE_R = crate::FieldReader; #[doc = "Field `BLUE` writer - Blue Value"] pub type BLUE_W<'a, REG, const O: u8> = crate::Fie...
use crate::CliError; use log::trace; use nu_engine::eval_block; use nu_parser::{lex, parse, trim_quotes, Token, TokenContents}; use nu_protocol::engine::StateWorkingSet; use nu_protocol::{ ast::Call, engine::{EngineState, Stack}, PipelineData, ShellError, Span, Value, }; #[cfg(windows)] use nu_utils::enable...
#[doc = "Reader of register RCC_MP_AHB4LPENSETR"] pub type R = crate::R<u32, super::RCC_MP_AHB4LPENSETR>; #[doc = "Writer for register RCC_MP_AHB4LPENSETR"] pub type W = crate::W<u32, super::RCC_MP_AHB4LPENSETR>; #[doc = "Register RCC_MP_AHB4LPENSETR `reset()`'s with value 0x07ff"] impl crate::ResetValue for super::RCC...
use std::error::Error; use std::str; use std::time::Instant; use log::debug; use rusqlite::types::ValueRef; use rusqlite::{CachedStatement, Connection, Result}; use crate::db::utils::{escape_fields, escape_table, repeat_vars}; mod functions; pub mod utils; pub struct Db { pub connection: Connection, } pub type...
use sqltypes::*; pub const SQL_SUCCESS: SQLRETURN = 0;
// This crate implements RSA primitives from PKCS #1 v2.2, as specified in RFC8017: https://datatracker.ietf.org/doc/html/rfc8017 // Secret keys are represented in the representation described in section 3.2 of https://datatracker.ietf.org/doc/html/rfc8017#section-3.2 // Note that the RSA primitives return a MessageToo...
{ "id": "4793c4ef-b96e-428e-930c-0c007c72dd0b", "$type": "NestingPartResource", "Part": { "$type": "ResourcePart" } }
use assert_cmd::prelude::{CommandCargoExt, OutputAssertExt}; use predicates::{ prelude::PredicateBooleanExt, str::{contains, ends_with, starts_with}, }; use std::{error::Error, process::Command}; #[test] fn test_toplevel_1k_counts() -> Result<(), Box<dyn Error>> { let test_file = "tests/data/toplevel-1k.tx...