text
stringlengths
8
4.13M
#![cfg_attr(not(feature = "std"), no_std)] #![recursion_limit = "256"] #![allow(clippy::string_lit_as_bytes)] use frame_support::dispatch; use sp_std::{ cmp::{Eq, PartialEq}, ops::Not, prelude::*, }; use codec::{Decode, Encode}; use sp_core::H256; use sp_runtime::{DispatchResult, RuntimeDebug}; #[derive(...
use crate::parser::log_line_parse_result::LogLineParseResult; pub trait Constraint { fn check(&self, log_line: &dyn LogLineParseResult) -> bool; } #[derive(Debug, Eq, PartialEq)] /// A constraint that just echos a boolean value pub struct BooleanConstraint { val: bool, } impl BooleanConstraint { fn new(v...
use crate::{Point2F, RectF, RectTrait}; use std::f32::{MIN, MAX}; pub struct PolygonF { points: Vec<Point2F> } impl PolygonF { pub fn new() -> Self { Self { points: Vec::new() }} pub fn push(&mut self, point: Point2F) { self.points.push(point) } pub fn bbox(&self) -> RectF { let (mut minx, mut miny, mut ma...
use alloc::btree_map::{self, BTreeMap}; use alloc::{String, Vec}; use arch::context::Context; use core::fmt; use core::result::Result; use syscall::error::Error; use task::{Priority, Process, ProcessId, State}; pub struct ProcessList { map: BTreeMap<ProcessId, Process>, next_id: usize, } impl fmt::Debug for P...
/** Registers a selector, returning a `Sel`. # Example ``` # #[macro_use] extern crate objc; # fn main() { let sel = sel!(description); let sel = sel!(setObject:forKey:); # } ``` */ #[macro_export] macro_rules! sel { // Declare a function to hide unsafety, otherwise we can trigger the // unused_unsafe lint; se...
pub fn run() { println!("fib(10) = {}", fib(10)); } fn fib(n: i64) -> i64 { fn f(a: i64, b: i64, remains: i64) -> i64 { if remains <= 0 { a } else { f(b, a + b, remains - 1) } } f(0, 1, n) }
use crate::queryplanner::project_schema; use crate::sql::cache::{sql_result_cache_sizeof, SqlResultCache}; use arrow::array::{Array, Int64Builder, StringBuilder}; use arrow::datatypes::{DataType, Field, Schema, SchemaRef}; use arrow::record_batch::RecordBatch; use async_trait::async_trait; use datafusion::datasource::d...
use primitives::*; //use props::*; use errors::*; use graph::*; use ops::interface::default::*; use api; use std::collections::HashMap; //use std::borrow::Borrow; use std::convert::AsRef; use std::ops::DerefMut; /// Calculates the gradient of the expression **f** with respect to all of the /// expressions in **x** us...
mod docs { macro_rules! test_include {( $($ident:ident),* $(,)? ) => ( $( mod $ident { #[test] fn test () { main() } include! { concat!( "../src/proc_macro/doc_examples/", stringify!($...
// Copyright 2020 WHTCORPS INC Project Authors. Licensed Under Apache-2.0 use prometheus::core::{Collector, Desc}; use prometheus::proto::MetricNetwork; use prometheus::{IntGaugeVec, Opts, Result}; pub fn monitor_allocator_stats<S: Into<String>>(namespace: S) -> Result<()> { prometheus::register(Box::new(AllocSta...
/// Types that are safe to transfer over a WinRT API boundary. /// /// # Safety /// Implementing types only have associated `Abi` types that are /// safe to transfer over a WinRT boundary. Implementing types /// must also be exactly equivalent to their associated types /// in layout and abi such that it is safe to tran...
#[doc = "Register `INTEN` reader"] pub struct R(crate::R<INTEN_SPEC>); impl core::ops::Deref for R { type Target = crate::R<INTEN_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<INTEN_SPEC>> for R { #[inline(always)] fn from(reader: crate::R<INT...
pub use accounts_subcommands::{AccountCommand, HandleSubcommand}; pub use blockchain_subcommands::BlockchainCommand; pub use mempool_subcommands::MempoolCommand; pub use network_subcommands::NetworkCommand; pub use policy_subcommands::PolicyCommand; pub use transactions_subcommands::TransactionCommand; pub use validato...
use std::convert::Into; use std::ops::Mul; // Color: #[repr(packed)] #[repr(C)] #[derive(Clone, Copy)] #[derive(Debug)] pub struct Color { pub red: u8, pub green: u8, pub blue: u8, pub alpha: u8 } impl Color { pub fn new(red: u8, green: u8, blue: u8, alpha: u8) -> Self { Color { red, green, blue, alpha } } } i...
use crate::Error; use bytes::Bytes; use futures_util::future::poll_fn; use hreq_h1 as h1; use hreq_h2 as h2; /// Generalisation over sending body data. pub(crate) enum BodySender { H1(h1::SendStream), H2(h2::SendStream<Bytes>), } impl BodySender { pub async fn ready(self) -> Result<Self, Error> { ...
use super::operation::Operation; use super::parameter::Parameter; #[derive(Debug)] pub struct Instruction { pub operation: Operation, pub parameters: Vec<Parameter>, } impl Instruction { pub fn new(instruction_pointer: usize, program: &mut [i32]) -> Instruction { let code = format!("{:0>5}", progr...
#[allow(unused_imports)] use serde_json::Value; #[derive(Debug, Serialize, Deserialize)] pub struct CreateAuthRefreshItemResponse { /// Unique ID of the log filter. #[serde(rename = "id")] pub id: Option<i32>, }
use crate::app::App; use crate::common::Warping; use crate::game::{PopupMsg, Transition}; use crate::helpers::ID; use crate::sandbox::time_warp::JumpToTime; use crate::sandbox::{GameplayMode, SandboxMode, TimeWarpScreen}; use geom::{Duration, Polygon, Time}; use sim::AlertLocation; use widgetry::{ hotkey, Btn, Choi...
#[cfg(feature = "run_bindgen")] extern crate bindgen; #[cfg(feature = "run_bindgen")] fn bindgen_it() { use std::env::var; let chainblocks_dir = var("CHAINBLOCKS_DIR").unwrap_or("../".to_string()); println!("cargo:rustc-link-search={}/build", chainblocks_dir); // Tell cargo to invalidate the built crate when...
use serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize, Debug, Clone)] pub enum WorkType { Send, Recv, } #[derive(Serialize, Deserialize, Debug)] pub struct PerfRequest { pub work_type: WorkType, }
use std::{collections::HashMap, path::Path}; use crate::{ datastructure::generic::{Vec2f, Vec2i}, opengl::Primitive, ui::basic::{boundingbox::BoundingBox, coordinate::Margin}, }; use super::{ glinit::OpenGLHandle, shaders::RectShader, text_renderer::BufferIndex, types::{RGBAColor, Rectangl...
// Copyright (c) The Starcoin Core Contributors // SPDX-License-Identifier: Apache-2.0 use anyhow::{bail, Result}; use starcoin_config::NodeConfig; use starcoin_logger::prelude::*; use starcoin_metrics::{default_registry, Registry}; use starcoin_service_registry::{ActorService, EventHandler, ServiceContext, ServiceFac...
#[macro_use] extern crate aoc_runner_derive; mod y2020; aoc_lib! {year = 2020}
use spec::*; use util::*; use std::collections::{HashMap, HashSet}; use itertools::Itertools; /// A tool designed to replace all anonymous types in a specification /// of the language by explicitly named types. /// /// Consider the following mini-specifications for JSON: /// /// ```idl /// interface Value { /// ...
//! brokkr is a simple distributed task queue library for Rust. //! //! It allows queueing tasks and processing them in the background with //! independent workers and should be simple to integrate in existing //! applications and deployments. //! #![deny(missing_docs)] #[macro_use] extern crate log; #[macro_use] ext...
mod submodule_a; mod submodule_b; pub const COMMON_THING: &str = "hehehe"; pub fn common_fn() -> String { "jajaja".to_owned() } pub use submodule_a::thing_a; pub use submodule_b::thing_b;
#[doc = "Register `HYSTERESIS1` reader"] pub struct R(crate::R<HYSTERESIS1_SPEC>); impl core::ops::Deref for R { type Target = crate::R<HYSTERESIS1_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<HYSTERESIS1_SPEC>> for R { #[inline(always)] fn f...
#![allow(non_upper_case_globals)] #![allow(non_camel_case_types)] #![allow(non_snake_case)] use std::env; type size_t = usize; include!(concat!(env!("OUT_DIR"), "/bindings.rs")); #[cfg(test)] mod tests { use crate::*; use std::ptr; use std::slice; const EPSILON: tsReal = 0.0001; #[test] fn i...
use crate::{ common::ClientId, transaction::{TxId, TxType}, }; #[derive(PartialEq)] pub enum Message { NotEnoughFunds(ClientId, TxId, TxType), AlreadyInDispute(ClientId, TxId, TxType), AlreadyDisputed(ClientId, TxId, TxType), NotInDispute(ClientId, TxId, TxType), AccountIsLocked(...
use std::{ io, ops::Deref, pin::Pin, sync::Arc, task::{Poll, Context}, }; use mio::{ event::Evented, unix::EventedFd, }; use tokio::io::{AsyncRead, PollEvented}; use futures_core::{Stream, ready}; use crate::events::{ Event, EventOwned, }; use crate::fd_guard::FdGuard; use crate::u...
use super::glcall; use std::{ collections::HashMap, fs::File, io::{BufRead, BufReader, Write}, }; use nalgebra_glm as glm; pub struct Shader { _filepath: String, renderer_id: u32, uniform_location_cache: HashMap<String, i32>, } fn compile_shader(source: &str, shader_type: u32) -> u32 { l...
// This file is part of Substrate. // Copyright (C) Parity Technologies (UK) Ltd. // SPDX-License-Identifier: Apache-2.0 // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.a...
//! HTTP2 client side. use {SendStream, RecvStream, ReleaseCapacity}; use codec::{Codec, RecvError, SendError, UserError}; use frame::{Headers, Pseudo, Reason, Settings, StreamId}; use proto; use bytes::{Bytes, IntoBuf}; use futures::{Async, Future, Poll}; use http::{uri, Request, Response, Method, Version}; use tokio...
extern crate num; use num::integer::Integer; pub fn sum_of_multiples(limit: u32, factors: &[u32]) -> u32 { (1..limit) .filter(|n| factors.iter().any(|d| n.is_multiple_of(d))) .sum() }
use std::hash::*; // auto implement methods #[derive(Clone, Copy, Debug)] pub struct Point { x : i16, y : i16, } impl Point { // build a new point pub fn new (x : i16, y : i16) -> Self { Point { x : x, y : y, } } pub fn adjacent (&self, other : &Point) -> bool { if se...
#![warn(missing_docs)] #![warn(missing_debug_implementations)] #![warn(unused)] #![warn(nonstandard_style)] #![warn(rust_2018_idioms)] //! cash_addr format implementation inspired by cashaddrjs. //! # Example //! ```rust //! use cash_addr::{encode, decode, AddressType}; //! //! let data = [0xF5, 0xBF, 0x48, 0xB3, 0x9...
pub mod kafka; pub mod sockets; pub mod utils;
use caminatus::schedule::Schedule; fn main() { let schedule = Schedule::from_file("./schedules/sample.yaml".to_string()); println!("{:?}", schedule); let normalized = schedule.unwrap().normalize(); println!("{:?}", normalized); }
#![allow(unused_must_use)] #![allow(unstable)] use std::os; use std::io::File; use std::iter::Iterator; use std::iter::Peekable; use std::iter::IteratorExt; use Sugar::*; use State::*; #[derive(Copy)] enum State { Walk, Bracket, Start(Sugar), Inline(Sugar), Multiline(Sugar, u8) } #[derive(Copy)] enum Sugar { Array, ...
use std::marker::PhantomData; use std::sync::atomic::AtomicPtr; use std::sync::atomic::AtomicUsize; use std::sync::atomic::Ordering::SeqCst; use winapi::ctypes::c_void; use winapi::um::libloaderapi::{GetProcAddress, LoadLibraryA}; const UNINITIALIZED: usize = 0; const INIT_IN_PROGRESS: usize = 1; const INITIALIZED: u...
use crate::utils::intcode::IntcodeMachine; use crate::utils::Day; pub struct Day2 { machine: IntcodeMachine, } impl Day2 {} impl Day for Day2 { fn new(input: String) -> Self { let input: Vec<i128> = input .trim() .split(',') .map(|x| x.parse().ok().unwrap()) ...
mod guard; use crate::write::generic::WriteStr; use crate::LockWrite; pub use self::guard::*; use std::sync::MutexGuard; use std::io; use std::sync::Mutex; use std::fmt; ///Combining multiple `Trait Write` into one common. #[derive(Debug)] pub struct MutexWrite<T> { mutex: Mutex<T> } impl<T> MutexWrite<T> { #[in...
mod terminal; pub use self::terminal::App as TerminalApp; mod null; pub use self::null::App as Headless; mod smithay; pub use self::smithay::App as Wayland;
/*! ```compile_fail,E0277 use std::rc::Rc; let r = Rc::new(22); rayon_core::join(|| r.clone(), || r.clone()); //~^ ERROR ``` */
#[path = "adt_huffman.rs"] mod adt_huffman; use adt_huffman::{Tree, Heap}; use std::fs; use std::io::{Read, Write, Seek, SeekFrom}; pub fn compress(mut file: fs::File) -> std::io::Result<()> { let mut frequency: Vec<u64> = vec![0;256]; let f = Read::by_ref(&mut file); for i in f.bytes() { let b =...
//! The module responsible for batch generation for rendering optimizations. use crate::{ core::{ algebra::Matrix4, arrayvec::ArrayVec, math::aabb::AxisAlignedBoundingBox, pool::Handle, scope_profile, sstorage::ImmutableString, }, material::{PropertyValue, SharedMaterial}, scene::{ ...
//! `bak` is a Rust library for safely moving files out of the way. //! //! The API has a few methods, but the one to start with is //! `bak::move_aside(PATH)`. //! //! `move_aside("foo")` will move the file or directory "foo" to //! "foo.bak", if there isn't already something there. If there is //! already a file call...
use std::ops::*; use std::fmt; use num; use super::super::pbrt::Float; use super::Point3; pub type Vector3f = Vector3<Float>; pub type Vector3i = Vector3<i32>; /// Representation of a 3D Vector. #[derive(Debug, Default, Copy, Clone, PartialEq, PartialOrd)] #[repr(C)] pub struct Vector3<T> { pub x: T, pub y: T...
// This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of // the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/ //! Generation of the code for macros defining the data types. use askama::Template; use crate::definition::output::{En...
#![allow(dead_code, unused_imports, unused_must_use)] mod internal_module; mod quickjs_sys; pub use quickjs_sys::*;
#![warn(missing_docs)] #![feature(decl_macro, proc_macro_hygiene)] #[macro_use] extern crate log; extern crate env_logger; extern crate clap; use clap::{Arg, App, SubCommand,ArgMatches}; #[macro_use] extern crate rocket; extern crate rust_summer as summer; use summer::{BaseService, Service}; fn main() { //...
mod lexer; mod parser; mod syntax; mod type_def; mod typing; fn main() { let lexer = lexer::Lexer::from_file("test.txt"); }
use crate::window_base::Window; /// Main engine entry point /// /// Application should be implemented by the client's main struct. pub trait Application { /// Initialises the application fn init(&mut self) { gl::load_with(|s| self.get_window().window.get_proc_address(s)); } /// Runs the engine fn run(&mut sel...
extern crate graphers; extern crate serde; extern crate serde_json; mod schema { use serde::{Serialize, Serializer}; use serde::ser::MapVisitor; use graphers::query; pub trait ResolvePerson { fn first_name(&self) -> String; fn last_name(&self) -> String; } pub struct PersonSe...
use std::sync::Arc; pub const HASH_SIZE: usize = sys::RANDOMX_HASH_SIZE as usize; pub struct FullCache { cache_ptr: *mut sys::randomx_cache, dataset_ptr: *mut sys::randomx_dataset, } unsafe impl Send for FullCache { } unsafe impl Sync for FullCache { } impl FullCache { pub fn new(key: &[u8]) -> Self { let flag...
use std::fs::File; use std::io::prelude::*; use std::str; use super::crypt; use super::user; pub fn decrypt_session_token() -> String { let f = File::open("session_token.txt").unwrap(); let mut password = String::new(); match File::open("password.txt") { Ok(ref mut pwd_f) => { pwd_f.r...
/** * - Variáveis são block scoped, similar ao Java. * - Variáveis são por padrão imutáveis * - Variáveis guardam dados primitivos ou referências * * - Podem ser declaradas de algumas formas: * - let nome_da_variavel --- definição de variável comum, imutável por padrão, sempre snake_case * - let m...
extern crate ndarray; use crate::utils::one_hot; use ndarray::{Array, Array2, Ix2}; use std::fs::File; use std::io::{self, Read}; use std::path::Path; pub fn load_mnist<P: AsRef<Path>>( path: Vec<P>, ) -> ((Array2<f32>, Array2<f32>), (Array2<f32>, Array2<f32>)) { let mut path_iter = path.into_iter(); let ...
fn main() { let cont = [1, 2, 3]; for c in cont.iter() { println!("{}", c); } }
use std::collections::HashMap; use crate::obj::{MtlFile, MtlMaterialDefinition}; use crate::shaders::ShaderUniform; pub type MaterialKey = String; pub type ShaderKey = String; pub struct Material { name: String, shader: ShaderKey, ambient_color: [f32; 3], diffuse_color: [f32; 3], specular_color: ...
use crate::{ message::{ GetMaybeRequestId, Message, MessageProtocolVersionBound, MsgId, RequestId, SetRequestId, }, sync::{ message::{ msgid, Context, DynamicCapability, Handleable, KeyContainer, StateSyncCandidateResponse, }, request_manager::...
#![feature(macro_rules)] #![feature(asm)] pub mod numeric; #[cfg(test)] mod test { use numeric::{CryptoU64, CryptoI64, CryptoU32, CryptoI32, CryptoU8, CryptoI8}; use numeric::{CryptoU32Condition}; #[test] fn wrap_unwrap() { assert_eq!(CryptoU64::new(0x5040302010).value, 0x5040302010); ...
// Copyright (c) The Starcoin Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::cli_state::CliState; use crate::StarcoinOpt; use anyhow::Result; use clap::Parser; use itertools::Itertools; use scmd::{CommandAction, ExecContext}; use serde::Deserialize; use serde::Serialize; use starcoin_crypto::ed255...
//! Vulkan backend types. use super::ColorFormat; use gfx_device_vulkan; use gfx_window_vulkan; /// Command buffer type. pub type CommandBuffer = gfx_device_vulkan::CommandBuffer; /// Graphics device type. pub type Device = gfx_device_vulkan::GraphicsQueue; /// Graphics factory type. pub type Factory = gfx_device_v...
//! Functions with 0.5 ULP error bound use super::*; /// Evaluate sin( π***a*** ) and cos( π***a*** ) for given ***a*** simultaneously /// /// Evaluates the sine and cosine functions of π***a*** at a time, and store the two values in a tuple. /// The error bound of the returned value are `max(0.506 ULP, f32::MIN_POSI...
use crate::components::{CombatStats, Name, Player, Position, Ranged, Renderable, WantsToDropItem, WantsToUseItem}; use crate::game_log::GameLog; use crate::map::Map; use crate::systems::{ DamageSystem, ItemCollectionSystem, ItemDropSystem, ItemUseSystem, MapIndexingSystem, MeleeCombatSystem, MonsterAI, Visibili...
//! Simple multiplication algorithm. use crate::{ add, arch::{self, SignedWord, Word}, mul, sign::Sign::{self, *}, }; /// Split larger length into chunks of CHUNK_LEN..2 * CHUNK_LEN for memory locality. const CHUNK_LEN: usize = 1024; /// Max supported smaller factor length. pub(crate) const MAX_SMALL...
//! A rand_core::Rng implementation. //! Available with the `rand` feature. //! //! # Usage //! //! ```rust,no_run //! use rand_core::RngCore; //! use randomorg::Random; //! //! let mut random = Random::new("API KEY HERE"); //! let mut key = [0u8; 16]; //! random.fill_bytes(&mut key); //! let random_u64 = random.next_u...
use cgmath::Point2; use num::clamp; const MIN_WIDTH: u8 = 0; const MIN_HEIGHT: u8 = 0; pub struct Grid { points: Vec<Point2<u16>>, } impl Grid { pub fn new( center: impl Into<Point2<u16>>, ring_count: u16, max_width: u16, max_height: u16, ) -> Grid { let center_poi...
use ra_client::ClientRaContext; use ra_common::tcp::tcp_connect; use std::time::Duration; fn main() { let enclave_port = 7777; let sp_port = 1234; let localhost = "localhost"; let timeout = Duration::from_secs(5); let mut enclave_stream = tcp_connect(localhost, enclave_port, timeout).expec...
//! Traits for immutable access to a HandleGraph, including its //! nodes/handles, edges, and the sequences of nodes. //! //! With the exception of [`HandleGraph`] and [`HandleGraphRef`], each of //! these traits are centered on providing iterators to one specific //! part of a graph. For instance, [`IntoNeighbors`] gi...
use std::mem; use std::str::CharIndices; use crate::BytePos; #[derive(Clone, Debug, PartialEq)] pub enum Token { // Identifiers Ident(String), // Literals Litrl(String), // Punctuation Comma, Semicolon, Colon, LeftParen, RightParen, LeftCurlyBrace, ...
//! Main function of the weaver server. //! use chrono::prelude::*; use crate::cli::ServerRun; use crate::cli::{parse, CommandAndConfig, ServerSubCommand}; use daemonize::{self, Daemonize}; use lib_db::SqlStore; use lib_error::*; use lib_goo::config::db::PasswordSource; use lib_goo::config::{file_utils, ServerConfig}; ...
use std::fmt::Debug; use ton::Player; use ton::Sample; use crate::state::DAY_LENGTH; pub struct Time { pub start: std::time::Instant, pub day_time: f32, } impl Default for Time { fn default() -> Self { Self { start: std::time::Instant::now(), day_time: 0.5, } } ...
use std::fs; fn main() -> std::io::Result<()> { let input = fs::read_to_string("../resources/input.txt")?; let first_result: i32 = input.lines().map(|line| { calculate(line.parse().unwrap()) }).sum(); let second_result: i32 = input.lines().map(|line| { let mut result = 0; let m...
use super::constants::ERRBUF_SIZE; use crate::common::InterfaceDescription; use crate::utils::cstr_to_string; use libc::{c_char, c_uchar, c_uint, c_ushort, c_void, timeval}; use std::ffi::CStr; use std::mem::MaybeUninit; ///Raw PCap handle - created only to allow construction of pointers. pub enum PCapHandle {} ///Ra...
use std::os::raw::{c_char, c_void}; use wayland_sys::common::*; const NULLPTR: *const c_void = 0 as *const c_void; static mut types_null: [*const wl_interface; 3] = [ NULLPTR as *const wl_interface, NULLPTR as *const wl_interface, NULLPTR as *const wl_interface, ]; static mut zwp_tablet_manager_v2_requests_...
// Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0. use criterion::*; mod yatp_callback { use criterion::*; use std::sync::mpsc; use yatp::task::callback::Handle; pub fn chained_spawn(b: &mut Bencher<'_>, iter_count: usize) { let pool = yatp::Builder::new("chained_spawn").build...
use ethsign::{KeyFile, Protected, SecretKey}; use serde_json; use std::collections::HashMap; use std::fs::{self, DirEntry, File}; use std::io; use std::path::Path; use web3::types::Address; pub fn list_keys(keystore: &Path) -> io::Result<HashMap<String, Address>> { let mut keys: HashMap<String, Address> = HashMap:...
mod command; mod environment; mod kernel_parameter_manager; pub mod logging; mod managed_kernel_parameter; mod rule; mod target; pub use command::Command; pub use environment::Environment; pub use kernel_parameter_manager::KernelParameterManager; pub use managed_kernel_parameter::ManagedKernelParameter; pub use rule::...
// Copyright 2019 Intel Corporation. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 use super::super::{Descriptor, Queue}; use super::{Error, Result}; use crate::{get_host_address_range, VirtioInterrupt, VirtioInterruptType}; use std::convert::TryInto; use std::os::unix::io::AsRawFd; use std::sync::Arc; u...
use super::Location; struct Plane<T> { // NOTE: when you call a Plane you have to enter a dummy T of any type loc: Location, data: Option<T>, } impl<T> Plane<T> { fn new(loc: Location) -> Self { Self { loc, data: None, } } } #[cfg(test)] mod test {...
#![allow(clippy::enum_glob_use)] use anyhow::{anyhow, Context, Result}; use std::{fs, iter::Iterator, str}; #[derive(Debug, Default)] struct PassportRaw<'a> { byr: Option<&'a str>, iyr: Option<&'a str>, eyr: Option<&'a str>, hgt: Option<&'a str>, hcl: Option<&'a str>, ecl: Option<&'a str>, ...
use std::str::FromStr; use actix_web::{HttpRequest, HttpResponse, web}; use serde_json::Value; use crate::dbconfig::{MysqlPool, MySqlPooledConnection}; pub fn mysql_pool_handler(pool: web::Data<MysqlPool>) -> Result<MySqlPooledConnection, HttpResponse> { pool.get() .map_err(|e| HttpResponse::InternalServ...
use std::error::Error; use std::fs::{self, DirEntry}; use std::io; use crate::commands::factory::RespondingCommand; use crate::models::commands::GetFolder as GetFolderModel; use crate::models::responses::{FolderNode, FolderResponse}; use crate::services::disk_path; pub struct GetFolder { pub model: GetFolderModel...
mod non_packed; mod update;
use crate::study::operation::{Operation, OperationKey}; use crate::study::subscriber::{SubscribeId, Subscriber}; use crate::study::{ Message, Seconds, StudyDirection, StudyId, StudyName, StudyNameAndId, StudySummary, }; use crate::time::Timestamp; use crate::trial::{Trial, TrialId, TrialParamValue, TrialState}; use...
// Copyright 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-MIT or ...
use crate::resource::{File, Resource, ResourceKey, Text, Texture}; use anyhow::*; use log::{debug, error}; use notify::{watcher, DebouncedEvent, ReadDirectoryChangesWatcher, RecursiveMode, Watcher}; use std::{collections::HashMap, path::PathBuf, sync::Arc, time::Duration}; pub struct ResourceManager { root:...
#[macro_use] extern crate serde_derive; extern crate image; extern crate rayon; extern crate indicatif; pub mod scene; mod rendering; mod vector; mod matrix; mod point; use indicatif::ProgressBar; use rayon::prelude::*; use scene::{Scene, Color, Intersection}; use image::{DynamicImage, GenericImage, Rgba, Pixel}; use...
use rppal::gpio::{Gpio, Level}; use rppal::system::DeviceInfo; const GPIO_PIN_CLK: u8 = 15; const GPIO_PIN_DAT: u8 = 14; fn main() { match run() { Ok(_) => {} e => { eprintln!("Error: {:?}", e); } } } #[tokio::main] async fn post_request(data: f32) -> Result<(), reqwest::...
extern crate gl_generator; extern crate gl_generator_profiling_struct; use gl_generator::{Registry, Fallbacks, Api, Profile}; use gl_generator_profiling_struct::ProfilingStructGenerator; use std::env; use std::fs::File; use std::path::Path; fn main() { let out_dir = env::var("OUT_DIR").unwrap(); let mut file...
use serde::{Deserialize, Serialize}; #[derive(Clone, Deserialize, Serialize)] #[cfg_attr( feature = "config-schema", derive(schemars::JsonSchema), schemars(deny_unknown_fields) )] #[serde(default)] pub struct OCamlConfig<'a> { pub format: &'a str, pub version_format: &'a str, pub global_switch_...
#![feature(test)] extern crate test; use test::{black_box, Bencher}; extern crate integer_sqrt; use integer_sqrt::IntegerSquareRoot; // Use f64::sqrt to compute the integer sqrt fn isqrt_via_f64(n: u64) -> u64 { let cand = (n as f64).sqrt() as u64; // Rounding can cause off-by-one errors if let Some(prod...
use crate::core::definition; use crate::core::implementation; pub struct Enum { pub ident: syn::Ident, } impl From<&definition::Enum> for Enum { fn from(enum_definition_ref: &definition::Enum) -> Self { Enum { ident: format_ident!("{}flexpilerDeserializer", enum_definition_ref.ident), ...
#![allow(dead_code)] extern crate winapi; #[macro_use] extern crate log; extern crate serde; #[macro_use] extern crate serde_derive; extern crate serde_json; extern crate toml; #[macro_use] extern crate crossbeam_channel; extern crate tungstenite; mod config; pub use config::*; mod hook; pub use hook::Hook; mod i...
#![feature(proc_macro_diagnostic)] //! You probably want documentation for the [`hotpatch`](https://docs.rs/hotpatch) crate. use proc_macro::TokenStream; use std::sync::RwLock; use syn::{parse::Nothing, ItemFn, ItemImpl, Path}; mod item_fn; mod item_impl; lazy_static::lazy_static! { static ref EXPORTNUM: RwLock...
// This file is part of Substrate. // Copyright (C) Parity Technologies (UK) Ltd. // SPDX-License-Identifier: Apache-2.0 // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.a...
#[aoc_generator(dayX)] pub fn input_generator(input: &str) -> i32 { 3 } #[aoc(dayX, part1)] pub fn part1(input: &i32) -> usize { 2 } #[aoc(dayX, part2)] pub fn part2(input: &i32) -> usize { 1 } #[cfg(test)] mod tests { use super::{input_generator, part1, part2}; #[test] fn sample1() { ...
// Copyright 2020 The Bazel Authors. All rights reserved. // // 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 appl...