text
stringlengths
8
4.13M
extern crate actix; #[macro_use] extern crate diesel; mod actor; mod model; mod handler; mod schema; use crate::actor::{ db::DbActor, ws::WsActor }; use crate::handler::{ get_ws, login, send_msg }; use crate::model::AppState; use actix::prelude::*; use actix_web::{ http::Method, server, App }; use diesel::{ r2d2::Co...
//! Contains the management endpoint + types. use config::ConfigContainer; use auth::SessionStore; use types::FileMetadata; use types::StringError; use std::fs; use std::fs::DirEntry; use iron::prelude::*; use iron::status; use handlebars_iron::Template; use persistent; use serde_json; /// Metadata for each fi...
macro_rules! spectrum_impl { ($ty:ident) => { const __SPECTRUM_IMPL: () = { use std::ops::{ Add, AddAssign, Div, DivAssign, Mul, MulAssign, Sub, SubAssign, Deref, DerefMut, }; use crate::prelude::*; impl Deref for $ty { type Target = [Float]; fn deref(&self) -> &Self::Target { &...
use std::str::FromStr; pub fn split_pair(text: &str, separator: char) -> Option<(&str, &str)> { match text.find(separator) { None => None, Some(index) => Some((&text[..index], &text[index + 1..])), } } pub fn parse_pair<N>(text: &str, separator: char) -> Option<(N, N)> where N: FromStr, { ...
/// Module ProcessR /// This module contains the helper functions in order to process a R format /// instruction. /// /// AUTHOR: Zach LeBlanc /// DATE: 2017-6-15 use process; /// This function gets the shift amount from the instruction. /// Parameters: /// *string: the instruction. /// Returns: the decimal value of ...
/* * Datadog API V1 Collection * * Collection of all Datadog Public endpoints. * * The version of the OpenAPI document: 1.0 * Contact: support@datadoghq.com * Generated by: https://openapi-generator.tech */ /// SyntheticsDeleteTestsPayload : A JSON list of the ID or IDs of the Synthetic tests that you want to ...
macro_rules! implement_map { ($elem:ty, $($field:ident),*) => { #[inline] pub fn map<F>(self, mut f: F) -> Self where F: FnMut($elem) -> $elem, { Self { $($field: f(self.$field),)* } } #[inline] pub fn map2<...
use stm32f407; use crate::hal::serial::*; use crate::hal::pin::*; use crate::hal::pmc::*; use crate::hal_stm32f407::core::*; impl<'pins> Serial<'pins, stm32f407::UART, stm32f407::PIOA, stm32f407::PIOA> { // Pin<ENABLED, DIRECTION, VALID> //pub fn create_serial_handle<'a>(_handle: target::UART, pin_tx: pin::Pi...
use crate::common::{for_each_token, run_command}; use crate::{Browser, BrowserOptions, Error, ErrorKind, Result, TargetType}; use log::trace; use std::path::Path; use std::process::Command; const ASSOCF_IS_PROTOCOL: u32 = 0x00001000; const ASSOCSTR_COMMAND: i32 = 1; #[link(name = "shlwapi")] extern "system" { fn ...
use crate::*; use riddle_platform_common::{LogicalPosition, WindowId}; #[derive(Clone, PartialEq, Debug)] pub enum InputEvent { CursorMove { window: WindowId, position: LogicalPosition, }, MouseButtonDown { window: WindowId, button: MouseButton, }, MouseButtonUp { window: WindowId, button: MouseButto...
use super::handlers; #[repr(C)] pub struct HardwareIdt([HardwareIdtEntry; 256]); #[derive(Clone, Copy, Debug)] #[repr(C)] pub struct HardwareIdtEntry { pointer_low: u16, gdt_selector: u16, options: EntryOptions, pointer_middle: u16, pointer_high: u32, reserved: u32 } #[repr(transparent)] #[de...
#![allow(dead_code)] use std::ops::{Add, AddAssign, Div, Mul, Neg, Sub}; use std::{cmp, fmt}; pub fn lerp(a: Vec3d, b: Vec3d, d: f64) -> Vec3d { a + (b - a) * d.max(0.).min(1.) } #[derive(Copy, Clone)] pub struct Vec3d { pub x: f64, pub y: f64, pub z: f64, } impl Vec3d { pub fn x_comp(self) -> Ve...
// Copyright 2015 The GeoRust 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 or agreed...
#![feature(proc_macro_hygiene, decl_macro)] #[macro_use] extern crate rocket; use rocket::State; use rsbacktester::*; #[get("/")] fn hello(state: State<Engine>) -> String { format!("{}", state.prices.ticks.len()) } fn main() { let config = init_engine(&"ticks.csv", 10000); rocket::ignite() .mou...
extern crate unterflow_protocol; use std::env; use std::net::TcpStream; use unterflow_protocol::{RequestResponseMessage, SingleRequestMessage, TransportMessage}; use unterflow_protocol::io::{FromBytes, FromData, ToBytes}; use unterflow_protocol::message::{TaskEvent, TaskSubscription}; use unterflow_protocol::sbe::{Con...
extern crate proc_macro; extern crate syn; #[macro_use] extern crate quote; use syn::{ Ident, Body, Variant, VariantData }; use proc_macro::TokenStream; #[proc_macro_derive(EnumIterator)] pub fn enum_iterator(input: TokenStream) -> TokenStream { let s = input.to_string(); let ast = syn::parse_macro_input(&s)....
#[macro_use] extern crate lazy_static; extern crate clap; use clap::{Arg, App}; use regex::Regex; use std::io::prelude::*; use std::io::Error; use std::path::{Path, PathBuf}; use std::fs::{self, create_dir}; lazy_static! { // HTML patterns, sort these by priority as they will be find/replace within the body ...
mod cli; mod docker; pub use cli::ask_for_confirm; pub use docker::DockerCommand;
//! Rest handlers for account-based calls use super::validation::{self, JWTResponse, RefreshTokenInfo, TokenManager, ValidationError}; use super::REFRESH_TOKEN_COOKIE; use crate::database::accounts::{self, AccountError, DatabaseAccount}; use crate::notifications::account; use chrono::{DateTime, NaiveDateTime, Utc}; use...
mod keycodes; pub use keycodes::*; mod quadrender; pub use quadrender::*; mod init; pub mod shader_strings; pub use init::*; mod events; pub use events::*; mod mainloop; pub use mainloop::*; mod simple_console_backing; pub use simple_console_backing::*; mod sparse_console_backing; pub use sparse_console_backing::*; pub...
mod matchmaker; use async_std::{io, net::TcpListener, net::TcpStream, prelude::*, task}; use async_tls::TlsAcceptor; use rustls::{internal::pemfile, NoClientAuth, ServerConfig}; use std::{fs::File, io::BufReader, net::SocketAddr, path::Path, sync::Arc, thread}; fn main() { eprintln!("Creating server configurati...
pub fn connect(){ println!("Connected to network"); } pub mod server;
use crate::common::{Direction, Point}; use crate::intcode::{Computer, StoppedResult}; use anyhow::Result; use itertools::join; use std::collections::HashSet; use std::iter::FromIterator; #[derive(Debug, Copy, Clone)] enum Color { Black, White, } #[derive(Debug, Clone)] struct ShipHullExplorer { computer: ...
use prometheus::Registry; use rocket_prometheus::prometheus::{opts, HistogramVec, IntCounterVec}; use std::error::Error; #[derive(Debug, Clone)] pub struct Metrics { deploy_counter: IntCounterVec, deploy_failures_counter: IntCounterVec, undeploy_counter: IntCounterVec, undeploy_failures_counter: IntCou...
// Copyright 2019 Steven Bosnick // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE-2.0 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 accord...
use crate::{config::ConfigFromEnv, defaults}; use async_trait::async_trait; use drogue_cloud_service_api::endpoints::*; use serde::Deserialize; use std::fmt::Debug; const DEFAULT_REALM: &str = "drogue"; pub type EndpointSourceType = Box<dyn EndpointSource + Send + Sync>; #[async_trait] pub trait EndpointSource: Debu...
// Copyright 2018 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #![allow(deprecated)] // Necessary for AsciiExt usage from clap args_enum macro use wlan; arg_enum!{ #[derive(PartialEq, Copy, Clone, Debug)] pub...
#[doc = "Reader of register SW_AMUXBUF_SEL"] pub type R = crate::R<u32, super::SW_AMUXBUF_SEL>; #[doc = "Writer for register SW_AMUXBUF_SEL"] pub type W = crate::W<u32, super::SW_AMUXBUF_SEL>; #[doc = "Register SW_AMUXBUF_SEL `reset()`'s with value 0"] impl crate::ResetValue for super::SW_AMUXBUF_SEL { type Type = ...
//! Testing my buggy quicksort. fn partition<T: Ord>(slice: &mut [T]) -> usize { let pivot = slice.len() - 1; let mut i = 0; for j in 0 .. pivot { if slice[j] < slice[pivot] { slice.swap(i, j); i += 1; } } slice.swap(i, pivot); i } pub fn my_sort<T: O...
// This file is part of Substrate. // Copyright (C) 2017-2020 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 // // ht...
//extern crate getopts; //use getopts::Options; extern crate curl; extern crate serde; extern crate serde_json; //use std::io;::{stdin , stdout, Write}; use curl::easy::Easy; use serde_json::{Value}; use std::env; use std::process; fn main() { let args: Vec<String> = env::args().collect(); //let mut opts = O...
//! Classes and subclasses for standard return codes. use sqlstate_macros::class; #[class(standard)] #[derive(Clone, Eq, PartialEq, Hash, Debug)] #[non_exhaustive] pub enum Success {} #[class(standard)] #[derive(Clone, Eq, PartialEq, Hash, Debug)] #[non_exhaustive] pub enum Warning { #[subclass("001")] Curso...
/* Copyright 2021 Al Liu (https://github.com/al8n). Licensed under Apache-2.0. * * Copyright 2017 The Hashicorp's Raft repository authors(https://github.com/hashicorp/raft) authors. Licensed under MPL-2.0. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in com...
#[cfg(unix)] extern crate nix; extern crate rand; pub mod error; mod shm; use error::{Error, Result}; use shm::SharedMemory; use std::mem; use std::ops::{Index, IndexMut}; use std::path::Path; use std::sync::atomic::{AtomicUsize, Ordering}; struct RubberBand { shm: SharedMemory, header: *const Header, ...
extern crate cgmath; pub mod shape; pub mod math; pub use shape::Shape;
use std::ops::{Deref, DerefMut, Index, IndexMut}; use std::fmt; use std::convert::TryInto; use std::iter::FromIterator; use std::rc::Rc; use std::sync::Arc; use std::fmt::Write; use std::hash::Hash; use std::collections::HashMap; use super::{ElabError, BoxError, spans::Spans}; use crate::util::*; use super::lisp::{Lisp...
#![allow(dead_code)] #![allow(unused_imports)] extern crate libc; extern crate sysctl; // Import the trait use sysctl::Sysctl; // Converted from definition in from /usr/include/sys/time.h #[derive(Debug)] #[repr(C)] struct ClockInfo { hz: libc::c_int, /* clock frequency */ tick: libc::c_int, /* micro-secon...
#![doc = "Peripheral access API for STM32G0C1 microcontrollers (generated using svd2rust v0.30.0 (8dd361f 2023-08-19))\n\nYou can find an overview of the generated API [here].\n\nAPI features to be included in the [next] svd2rust release can be generated by cloning the svd2rust [repository], checking out the above comm...
// Reachable modules pub mod io; pub mod protocol; // Re-exporting pub use io::Reader; pub use protocol::Packet;
// This file is part of Substrate. // Copyright (C) 2019-2020 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 // // ht...
//! The RFC 959 File Structure (`STRU`) command // // The argument is a single Telnet character code specifying // file structure described in the Section on Data // Representation and Storage. // // The following codes are assigned for structure: // // F - File (no record structure) // R - Record structure // P - Page...
extern crate libc; use std::ffi::{CStr,CString}; use std::io::prelude::*; use std::fs::{self,File,OpenOptions}; use std::io::{BufReader,LineWriter}; use std::path::Path; use std::str; mod ext_readline { use libc::c_char; extern { pub fn add_history(line: *const c_char); pub fn readline(p: *co...
use super::{list_shells, switch_shell, SwitchTo}; use nu_engine::CallExt; use nu_protocol::ast::Call; use nu_protocol::engine::{Command, EngineState, Stack}; use nu_protocol::{Category, Example, PipelineData, ShellError, Signature, Spanned, SyntaxShape}; /// Source a file for environment variables. #[derive(Clone)] pu...
use std::ops::Index; struct Solution; /// https://leetcode.com/problems/search-insert-position/ impl Solution { pub fn search_insert(nums: Vec<i32>, target: i32) -> i32 { Solution::binary_search(nums, target) } /// 0 ms 2 MB fn binary_search(nums: Vec<i32>, target: i32) -> i32 { if nu...
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT license. */ use std::ops::Range; use rayon::prelude::{IntoParallelIterator, ParallelIterator}; use crate::common::ANNResult; /// based on thread_num, execute the task in parallel using Rayon or serial #[inline] pub fn execute_w...
#![feature(test)] extern crate test; extern crate reffers; use reffers::*; use std::sync::Arc; #[bench] fn rmba(b: &mut test::Bencher) { let z = Arc::new(String::from("Hello world")); let q = RMBA::from(z); b.iter(|| test::black_box(&q).len()); } #[bench] fn slow_rmb...
pub fn intersect<T: Eq + Clone>(arr1: &Vec<T>, arr2: &Vec<T>) -> Option<Vec<T>> { let mut intersect: Vec<T> = vec![]; let mut a2 = arr2.clone(); for i in arr1.iter() { let a = a2.clone(); for (ind, val) in a.iter().enumerate() { if i == val { intersect.push(i.clone()); a2.remove(i...
#[doc = "Register `PLLI2SCFGR` reader"] pub type R = crate::R<PLLI2SCFGR_SPEC>; #[doc = "Register `PLLI2SCFGR` writer"] pub type W = crate::W<PLLI2SCFGR_SPEC>; #[doc = "Field `PLLI2SN` reader - PLLI2S multiplication factor for VCO"] pub type PLLI2SN_R = crate::FieldReader<u16>; #[doc = "Field `PLLI2SN` writer - PLLI2S ...
pub struct KeyState { space_key: bool, alt_key: bool, ctrl_key: bool, shift_key: bool, } impl KeyState { fn update(&mut self, e: web_sys::KeyboardEvent, is_key_down: bool) { let alt_key = e.alt_key(); let ctrl_key = e.ctrl_key() || e.meta_key(); let shift_key = e.shift_key()...
/*! Utility methods to split a `Crossword` into component words. */ use crate::{Crossword, Direction}; /// Parses a Crossword into a `Vec<WordBoundary>`. Returns all words present in the puzzle. /// /// Note that every square in a Crossword is present in two word boundaries; one `Down` and /// one `Across`. /// /// Al...
use std::fmt; use super::trit::Trit; use super::operation::Operation; #[macro_export] macro_rules! byte_le { ( 0 ) => { crate::trit::Trit::ZERO }; ( 1 ) => { crate::trit::Trit::ONE }; ( T ) => { crate::trit::Trit::TERN }; ( $t0:tt,$t1:tt,$t2:tt,$t3:tt,$t4:tt,$t5:tt,$t6:tt,$t7:tt,$t8:tt ) => { c...
// Copyright 2019 The Grin 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 or a...
#![allow(clippy::upper_case_acronyms)] //! The structures, as they are serialized //! //! This module contains the low-level structs that make up the FDB file. These //! structures are annotated with `#[repr(C)]` and can be used to read directly //! from a memory-mapped file on a little-endian machine. //! //! Not all ...
use std::io; use std::str::FromStr; use std::io::{BufRead, Read}; use std::io::{Write}; use std::error::Error; use super::types::{RespValue, RespError}; // https://redis.io/topics/protocol pub struct RespReader<R: BufRead> { reader: R } pub struct RespWriter<W: Write> { writer: W, } impl<R: BufRead> RespRe...
#![doc = "generated by AutoRust 0.1.0"] #![allow(unused_mut)] #![allow(unused_variables)] #![allow(unused_imports)] use super::{models, API_VERSION}; #[non_exhaustive] #[derive(Debug, thiserror :: Error)] #[allow(non_camel_case_types)] pub enum Error { #[error(transparent)] BestPractices_Get(#[from] best_practi...
pub use optimizer::Optimizer; pub use stochastic_gradient_descent::SGD; mod optimizer; mod stochastic_gradient_descent;
use actix::prelude::*; use actix_web::*; use diesel::prelude::*; use models::thing::Thing; use schema; use db::DbExecutor; // Message Definitions pub struct FindThing { pub name: String, } impl Message for FindThing { type Result = Result<Option<Thing>, Error>; } impl Handler<FindThing> for DbExecutor { ...
use std::sync::Arc; use super::Configuration; use ::client::Context; use ::model::Message; #[doc(hidden)] pub type Command = Fn(&Context, &Message, Vec<String>) + Send + Sync; #[doc(hidden)] pub type InternalCommand = Arc<Command>; pub fn positions(content: &str, conf: &Configuration) -> Option<Vec<usize>> { if l...
use std::{error::Error, mem, time::Instant}; mod arm; pub mod ast; pub mod common; pub mod ir; use crate::arm::LowLevelArm; use mmap_rs::{MmapOptions, Mmap}; fn compile_arm(arm: &mut LowLevelArm) -> Result<Mmap, Box<dyn Error>> { let mut buffer = MmapOptions::new(MmapOptions::page_size())?.map_mut()?; l...
/* * Datadog API V1 Collection * * Collection of all Datadog Public endpoints. * * The version of the OpenAPI document: 1.0 * Contact: support@datadoghq.com * Generated by: https://openapi-generator.tech */ /// SloHistoryResponseData : An array of service level objective objects. #[derive(Clone, Debug, Part...
// mod counting { // pub mod check { // pub fn digits() { // println!("We are in check function of counting module - BINARY PACKAGE"); // for counting in 1..11 { // println!("{}",counting); // } // } // } // } ...
//! interfaces for interacting with travis builds use {Branch, Client, Error, Stream, Future, Owner, Pagination, State}; use futures::{ future, stream, Future as StdFuture, IntoFuture, Stream as StdStream }; use hyper::client::Connect; use jobs::Job; use url::form_urlencoded::Serializer; #[derive(Debug, Deser...
use std::{ thread, time::Duration, }; use crate::support::*; pub fn test() { let mut server = server::builder().tcp_keep_alive_secs(3).tcp(); let mut stream = tcp::stream(); thread::sleep(Duration::from_secs(1)); stream.write(net_chunks![ ..net_chunks!({ "host": "foo", ...
use rand::{distributions::Uniform, Rng}; fn main() { let mut rng = rand::thread_rng(); let k_code = 2; // u_array = np.random.randint(2, size=(N_iter, K_code)) let range = Uniform::new(0, 2); let u_array: Vec<u32> = (0..k_code).map(|_| rng.sample(&range)).collect(); println!("{:?}", u_array)...
//! src/main.rs use axum::{prelude::*, AddExtensionLayer}; use dotenv; use handlers::{get_recipe, create_recipe, get_recipes, delete_recipe}; use sqlx::postgres::PgPoolOptions; use std::{env, net::SocketAddr}; mod handlers; mod models; #[tokio::main] async fn main() { dotenv::dotenv().expect("Failed to read .env fi...
use crate::service::resources::{identity::IdentityOperation, AuthenticationMechanism}; use crate::service::responses::ModuleIdentityResponse; use crate::service::{ServiceClient, API_VERSION}; use http::Method; use serde::Serialize; use std::convert::TryInto; /// The CreateOrUpdateModuleIdentityBuilder is used to const...
use crate::level::Level; use crate::expr::{ Expr, ExprsPtr, ExprPtr, Expr::* }; use crate::tc::infer::InferFlag::*; use crate::utils::{ Ptr, Tc, List::* }; use ShortCircuit::*; use DeltaResult::*; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum ShortCircuit { EqShort, NeqShort } #[d...
use os_type::OSType; // use system_services::{OSType}; pub struct Platform { pub install_command: String, pub package_installed_command: String } pub fn for_os_type(os_type: OSType) -> Option<Platform> { match os_type { OSType::Redhat => { Some(Platform { install_comma...
use rand::seq::SliceRandom; const CHARSET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789)(*&^%$#@!~"; const PASSWORD_LEN: usize = 16; pub fn random_pass() -> String { let mut rng = rand::thread_rng(); let password: String = (0..PASSWORD_LEN) .map(|_| char::from(*CHARSET.cho...
use std::mem; use silkenweb_reactive::memo::MemoCache; #[test] fn cross_frame_cache() { let memo = MemoCache::new(); { let frame = memo.frame(); assert_eq!(frame.cache(0, || 1), 1); } let frame = memo.frame(); assert_eq!(1, frame.cache(0, || 2), "The old value should be cached")...
extern crate wasm_bindgen; extern crate js_sys; extern crate itertools; extern crate log; use wasm_bindgen::prelude::*; use std::{str, str::FromStr}; use itertools::put_back; use log::error; /// Program struct holds all the info of a single hook. #[wasm_bindgen] #[derive(Debug)] pub struct Program { #[wasm_bindge...
use std::{collections::HashMap, env, fs}; #[derive(Clone)] enum Operation { Add(u64), Multiply(u64), Exponent(), } #[derive(Clone)] struct Monkey { number: u64, items: Vec<u64>, operation: Operation, test: u64, test_true: u64, test_false: u64, inspected: u64, } impl Monkey { ...
//! Types involving state. use std::any::Any; use std::fmt::Debug; /// An object suitable for storing as state. /// /// We might separate the eq and Send roles. Further, we might have /// one variant that supports PartialEq and another that supports /// Druid Data. pub trait State: Send { fn as_any(&self) -> &dyn...
use proxy_wasm::{traits::RootContext, types::LogLevel}; use crate::context::root_context::ResponseStatusRoot; mod context; #[no_mangle] #[cfg(not(test))] pub fn _start() { start(); } pub fn start() { proxy_wasm::set_log_level(LogLevel::Trace); proxy_wasm::set_root_context(|_| -> Box<dyn RootContext> { Bo...
use std::collections::HashMap; use std::pin::Pin; use std::sync::Arc; use std::task::{Context, Poll}; use futures::{ future::{poll_fn, select}, pin_mut, select, FutureExt, Sink, Stream, }; use tokio::sync::oneshot; use crate::{ client::{ watch_for_client_state_change, Broadcast, Client, ClientTask...
mod canvas; mod debug; mod event; mod input; mod palette; mod terminal; mod util; fn main() { let mut terminal = terminal::Terminal::new(); terminal.set_title("BlockPaint (Untitled)"); terminal.initialize(); event::main_loop(&mut terminal); terminal.deinitialize(); }
#[doc = "Register `D3CFGR` reader"] pub type R = crate::R<D3CFGR_SPEC>; #[doc = "Register `D3CFGR` writer"] pub type W = crate::W<D3CFGR_SPEC>; #[doc = "Field `D3PPRE` reader - D3 domain APB4 prescaler"] pub type D3PPRE_R = crate::FieldReader<D3PPRE_A>; #[doc = "D3 domain APB4 prescaler\n\nValue on reset: 0"] #[derive(...
use std::fs; use itertools::Itertools; fn get_input() -> String { fs::read_to_string("input/day_eight.txt") .expect("Something went wrong reading the file") } const WIDTH: i32 = 25; const HEIGHT: i32 = 6; const BLACK: u32 = 0; const WHITE: u32 = 1; const TRANSPARENT: u32 = 2; pub fn one() { let inp...
struct Solution(); impl Solution { pub fn reverse_string(s: &mut Vec<char>){ if s.len()<=1{ return ; } let n = s.len(); let mut idx; for i in 0..n/2{ idx=n-i-1; s.swap(i,idx); } // let mut p=0; // let mut q=s.len()-1...
// Copyright 2018 Steven Bosnick // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE-2.0 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 accord...
use std::io::Error; use std::fs::File; use std::io::prelude::*; use std::collections::HashMap; fn read_input(filename: &str) -> Result<String, Error> { let mut input = String::new(); File::open(filename)?.read_to_string(&mut input)?; return Ok(input); } fn main() { match read_input("input.txt") { Ok(input...
use ::core; use ::crust; use ::mantle::KError; use ::kobject::*; use ::memory; struct FragmentAllocator { available_fragments: memory::LinkedList<Untyped>, expired_sets: memory::LinkedList<UntypedSet> } impl FragmentAllocator { fn refill(&mut self) -> core::result::Result<(), KError> { assert!(sel...
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT license. */ #![cfg_attr( not(test), warn(clippy::panic, clippy::unwrap_used, clippy::expect_used) )] pub mod logger { pub mod indexlog { include!(concat!(env!("OUT_DIR"), "/diskann_logger.rs")); } } pub ...
use bytes::{BigEndian, ByteOrder}; use std::env; use std::io::{self, Write}; #[cfg(windows)] use std::net::TcpStream; #[cfg(unix)] use std::os::unix::net::UnixStream; pub struct Session<T> where T: Write, { transport: T, } #[cfg(unix)] impl Session<UnixStream> { pub fn connect() -> Result<Session<UnixStre...
use std::collections::HashSet; use aoc_runner_derive::{aoc, aoc_generator}; #[aoc_generator(day1)] pub fn part1_generator(input: &str) -> Vec<u64> { input.lines() .map(|i| i.parse().unwrap()) .collect() } #[aoc(day1, part1)] pub fn part1(input: &Vec<u64>) -> u64 { let target = 2020; let mu...
use anyhow::{anyhow, Result}; use serde::de::DeserializeOwned; use serde_json::Value; #[derive(Debug, Clone)] pub struct RpcObject(pub Value); pub type RequestId = u64; #[derive(Debug, Clone, PartialEq)] /// An RPC call, which may be either a notification or a request. pub enum Call<N, R> { /// An id and an RPC ...
fn factory() -> &'static(Fn(i32) -> i32){ let num = 5; |x| x + num } fn main(){ let f = factory(); let answer = f(1); assert_eq!(6,answer) }
#[cfg(all(target_os = "windows", not(debug_assertions)))] pub use windows::*; #[cfg(all(target_os = "windows", debug_assertions))] pub use windows_debug::*; #[cfg(all(target_os = "linux", not(debug_assertions)))] pub use linux::*; #[cfg(all(target_os = "linux", debug_assertions))] pub use linux_debug::*; #[cfg(all(ta...
// Copyright (c) 2019, Facebook, Inc. // All rights reserved. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. extern "C" { fn ocamlpool_enter(); fn ocamlpool_leave(); } use ocaml::caml; use ocaml_ffi_test_utils::test_case; use ...
// Problem 3 - Largest prime factor // // The prime factors of 13195 are 5, 7, 13 and 29. // What is the largest prime factor of the number 600851475143? fn main() { println!("{}", solution()); } fn solution() -> u64 { let mut n: u64 = 600851475143; let upper = (n as f64).sqrt().floor() as u64; let m...
use {GitDirectory, DirectoryEntry, TreeEntryExt}; use std::cmp::Ordering; use git2::Tree; /// A set of extension methods for the `Tree` type in `git2`. pub trait TreeExt { /// Get a list of all the named entries at this level in the tree. fn entry_names(&self) -> Vec<String>; /// Get a higher level, pre-s...
// Copyright (c) 2016, <daggerbot@gmail.com> // This software is available under the terms of the zlib license. // See COPYING.md for more information. use std::mem; use std::os::raw::*; use std::rc::Rc; use x11_dl::xlib; use error::Result; use imp::x11::display::DisplayShared; use pixel_format::PixelFormatBridge; u...
#[doc = "Register `HWCFGR1` reader"] pub type R = crate::R<HWCFGR1_SPEC>; #[doc = "Register `HWCFGR1` writer"] pub type W = crate::W<HWCFGR1_SPEC>; #[doc = "Field `CHMAP3` reader - Input channel mapping"] pub type CHMAP3_R = crate::FieldReader; #[doc = "Field `CHMAP3` writer - Input channel mapping"] pub type CHMAP3_W<...
pub mod cpu; pub mod bus; pub mod cartridge; pub mod ram; pub mod io; pub mod interrupt; pub mod pad; pub mod ppu; pub mod hram; pub mod apu; pub mod timer;
use std::fmt::Display; #[derive(Debug, Eq, PartialEq)] pub enum DiagType { Warning, Error, } pub struct DiagMsg { pub diag_type: DiagType, pub module: Option<String>, pub msg: String, } impl Display for DiagMsg { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { mat...
#![cfg(target_arch = "wasm32")] use day12::*; use wasm_bindgen_test::*; wasm_bindgen_test_configure!(run_in_browser); static INPUT: &str = include_str!("../input.txt"); #[wasm_bindgen_test] fn day12_part1() { assert_eq!(part1(INPUT), Ok(10055)); } #[wasm_bindgen_test] fn day12_part2() { assert_eq!(part2(IN...
use std::time::Duration; pub const HEARTBEAT_INTERVAL: Duration = Duration::from_secs(10); pub const CLIENT_TIMEOUT: Duration = Duration::from_secs(11); pub const CLIENT_TERMINATE: Duration = Duration::from_secs(30);
use std::ops::Range; use crate::layout::{ FieldAlignment, PointAttributeDefinition, PointLayout, PointType, PrimitiveType, }; use super::{ InterleavedPointBuffer, PerAttributePointBuffer, PerAttributePointBufferSlice, PointBuffer, }; /// A non-owning view for a contiguous slice of interleaved point data. Thi...
#[doc = "Register `C2CR3` reader"] pub type R = crate::R<C2CR3_SPEC>; #[doc = "Register `C2CR3` writer"] pub type W = crate::W<C2CR3_SPEC>; #[doc = "Field `EWUP1` reader - Enable Wakeup pin WKUP1 for CPU2"] pub type EWUP1_R = crate::BitReader; #[doc = "Field `EWUP1` writer - Enable Wakeup pin WKUP1 for CPU2"] pub type ...
//pub mod event_dispatcher; //pub mod http_kernel; pub mod thread;