text
stringlengths
8
4.13M
use crate::class_file::class_file::ClassFile; use crate::class_loader::class_init_preparation::ClassPreparation; use crate::class_path::class_path::{ClassPath, Entry}; use crate::instrument::java_lang_instrument::JavaLangInstrument; use crate::interpreter::invoke_java_method; use crate::invoke_support::parameter::{Para...
use std::collections::HashMap; use std::fs::File; use std::io::{BufReader, BufWriter, Write}; use xml::reader::{EventReader, XmlEvent}; use std::io::Seek; use std::io::SeekFrom; use crate::campaign::SearchTag; use crate::elements::{find_attribute, Element, ElementType, LatLng, Tag}; fn serialize_counter(hashmap: ...
use crate::api::OpenWeatherMap; use crate::auth; use crate::command; use crate::module; use crate::prelude::*; use anyhow::Result; use uom::si::{ f32::ThermodynamicTemperature, thermodynamic_temperature::{degree_celsius, degree_fahrenheit, kelvin}, Unit as _, }; #[derive(Debug, Clone, Copy, serde::Deserial...
pub mod libm; pub mod shared; pub use test::unix::libm::LIBM;
use std::fs::{self, File}; use std::io::BufReader; use img_parts::webp::WebP; use img_parts::ImageEXIF; #[test] fn extract_webp_noprofile() { extract_webp_image("P1133897.webp", None); } #[test] fn extract_webp_srgb() { extract_webp_image("P1133897_sRGB.webp", Some("P1133897_sRGB.exif")); } #[test] fn extra...
//! Source-level operations. //! //! Reading a JavaScript text source file into an AST. mod parser; pub use self::parser::SourceParser; /// Parsing JavaScript using the Shift source parser (in Node). pub mod shift; pub use self::shift::Shift;
//! High-level storage pool object methods. //! //! They provide abstraction on top of aio and uring bdev, lvol store, etc //! and export simple-to-use json-rpc methods for managing pools. use std::{ffi::CStr, os::raw::c_char}; use ::rpc::mayastor as rpc; use spdk_sys::{ lvol_store_bdev, spdk_bs_free_cluster_...
#![recursion_limit = "128"] extern crate proc_macro; extern crate proc_macro2; #[macro_use] extern crate quote; extern crate syn; use proc_macro2::{Ident, Span}; use quote::TokenStreamExt; #[proc_macro_derive(Address, attributes(address_repr))] pub fn address(input: proc_macro::TokenStream) -> proc_macro::TokenStream...
#![allow(warnings)] mod question_10; mod question_11; mod question_1_7; mod question_8; mod question_9; fn main() { ownership_moved(); copy_trait(); clone_trait(); borrow_reference(); slice(); object_method(); let ymd = "yyyy-mm-dd"; let year = &ymd[0..4]; let month = &ymd[5..7]; ...
extern crate image; extern crate nalgebra; extern crate piston_window; extern crate kiss3d; extern crate serde_json; extern crate mono_slam; extern crate stats; use kiss3d::light::Light; use kiss3d::window::Window; use mono_slam::app_state::AppState; use mono_slam::camera_model::WideAngleCameraModel; use mono_slam::vi...
use std::sync::Arc; use futures::{future, StreamExt}; use nimiq_blockchain_interface::AbstractBlockchain; use nimiq_bls::KeyPair as BlsKeyPair; use nimiq_consensus::{Consensus, ConsensusEvent}; use nimiq_database::DatabaseProxy; use nimiq_genesis_builder::{GenesisBuilder, GenesisInfo}; use nimiq_keys::{Address, KeyPai...
use anyhow::{Result, bail}; use std::collections::{BTreeMap, HashMap, HashSet}; use std::convert::{TryFrom}; use core::num::TryFromIntError; use std::ops::RangeInclusive; use std::iter::FromIterator; use std::cmp::Ordering; use std::path::Path; use std::io::Read; use std::io::BufWriter; use crate::charsets::bi...
#[doc = "Register `FLCTL_BMRK_CTLSTAT` reader"] pub struct R(crate::R<FLCTL_BMRK_CTLSTAT_SPEC>); impl core::ops::Deref for R { type Target = crate::R<FLCTL_BMRK_CTLSTAT_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<FLCTL_BMRK_CTLSTAT_SPEC>> for R { ...
//! Utility functions for assisting with conversion of headers from and to the HTTP text form. use std::vec; use std::ascii::Ascii; use rfc2616::{is_token, is_token_item}; /// Normalise an HTTP header name. /// /// Rules: /// /// - The first character is capitalised /// - Any character immediately following `-` (HYPH...
pub mod auth_controller; pub mod user_controller; use rocket::Route; pub fn routes() -> Vec<Route> { routes![ auth_controller::users_login, auth_controller::users_register, user_controller::get_user_options, user_controller::get_user_inbox, ] }
use std::char; use std::fmt; #[derive(Clone, Copy, PartialEq, Debug)] pub struct Cell { pub file: char, pub row: i32 } impl Cell { #[allow(dead_code)] pub fn new(cell_name: &str) -> Cell { Cell { file: cell_name.chars().nth(0).unwrap(), row: cell_name.chars().nth(1).unw...
use core::any::{Any, TypeId}; use core::ops::Deref; use core::mem; use core::ptr; use common::*; use spin::{Mutex}; use util::{MemoryObject}; use super::{ManagedArc, ManagedArcAny, ManagedArcInner, ManagedWeakAddr, ManagedWeakNode}; /// Managed weak pool of size 1. pub struct ManagedWeakPool1([Mutex<Option<ManagedWea...
use crate::listener::{self, Listener}; use crate::metainfo::MetaInfo; use crate::InfoHash; use crate::{peer_protocol, signals}; use crate::{PeerId, Port}; use rand::prelude::IteratorRandom; use rand::{thread_rng, Rng}; use sha1::Digest; use std::collections::{HashMap, HashSet}; use std::convert::{TryFrom, TryInto}; use...
use clap::{App, Arg}; pub static SOCKET: &str = "SOCKET"; pub fn create_app() -> App<'static, 'static> { App::new("Timetracker core") .version("1.0") .author("Samuli S. <samuli.suortti@gmail.com>") .about("") .arg(Arg::with_name(SOCKET).required(true)) }
extern crate actix; extern crate actix_web; extern crate futures; use actix_web::*; use actix_web::http::Method; use futures::*; pub fn handle_multipart_field(field: multipart::Field<HttpRequest>) -> Box<Future<Item=i64, Error=Error>> { use std::fs; use std::io::Write; let file_path_string = "upload.png";...
fn main() { println!("{} day", 1); println!("{0} or {1}: {0}", "Yes", "No"); println!("{blue} {green} {red}", red = "red", green = "green", blue = "blue"); println!("binary representation: {:b}", 7); println!("right align fill with spaces:{:>5}", 3); printl...
use serde::Deserialize; use std::path::Path; use tokio::{ fs::File, io::{AsyncReadExt, BufReader}, }; #[derive(Deserialize)] #[serde(rename_all = "kebab-case")] /// Struct holding the email configuration values pub struct ConfigurationEmail { pub active: bool, pub server: String, pub starttls: boo...
#[macro_use] pub mod macros; pub mod matrix;
//! Receive talkers messages for a few seconds and store them in a Vec. use talkers; use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4, TcpListener}; use std::sync::{Arc, Mutex}; use std::thread; use std::time; use std::time::{SystemTime, UNIX_EPOCH}; fn main() { let bind_to = SocketAddr::V4(SocketAddrV4::new(Ip...
use std::fs::File; use std::io; use std::io::Read; use std::path::Path; use std::{thread, time::Duration}; pub fn read_from_file(path_of_file:&std::path::Path) -> Result<String, io::Error> { let mut f = File::open(path_of_file)?; let mut s = String::new(); f.read_to_string(&mut s)?; Ok(s) } fn mai...
fn main() { // A tuple is an ordered list of fixed size let x1 = (1, "hello"); // or let x2: (i32, &str) = (1, "hello"); // You can assign one tuple into another, if they have // the same contained types and arity (arity refers to the number // of arguments a function or operation takes). T...
fn main() { //Args is an iterator. We want to skip the first element because that is the program name, so we can use the methord "skip()". let mut args = std::env::args().skip(1); //In rust language: binding to a variable //In rust, everything is immutable by default in contrast to most other languages. Th...
use std::cell::RefCell; use std::env; use std::rc::Rc; use std::time::Duration; use anyhow::anyhow; use clap::{App, AppSettings, Arg, ArgMatches, SubCommand}; use mun_compiler::{Config, DisplayColor, PathOrInline, Target}; use mun_runtime::{invoke_fn, ReturnTypeReflection, Runtime, RuntimeBuilder}; fn setup_logging()...
/* * The texture manager coordinates the allocation of textures, especially those, that are loaded * from SDL Surfaces and May be used more than just one time. */ extern crate sdl2; use sdl2::pixels::Color; use sdl2::render::{Texture, Renderer}; use sdl2::surface::Surface; use sdl2::{SdlResult}; use std::collectio...
use std::char; extern crate md5; macro_rules! has_5_consec_zeroes { // https://doc.rust-lang.org/beta/book/macros.html ($a : expr) => ( // 以下为宏展开内容. ($a.chars().nth(1).unwrap()==char::from_digit(0, 10).unwrap())&& // ($a.chars().nth(2).unwrap()==char::from_digit(0, 10).unwrap())&& ...
#[doc = "Reader of register WAY[%s]"] pub type R = crate::R<u32, super::WAY>; #[doc = "Writer for register WAY[%s]"] pub type W = crate::W<u32, super::WAY>; #[doc = "Register WAY[%s] `reset()`'s with value 0"] impl crate::ResetValue for super::WAY { type Type = u32; #[inline(always)] fn reset_value() -> Sel...
pub struct Solution {} impl Solution { pub fn restore_ip_addresses(s: String) -> Vec<String> { let mut results = vec![]; let mut hand = vec![]; let mut packet = vec![]; Self::backtrack(s.as_bytes(), &mut hand, &mut packet, &mut results); results } fn backtrack( ...
//! Treiber's stack use std::mem; use std::ptr; use std::sync::atomic::AtomicPtr; use std::sync::atomic::Ordering; use garbage_queue::{self, Garbage, Pause}; #[derive(Debug)] pub struct Stack<T> { top: AtomicPtr<Node<T>>, } impl<T> Stack<T> { pub fn new() -> Self { Stack { top: AtomicPtr:...
#![macro_use] use ffi; pub trait RawConversion<T> { fn as_raw(&self) -> T; fn from_raw(T) -> Self; } macro_rules! raw_conversion { ($inp: ty, $raw: ty) => ( impl RawConversion<$raw> for $inp { fn as_raw(&self) -> $raw { ::std::num::FromPrimitive::from_u64(*self as u64).unwrap() } f...
mod config; mod connector; mod domain; mod handler; mod persistence; mod service; use clap::{load_yaml, App, ArgMatches}; use handler::{ handle_add, handle_config_argument, handle_connect, handle_init, handle_list, handle_remove, handle_test, }; /// Command line todo application /// Below actions can be perfo...
fn main() { let n = 1; let x: Vec<_> = (0..6).map(|_| n).collect(); println!("{:#?}", x); }
use rand::{RngCore, SeedableRng}; use rand_chacha::ChaCha20Rng; /// Initialize the rng with entropy. /// /// Note that we use this to reseed as there's no way to reseed right now. /// We should re-implement this or better delegate it to the crypto provider. pub(crate) fn init() -> ChaCha20Rng { ChaCha20Rng::from_e...
use specs::prelude::*; use crate::{ MyTurn, MoveMode, Movement, Position, Map, EntityMoved, RandomNumberGenerator, }; pub struct DefaultMoveAI {} impl<'a> System<'a> for DefaultMoveAI { type SystemData = ( WriteStorage<'a, MyTurn>, ReadStorage<'a, MoveMode>, Wr...
use super::super::{DiscoveryHandler, DiscoveryResult}; use super::{discovery_impl::do_standard_discovery, OPCUA_DISCOVERY_URL_LABEL}; use akri_shared::akri::configuration::{OpcuaDiscoveryHandlerConfig, OpcuaDiscoveryMethod}; use async_trait::async_trait; use failure::Error; /// `OpcuaDiscoveryHandler` discovers the OP...
struct Solution; impl Solution { fn min_available_duration( mut slots1: Vec<Vec<i32>>, mut slots2: Vec<Vec<i32>>, duration: i32, ) -> Vec<i32> { slots1.sort_unstable_by_key(|v| v[0]); slots2.sort_unstable_by_key(|v| v[0]); let n = slots1.len(); let m = sl...
use crate::model::version::{DistributionGroup, Version}; pub struct VersionList {} impl VersionList { pub fn latest_version(versions: Vec<Version>) -> Option<Version> { VersionList::sort_versions(versions).first().cloned() } pub fn latest_version_of_distribution_group( versions: Vec<Versio...
extern crate encoding; extern crate ascii; extern crate chrono; extern crate chunked_transfer; use std::sync::Arc; use std::sync::atomic::AtomicBool; use std::sync::atomic::Ordering; use std::net::{SocketAddr, ToSocketAddrs, TcpListener, TcpStream, Shutdown}; use std::thread; use std::time::Duration; use std::error::E...
use assert_cmd::prelude::*; use std::process::Command; #[test] fn personal_input() -> Result<(), Box<dyn std::error::Error>> { let mut command = Command::cargo_bin("advent_15")?; command.arg("input"); command.assert().success().stdout("1280\n651639\n"); Ok(()) }
#[macro_use] extern crate log; #[macro_use] extern crate cfg_if; extern crate serde; #[macro_use] extern crate serde_derive; extern crate serde_json as json; extern crate futures; extern crate tokio_reactor; extern crate tokio_current_thread; extern crate sandbox_ipc as ipc; cfg_if! { if #[cfg(target_os = "windows...
#![feature(btree_range, collections_bound)] #![deny(missing_docs)] //! Overview //! --------- //! This library contains the internal data structure used by the ironstrom project //! //! Design goals //! --------------- //! - Lightning fast auto completion / type ahead lookups (~200 microseconds! per lookup) //! - Not...
#![feature(panic_implementation)] #![no_std] #![cfg_attr(not(test), no_main)] use core::panic::PanicInfo; #[cfg(not(test))] #[panic_implementation] #[no_mangle] pub fn panic(info: &PanicInfo) -> ! { loop {} } extern crate volatile; #[macro_use] extern crate lazy_static; extern crate spin; #[cfg(not(test))] #[no_...
extern crate rand; use rand::Rng; use rand::distributions::Alphanumeric; use crate::peers::Peer; use crate::tracker::Tracker; use crate::torrent_file::{TorrentInfo}; use crate::utils::{TorrentChannel, TorrentEventType, TorrentEvent}; use std::sync::{Arc, Mutex}; use std::thread::JoinHandle; use std::io; use std::io:...
use super::Instance; #[derive(Default)] pub struct MusicTheme { instance_symbol: usize, file: String, vol: f32, loop_: i32, reverb_mix: f32, reverb_time: f32, trans_type: i32, trans_sub_type: i32, } impl MusicTheme { pub fn new() -> Self { Default::default() } } impl Ins...
pub mod binary_search_tree; pub mod binary_tree; pub mod priority_queue; pub use binary_search_tree::*; pub use binary_tree::*; pub use priority_queue::*;
use geometry::{Plane, Ray, Vec3, CollisionDirection}; pub fn trace<T:Plane>(ray: &Ray, model: &T, lights: &[Vec3], ambient_intensity: f64, diffuse_reflection_constant: f64, specular_reflection_constant: f64, transmission_coefficient: f64, max_depth: u8) -> f64 { trace_down(ray, model, lights, ...
use autovec_demo::*; use criterion::{black_box, criterion_group, criterion_main, Criterion}; const BENCHMARK_SAMPLES: usize = 100_000; fn criterion_benchmark(c: &mut Criterion) { let src = vec![0.0; BENCHMARK_SAMPLES]; let mut dst = vec![0.0; BENCHMARK_SAMPLES * 2]; c.bench_function("attempt 1", move |b| ...
use crate::citaprotocol::pubsub_message_to_network_message; use crate::config::NetConfig; use bytes::BytesMut; use crossbeam_channel; use crossbeam_channel::{select, tick, unbounded}; use discovery::RawAddr; use fnv::FnvHashMap; use libproto::{Message as ProtoMessage, TryInto}; use log::{debug, trace, warn}; use p2p::{...
use std::fmt::Debug; use std::path::PathBuf; use std::ffi::OsStr; use prelude::*; use config::RuntimeConfig; use ctx::Context; use utils::cmd::CommandBuilder; pub trait Runtime<'a>: Debug + Sync { /// Return the context this runtime was created from. fn ctx(&'a self) -> &'a Context; /// Return the contex...
use ndarray::prelude::*; //use rayon::prelude::*; //use ndarray_parallel::prelude::*; //use ndarray::Zip; use ndarray::{Data, RemoveAxis, Zip}; use std::cmp; use std::time::{Duration, Instant}; use std::fmt::format; use std::error::Error; use std::fs::File; use std::io::prelude::*; //use std::path::Path; //use std::...
// Copyright 2019 German Research Center for Artificial Intelligence (DFKI) // Author: Clemens Lutz <clemens.lutz@dfki.de> // // Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or // http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or // http://opensource.org/licenses/MIT>, at you...
#![no_std] pub extern crate atmega168_hal as hal; /// See [`avr_device::entry`](https://docs.rs/avr-device/latest/avr_device/attr.entry.html). #[cfg(feature = "rt")] pub use hal::entry; mod pins; pub use crate::atmega168::Peripherals; pub use crate::pins::*; pub use atmega168_hal::adc; pub use atmega168_hal::atmega1...
use crate::api::auth_middleware::Auth; use crate::db::Conn; use crate::errors::Errors; use crate::services::user_service; use rocket::http::Status; use rocket_contrib::json::JsonValue; #[get("/user/options")] pub fn get_user_options(auth: Option<Auth>, conn: Conn) -> Result<JsonValue, Errors> { let user_id = auth...
pub mod bioinspired { //! # Biologically inspired vision models and derivated tools //! //! The module provides biological visual systems models (human visual system and others). It also //! provides derivated objects that take advantage of those bio-inspired models. //! //! [bioinspired_retina] use crate::{mo...
//! Remote api client for [Weaver](../weaver/index.html). pub mod client;
use arc_swap::*; use async_trait::*; use rusqlite::{Connection, OpenFlags}; use serde::Serialize; use serde::de::DeserializeOwned; use std::ops::{Deref, DerefMut}; use std::path::{PathBuf, Path}; use std::time; use std::sync::Arc; use sylphie_core::prelude::*; use sylphie_utils::strings::StringWrapper; use tokio::runti...
// Copyright 2018 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 ...
//! General tests that check the heap internals extern crate alloc; use core::mem::size_of; use std::cmp; use std::ptr; use std::slice; use std::vec::Vec; use crate::o1heap::{ log_2_floor, o1heap_allocate, o1heap_do_invariants_hold, o1heap_free, o1heap_get_diagnostics, o1heap_init, Fragment, O1HeapDiagnostic...
use std::ops::Index; use std::cmp::PartialEq; pub struct Ubd<T> { ubd: Vec<T>, } impl<T: PartialEq<&'static str>> Ubd<T> { pub fn new() -> Ubd<T> { Ubd { ubd: Vec::new() } } pub fn push(&mut self, ubd: T) { if !ubd.eq(&"엄복동") { panic!("엄복동 하나만 기억해주세요"); } i...
use std::thread; use std::time::Duration; use indicatif::ProgressBar; fn main() { let pb = ProgressBar::new(1024); for _ in 0..1024 { pb.inc(1); thread::sleep(Duration::from_millis(5)); } pb.finish_with_message("done"); }
use std::net::{Ipv4Addr, SocketAddrV4}; use c_wrapper::{file::FileDescriptor, fork::{ForkResult, fork}, pipe::pipe}; use socket2::*; use uuid::Uuid; use crate::env_util::env_is_true; pub(crate) fn server(command: &[String]) -> crate::Result<u8> { let socket_debug = env_is_true("socket_debug"); let port = if command...
extern crate actix; use actix::prelude::*; struct MyActor; impl Actor for MyActor { type Context = Context<Self>; fn started(&mut self,ctx: &mut Context<Self>) { let _addr = ctx.address(); } } fn main() { System::new("test"); let _addr = MyActor.start(); }
/* This module handles configuration. Ideally it should depend only on constants. * */ use std::fs::{File,OpenOptions}; use std::io; use std::io::{Write,Read}; use std::path::{Path,PathBuf}; use constants::{get_default_config_path, CURRENT_CONFIG_VERSION}; use models::{DisplayMaster,SimpleValue,format_value}; use ...
use super::super::driver::{DeviceType, Driver, DRIVERS}; use alloc::sync::Arc; use spin::Mutex; use virtio_drivers::{VirtIOBlk, VirtIOHeader}; use alloc::vec::Vec; /// virtio 协议的块设备驱动 struct VirtIOBlkDriver(Mutex<VirtIOBlk<'static>>); /// 为 [`VirtIOBlkDriver`] 实现 [`Driver`] trait /// /// 调用了 [`virtio_drivers`] 库,其中规定...
use crate::base; use crate::func::actions as fa; use crate::func::Func; use base::Action as _; use super::*; #[derive(Debug)] pub enum Error { NotApplicable(Action, Path), } #[derive(Clone, Debug)] pub enum Action { ActOnStart(fa::Action), ActOnEnd(fa::Action), Reverse, // Induction. Induct...
extern crate neon; use neon::vm::{Call, Result, JS, Module}; use neon::value::{Integer,String}; use neon::mem::Handle; fn common_prefix_length(word: &str, previous: &str) -> i32 { match word.chars() .zip(previous.chars()) .position(|(a, b)| a != b) { Some(l) => { return l as i32; }, ...
#![allow(overflowing_literals)] type NanoSecond = u64; type Inch = u64; #[allow(non_camel_case_types)] type u64_t = u64; fn casts() { let decimal = 65.324_f32; let integer = decimal as u8; let character = integer as char; println!("{}, {}, {}", decimal, integer, character); let nano: NanoSecond ...
extern crate byteorder; use std::io::{self, Read, Write, Seek, SeekFrom}; use num::Bounded; use std::fmt; use self::byteorder::{BigEndian, ReadBytesExt}; /// The fields in an ID3v1 tag, including the "1.1" track number field. #[derive(Copy, Clone)] #[allow(missing_docs)] pub enum Fields { Title, Artist, A...
use std::fs::File; use std::io::prelude::*; mod chip8; fn main() { let mut rom: [u8; 3584] = [0; 3584]; let mut file = File::open("test.rom").unwrap(); file.read(&mut rom).unwrap(); let mut vm = chip8::VM::new(); vm.load(rom); vm.cycle(); }
// day03 use std::env; use std::error::Error; use std::fs::File; use std::io::{ self, prelude::*, BufReader, }; // CLI arguments type Args = Vec<String>; // Moves that can be made #[derive(Debug, Clone, PartialEq)] enum Direction { Up(usize), Down(usize), Left(usize), Right(usize), } impl...
use crate::entity::tile::Tile; use crate::misc::random::{Seed,RNG,from_seed, next_u32}; use std::collections::HashMap; const WIDTH: i32 = 50; const HEIGHT: i32 = 50; const ITERS: i32 = 5; /// Map Type /// /// A Map is a HashMap which associates positions to Tiles. pub type Map = HashMap<MapIdx, Tile>; /// MapIdx T...
use chrono::NaiveDateTime; use diesel; use diesel::prelude::*; use crate::schema::user; #[derive(Queryable, Serialize, Deserialize)] pub struct User { pub id: String, pub first_name: String, pub last_name: String, pub email: String, pub name: String, pub create_at: NaiveDateTime, pub avata...
pub fn run() { }
// init.rs // AltOSRust // // Created by Daniel Seitz on 12/9/16 // FIXME: Try to see if there's a better way to handle this for testing // We do this cfg for testing purposes, this allows doctests to run without any compilation errors. #![cfg(not(test))] //! Contains functions used for initialization of the kernel ...
#[allow(unused_imports)] use serde_json::Value; #[derive(Debug, Serialize, Deserialize)] pub struct JobStatisticsJobNodeMemoryPhysical { /// The average physical memory utilization of the job on this node, in KB. #[serde(rename = "average")] pub average: Option<f32>, /// The current physical memory uti...
use proconio::input; fn main() { input! { a: isize, b: isize } if a * b % 2 == 0 { println!("Even"); } else { println!("Odd"); } }
use std::{ pin::Pin, task::{Context, Poll}, }; use actix_service::{Service, Transform}; use actix_web::{ dev::ServiceRequest, dev::ServiceResponse, error::ErrorUnauthorized, http::header, Error, }; use futures::future::{ok, Ready}; use futures::Future; use crate::token::decodetoken; pub struct Auth; imp...
use std::net::SocketAddr; use std::thread; use crossbeam_channel::{Receiver, Sender, TryRecvError}; use laminar::{ErrorKind, Packet, Result, Socket, SocketEvent}; use crate::message::{deserialize, serialize, Message}; use crate::network::config::NetworkConfig; pub mod config; pub mod constants; pub enum NetworkEven...
// Load modules pub mod handlers; pub mod db; pub mod schema; pub mod models; use actix_files as fs; use actix_web::{web, middleware, App, HttpServer}; use tera::Tera; #[macro_use] extern crate diesel; #[actix_rt::main] async fn main() -> std::io::Result<()> { std::env::set_var("RUST_LOG", "actix_web=info"); ...
use byteorder::ReadBytesExt; use std::io::Cursor; use byteorder::{LittleEndian}; use std::fs; use std::fs::{OpenOptions, File}; use crate::protocol::errors::Errors; /// tests if a bit is set in a byte pub fn bit_at(byte: u8, n: u8) -> bool { if n < 32 { return byte & (1 << n) != 0; } else { return false...
use token; use roo_impl; use roo_impl::Impl as Impl; use common::ParseError as ParseError; use type_name; #[test] fn just_target() { let tokens = token::tokenize_string("impl Application {".to_string(), "code.roo".to_string()); let (impl_result, seek) = roo_impl::get_impl(&tokens, 1); assert_target(&impl_...
pub mod assembly; pub mod instruction;
use criterion::{black_box, criterion_group, criterion_main, BenchmarkId, Criterion}; use voting_map::{election, Point}; fn criterion_benchmark(c: &mut Criterion) { let candidates = vec![ Point::new(0.12, 0.28), Point::new(0.85, 0.7), Point::new(0.39, 0.28), Point::new(0.97, 0.14), ...
use std::io::{self, Read}; use std::fs::File; fn main() { match read_from_file() { Ok(s) => println!("The content of the file is {}", s), Err(err) => panic!("Couldn't read the file {:?}", err), }; } fn read_from_file()->Result<String, io::Error> { let mut f = File::open("hello.txt")?; ...
use memory::*; use ram::*; use ppu::*; use apu::*; use controller::*; use std::rc::Rc; use std::cell::RefCell; pub struct MemoryBus<'a> { rom: Rc<RefCell<Box<Memory>>>, ram: Box<Memory>, ppu: Rc<RefCell<Ppu<'a>>>, apu: Rc<RefCell<Apu<'a>>>, controllers: Vec<Rc<RefCell<Controller>>>, } impl<'a> Me...
#[macro_use] extern crate criterion; use criterion::{criterion_group, criterion_main, Criterion}; use cave::grid::{Grid, GridPosition}; use cave::pathfinding::{AStar, Locomotion, NoOpCost, NoOpLocomotion, Pathfinder, GO_ANYWHERE}; fn pathfinding_benchmark(c: &mut Criterion) { c.bench_function("Bench Pathfinding ...
// Copyright (c) 2015 Brandon Thomas <bt@brand.io> pub mod soap; pub mod ssdp;
#[doc = "Reader of register FORCEOFF"] pub type R = crate::R<u32, super::FORCEOFF>; #[doc = "Writer for register FORCEOFF"] pub type W = crate::W<u32, super::FORCEOFF>; #[doc = "Register FORCEOFF `reset()`'s with value 0x01"] impl crate::ResetValue for super::FORCEOFF { type Type = u32; #[inline(always)] fn...
fn is_palindrome(x: u64, y: u64) -> bool { let mult_str: String = (x*y).to_string(); mult_str == mult_str.chars().rev().collect::<String>() } fn main() { let mut largest: u64 = 0; for i in 100..999 { for j in 100..999 { if is_palindrome(i, j) && i*j > largest { largest = i * j } } } pr...
// 5 5 5 5 = 5 // // + 0 // - 1 // * 2 // / 3 // fn calc(mut num: Vec<f64>, mut op: Vec<i32>) -> f64 { let mut index: usize = 0; if op.len() == 0 { return num[0]; } while index != op.len() { if op[index] < 2 { index += 1; } else { if op[in...
// 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...
use std::collections::BTreeSet; const INPUT: &'static str = include_str!("input.txt"); fn main() { let mut output = 0; let mut frequency_history = BTreeSet::new(); let mut duplicate_found = false; let mut iteration_count = 0; while !duplicate_found { println!("Iteration {} output: {}", iteration_count,...
pub mod vector; pub mod xorshift; pub mod rgb; pub mod ppm_gen; pub mod ray; pub mod sphere; pub mod hittable_list; pub mod camera; pub mod material; pub mod buffer; pub mod moving_sphere; pub mod texture; pub mod constant_medium;
use std::thread; use rumqttc::Client; use crate::mov::*; #[allow(dead_code)] pub fn test3(mut client: Client) { let pos: Vec<(i16, i16)> = vec![ (-120, 120), (-60, 120), (0, 120), (60, 120), (120, 120), (-60, 180), (0, 180), (60, 180), (120, ...
use std::time::Duration; use std::marker::PhantomData; use actix::*; use actix_web::*; use actix_web::http::Method; use actix_web::http::header::ACCESS_CONTROL_ALLOW_METHODS; use context::ChannelItem; use protocol::{Frame, CloseCode}; use utils::SockjsHeaders; use session::Session; use manager::{Broadcast, Record, Se...
#[doc = "Audio PLL frequency in 11.176 MHz - 11.402 MHz or 12.165 MHz - 12.411 MHz frequency bands\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::gene...