text
stringlengths
8
4.13M
/**********************************************************\ | | | hprose | | | | Official WebSite: http://www.hprose.com/ | | ...
use std::io; fn main() { let mut choice:usize = 0; while choice!=5{ println!("=========================================================\nATIVIDADE AVALIATIVA - P1\nLINGUAGENS E TÉCNICAS DE PROGRAMAÇÃO\n[ 1 ] - VERIFICAR PARIDADE\n[ 2 ] - VERIFICAR POLARIDADE\n[ 3 ] - CRÉDITO ESPECIAL\n[ 4 ] - TRIAN...
use std::{cell::Cell, fmt::Display, mem, u8}; pub struct Objects { first: Cell<Option<Obj>>, } impl Objects { pub fn new() -> Self { Self { first: Cell::new(None) } } pub fn string(&self, s: &str) -> Obj { let obj = Obj::string(s, self.first.get()); self.fi...
// 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::collections::HashMap; fn main() { let filename = "input2.txt"; let input = std::fs::read_to_string(filename).unwrap(); let required_fields = ["byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid"]; // let optional_field = "cid"; let credentials: Vec<HashMap<&str, &str>> = input ...
#![allow(dead_code)] #[derive(Debug)] struct Person<'lifetime> { name: &'lifetime str } #[derive(Debug)] struct Company<'lifetime> { employees: Vec<Person<'lifetime>> } pub fn lifetime_test() { let p1 = Person { name: "Vadhri" }; let p2 = Person { name: "Venkata" }; let ...
use std::cmp::{Eq, Ord, Ordering, PartialEq, PartialOrd}; use std::ops::Add; pub trait Number { fn value(&self) -> i32; fn zero(&self) -> Self; fn is_zero(&self) -> bool; fn successor(&self) -> Self; fn predecessor(&self) -> Self; } #[allow(dead_code)] pub fn factorial< T: Number + std:...
#[repr(C)] pub struct Point { pub x: f32, pub y: f32, } #[repr(u32)] pub enum Foo { A = 1, B, C, } #[no_mangle] pub unsafe extern "C" fn get_origin() -> Point { Point { x: 0.0, y: 0.0 } } #[no_mangle] pub unsafe extern "C" fn add_points(p1: Point, p2: Point) -> Point { Point { x: ...
use binread::BinRead; /// An unsigned axis, representing a centered value, such as a joystick axis. #[derive(BinRead, Debug, Default)] pub struct SignedAxis(u8); impl SignedAxis { pub fn from_raw(val: u8) -> Self { Self(val) } pub fn raw(&self) -> u8 { self.0 } /// Return axis as...
use crate::hittable::*; use crate::ray::*; use crate::vec3::*; pub struct Sphere { pub center: Point3, pub radius: f64, } impl Sphere { pub fn new() -> Self { Self { center: Point3::new(), radius: 0.0, } } pub fn from(cen: Point3, r: f64) -> Self { S...
use common::rsip::{self, prelude::*}; use models::transport::{RequestMsg, ResponseMsg, TransportMsg}; use std::convert::TryInto; use tokio::sync::Mutex; #[derive(Debug)] pub struct Messages(pub Mutex<Vec<TransportMsg>>); impl Messages { pub async fn len(&self) -> usize { self.0.lock().await.len() } ...
#[doc = "Register `SCR` writer"] pub type W = crate::W<SCR_SPEC>; #[doc = "Field `CALRAF` writer - CALRAF"] pub type CALRAF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `CALRBF` writer - CALRBF"] pub type CALRBF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `CWUTF` wri...
//! Library representing a Tetris game. //! ``` //! use tetris::State; //! use tetris::State::*; //! //! // Initialise a game at the title screen //! let mut state = State::title(); //! //! loop { //! // Match on the state of the game and get a new state back. //! state = match state { //! Title(title) ...
use super::{ shared::{mask_32, vector_256}, *, }; use crate::{ bin_u32, classification::{QuoteClassifiedBlock, ResumeClassifierBlockState, ResumeClassifierState}, debug, input::{error::InputError, InputBlock, InputBlockIterator}, FallibleIterator, }; super::shared::structural_classifier!(Av...
/* Import macros and others */ use crate::schema::*; /* For beeing able to serialize */ use serde::Serialize; #[derive(Debug, Queryable, Serialize)] pub struct User { pub id: i32, pub first_name: String, pub last_name: Option<String>, pub email: String, pub created_at: String, pub updated_at: String, } #...
use reqwest; use reqwest::StatusCode; use reqwest::header::HeaderMap; use std::io; use std::io::Write; use super::error::{NodError, Result}; use url::Url; pub fn download(url: &str) -> Result<Vec<u8>> { let mut writer: Vec<u8> = vec![]; download_to(url, &mut writer)?; Ok(writer) } pub fn download_t...
use ethereum_types::{Address, Bloom, H256, U256}; use bytes::Bytes; use rlp::{Decodable, DecoderError, Encodable, RlpStream, UntrustedRlp}; use keccak_hash::{keccak, KECCAK_NULL_RLP}; use byteorder::{BigEndian, ByteOrder}; #[derive(Debug, Clone, Eq)] pub struct Header { pub parent_hash: H256, pub coinbase: Add...
use { crate::{ client::{self, RequestType}, entities::*, Client, }, image::DynamicImage, serde_json::json, std::error::Error, }; pub struct EnableMFA(Client); impl EnableMFA { /// Finishes the 2FA activation. This will invalidate your token and you need to re-authentica...
pub mod file_msg; pub mod file_thread; pub mod text;
use common::{rsip, tokio::time::Instant}; #[derive(Debug)] pub struct Terminated { //final response, if none it means that it timedout pub response: Option<rsip::Response>, pub entered_at: Instant, }
#[doc = "Reader of register RCC_BDCR"] pub type R = crate::R<u32, super::RCC_BDCR>; #[doc = "Writer for register RCC_BDCR"] pub type W = crate::W<u32, super::RCC_BDCR>; #[doc = "Register RCC_BDCR `reset()`'s with value 0"] impl crate::ResetValue for super::RCC_BDCR { type Type = u32; #[inline(always)] fn re...
use std::io; use std::io::{Read, Write}; use std::string::String; #[no_mangle] pub fn add_emoji() { let pattern = ":-)"; let mut input_vec: Vec<u8> = Vec::new(); // read vector and convert it to a string io::stdin() .read_to_end(&mut input_vec) .expect("Unable to read input"); let ...
use { http::{Method, Request}, juniper::{http::tests as http_tests, tests::model::Database, EmptyMutation, RootNode}, percent_encoding::{define_encode_set, utf8_percent_encode, QUERY_ENCODE_SET}, std::{cell::RefCell, sync::Arc}, tsukuyomi::{ endpoint, test::{self, TestResponse, TestS...
extern crate gcc; fn main() { let mut config = gcc::Config::new(); config.include("breakpad"); config.include("breakpad/common"); config.include("breakpad/google_breakpad"); config.include("breakpad/common/linux"); if cfg!(target_os = "windows") { config.define("OS_WINDOWS", Some("1")...
#[doc = "Register `AHBRSTR` reader"] pub type R = crate::R<AHBRSTR_SPEC>; #[doc = "Register `AHBRSTR` writer"] pub type W = crate::W<AHBRSTR_SPEC>; #[doc = "Field `DMARST` reader - DMA reset"] pub type DMARST_R = crate::BitReader<DMARSTW_A>; #[doc = "DMA reset\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, Partial...
#[doc = "Register `LCCCR` reader"] pub type R = crate::R<LCCCR_SPEC>; #[doc = "Field `COLC` reader - Color Coding"] pub type COLC_R = crate::FieldReader; #[doc = "Field `LPE` reader - Loosely Packed Enable"] pub type LPE_R = crate::BitReader; impl R { #[doc = "Bits 0:3 - Color Coding"] #[inline(always)] pub...
use crate::model::{Post, User}; use crate::repository::PostsRepository; use chrono::{DateTime, Utc}; pub struct PostsService {} impl PostsService { pub fn get_all() -> Vec<Post> { PostsRepository::get_all().unwrap() } pub fn get_page(page_number: usize, posts_per_page: usize) -> Vec<Post> { ...
#![cfg_attr(feature="serde-serialize", feature(proc_macro))] extern crate chrono; extern crate regex; extern crate reqwest; #[cfg(feature="serde-serialize")] #[macro_use] extern crate serde_derive; extern crate xml; #[macro_use] mod decoder; pub mod api; pub mod diff; pub mod gradebook;
use anyhow::{anyhow, Result}; use proger_backend::{DynamoDbDriver, Server}; use proger_core::{ protocol::{ request::{DeleteStepPage, CreateStepPage, UpdateStepPage}, response::{PageAccess, StepPageProgress}, }, API_URL_V1_CREATE_STEP_PAGE, API_URL_V1_READ_STEP_PAGE, API_URL_V1_UPDATE_STEP_PA...
use crate::Event; use async_channel::{Receiver, Sender}; use std::path::{Path, PathBuf}; use std::time::SystemTime; use std::{fs, io}; //events in the background that the thread will respond to pub enum BgEvent { //save task to a file Save(PathBuf, String), //Exit from the program loop Quit, } pub as...
pub fn iterator_simple_test() { println!( "{}", "------------iterator_demo_test start-------------------" ); let v1 = vec![1, 2, 3]; //通过调用定义于 Vec 上的 iter 方法在一个 vector v1 上创建了一个迭代器 let v1_iter = v1.iter(); for val in v1_iter { println!("Got: {}", val); } let mu...
//! High-level resolver operations use std::cell::Cell; use std::io; use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, ToSocketAddrs}; use std::time::{Duration, Instant}; use std::vec::IntoIter; use log::info; use crate::address::address_name; use crate::config::DnsConfig; use crate::message::{Message, Qr, Ques...
use ::window::WindowBuilder; use ::widget::Widget; #[cfg(target_os = "windows")] mod win32; #[cfg(any(target_os = "linux", feature = "gtk"))] mod gtk; #[cfg(all(target_os = "windows", not(feature = "gtk")))] pub type BackendImpl = win32::Backend; #[cfg(any(target_os = "linux", feature = "gtk"))] pub type BackendImp...
// error-pattern:unexpected token: '}' // Issue #1200 type t = {}; fn main() { }
use crate::get_result_i64; use std::collections::HashMap; use std::ops::Neg; // https://adventofcode.com/2020/day/14 // https://www.reddit.com/r/rust/comments/kcrbxw/advent_of_code_2020_day_14/ const INPUT_FILENAME: &str = "inputs/input14"; pub fn solve() { get_result_i64(1, part01, INPUT_FILENAME); get_resu...
extern crate extprim; extern crate libc; extern crate serde; extern crate serde_json; extern crate uuid; extern crate byteorder; extern crate bit_vec; extern crate hex; #[macro_use] mod encoding; #[macro_use] mod messages; #[macro_use] mod macros; mod assets; mod capi; mod decimal; mod error; mod transactions; mod sto...
use cgmath; pub use cgmath::prelude::*; pub type Vector2 = cgmath::Vector2<f32>; pub type Vector3 = cgmath::Vector3<f32>; pub type Vector4 = cgmath::Vector4<f32>; pub type Matrix4 = cgmath::Matrix4<f32>; pub type Quaternion = cgmath::Quaternion<f32>;
#[doc = "Reader of register RCC_MP_TZAHB6ENSETR"] pub type R = crate::R<u32, super::RCC_MP_TZAHB6ENSETR>; #[doc = "Writer for register RCC_MP_TZAHB6ENSETR"] pub type W = crate::W<u32, super::RCC_MP_TZAHB6ENSETR>; #[doc = "Register RCC_MP_TZAHB6ENSETR `reset()`'s with value 0"] impl crate::ResetValue for super::RCC_MP_T...
use crate::board::{Board, GameResult, PieceSpot, Player}; use crate::colors; use iced::{ button, container, Align, Background, Button, Column, Container, Element, HorizontalAlignment, Length, Row, Sandbox, Space, Text, }; const HEADING: &str = "Connect – 4"; // en dash, not hyphen const INSTRUCTIONS: &str = "...
// pathfinder/examples/canvas_minimal/src/main.rs // // Copyright © 2019 The Pathfinder Project Developers. // // 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....
use crate::hittable::{aabb::Aabb, HitRecord, Hittable, Hittables}; use crate::material::{isotropic::Isotropic, MaterialType}; use crate::ray::Ray; use crate::texture::Texture; use crate::util::random_double; use crate::vec::vec3; use rand::rngs::SmallRng; use std::sync::Arc; #[derive(Debug, Clone)] pub struct Constant...
use crate::interaction::navmesh::data_model::{Navmesh, NavmeshEdge}; use crate::interaction::navmesh::{NavmeshEntity, NavmeshVertex}; use rg3d::core::pool::Handle; use std::collections::HashSet; #[derive(PartialEq, Clone, Debug, Eq)] pub struct NavmeshSelection { dirty: bool, navmesh: Handle<Navmesh>, enti...
// overflow fn main() { }
use embedded_hal::blocking::delay::DelayMs; use hdc20xx::{Hdc20xx, SlaveAddr}; use linux_embedded_hal::{Delay, I2cdev}; fn main() { let mut delay = Delay {}; let dev = I2cdev::new("/dev/i2c-1").unwrap(); let address = SlaveAddr::default(); let mut sensor = Hdc20xx::new(dev, address); loop { ...
fn main() { let mut door_open = [false; 100]; for pass in 1..101 { let mut door = pass; while door <= 100 { door_open[door - 1] = !door_open[door - 1]; door += pass; } } //for (i, &is_open) in door_open.iter().enumerate() { // println!("Door {} is {...
//! Edit command use super::Command; use crate::Error; use async_trait::async_trait; use clap::{Arg, ArgMatches, Command as ClapCommand}; /// Abstract `edit` command /// /// ```sh /// leetcode-edit /// Edit question by id /// /// USAGE: /// leetcode edit <id> /// /// FLAGS: /// -h, --help Prints help inf...
mod lib; use lib::listen_and_serve; use std::net::TcpStream; fn main() { println!("Hello, world!"); listen_and_serve(80, "hello_world") } fn hello_world(s: TcpStream) { println!("eek"); }
#![allow(dead_code)] pub mod cache; pub mod multiset; pub mod patch; pub mod traits; pub mod translate; pub mod functions; use crate::cache::*; use crate::multiset::*; use crate::patch::*; use crate::traits::*; use crate::translate::*; use std::collections::HashMap; use std::hash::Hash; fn main() { let b = Multise...
//! The Styx IR builder. //! //! Styx IR is a structure very close to actual assembly. //! //! It consists of raw assembly with the following added features: //! - **Macros**: Instructions that get expanded to one or more other instructions. //! - **Variables**: Abstract variables that are automatically transformed...
use core::cmp::{max, min}; /// Solves the Day 22 Part 1 puzzle with respect to the given input. pub fn part_1(input: String) { let steps = parse_input(input) .into_iter() .filter(|step| step.cuboid.min_x.abs() <= 50) .filter(|step| step.cuboid.min_y.abs() <= 50) .filter(|step| step....
use syscalls::*; #[test] fn test_syscall() { let s = "Hello\0"; assert_eq!( unsafe { syscall!(Sysno::write, 1, s.as_ptr() as *const _, 6) }, Ok(6) ); } #[test] fn test_syscall_map() { // Make sure the macro exports are ok let mut map = SysnoMap::new(); assert!(map.is_empty()); ...
#[doc = "Reader of register DDRCTRL_PWRTMG"] pub type R = crate::R<u32, super::DDRCTRL_PWRTMG>; #[doc = "Writer for register DDRCTRL_PWRTMG"] pub type W = crate::W<u32, super::DDRCTRL_PWRTMG>; #[doc = "Register DDRCTRL_PWRTMG `reset()`'s with value 0x0040_2010"] impl crate::ResetValue for super::DDRCTRL_PWRTMG { ty...
use serde_derive::{ Deserialize, Serialize, }; #[derive(Debug, Serialize, Deserialize)] pub struct Index { pub name: String, pub number: i32, }
//! <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.2/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script> //! //! The OSQP (Operator Splitting Quadratic Program) solver is a numerical optimization package for //! solving convex quadratic programs in the form //! //! <div class="mat...
/// Search for an element in a sorted array using binary search /// /// # Parameters /// /// - `target`: The element to find /// - `arr`: A vector to search the element in /// /// # Type parameters /// /// - `T`: A type that can be checked for equality and ordering e.g. a `i32`, a /// `u8`, or a `f32`. /// /// # Ex...
use fltk::{ app, dialog, enums::{CallbackTrigger, Color, Event, Font, FrameType, Shortcut}, menu, prelude::*, printer, text, window, }; use std::{ error, ops::{Deref, DerefMut}, panic, path, }; #[derive(Copy, Clone)] pub enum Message { Changed, New, Open, Save, SaveA...
use anyhow::Result; use tree_traversal::run; fn main() -> Result<()> { run() }
//! # The Chain Library //! //! This Library contains the `ChainProvider` traits and `Chain` implement: //! //! - [ChainProvider](chain::chain::ChainProvider) provide index //! and store interface. //! - [Chain](chain::chain::Chain) represent a struct which //! implement `ChainProvider` pub mod cell_set; pub mod c...
/* chapter 4 primitive types booleans */ fn main() { let a = true; println!("{}", a); let b: bool = false; println!("{}", b); } // output should be: /* true false */
use universe::planet::Planet; use rand::{Rng, SeedableRng, StdRng}; use nalgebra::geometry::Point3; pub struct Star{ pub star_type: u32, pub name: String, pub coords: Point3<usize>, pub surf_temperature: u32, pub planets: Vec<Planet> } impl Star{ pub fn gen(coords: Point3<usize>, seed: &[usize...
use std::{mem, ops::DerefMut, panic::panic_any, sync::Arc, time::Duration}; use tokio::{ select, sync::{Mutex, Notify}, task::JoinHandle, time::sleep, }; use crate::{ connection::{Settings, SingleConnection}, error::RconError::{self, BusyReconnecting, IO}, reconnect::Status::{Connected, Disconnected, Stopped},...
#![feature(plugin)] #![feature(duration_float)] extern crate pest; #[macro_use] extern crate pest_derive; extern crate inference; extern crate libc; extern crate llvm_sys; mod array; mod ast; mod compiler; mod error; mod expressions; mod function_loader; mod llvm_builder; mod llvm_codegen; mod loader; mod macros; mod ...
//! # Cargo And Crates //! //! `cargo_and_crates` is a collection of utilities to make performing certain //! calculations more convenient. pub mod kinds; pub mod utils; pub use kinds::PrimaryColor; pub use kinds::SecondaryColor; pub use utils::mix; /// Adds one to the number given. /// /// # Examples /// /// ``` //...
#[derive(Queryable)] pub struct User { pub id: i32, pub username: String, pub password: Option<String>, pub firstname: Option<String>, pub lastname: Option<String>, pub userlevel: i32, pub email: Option<String>, pub editable: i32, pub salt: Option<String>, }
use superslice::Ext; pub trait LineIndex { /// returns line number for given offset fn line(&self, offset: usize) -> Option<usize>; /// returns char offset of given line index fn offset(&self, line: usize) -> Option<usize>; } pub struct LinearLineIndex { line_offsets: Vec<usize>, len: usize }...
#![cfg(test)] use super::FastBernoulliTrial; use rand::{SeedableRng, XorShiftRng}; use std; fn make(probability: f64) -> FastBernoulliTrial<XorShiftRng> { let rng = XorShiftRng::from_seed([0x3b3f4150, 0x53704c15, 0x09b0136e, 0xf66c1396]); FastBernoulliTrial::new_with_rng...
// Copyright (C) 2022 Subspace Labs, Inc. // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option)...
use rowan::TextSize; use parser::syntax_kind::SyntaxKind; use SyntaxKind::*; use vimscript_core::peekable_chars_with_position::PeekableCharsWithPosition; use std::convert::TryFrom; #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct Token { pub kind: SyntaxKind, pub len: TextSize, } ...
use async_trait::async_trait; use std::path::Path; use std::{io, io::SeekFrom}; use tokio::{fs::File, io::AsyncReadExt}; use nbd_async::BlockDevice; struct FileBackedDevice { current_file_offs: u64, file: tokio::fs::File, block_size: u32, block_count: u64, } impl FileBackedDevice { fn new(block_s...
extern crate sdl2; extern crate rand; extern crate serde; extern crate serde_json; #[macro_use] extern crate serde_derive; #[macro_use] #[allow(unused_imports, dead_code,unused_must_use,unused_variables,unused_mut,non_camel_case_types,patterns_in_fns_without_body)] mod phi; #[allow(unused_imports, dead_code,unused_mus...
extern crate stomp; extern crate rustc_serialize; use self::stomp::session::Session; use self::stomp::session_builder::SessionBuilder; use self::stomp::connection::{Credentials, HeartBeat}; use self::stomp::frame::Frame; use self::stomp::header::{Header, SuppressedHeader}; use self::stomp::subscription::AckOrNack::{Ac...
use crate::view::shader_utils; use cgmath; use web_sys::{WebGl2RenderingContext, WebGlProgram}; pub fn initialize_shader(context: &WebGl2RenderingContext) -> Result<WebGlProgram, String> { let vert_shader = shader_utils::compile_shader( &context, WebGl2RenderingContext::VERTEX_SHADER, r#"...
//! This file contains the main function #![warn( missing_docs, absolute_paths_not_starting_with_crate, anonymous_parameters, box_pointers, clashing_extern_declarations, deprecated_in_future, elided_lifetimes_in_paths, explicit_outlives_requirements, indirect_structural_match, k...
use quicksilver::{ geom::{ Rectangle, Shape, Tile, Tilemap, Vector}, graphics::{Background::Blended, Background::Img, Color, Font, FontStyle, Image}, input::Key, lifecycle::{run, Asset, Settings, State, Window}, Future, Result }; use std::collections::HashMap; #[derive(Clone, Debug, PartialEq)] st...
pub mod index; pub mod register; pub mod login;
mod arithmetic; mod karatsuba; mod search; mod sort; mod strassen; use std::{ fs::File, io::{prelude::*, BufReader, Error, ErrorKind}, }; fn read_to_ints(filename: &str) -> Result<Vec<i64>, Error> { let file = File::open(filename).expect("File not found!"); let buf = BufReader::new(file); let resu...
use std::io; // Use the std::io library which allows reading from stdin fn main() { let mut inpt = String::new(); // Create a mutable variable called inpt // that is a new instance of a String. println!("Input some text: "); io::stdin() .read_line(&mut inpt) .expect("Failed to read line"); print...
use proconio::{fastout, input}; #[fastout] fn main() { input! { a: i64, } let a_2: i64 = a * a; println!("{}", a + a_2 + a * a_2); }
struct A; struct S(A); struct SGen<T>(T); // not generic fn reg_fn(_s: S) {} // not generic fn gen_spec_t(_s: SGen<A>) {} // not generic fn gen_spec_i32(_s: SGen<i32>) {} // generic fn generic<T>(_s: SGen<T>) {} #[cfg(test)] mod tests { use crate::functions::{reg_fn, A, S, gen_spec_t, SGen, gen_spec_i32, gen...
pub use systemd::SystemdNetworkConfig; pub use systemd::NetworkConfigLoader; pub mod systemd;
extern crate hyper; use hyper::{Body, Request, Server, Method}; use hyper::rt::{Future}; use hyper::service::service_fn; extern crate futures; #[macro_use] extern crate serde_derive; mod handlers; fn router(req: Request<Body>) -> handlers::BoxFutResponse { match (req.method(), req.uri().path()) { (&Met...
//use std::rc::Rc; // For pointer count mem management use std::sync::mpsc; // multiple producer, single consumer use std::sync::{Arc, Mutex}; // Arc is Atomic Rc use std::thread; use std::time::Duration; pub fn basic_example() { let handle = thread::spawn(|| { for i in 1..10 { println!("hi num...
// Copyright 2019. The Tari Project // SPDX-License-Identifier: BSD-3-Clause //! Bulletproofs+ implementation use alloc::vec::Vec; use std::convert::TryFrom; pub use bulletproofs_plus::ristretto::RistrettoRangeProof; use bulletproofs_plus::{ commitment_opening::CommitmentOpening, extended_mask::ExtendedMask ...
use std::fs; use std::result::Result; use rayon::prelude::*; fn main() -> Result<(), String> { let input = fs::read_to_string("input/data.txt").map_err(|e| e.to_string())?; part1(&input); part2(&input); Ok(()) } fn part1(input: &str) -> () { let result = perform_reactions(input); println!("Re...
// Copyright 2019, 2020 Wingchain // // 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...
extern crate leap; #[test] fn test_vanilla_leap_year() { assert_eq!(leap::is_leap_year(1996), true); } #[test] #[ignore] fn test_any_old_year() { assert_eq!(leap::is_leap_year(1997), false); } #[test] #[ignore] fn test_century() { assert_eq!(leap::is_leap_year(1900), false); } #[test]...
use super::DbIterator; use super::tuple::Tuple; #[derive(Debug, Clone)] pub struct Projection<I> { pub input: I, pub columns: Vec<usize>, } impl <I: DbIterator> DbIterator for Projection<I> where Self: Sized, { fn next(&mut self) -> Option<Tuple> { // TODO assert that all cols exist i...
#[doc = "Register `IWDG_SIDR` reader"] pub type R = crate::R<IWDG_SIDR_SPEC>; #[doc = "Field `SID` reader - SID"] pub type SID_R = crate::FieldReader<u32>; impl R { #[doc = "Bits 0:31 - SID"] #[inline(always)] pub fn sid(&self) -> SID_R { SID_R::new(self.bits) } } #[doc = "IWDG size identificati...
use std::{ collections::BTreeSet, sync::{Arc, RwLock}, }; use crate::{SelectFilter, Selection}; #[derive(Debug)] pub enum Filtered { None, Some(BTreeSet<usize>), All, } /// Internal state is wrapped in an Arc, so cloning this is not very expensive pub struct SelectState<T> { pub(crate) option...
use proc_macro::TokenStream; use quote::{format_ident, quote}; use syn::{parse_macro_input, DeriveInput}; struct FieldAttribute { name: String, value: String, } #[proc_macro_derive(Builder, attributes(builder))] pub fn derive(input: TokenStream) -> TokenStream { let parsed_input = parse_macro_input!(input...
#![allow(dead_code, clippy::unreadable_literal)] use image; use rayon::prelude::*; const INTPUT_PATH: &str = "src/day8_input.txt"; const IMG_WIDTH: u32 = 25; const IMG_HEIGHT: u32 = 6; const IMG_SIZE: usize = IMG_HEIGHT as usize * IMG_WIDTH as usize; pub fn solve_day_8_pt_1() -> u32 { let input = std::fs::read_to_...
use std::iter; use itertools::Itertools; use crate::helpers; pub fn solve_1() { let input: Vec<u16> = helpers::input::nums!(); // our wall outlet is treated as having a value of 0, so we add that to our input for convenience // also, the correct order of adapters is just sorted in ascending order. let sequence =...
#![crate_name = "hy_syntax"] #![comment = "Hydra Tokens, Scanner, Parser, and AST"] #![license = "MIT"] #![crate_type = "dylib"] #![crate_type = "rlib"] #![feature(macro_rules)] #![feature(globs)] #![allow(dead_code)] #![allow(unused_variable)] #![allow(unused_mut)] #![allow(non_camel_case_types)] #![allow(dead_assig...
use num_cpus; use std::sync::{Arc, Mutex}; use std::thread; use std::collections::BTreeMap; use op::*; use collect_stream::collect_stream; /* lazy_static allows us to define a global variable that needs initialization * code (that code runs on the first time the variable is referenced). * To use the NUM_WORKERS var...
#![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 AddressResponse { #[serde(rename = "serviceIpAddress", default, skip_serializing_if = "Option::is_none")] p...
mod content; mod feed; mod gen; mod item; mod markdown; mod paths; mod site; mod site_url; mod upload; mod util; #[cfg(test)] mod tests; use crate::site_url::{HrefUrl, ImgUrl}; use axum::{http::StatusCode, response::IntoResponse, routing::get_service, Router}; use camino::Utf8PathBuf; use clap::{Parser, Subcommand}; ...
fn main() { let a=[1,2,3,4,5]; let mut x=a.iter(); let mut y=x.next() assert_eq!(1,*x.next().unwrap()); assert_eq!(1,*a.iter().next().unwrap()); assert_eq!(2,*x.next().unwrap()); assert_eq!(2,*a.iter().next().unwrap()); }
pub struct Point(f64, f64);
use crate::ParsingError; use std::fmt; use std::str::FromStr; const PREFIX: &str = "bytes "; #[derive(Debug, Copy, Clone, PartialEq)] pub struct ContentRange { start: u64, end: u64, total_length: u64, } impl ContentRange { pub fn new(start: u64, end: u64, total_length: u64) -> ContentRange { ...
use crate::built_in::BuiltInChannel; use crate::comm_queue::CommQueue; use crate::prettyprint::PrettyPrintable; use crate::prettyprint::PrettyPrintable::*; use std::fmt; use std::fmt::Display; use uuid::Uuid; #[derive(Clone, Debug, PartialEq)] pub enum ProcCons<Binders> { Parallel(Vec<ProcCons<Binders>>), Unf...