text
stringlengths
8
4.13M
use actix_web::{error, Error, HttpRequest, HttpResponse, State}; use git2::ObjectType; use middleware::RepoFull; use AppState; use CommitDetails; pub fn log_detail( (req, repo, state): (HttpRequest<AppState>, RepoFull, State<AppState>), ) -> Result<HttpResponse, Error> { let params = req.match_info(); let...
//! A simple commandline application to demonstrate a claim prover's (AKA an investor) //! steps to create proofs for their claims. //! Use `scp --help` to see the usage. //! use cli_common::Proof; use cryptography::claim_proofs::{ build_scope_claim_proof_data, compute_cdd_id, compute_scope_id, random_claim, Proo...
mod chat; pub use chat::Chat; use std::sync::mpsc::Sender; pub struct Message { pub text: String, pub who: String, } pub trait MessageListener: 'static + Send { fn process_message(&self, msg: Message); } impl MessageListener for Sender<Message> { fn process_message(&self, msg: Message) { self...
use maplit::hashmap; use noir::alias::Alias; use noir::expander::Expander; use noir::expression::RawQuery; fn r(expression: &str) -> RawQuery { RawQuery::new(expression.to_owned()) } #[test] fn test_expandable() { let e = Expander::new( hashmap!{ "hoge".to_owned() => Alias { expression: "fuga".to_...
//! Arithmetic mod (2^249 - 15145038707218910765482344729778085401) //! with five \\(52\\)-bit unsigned limbs. use core::fmt::Debug; use core::ops::{Index, IndexMut}; use core::ops::Add; use core::ops::Sub; use crate::backend::u64::constants; /// The `Scalar` struct represents an Scalar over a modulo /// `2^249 - 151...
use noise::{NoiseFn, Fbm, MultiFractal}; use math::{Vec3i, Vec2i}; use world::constants::CHUNK_HEIGHT; lazy_static! { static ref BLOCK_NOISE: Fbm = Fbm::new() .set_octaves(2) .set_frequency(0.07) .set_persistence(0.4); static ref HEIGHT_NOISE: Fbm = Fbm::new() .set_octaves(6) ...
use token; use common::ParseError as ParseError; use import; use import::Import as Import; use import::ImportType as ImportType; #[test] fn primitives() { let mut tokens = token::tokenize_string("import int: Jint".to_string(), "code.roo".to_string()); let (import_result, seek) = import::get_imports(&tokens, 1)...
use noise::{NoiseModule, Perlin, Seedable}; //use rand::{Rng, SeedableRng, XorShiftRng}; use sfml::graphics::*; use registry::terrain::Terrain; use tiles::TILES_ROW; pub const WORLD_SIZE: u32 = 512; pub const WORLD_SIZE_HALF: u32 = WORLD_SIZE / 2; //pub const PLANT_SECTORS: u32 = 64; //pub const PLANT_SKIP: u32 = WORL...
extern crate shredder; use shredder::Scan; struct NotScan {} #[derive(Scan)] struct Test0 { field: NotScan } fn main() {}
// time.rs // AltOS Rust // // Created by Daniel Seitz on 1/7/17 use altos_core::sync::Mutex; use altos_core::syscall; use altos_core::atomic::{AtomicUsize, ATOMIC_USIZE_INIT, Ordering}; use core::ops::{Add, AddAssign, Sub}; static SYSTEM_TIME: Mutex<Time> = Mutex::new(Time::new()); static MS_RESOLUTION: AtomicUsize ...
pub mod thread_worker; use std::marker::PhantomData; use std::time::Duration; pub fn blocking<T>() -> Blocking<T> { Blocking(PhantomData) } pub struct Blocking<T>(PhantomData<T>); impl<T> Iterator for Blocking<T> { type Item = T; fn next(&mut self) -> Option<T> { loop { ::std::threa...
#![allow(dead_code)] #![allow(unused)] #[allow(unused_imports, dead_code)] use tracing::{info, error, debug, trace, warn}; use std::sync::Arc; use std::collections::HashMap; use std::collections::HashSet; use tokio::sync::RwLock; use tokio::sync::oneshot; use wasm_bindgen::JsCast; use wasm_bindgen::prelude::*; use wasm...
use byteorder::{ByteOrder, LittleEndian, BigEndian, ReadBytesExt}; use std::marker::PhantomData; //use serde::Deserialize; //use serde::Deserializer; use serde::{ de::{ self, DeserializeSeed, EnumAccess, IntoDeserializer, MapAccess, SeqAccess, VariantAccess, Visitor, DeserializeOwned, }, }; use paste::past...
// Constants by encoders & decoders. // used for better understanding in code. pub const MAJOR_POSITIVE: u8 = 0; pub const MAJOR_NEGATIVE: u8 = 1; pub const MAJOR_BYTE: u8 = 2; pub const MAJOR_TEXT: u8 = 3; pub const MAJOR_ARRAY: u8 = 4; pub const MAJOR_MAP: u8 = 5; pub const MAJOR_TAG: u8 = 6; pub const MAJOR_PRIMITI...
use std::fs::File; use std::io; use std::io::Read; use std::os::unix::fs as unix_fs; use std::process::{Command, Stdio}; use std::time::{Duration, Instant}; use log; use tokio::fs; use tokio::sync::mpsc; use crate::builder::Builder; use crate::comparer::Comparer; use crate::process::*; use crate::runner::Runner; use ...
use std::env; use std::path::PathBuf; use async_trait::async_trait; use clap::{ArgMatches, Clap, FromArgMatches, IntoApp}; use directories::ProjectDirs; use miette_utils::{IntoDiagnostic, DiagnosticResult as Result}; use ruget_command::RuGetCommand; use ruget_config::{RuGetConfig, RuGetConfigLayer, RuGetConfigOptions}...
pub enum GLInteger { I8(i8), U8(u8), I16(i16), U16(u16), I32(i32), U32(u32), I64(i64), U64(u64), I128(i128), U128(u128), Overflow, } impl GLInteger { pub fn from_string(number_string: String) -> GLInteger { let number = number_string.parse::<i8>(); if number.is_ok() { return GLInteger::I8(number.unw...
extern crate regex; use regex::Regex; use std::collections::HashSet; use std::io::{self, BufRead}; #[derive(Debug)] struct Node { id: String, weight: i32, subnodes: Vec<String>, } fn read_nodes(reader: &mut BufRead) -> Vec<Node> { let mut nodes: Vec<Node> = Vec::new(); let re = Regex::new(r"^(\w+...
#![feature(proc_macro_hygiene, decl_macro)] #![feature(plugin)] mod routes; use routes::rocket; fn main() { rocket().launch(); }
use core::mem; use sys::*; #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum Event { Window(::window::Id, ::window::Event), Keyboard { wid: ::window::Id, state: bool, repeat: bool, sym: ::key::Sym }, Pointer { wid: ::window::Id, state: bool, pos: [i32; 2], button: Button }, Text { wid: ::wind...
// Copyright 2021 Conflux Foundation. All rights reserved. // Conflux is free software and distributed under GNU General Public License. // See http://www.gnu.org/licenses/ // // Modification based on https://github.com/hlb8122/rust-bitcoincash-addr in MIT License. // A copy of the original license is included in LICEN...
use super::{Byte,Word,MemoryMapped}; pub struct Ram { pub data: [Byte;0xFFFF], } impl MemoryMapped for Ram { fn read(&self, addr:Word) -> Byte { self.data[addr as usize] } fn write(&mut self, addr:Word, value:Byte) { self.data[addr as usize] = value } } impl Ram { pub fn new()...
use std::io::{self, Write}; use rpn::{self, Stack}; /// Start a read-eval-print loop, which runs until an error or `quit`. #[allow(unused_must_use)] pub fn read_eval_print_loop() -> rpn::Result<()> { // Create a stack to work on. let mut stack = Stack::new(); loop { // Print a user input prompt. ...
use std::iter::FromIterator; use self::sealed::AsConnectionOption; use util::FlatCsv; use {HeaderName, HeaderValue}; /// `Connection` header, defined in /// [RFC7230](http://tools.ietf.org/html/rfc7230#section-6.1) /// /// The `Connection` header field allows the sender to indicate desired /// control options for the...
mod ping_readiness { use actix_web::{dev::Service, http::StatusCode, test, web, App}; use todo_server::todo_api_web::routes::apps_routes; #[actix_rt::test] async fn test_ping_pong() { let mut app = test::init_service(App::new().configure(apps_routes)).await; let req = test::TestRequest...
use crate::hkt::HKT; pub trait Pure<A>: HKT<A> { fn of(c: Self::Current) -> Self::Target; } impl<A> Pure<A> for Option<A> { fn of(a: A) -> Self::Target { Some(a) } } impl<A, E> Pure<A> for Result<A, E> { fn of(a: A) -> Self::Target { Ok(a) } }
use std::collections::HashMap; use serde_derive::{Deserialize, Serialize}; use super::env; use super::external_func; use super::function; use super::lang; #[derive(Clone, Serialize, Deserialize)] pub struct JSFunc { pub eval: String, pub return_type: lang::Type, pub name: String, pub description: Str...
//! Contains the `jobs`, `disown`, `bg`, and `fg` commands that manage job control in the shell. use shell::Shell; use shell::job_control::{JobControl, ProcessState}; use shell::status::*; use shell::signals; use std::io::{stderr, Write}; /// Disowns given process job IDs, and optionally marks jobs to not receive SIGH...
use super::DifficultyObject; use rosu_pp::parse::Pos2; use std::collections::VecDeque; use std::f32::consts::{FRAC_PI_2, LN_2}; const OBJ_COUNT_ESTIMATE: usize = 256; const AIM_BASE_DECAY: f32 = 0.75; const AIM_HISTORY_LEN: usize = 2; const AIM_SNAP_STRAIN_MULTIPLIER: f32 = 7.3727; const AIM_FLOW_STRAIN_MULTIPLIER: ...
// This file is part of Substrate. // Copyright (C) Parity Technologies (UK) Ltd. // SPDX-License-Identifier: Apache-2.0 // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.a...
/* * @lc app=leetcode.cn id=728 lang=rust * * [728] 自除数 */ // @lc code=start impl Solution { pub fn self_dividing_numbers(left: i32, right: i32) -> Vec<i32> { let mut ans: Vec<i32> = vec![]; for i in left..(right + 1) { ans.push(i); let mut x = i; while 0 !=...
use aocinput::request; fn main() { let resp = request::get_input(2020, 6); let groups: Vec<String> = resp.trim().split("\n\n").map(|x| x.to_owned()).collect(); let mut sum = 0; for group in groups.iter() { let mut answers: Vec<u8> = group.trim().replace("\n", "").as_bytes().to_vec(); ...
use std::sync::atomic::{AtomicUsize, Ordering}; use actix_web::{get, HttpResponse, post, Responder}; static GLOBAL_REQUEST_COUNTER: AtomicUsize = AtomicUsize::new(1); #[get("/")] pub async fn hello() -> impl Responder { HttpResponse::Ok().body("Hello world!") } #[post("/hello")] pub async fn echo(req_body: Stri...
// // Copyright 2021 The Project Oak Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law o...
/* * * * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) * * OpenAPI spec version: 1.11.0 * * Generated by: https://github.com/swagger-api/swagger-codegen.git */ #[allow(unused_imports)] use serde_json::Value; #[derive(Debug, Serialize, Deserialize)] p...
use crate::{Equiv, Nat, NatStoreError}; use qd_core::{Deducible, StaticallyProvable}; use std::marker::PhantomData; #[derive(Copy, Clone)] pub struct Add<N1: Nat, N2: Nat>(PhantomData<(N1, N2)>); impl<N1: Nat, N2: Nat> Nat for Add<N1, N2> { fn get_usize() -> Option<usize> { N1::get_usize().and_then(|n1| N2...
use cargo_snippet::snippet; #[snippet("CumulativeSum")] #[derive(Debug, Clone)] struct CumulativeSum<T: num::Num + Copy> { cum: Vec<T>, } #[snippet("CumulativeSum")] impl<T: num::Num + Copy> CumulativeSum<T> { pub fn from_vec(v: &Vec<T>) -> Self { v.iter().copied().collect() } pub fn query(&se...
fn main() { println!("Hello, world!"); let mut s = String::from("hello"); { let s2 = &mut s; // append "world" to s2 s2.push_str(" world"); println!("{}", s2); println!("{}", s); } s.push_str(" again"); println!("{}", s); }
pub fn is_leap_year(year: u64) -> bool { if year % 4 == 0 { if year % 400 == 0 { return true; // if year is div 400 -> true } else if year % 100 == 0 { return false; // if year is div 100 -> false } true // year is div by 4 -> true } else { false ...
use std::io; use std::io::BufRead; pub fn read_until<R: BufRead>(reader: &mut R, seperator: &str) -> io::Result<Vec<u8>> { let mut buf: Vec<u8> = Vec::with_capacity(128); let mut consumed; let mut quit = false; loop { { let available = match reader.fill_buf() { Ok(n...
extern crate winit; fn main() { let mut events_loop = winit::EventsLoop::new(); let window = winit::WindowBuilder::new().with_decorations(false) .with_transparency(true) .build(&events_loop).unwrap(); window...
use crate::nes::cpu::{Cpu,FromImplied,AddressMode}; pub struct Dex { } impl FromImplied for Dex { fn from_implied(cpu: &mut Cpu) -> u32 { cpu.X = cpu.X.wrapping_sub(1); // TODO The reason we create `word` here is because we can't pass cpu.X to // `zero_and_negative_status` as it's already ...
use std::collections::{HashSet}; use client_io; use client::{ClientId, Client, MessageOrigin}; use user::HostMask; use protocol::{Command, ResponseCode}; use super::{Flags, ChannelMode}; use super::ChannelMode::{OperatorPrivilege, VoicePrivilege}; /// Represents a channel member pub struct Member { id: ClientId, ...
pub mod align; pub mod property; pub mod style; pub mod style_id; pub mod text_style_id; pub mod types; pub mod value_variant; #[doc(inline)] pub use align::*; #[doc(inline)] pub use property::*; #[doc(inline)] pub use style::*; #[doc(inline)] pub use style_id::*; #[doc(inline)] pub use text_style_id::*; #[doc(inline)...
use chargrid_ansi_terminal::{col_encode, Context}; use general_audio_native::NativeAudioPlayer; use soundboard_app::app; fn main() { let player = NativeAudioPlayer::new_default_device(); let context = Context::new().unwrap(); context.run_app(app(player), col_encode::FromTermInfoRgb); }
use GL; use GL::Gl; use shader::{Shader, Type as ShaderType}; use math::{Mat4, Vec3, One, Ext::{translate, scale}}; use std::mem::size_of; use std::ptr::null as NULL; use std::ffi::c_void; use world::block::block_light::BlockLight; use camera::Camera; use world::block::block::Block; use world::block::block_buffer::Bloc...
use super::{HashTable, Hasher, Prober, ELEMENT_COUNT}; use std::marker::PhantomData; /// Simple and fast HashTable with OpenAddressing /// /// OpenAddressing is used for collision resolution. The number of /// buckets is always equal to ELEMENT_COUNT. If quadratic probing is /// used, insertion could fail even though ...
// TODO(ubsan): make sure to start dealing with Spanneds // whee errors are fun // TODO(ubsan): typeck should *probably* be done in AST // the current typeck is pretty hax // TODO(ubsan): figure out a good way to give params names // without lots of allocations mod runner; mod ty; mod data; use ast::Ast; use containe...
//! # API for the Analog to Digital converter use core::marker::PhantomData; use embedded_hal::adc::{Channel, OneShot}; #[cfg(all(feature = "stm32f103", any(feature = "high", feature = "xl",),))] use crate::dma::dma2; use crate::dma::{dma1, CircBuffer, Receive, RxDma, Transfer, TransferPayload, W}; use crate::gpio::{...
use std::ops::Range; use gltf; use mikktspace; use renderer::{AnimatedComboMeshCreator, Attribute, MeshData, Separate}; use super::{Buffers, GltfError}; use GltfSceneOptions; pub fn load_mesh( mesh: &gltf::Mesh, buffers: &Buffers, options: &GltfSceneOptions, ) -> Result<Vec<(MeshData, Option<usize>, Rang...
// variables1.rs // Make me compile! Execute the command `rustlings hint variables1` if you want a hint :) // About this `I AM NOT DONE` thing: // We sometimes encourage you to keep trying things on a given exercise, // even after you already figured it out. If you got everything working and // feel ready for the next...
use diesel; use diesel::mysql::MysqlConnection; use diesel::prelude::*; use crate::schema::issues; use crate::schema::issues::dsl::issues as all_issues; use crate::schema::users; use diesel::result::{DatabaseErrorKind, Error}; use crate::models; use models::issues::{Issues, NewIssues, UpdateIssues}; use models::use...
extern crate byteorder; extern crate test; mod basic; mod benchmark; mod log; mod ppu;
#[doc = r"Register block"] #[repr(C)] pub struct SEQ { #[doc = "0x00 - Description cluster: Beginning address in RAM of this sequence"] pub ptr: PTR, #[doc = "0x04 - Description cluster: Number of values (duty cycles) in this sequence"] pub cnt: CNT, #[doc = "0x08 - Description cluster: Number of ad...
use crate::rdf::graph::{Graph, GraphType, IndexedGraph, FullIndexedGraph, SimpleGraph, Statement}; use std::collections::{HashMap, HashSet}; use crate::rdf::node_factory::{IRIResource, RDFNode}; pub struct Database{ graph_type: GraphType, default_graph: Box<dyn Graph>, named_graphs: HashMap<String, Box<dyn...
#[cfg(test)] mod problem2 { use crate::problems::medium::problem2; use crate::problems::medium::problem2::ListNode; #[test] fn it_should_get_val_of_one_plus_one() { let l1 = problem2::ListNode { val: 1, next: None }; let l2 = problem2::ListNode { val: 1, next: None }; let boxed...
use hdk::holochain_json_api::{ error::JsonError, json::JsonString, }; use crate::game_move::Move; use crate::game::Game; use super::MoveType; /** * * As a game author you get to decide what the State object of your game looks like. * Most of the time you want it to include all of the previous moves as well. *...
fn test(x: i64, f: f64, b: bool, ptr: [i64; 2], ptr2: &[[i64; 2]]) -> i64 { let x: i64 = -1; let y: bool = !(!true); let z: f64 = -0.0; z = -1.0; f = 5.0; f /= 2.0; ptr[0] = 1; ptr[1] = ptr[2 + x]; let foo : i64 = test2(1, 2); test3(); let test: [i64;2] = [0, 1]; let te...
fn main() {} struct Solution; impl Solution { pub fn reverse(x: i32) -> i32 { if x == i32::min_value() { return 0; } let negative = if x < 0 { true } else { false }; let mut x = x.abs(); let mut res: i32 = 0; while x != 0 { let remainder = ...
extern crate test; use super::discretize::Discretizer; use super::distances; use super::pgres; use crossbeam::crossbeam_channel::bounded; use num_cpus; use num_format::{Locale, ToFormattedString}; use std::collections::HashMap; use std::mem; use std::sync::{Arc, Mutex}; use std::time::Instant; use threadpool::ThreadP...
use std::sync::Arc; use vulkano::device::Queue; use vulkano::framebuffer::{Subpass, RenderPassAbstract}; use vulkano::pipeline::{GraphicsPipelineAbstract, GraphicsPipeline}; use vulkano::buffer::{BufferAccess, ImmutableBuffer, BufferUsage, CpuAccessibleBuffer}; use vulkano::pipeline::blend::{AttachmentBlend, BlendOp, ...
//! ONNX node attribute helpers. use crate::{attribute_proto::AttributeType, AttributeProto, GraphProto, TensorProto}; /// Axes helpers struct. pub struct Axes(pub Vec<i64>); impl From<i64> for Axes { fn from(axes: i64) -> Self { Axes(vec![axes]) } } impl From<Vec<i64>> for Axes { fn from(axes: ...
use std::io::{Write,stdout}; fn print_letter(l: char) { print!("\x1b[1;32m{}\x1b[0m", l); stdout().flush().is_ok(); } fn main() { print_letter('H'); print_letter('e'); print_letter('l'); print_letter('l'); print_letter('o'); print_letter(' '); print_letter('D'); print_letter('e'); print_letter('v'); print...
// Copyright 2020 The Jujutsu Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed t...
use num::BigUint; use serde::{Deserialize, Serialize}; use super::Group; use crate::perm::{DefaultPermutation, Permutation}; /// A simple struct that keeps track of additional information of a group, such /// as the order. This is very useful for testing stabilizer chains #[derive(Debug, Clone, Serialize, Deserialize...
// Copyright 2014-2016 Johannes Köster. // Licensed under the MIT license (http://opensource.org/licenses/MIT) // This file may not be copied, modified, or distributed // except according to those terms. //! Myers bit-parallel approximate pattern matching algorithm. //! Finds all matches up to a given edit distance. T...
use std::io; use std::sync::mpsc; use std::thread; use std::time::{Duration, SystemTime, UNIX_EPOCH}; use termion::event::Key; use termion::input::TermRead; pub fn ts_now() -> u64 { SystemTime::now() .duration_since(UNIX_EPOCH) .expect("Time went backwards") .as_millis() as u64 } pub fn h...
struct Solution; use crate::util::tree::*; use std::cell::RefCell; use std::rc::Rc; impl Solution { pub fn right_side_view(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<i32> { if root.is_none() { return vec![]; } let mut deq = std::collections::VecDeque::new(); deq.push_ba...
#[derive(PartialEq, Eq, Debug, Clone, Copy)] pub struct FilePositionRange { pub start: FilePosition, pub end: FilePosition, } #[derive(PartialEq, Eq, Debug, Clone, Copy)] pub struct FilePosition { /// First line is line `1`. pub line: usize, /// First column is column `0`. pub column: usize, ...
use crossbeam::queue::SegQueue; use std::sync::Arc; use std::time::{Duration, Instant}; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Event { Initiated, DnsResolutionStarted, DnsResolutionFinished, ConnectionStarted, Connected, TlsNegotiationStarted, TlsNegotiated, HeadersReceiv...
use crate::reflect::RuntimeType; /// Reflective representation of field type. pub enum RuntimeFieldType { /// Singular field (required, optional for proto2 or singular for proto3) Singular(RuntimeType), /// Repeated field Repeated(RuntimeType), /// Map field Map(RuntimeType, RuntimeType), }
fn main() { let x = 5; let r = &x; println!("r {} x {}", r, x); println!("longest {}", longest("abc", "abcd")); } fn longest<'a>(s1: &'a str, s2: &'a str) -> &'a str { if s1.len() > s2.len(){ s1 } else { s2 } }
use std::io; use std::io::Read; fn main() { let mut input = String::new(); let _ = io::stdin().read_to_string(&mut input); println!("{}", path(&input)); } #[derive(Debug, PartialEq)] enum Square { Empty, LeftRight, UpDown, Turn, Letter(char) } enum Direction { Up, Down, Le...
use piston_window::Graphics; use cgmath::{Point2, Vector2, Rad, InnerSpace}; use rustfest_game_assets::ASTEROIDS; use rand::random; use player::Player; use transform::Transform; use polygon::Polygon; use bullets::Bullets; const RED: [f32; 4] = [1., 0., 0., 1.]; const ASTEROID_SCALES: [f64; 3] = [0.03, 0.06, 0.08]; co...
use proconio::input; // use proconio::marker::Chars; fn main() { input! { a:i64, b:i64, c:i64, d:i64 } let kouho = vec![a*c, a*d, b*c, b*d]; let ans = kouho.into_iter().max().unwrap(); println!("{}", ans); }
use std::borrow::Borrow; use std::collections::{HashMap, HashSet, VecDeque}; use std::fmt::Debug; use std::hash::{Hash, Hasher}; use std::rc::{Rc, Weak}; pub trait Graph { type Node; type Edge; type Adjacents: IntoIterator<Item = (Self::Edge, Self::Node)>; fn adjacents(&self, node: &Self::Node) -> Sel...
use crate::genome::Genome; use rand::prelude::*; const ELITES: i64 = 2; const POOL_SIZE: i64 = 10; const TOURNAMENT_SIZE: usize = 8; // 1 is random, higher up to pop.len() is higher pressure const SELECTION_PRESSURE: f64 = 0.9; // Higher = closer to deterministic, should be between 0 and 1 pub fn _fitness_s...
fn main() { let x: u8 = 3; if x < 5 { println!("Conditional was true.") } else { println!("Conditional was false.") } let number = 6; if number % 4 == 0 { println!("number is divisible by 4"); } else if number % 3 == 0 { println!("number is divisible by 3")...
// Copyright 2012 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 std::collections::HashMap; use std::collections::HashSet; fn main() { let part_1 = std::fs::read_to_string("input") .unwrap() .split("\n\n") .map(|g| { g.chars() .filter(|c| c.is_alphanumeric()) .collect::<HashSet<char>>() .len...
//! Prints the domain store definition. use crate::print; use proc_macro2::{Ident, Span}; use quote::ToTokens; use serde::Serialize; /// Returns the name of the getter method for `choice`. If `get_old` is true, the method /// will only take into account decisions that have been propagated. pub fn getter_name(choice: &...
use actix_web::{delete, get, post, put, web, HttpResponse, Responder}; use serde_json::json; use super::model::Character; #[get("/characters")] async fn find_all() -> impl Responder { HttpResponse::Ok().json(vec![ Character { id: 1, name: String::from("Osel Mon"), }, Character { id: 2, ...
pub mod event; pub mod device_state; pub mod event_queue;
pub mod ownership; pub mod slice;
use liblumen_alloc::erts::term::prelude::*; #[native_implemented::function(erlang:is_number/1)] pub fn result(term: Term) -> Term { term.is_number().into() }
/* * Rustのトレイト。(C#やJavaでいうインタフェースに類似) * CreatedAt: 2019-06-28 */ fn main() { let v = vec![7, 3, 5, 1, 2]; println!("{:?}: {}", v, largest(&v)); } fn largest<T>(list: &[T]) -> T { let mut max = list[0]; for i in list.iter() { if max < i { max = list[i]; } // error[E0369]: binary operation `<` ...
// This file is part of linux-epoll. 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/linux-epoll/master/COPYRIGHT. No part of linux-epoll, including this file, may be copied, modified, propagated, or distri...
//! Tests auto-converted from "sass-spec/spec/values/colors/alpha_hex" #[allow(unused)] use super::rsass; #[allow(unused)] use rsass::precision; /// From "sass-spec/spec/values/colors/alpha_hex/initial_digit" #[test] fn initial_digit() { precision::set(10); assert_eq!( rsass( "a {\n four-d...
extern crate proconio; use proconio::input; fn main() { input! { n: usize, pts: [(f64, f64, f64); n], } let mut ng = 0.0; let mut ok = 1e9; for _ in 0..100 { let t = (ng + ok) / 2.0; let mut xs = pts .iter() .map(|(x, _, c)| (x - 1.0 / c * t, ...
use crate::{ core::{ cppstd::CppString, error::Error, refptr::{OpaquePtr, Ref, RefMut}, }, flat::{ flat_image::{FlatImageRef, FlatImageRefMut}, flat_image_channel::{ FlatChannelF16Ref, FlatChannelF16RefMut, FlatChannelF32Ref, FlatChannelF32RefM...
use std::collections::HashMap; use proconio::input; fn f(mut x: u32) -> Option<(u32, u32)> { let (mut t2, mut t3) = (0, 0); while x % 2 == 0 || x % 3 == 0 { if x % 2 == 0 { x /= 2; t2 += 1; continue; } if x % 3 == 0 { x /= 3; ...
/// Contains the definition and logic of the State struct. use crate::{ datetime_from_iso, error::Error, event_to_record, Event, Interval, }; use std::default::Default; use tui::widgets::{ ListState, TableState }; /// Describes the "Focus" of the interface: whether it is in insert mode or focused ...
use super::Authenticator; use crate::conn::ConnectionCore; use crate::protocol::parts::{ AuthFields, ClientContext, ConnOptId, ConnectOptions, DbConnectInfo, OptionValue, }; use crate::protocol::{Part, Reply, ReplyType, Request, RequestType}; use crate::{HdbError, HdbResult}; use secstr::SecUtf8; pub(crate) enum F...
use crate::irust::{IRust, Result}; use crossterm::style::Color; impl IRust { pub fn wait_add(&mut self, mut add_cmd: std::process::Child, msg: &str) -> Result<()> { self.printer.cursor.save_position(); self.printer.cursor.hide(); self.printer.writer.raw.set_fg(Color::Cyan)?; match ...
use std::vec::Vec; // Sorts an array by comparison counting // Input: An array a[0..n-1] of orderable elements // Output: Array s[0..n-1] of a's elements sorted in nondecreasing order fn comparison_counting_sort(a: &Vec<u8>) -> Vec<u8> { let n = a.len(); let mut s = Vec::<u8>::new(); let mut count = Vec::<...
#[macro_use] extern crate getset; #[derive(CopyGetters, Setters)] #[getset(get_copy, set)] pub struct Plain { // If the field was not skipped, the compiler would complain about moving a // non-copyable type. #[getset(skip)] non_copyable: String, copyable: usize, // Invalid use of skip -- compi...
use std; use serde_json; use reqwest; // TODO: figure out how to deal with errors correctly // TODO: is f64 the correct return val? pub fn get_xlm_price( ticker: &str, ) -> std::result::Result<std::option::Option<f64>, reqwest::Error> { let url = &format!( "https://min-api.cryptocompare.com/data/price?...
//! Types for defining custom [Runtime](https://github.com/rustasync/runtime)s. See the //! [Runtime](https://docs.rs/runtime) documentation for more details. //! //! These types are only necessary when implementing custom runtimes. If you're only trying to //! perform IO, then there's no need to bother with any of the...
use crate::packet::ReferenceIdentifier; use std::convert::From; use std::error::Error; use std::fmt::{Display, Formatter}; /// Kiss code, reason of a Kiss-o'-Death reply. /// /// Kiss code provides information about why the SNTP server sent a Kiss-o'-Death packet, i.e. /// why the request has been rejected. This enum ...
//! Oasis runtime SDK. #![deny(rust_2018_idioms, unreachable_pub)] #![forbid(unsafe_code)] pub mod callformat; pub mod context; pub mod crypto; pub mod dispatcher; pub mod error; pub mod event; pub mod keymanager; pub mod module; pub mod modules; pub mod runtime; pub mod storage; pub mod testing; pub mod types; pub u...