text
stringlengths
8
4.13M
//! Rendering functions and backend traits. use nalgebra::{Point2, Vector2}; use template::{Color}; use {ComponentId, Ui, Error, ComponentFlow}; /// A renderer backend, implements how individual rendering operations are done. pub trait Renderer { fn render_cache_to_target(&mut self, id: ComponentId) -> Result<(),...
extern crate argparse; extern crate pnet; use argparse::{ArgumentParser, Store, StoreTrue}; use pnet::datalink::{self, NetworkInterface}; use pnet::datalink::Channel::Ethernet; use pnet::packet::{MutablePacket, Packet}; use pnet::packet::ethernet::{MutableEthernetPacket, EthernetPacket, EtherType}; use pnet::packet::...
//! Assorted analytical modules for the cryptanalysis engine.
use actix::prelude::*; use actix::{ Addr, Actor, StreamHandler, fut }; use actix_web::{web, Error, HttpRequest, HttpResponse}; use actix_web_actors::ws; use serde_json::Value; use crate::coordinator::Coordinator; use crate::messages::{ Connect, StatusUpdate, CreateWorker }; pub fn websocke...
use iced::{button, Align, Button, Row, Element, Sandbox, Settings, Text, HorizontalAlignment, Length}; // the window size is an unsigned 32 bit integer, the padding is unsigned 16 bit integer const SIZE: (u32, u32) = (250, 80); const PAD: u16 = 25; pub fn main() -> iced::Result{ // Set the window properties l...
use nom::combinator::map; use nom::number::complete::be_u128; use nom::IResult; use std::net::Ipv6Addr; pub(crate) fn parse_ipv6_address(input: &[u8]) -> IResult<&[u8], Ipv6Addr> { map(be_u128, Ipv6Addr::from)(input) }
//! Traits for interactions with a processors watchdog timer. /// Feeds an existing watchdog to ensure the processor isn't reset. Sometimes /// the "feeding" operation is also referred to as "refreshing". pub trait Watchdog { /// An enumeration of `Watchdog` errors. /// /// For infallible implementations, ...
use super::Part; use crate::codec::{Decode, Encode}; use crate::spacecenter::Thruster; use crate::{remote_type, RemoteObject, Vector3}; use std::collections::BTreeMap; remote_type!( /// An engine, including ones of various types. For example liquid fuelled gimballed engines, /// solid rocket boosters and jet engines....
use super::resource_id::{ResourceId}; use std::net::{SocketAddr}; /// Information to identify the remote endpoint. /// The endpoint is used mainly as a connection identified. #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] pub struct Endpoint { resource_id: ResourceId, addr: SocketAddr, } impl Endpoint { ...
pub struct Solution; impl Solution { pub fn kth_smallest(matrix: Vec<Vec<i32>>, k: i32) -> i32 { let k = k as usize; let n = matrix.len(); let mut a = matrix[0][0]; let mut b = matrix[n - 1][n - 1]; while a < b { let c = a + (b - a) / 2; let mut count...
use std::time::Duration; use rand::prelude::*; use rand_chacha::ChaCha8Rng; use crate::chip8::{Opcode, Register, Address, Chip8Result, Chip8Error}; use crate::chip8::quirks::{ReadWriteIncrementQuirk, BitShiftQuirk}; use crate::chip8::gpu::{self, Gpu}; /// `Chip8` is the core emulation structure of this project. It im...
/* 132. Palindrome Partitioning II Hard Given a string s, partition s such that every substring of the partition is a palindrome. Return the minimum cuts needed for a palindrome partitioning of s. Example 1: Input: s = "aab" Output: 1 Explanation: The palindrome partitioning ["aa","b"] could be produced using 1 cut. ...
#[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::RIS { #[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 super::thread_future::ThreadFuture; use crate::dialog::{MessageButtons, MessageDialog, MessageLevel}; use winapi::um::winuser::{ MessageBoxW, IDOK, IDYES, MB_ICONERROR, MB_ICONINFORMATION, MB_ICONWARNING, MB_OK, MB_OKCANCEL, MB_YESNO, }; use std::{ffi::OsStr, iter::once, os::windows::ffi::OsStrExt, ptr}; ...
use std::ops::Deref; use ash::vk; pub struct RawVkDebugUtils { pub debug_utils_loader: ash::extensions::ext::DebugUtils, pub debug_messenger: vk::DebugUtilsMessengerEXT, } impl Drop for RawVkDebugUtils { fn drop(&mut self) { unsafe { self.debug_utils_loader .destroy_de...
//! Retention Rules use serde::{Deserialize, Serialize}; /// RetentionRule #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct RetentionRule { /// Expiry #[serde(rename = "type")] pub r#type: Type, /// Duration in seconds for how long data...
//! Attribute values. //! //! Type Attr represents an attribute of a Layer. extern crate libc; use super::token::Token; use super::range::Range; use super::variant::{Value, Variant}; /// An attribute object. #[repr(C)] pub struct Attr { id: Token, typ: Token, val: Variant, range: (u32, u32), } impl<...
use config::{Config, File}; use std::path::PathBuf; pub fn load_config(file: Option<&PathBuf>) -> Config { let mut s = Config::new(); s.merge(File::with_name(file.unwrap_or(&PathBuf::from("config/session")).to_str().unwrap())).unwrap(); s }
//============================================================================== // Notes //============================================================================== // drivers::lcd.rs //============================================================================== // Crates and Mods //===========================...
use std::rc::Rc; use crate::object::{Hittable, HitRecord}; use crate::Ray; pub struct HittableList { objects: Vec<Rc<dyn Hittable>>, } impl HittableList { pub fn new() -> Self { HittableList { objects: Vec::new() } } pub fn add(&mut self, object: Rc<dyn Hittable>) { self.objects.push...
use nutype::nutype; use std::convert::TryFrom; use crate::{format_string, Error}; const METERS_PER_MILE: f64 = 1609.344; /// Distance in meters #[nutype(validate(min=0.0))] #[derive(*, Serialize, Deserialize)] pub struct Distance(f64); impl Default for Distance { fn default() -> Self { Self::new(0.0).un...
use crate::{auth, Department, Gender, IdTokenPayload, Request, State, User}; use serde::{Deserialize, Serialize}; use serde_json::json; use tide::http::{headers, mime, Cookie}; use tide::{Redirect, Response, StatusCode}; macro_rules! oauth_redirect { ($redirect_uri:expr, $query:expr $(,)?) => { Redirect::n...
fn main() { // Prevent building SPIRV-Cross on wasm32 target let target_arch = std::env::var("CARGO_CFG_TARGET_ARCH"); if let Ok(arch) = target_arch { if "wasm32" == arch { return; } } let target_vendor = std::env::var("CARGO_CFG_TARGET_VENDOR"); let is_apple = targe...
extern crate core; extern crate rayon; use std::fmt::{Display, Formatter, Error}; use ::SquareState::{BLOCK, PLAYABLE, EMPTY, FULL}; use core::fmt::Write; use std::sync::atomic::AtomicBool; use std::sync::atomic::Ordering::Relaxed; use rayon::iter::IntoParallelRefIterator; use rayon::iter::ParallelIterator; #[derive(...
// 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 crate::{ common::{inherit_rights_for_clone, send_on_open_with_error}, directory::{ common::{ check_child_connection_flags, ...
use crate::*; use ark_crypto_primitives::Error; use ark_ec::PairingEngine; use ark_groth16::{Proof, VerifyingKey}; use ark_serialize::CanonicalDeserialize; use arkworks_gadgets::{ setup::{common::verify_groth16, mixer::get_public_inputs}, utils::to_field_elements, }; use sp_std::marker::PhantomData; pub struct Arkwo...
// Kth Largest Element in an Array // https://leetcode.com/explore/challenge/card/january-leetcoding-challenge-2021/581/week-3-january-15th-january-21st/3606/ #[cfg(disabled)] use std::cmp::Ordering::*; pub struct Solution; impl Solution { #[cfg(disable)] pub fn find_kth_largest(nums: Vec<i32>, k: i32) -> i3...
use std::fmt; #[derive(Clone, Copy, PartialEq, Debug)] pub enum States { Alive, Dead, } #[derive(Clone, PartialEq, Debug)] pub struct Cell { pub state :States, pub next_state :States, } impl Cell { pub fn new() -> Cell { Cell { state: States::Dead, next_state: States::Dead} } pub fn upd...
//! # `deploy` //! Run a binary on a constellation cluster //! //! ## Usage //! ```text //! deploy [options] <host> <binary> [--] [args]... //! ``` //! //! ## Options //! ```text //! -h --help Show this screen. //! -V --version Show version. //! --format=<fmt> Output format [possible values: human, j...
use criterion::{ criterion_group, criterion_main, Bencher, Criterion, Throughput, }; use regex_automata::dfa::{dense, regex}; use regex_automata::nfa::thompson; use crate::inputs::*; mod inputs; fn is_match(c: &mut Criterion) { let corpus = SHERLOCK_HUGE; define(c, "is-match", "sherlock-huge", corpus, mo...
use rustfft::{num_complex::Complex, FftPlanner}; pub fn compute(signal: &Vec<f64>) -> Vec<f64> { let fft_len = signal.len(); let fft = FftPlanner::new().plan_fft_forward(fft_len); let mut fft_buffer: Vec<_> = signal .iter() .map(|&sample| Complex::new(sample, 0_f64)) .collect(); ...
/// The macro for making a union of materials. /// /// You can read more about the technique [here](https://clay-rs.github.io/knowledge/#objects). #[macro_export] macro_rules! material_select { ( $Select:ident { $( $Enum:ident ( $Param:ident = $Material:ty ) ),+ $(,)? } ) => { $crate::instance_select!( ...
use crate::comment::{comment_parser, CommentType}; use crate::common::empty_line_parser; use crate::samples::{parse_sample, SampleEntry}; use crate::types::{Err, Metric, MetricType, Sample}; use nom::branch::alt; use nom::combinator::map; use nom::IResult; use std::collections::HashMap; // Restrict this to internal vi...
#[doc = "Reader of register HFXOSTEADYSTATECTRL"] pub type R = crate::R<u32, super::HFXOSTEADYSTATECTRL>; #[doc = "Writer for register HFXOSTEADYSTATECTRL"] pub type W = crate::W<u32, super::HFXOSTEADYSTATECTRL>; #[doc = "Register HFXOSTEADYSTATECTRL `reset()`'s with value 0xa30b_4507"] impl crate::ResetValue for super...
extern crate nix; use clap::{App, Arg}; use std::fs::{File, rename}; use std::io; use std::os::unix::io::AsRawFd; use nix::fcntl::{splice, SpliceFFlags}; const BUF_SIZE: usize = 16384; const WRAP_AFTER: usize = 4 * BUF_SIZE; fn main() { let stdin = io::stdin(); let _handle = stdin.lock(); let mut file_i...
use actix_web::{middleware, App, HttpServer}; use dotenv::dotenv; mod image; #[actix_rt::main] async fn main() -> std::io::Result<()> { dotenv().ok(); //let host = env::var("host").expect("host not set"); //let port = env::var("port").expect("port not set"); let host = String::from("127.0.0.1"); l...
use firefly_session::Input; /// Maps to an interned instance of Input #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)] pub struct InternedInput(salsa::InternId); impl From<u32> for InternedInput { #[inline] fn from(i: u32) -> Self { Self(i.into()) } } impl salsa::InternKey for InternedInput { ...
struct Number { odd: bool, value: i32, } fn print_number(n: Number) { if let Number { odd: true, value } = n { println!("Odd number: {}", value); } else if let Number { odd: false, value } = n { println!("Even number: {}", value); } } fn main() { let one = Number { odd: true, v...
mod color; use crate::color::{hsl_to_rgb, Color}; use image::{ImageBuffer, RgbaImage, Progress}; use rand::Rng; use rand_pcg::Pcg64Mcg; use std::path::Path; use std::time::Instant; use std::sync::{Arc, Mutex}; use rayon::prelude::*; const PX: f64 = -0.5557506; const PY: f64 = -0.5556003; const PH: f64 = 0.0000000007;...
use super::{overflow, Loc, Shift, Ts, TsDiff}; use crate::index::Index; use crate::util::*; use std::{fmt, ops}; #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] #[repr(transparent)] pub struct ViewDiff(u64); #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] #[repr(transparent)] pub struct View...
use anyhow::Result; use model::{ Account, GoogleId, HashSha256, PlayerStats, RankedScore, Score, ScoreId, Scores, Songs, VisibleAccount, }; pub trait PublishedUsers { fn fetch_users(&mut self) -> Result<Vec<VisibleAccount>>; } pub trait HealthCheck { fn health(&mut self) -> Result<()>; } pub trait Ac...
//! This module implements adapted `web3` error types so that the errors in //! the parent module all implement `Sync`. Otherwise, dealing with propagating //! errors across threads can be tricky. use crate::abicompat::AbiCompat; use ethcontract_common::abi::Error as AbiError; use thiserror::Error; use web3::error::Er...
#[allow(dead_code)] mod opengl; mod program; mod color; mod vertex; #[allow(dead_code)] mod renderer; mod image; mod texture; mod canvas; mod sprite_params; use opengl::BufferUsage; use renderer::{Renderer, RendererBuilder}; use texture::TextureHolder; pub use opengl::{PrimitiveType, FilterMode, Filter, WrapMode, Wra...
#[doc = "Reader of register EECR3"] pub type R = crate::R<u32, super::EECR3>; #[doc = "Writer for register EECR3"] pub type W = crate::W<u32, super::EECR3>; #[doc = "Register EECR3 `reset()`'s with value 0"] impl crate::ResetValue for super::EECR3 { type Type = u32; #[inline(always)] fn reset_value() -> Sel...
/// Defines global allocator /// /// /// # Example /// /// ``` /// // define global allocator /// default_alloc!() /// /// // Default allocator uses a mixed allocation strategy: /// // /// // * Fixed block heap, only allocate fixed size(64B) memory block /// // * Dynamic memory heap, allocate any size memory block /// ...
use std::borrow::Cow; use heed_traits::{BytesDecode, BytesEncode}; use zerocopy::{AsBytes, FromBytes, LayoutVerified, Unaligned}; /// Describes a type that is totally borrowed and doesn't /// depends on any [memory alignment]. /// /// If you need to store a type that does depend on memory alignment /// and that can b...
// This file was generated by gir (https://github.com/gtk-rs/gir) // from gir-files (https://github.com/gtk-rs/gir-files) // DO NOT EDIT use glib::object::Cast; use glib::object::IsA; use glib::signal::connect_raw; use glib::signal::SignalHandlerId; use glib::translate::*; use glib::GString; use glib_sys; use libc; us...
use P36::prime_factor_multiplicity; pub fn main() { println!("{:?}", prime_factor_multiplicity(315)); }
use { std::convert::TryInto, tracing::{debug, info}, }; const NUM_STACKS: usize = 9; fn read_stacks(input: &str) -> [Vec<char>; NUM_STACKS] { let mut stacks: [Vec<char>; NUM_STACKS] = Default::default(); for line in input.split('\n') { let line_bytes = line.as_bytes(); for (i, stack) ...
/* * If not stated otherwise in this file or this component's LICENSE file the * following copyright and licenses apply: * * Copyright 2022 RDK Management * * 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 cop...
#![cfg_attr( all(feature = "async", feature = "chrono", feature = "time"), doc = r##" # rsntp An [RFC 5905](https://www.rfc-editor.org/rfc/rfc5905.txt) compliant Simple Network Time Protocol (SNTP) client library for Rust. `rsntp` provides an API to synchronize time with SNTPv4 time servers with the following...
use crate::error::Error; use crate::mssql::MssqlConnectOptions; use percent_encoding::percent_decode_str; use std::str::FromStr; use url::Url; impl FromStr for MssqlConnectOptions { type Err = Error; fn from_str(s: &str) -> Result<Self, Self::Err> { let url: Url = s.parse().map_err(Error::config)?; ...
#![feature(test)] extern crate blake2_rfc; extern crate blake2 as rust_blake2; extern crate crypto as rust_crypto; extern crate libb2_sys; extern crate libc; extern crate test; #[cfg(test)] mod bench_blake2_rfc { use test::Bencher; fn bench_blake2b(data: &[u8], b: &mut Bencher) { use blake2_rfc::blak...
use crate::models::DieselResult; use crate::schema::*; use crate::MySqlPooledConnection; #[derive(Debug, Clone, Queryable, Insertable)] #[diesel(table_name = hashes)] pub struct Hash { pub sha256: String, pub md5: String, } impl Hash { pub fn all(connection: &mut MySqlPooledConnection) -> DieselResult<Vec...
use sha1::{Digest, Sha1}; use std::borrow::Cow; use std::{env, fs, io}; use walkdir::WalkDir; /// Get the filename of an entry from a directory walk, with backslashes replaced with forward slashes fn unixy_filename_of(entry: &walkdir::DirEntry) -> String { return entry.path().display().to_string().replace("\\", "/...
const DTB_ADDRESS_RANGE: [usize; 2] = [0x1020, 0x1fff]; use memory::Memory; use cpu::{PrivilegeMode, Trap, TrapType, Xlen}; use device::virtio_block_disk::VirtioBlockDisk; use device::plic::Plic; use device::clint::Clint; use device::uart::Uart; use terminal::Terminal; pub struct Mmu { clock: u64, xlen: Xlen, ppn:...
use crate::utils; use std::io; #[derive(Debug)] struct Entry { min: i32, max: i32, letter: char, password: String, } fn read_problem_data() -> io::Result<Vec<Entry>> { let mut result = Vec::new(); if let Ok(lines) = utils::read_lines("data/day2.txt") { for line in lines { i...
use crate::{ make, raw_data, Area, AreaID, Building, Intersection, IntersectionID, IntersectionType, Lane, LaneID, Road, RoadID, Turn, TurnID, LANE_THICKNESS, }; use abstutil::Timer; use geom::{Bounds, Polygon}; use std::collections::BTreeMap; pub struct HalfMap { pub roads: Vec<Road>, pub lanes: Vec<L...
//! This module implements the session setup response. //! The SMB2 SESSION_SETUP Response packet is sent by the server in response to an SMB2 SESSION_SETUP Request packet. //! This response is composed of an SMB2 header that is followed by this response structure: /// session setup request size of 25 bytes const STRU...
use std::boxed::Box; use std::collections::HashMap; pub struct Field { name: String, type_name: String, r#type: String, } pub struct Type { name: String, alias_of_name: String, array_of: Box<Type>, optionalOf: Box<Type>, base_name: String, base: String, fields: Vec<Field>, } p...
use crate::extra; use crate::traits::*; use itertools::Itertools; use nix::unistd; use regex::Regex; use std::fs; use std::path::PathBuf; use std::process::{Command, Stdio}; pub struct NetBSDBatteryReadout; pub struct NetBSDKernelReadout; pub struct NetBSDGeneralReadout; pub struct NetBSDMemoryReadout; pub struct ...
extern crate irc; extern crate postgres; use irc::client::prelude::{ClientExt, Command, Config, IrcReactor}; use postgres::{NoTls, Client}; fn main() { // Connect to IRC server println!("[DEBUG] Connecting to IRC server..."); let irc_config = Config::load("config.toml").unwrap(); let mut reactor = Ir...
use crate::interface; use near_sdk::{ borsh::{self, BorshDeserialize, BorshSerialize}, }; use std::ops::{Add, Mul}; #[derive( BorshSerialize, BorshDeserialize, Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Default, )] pub struct Gas(pub u64); /// 1 teraGas pub const T...
// Copyright 2020-2021, The Tremor Team // // 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 agr...
/* * Copyright (C) 2020 Zixiao Han */ use crate::{ bitboard::BitBoard, bitmask, def, util, zob_keys, }; use std::fmt; const FEN_SQRS_INDEX: usize = 0; const FEN_PLAYER_INDEX: usize = 1; const FEN_CAS_RIGHTS_INDEX: usize = 2; const FEN_ENP_SQR_INDEX: usize = 3; const FEN_HALF_MOV_INDEX: usize = ...
// RGB standard library // Written in 2020 by // Dr. Maxim Orlovsky <orlovsky@pandoracore.com> // // To the extent possible under law, the author(s) have dedicated all // copyright and related and neighboring rights to this software to // the public domain worldwide. This software is distributed without // any warr...
//! The main storage for values travelling through the system. //! We have support for singular as well as composite values. use serde::{Deserialize, Serialize}; #[derive(Debug, Clone, Copy)] pub enum ValueKind { Int, Float, String, } impl From<u8> for ValueKind { fn from(kind: u8) -> ValueKind { ...
use rand::{Rng, thread_rng}; struct Gene { strategy: Vec<f64>, score: u32, } impl Gene { fn build_random_gene() -> Gene { let mut rng = thread_rng(); let mut a: Vec<f64> = vec![0f64; 6 ]; a = a.into_iter().map(|_item| { rng.gen_range(0f64..1f64)}).collect(); let mut gene = ...
use super::{CommandBlocking, DrawableComponent}; use crate::{ components::{CommandInfo, Component}, keys, queue::{InternalEvent, NeedsUpdate, Queue}, strings, ui, }; use asyncgit::{hash, sync, StatusItem, StatusItemType, CWD}; use crossterm::event::Event; use std::{ borrow::Cow, cmp, convert...
use std::{ collections::HashMap, fs::File, io::{BufRead, BufReader}, }; use math::{ partition::ordered_interval_partitions::OrderedIntervalPartitions, set::{ contiguous_integer_set::ContiguousIntegerSet, ordered_integer_set::OrderedIntegerSet, }, }; use crate::{ error::Erro...
#![cfg_attr(not(feature = "std"), no_std)] /// A runtime module template with necessary imports /// Feel free to remove or edit this file as needed. /// If you change the name of this file, make sure to update its references in runtime/src/lib.rs /// If you remove this file, you can remove those references /// For m...
fn parse_ids(input: &str) -> Vec<Option<usize>> { input .split(",") .map(|s| { if s == "x" { None } else { Some(s.parse::<usize>().unwrap()) } }) .collect() } fn main() { let input = std::fs::read_to_string("inp...
use std::io; use std::collections::BTreeSet; use std::cmp::Ordering; use std::fmt; type Point = (usize, usize); #[derive(Clone, Copy, Eq, PartialEq)] enum Facing { Up, Down, Left, Right } #[derive(Clone, Copy, Eq, PartialEq)] enum Track { None, Horizontal, Vertical, Turn(char), In...
use crate::windowing::{Window}; use std::rc::{Weak, Rc}; use std::cell::RefCell; use gl_bindings::gl; use crate::utils::lazy_option::Lazy; pub struct GLWindowContext { glfw_window: Weak<RefCell<Window>>, } impl GLWindowContext { pub fn set_swap_interval(&mut self, interval: glfw::SwapInterval) -> bool { // if self...
use std::collections::HashSet; use crate::{ prelude::*, map::Map, shape::*, }; /// A new shape obtained by applying some mapping to another shape. pub struct ShapeMapper<S: Shape, M: Map> { pub shape: S, pub map: M, } impl<S: Shape, M: Map> ShapeMapper<S, M> { pub fn new(shape: S, map: M) -> S...
use bytes::{Buf, Bytes}; use crate::error::Error; #[derive(Debug)] pub(crate) struct ReturnStatus { #[allow(dead_code)] value: i32, } impl ReturnStatus { pub(crate) fn get(buf: &mut Bytes) -> Result<Self, Error> { let value = buf.get_i32_le(); Ok(Self { value }) } }
// 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 ...
use std::fmt::Debug; trait Movable: Debug { fn ride(&self); } trait MovableDecorator: Movable { fn get_decorated(&self) -> &Movable; } #[derive(Debug)] struct Vehicle { handbrake_enabled: bool } #[derive(Debug)] struct PaintedVehicle<'a> { vehicle: &'a Movable } #[derive(Debug)] struct IlluminatedV...
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)] #[link(name = "windows")] extern "system" { #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Globalization"))] pub fn ImmAssociateContext(param0: super::super::super::Foundation::HWND, para...
use crate::ckb_constants::*; use crate::debug; use crate::error::SysError; use crate::syscalls; use alloc::vec::Vec; use ckb_types::{packed::*, prelude::*}; /// Default buffer size pub const BUF_SIZE: usize = 1024; /// Load tx hash /// /// Return the tx hash or a syscall error /// /// # Example /// /// ``` /// let tx...
use crate::{core::{Part, Solution}, utils::string::StrUtils}; pub fn solve(part: Part, input: String) -> String { match part { Part::P1 => Day11::solve_part_one(input), Part::P2 => Day11::solve_part_two(input), } } #[derive(Debug)] enum Operation { Add(u64), AddSelf, Multiply(u64),...
#[doc = r"Value read from the register"] pub struct R { bits: u16, } #[doc = r"Value to write to the register"] pub struct W { bits: u16, } impl super::DMACTL6 { #[doc = r"Modifies the contents of the register"] #[inline(always)] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, ...
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 /// The microvm state. When Firecracker starts, the instance state is Uninitialized. /// Once start_microvm method is called, the state goes from Uninitialized to Starting. /// The state is changed to Runn...
#[doc = "Reader of register TAPR"] pub type R = crate::R<u32, super::TAPR>; #[doc = "Writer for register TAPR"] pub type W = crate::W<u32, super::TAPR>; #[doc = "Register TAPR `reset()`'s with value 0"] impl crate::ResetValue for super::TAPR { type Type = u32; #[inline(always)] fn reset_value() -> Self::Typ...
use clap::{App, Arg, SubCommand}; pub fn threshold() -> App<'static, 'static> { return SubCommand::with_name("threshold") .about("Intervals defined by lightness thresholds; only pixels with a lightness outside of the upper and lower thresholds interval are sorted.") .arg(Arg::with_name("lower") ...
use crate::backend::{Backend, instance}; #[derive(Debug)] #[cfg(not(target_arch = "wasm32"))] pub struct SurfaceData { pub framebuffer: u32 } #[cfg(target_arch="wasm32")] use webgl_stdweb::WebGLFramebuffer; #[derive(Debug)] #[cfg(target_arch="wasm32")] pub struct SurfaceData { pub framebuffer: WebGLFramebuff...
//! This module implements CLI commands for debugging the ingester WAL. use futures::Future; use influxdb_iox_client::connection::Connection; use thiserror::Error; mod inspect; mod regenerate_lp; /// A command level error type to decorate WAL errors with some extra /// "human" context for the user #[derive(Debug, E...
pub mod counter; pub mod elapsed_time;
use wasm_bindgen::prelude::*; use web_sys::HtmlCanvasElement; use crate::renderers::consts::*; #[wasm_bindgen] pub struct RsRenderer { pub(super) width: usize, pub(super) height: usize, pub(super) framebuffer: Vec<u8> } #[wasm_bindgen] impl RsRenderer { pub fn new(width: usize, height: usize) -> Rs...
use crate::Transformer; use lowlang_syntax::*; use lowlang_syntax::visit::VisitorMut; pub struct BlockMerger<'t> { current_body: Option<*mut Body<'t>>, current_block: Option<*mut Block<'t>>, changed: bool, } impl<'t> BlockMerger<'t> { pub fn new() -> BlockMerger<'t> { BlockMerger { ...
//! different shakespeare datasets use std::error::Error; use std::fs::File; use std::io::Read; use std::path::Path; use crate::utils::download; /// 100000 characters of shakespeare /// http://karpathy.github.io/2015/05/21/rnn-effectiveness/ pub fn shakespeare_100000(download_dir: &Path) -> Result<String, Box<dyn Er...
use std::io::{Read, Result as IOResult}; use crate::PrimitiveRead; #[derive(Copy, Clone, Debug, Default)] pub struct Lump { pub file_offset: i32, pub file_length: i32, pub version: i32, pub four_cc: i32, } impl Lump { pub fn read(reader: &mut dyn Read) -> IOResult<Self> { let file_offset = reader.read_i...
use std::collections::HashMap; use std::io; use std::io::Read; use regex::Regex; fn main() { let mut input = String::new(); io::stdin().read_to_string(&mut input).unwrap(); let re = Regex::new(r"(?m)(?:^mask = ([01X]+)$)|(?:^mem\[(\d+)\] = (\d+)$)").unwrap(); let mut mem = HashMap::new(); let mut...
fn main() { let stdin = std::io::stdin(); let mut rd = ProconReader::new(stdin.lock()); let h: usize = rd.get(); let w: usize = rd.get(); let a: Vec<Vec<char>> = (0..h).map(|_| rd.get_chars()).collect(); let mut left = vec![vec![0; w]; h]; let mut right = vec![vec![0; w]; h]; let mut u...
use std::fmt; use super::items::Item; use super::items::wall::Wall; use super::items::player::Player; use super::geometry::Geometry; pub struct World{ //Using a box with a 'trait object' called Item //We box Item because we can never know the size of an Item //which means that it can only be borrowed. And ...
//! Bitwise instructions use bigint::{Sign, M256, MI256}; use super::State; use crate::{Memory, Patch}; pub fn iszero<M: Memory, P: Patch>(state: &mut State<M, P>) { pop!(state, op1); if op1 == M256::zero() { push!(state, M256::from(1u64)); } else { push!(state, M256::zero()); } } p...
use screen::dimension::Dimension; use screen::layout::layout::{Layout, LayoutRc}; use screen::screen::Screen; pub struct HLayout { data: Vec<LayoutRc>, width: usize, height: usize, } impl HLayout { pub fn new(data: Vec<LayoutRc>) -> HLayout { let width = data.iter().fold(0, |a, l| a + l.width...
use std::alloc::Layout; use std::any::type_name; use std::ffi::c_void; use std::ptr::{self, NonNull}; use std::str::Chars; use std::sync::Arc; use hashbrown::HashMap; use liblumen_core::util::reference::bytes; use liblumen_core::util::reference::str::inherit_lifetime as inherit_str_lifetime; use crate::borrow::Clone...
use crate::*; use reqwest::Url; use serde::{Deserialize, Serialize}; use std::fmt; use std::fmt::{Display, Formatter}; #[derive(Debug, Deserialize, Serialize)] pub struct DocumentsList { pub documents: Vec<Document>, } impl Display for DocumentsList { fn fmt(&self, f: &mut Formatter) -> fmt::Result { ...
extern crate serde; mod test_utils; use chrono::NaiveDate; use flexi_logger::LoggerHandle; use hdbconnect::{Connection, HdbResult}; // From wikipedia: // // Isolation level Lost updates Dirty reads Non-repeatable reads Phantoms // ------------------------------------------------------------------------------...