text
stringlengths
8
4.13M
/// 0000000 XOR 1001001 = 1001001 /// 1001001 XOR 0101000 = 1100001 /// 방금 수를 취소 하려면 /// 1100001 XOR 0101000 = 1001001 // use hexe::zobrist::Zobrist
/// Rayon extensions to `HashMap` extern crate num_cpus; use rayon::iter::{ParallelIterator, IndexedParallelIterator, IntoParallelIterator, FromParallelIterator, ParallelExtend}; use std::collections::LinkedList; use super::{Hash, HashMap, BuildHasher}; use super::super::table; use super::super::table::SafeHash; pu...
pub mod color; pub mod point; pub mod ray; pub mod vec3; use color::Color; use point::Point; use ray::Ray; use vec3::Vec3; fn hit_sphere(center: &Point, radius: f32, ray: &Ray) -> f32 { let oc: Vec3 = ray.origin - *center; let a = ray.direction.length_squared(); let half_b = oc.dot(&ray.direction); le...
use postgres::{Client, NoTls, Error}; struct Person { _id: i32, first_name: String, last_name: String } fn create_person(first_name: &str, last_name: &str) -> Person { Person { _id: 0, first_name: first_name.to_string(), last_name: last_name.to_string() } } fn main() -> Re...
use crate::{handler_fn, response_ok, Config, Error, Response}; use artell_usecase::admin::add_art as usecase; use bytes::Bytes; use uuid::Uuid; use warp::{reject::Rejection, Filter}; #[derive(Deserialize)] #[serde(rename_all = "camelCase")] pub struct ReqBody { artist_id: Uuid, title: String, materials: St...
use crate::circbuf::CircBuf; use std::ops::{Mul, Add, Div}; pub type WeightedMovingAvgF32<I, F> = WeightedMovingAvg<I, F, f32>; pub struct WeightedMovingAvg<I, F, T> { circbuf: CircBuf<(T, T)>, inner: I, factor: F, } impl<I, F, T> WeightedMovingAvg<I, F, T> where I: Iterator<Item=T>, F: Iterator<Item=T>, T: De...
use std::time::Duration; use std::time::Instant; pub struct Clock { period: Duration, offset: Instant, } impl Clock { #[allow(clippy::cast_possible_truncation)] #[allow(clippy::cast_sign_loss)] pub fn new(freq: f64) -> Self { Self { period: Duration::from_nanos(1_000_000_000 / ...
use serde::{Deserialize, Serialize}; use worker::{kv::KvStore, prelude::*}; mod utils; #[derive(Deserialize, Serialize)] struct MyData { message: String, #[serde(default)] is: bool, #[serde(default)] data: Vec<u8>, } #[cf::worker(fetch)] pub async fn main(mut req: Request) -> Result<Response> { ...
// Our use cases use super::stream; pub const WAVE_FORMAT_PCM: usize = 1; #[derive(Default)] pub struct WaveFormatEx { pub format_tag: u16, pub channels: u16, pub samples_per_second: i32, pub average_bytes_per_second: i32, pub block_align: u16, pub bits_per_sample: u16, pub cb_size: u16, }...
use crate::symbol_table::Scope; use std::cell::RefCell; use std::hash::Hash; use std::hash::Hasher; use std::rc::Rc; #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct Constant(i32); impl Constant { pub fn new<T: Into<i32>>(c: T) -> Self { Constant(c.into()) } pub fn constant(&self) -> i32 {...
use cmake::*; use std::collections::HashMap; use std::rc::*; #[derive(Debug, Eq, PartialEq)] pub enum Value { String(String), Vector(Vec<String>), } #[derive(Debug, Eq, PartialEq)] pub enum TargetType { Alias(String), // (name of referenced library) Executable(bool, Vec<String>), // (exclude_from_all,...
// // TODO: optimization functions? // - levenshtein distance for "Did you mean.." feature // - allow accidental whitespace in intrepeter (who cares, there's no scope) // - allow shortcuts (i.e load can be ld) pub const FILLER_TOKEN: &str = "<NULL>"; #[derive(Debug)] pub enum Opcode { Help, Load(String), ...
use std::borrow::Cow; use std::fmt; use regex::Regex; use serde::{Deserialize, Serialize}; /// The URIs known to WAMP. pub mod known_uri { #![allow(non_upper_case_globals)] macro_rules! w_uri { ($doc:expr, $name:ident) => { #[doc=$doc] pub const $name: $crate::uri::Uri = $crat...
#[doc = "Register `RDL1R` reader"] pub type R = crate::R<RDL1R_SPEC>; #[doc = "Field `DATA0` reader - DATA0"] pub type DATA0_R = crate::FieldReader; #[doc = "Field `DATA1` reader - DATA1"] pub type DATA1_R = crate::FieldReader; #[doc = "Field `DATA2` reader - DATA2"] pub type DATA2_R = crate::FieldReader; #[doc = "Fiel...
use proconio::{fastout, input}; use std::cmp::Reverse; use std::collections::BinaryHeap; const INF: i64 = 1_000_000_000_000_000_000; #[derive(Clone, Debug)] struct Edge { to: i64, co: i64, } impl Edge { fn new(to: i64, co: i64) -> Self { Self { to, co } } } #[fastout] fn main() { input! ...
use num::{One, Zero}; use std::iter::Product; use std::ops::{Div, Mul, Sub}; fn main() { let f = lag_poly_a(vec![(0.0, 0.0), (1.0, 1.0), (-1.0, 1.0)]); println!("{}", f(-3.0)); let mut finv = vec![1.0; 10]; for i in 1..10 { finv[i] = finv[i - 1] / (i as f64); } let f = lag_poly_b(vec![0...
mod clue_placer; mod clues_placer; mod line_solver; mod solve_grid; pub use clue_placer::*; pub use clues_placer::*; pub use line_solver::*; pub use solve_grid::*;
extern crate glium; use glium::buffer::{BufferMutSlice, BufferSlice}; use glium::vertex::{Vertex, VertexBuffer, VertexBufferAny, VerticesSource}; use std::any::TypeId; use std::error::Error; use std::fmt::{Display, Formatter, Result as FmtResult}; use std::ops::Deref; /// A type-erased `VertexBuffer` which can be saf...
fn main() { let mut tree = BinaryTree::new_root(0_i32); let nums = vec![-2, -6, 12, 14, 3, -24, 8]; for idx in nums { tree.add(idx); } assert!(tree.search(-6)); assert!(tree.search(-24)); assert!(tree.search(8)); assert!(tree.search(0)); assert!(!tree.search(101)); asser...
extern crate glob; extern crate libc; use glob::glob; use std::os::unix::io::AsRawFd; use std::{mem, fs, io}; use std::io::Read; use std::fs::File; fn get_fd() -> Option<File> { let event_device_mask = "/dev/input/event*"; let event_device_name = "Asus WMI hotkeys"; match glob(event_device_mask) { ...
use super::{Cartridge, Mapper, Mirror, serialize::*}; pub struct Mmc3 { cart: Cartridge, mirroring: Mirror, bank_registers: Vec<usize>, next_bank: u8, irq_latch: u8, irq_counter: u8, irq_enable: bool, trigger_irq: bool, // signal to send to CPU reload_counter: bool, irq_delay:...
#[macro_use] extern crate lazy_static; use std::env; use std::fmt; use std::fs::File; use std::io::prelude::*; use std::ops::{Index, IndexMut}; use std::str::FromStr; use failure::{format_err, Error}; use regex::Regex; use slotmap::{new_key_type, SlotMap}; new_key_type! { struct ArmyKey; struct GroupKey; } ...
fn main() { #[cfg(my_flag)] bitflags::bitflags! { } println!("Hello, world!"); }
//! This example demonstrates using the [`Span`] [`CellOption`] to //! extend [Cells](Cell) over a specified number of columns/rows. //! //! * Note how [`Span`] is available for [`Cell`] modifications //! after the [`Modify`] [`TableOption`] is applied. //! //! * ⚠️ `with()` is a reused pattern within [`tabled`] for bo...
use anyhow::Error; use rumqttc::{Client as MqttClient, MqttOptions, Packet, QoS}; use serde::Deserialize; use std::collections::HashMap; use std::env; use std::fs; #[derive(Debug, Deserialize)] struct MQTTConnectionConfig { host: String, user: String, password: String, } #[derive(Debug, Deserialize, Parti...
pub mod entity; pub mod adapter; pub mod usecase; pub mod driver;
pub mod websocket_jsonrpc;
use std::time::Duration; use bonsaidb::{ client::{Client, RemoteDatabase}, core::{ admin::{Admin, PermissionGroup}, connection::ServerConnection, permissions::Statement, schema::Collection, test_util::{BasicSchema, HarnessTest, TestDirectory}, }, server::test_uti...
use crate::internal::*; use drg::asset::property::meta::*; use drg::asset::property::prop_type::*; use drg::asset::property::*; use drg::asset::*; use imgui::*; #[derive(Debug, PartialEq)] pub enum EditStatus { Continue, Cancel, Done, } pub enum ValueCreator { WithDefault { for_type: PropType, value: Value },...
macro_rules! call_ctrl { ($ctrl_fn: expr) => { $ctrl_fn() .and_then(|result| match result { Ok(result) => Ok(HttpResponse::Ok().json(result)), Err(err) => Err(UserError::from(err)), }).responder() }; }
pub mod auth; pub mod csrf; pub mod key; pub mod service; pub mod user; use crate::driver; use chrono::{DateTime, Utc}; // TODO(refactor): Error string descriptions for logs. /// Core errors. #[derive(Debug, Fail)] pub enum Error { /// Bad request. #[fail(display = "CoreError::BadRequest")] BadRequest, ...
#[doc = "Reader of register RCC_OCENSETR"] pub type R = crate::R<u32, super::RCC_OCENSETR>; #[doc = "Writer for register RCC_OCENSETR"] pub type W = crate::W<u32, super::RCC_OCENSETR>; #[doc = "Register RCC_OCENSETR `reset()`'s with value 0x01"] impl crate::ResetValue for super::RCC_OCENSETR { type Type = u32; ...
use wasm_bindgen::prelude::*; #[wasm_bindgen] #[derive(Clone, Copy, Debug)] /// $1$: MD5 /// $2$: bcrypt /// $2a$: bcrypt /// $2x$: bcrypt /// $2y$: bcrypt /// $2b$: bcrypt /// $5$: SHA-256 /// $6$: SHA-512 /// https://stackoverflow.com/questions/5393803/can-someone-explain-how-bcrypt-verifies-a-hash pub ...
extern crate failure; use failure::{Error, ResultExt}; use std::io; pub trait CRUD { // All object stores in this framework should implement these. // TODO: CHeck Anterofit. // // Using RLIDWKA as a shout out to the AFS community. // https://www.cs.cmu.edu/~help/afs/afs_acls.html // The Opti...
use std::env; use std::fs::File; use std::io::Read; use std::process; fn main() { let args: Vec<String> = env::args().collect(); if args.len() < 2 { eprintln!("{:?}: file name not given", args[0]); process::exit(1); } else { for i in 1..args.len() { println!("{:?}", do_...
//! A collection of reusable algorithms without dependencies on any other module in the project. pub mod dbscan; pub mod gsom; pub mod mdp; pub mod nsga2; pub mod geometry; pub mod statistics;
#[derive(Debug, Clone)]//É necessário indicar que tem o metodo clone, //Podemos AINDA USAR COPY para que a var se comporte como um primitivo, desde que nao existam var de Heap struct MigStruct { a: i32, b: f64, } //Struct pode ter milhares de campos, por isso não pode ser assumida com Stack Var, mas sim como H...
use std::env; use std::fs::File; use std::io::prelude::*; fn main() { let args: Vec<String> = env::args().collect(); let day = args[1].parse::<u8>().unwrap(); let problem = args[2].parse::<char>().unwrap(); if let Some(solver) = advent::get_solution(day, problem) { let mut input = String::new(...
use crate::{ commands::osu::ProfileSize, database::{EmbedsSize, MinimizedPp, UserConfig}, embeds::Author, }; use rosu_v2::prelude::GameMode; use std::fmt::Write; use twilight_model::user::User; pub struct ConfigEmbed { author: Author, description: String, title: &'static str, } impl ConfigEmb...
pub mod apploader; pub mod dol; pub mod fst; pub mod header; mod section; pub use self::section::Section;
// 2019-01-02 // On va fabriquer un nouveau struct en modifiant quelques variables d'un autre. // Debug est un TRAIT. Solution tirée de stack overflow pour afficher le struct. #[derive(Debug)] // On définit le struct User EN DEHORS de la fonction main() struct User { username: String, email: String, age:...
use std::fmt::Debug; pub trait Encodable: Send + Sync + Sized { type Encoded: AsRef<[u8]> + Send + Sync; fn encode(self) -> Self::Encoded; } pub trait Decodable: Send + Sync + Sized { fn decode(b: &[u8]) -> anyhow::Result<Self>; } pub trait TableObject: Encodable + Decodable {} impl<T> TableObject for ...
extern crate orbclient; extern crate tetrahedrane; use tetrahedrane::vid::*; use tetrahedrane::start; fn main() { let mut window = start::Window::new(640, 480, "Hello!", 4 as usize); let triangle_color = Color::new(200, 200, 200); window.window.set(Color::new(20, 40, 60).orb_color()); let point1 =...
use backtrace::Backtrace; use msgbox::{self, IconType}; use std::panic; use std::path::{Path, PathBuf}; use std::ffi::OsStr; pub fn init() { panic::set_hook(Box::new(|info| display_panic(info))); } fn trim_path(path: &Path) -> String { if let Some(component) = path.components() .filter_map(|c| c.as_o...
use crate::BoxedErrorResult; use crate::component_manager::*; use crate::constants; use crate::filesystem; use crate::globals; use crate::modular::*; use crate::operation::*; use serde::{Serialize, Deserialize}; use std::collections::{HashMap, HashSet}; use std::convert::TryInto; use std::iter::FromIterator; use std::t...
//!Handles the module multiboot2 tag. ///Represents the module tag. #[repr(C)] struct Module { //type = 3 tag_type: u32, size: u32, mod_start: usize, //verify this is really 64 bit mod_end: usize, string: [u8] }
use kiss3d::scene::SceneNode; use kiss3d::window::Window; use na::{UnitQuaternion, Vector3}; use nalgebra::{Translation3, Unit}; //phantom is 289.5mm square pub struct Drone { model: SceneNode, } impl Drone { pub fn new(window: &mut Window) -> Self { let mut container = window.add_group(); cont...
use std::fmt::Debug; pub trait Engine<Ret: Debug>: Debug { fn find(&self, s: &str) -> Option<(usize, usize, Ret)>; fn clone_box(&self) -> Box<Engine<Ret>>; } pub mod anchored; pub mod forward_backward; pub mod program;
// Copyright 2020 Google LLC // // Use of this source code is governed by an MIT-style license that can be found // in the LICENSE file or at https://opensource.org/licenses/MIT. //! Defines an internal type for client side file finder action and provides //! a function converting proto format of the request //! `rrg_...
use crate::{ common::math::{self, Vector2f}, app::Blob, common::config::Config, }; const WHITE: [u8; 4] = [255, 255, 255, 255]; pub struct World { pub width: usize, pub height: usize, pub config: Config, pub blobs: Vec<Blob> } impl World { pub fn refresh_config(&mut self) -> anyhow::...
//! Class for video capturing from video files, image sequences or cameras. use core::*; use opencv_sys as ffi; use std::ffi::CString; use std::path::Path; /// VideoCapture #[derive(Debug)] pub struct VideoCapture { inner: ffi::VideoCapture, } impl Drop for VideoCapture { fn drop(&mut self) { unsafe {...
use super::*; use crate::mem::{self, MaybeUninit}; use core::array::FixedSizeArray; // Verify that the bytes of initialized RWLock are the same as in // libunwind. If they change, `src/UnwindRustSgx.h` in libunwind needs to // be changed too. #[test] fn test_c_rwlock_initializer() { #[rustfmt::skip] const RWLO...
use crate::core::prelude::*; use crate::filesystem::responses::ListFilesystemsResponse; use azure_core::errors::AzureError; use azure_core::prelude::*; use futures::stream::{unfold, Stream}; use hyper::{Method, StatusCode}; #[derive(Debug, Clone)] pub struct ListFilesystemsBuilder<'a, C> where C: Client, { cli...
use crate::memory::io::PSGChannel; use super::Gba; use arm::Cycles; use std::cell::RefCell; use std::collections::VecDeque; use std::rc::Rc; #[allow(clippy::upper_case_acronyms)] #[derive(Copy, Clone, PartialEq, Eq)] pub enum EventTag { // Use this tag for events that don't really need to be rescheduled // or...
use clap::{App, ArgMatches}; use feedspool::db; use feedspool::gql::{mutation::RootMutation, query::RootQuery, Context}; use hyper::{ service::{make_service_fn, service_fn}, Body, Method, Response, Server, StatusCode, }; use hyper_staticfile::Static; use juniper::{EmptySubscription, RootNode}; use std::error::E...
use crate::prelude::*; use apint; use apint::Width; use std::result; use std::fmt; use std::error; /// Represents a bitvector in the sense of the SMT theory of bitvectors. /// /// These are used to represent constant bitvector values. /// This struct mainly wraps an underlying bitvector implementation /// and provid...
#[doc = "Reader of register PERIPH_ID_5"] pub type R = crate::R<u32, super::PERIPH_ID_5>; #[doc = "Reader of field `PERIPH_ID_5`"] pub type PERIPH_ID_5_R = crate::R<u8, u8>; impl R { #[doc = "Bits 0:7 - not used"] #[inline(always)] pub fn periph_id_5(&self) -> PERIPH_ID_5_R { PERIPH_ID_5_R::new((sel...
#![allow(unused)] use std::{ error::Error, io::{self, BufRead, BufReader, Read, Write}, }; fn main() -> Result<(), Box<dyn Error>> { let mut t = String::new(); let mut tmp = String::new(); let mut m: usize; let mut buff = Vec::new(); let mut stdin = io::stdin(); stdin.lock().read_line(&...
#![cfg_attr(feature="experimental-auto-traits", feature(optin_builtin_traits))] #![cfg_attr(not(feature="std"), no_std)] //! The interprocess-traits crate provides type traits to annotate types which have certain //! properties when used in a multiprocess environment. #[cfg(feature="std")] use std as core; use core:...
#[doc = "Register `CSR` reader"] pub type R = crate::R<CSR_SPEC>; #[doc = "Register `CSR` writer"] pub type W = crate::W<CSR_SPEC>; #[doc = "Field `PU10K` reader - 10 kO pull-up resistor"] pub type PU10K_R = crate::BitReader; #[doc = "Field `PU10K` writer - 10 kO pull-up resistor"] pub type PU10K_W<'a, REG, const O: u8...
//! A fluent interface for the analyser. //! //! This interface provides proxies for the different properties of tensors. //! This allows inference rules to be stated in a clear, declarative fashion //! inside the `rules` method of each operator. //! //! Take these rules for instance: //! ```text //! solver.equals(inpu...
#[doc = "Reader of register TZENR2"] pub type R = crate::R<u32, super::TZENR2>; #[doc = "Writer for register TZENR2"] pub type W = crate::W<u32, super::TZENR2>; #[doc = "Register TZENR2 `reset()`'s with value 0"] impl crate::ResetValue for super::TZENR2 { type Type = u32; #[inline(always)] fn reset_value() ...
use actix_files as fs; use actix_web::{web, App, HttpServer}; use ::web::db_connection::init_pool; use ::web::handlers::user::{index, create, detail, list}; fn main() { println!("Server is listening..."); HttpServer::new(|| { App::new() .data(init_pool()) .service(fs::Files::ne...
use std::io::Write; use crate::error::TychoStatus; use crate::write::func::{write_byte, write_bytes}; use crate::write::length::write_length; pub(crate) fn write_string<W: Write>(writer: &mut W, s: &str) -> TychoStatus { let bytes = s.as_bytes(); write_length(writer, bytes.len())?; write_bytes(writer, by...
use anyhow::Result; use itertools::izip; use std::convert::TryInto; use std::fmt; use std::mem; use std::str; #[derive(Debug)] enum PageError { BufferSizeExceeded, } impl std::error::Error for PageError {} impl fmt::Display for PageError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match s...
use chrono::{NaiveDate, NaiveDateTime, NaiveTime}; use r2d2_mysql::mysql::consts::{ColumnFlags, ColumnType}; use rust_decimal::Decimal; use serde_json::Value; #[derive(Copy, Clone, Debug)] pub enum MySQLTypeSystem { Float(bool), Double(bool), Tiny(bool), Short(bool), Long(bool), Int24(bool), ...
use super::*; /// A headline. /// /// # Semantics /// /// The main element used to structure an org file. Also used as todo items/tasks. Can be /// assigned a [`elements::Planning`] item to schedule an event. /// /// If the first word of `TITLE` is `COMMENT` the headline will be considered as commented /// (case is si...
//! Tests auto-converted from "sass-spec/spec/directives/import/error" #[allow(unused)] use super::rsass; // From "sass-spec/spec/directives/import/error/conflict.hrx" mod conflict { #[allow(unused)] use super::rsass; // Ignoring "all", error tests are not supported yet. // Ignoring "extension", erro...
use std::marker::PhantomData; use std::collections::HashMap; use ggez::graphics::{Mesh, MeshBuilder}; use ggez::{Context}; use std::hash::{Hash, Hasher}; use crate::entities::World; use std::collections::hash_map::{Values, ValuesMut}; #[derive(Debug)] pub struct Id<T> (usize, PhantomData<T>); impl<T> PartialEq for Id...
extern crate num_bigint; extern crate num_traits; extern crate secret_integers; #[macro_use] mod macros { #[macro_export] macro_rules! verif_assert { ($e:expr) => { assert!($e) } } #[macro_export] macro_rules! verif_pre { ($e:expr) => { assert!($e) } } #[macro_export] ma...
struct Counter { count: u32, } impl Counter { fn new() -> Counter { Counter { count: 0 } } } impl Iterator for Counter { type Item = u32; fn next(&mut self) -> Option<Self::Item> { self.count += 1; if self.count < 6 { Some(self.count) } else { ...
use bytes::Bytes; use mini_redis::{Connection, Frame}; use parking_lot::Mutex as ParkingLotMutex; use std::collections::HashMap; use std::sync::Arc; use tokio::net::{TcpListener, TcpStream}; type Dd = Arc<ParkingLotMutex<HashMap<String, Bytes>>>; /// <https://c9x.me/articles/gthreads/intro.html> /// <https://users.ru...
use std::cmp::Eq; use std::collections::HashMap; use std::hash::Hash; use collector::Collector; use fastfield::FastFieldReader; use schema::Field; use DocId; use Result; use Score; use SegmentReader; use SegmentLocalId; /// Facet collector for i64/u64 fast field pub struct IntFacetCollector<T> where T: FastFie...
#[derive(Clone, Debug, PartialEq)] pub struct State { pub pos: usize, pub tape: Vec<u8>, } #[derive(Clone, Debug, PartialEq)] pub enum NextAction { GoForward, JumpBackward, JumpForward, }
/// # Rectangel example from variouse sources. /// <https://doc.rust-lang.org/rust-by-example/fn/methods.html> /// Refactor to use point /// #[derive(Debug, PartialEq)] pub struct Point { x: f64, y: f64, } impl Point { /// static method often are constructors of some sort. /// create a point repesentin...
use rand::Rng; use serde_derive::{Deserialize, Serialize}; use crate::{ entity::Item, types::Stats, types::{CmdResult, ItemMap}, util::dont_have, }; #[derive(Debug, Serialize, Deserialize)] pub struct Player { hp: (i32, u32), xp: (u32, u32), in_combat: bool, lvl: u32, stats: Stats...
//! Materials that can be struck by a ray and how they affect light. use std::sync::Arc; use crate::hittable::HitRecord; use crate::ray::Ray; use crate::texture::{SolidColor, Texture}; use crate::vec3::{Color, Vec3}; /// Type of material. #[derive(Clone)] pub enum Material { /// Diffuse material. Lambertian(...
//! Parse responses from HAProxy sockets. use crate::errors::Error; use std::path::PathBuf; use std::str::FromStr; #[derive(Clone, Debug, Eq, PartialEq)] pub struct Acl { pub id: i32, pub reference: Option<String>, pub description: String, } impl FromStr for Acl { type Err = Error; fn from_str(s...
//! panoradix is a set of structures based of the [Radix //! tree](https://en.wikipedia.org/wiki/Radix_tree) data structure, optimized for indexing strings //! "by prefix". #![deny(missing_docs)] pub use map::RadixMap; pub use set::RadixSet; pub use key::ExtensibleKey as RadixKey; /// Module containing a map based o...
use rg3d::core::{algebra::Vector3, math::plane::Plane}; #[derive(Copy, Clone, Debug)] pub enum PlaneKind { X, Y, Z, XY, YZ, ZX, } impl PlaneKind { pub fn make_plane_from_view(self, look_direction: Vector3<f32>) -> Plane { match self { PlaneKind::X => Plane::from_normal_...
//**THIS CODE IS ONLY MY PRACTICE! REVIEW OTHER CODES FOR BETTER UNDERSTANDING THE CONCEPT OF RUST** // // fn largest<T: PartialOrd + Copy>(x: &[T]) -> T { // // let mut largest = x[0]; // // for &numbers in x.iter() { // // if numbers > largest { // // largest = numbers; // // } // // } // // larg...
use crate::{ util::{ constants::{GENERAL_ISSUE, TWITCH_API_ISSUE}, MessageExt, }, BotResult, CommandData, Context, MessageBuilder, }; use std::sync::Arc; #[command] #[authority()] #[short_desc("Notifying a channel when a twitch stream comes online")] #[aliases("streamadd", "trackstream")] ...
use khadga::{auth::login, chat::{user_connected, Users}, config::Settings}; use log::info; use std::{collections::HashMap, net::SocketAddr, sync::Arc}; use tokio::sync::Mutex; use warp::{http::{Response, StatusCode}, ws::Ws, ...
#[derive(Debug)] struct Info<'a> { name: &'a str, class: &'a str, roll: &'a str } fn main() { println!("{:?}", Info { name: &"xxx", class: &"yyy", roll: &"zzz" }); }
#[macro_use] extern crate lazy_static; #[macro_use] extern crate diesel_migrations; embed_migrations!(); mod configuration; mod graphql; mod health_check; mod helpers;
// use std::cell::RefCell; use std::fmt; use std::sync::Arc; use std::time::{Duration, Instant}; use async_trait::async_trait; use crossbeam_channel::{Receiver, Sender}; use failure::Fallible; use serde::{Deserialize, Serialize}; use slog_scope::{error, info}; use tokio::runtime; use crate::effects::Interpreter; pub...
use serde_json::Value; /** TCP HOOK PROTOCOL 0 - 4 HOOK IDENTITY BYTES 4 - 8 VERSION 8 - 16 HOOK TYPE 16 - * DATA */ use std::str::from_utf8; pub const IDENTITY_BYTES: &[u8] = &[0x99, 0x99, 0x99, 0x99]; pub const IDENTITY_BYTES_LENGTH: usize = IDENTITY_BYTES.len(); pub const VERSION_BYTES: usize = 1 <<...
use super::heeren::{solve_types, Constraint, ConstraintSet}; use std::rc::Rc; #[derive(Clone, PartialEq, Debug)] enum ExampleTypes { Bool, FunctionType(Vec<Box<ExampleTypes>>, Box<ExampleTypes>), } #[test] fn test_unification() { let mut constraints = ConstraintSet::new(); let a = constraints.create_t...
use arbitrary::{Arbitrary, Unstructured}; use std::env::args; use std::fs::File; use std::io::Read; mod validation { include!("../../fuzz_targets/validation.rs"); } fn main() { let mut data = vec![]; let filename = args().skip(1).next().unwrap().as_str().to_string(); File::open(&filename) .unw...
pub mod cubebox; pub mod pack; pub use cubebox::Cubebox; pub use pack::{Pack, PackDepth}; pub mod prelude { #[allow(unused_imports)] pub use super::super::ArenaMut; #[allow(unused_imports)] pub use super::super::BlockMut; #[allow(unused_imports)] pub use crate::libs::random_id::U128Id; #[a...
use std::io; pub fn string_to_integer(s: &str) -> i32 { } pub fn integer_to_string(i: i32) -> String { } fn main() -> io::Result<()> { let input = // you are allowed to make this mut println!("You got: {}", string_to_integer(input)); println!("You got: {}", integer_to_string(string_to_integer(input)...
// 2019-04-26 // Le relecteur parcourra first.rs d'abord, donc le code a été récupéré pour servir ici. use std::mem; // rendons le code générique avec des <T> partout où il faut pub struct List<T> { head: Link<T>, } // On remplace l'enum Link { Empty, More(Box<Node>), } par ceci : type Link<T> = Option<Box<Node<...
use std::fmt; use std::mem; use std::net::Ipv6Addr; use std::os::raw::{c_int, c_uchar, c_void}; use std::ptr; use std::slice; use itertools::Itertools; use crate::error::{Error, Result}; use crate::panic; use crate::types::MAX_ADDRTTLS; /// The result of a successful AAAA lookup. #[derive(Clone, Copy)] pub struct AA...
use std::fs::File; use std::io::{BufReader, BufRead}; use ndarray::{Array2, arr2, ArrayBase, Ix2, OwnedRepr}; use rand::prelude::*; use plotlib::view::ContinuousView; use plotlib::line; use plotlib::page::Page; use plotlib::style::Line; struct NeuralNetwork {} impl NeuralNetwork { fn new(activation_function: &F...
#![crate_name="orbimage"] #![crate_type="lib"] extern crate orbclient; extern crate resize; extern crate image; use std::{cmp, slice}; use std::path::Path; use std::error::Error; use std::cell::Cell; use orbclient::{Color, Renderer, Mode}; pub use resize::Type as ResizeType; pub struct ImageRoi<'a> { x: u32, ...
//! File format for the file stored. Need to have fast lookup for messages contained in the file. //! I think the best thing to do would be to have a header on the file so there is less of a chance //! from someone modifying the file accidently. All you would need to do is then loop through the //! files. //! //! # E...
#[doc = "Reader of register STREAM_ADDR"] pub type R = crate::R<u32, super::STREAM_ADDR>; #[doc = "Writer for register STREAM_ADDR"] pub type W = crate::W<u32, super::STREAM_ADDR>; #[doc = "Register STREAM_ADDR `reset()`'s with value 0"] impl crate::ResetValue for super::STREAM_ADDR { type Type = u32; #[inline(...
use std::ops::{Add, Div, Mul, Sub}; #[derive(Debug)] // TODO refactor Vec3 into just a tuple. // xyz doesn't always make sense, let's not name them, it makes the code more // confusing pub struct Vec3 { pub x: f32, pub y: f32, pub z: f32, } impl Vec3 { pub fn new(x: f32, y: f32, z: f32) -> Vec3 { ...
#![feature(test)] extern crate loge; extern crate test; #[macro_use] extern crate log; use test::Bencher; #[bench] fn b10_no_logger_active(b: &mut Bencher) { b.iter(use_error); } #[bench] fn b20_initialize_logger(_: &mut Bencher) { ::std::env::set_var("RUST_LOG", "trace"); ::std::env::set_var("LOGE_FORM...
use crate::atom::Package; use clap::{App, Arg, ArgMatches, Error, SubCommand}; pub(crate) const NAME: &str = "package"; pub(crate) const ABOUT: &str = "Validate/Parse a package(with category)"; pub(crate) fn subcommand<'x, 'y>() -> App<'x, 'y> { SubCommand::with_name(NAME).about(ABOUT).arg( Arg::with_name...