text
stringlengths
8
4.13M
use std::fs; use std::path::Path; use std::str; use clap::Parser; use cutter::imageprocessing::{str_to_size, transform_images, Size}; use cutter::s3::{download_from_s3, upload_to_s3}; use cutter::util::get_files_in_dir; mod cutter; extern crate clap; pub const DEFAULT_REGION: &str = "eu-central-1"; const DEFAULT_C...
#[macro_use] extern crate clap; #[macro_use] extern crate log; extern crate simplelog; mod day1; mod day2; mod io; use clap::App; use log::LevelFilter; use simplelog::TermLogger; use simplelog::CombinedLogger; use simplelog::Config; fn init_terminal_logger(log_level: LevelFilter) { CombinedLogger::init(vec![Term...
// brings io and Rng traits into scope // brings the Ordering enum type into scope use rand::Rng; use std::cmp::Ordering; use std::io; fn main() { println!("Guess the number!"); // thread_rng(): a random nr generator local to the current thread and seeded from the OS // gen_range(): method defined by the ...
#[doc = "Reader of register ACT_SRC"] pub type R = crate::R<u32, super::ACT_SRC>; #[doc = "Reader of field `SRC_ADDR`"] pub type SRC_ADDR_R = crate::R<u32, u32>; impl R { #[doc = "Bits 0:31 - Current address of source location."] #[inline(always)] pub fn src_addr(&self) -> SRC_ADDR_R { SRC_ADDR_R::n...
// This file is part of rdma-core. It is subject to the license terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/rdma-core/master/COPYRIGHT. No part of rdma-core, including this file, may be copied, modified, propagated, or distributed ...
//! Tests for nonce validity checks use aead::{generic_array::GenericArray, Aead, KeyInit}; use mgm::Mgm; #[test] fn kuznyechik_bad_nonce() { let key = GenericArray::from_slice(&[0u8; 32]); let mut nonce = GenericArray::clone_from_slice(&[0u8; 16]); let cipher = Mgm::<kuznyechik::Kuznyechik>::new(key); ...
//! B/W Color for EPDs //! //! EPD representation of multicolor with separate buffers //! for each bit makes it hard to properly represent colors here #[cfg(feature = "graphics")] use embedded_graphics_core::pixelcolor::BinaryColor; #[cfg(feature = "graphics")] use embedded_graphics_core::pixelcolor::PixelColor; /// ...
use specs::*; use types::systemdata::IsAlive; use types::*; use component::time::*; use std::f32::consts; use std::marker::PhantomData; use std::time::Duration; use airmash_protocol::server::{PlayerUpdate, ServerPacket}; use airmash_protocol::{to_bytes, ServerKeyState, Upgrades as ServerUpgrades}; use websocket::Own...
mod compile; use compile::Compile; use verified::*; const TRUE: B1 = B1; const FALSE: B0 = B0; #[test] fn can_verify_single_bool_identity_clause() { #[verify] fn f<B: Bit>(_: B) where _: Verify<{ B }>, { } f(TRUE); } #[test] fn can_verify_multiple_bool_identity_clauses() { #[verif...
use sdl2::render::{WindowCanvas, Texture, TextureQuery}; use std::path::Path; use sdl2::image::LoadTexture; use sdl2::rect::{Point, Rect}; use sdl2::ttf::FontStyle; use sdl2::pixels::Color; use crate::widgets::{Button, Image, Text}; macro_rules! rect( ($x:expr, $y:expr, $w:expr, $h:expr) => ( Rect::new($x ...
use std::io::{stdin, Read, StdinLock}; use std::str::FromStr; #[allow(dead_code)] struct Scanner<'a> { cin: StdinLock<'a>, } #[allow(dead_code)] impl<'a> Scanner<'a> { fn new(cin: StdinLock<'a>) -> Scanner<'a> { Scanner { cin } } fn read<T: FromStr>(&mut self) -> Option<T> { let token ...
extern crate rustty; use rustty::{ Terminal, Event, HasSize, CellAccessor }; use rustty::ui::core::{ Widget, HorizontalAlign, VerticalAlign, ButtonResult }; use rustty::ui::{ Dialog, StdButton, Canvas }; const BLOCK: char = '\u{25AA}'; fn create_optiondlg() -> Dialog { ...
extern crate lab_common; use std::hint::unreachable_unchecked; use lab_common::get_user_input; fn get_name() -> String { get_user_input( Some("Enter your first and last name separate by a space: ") ) } fn part1() { let mut name: String = get_name(); while let None = name.find(' ') { ...
use serde::{Deserialize, Serialize}; use tracing::instrument; use htsget_config::types::Query; use crate::{QueryBuilder, Result}; /// A struct to represent a POST request according to the /// [HtsGet specification](https://samtools.github.io/hts-specs/htsget.html). It implements /// [Deserialize] to make it more erg...
mod common; use common::{testenv, TestEnv, EXAMPLE_UNSUPPORTED}; use predicates::prelude::*; use rstest::rstest; const EXAMPLE_NOT_EXISTING: &str = "just/some/random/path"; const EXAMPLE_DIR: &str = "."; #[rstest] #[case(&["info", EXAMPLE_UNSUPPORTED.to_str().unwrap()])] #[case(&["preview", EXAMPLE_UNSUPPORTED.to_st...
use once_cell::sync::Lazy; use rusqlite::Connection; use std::sync::Mutex; pub static CONN: Lazy<Mutex<Connection>> = Lazy::new(|| Mutex::new(Connection::open("blog.db").unwrap()));
use azure_core::headers::{ account_kind_from_headers, date_from_headers, request_id_from_headers, sku_name_from_headers, }; use azure_core::RequestId; use chrono::{DateTime, Utc}; use http::HeaderMap; #[derive(Debug, Clone)] pub struct GetAccountInformationResponse { pub request_id: RequestId, pub date: Da...
#[doc = "Register `DDRCTRL_INIT1` reader"] pub type R = crate::R<DDRCTRL_INIT1_SPEC>; #[doc = "Register `DDRCTRL_INIT1` writer"] pub type W = crate::W<DDRCTRL_INIT1_SPEC>; #[doc = "Field `PRE_OCD_X32` reader - PRE_OCD_X32"] pub type PRE_OCD_X32_R = crate::FieldReader; #[doc = "Field `PRE_OCD_X32` writer - PRE_OCD_X32"]...
pub fn foo() { let _x = 5; }
//! Render utilities for graphics backend for game engine. use std::collections::HashSet; use std::iter; use std::sync::Arc; use egui::{ClippedMesh, Texture, TextureId}; use image::RgbaImage; use vulkano::buffer::{BufferUsage, DeviceLocalBuffer}; use vulkano::command_buffer::{ AutoCommandBufferBuilder, CommandBuf...
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT license. */ use byteorder::{LittleEndian, ReadBytesExt}; use rand::distributions::{Distribution, Uniform}; use std::fs::File; use std::io::{Read, Seek, SeekFrom, Write}; use std::mem; use crate::common::{ANNError, ANNResult}; us...
#[doc = "Register `AHB2ENR` reader"] pub type R = crate::R<AHB2ENR_SPEC>; #[doc = "Register `AHB2ENR` writer"] pub type W = crate::W<AHB2ENR_SPEC>; #[doc = "Field `GPIOAEN` reader - IO port A clock enable"] pub type GPIOAEN_R = crate::BitReader<GPIOAEN_A>; #[doc = "IO port A clock enable\n\nValue on reset: 0"] #[derive...
pub const SEEK_SET: u32 = 0; pub const SEEK_CUR: u32 = 1; pub const SEEK_END: u32 = 2;
pub mod item; // Reexports pub use item::{Debug, Item, Tool, Spell}; use crate::{ comp::HealthSource, effect::Effect, comp::spell::SpellShape }; use specs::{Component, HashMapStorage, NullStorage}; #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] pub struct Inventory { pub slots: Ve...
use wrapper_sys; pub fn add_numbers(a: i32, b: i32) -> i32 { unsafe { wrapper_sys::add_numbers(a, b) } } #[cfg(test)] mod tests { #[test] fn test_me() { assert_eq!(super::add_numbers(1, 2), 3); assert_eq!(super::add_numbers(4, 5), 9); } }
use crate::Point3D; use crate::static_optional::{StaticNone, StaticOptional, StaticSome}; #[derive(Default)] pub struct Point3DBuilder<X, Y, Z> where X: StaticOptional<Element = f64>, Y: StaticOptional<Element = f64>, Z: StaticOptional<Element = f64>, { x: X, y: Y, z: Z, } impl<Y, Z> Point3DBuilder<StaticNo...
use std::io::{self, ErrorKind}; use std::rc::Rc; use mio::net::TcpListener; use mio::unix::UnixReady; use mio::{Events, Poll, PollOpt, Ready, Token}; use slab; use connection::Connection; type Slab<T> = slab::Slab<T, Token>; pub struct Server { // main socket for our server sock: TcpListener...
use std::fs::File; use std::io::{BufRead, BufReader}; use std::str::Chars; use math::round; pub fn exercise() { let mut floor_plan: Vec<Vec<char>> = vec![vec!['_'; 8]; 128]; let mut seat_ids: Vec<i32> = Vec::new(); let data = load_data(); for ticket in data { let mut row_position = (0,127); ...
// Copyright 2013 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 crypto_hash::{hex_digest, Algorithm}; use hyper::{Body, Client, Method, Request}; use hyper_tls::HttpsConnector; use serde::{Deserialize, Serialize}; use std::error::Error; #[derive(Serialize, Deserialize)] pub struct ErrorData { pub error: ErrorInfo, } #[derive(Serialize, Deserialize)] pub struct ErrorInfo { ...
#[doc = "Register `CFGR3` reader"] pub type R = crate::R<CFGR3_SPEC>; #[doc = "Register `CFGR3` writer"] pub type W = crate::W<CFGR3_SPEC>; #[doc = "Field `TRIM1_NG_CCRPD` reader - SW trim value for RPD resistors on the CC1 line"] pub type TRIM1_NG_CCRPD_R = crate::FieldReader; #[doc = "Field `TRIM1_NG_CCRPD` writer - ...
#![allow(dead_code)] use std::path::Path; use std::{env, fs}; // const SETTINGS_FILE: &str = "Settings.toml"; const LOG4RS_FILE: &str = "log4rs.yaml"; fn main() { let target_dir_path = env::var("OUT_DIR").unwrap(); println!("Out dir = {}", target_dir_path); copy_to_examples(&target_dir_path, LOG4RS_FILE);...
use super::{PacketEncoder, PacketEncoderExt, SlotData}; use crate::player::Gamemode; use crate::utils::NBTMap; use serde::Serialize; use std::collections::HashMap; pub trait ClientBoundPacket { fn encode(&self) -> PacketEncoder; } // Server List Ping Packets pub struct CResponse { pub json_response: String, ...
use super::common::*; use std::path::{Path, PathBuf}; use anyhow::{Result, anyhow, bail}; use std::collections::{BTreeMap, BTreeSet}; use serde::Deserialize; #[derive(Debug)] pub struct Mandir { cat: Catalogue, manpath: Vec<PathBuf>, mandoc: PathBuf, sections: BTreeSet<String>, subsections: BTreeSe...
#[doc = "Register `I3C_TIMINGR0` reader"] pub type R = crate::R<I3C_TIMINGR0_SPEC>; #[doc = "Register `I3C_TIMINGR0` writer"] pub type W = crate::W<I3C_TIMINGR0_SPEC>; #[doc = "Field `SCLL_PP` reader - SCL low duration in I3C push-pull phases, in number of kernel clocks cycles: tSCLL_PP = (SCLL_PP + 1) x tI3CCLK SCLL_P...
use embedded_hal::blocking::delay::DelayMs; use embedded_hal::blocking::spi; use embedded_hal::digital::v2::{InputPin, OutputPin}; struct EpdInterface<SPI, RST, BUSY, ECS, DC> { spi: SPI, rst: RST, busy: BUSY, ecs: ECS, dc: DC, } impl<SPI, RST, BUSY, ECS, DC> EpdInterface<SPI, RST, BUSY, ECS, DC> ...
#[doc = "Register `WKUPCR` reader"] pub type R = crate::R<WKUPCR_SPEC>; #[doc = "Register `WKUPCR` writer"] pub type W = crate::W<WKUPCR_SPEC>; #[doc = "Field `WKUPC` reader - Clear Wakeup pin flag for WKUP. These bits are always read as 0."] pub type WKUPC_R = crate::FieldReader; #[doc = "Field `WKUPC` writer - Clear ...
use crate::{Entity, Log, OnRemove}; use attached::Var; use parking_lot::RwLock; pub type Deps = RwLock<Vec<Box<dyn Fn(&mut Vars) + Send + Sync>>>; pub type LogVar<T> = Var<T, vars::Log>; pub type TblVar<T> = Var<T, vars::Tbl>; pub trait Accessor: Sized + 'static { fn var() -> &'static TblVar<Self>; fn deps() ...
fn main() { let test = vec!["one", "two", "three"]; let index = test.iter().position(|&r| r == "two").unwrap(); println!("{}", index); }
extern crate iron; extern crate router; use std::io::Read; use iron::prelude::*; use iron::status; use router::Router; use std::io::prelude::*; use std::fs::File; use std::io::BufWriter; fn main(){ MainLoop(); } fn MainLoop(){ let mut router = Router::new(); router.post("/", catchIP, "catchIP"); ...
fn main() { // let my_vector: Vec<i8> = Vec::new(); let mut my_vector = vec![1, 2, 3, 4, 5]; println!("Vector at 2: {}", my_vector[2]); my_vector.push(6); my_vector.remove(2); for n in my_vector { println!("{}", n); } }
#[doc = "Register `MISR` reader"] pub type R = crate::R<MISR_SPEC>; #[doc = "Field `ALRAMF` reader - Alarm A masked flag"] pub type ALRAMF_R = crate::BitReader<ALRAMF_A>; #[doc = "Alarm A masked flag\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum ALRAMF_A { #[doc = "1: This flag is set...
use libbeaglebone::enums::DeviceState; use libbeaglebone::pwm::PWM; use libbeaglebone::pwm::PWMState; use crate::pinouts::analog::output::AnalogOutput; use crate::pinouts::analog::output::PwmOutput; pub struct LibBeagleBonePwm { pwm: PWM, period: u32, } impl AnalogOutput for LibBeagleBonePwm { fn set_val...
use advent20::input_string; use anyhow::*; use itertools::iproduct; fn part1(input: &[u32]) -> Option<u32> { iproduct!(input, input) .filter(|(&x, &y)| x + y == 2020) .next() .map(|(x, y)| x * y) } fn part2(input: &[u32]) -> Option<u32> { iproduct!(input, input, input) .filter(...
use specs::Join; pub struct AttractedSystem { collided: Vec<(::specs::Entity, f32)>, } impl AttractedSystem { pub fn new() -> Self { AttractedSystem { collided: vec![] } } } impl<'a> ::specs::System<'a> for AttractedSystem { type SystemData = ( ::specs::ReadStorage<'a, ::component::Pl...
use crate::camera::{Camera, CameraConfig}; use crate::color::color; use crate::hittable::{ box3d::Box3D, bvh::BvhNode, hittable_list::HittableList, rect::{XyRect, XzRect, YzRect}, rotate::{RotateX, RotateY, RotateZ}, Hittables, }; use crate::material::{diffuse::Diffuse, lambertian::Lambertian}; ...
extern crate proc_macro; use sde_specs::Schema; use sde_specs_macro::Schema; #[derive(Schema)] pub struct Point { pub x: u32, pub y: u32, } fn main() { Point::to_schema(); let sample = syn::parse_str::<syn::Item>("pub struct Point { pub x: u32, pub y: u32, }").unwrap(); dbg!...
//! Process and store MARC data. //! //! This module provides support for parsing MARC data from XML (in both //! Library of Congress and VIAF formats), and for storing MARC data in //! Parquet files as a flat table of MARC fields. pub mod book_fields; pub mod flat_fields; pub mod parse; pub mod record; pub use record...
use super::constants::*; pub fn sine_wave(freq: f32, t: f32, offset: f32) -> f32 { ((t * freq + offset) * PI * 2.0).sin() } pub fn square_wave(freq: f32, t: f32, offset: f32) -> f32 { sine_wave(freq, t, offset).signum() } pub fn sawtooth_wave(freq: f32, t: f32, offset: f32) -> f32 { (2.0 * ((t * freq + o...
use std::io::prelude::*; use mio::tcp::*; use http::*; use app_server::*; pub use regex::Regex; pub trait Handler : Send + 'static { fn process(&mut self, request: Request, response: &mut Response); fn duplicate(&self) -> Box<Handler>; } struct HandlerRule(Regex, Box<Handler>); pub struct HandlerRoute(pub Str...
fn main() { fizzbuzz(50); } fn fizzbuzz(count: usize) { for i in 1..(count + 1) { match i { i if i % 5 == 0 => println!("FizzBuzz"), i if i % 3 == 0 => println!("Fizz"), _ => println!("{}", i), } } }
// MIT License // // Copyright (c) 2018-2021 Hans-Martin Will // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, cop...
// Copyright 2016 Google Inc. All Rights Reserved. // // Licensed under the MIT License, <LICENSE or http://opensource.org/licenses/MIT>. // This file may not be copied, modified, or distributed except according to those terms. /// Creates an enum where each variant contains a `Future`. The created enum impls `Future`...
#[doc = "Reader of register BUFF_CTL"] pub type R = crate::R<u32, super::BUFF_CTL>; #[doc = "Writer for register BUFF_CTL"] pub type W = crate::W<u32, super::BUFF_CTL>; #[doc = "Register BUFF_CTL `reset()`'s with value 0x01"] impl crate::ResetValue for super::BUFF_CTL { type Type = u32; #[inline(always)] fn...
// Copyright 2018 (c) rust-themis developers // // 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 o...
#![doc = "generated by AutoRust 0.1.0"] #![allow(non_camel_case_types)] #![allow(unused_imports)] use serde::{Deserialize, Serialize}; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Operation { #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serd...
#![feature(assert_matches)] mod archiver; mod piece_reconstruction; mod reconstructor;
pub mod tables; pub mod pages; use super::interrupts::InteruptStack; use self::tables::{EntryFlags, address_to_tables}; use self::pages::{alloc_page}; pub fn handle_page_fault(_vars: &mut InteruptStack) { let cr2: u64; unsafe { asm!("mov $0, cr2" : "=r"(cr2) ::: "intel"); } let pages = addres...
/// The base node struct that contains props, and a Vec of child nodes. #[derive(Debug)] pub struct RusxNode<T: Default> { /// The node's props. The only required traits to implement are `Debug` and `Default` pub props: T, /// A vector of child nodes. Can be empty. pub children: Vec<RusxNode<T>>, } impl<T...
use sudo_test::{Command, Env, TextFile}; use crate::{helpers, Result, SUDOERS_ALL_ALL_NOPASSWD, USERNAME}; macro_rules! assert_snapshot { ($($tt:tt)*) => { insta::with_settings!({ prepend_module_to_snapshot => false, snapshot_path => "../snapshots/path_search", }, { ...
use core::ops::Mul; /// Complex and hypercomplex transformation basic trait. pub trait Transform<U> { /// Apply the transformation. fn apply(&self, x: U) -> U; } /// Transformation that has an identity element. pub trait Identity { /// Get an identity element. fn identity() -> Self; } /// Transforma...
use glob::{GlobError, PatternError}; use std::ffi::OsString; use std::fmt::{self, Display}; use std::io; use std::path::PathBuf; #[derive(Debug)] pub enum Error { Cargo(io::Error), CargoFail, GetManifest(PathBuf, Box<Error>), Glob(GlobError), Io(io::Error), Metadata(serde_json::Error), Mism...
//use tokio_io::{try_nb, AsyncRead, AsyncWrite}; // //use super::tokio_tls; //use super::tokio_tls::client; //use super::tokio_tls::entry; //use super::tokio_tls::server; //use core::fmt::Pointer; //use futures::{Async, Future, Poll}; //use rustls::{ClientConfig, ClientSession, ServerConfig, ServerSession, Stream}; //u...
// Copyright 2019 Google LLC // // 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 in ...
use std::env; use std::fs; use std::io::{self, BufRead, Write}; mod scanner; mod token; use crate::scanner::*; use crate::token::*; fn run(source: &str) { //println!("{} lines of source", source.lines().count()); let tokens: Vec<Result<Token, ScannerError>> = Scanner::new(source.chars()).collect(); print...
#![cfg(test)] use problem1::{sum, dedup, filter}; use problem2::mat_mult; use problem3::sieve; use problem4::{hanoi, Peg}; // // Problem 1 // // Part 1 #[test] fn test_sum_small() { let array = [1,2,3,4,5]; assert_eq!(sum(&array), 15); } // Part 2 #[test] fn test_dedup_small() { let vs = vec![1,2,2,3,4...
/// This module handles the deserialization of the humble bundle monthly trove metadata feed. /// It provides operations that deal with the contents of the feed itself. use crate::cache::Cache; use chrono::{NaiveDateTime, Utc}; use failure::Error; use log::{debug, info, warn}; use select::{document::Document, predicate...
use generic_array::GenericArray as Array; use typenum::*; use super::*; #[inline] pub fn translate<A: Copy, N>(a: Matrix<A, N>) -> Matrix<A, Add1<N>, Add1<N>> where A: Zero + One, N: Add<B1> + ArrayLength<A>, Add1<N>: ArrayLength<A> + ArrayLength<GenericArray<A, Add1<N>>> { unsafe { let mut c = ...
pub struct SelectList<T> { payload: Vec<T>, selected_idx: usize, } impl<T> SelectList<T> { pub fn new(payload: Vec<T>, selected_idx: usize) -> Self { Self { payload, selected_idx, } } pub fn selected_idx(&self) -> usize { self.selected_idx } ...
//! `iui`, the `i`mproved `u`ser `i`nterface crate, is a **simple** (about 4 kLOC of Rust), **small** (about 800kb, including `libui`), **easy to distribute** (one shared library) GUI library, providing a **Rusty** user interface library that binds to **native APIs** via the [libui](https://github.com/andlabs/libui) an...
pub fn bubble_sort<T: PartialOrd>(list: &mut [T]) { let size = list.len(); for i in 0..(size - 1) { let mut swapped = false; for j in 0..(size - 1 - i) { if list[j] > list[j + 1] { list.swap(j, j + 1); swapped = true; } } if...
use std::slice; use ::ffi; use traits::FromRaw; pub struct MaterialProperty<'a> { raw: &'a ffi::AiMaterialProperty, } impl<'a> FromRaw<'a, MaterialProperty<'a>> for MaterialProperty<'a> { type Raw = *const ffi::AiMaterialProperty; #[inline(always)] fn from_raw(raw: &'a Self::Raw) -> MaterialPropert...
use std::borrow::{Borrow, BorrowMut}; use std::cmp::Ordering; use std::fmt; use std::hash::{Hash, Hasher}; use std::ops::{Deref, DerefMut}; /// Original position of element in source code #[derive(PartialOrd, Ord, PartialEq, Eq, Clone, Copy, Default, Hash)] pub struct Pos { /// One-based line number pub line: ...
use hacspec_dev::prelude::*; use hacspec_ed25519::*; use hacspec_edwards25519::*; use hacspec_lib::*; use quickcheck::QuickCheck; // Test vectors from https://datatracker.ietf.org/doc/rfc8032 create_test_vectors!( IetfTestVector, secret_key: String, public_key: String, message: String, signature: S...
use std::sync::{ atomic::{AtomicUsize, Ordering}, Arc, }; #[async_metronome::test] async fn test_ordering() { let ai1 = Arc::new(AtomicUsize::new(0)); let ai2 = ai1.clone(); let ai3 = ai1.clone(); let ordering = Ordering::SeqCst; let task1 = async move { ai1.compare_and_swap(0, 1,...
use std::collections::BTreeMap; #[derive(Eq, PartialEq, Copy, Clone)] pub enum TransactionType { Read, Write, } pub(super) struct TransactionState { pub(super) ty: TransactionType, pub(super) offset_map: BTreeMap<u32, u64>, pub(super) frame_count: u32, pub(super) db_file_size: u64, } impl Tra...
use bellman::gadgets::multipack; use bellman::groth16; use bitvec::{order::Lsb0, view::AsBits}; use blake2s_simd::Params as Blake2sParams; use bls12_381::Bls12; use ff::{Field, PrimeField}; use group::{Curve, GroupEncoding}; use rand::rngs::OsRng; use std::io; use std::time::Instant; use super::coin::merkle_hash; use ...
//! This module holds some macros that should be usable everywhere within the //! kernel. /// Creates a `&'static str` from a c string. /// /// Converts the string at the given address from a c string to a rust /// `&'static str`. /// Optionally if the length is known, the process can be sped up, by passing /// it. #[...
///! Server control command ///! use std::fmt; use std::net::SocketAddr; use crate::session::SessionId; pub enum ServerCommand<T> { /// terminate Terminate, /// connected stream and client address Connect(T, SocketAddr), Disconnect(SessionId), } impl<T> fmt::Debug for ServerCommand<T> { fn fm...
/** * Implements Default for an enum. * Requires the enum to have a variant named "Default" */ #[macro_export] macro_rules! enum_default { ($name: ident) => { impl Default for $name { fn default() -> Self { $name::Default } } }; } /** * Implements a fmt trait for an enum. * The output is the enum ...
pub mod error; use error::Error; pub mod ioops; use ioops::{create_and_write_archive, Manifest}; pub mod runtime; use runtime::Operation; use std::fs::File; pub fn run(operation: Operation) -> Result<(), Error> { match operation { Operation::Backup(profile_path, archive_file_name) => { let prof...
use bitcoin::util::base58; use byteorder::{LittleEndian, ReadBytesExt}; use hex; use std::io::prelude::*; use std::io::Cursor; use std::io::SeekFrom; use enums::TransactionType; use identities::{address, public_key}; use transactions::transaction::{Asset, Transaction}; use utils; pub fn deserialize(serialized: &str) ...
use serde::de::{self, Deserialize, Deserializer, Visitor}; use serde_derive::Deserialize; use std::fmt; #[derive(Deserialize)] #[serde(deny_unknown_fields)] pub struct InheritEdition { pub workspace: True, } pub struct True; impl<'de> Deserialize<'de> for True { fn deserialize<D>(deserializer: D) -> Result<S...
use regex::Regex; #[derive(Debug, PartialEq, Eq)] pub struct Passport { birth_year: Option<String>, issue_year: Option<String>, expiration_year: Option<String>, height: Option<String>, hair_color: Option<String>, eye_color: Option<String>, passport_id: Option<String>, country_id: Option...
// TODO use https://docs.rs/embedded-graphics/0.7.1/embedded_graphics/draw_target/trait.DrawTargetExt.html // to clip while scrolling use crate::hal::prelude::{OutputPin, _embedded_hal_blocking_delay_DelayUs as DelayUs}; use display_interface::WriteOnlyDataCommand; use pinetime_common::embedded_graphics::{ draw_ta...
/** Single item to verification: - SP Trie with RootHash - BLS MS - set of key-value to verify */ #[derive(Serialize, Deserialize, Debug)] pub struct ParsedSP { /// encoded SP Trie transferred from Node to Client pub proof_nodes: String, /// RootHash of the Trie, start point for verification. Should be ...
use std::fs::File; use std::io::{BufRead, BufReader}; use std::collections::HashSet; pub fn exercise() { let data = load_data(); compute_manhattan_distance(data); } fn compute_manhattan_distance(data: Vec<String>) { let directions = vec!['N','E','S','W']; let mut current_direction = 'E'; let mut east_west_po...
mod common; mod list; mod medal; mod missing; mod recent; pub mod stats; use std::sync::Arc; use rosu_v2::prelude::Username; use twilight_model::application::{ command::CommandOptionChoice, interaction::{ application_command::{CommandDataOption, CommandOptionValue}, ApplicationCommand, }, ...
// Copyright (c) The Starcoin Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::get_unix_ts; use anyhow::{Error, Result}; use futures::lock::Mutex; use hex; use libra_crypto::HashValue; use libra_logger::prelude::*; use libra_types::account_address::{AccountAddress, ADDRESS_LENGTH}; use rand::prelude...
mod json; mod linefile; mod node; mod notebook; mod page; mod render; use crate::node::{parse_nodes, Node}; use crate::notebook::Notebook; use crate::render::render_notebook; use serde::{Deserialize, Serialize}; use std::error::Error; use std::fs::File; use std::path::Path; use std::path::PathBuf; use structopt::Struc...
async fn foo(id: i32) { for i in 1..10 { println!("hi number {} in foo({}).", i, id); std::thread::sleep(std::time::Duration::from_millis(1000)); } } fn main() { let task = async { foo(10).await ; foo(20).await ; foo(30).await ; }; println!("program start."); ...
pub mod download_link; pub mod file_details; pub mod file_list; pub mod games; pub mod md5_search; pub mod mod_info; pub mod queriable; pub mod search; pub use self::download_link::*; pub use self::file_details::*; pub use self::file_list::*; pub use self::games::*; pub use self::md5_search::*; pub use self::mod_info:...
// =============================================================================================== // Configuration // =============================================================================================== #![feature( allocator, const_fn, )] #![no_std] #![allocator] // ==============================...
// Copyright 2017 Dmitry Tantsur <divius.inside@gmail.com> // // 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 ap...
fn sjf(jobs: &[usize], index: usize) -> usize { jobs.iter() .enumerate() .filter(|&(i, &x)| x < jobs[index] || x == jobs[index] && i <= index) .map(|(_, x)| x) .sum() } #[test] fn returns_expected() { assert_eq!(sjf(&[100], 0), 100); assert_eq!(sjf(&[3,10,20,1,2], 0), 6); assert_eq!(sjf(&[3,3,3,10,20,1,...
#![doc = "generated by AutoRust 0.1.0"] #![allow(non_camel_case_types)] #![allow(unused_imports)] use serde::{Deserialize, Serialize}; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AvailableRpOperation { #[serde(default, skip_serializing_if = "Option::is_none")] pub display: Option<Avail...
use super::{Camera, Location, SizeCollection}; use crate::{config::ExifConfig, models::size, tools::replace_pairs}; use chrono::{DateTime, FixedOffset}; use core::cmp::Ordering; use serde::{Deserialize, Serialize}; /// Unique path to any blog photo #[derive(Serialize, Deserialize, Debug, Clone)] pub struct PhotoPath {...
//! Defines additional methods on RistrettoPoint for Lizard #![allow(non_snake_case)] use digest::Digest; use digest::generic_array::typenum::U32; use constants; use field::FieldElement; use subtle::ConditionallySelectable; use subtle::ConstantTimeEq; use subtle::Choice; use edwards::EdwardsPoint; use lizard::jac...
tonic::include_proto!("common/common");
use usd_plugin::info::{PluginInfo, PluginVariants}; #[test] fn deserialize_single_plugin_info() { let data = r#" { "Type": "library", "Name": "MyPlugin", "Root": "/foo", "LibraryPath": "lib", "ResourcePath": "resources", "Info": { "value": 1 }...