text
stringlengths
8
4.13M
use std::rc::Rc; use yew::{Component, ComponentLink, Html, Properties, ShouldRender}; use crate::{ component::wrapper::WithDispatch, dispatch::{DispatchProps, DispatchPropsMut}, store::Store, }; pub type Render<STORE> = Rc<dyn Fn(&DispatchProps<STORE>) -> Html>; pub type Rendered<STORE> = Rc<dyn Fn(&Disp...
use libkrem::parse::Instruction; use std::collections::HashMap; use std::collections::VecDeque; use std::env; use std::fs; use std::process::exit; #[repr(u64)] enum ReservedNativeProcedures { // 0x - I/O PutC = 0x00, PutZ = 0x01, PutU = 0x02, GetC = 0x03, GetZ = 0x04, GetU = 0x05, // 1...
//! Miscellaneous utility data structures. use std::iter::FromIterator; use std::ops::Deref; use std::ops::DerefMut; use tui::layout::Rect; /// A vector with a specifically selected element. /// /// This type is primarially used to implement scrolling selections through /// different options. #[derive(Clone, Debug)]...
//! UI scrollbar rendering functions. use super::state::ElementId; use crate::{error::Result, ops::clamp_size, prelude::*}; pub(crate) const THUMB_MIN: i32 = 10; pub(crate) const SCROLL_SPEED: i32 = 3; /// Scroll direction. #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] pub(crate) enum ScrollDirection { /// ...
// With "use-explicitly-provided-auxv" enabled, we expect to be initialized // with an explicit `rustix::param::init` call. // // With "use-libc-auxv" enabled, use libc's `getauxval`. // // Otherwise, we read aux values from /proc/self/auxv. #[cfg_attr(feature = "use-explicitly-provided-auxv", path = "init.rs")] #[cfg_...
//TODO merge file with map_iter use std::hash::Hash; use std::cmp::Eq; use std::slice; use std::fmt::{ self, Debug }; use std::ops::DerefMut; use std::iter::ExactSizeIterator; use stable_deref_trait::StableDeref; use super::TotalOrderMultiMap; impl<K, V> TotalOrderMultiMap<K, V> where K: Hash + Eq + Copy, ...
#![macro_use] /// Construct HashSet literal as `hash_set!{a, b, c}`. #[macro_export] macro_rules! hash_set { ($($k: expr),*) => {{ #[allow(unused_mut)] let mut set = ::std::collections::hash_set::HashSet::new(); $( set.insert($k); )* set }}; ($($k: expr,)*) => { hash...
use crate::reflect::repeated::drain_iter::ReflectRepeatedDrainIter; use crate::reflect::repeated::iter::ReflectRepeatedIter; use crate::reflect::repeated::ReflectRepeated; use crate::reflect::EnumDescriptor; use crate::reflect::MessageDescriptor; use crate::reflect::MessageRef; use crate::reflect::ReflectRepeatedMut; u...
use proc_macro2::{ TokenStream, Ident, Literal }; #[derive(Debug)] pub struct Grammar { pub doc: Option<TokenStream>, pub visibility: Option<TokenStream>, pub name: Ident, pub args: Vec<(Ident, TokenStream)>, pub items: Vec<Item>, pub input_type: TokenStream, } impl Grammar { pub fn iter_r...
use std::sync::Arc; use hyper::body::to_bytes; use hyper::Response; use hyper::{Body, StatusCode}; use log::info; use toshi_types::*; use crate::handlers::ResponseFuture; use crate::utils::{empty_with_code, with_body}; pub async fn doc_search<C: Catalog>(catalog: Arc<C>, body: Body, index: &str) -> ResponseFuture {...
use crate::dynamics::{RawIslandManager, RawJointParams, RawRigidBodySet}; use rapier::dynamics::{Joint, JointSet}; use wasm_bindgen::prelude::*; #[wasm_bindgen] pub struct RawJointSet(pub(crate) JointSet); impl RawJointSet { pub(crate) fn map<T>(&self, handle: u32, f: impl FnOnce(&Joint) -> T) -> T { let ...
//! Rust中的字符串实际上是被编码成UTF-8的一个字节数组 //! 简单来说,Rust字符串内部存储的是一个u8数组,但是这个数组是Unicode字符经过UTF-8编码得来的。 //! 因此,可以看成Rust原生就支持Unicode字符集 //! //! 在代码里写的,所有的用""包裹起来的字符串,都被声明成了一个不可变,静态的字符串 //! #[test] fn test_str() { // 实际上是将 "Hello" 这个静态变量的引用传递给了x。同时,这里的字符串不可变! let x = "Hello"; println!("{}", x); let z = "foo bar"; ...
use std::{ error::Error, fmt::{Display, Formatter, Result}, }; use serde::Serialize; #[derive(Debug, Serialize)] pub enum ScheduleError { InvalidStep { description: String }, IOError { description: String }, InvalidYaml { location: String }, InvalidJson {}, InvalidName(String), } impl Dis...
use wasm_bindgen::JsCast; use wasm_bindgen::JsValue; use web_sys::*; use web_sys::WebGlRenderingContext as GL; use js_sys::WebAssembly; use crate::core_state::AppState; use super::super::gl_common; use super::super::math::matrix; use super::Scene; pub struct Scene2 { program: WebGlProgram, buffer: WebGlBuffe...
use gfx_backend_vulkan as backend; use gfx_hal::{Adapter, Features, Instance, PhysicalDevice, QueueFamily}; use winit::{ dpi::LogicalSize, event::{Event, WindowEvent}, event_loop::{ControlFlow, EventLoop}, window::WindowBuilder, }; fn main() { let event_loop = EventLoop::new(); let window = Win...
// Copyright 2020 Parity Technologies // // 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. This file may not be copied, modified, or distributed // except accor...
use std::path::Path; use std::mem; use dylib::DynamicLibrary; /// represents a loaded and active plugin pub struct Plugin { pub name: String, lib: DynamicLibrary, desc: fn() -> &'static str, } impl Plugin { /// constructs a new `Plugin` by loading the associated dynamic library pub fn new<S>(name:...
use crate::reader; use crate::tables::offset::OffsetTable; #[derive(Debug, Clone)] pub enum Loca { Short(Vec<u16>), Long(Vec<u32>), } pub fn read( r: &mut reader::FontReader, loca_offset_table: OffsetTable, glyph_count: u16, index_to_loc_format: i16, ) -> Option<Loca> { let ...
// serenity use serenity::client::Client; use serenity::framework::standard::{ help_commands, macros::{check, command, group, help}, Args, CheckResult, CommandGroup, CommandOptions, CommandResult, DispatchError, HelpOptions, StandardFramework, }; use serenity::http::Http; use serenity::model::{ chan...
mod gui; mod sensor; use gui::display_graph; use sensor::Sensor; use std::env::args; static HELP_MESSAGE: &'static str = "Visualization of BME280 sensor measurements\n\n\ USAGE:\n\ \tbme280_vizualizer [OPTIONS]\n\n\ ...
use super::IEventRemindersGenerationJobsRepo; use nettu_scheduler_domain::EventRemindersExpansionJob; use sqlx::{types::Uuid, FromRow, PgPool}; use tracing::error; pub struct PostgresEventReminderGenerationJobsRepo { pool: PgPool, } impl PostgresEventReminderGenerationJobsRepo { pub fn new(pool: PgPool) -> Se...
#![no_std] // underscore to not interfere with `[#interrupt] in generated fn. pub mod interrupt_; pub mod low_power;
extern crate discord; use std::path::Path; use std::fs; use std::env; use std::fmt; use std::time::Duration; use std::thread; use discord::{Discord, State}; use discord::model::Event; const PREFIX: char = '$'; fn main(){ let discord = Discord::from_bot_token(&env::var("DISCORD_TOKEN").expect("Bad DISCORD_TOKEN")...
use super::kw; use super::Line; #[derive(Debug, Clone)] /// Representa um comando, que é executado dentro do contexto atual /// Os valores passados aos comandos têm nomes fantasia alfabéticos para exemplificação pub enum Command { /// Move (copia) o conteudo da variavel no endereco a pro b Move(String,...
use std::fmt; struct Bottles(u8); impl fmt::Display for Bottles { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { Bottles(0) => write!(f, "no more bottles"), Bottles(1) => write!(f, "1 bottle"), Bottles(n) => write!(f, "{n} bottles"), } ...
use std::collections::HashMap; struct TopVotedCandidate { times: Vec<i32>, leaders: Vec<i32>, } impl TopVotedCandidate { fn new(persons: Vec<i32>, times: Vec<i32>) -> Self { let n = persons.len(); let mut hm: HashMap<i32, usize> = HashMap::new(); let mut leader: (usize, i32) = (0, ...
// We want to control preemption here. //@compile-flags: -Zmiri-preemption-rate=0 #![feature(core_intrinsics)] use std::ptr; use std::sync::atomic::AtomicU32; use std::sync::atomic::Ordering::*; use std::thread::spawn; fn static_atomic_u32(val: u32) -> &'static AtomicU32 { let ret = Box::leak(Box::new(AtomicU32:...
use anyhow::Result; use v8; use crate::{ api::util::{v8_deserialize, v8_serialize}, v8util::{create_uint8array_from_bytes, LocalValueExt}, }; pub fn api_text_json_parse( scope: &mut v8::HandleScope, args: v8::FunctionCallbackArguments, mut retval: v8::ReturnValue, ) -> Result<()> { let text = unsafe { arg...
use nimiq_network_interface::peer_info::{NodeType, Services}; use tsify::Tsify; /// Information about a networking peer. #[derive(serde::Serialize, Tsify)] #[serde(rename_all = "camelCase")] pub struct PlainPeerInfo { /// Address of the peer in `Multiaddr` format pub address: String, /// Node type of the p...
struct Solution; impl Solution { fn length_of_longest_substring_two_distinct(s: String) -> i32 { let s: Vec<char> = s.chars().collect(); let mut count: Vec<usize> = vec![0; 256]; let mut start = 0; let mut end = 0; let mut res = 0; let n = s.len(); let mut su...
//! Serial interface reconfiguration test //! //! You have to short the TX and RX pins to make this program work #![allow(clippy::empty_loop)] #![deny(unsafe_code)] #![no_main] #![no_std] use panic_halt as _; use cortex_m::asm; use nb::block; use cortex_m_rt::entry; use stm32f1xx_hal::{ pac, prelude::*, ...
use std::convert::TryFrom; use tapl_rust::chapter_7::*; use term::unnamed::Term as UnnamedTerm; fn main() { let src = r#"(\a. a \b. a) \b.b"#; let unnamed = UnnamedTerm::try_from(parse(src).expect("Cannot parse.")).expect("Cannot remove names."); println!("Unnamed: {}", unnamed.clone().into_unposit...
use crate::ensure; use crate::{String, Vec}; /// Builds a [`String`] compliant with the Fixed-Gas rules. pub struct StringBuilder { bytes: Vec<u8>, } impl StringBuilder { /// New builder, reserves room for `capacity` bytes. pub fn with_capacity(capacity: usize) -> Self { Self { bytes: ...
mod tic_tac_toe; use crate::tic_tac_toe::game_board::GameBoard; use std::error::Error; use std::io::{stdin, stdout, Write}; use termion::event::{Event, Key, MouseEvent}; use termion::input::{MouseTerminal, TermRead}; use termion::raw::IntoRawMode; /// Create a `GameBoard` and simulate a game of tic-tac-toe fn main()...
/** ! This is a mod file, or modular file. ! This file allows the main file to interact with the files called in here. with out it, the main file will not have a way to interact with them */ pub mod meta; pub mod owner;
use std::collections::HashMap; use std::collections::HashSet; use std::fs; use std::io; use std::str; extern crate regex; use regex::Regex; type PendingSteps = HashMap<u8, HashSet<u8>>; fn add_step(pending: &mut PendingSteps, step: u8, prereq: u8) { pending.entry(prereq).or_default(); let set = pending.entry...
use crate::ecs::{AtomicEntity, Entity}; use crate::utils::Bits; pub struct FamilyMeta { pub family: Family, pub initialized: bool, pub entities: Vec<AtomicEntity>, } impl FamilyMeta { pub fn new(family: Family) -> Self { Self { family, entities: Vec::new(), ...
// Copyright 2023 IOTA Stiftung // SPDX-License-Identifier: Apache-2.0 use crypto::keys::slip10::Chain; use iota_client::{ api::{transaction::validate_transaction_payload_length, verify_semantic, PreparedTransactionData}, block::{ input::{Input, UtxoInput}, output::InputsCommitment, pay...
use crate::components::forms; use crate::config; use crate::custom_error::CustomError; use crate::layouts; use actix_web::{http, web, HttpResponse, Result}; use lettre::Message; use serde::{Deserialize, Serialize}; use sqlx::PgPool; use std::default::Default; use validator::ValidationErrors; pub static INVALID_USER_ID...
//! ThreadPool implementation from the Rust Book //! //! See: [`https://doc.rust-lang.org/stable/book/ch20-02-multithreaded.html`] //! //! [`https://doc.rust-lang.org/stable/book/ch20-02-multithreaded.html`]: //! https://doc.rust-lang.org/stable/book/ch20-02-multithreaded.html mod message; mod threadpool; mod worker; ...
//Creates a vertex buffer object for the given array of floats. pub fn create_vbo(vertices:&Vec<f32>)-> gl::types::GLuint { let mut vbo: gl::types::GLuint = 0; unsafe { gl::GenBuffers(1, &mut vbo); bind_buffer(vbo); gl::BufferData( gl::ARRAY_BUFFER,//Target (vert...
//! Module providing utility traits for decoding CAN-bus data. //! //! The module provides three traits: [TryDecode], [DefaultDecode], and [Decode]. //! [try_decode](TryDecode::try_decode) models the possibility of the decoding to fail. //! [default_decode](DefaultDecode::default_decode) returns a default value if the ...
struct Solution; impl Solution { pub fn reverse_left_words(s: String, n: i32) -> String { let cs = s.chars().collect::<Vec<char>>(); cs[n as usize..].iter().collect::<String>() + &cs[0..n as usize].iter().collect::<String>() } }
#![deny(warnings)] use std::env; use std::{convert::Infallible, net::SocketAddr}; use config::{Config, File, FileFormat}; use hyper::{ service::{make_service_fn, service_fn}, Body, Method, Request, Response, Server, StatusCode, }; use lazy_static::lazy_static; use super::render; use crate::data::Data; lazy_...
use std::env::args; use pc_common::StoreFormatV1; fn main() { let input = args().nth(1).unwrap(); let passphrase = args().nth(2).unwrap(); let payload = std::fs::read(input).unwrap(); let s = StoreFormatV1::decode_from_kv(&payload, passphrase.as_bytes()).unwrap(); println!("{}", String::from_utf8...
use std::net::TcpStream; use std::net::Shutdown; use std::thread; use std::io::{Read, Write}; use std::env; use std::sync::Arc; use std::sync::RwLock; use std::time::Duration; use std::net::SocketAddr; use std::str::FromStr; extern crate time; struct BenchResult { time: f64, count: i32, } fn main() { let...
use std::sync::mpsc::channel; use std::sync::mpsc::Sender; use std::sync::mpsc::Receiver; use std::thread::spawn; /// Implement this somehow, later fn num_cpus() -> usize { return 1; } /// Error codes pub enum PoolError { Busy } /// A worker pool pub struct Pool { workers:Vec<Worker>, pub idle: usize } /// ...
pub mod lexer; pub mod token; pub mod util;
use linked_hash_map::LinkedHashMap; #[derive(Debug, Clone, PartialEq, Default)] pub struct Namespaces(LinkedHashMap<String, String>); impl Namespaces { pub fn new<S: Into<String>>(uri: S) -> Self { let mut ns = Namespaces::default(); ns.set_default_namespace(uri); ns } pub fn add_n...
//! Capabilities: this is a placeholder. #[derive(Clone, Debug, PartialEq)] pub struct Capability { index: u64, } impl Capability { pub fn new() -> Capability { Self { index: 0x0 } } } impl Default for Capability { fn default() -> Self { Self::new() } }
mod change_password; pub mod email_otp; pub mod login; mod registration; mod reset_request; use crate::config; use actix_web::web; use reqwest::Url; use serde::{Deserialize, Deserializer}; use std::collections::HashSet; #[derive(PartialEq, Eq, Hash, Debug)] pub enum Code { MissingSecret, InvalidSecret, Mis...
mod entities; use serde::{Serialize}; use super::CrudResult; use crate::gcloud::{GCloud, GCloudFactory, client::Endpoint}; use entities::{InsertAll}; pub struct Table { gcloud_client: GCloud, project_id: String, dataset_id: String, name: String, } impl Endpoint for Table {} impl<'a> Table { pu...
use criterion::{criterion_group, criterion_main, Criterion}; use clueengine::ClueEngine; /*fn main() { let start = Instant::now(); let clue_engine = ClueEngine::load_from_string("63A-.3-A.3-A.3-A.3-A.3-A.3-A.").unwrap(); for _ in 0..10 { let simulation_data = clue_engine.do_simulation(); l...
use crate::filtertree::*; use crate::txtree::*; use bitcoin::{consensus::deserialize, hashes::hex::FromHex, OutPoint, Script, Transaction}; use chrono::Utc; use ergvein_filters::util::is_script_indexable; use std::io; use std::io::BufRead; #[test] fn full_filter() { let txtree = TxTree::new(); let txs = load_t...
mod angle_correction; use angle_correction::*; mod array_vec; use array_vec::ArrayVec; mod control_point_iter; use control_point_iter::{ControlPoint, ControlPointIter}; mod hit_probabilities; use hit_probabilities::HitProbabilities; mod interpolations; use interpolations::{CubicInterpolation, TricubicInterpolation}...
extern crate nalgebra as na; use std::collections::HashMap; use std::cmp::Ordering; use na::*; use std::f32::EPSILON; use super::region_impl::Region; use crate::parser::Polarity; use super::super:: { Path, AlgebraicPathElement, CircularDirection, tree::{ Forest, Tree } }; use super::super::{ StrokePathElemen...
#![allow(unused)] // need some cleanup use bitcoin_indexer::{ db::{self, DataStore}, node::prefetcher, opts, prelude::*, }; use log::info; use std::sync::Arc; use common_failures::{prelude::*, quick_main}; struct Indexer { node_starting_chainhead_height: u64, rpc: Arc<bitcoincore_rpc::Client>...
fn main() { let x = 100; let raw = &x as *const i32; let mut y = 100; let raw2 = &mut y as *mut i32; let raw_value = unsafe { *raw }; println!("the raw point is {:?}", raw2); println!("the raw point is {}", raw_value); }
use crate::AsyncRuntime; use crate::Error; use crate::Stream; use hreq_h1 as h1; use tracing_futures::Instrument; mod agent; mod conn; mod cookies; mod req_ext; mod reqb_ext; pub use agent::Agent; pub use req_ext::RequestExt; pub use reqb_ext::RequestBuilderExt; #[cfg(feature = "server")] pub(crate) use conn::config...
#[macro_use] extern crate glium; pub mod geometry; pub mod primitive; pub mod camera; pub mod renderer; pub mod shader;
use crate::codec::{Codec, StdError, WithOffset, WithSize}; // ALP_SPEC: What does that mean? Is it a complete file copy including the file properties or just // the data? If not then if the destination file is bigger than the source, does the copy only // overwrite the first part of the destination file? // // Wouldn'...
use crate::audio_output::CpalAudioOutput; use crate::graphics::gameboy_screen::GameboyScreen; use crate::savegame::filesystem_ram_dumper::FilesystemRamDumper; use crate::EmulationSignal; use lib_gbemulation::apu::apu::Apu; use lib_gbemulation::cartridge; use lib_gbemulation::cpu::cpu::Cpu; use lib_gbemulation::gpu::gp...
/** * [881] Boats to Save People * * You are given an array people where people[i] is the weight of the ith person, and an infinite number of boats where each boat can carry a maximum weight of limit. Each boat carries at most two people at the same time, provided the sum of the weight of those people is at most lim...
// SPDX-License-Identifier: Apache-2.0 OR MIT // // Copyright (c) 2018-2020 by the author(s) // // Author(s): // - Andre Richter <andre.o.richter@gmail.com> //! Hypervisor System Trap Register - EL2 //! //! Controls trapping to EL2 of Non-secure EL1 or lower AArch32 accesses to the System register in //! the coproc ...
#[macro_use] extern crate diesel; mod auth; mod conduit; mod configuration; mod db; mod middleware; mod models; mod schema; mod web; #[cfg(test)] mod test_helpers; use crate::configuration::Settings; use diesel::PgConnection; use tide::App; type Repo = db::Repo<PgConnection>; pub fn set_routes(mut app: App<Repo>) ...
use std::cell::RefCell; use regex::Regex; use aoc::get_input; struct Point { x: i32, y: i32, z: i32, } struct Moon { position: Point, velocity: RefCell<Point>, } impl Moon { pub fn from(line: &str) -> Moon { let re = Regex::new(r"<x=(?P<x>-?[0-9]*), *y=(?P<y>-?[0-9]*), *z=(?P<z>-?[0-9...
// Copyright 2019 Conflux Foundation. All rights reserved. // Conflux is free software and distributed under GNU General Public License. // See http://www.gnu.org/licenses/ use crate::sync::message::TransactionDigests; use cfx_types::H256; use malloc_size_of_derive::MallocSizeOf as DeriveMallocSizeOf; use metrics::{re...
use qd_core::*; use qd_nat::*; use std::marker::PhantomData; use std::ops::Index; #[derive(Clone)] pub struct Vect<T, N: Nat>(Vec<T>, PhantomData<N>); impl<Item, N: Nat> Dependent for Vect<Item, N> { type Native = Vec<Item>; type Frozen = [Item]; fn freeze(&self) -> &Self::Frozen { self.0.as_slice(...
use cancel_culture::twitter::{store::Store, Client}; use clap::{crate_authors, crate_version, Clap}; use egg_mode::user::TwitterUser; use futures::{stream::LocalBoxStream, StreamExt, TryStreamExt}; use log::info; use rusqlite::Connection; type Void = Result<(), Box<dyn std::error::Error>>; #[tokio::main] async fn mai...
use crate::errors::*; use crate::kvsengine::*; use serde::{Deserialize, Serialize}; use std::collections::BTreeMap; use std::collections::HashMap; use std::ffi::OsStr; use std::fs; use std::fs::File; use std::fs::OpenOptions; use std::io; use std::io::prelude::*; use std::io::SeekFrom; use std::io::{BufReader, BufWrite...
mod aechunker; mod rabinchunker; //mod zerocopyaechunker; //mod zerocopyrabinchunker; //pub use self::zerocopyaechunker::Chunker as ZeroCopyAEChunker; //pub use self::zerocopyrabinchunker::Chunker as ZeroCopyRabinChunker; pub use self::aechunker::Chunker as AEChunker; pub use self::rabinchunker::Chunker as RabinChunke...
use proto; use proto::device::Device; use proto::util; use proto::packet::ethernet::Frame; fn main() { let mut name = String::from("exp0"); let mut dev = proto::device::tuntap::TapDevice::new(name.as_mut_str()).unwrap(); // dev.setup().unwrap(); // dev.up().unwrap(); println!("{:?}", dev); u...
use super::standard_header::StandardHeader; /// An enum representing the different types of packets that can be /// sent/received #[derive(Copy, Clone, Debug, PartialEq)] #[repr(u8)] pub enum PacketType { /// A packet containing Event/Entity data Data = 1, /// A packet sent to maintain the connection by pr...
use vulkano::instance::{Instance, InstanceExtensions, PhysicalDevice}; use vulkano::device::{Device, DeviceExtensions, Features}; use vulkano::buffer::{BufferUsage, CpuAccessibleBuffer}; use vulkano::command_buffer::{AutoCommandBufferBuilder, CommandBuffer}; use vulkano::descriptor::descriptor_set::PersistentDescriptor...
// Copyright 2019 Conflux Foundation. All rights reserved. // Conflux is free software and distributed under GNU General Public License. // See http://www.gnu.org/licenses/ use crate::{ consensus::{ MaybeExecutedTxExtraInfo, SharedConsensusGraph, TransactionInfo, }, light_protocol::{ common...
#![no_std] #![forbid(unsafe_code)] #![allow(non_shorthand_field_patterns)] #[cfg(test)] #[macro_use] extern crate std; pub mod cayley; pub mod tensor; pub mod galois; #[cfg(test)] mod tests { use super::cayley::CayleyPair; use super::galois::{Galois, GF7}; #[test] fn octonion() { let a = Cay...
use std::fs; use std::io; use std::vec::Vec; use crate::color::Color; use crate::progress_bar::ProgressBar; use png::{BitDepth, ColorType, Encoder}; pub struct Canvas { width: usize, height: usize, pixels: Vec<Color>, } impl Canvas { pub fn new(width: usize, height: usize, color: Color) -> Canvas { ...
mod cloudflare; mod hetzner; mod mock; mod record_store; use ::cloudflare as cf; use act_zero::runtimes::tokio::spawn_actor; use act_zero::{upcast, Actor, ActorResult, Addr}; use async_trait::async_trait; use std::net::IpAddr; use crate::config; use crate::AppConfig; use cf::framework::auth::Credentials; use cf::fram...
//! Datafusion integration for Delta Table //! //! Example: //! //! ```rust //! use std::sync::Arc; //! use datafusion::execution::context::SessionContext; //! //! async { //! let mut ctx = SessionContext::new(); //! let table = deltalake::open_table("./tests/data/simple_table") //! .await //! .unwrap()...
use crate::controllable::ControllableId; use serde_derive::{Deserialize, Serialize}; /// Notifies about the depletion and possible overuse of a resource of your [`Controllable`]. #[derive(Debug, Serialize, Deserialize, Clone)] pub struct DepletedResourceEvent { pub universe: usize, #[serde(rename = "controllab...
use iron::prelude::*; use persistent::Read; use db::Database; use models::News; use views::utils::*; use super::SingleNewsHandler; use super::forms::NewsForm; pub fn show(req: &mut Request) -> IronResult<Response> { let news = req.extensions.remove::<SingleNewsHandler>() .expect("Could not get news id in admin::ne...
//! Futures compatibility for `tracing` //! //! # Feature flags //! - `tokio`: Enables compatibility with the `tokio` crate, including //! [`Instrument`] and [`WithSubscriber`] implementations for //! `tokio::executor::Executor`, `tokio::runtime::Runtime`, and //! `tokio::runtime::current_thread`. Enabled by d...
extern crate futures; extern crate tokio_core; use tokio_core::io::{Codec, EasyBuf}; use std::{io, str}; pub struct LineCodec; impl Codec for LineCodec { type In = String; type Out = String; fn decode(&mut self, buf: &mut EasyBuf) -> Result<Option<String>, io::Error> { // Check to see if the fra...
use std::borrow::Cow; use crate::packets::macros::{packet_enum, proto_enum}; packet_enum! { ClientBound<'a> { 0x00 => KeepAlive { #[protocol_field(varnum)] keep_alive_id: i32 }, 0x01 => JoinGame<'a> { entity_id: i32, game_mode: GameMode, ...
use std::cell::RefCell; #[cfg(test)] #[path = "./gpu_test.rs"] mod gpu_test; #[derive(Clone, Default)] pub struct GPU { pub scanline: u32, pub width: u32, pub height: u32, pub pal: Vec<DACPalette>, // the palette in use pub dac_color: usize, // for out 03c9, 0 = red, 1 = green, 2 = blu...
use crate::{ tl_types::{tl_bytes::TLBytes, TLType}, utils::MyResult, }; impl TLType for String { fn tl_read(input: &mut std::io::Read) -> MyResult<Self> { let tl_bytes: TLBytes = TLBytes::tl_read(input)?; let bytes = tl_bytes.into_bytes(); Ok(String::from_utf8(bytes)?) } fn...
#![doc = "Peripheral access API for MKL82Z7 microcontrollers (generated using svd2rust v0.14.0)\n\nYou can find an overview of the API [here].\n\n[here]: https://docs.rs/svd2rust/0.14.0/svd2rust/#peripheral-api"] #![deny(missing_docs)] #![deny(warnings)] #![allow(non_camel_case_types)] #![no_std] #![feature(untagged_un...
// Copyright 2020-2022 The NATS Authors // 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 ...
fn is_prime(num: u32) -> bool { //returs first prime factor of num. (if num is prime, return false) for i in 2..num ^ (1/2) { if num % i == 0 { return false; } } true } fn main() { let upto: u32 = 2000000; let mut sum : u64 = 0; for i in 2..upto { if is_prime(i){ sum += i as u64; } } print...
// 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...
mod core; mod grammar; mod item; mod itoken; mod parser; mod production; mod symbol; mod tree; pub use crate::core::*; pub use grammar::*; pub use item::*; pub use itoken::*; pub use parser::*; pub use production::*; pub use symbol::*; pub use tree::*;
mod aes; mod hkdf; mod interface; use std::io::{Error, ErrorKind}; use std::pin::Pin; use std::task::Context; use std::task::Poll; use crypto::digest::Digest; use crypto::md5::Md5; use futures::ready; use tokio::io; use tokio::io::ReadBuf; pub struct CryptoWriter<T> where T: io::AsyncWrite + std::marker::Unpin, ...
use email::MimeMessage; use result::Result; use flags::Flags; use id::MailId; use internal::InternalMaildir; use lazy::single::Thunk; use maildir::Maildir; use msg::MaildirMessage; use raw::RawMaildir; use snapshot::Snapshot; use std::any::Any; use std::sync::mpsc; use task; pub struct Mail { maildir: Box<RawMaild...
// Copyright 2020 WHTCORPS INC. Licensed under Apache-2.0. use std::fmt; use std::time::Instant; use edb::{CompactedEvent, CausetEngine, Snapshot}; use ekvproto::import_sst_timeshare::SstMeta; use ekvproto::kvrpc_timeshare::ExtraOp as TxnExtraOp; use ekvproto::meta_timeshare; use ekvproto::meta_timeshare::BraneEpoch;...
fn main() { let x: bool = true; if x { let one:i64 = 1; println!("{:?}", one); } else { let two:i64 = 2; println!("{:?}", two); } }
//! Encode a BinJS, then decode it, ensure that we obtain the same AST. #[macro_use] extern crate bencher; extern crate binjs; #[macro_use] extern crate lazy_static; use binjs::source::*; const PATHS: &[&str] = &["tests/data/frameworks/angular.1.6.5.min.js"]; fn launch_shift() -> Shift { Shift::try_new().expec...
//! Swift Demangling Tests //! All functions were compiled with Swift 4.0 in a file called mangling.swift //! see https://github.com/apple/swift/blob/master/test/SILGen/mangling.swift #![cfg(feature = "swift")] #[macro_use] mod utils; use symbolic_common::Language; use symbolic_demangle::DemangleOptions; #[test] fn ...
use anyhow::Context; use clap::Parser; use core::sync::atomic::Ordering::{Relaxed, SeqCst}; use rand::Rng; use rand::{rngs::SmallRng, SeedableRng}; use std::collections::hash_map::DefaultHasher; use std::ffi::OsStr; use std::fmt::Display; use std::hash::{Hash, Hasher}; use std::path::{Path, PathBuf}; use std::sync::ato...
pub const MEMORY_REGIONS_MAX: usize = 8;
extern crate csv; #[macro_use] extern crate serde_derive; #[macro_use] extern crate lazy_static; extern crate serde; extern crate chrono; extern crate regex; use chrono::TimeZone; use std::error::Error; use std::io; use std::fs::File; use std::path::Path; use chrono::offset::{Local}; use regex::Regex; const ML_PER_OZ...