text
stringlengths
8
4.13M
use std::fs::File; use std::io::Read; use crate::color; use crate::flag; use crate::setting; use crate::hexdump::hexdump; pub fn run(path: &str, flags: flag::Flags, params: Option<setting::Params>) { let mut f = File::open(path).expect("File open failed"); let mut contents = String::new(); f.read_to_stri...
use std::ops::Range; use std::iter::Iterator; use logos::{self, Logos}; #[derive(Logos, Debug, PartialEq, Clone, Copy)] pub enum Token { #[end] End, #[error] Error, #[token = "!"] Exclam, #[regex = "[a-zA-Z_][a-zA-Z_0-9]*"] Text, } #[derive(Debug)] pub struct TokenData<'a> { tokty: Token...
use crate::controls::ControlHandle; use crate::win32::window::bind_raw_event_handler_inner; use crate::win32::window_helper as wh; use crate::NwgError; use winapi::shared::windef::{HWND}; use std::rc::Rc; use std::cell::RefCell; use std::ptr; /// A control item in a DynLayout #[derive(Debug)] pub struct DynLayoutItem...
use std::net::TcpStream; use std::io::{Read, Write}; pub fn handle_response(mut stream: &TcpStream) { let mut buf = [0u8; 4096]; match stream.read(&mut buf) { Ok(_) => println!("Client: Received response \n{}\n\n\n", String::from_utf8_lossy(&buf)), Err(e) => println!("{}", e) }...
extern crate x11; pub mod file; pub mod window;
use crate::{ import::* }; /// Events related to the WebSocket. You can filter like: /// /// ``` /// use ///{ /// ws_stream_wasm :: * , /// pharos :: * , /// wasm_bindgen :: UnwrapThrowExt , /// wasm_bindgen_futures :: futures_...
#![allow(improper_ctypes)] extern crate bytes; extern crate libc; use libc::size_t; use std::os::raw::{c_char, c_int, c_void}; use bytes::Bytes; #[repr(C)] pub struct worker { _unused: [u8; 0], } use worker::Worker as wrk; #[link(name = "binding")] extern "C" { pub fn v8_init(); pub fn get_version() ->...
#![deny(unsafe_code)] #![doc(html_root_url = "https://docs.rs/indexmap/1/")] //! [`IndexMap`] is a hash table where the iteration order of the key-value //! pairs is independent of the hash values of the keys. //! //! [`IndexSet`] is a corresponding hash set using the same implementation and //! with similar properti...
pub struct Solution; impl Solution { pub fn word_break(s: String, word_dict: Vec<String>) -> Vec<String> { let mut next = vec![Vec::new(); s.len()]; for word in &word_dict { let mut i = 0; while let Some(f) = s[i..].find(word) { next[i + f].push(i + f + word....
use arrow_util::assert_batches_eq; use data_types::{StatValues, Statistics}; use mutable_batch::{writer::Writer, MutableBatch}; use schema::Projection; use std::{collections::BTreeMap, num::NonZeroU64}; #[test] fn test_extend_range() { let mut a = MutableBatch::new(); let mut writer = Writer::new(&mut a, 5); ...
use alloc::{sync::Arc, vec, vec::Vec}; use crate::{ nfa::thompson::{self, Error, State, NFA}, util::{ id::{PatternID, StateID}, matchtypes::MultiMatch, sparse_set::SparseSet, }, }; #[derive(Clone, Copy, Debug, Default)] pub struct Config { anchored: Option<bool>, utf8: Opti...
pub mod ledger; pub mod remote_keypair; pub mod remote_wallet;
//! Utopia's Layout widgets pub mod data; pub mod widgets; pub use data::*; pub use widgets::*;
use serde::Serialize; use serde_json::Value; use crate::types::{ Breakpoint, BreakpointEventReason, Capabilities, InvalidatedAreas, LoadedSourceEventReason, Module, ModuleEventReason, OutputEventCategory, OutputEventGroup, ProcessEventStartMethod, Source, StoppedEventReason, ThreadEventReason, }; use std::...
#[doc = "Reader of register MPCBB1_VCTR51"] pub type R = crate::R<u32, super::MPCBB1_VCTR51>; #[doc = "Writer for register MPCBB1_VCTR51"] pub type W = crate::W<u32, super::MPCBB1_VCTR51>; #[doc = "Register MPCBB1_VCTR51 `reset()`'s with value 0xffff_ffff"] impl crate::ResetValue for super::MPCBB1_VCTR51 { type Typ...
use crate::spec::{EncodingType, LinkerFlavor, Target, TargetOptions}; pub fn target() -> Target { let mut base = super::openbsd_base::opts(); base.cpu = "x86-64".into(); base.max_atomic_width = Some(64); base.pre_link_args .entry(LinkerFlavor::Gcc) .or_default() .push("-m64".int...
// auto generated, do not modify. // created: Wed Jan 20 00:44:03 2016 // src-file: /QtNetwork/qudpsocket.h // dst-file: /src/network/qudpsocket.rs // // header block begin => #![feature(libc)] #![feature(core)] #![feature(collections)] extern crate libc; use self::libc::*; // <= header block end // main block begi...
use webp::AnimEncoder; use webp::AnimFrame; use webp::WebPConfig; fn main() { let width = 32u32; let height = 32u32; fn dumy_image(width: u32, height: u32, color: [u8; 4]) -> Vec<u8> { let mut pixels = Vec::with_capacity(width as usize * height as usize * 4); for _ in 0..(width * height) { ...
use std::ops::Index; use std::path::Path; use crate::chunk::BiomeId; use crate::minecraft::data; use gfx_voxel::texture::ColorMap; #[derive(Copy, Clone)] pub struct Biome { pub name: &'static str, pub temperature: f32, pub humidity: f32, pub grass_color: [u8; 3], pub foliage_color: [u8; 3], } pub...
//! Contains the algorithm to determine which chunks may contain "duplicate" primary keys (that is //! where data with the same combination of "tag" columns and timestamp in the InfluxDB DataModel //! have been written in via multiple distinct line protocol writes (and thus are stored in //! separate rows) use crate::...
use std::ptr::eq; use std::thread; use std::time::Duration; use rand; use rand::Rng; use crate::test_closure::CacheClosure; use rust_samples::{mix, PrimaryColor}; use std::borrow::Borrow; use std::fmt::Pointer; fn main() { println!("主线程!"); let simulated_user_specified_value = rand::thread_rng().gen_range(1....
//! Firefly Algorithm. //! //! # Example //! ``` //! extern crate meta_heuristics; //! extern crate rand; //! //! use meta_heuristics::firefly::{self, Firefly}; //! //! #[derive(Clone, Copy)] //! struct Particle { //! pos: f64, //! } //! //! fn eval_func(x: f64) -> f64 { //! 1.0 - ((x - 3.0) * x + 2.0) * x * x ...
use std::fmt::{Debug, Formatter}; use std::time::{SystemTime, UNIX_EPOCH}; use crate::auth::{CodeAuthenticator, TokenResponseData, AUTH_CONTENT_TYPE}; use crate::{Authenticator, Authorized, utils}; use async_trait::async_trait; use log::warn; use reqwest::header::{HeaderMap, HeaderValue, AUTHORIZATION, CONTENT_TYPE, U...
#[doc = "Reader of register ICR"] pub type R = crate::R<u32, super::ICR>; #[doc = "Writer for register ICR"] pub type W = crate::W<u32, super::ICR>; #[doc = "Register ICR `reset()`'s with value 0"] impl crate::ResetValue for super::ICR { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { ...
use crate::libc as c; use crate::unix::errno::Errno; use std::cell::Cell; use std::ptr; use thiserror::Error; macro_rules! error { ($s:expr, $expr:expr) => {{ let result = $expr; if result < 0 { let errno = { pulse::pa_context_errno($s.handle.as_ptr()) }; Err(crate::pulse:...
// 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...
use nalgebra::geometry::{IsometryMatrix3, Perspective3}; use nalgebra::{matrix, Matrix4, Translation3}; use winit::event::VirtualKeyCode; use winit_input_helper::WinitInputHelper; /// OpenGL convention (which nalgebra follows): z goes from [-1, 1]. /// WebGPU uses [0, 1] for z. const OPENGL_TO_WGPU_M: Matrix4<f32> = m...
use nom::{digit, is_space, line_ending, crlf, rest}; use std::{str, slice}; use lookup::{is_token, is_request_uri, is_reason_phrase, is_header_value}; /// A Result of any parsing action. /// /// If the input is invalid, an `IResult::Error` will be returned. /// Note that incomplete data is not considered invalid, /// ...
use itertools::Itertools; use matcher::MatchScope; use serde::{Deserialize, Serialize}; use types::{ClapItem, FuzzyText}; #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, Default)] #[serde(rename_all = "camelCase")] pub struct Scope { pub scope: String, pub scope_kind: String, } #[derive(Serializ...
use crate::prelude::Colour; pub enum StateColour { Hovered, Active, Default, Text, } pub fn state_get_colour(state: StateColour) -> Colour { match state { StateColour::Hovered | StateColour::Active => Colour::DARKGRAY, StateColour::Default => Colour::GRAY, StateColour::Text...
use anyhow::Result; use super::crypto::BothNonces; use super::crypto::MacKey; use super::crypto::MasterKey; use super::crypto::Nonce; use super::crypto::XParam; use super::crypto::Y_H_LEN; use super::SessionCrypto; pub struct Kex { key: MasterKey, decrypt: bool, our_x: XParam, our_nonce: Nonce, ...
//! Нагрузки от колонн и стен при опирании на плиту use crate::sig::rab_e::*; use crate::sig::HasWrite; use nom::{ bytes::complete::take, number::complete::{le_f32, le_u16, le_u8}, IResult, }; use std::fmt; #[derive(Debug)] pub struct LeanOnSlab { load_time: u8, //Тип вертикальной нагрузки на плиту. 0=...
//! Compute the maximal impact of a choice. use ir; use ir::dim::kind; use std::collections::hash_map; use utils::*; /// Indicates if an `Action` can have a negative impact on the execution time. pub fn has_impact(action: ir::Action, fun: &ir::Function) -> bool { let mut action_set = ActionSet::default(); acti...
use crate::mutators::map::MapMutator; use crate::{DefaultMutator, Mutator}; /// The default mutator for strings. It is not very good and will be replaced by a different /// one in the future. /// /// Construct it with: /// ```rust /// use fuzzcheck::DefaultMutator; /// /// let m = String::default_mutator(); /// // or:...
#[doc = "Reader of register TAFCR"] pub type R = crate::R<u32, super::TAFCR>; #[doc = "Writer for register TAFCR"] pub type W = crate::W<u32, super::TAFCR>; #[doc = "Register TAFCR `reset()`'s with value 0"] impl crate::ResetValue for super::TAFCR { type Type = u32; #[inline(always)] fn reset_value() -> Sel...
//! # Delays //! //! Implementations for the [`DelayMs`] and [`DelayUs`] traits //! //! [DelayMs]: embedded_hal::blocking::delay::DelayMs //! [DelayUs]: embedded_hal::blocking::delay::DelayUs use core::convert::From; use cortex_m::peripheral::syst::SystClkSource; use cortex_m::peripheral::SYST; use crate::hal::block...
pub trait VecExtension<T> { fn middle(&self) -> &T; fn looped_get(&self, index: usize, loop_size: usize) -> &T; fn normalized_get(&self, normalized_index: f32) -> &T; fn denormalize_index(&self, normalized_index: f32) -> usize; fn repeat_n(self, n: usize) -> itertools::RepeatN<Vec<T>>; fn normal...
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
use neqo_future::*; use async_std::task; use async_std::io; use futures::prelude::*; use simplelog::*; async fn read_and_print(mut rx: QuicRecvStream) { let mut buf = [0u8; 4096]; while let Ok(len) = rx.read(&mut buf).await { std::print!("{}", std::str::from_utf8(&buf[..len]).unwrap()); } } fn ...
// Copyright 2021 Datafuse Labs. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to ...
/*! # fltk-flex A Rust port of [FL_Flex](https://github.com/osen/FL_Flex), which provides a flexbox widget for fltk-rs. ## Usage ```toml,no_run [dependencies] fltk = "1.2" fltk-flex = "0.2" ``` ## Example ```rust,no_run use fltk::{prelude::*, *}; use fltk_flex::Flex; fn main() { let a = app::App::default().with...
use actix::fut; use actix::prelude::*; use actix::Actor; use actix_web::ws; use failure::{Fallible, ResultExt}; use std::time; use super::client_proto::*; use super::manager; use super::room; use crate::app; // client session pub struct RoomClientSession { client_id: u32, room_id: u32, room_key: String, ...
use super::{ get_byte, get_word, ByteString, CardinalDirection, ColorValue, CounterContext, Counters, Direction, OverlayMode, ParamValue, Thing, CHAR_BYTES, }; use num_traits::FromPrimitive; use std::mem; #[derive(Copy, Clone, Debug, PartialEq)] pub enum Operator { Equals, NotEquals, LessThan, ...
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use failure::{bail, Error, ResultExt}; use fuchsia_async::{self as fasync, DurationExt, Timer}; use fuchsia_framebuffer::{ to_565, Config, Frame, Frame...
use cgmath::{Vector2, Vector3, Vector4}; use buffer::Buffer; use device::Device; use geometry::Geometry; use sys::*; use {BufferType, CurveType, Format, GeometryType}; pub struct LinearCurve<'a> { device: &'a Device, pub(crate) handle: RTCGeometry, pub vertex_buffer: Buffer<'a, Vector4<f32>>, pub inde...
pub mod utils;
use arrow::array::Array; use arrow::compute::{lt_dyn_scalar, nullif}; use datafusion::common::{Result, ScalarValue}; use datafusion::logical_expr::window_state::WindowAggState; use datafusion::logical_expr::PartitionEvaluator; use std::ops::Range; use std::sync::Arc; /// Wrap a PartitionEvaluator in a non-negative fil...
use crate::models::Script; use colored::*; use pad::{Alignment, PadStr}; // TODO: make this a Display impl on Script? pub fn print_script(script: Script) { let script_path = script.path.into_os_string().into_string().unwrap(); if script.functions.is_empty() { println!( "Runsh has found no f...
use procon_reader::ProconReader; fn main() { let stdin = std::io::stdin(); let mut rd = ProconReader::new(stdin.lock()); let a: u32 = rd.get(); let b: u32 = rd.get(); println!("{}", a ^ b); }
use reqwest::blocking::{Client, Response}; use reqwest::header::{HeaderMap, ACCEPT, AUTHORIZATION, USER_AGENT}; use serde::{Deserialize, Serialize}; use std::collections::HashMap; #[derive(Debug, Clone, Serialize, Deserialize)] pub struct TreeObject { path: String, mode: String, #[serde(rename = "type")] ...
use crate::app::Args; use anyhow::Result; use clap::Parser; use maple_core::find_usages::GtagsSearcher; use maple_core::paths::AbsPathBuf; /// Fuzzy filter the current vim buffer given the query. #[derive(Parser, Debug, Clone)] pub struct Gtags { /// Initial query string #[clap(index = 1)] query: String, ...
use std::time::Instant; use indicatif::{ProgressBar, ProgressStyle}; use procfs::{diskstats, DiskStat}; pub struct Panel { amount: u64, processed: u64, bar: ProgressBar, timer: Instant, disk_monitor: DiskMonitor, } impl Panel { pub fn with_amount(amount: u64) -> Self { let bar = Prog...
extern crate serde; mod test_utils; use flexi_logger::LoggerHandle; use hdbconnect_async::HdbResult; use log::*; use std::time::Instant; #[tokio::test] async fn test_012_connect_other_user() -> HdbResult<()> { let mut log_handle = test_utils::init_logger(); let start = Instant::now(); connect_other_user(...
use abstutil::{Counter, Timer}; use geom::HashablePt2D; use map_model::{osm, raw_data, IntersectionType}; use std::collections::{HashMap, HashSet}; pub fn split_up_roads( (mut map, roads, traffic_signals, osm_node_ids): ( raw_data::Map, Vec<raw_data::Road>, HashSet<HashablePt2D>, Ha...
#[test] fn incomplete_inline_table_issue_296() { let err = "native = {".parse::<toml_edit::Document>().unwrap_err(); snapbox::assert_eq( r#"TOML parse error at line 1, column 11 | 1 | native = { | ^ invalid inline table expected `}` "#, err.to_string(), ); } #[test] fn bare_va...
#![cfg(all(test, feature = "moz_central"))] use ressa::Parser; use resw::{write_str::WriteString, Writer}; use std::path::Path; mod common; #[test] fn moz_central() { pretty_env_logger::try_init().ok(); let moz_central_path = Path::new("./moz-central"); if !moz_central_path.exists() { panic!("Pleas...
trait A { fn a(&self) -> String { format!("a") } } trait B: A { fn b(&self) -> String { format!("{}, {}", self.a(), "b") } } pub struct Context; impl A for Context {} impl B for Context {} fn main() { let ctx = Context; ctx.b(); } #[cfg(test)] mod tests { use super::*; ...
use macroquad::prelude::*; use macroquad_tantan_toolbox::water::*; pub struct MyWater { pub water: Water, } impl MyWater { pub fn new( texture_water_raw: Image, render_target_texture: Texture2D, water_size: Vec2, pos: Vec2, ) -> Self { let tex_water_normal = { ...
//! Commands to control the modes. use super::{Modes, Default, CustomLua, write_current_mode}; /// Sets the mode to the default (don't execute custom Lua code). pub fn set_default_mode() { *write_current_mode() = Modes::Default(Default) } /// Sets the mode to the Custom Lua mode (execute any custom Lua code tha...
use crate::ScaledOrthographicProjection; use game_lib::bevy::{ ecs as bevy_ecs, prelude::*, render::{ camera::{Camera, VisibleEntities}, render_graph::base::camera, }, }; #[derive(Bundle)] pub struct ScaledCamera2dBundle { pub camera: Camera, pub orthographic_projection: ScaledO...
#[global_allocator] static ALLOCATOR: jemallocator::Jemalloc = jemallocator::Jemalloc; use std::sync::mpsc::channel; use std::time::{Duration, Instant}; use timely::Configuration; use differential_dataflow::operators::{Consolidate, Count}; use declarative_dataflow::plan::{Aggregate, AggregationFn, Join, Union}; use...
use crate::bounds::Bounds3; use crate::geometry::vector::face_forward; use crate::geometry::vector::Cross; use crate::geometry::vector::Dot; use crate::geometry::vector::Length; use crate::geometry::vector3::Vector3; use crate::interaction::Shading; use crate::interaction::SurfaceInteraction; use crate::math; use crate...
use crate::ctxt::Ctxt; use crate::symbol::*; use proc_macro2::TokenStream; use quote::{format_ident, quote, ToTokens}; use syn::{ self, parse::{Parse, ParseStream}, parse_quote, Data, DataEnum, DataUnion, DeriveInput, Error, Expr, Fields, Ident, Meta::{List, NameValue, Path as MetaPath}, NestedMeta:...
#[cfg(feature = "Wdk_System")] pub mod System;
extern crate ggez; use ggez::*; struct State { dt: std::time::Duration, font: graphics::Font, } impl ggez::event::EventHandler for State { fn update(&mut self, _ctx: &mut Context) -> GameResult<()> { Ok(()) } fn draw(&mut self, ctx: &mut Context) -> GameResult<()> { self.dt += t...
use std::i32; use std::sync::atomic::{AtomicU32, Ordering}; use sys::{futex_wait_bitset, futex_wake_bitset}; pub struct RwFutex2 { futex: AtomicU32, } const M_DEATH: u32 = 0b10100000000010000000001000000000; const F_WRITE_SHOVE: u32 = 0b01000000000000000000000000000000; const M_WRITERS: u32 = 0...
//! @brief Morgan Rust-based BPF program logging use crate::entrypoint::{SolKeyedAccount, SolPubkey}; /// Prints a string to stdout #[inline(never)] // stack intensive, prevent inline so everyone does not incur cost pub fn sol_log(message: &str) { // TODO This is extremely slow, do something better let mut bu...
// Copyright 2021 Datafuse Labs. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to ...
pub mod fzy; pub mod skim; pub mod substring; use crate::MatchResult; use types::{CaseMatching, FuzzyText}; #[derive(Debug, Clone, Copy, Default)] pub enum FuzzyAlgorithm { Skim, #[default] Fzy, } impl std::str::FromStr for FuzzyAlgorithm { type Err = (); fn from_str(s: &str) -> Result<Self, Self...
use std::{cell::RefCell, rc::Rc}; use super::{actor::Actor, state_mask::StateMask}; use crate::PacketReader; /// An Enum with a variant for every Actor that can be synced between /// Client/Host pub trait ActorType<Impl = Self>: Clone { /// Read bytes from an incoming packet into all contained Properties fn ...
use smaz::{compress}; use lz4_flex::{compress_prepend_size}; fn main() { println!("smaz:"); let original_length = *&compression_test::INPUT.as_bytes().len() as f64; println!("original length: {:?}", original_length); let compressed = compress(&compression_test::INPUT.as_bytes()); let compressed_le...
//! https://github.com/lumen/otp/tree/lumen/lib/observer/src use super::*; test_compiles_lumen_otp!(cdv_atom_cb); test_compiles_lumen_otp!(cdv_bin_cb); test_compiles_lumen_otp!(cdv_detail_wx); test_compiles_lumen_otp!(cdv_dist_cb); test_compiles_lumen_otp!(cdv_ets_cb); test_compiles_lumen_otp!(cdv_fun_cb); test_compi...
//< Implementations for naive algorithms that outputs all matching subwords of a //< regex. //< //< Note that these algorithms are not as strong as other algorithms of this //< project as they can't handle defined groups. use lib_regex; use std::ops; use super::super::automaton::Automaton; use super::super::regex; u...
use dlal_component_base::{component, json_to_ptr, serde_json, Body, CmdResult}; use std::f32; use std::f32::consts::PI; fn smooth(x: &mut [f32], xf: &[f32], smooth: f32) { for i in 0..x.len() { x[i] = x[i] * smooth + xf[i] * (1.0 - smooth); } } component!( {"in": ["midi", "cmd"], "out": ["audio"]...
/// `super` untuk mengakses diluar module saat ini /// `self` untuk mengakses current module /// `crate` untuk root module fn function() { println!("Called `function()`"); } mod cool { pub fn function() { println!("Called `cool::function()`"); } } mod my { pub fn function() { println!("Called ...
#![feature(inclusive_range_syntax)] extern crate rand; mod sim; fn main() { let mut game = sim::LifeSimulator::new(sim::LifeRules::PercentageRules, 2, 100); /* *game.mut_coords(&[50, 50]) = sim::Cell::Alive; *game.mut_coords(&[51, 50]) = sim::Cell::Alive; *game.mut_coords(&[51, 48]) = sim::Cell::Al...
use openvr::{init, ApplicationType, Compositor, Context, System}; use utilities::prelude::*; use vulkan_rs::prelude::*; use crate::p_try; use std::ffi::CString; use std::mem; use std::sync::Arc; pub struct OpenVRIntegration { _context: Context, system: Arc<System>, compositor: Arc<Compositor>, } impl O...
#[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::CTRL { #[doc = r"Modifies the contents of the register"] #[inline(always)] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'w...
use crate::geometry::vector::Dot; use crate::math; use crate::transform::Matrix4x4; use crate::transform::Transform; use crate::types::Float; use crate::Vector3f; use std::ops; #[derive(Clone, Copy, Default)] pub struct Quaternion { pub v: Vector3f, pub w: Float, } impl Quaternion { pub fn normalized(self...
use crate::util::Point; use crate::util::Minimum; #[allow(dead_code)] pub fn solve_naive(points: &[Point]) -> (Point, Point) { let mut minimum = Minimum::new( points[0].clone(), points[1].clone(), ); for i in 0..points.len() { let p1 = points[i]; for j in (i + 1)..points.le...
// This file is Copyright its original authors, visible in version control // history. // // This file is 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. // You may...
use rltk::{GameState, Point, Rltk}; use specs::prelude::*; mod components; mod constants; mod damage_system; mod gamelog; mod gui; mod inventory_system; mod map; mod map_indexing_system; mod melee_combat_system; mod monster_ai_system; mod player; mod rect; mod spawner; mod visibility_system; pub use components::*; us...
mod bloom; pub use bloom::*;
/// Inserts a data memory barrier, useful when reading data from a CPU peripheral. pub fn read_barrier() { unsafe { asm!("dmb") } } /// Inserts a data sychronisation (or write) barrier, useful when writing data from a CPU /// peripheral. #[allow(dead_code)] pub fn write_barrier() { unsafe { asm!("dsb") } }
use std::fmt; use crate::row::Row; #[derive(Clone)] pub struct Grid { pub rows: Vec<Row>, } impl Grid { pub fn neib(&self, x: usize, y: usize, dir: u8) -> Result<(usize, usize), &'static str> { // Get the grid coordinates in the dir provided // 0 1 2 // 3 4 // 5 6 7 ...
use crate::{DocBase, VarType}; const DESCRIPTION: &'static str = r#" The wma function returns weighted moving average of x for y bars back. In wma weighting factors decrease in arithmetical progression. "#; const EXAMPLE: &'static str = r#" ```pine plot(wma(close, 15)) // same on pine, but much less efficient pine_w...
#[cfg(any( all(debug_assertions, feature = "debug-glam-assert"), feature = "glam-assert" ))] macro_rules! glam_assert { ($($arg:tt)*) => ( assert!($($arg)*); ) } #[cfg(not(any( all(debug_assertions, feature = "debug-glam-assert"), feature = "glam-assert" )))] macro_rules! glam_assert { ($($arg:t...
use log::error; use std::env; use std::result::Result; use thiserror::Error; use crate::common; #[derive(Error, Debug)] enum ListCommandError { #[error("reading .rpilot file failed. Make sure this project is initialised properly")] NotInitialized, #[error("Failed at reading the config")] ConfigReadEr...
mod sha2; fn main() { println!("{:?}", sha2::sha256("hello world")); }
extern crate pcre; use pcre::Pcre; use std::fs::File; use std::io::BufReader; use std::io::BufRead; fn nice1(word: &str) -> bool { let mut one = Pcre::compile(r"(?:[aeiou].*?){3}").unwrap(); let mut two = Pcre::compile(r"(.)\1").unwrap(); let mut three = Pcre::compile(r"ab|cd|pq|xy").unwrap(); one.ex...
#![recursion_limit = "256"] use async_std::{ io::{stdin, BufReader}, net::{TcpStream, ToSocketAddrs}, prelude::*, task, }; use chat_shared::Message; use futures::{select, FutureExt}; type Result<T> = std::result::Result<T, Box<dyn std::error::Error + Send + Sync>>; fn main() -> Result<()> { task:...
use std::collections::{HashMap, HashSet}; use crate::arena::{Arena, ArenaId}; use crate::bvh::Bvh; use crate::geo::{BarycentricCoords, Bbox, Circle, Vec2}; pub type TriangleId = ArenaId<Triangle>; pub type VertexId = ArenaId<Vertex>; #[derive(Debug)] pub struct DelaunayMesh { triangles: Arena<Triangle>, vert...
use crate::tokenizer::Token; use self::{nodes::AstNode}; mod parser; mod parsers; pub mod nodes; #[derive(Debug)] pub struct AstProgram { pub body: Vec<AstNode>, } impl AstProgram { pub fn new() -> AstProgram { Self { body: Vec::new(), } } pub fn from_body(body: &Vec<Ast...
fn main() { let mut layer: i64 = 0; let target = 265149; loop { let x = layer * 2 + 1; if i64::pow(x, 2) >= target { break } else { layer += 1; } } //we now know what the layer that the raget will be in. //next we need to traverse t...
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use failure::Fail; #[allow(missing_docs)] #[derive(Fail, Debug, PartialEq, Eq)] pub enum RuleParseError { #[fail(display = "invalid hostname")] In...
use std::os::raw::c_int; #[derive(Debug)] pub enum Error { DeviceNotFound, DeviceNotAvailable, CompilerNotAvailable, MemObjectAllocationFailure, OutOfResources, OutOfHostMemory, ProfilingInfoNotAvailable, MemCopyOverlap, ImageFormatMismatch, ImageFormatNotSupported, BuildPro...
#[doc = "Reader of register MPCBB2_VCTR29"] pub type R = crate::R<u32, super::MPCBB2_VCTR29>; #[doc = "Writer for register MPCBB2_VCTR29"] pub type W = crate::W<u32, super::MPCBB2_VCTR29>; #[doc = "Register MPCBB2_VCTR29 `reset()`'s with value 0"] impl crate::ResetValue for super::MPCBB2_VCTR29 { type Type = u32; ...
use std::error; type Error = Box<dyn error::Error>; macro_rules! error { ($fmt:literal $(, $e:expr)*) => { Error::from(format!($fmt $(, $e)*)) }; } fn main() -> Result<(), Error> { for filename in std::env::args().skip(1) { println!("{}", filename); let window = parse_window(&filename)?; ...
use crate::matcher::WildcardMatcher; use std::collections::BTreeSet; // Match http header 'host' #[derive(Debug, Clone)] pub struct HostMatcher { modes: Vec<MatchMode>, } #[derive(Debug, Clone)] enum MatchMode { Text(String), Wildcard(WildcardMatcher), } impl Default for HostMatcher { fn default() ->...
pub(crate) use decl::make_module; #[pymodule(name = "faulthandler")] mod decl { use crate::vm::{frame::Frame, function::OptionalArg, stdlib::sys::PyStderr, VirtualMachine}; fn dump_frame(frame: &Frame, vm: &VirtualMachine) { let stderr = PyStderr(vm); writeln!( stderr, ...