text
stringlengths
8
4.13M
#[macro_use] extern crate log; extern crate clap; extern crate env_logger; extern crate hyper; extern crate raft; extern crate rustc_serialize; use std::env; use std::fs::File; use std::io::Read; use std::path::Path; use std::sync::Arc; use std::thread; use clap::App; use hyper::Server; use hyper::service::{make_serv...
use serde::Serializer; use graphers_core::{MissingArgument, MissingType, TypeKindError, CoercionError}; use std::fmt; pub enum SelectError<S> where S: Serializer { SerializationSerror(S::Error), MissingArgument(MissingArgument), MissingType(MissingType), TypeKindError(TypeKindError), CoercionError(...
extern crate libc; extern crate coreaudio_sys; use cocoa::appkit::{ NSApp, NSApplication, NSBackingStoreBuffered, NSEvent, NSEventMask, NSEventModifierFlags, NSEventType, NSMenu, NSMenuItem, NSWindow, NSWindowStyleMask, }; use cocoa::base::{id, nil, selector, NO}; use cocoa::foundation::{ NSAutoreleasePoo...
/* <참쑰자의 κ·œμΉ™> - μ–΄λ– ν•œ κ²½μš°μ΄λ“  간에, μ—¬λŸ¬λΆ„μ€ μ•„λž˜ λ‘˜ λ‹€λŠ” μ•„λ‹ˆκ³  λ‘˜ 쀑 ν•˜λ‚˜λ§Œ κ°€μ§ˆ 수 μžˆμŠ΅λ‹ˆλ‹€: - ν•˜λ‚˜μ˜ κ°€λ³€ 참쑰자 - μž„μ˜ 개수의 λΆˆλ³€ μ°Έμ‘°μžλ“€ - μ°Έμ‘°μžλŠ” 항상 μœ νš¨ν•΄μ•Όλ§Œ ν•œλ‹€. */ fn main() { // let mut s1 = String::from("hello"); let len = calculate_length(&s1); println!("The length of '{}' is {}.", s1, len); // change(&mut s1); // l...
use aoc_runner_derive::{aoc, aoc_generator}; use itertools::Itertools; #[aoc_generator(day6)] fn generator_input(input: &str) -> Vec<char> { input.chars().collect() } #[aoc(day6, part1)] fn part1(signal: &[char]) -> usize { find_start_of_packet_pos(signal, 4) } #[aoc(day6, part2)] fn part2(signal: &[char]) -...
extern crate iron; extern crate time; extern crate e_web; extern crate serde_json; #[macro_use] extern crate serde_derive; extern crate serde; use serde::ser::Serialize; use iron::prelude::*; use iron::{BeforeMiddleware, AfterMiddleware, typemap}; use time::precise_time_ns; use e_web::RenderBuilder; use std::collectio...
//@revisions: stack tree //@[tree]compile-flags: -Zmiri-tree-borrows //@error-in-other-file: is a dangling pointer use std::ptr::NonNull; fn main() { unsafe { let ptr = NonNull::<i32>::dangling(); drop(Box::from_raw(ptr.as_ptr())); } }
use chargrid::*; use common_event::*; use event_routine::*; use general_audio::{AudioHandle, AudioPlayer}; use render::*; use std::marker::PhantomData; #[derive(Clone, Copy)] enum MenuEntry { Sneeze, Bark, Horn, } impl<'a> From<&'a MenuEntry> for &'a str { fn from(menu_entry: &'a MenuEntry) -> Self { ...
// To run // rustc rust.rs // ./rust use std::env; use std::io::{self, Write}; use std::io::prelude::*; fn main() -> io::Result<()>{ unsafe { libc::signal(libc::SIGPIPE, libc::SIG_DFL); } let args: Vec<String> = env::args().collect(); let arg = &args[1]; let n:i32 = arg.trim().parse().expe...
use crate::{SlackRequest, LayoutBlock, TextObject, View, PostMessageResponse}; use serde::{Serialize, Deserialize}; use serde_json::Value; #[derive(Serialize, Deserialize, Default, Debug)] #[serde(default)] pub struct ViewUpdate { view: View, #[serde(skip_serializing_if = "Option::is_none")] external_id: O...
#![no_std] extern crate owasm_std; extern crate owasm_ethereum; use owasm_std::write_u32; use owasm_std::hash::H256; use owasm_ethereum::{ret, read}; fn get_value_from_key(key: u32) -> [u8; 32] { let mut full_key = [0u8; 32]; write_u32(&mut full_key[0..4], key); read(&H256::from(full_key)) } #[no_mangle] pub fn ...
extern crate sit_core; extern crate chrono; use chrono::prelude::*; extern crate tempfile; #[macro_use] extern crate clap; use std::env; use std::path::PathBuf; use std::fs; use std::process::exit; use clap::{Arg, App, SubCommand}; use sit_core::{Issue, Record}; use sit_core::issue::IssueReduction; extern crate se...
use tiny_skia::*; #[test] fn clone_rect_1() { let mut pixmap = Pixmap::new(200, 200).unwrap(); let mut paint = Paint::default(); paint.set_color_rgba8(50, 127, 150, 200); paint.anti_alias = true; pixmap.fill_path( &PathBuilder::from_circle(100.0, 100.0, 80.0).unwrap(), &paint, ...
pub use zkp_component::ZKPComponent; #[cfg(feature = "zkp-prover")] pub mod proof_gen_utils; pub mod proof_store; pub mod proof_utils; #[cfg(feature = "zkp-prover")] pub mod prover_binary; pub mod types; pub mod zkp_component; #[cfg(feature = "zkp-prover")] pub mod zkp_prover; pub mod zkp_requests;
use std::collections::HashMap; use std::io; use async_std::fs; use futures::StreamExt; use serde_json; use tokio::sync::mpsc; use crate::app; use crate::comm::Sender; #[derive(Debug)] pub enum AppMsg { InMsg(String, String), EndMsg(String, u64), // ends the given appid OutMsg(String, String), // Allow...
use std::pin::Pin; use std::future::Future; use crate::stdio::*; use crate::eval::EvalContext; pub(super) fn export(args: &[String], ctx: &mut EvalContext, stdio: Stdio) -> Pin<Box<dyn Future<Output = i32>>> { if args.len() == 1 || args[1] == "-p" { let output = ctx.env .iter() .fi...
use crate::credentials::Credential; use crate::storage::FileSystem; use crate::xenon::{self as x, scheduler_service_client::SchedulerServiceClient}; use anyhow::Result; use std::collections::HashMap; use tonic::transport::Channel; type Map<T> = std::collections::HashMap<String, T>; /// Represents a scheduler that can...
#![feature(const_fn)] #![feature(get_mut_unchecked)] pub mod angle; pub mod frequency; pub mod player; pub mod rate; pub mod signal; pub mod voltage; pub use self::angle::*; pub use self::frequency::*; pub use self::player::*; pub use self::rate::*; pub use self::signal::*; pub use self::voltage::*;
/// Returns the nearest number that is `>=` than `num` and is a multiple of 64 #[inline] pub fn round_upto_multiple_of_64(num: usize) -> usize { round_upto_power_of_2(num, 64) } /// Returns the nearest multiple of `factor` that is `>=` than `num`. Here `factor` must /// be a power of 2. pub fn round_upto_power_of_...
//! Binary formatting #![no_main] #![no_std] use panic_never as _; // this program contains zero core::panic* calls #[no_mangle] fn main() -> ! { let a = hal::cyccnt(); semidap::info!("The answer is {}", 0.12345678); // ^ this sends the byte sequence: // [2, 1, 0, 8, 233, 214, 252, 61] // | | ...
use crate::nes::cpu::{Cpu,FromRelative}; use crate::nes::cpu::status::Flags; use super::branch::Branch; pub struct Bmi { } impl FromRelative for Bmi { fn from_relative(cpu: &mut Cpu) -> u32 { Branch::branch_on_true(cpu, |c| c.SR.is_set(Flags::Negative)); 2 } } #[cfg(test)] mod test { use...
#[doc = "Reader of register UIDMH"] pub type R = crate::R<u32, super::UIDMH>; #[doc = "Reader of field `UID95_64`"] pub type UID95_64_R = crate::R<u32, u32>; impl R { #[doc = "Bits 0:31 - Unique Identification UID\\[95:64\\]"] #[inline(always)] pub fn uid95_64(&self) -> UID95_64_R { UID95_64_R::new(...
use sha2::{Digest, Sha256}; use std::slice; use crate::cvec::cvec; /// Calculate the SHA256 hash of the given bytes. #[no_mangle] pub unsafe extern "C" fn rpgp_hash_sha256( bytes_ptr: *const u8, bytes_len: libc::size_t, ) -> *mut cvec { assert!(!bytes_ptr.is_null()); assert!(bytes_len > 0); let b...
use std::{thread, time}; use std::io::{self, Write}; extern crate notify_rust; use notify_rust::Notification; const HELP: &'static str = r#" NAME prod - a simple Pomodor timer DESCRIPTION List information about the FILE(s), or the current directory COMMANDS help show this help work ...
use crate::fastate::*; use unit::*; #[derive(Clone)] pub struct Nfa { pub states: Vec<FaState>, pub head: usize, pub tail: usize, } impl Nfa { pub fn add_offset(&mut self, offset: usize) { self.head += offset; self.tail += offset; for state in &mut self.states { sta...
#![deny(warnings)] use clap::{App, Arg}; use rand::distributions::Alphanumeric; use rand::Rng; use std::io::{Read, Write}; use std::net::{Shutdown, TcpStream, ToSocketAddrs}; use std::thread; use std::time::{Duration, Instant}; use termion::color; mod average; use average::Average; const READ_TIMEOUT: u64 = 200; //[...
use petgraph; use petgraph::graphmap::GraphMap; use petgraph::visit::{Dfs, Reversed, Walker}; use petgraph::Directed; use petgraph::Direction; use rspirv::binary::Disassemble; use rspirv::mr::{BasicBlock, Function, Instruction, Module, Operand}; use rustc::mir; use rustc_data_structures::graph::{ iterate::post_orde...
//Anything related to DELETE requests for review app and it's properties goes here. use super::{ReviewApp, ReviewAppConfig}; use crate::framework::endpoint::{HerokuEndpoint, Method}; /// Review App Delete /// /// Delete an existing review app /// /// [See Heroku documentation for more information about this endpoint]...
pub use self::beatmap_button::BeatmapButton; pub use self::map_selection_event::MapSelectionEvent; pub use self::map_selection_ui_event_handler_system::MapSelectionUiEventHandlerSystem; mod beatmap_button; mod map_selection_event; mod map_selection_ui_event_handler_system;
use crate::common::*; pub(crate) struct Bin { path: PathBuf, pub(crate) subcommands: Vec<BinSubcommand>, } impl Bin { #[throws] pub(crate) fn new(path: &Path) -> Bin { let mut bin = Bin { path: path.into(), subcommands: Vec::new(), }; bin.add_subcommands(&mut Vec::new())?; bin.su...
#![no_std] fn main() { extern crate std; }
pub const BLOCKSIZE: usize = 11; pub const QUALITY_LEVEL: f64 = 1.0; pub const NUM_FEATURES: usize = 100; pub const LINEAR_VELOCITY_NOISE: f64 = 4.0; pub const ANGULAR_VELOCITY_NOISE: f64 = 6.0; pub const NUM_SIGMA: f64 = 3.0; pub const NUM_PARTICLES: usize = 100; pub const MIN_DISTANCE_HYPOTHESIS: f64 = 0.5; pub const...
use regex::Regex; use std::{ collections::{BTreeMap, BTreeSet}, cmp::Ordering }; fn part1() { let steps = utils::lines_from_file(String::from("day7.txt")).expect("Unable to load results from file"); let matcher = Regex::new(r"Step ([A-Z]) must be finished before step ([A-Z]) can begin.").expect("Unab...
#![feature(core)] #![feature(libc)] extern crate libc; mod bindings; pub mod gpgme; pub mod keys;
use crate::types::{IanaTag, Special, Type}; use std::str::Utf8Error; use thiserror::Error; #[derive(Error, Debug, Clone)] pub enum CborError { #[error("could not take array: {}", _0)] ArrayTakeError(String), #[error("unknown error occurred: {}", _0)] Unknown(String), #[error("expected bool but got...
/// Options for requests to https://op-developer.fi #[derive(Default)] pub struct Options { api_key: String, authorization: String, version: String, base_url: String, } impl Options { /// Creates new Options struct for production access /// /// Keep in mind that authorization must be feched...
pub mod handlers; extern crate actix_web; use actix_web::{ error, middleware, web, App, Error, HttpRequest, HttpResponse, HttpServer, }; use mongodb::{Client, options::ClientOptions, options::FindOptions, Database}; use bson::{doc, bson}; use bytes::{Bytes, BytesMut}; use futures::StreamExt; use json::JsonValue; ...
use super::cbff_structs::{ObjectType, SectorType}; use std::borrow::Cow; pub type CbffResult<T> = Result<T, CbffError>; #[derive(Debug, PartialEq)] pub struct CbffError { error: CbffErrorEnum, } #[derive(Debug, PartialEq)] pub enum CbffErrorEnum { IndexOutOfRange, DavidCantCount, InvalidDirectory, ...
#![allow(unused_imports)] use itertools::Itertools; use proconio::{fastout, input, marker::*}; #[fastout] fn main() { input! { n: Chars }; let ans = n.iter().map(|&c| if c == '9' { "1" } else { "9" }).join(""); println!("{}", ans); }
#[allow(unused_imports)] use serde_json::Value; #[derive(Debug, Serialize, Deserialize)] pub struct NfsAliases { #[serde(rename = "aliases")] pub aliases: Option<Vec <crate::models::NfsAliasExtended>>, }
use std::borrow::Cow; use std::fs::ReadDir; use std::io::Result as IoResult; use std::iter::Once; use std::path::Path; pub(crate) enum ItemPathsInner<'a> { ReadDir(ReadDir), Single(Once<&'a Path>), } impl<'a> Iterator for ItemPathsInner<'a> { type Item = IoResult<Cow<'a, Path>>; fn next(&mut self) ->...
use std::sync::Arc; use crate::vector::*; use crate::ray::Ray; use crate::material::Material; #[derive(Clone)] pub struct HitRecord { pub position: Vector3, pub normal: Vector3, pub material: Arc<dyn Material>, pub t: f64, pub u: f64, pub v: f64, pub front: bool, } impl HitRecord { pu...
//// Copyright 2018 Grove Enterprises 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 applica...
fn main() { let mut s1 = String::from("hey there"); s1.push_str(", you world you"); println!("{}", s1); }
#[macro_use] extern crate nom; #[macro_use] extern crate itertools; extern crate crc; mod internal; mod parser; mod writer; use serde::{Serialize, Deserialize}; #[derive(Debug, Serialize, Deserialize, Clone)] pub struct Nus3audioFile { pub files: Vec<AudioFile>, } #[derive(Debug, Serialize, Deserialize, Clone)]...
/** * A custom mutable iterator for Matrix that runs over the rows of an instance * instead of doing it for each element individually. */ pub struct MatrixRowIterMut<'a, T> where T: 'a, { data: &'a mut [T], cols: usize, data_idx: usize, } impl<'a, T> MatrixRowIterMut<'a, T> where T: 'a, { pu...
mod sphere; mod traits; pub use sphere::*; pub use traits::*; type HittableVec = Vec<Box<dyn Hittable>>; pub struct HittableCollection { objects: HittableVec, } impl HittableCollection { pub fn new() -> HittableCollection { HittableCollection { objects: vec![] } } pub fn add(&mut self, hitta...
extern crate wasm_bindgen_cli_support as cli; use std::env; use std::fs::{self, File}; use std::io::{Write, Read}; use std::path::{PathBuf, Path}; use std::process::Command; use std::sync::atomic::*; use std::sync::{Once, ONCE_INIT}; use std::time::Instant; static CNT: AtomicUsize = ATOMIC_USIZE_INIT; thread_local!(s...
#[doc = r"Register block"] #[repr(C)] pub struct RegisterBlock { #[doc = "0x00 - Control Register"] pub ctrl: CTRL, #[doc = "0x04 - Wide Arithmetic Configuration"] pub wac: WAC, #[doc = "0x08 - Command Register"] pub cmd: CMD, _reserved3: [u8; 0x04], #[doc = "0x10 - Status Register"] ...
use std::{collections::HashSet, fmt}; use tbsux::playered::Player; use crate::{ cards::{Card, Suit}, contract::{Contract, GameType}, error::{SechsUndSechzigError, SusResult}, hands::Hand, ordering::greatest_card_in_suit, variant::Variant, }; #[derive(Debug, Clone, PartialEq, Eq)] pub struct T...
use image::{imageops::overlay, io::Reader, GenericImageView}; use image_go_nord::{convert, Options, NORD}; use std::{ error::Error, io::{Cursor, Read}, time::Instant, }; fn main() -> Result<(), Box<dyn Error>> { let start = Instant::now(); let mut pic = { let req = ureq::get("https://source...
use std::env; use std::io::{self, Write}; mod modes; use modes::*; static MAN_PAGE: &'static str = /* @MANSTART{nc} */ r#" NAME nc - Concatenate and redirect sockets SYNOPSIS nc [[-h | --help] | [-u | --udp] | [-l | --listen]] [hostname:port] DESCRIPTION Netcat (nc) is command line utility which can read ...
#[cfg(test)] use crate::{sub_iot::v0::dash7, test_tools::test_item}; #[cfg(test)] use hex_literal::hex; pub use crate::spec::v1_2::action::{ status, Chunk, CopyFile, FileDataAction, FileIdAction, FilePropertiesAction, HeaderActionDecodingError, IndirectForward, Logic, Nop, OpCode, PermissionRequest, QueryActio...
//! Representation of a mesh in a scene use crate::renderer::{LightConfiguration, Renderer}; use specs::{Component, VecStorage}; use std::cell::RefCell; use std::rc::Rc; /// Mesh component for an entity in the 3D scene. /// Links some `MeshData` to some `MaterialInstance`. pub struct Mesh { material: usize, ...
use pyo3::prelude::*; use tantivy as tv; /// Tantivy schema. /// /// The schema is very strict. To build the schema the `SchemaBuilder` class is /// provided. #[pyclass] pub(crate) struct Schema { pub(crate) inner: tv::schema::Schema, } #[pymethods] impl Schema { fn get_field( &mut self, fiel...
#![no_std] #![no_main] #![feature(wake_trait)] #![feature(default_alloc_error_handler)] extern crate alloc; use stm32f4xx_hal as hal; use crate::hal::{ prelude::*, stm32::Peripherals }; use panic_semihosting as _; // logs messages to the host stderr; requires a debugger use cortex_m_rt::{entry, exception, E...
use pyo3::prelude::*; use pyo3::types::{PyDict, PyTuple}; use pyo3::wrap_pyfunction; use pyo3::Python; mod cheese_shop; use cheese_shop::CheeseShop; mod self_defense; use self_defense::{Instructor, Student}; /* A few comments before we get started: * Use #[text_signature(foo, bar)] to present the function signature...
use indexmap::IndexMap; use cpython::{ PyBytes, PyDict, PyList, PyObject, PyResult, PyTuple, Python, PythonObject, ToPyObject, }; /// Convert into a Python object. /// /// Primitives (i64, String, Option, Vec) have this trait implemented with /// calls to [cpython]. /// /// Structs have this trait derived to coll...
// Lumol, an extensible molecular simulation engine // Copyright (C) Lumol's contributors β€” BSD license //! [Chemfiles](https://chemfiles.org/) conversion for Lumol. use std::path::Path; use std::sync::Once; use soa_derive::soa_zip; use log::warn; use crate::sys::Permutation; use crate::{Molecule, Particle, Particle...
use shipyard::prelude::*; #[system(Test)] fn run<T>() {} fn main() {}
use std::ops::Deref; use num::Complex; use Precision; #[derive(Clone, Debug)] pub struct Channels { mono: Vec<Complex<Precision>>, left: Vec<Complex<Precision>>, right: Vec<Complex<Precision>>, } impl Channels { #[inline(always)] pub fn new(mono: Vec<Complex<Precision>>, left: Vec<Complex<Precisio...
use piston_window::*; use find_folder; use fps_counter::FPSCounter; mod libs; mod sprite; mod scene; mod camera; mod player; mod object; mod collider; use scene::Scene; fn main() { let mut window: PistonWindow = WindowSettings::new("2D Platformer", (600, 600)) .exit_on_esc(true) .build() .unwrap(); window....
use std::path::PathBuf; use anyhow::anyhow; use clap::Parser; use itertools::Itertools; use taiko_wiki_data_analysis::pukiwiki_parser::{ block::{Element, TableCell, TableRowKind}, reader::{ReaderConfig, WikiReader}, ParserConfig, }; #[derive(Parser)] struct Opts { path: PathBuf, page_name: String,...
use darling::{util::SpannedValue, FromMeta}; use http::header::HeaderName; use indexmap::IndexMap; use proc_macro2::{Ident, TokenStream}; use quote::{format_ident, quote}; use syn::{ AttributeArgs, Error, FnArg, ImplItem, ImplItemMethod, ItemImpl, Lit, Meta, NestedMeta, Path, ReturnType, }; use crate::{ co...
// Copyright 2018 Grove Enterprises 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 ...
use bitpattern::bitpattern; #[test] fn test_bit1() { let x = 0u8; assert_eq!(bitpattern!("0", x), Some(())); assert_eq!(bitpattern!("1", x), None); assert_eq!(bitpattern!("?", x), Some(())); assert_eq!(bitpattern!("a", x), Some(0)); let x = 1; assert_eq!(bitpattern!("0", x), None); asse...
use std::collections::HashMap; use std::ops::Deref; use std::str::FromStr; use diesel::prelude::*; use hyper::header::{AcceptLanguage, Authorization, Bearer, Header, Host, LanguageTag, Raw}; use rocket::{ http::Status, request::{self, FromRequest}, Outcome, Request, }; use url::Url; use super::{ error...
/* * ORY Hydra * * Welcome to the ORY Hydra HTTP API documentation. You will find documentation for all HTTP APIs here. * * The version of the OpenAPI document: v1.10.6 * * Generated by: https://openapi-generator.tech */ /// PluginConfigNetwork : PluginConfigNetwork plugin config network #[derive(Clone, De...
// Signature test vectors generated with ECDSA/ECC NIST P-256 // NIST P-256 ECDSA as specified in FIPS 186-4: Digital Signature Standard // Author: sreejith.naarakathil@gmail.com use p256::ecdsa::{signature::Signer, SigningKey}; use rand_core::OsRng; use hex::FromHex; fn main() { let custom_data1 = "0011223344667...
use geometry::ray::*; use geometry::vec3::*; #[derive(Copy, Clone)] pub struct Camera { pub horizontal: Vec3, pub lower_left: Vec3, pub origin: Vec3, pub vertical: Vec3, u: Vec3, v: Vec3, lens_radius: Dimension, } impl Camera { pub fn new( look_from: Vec3, look_at: Vec3...
use crate::traits::{AsFooter, MarkdownElement}; #[cfg(feature = "serde")] use serde::{Deserialize, Serialize}; use std::fmt; /// A markdown image. #[derive(Clone, Debug, Default)] #[cfg_attr(feature = "serde", derive(Deserialize, Serialize))] pub struct Image { /// Whether the image's link should be added as a foo...
// This module may become a plugin in the future, but for now let's avoid the complexity // of dynamic loading. //! Compiler tactic for the metamath C language. //! //! See [`mmc.md`] for information on the MMC format. //! //! [`mmc.md`]: https://github.com/digama0/mm0/blob/master/mm0-rs/mmc.md // rust lints we want ...
extern crate proc_macro; #[proc_macro_attribute] pub fn cloud_to_butt( attr: proc_macro::TokenStream, body: proc_macro::TokenStream, ) -> proc_macro::TokenStream { assert!( attr.is_empty(), "cloud_to_butt attribute takes no arguments" ); impl_cloud_to_butt(body) } fn impl_cloud_to_...
#[allow(non_snake_case)] extern crate roki; extern crate gl; use roki::gfx::shader::{ Shader, HasShader, ShaderBuilder, }; use roki::gfx::pipeline::Pipeline; use roki::gfx::object::ObjectBuilder; use roki::gfx::window::WindowBuilder; fn main() { let mut winbuilder = WindowBuilder::new(); let mut win = ...
use std::collections::VecDeque; use std::ops::{Bound, Range, RangeBounds}; use std::num::NonZeroU32; use rand::Rng; use rand::distributions::Distribution; use rand::distributions::uniform::Uniform; use rand::rngs::StdRng; use triangulation::PointIndex; use crate::Grid; pub const WORLD_MAX: u8 = 100; pub const OCEAN_...
use std::{thread, time}; fn main() { let start = time::Instant::now(); let mut pause = time::Duration::from_millis(5000); let handler1 = thread::spawn( move || { thread::sleep(pause.clone()); println!("fim thread 1"); }); pause = time::Duration::from_millis(500); let handler2...
ApBegin(RS,CLSID_FRUITGAMBLEGAME) WndBegin(FRUITGAMBLEGAME_WND_SPLASH) WdgBegin(CLSID_IMAGEWIDGET,pSplashImageWdg) WdgImageCreateForWndRC({{0,0}, {FRUITGAMEAPP_MAINVIEW_WIDTH,MAIN_LCD_HEIGHT}, IMAGE_STYLE_COMMON, ...
pub struct Seat { pub code: String, } impl Seat { pub fn create(code: &str) -> Self { Seat { code: String::from(code), } } pub fn row(&self) -> i32 { let mut min_counter = 0; let mut max_counter = 128; for sign in self.code.chars().take(7) { ...
//! A N-dimensional shape type representing geometric points used for drawing. //! //! # Examples //! //! You can create a [Point] using [`Point::new`]: //! //! ``` //! use pix_engine::prelude::*; //! //! let p = Point::new([10, 20]); //! ``` //! ...or by using the [point!] macro: //! //! ``` //! use pix_engine::prelud...
use std::convert::TryInto; use std::string::FromUtf8Error; use byteorder::ByteOrder; use crate::chunk_type::ChunkType; use crate::error::ChunkParseError; #[derive(::derive_more::Display)] #[display(fmt = "Chunk \"{}\" len:{}", chunk_type, length)] pub struct Chunk { length: u32, chunk_type: ChunkType, da...
struct Solution; impl Solution { fn find_max_average(nums: Vec<i32>, k: i32) -> f64 { let mut sum = 0; let k = k as usize; let n = nums.len(); for i in 0..k { sum += nums[i]; } let mut max = sum; for i in k..n { sum += nums[i]; ...
#![recursion_limit = "16384"] #[macro_use] extern crate lazy_static; use indicatif::ProgressBar; use regex::Captures; use regex::Regex; use std::boxed::Box; use std::collections::HashMap; use std::convert::TryInto; use std::env; use std::fs::File; use std::io::prelude::*; use std::io::BufReader; use std::io::BufWriter...
#![allow(clippy::unit_arg)] use crate::account_address::AccountAddress; #[cfg(any(test, feature = "testing"))] use canonical_serialization::SimpleSerializer; use canonical_serialization::{ CanonicalDeserialize, CanonicalDeserializer, CanonicalSerialize, CanonicalSerializer, }; #[cfg(any(test, feature = "testing"))...
// Copyright (c) The Starcoin Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::messages::PeerMessage; //TODO unify peer events /// Handle broadcast message from peer pub trait PeerMessageHandler: Send + Sync { fn handle_message(&self, peer_message: PeerMessage); }
pub mod constants; pub mod argument_end; pub use argument_end::ArgumentEnd; pub mod argument_end_or_separator; pub use argument_end_or_separator::ArgumentEndOrSeparator; pub mod argument_start; pub use argument_start::ArgumentStart; pub mod context_denominator; pub use context_denominator::ContextDenominator; pub mod ...
//! The Client struct, represents the state of the funds of an individual client's account. #[cfg(test)] mod test; use std::collections::{HashMap, HashSet}; use std::convert::TryInto; use crate::cents::Cents; use crate::err::TransactionError; use crate::transaction::{ DisputableTransaction, DisputableTransaction...
use method::Method; header! { #[doc="`Access-Control-Allow-Methods` header, part of"] #[doc="[CORS](http://www.w3.org/TR/cors/#access-control-allow-methods-response-header)"] #[doc=""] #[doc="The `Access-Control-Allow-Methods` header indicates, as part of the"] #[doc="response to a preflight reques...
//! ppm: library for PPM file read & write. use std::fs::File; use std::io; use std::io::BufWriter; use std::io::Write; use image::{open, ImageBuffer, RgbImage}; use crate::io::Color24; use crate::utils::{Color, Picture}; /// write_to_ppm: Write a picture to PPM file pub fn write_to_ppm(p: &Picture, filename: &str)...
use std::process::Command; use std::env; fn main() { let shell = env::var("SHELL").unwrap_or(String::from("/bin/sh")); let status = Command::new(shell) .current_dir("web") .arg("./build.sh") .status() .expect("build failed"); if !status.success() { ::std::process::e...
//! Test the syntax works correctly for if-chains starting with an `if let` //! clause in a non final `for` clause. use py_comp::comp; #[test] fn for_if_let_for() { let iterable1 = &[(1, 11), (2, 12), (3, 13), (4, 14), (5, 15)]; let iterable2 = &[(1, 11)]; let items: Vec<(i32, i32)> = comp!( (*a,...
// Copyright (c) The Starcoin Core Contributors // SPDX-License-Identifier: Apache-2.0 use serde::{Deserialize, Serialize}; use crate::move_resource::MoveResource; use schemars::JsonSchema; const TIMESTAMP_MODULE_NAME: &str = "Timestamp"; /// The CurrentTimeMilliseconds on chain. #[derive(Clone, Debug, Deserialize, ...
fn main() { // Enable the below code once tokio_rustls moves to std::future } /* use h2::client; use futures::*; use http::{Method, Request}; use tokio::net::TcpStream; use rustls::Session; use tokio_rustls::ClientConfigExt; use webpki::DNSNameRef; use std::net::ToSocketAddrs; use std::error::Error; const ALP...
/** * [150] Evaluate Reverse Polish Notation * * Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operators are +, -, *, and /. Each operand may be an integer or another expression. Note that division between two integers should truncate toward zero. It is guaranteed that the given RP...
extern crate proc_macro; use proc_macro2::{Ident, Span}; use self::proc_macro::TokenStream; use quote::{format_ident, quote}; use syn::{ parse_macro_input, AngleBracketedGenericArguments, Data::Struct, DataStruct, DeriveInput, Field, Fields::Named, FieldsNamed, GenericArgument, PathArguments, PathArguments:: { ...
/// HdfsRack : This is schema that contains HDFS rack properties. #[allow(unused_imports)] use serde_json::Value; #[derive(Debug, Serialize, Deserialize)] pub struct HdfsRack { /// Array of IP ranges. Clients from one of these IP ranges are served by corresponding nodes from ip_pools array. #[serde(rename = "...
// Copyright 2018 Evgeniy Reizner // // 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 according...
// Copyright 2022 IOTA Stiftung // SPDX-License-Identifier: Apache-2.0 //! Transaction preparation and signing use iota_types::block::{ input::{Input, UtxoInput}, output::{InputsCommitment, Output, OutputId}, payload::{ transaction::{RegularTransactionEssence, TransactionEssence, TransactionPayloa...
extern crate aarch64; use aarch64::regs::*; use volatile::*; /// The base address for the ARM generic timer, IRQs, mailboxes const GEN_TIMER_REG_BASE: usize = 0x40000000; /// Core interrupt sources (ref: QA7 4.10, page 16) #[repr(u8)] #[allow(dead_code)] #[allow(non_snake_case)] #[derive(Copy, Clone, PartialEq, Debu...
#![recursion_limit="1024"] // Recursion limit for error-chain. // Copyright 2020 sacn Developers // // 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 your option. This file may n...
use cc; use rustc_version::{version_meta, Channel}; fn main() { let using_nightly = version_meta().unwrap().channel == Channel::Nightly; let asm_capable_target = cfg!(not(any( all(target_os = "nacl", target_arch = "le32"), target_arch = "asmjs", target_arch = "wasm32" ))); if u...