text
stringlengths
8
4.13M
use roguelike_common::*; use serde_json::json; use std::collections::{HashMap, HashSet}; const DIJKSTRA_MAX: i32 = 1000; #[derive(Debug, Clone)] pub struct Map { pub key: &'static str, pub width: i32, pub height: i32, pub tiles: Vec<TileType>, pub neighbours: Vec<Vec<usize>>, pub dijkstra_valu...
use std::cmp::Ordering; fn main() { let position = vec![(17, -12, 13), (2, 1, 1), (-1, -17, 7), (12, -14, 18)]; let mut velocity = vec![(0, 0, 0); 4]; let energy = simulate(&mut position.clone(), &mut velocity, 1000); println!("Total energy after 1000 steps = {}", energy); let t = repeat_time...
use std::io; fn main() { loop { let mut temp_value = String::new(); let mut temp_unit = String::new(); println!("Choose your temperature unit, please enter f or c:"); io::stdin() .read_line(&mut temp_unit) .expect("Failed to read line"); let temp_unit...
use std::ffi::CString; use std::os::raw::c_char; #[no_mangle] pub extern "C" fn add(a: i32, b: i32) -> i32 { a + b } #[no_mangle] pub extern "C" fn hello_world_in_rust() -> *mut c_char { let c_to_print = CString::new("Hello World, Rust here!!").expect("CString::new failed"); let ptr = c_to_print.into_ra...
#[allow(unused_imports)] use tracing::{error, info, warn, debug}; use error_chain::bail; use crate::error::*; use crate::meta::*; use crate::transaction::*; use super::*; #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] pub(super) enum ComputePhase { BeforeStore, AfterStore, } impl TreeAuthorit...
use std::borrow; const N: usize = 10; fn wrap_in_for<S: AsRef<str>>(body: S) -> String { let mut result = String::new(); result.push_str("{% for i in (1..10) %}"); result.push_str(body.as_ref()); result.push_str("{% endfor %}"); result } fn wrap_in_if<S: AsRef<str>>(body: S) -> String { let m...
struct Solution {} impl Solution { pub fn partition_labels(s: String) -> Vec<i32> { use std::collections::HashMap; let mut map = HashMap::new(); for (i, c) in s.chars().enumerate() { map.insert(c, i); } let mut result = vec![]; let mut left = 0; ...
#![deny(unsafe_code)] // Don't allow unsafe code in this file. //#![deny(warnings)] // If the Rust compiler generates a warning, stop the compilation with an error. #![no_main] // Don't use the Rust standard bootstrap. We will provide our own. #![no_std] // Don't use the Rust standa...
fn main() { // ANCHOR: here struct AlwaysEqual; let subject = AlwaysEqual; // ANCHOR_END: here }
//! A future-based worker that can consume many inputs and produce many outputs. //! //! ## Example //! //! ```rust, no_run //! use gloo_worker::reactor::{reactor, ReactorScope}; //! use gloo_worker::Spawnable; //! use futures::{sink::SinkExt, StreamExt}; //! //! #[reactor] //! async fn SquaredOnDemand(mut scope: React...
//! serum-safe defines the interface for the serum safe program. #![cfg_attr(feature = "strict", deny(warnings))] use serum_common::pack::*; use solana_client_gen::prelude::*; #[cfg_attr(feature = "client", solana_client_gen(ext))] pub mod instruction { use super::*; #[derive(serde::Serialize, serde::Deseria...
/// Module for the ServiceError struct. use crate::config; use crate::context; use crate::templating::render; use actix_web::http::{header, StatusCode}; use actix_web::{HttpRequest, HttpResponse, ResponseError}; use log::error; use std::fmt; /// A generic error for the web server. #[derive(Debug)] pub struct ServiceE...
#![no_std] #![no_main] #![feature(custom_test_frameworks)] #![test_runner(os::test_runner)] #![reexport_test_harness_main = "test_main"] use core::panic::PanicInfo; use os::println; use bootloader::{BootInfo, entry_point}; use alloc::{boxed::Box, vec, vec::Vec, rc::Rc}; use os::task::{Task, simple_executor::SimpleExec...
use std::rc::Rc; use ggez::{ graphics::Color, graphics::{self, Scale, Text, TextFragment}, nalgebra::Point2, Context, GameResult, }; use graphics::DrawParam; use crate::utils::AssetManager; pub struct Death { asset_manager: Rc<AssetManager>, } impl Death { pub fn spawn(_ctx: &mut Context, as...
use crate::common::*; #[derive(Template)] #[template(path = "README.md")] pub(crate) struct Readme { pub(crate) table_of_contents: String, pub(crate) packages: Table<Package>, } const HEADING_PATTERN: &str = "(?m)^(?P<MARKER>#+) (?P<TEXT>.*)$"; impl Readme { #[throws] pub(crate) fn load(config: &Config, temp...
use std::fs; use std::path::PathBuf; use std::sync::Arc; use log::info; use failure::format_err; use crate::config::Config; use crate::dir_pool::{DirPool, HeldDir}; use crate::errors::*; use crate::git::Git; use crate::github; use crate::github::api::Session; // clones git repos with given github session into a mana...
use std::io::Read; use std::mem::size_of; use byteorder::BigEndian; use flate2::read::ZlibDecoder; use zerocopy::{AsBytes, ByteSlice, FromBytes, LayoutVerified, Unaligned, U32}; #[derive(FromBytes, AsBytes, Debug)] #[repr(C)] pub struct Metadata { dcx_magic: [u8; 4], format_magic: [u8; 4], dcs_offset: U32...
/* Load Yaml */ fn main() { // Load to string }
use std::collections::HashMap; use types::callable::Builtin; use types::lispvalue::LispValue; #[derive(Debug)] pub struct LexicalVarStorage { environ: HashMap<String, LispValue>, local: HashMap<String, LispValue>, } impl LexicalVarStorage { pub fn new(environ: HashMap<String, LispValue>) -> LexicalVarStora...
use std::env; use std::path::PathBuf; use std::process::Command; use chrono::{Duration, NaiveDate}; use rustc_version::Channel; fn main() { check_nightly_version(); let sysroot = Command::new(env::var("RUSTC").unwrap()) .arg("--print=sysroot") .output() .expect("Could not invoke rustc...
// Copyright 2020-2022 The NATS 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 or agreed to ...
// This file is part of Substrate. // Copyright (C) 2017-2023 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...
#[cfg(test)] #[allow(dead_code)] #[allow(unused_variables)] #[allow(unused_mut)] #[test] fn match_test() { enum Direction { East, West, South, North } fn print_direction(x: Direction) { match x { Direction::East => { println!("east") ; } D...
pub mod scene; pub mod scene1; pub mod scene2; pub mod scene3; pub use scene::Scene; pub use scene1::Scene1; pub use scene2::Scene2; pub use scene3::Scene3;
/* * @lc app=leetcode.cn id=884 lang=rust * * [884] 两句话中的不常见单词 */ // @lc code=start use std::collections::HashMap; impl Solution { pub fn uncommon_from_sentences(a: String, b: String) -> Vec<String> { let words_a = Self::get_unique_words(&a); let words_b = Self::get_unique_words(&b); le...
// While we have no threads, we can consider the 1 process we have to have 1 thread of execution. So we promise the // rust compiler we will only use this MUTABLE static in one thread of execution. use::std::cell::RefCell; // This is a container items where Rust wants to dynamically check borrow counts! thread_local!...
use std::os; use actix_files as fs; use actix_web::{web, App, HttpRequest, HttpResponse, HttpServer, Responder}; use postgres::{Client, NoTls}; #[actix_web::main] async fn main() -> std::io::Result<()> { HttpServer::new(|| { App::new() .service(fs::Files::new("/assets", "./assets")) ...
// Copyright 2020-2022 The NATS 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 or agreed to ...
// Copyright 2017 Daniel P. Clark & other zip-sys 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 not be // copied, modified, or distri...
#[allow(unused_imports)] use serde_json::Value; #[derive(Debug, Serialize, Deserialize)] pub struct AdsProviderDomainsDomain { #[serde(rename = "client_site")] pub client_site: Option<String>, #[serde(rename = "dc_address")] pub dc_address: Option<String>, #[serde(rename = "dc_name")] pub dc_na...
use chronicle_domain::Aggregate; use uuid::Uuid; use super::Money; #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(tag = "type", rename_all = "snake_case")] pub enum Event { AccountOpened { initial_balance: Money }, MoneyDeposited { transfer_id: Uuid, amount: Money, balance: Mo...
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use std::path::Path; use std::path::PathBuf; use antlir_image::layer::AntlirLayer; use antlir_image::partition::Partition; use a...
use cosmwasm_std::HumanAddr; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct InitMsg { pub initial_bridge: HumanAddr, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] #[serde(rename_all = "snak...
#[doc = "Register `HFCLKRUN` reader"] pub struct R(crate::R<HFCLKRUN_SPEC>); impl core::ops::Deref for R { type Target = crate::R<HFCLKRUN_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<HFCLKRUN_SPEC>> for R { #[inline(always)] fn from(reader: ...
use std::io::{self, Read}; use std::collections::HashMap; fn read_from_stdin() -> String { let mut buffer = String::new(); io::stdin().read_to_string(&mut buffer).unwrap(); buffer } fn day3(input: &String) -> usize { let mut x: i32 = 0; let mut y: i32 = 0; let mut visited_houses = HashMap::ne...
use crate::config::Config; use egg_mode; use log::{error, info}; use tokio_core::reactor::Core; pub struct TwitterBot { pub token: egg_mode::Token, pub user_id: u64, core: Core, } impl TwitterBot { pub fn new(config: Config) -> Self { let mut core = Core::new().expect("unable to create tokio c...
use crate::context::TestContext; use crate::init::drg::Drg; use crate::init::info::Information; use crate::init::token::TokenProvider; use crate::resources::apps::Application; use crate::tools::assert::{assert_msgs, CloudMessage}; use crate::tools::http::HttpSender; use crate::tools::messages::WaitForMessages; use crat...
use std::{iter, mem, ptr}; use std::collections::HashMap; use std::mem::ManuallyDrop; use std::sync::{Arc, Mutex, Weak}; use gfx_hal::{ buffer, command, format as f, format::{AsFormat, ChannelType, Rgba8Srgb as ColorFormat, Swizzle}, image as i, IndexType, memory as m, pass, pass::S...
// Copyright (c) 2015 Brandon Thomas <bt@brand.io> #![doc(html_logo_url = "http://i.imgur.com/bkgoCdy.png", html_favicon_url = "http://i.imgur.com/bkgoCdy.png")] #[cfg(feature = "subscriptions")] extern crate get_if_addrs; #[cfg(feature = "subscriptions")] extern crate iron; #[cfg(feature = "subscriptions")] ...
// // Copyright 2019 Trevor Bentley // // 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 machine::state::State; /// multiple exclusive-or immediate pub fn mxori(state: &mut State, x: u8, y: u8, z: u8) { // Load first operand let mut op1: u64 = state.gpr[y].into(); // Make z mutable let mut z = z; // Execute let mut matrix_op1: [[bool; 8]; 8] = [[false; 8]; 8]; let mut...
use crate::vec3::Vec3; use Vec3 as Point3; #[derive(PartialEq, Debug, Clone, Copy)] pub struct Ray { pub origin: Point3, pub direction: Vec3, } impl Ray { pub fn new(origin: Point3, direction: Vec3) -> Ray { Ray { origin, direction } } pub fn at(&self, t: f32) -> Point3 { return s...
fn to_int(s: String) -> i64 { s.parse::<i64>().unwrap() } fn get_nth_char_from_string(s: &String, index: usize) -> char { s.chars().nth(index).unwrap() } fn main() { proconio::input! { s: String, } let a = to_int(get_nth_char_from_string(&s, 0).to_string()); let c = to_int(get_nth_char...
#[derive(Debug)] pub struct Algo<'a, T: 'a> { vec: &'a mut Vec<T>, count: usize, } impl<'a, T: Ord> Algo<'a, T> { pub fn new(vec: &'a mut Vec<T>) -> Self { Algo { vec: vec, count: 0, } } pub fn len(&self) -> usize { 3 } pub fn is_sorted(&self) ...
use andrew::Canvas; use livesplit_core::{Segment, TimeSpan, TimerPhase}; use smithay_client_toolkit::{ default_environment, environment::{Environment, SimpleGlobal}, new_default_environment, reexports::{ calloop::{self, EventLoop}, client::protocol::*, client::{Display, Main}, ...
use std::fs; use std::path::Path; // print the use instructions pub fn usage() { println!("Use instructions:"); println!("\trsha <filename/path>"); } // open a file and pub fn get_file_byte_array(file: &String) -> Result<Vec<u8>, String> { // try to open file let data = match fs::read(Path::new(file)) { Ok(dat...
pub const ADDRESS: u32 = 0x40010400; /// Interrupt mask register (EXTI_IMR) pub mod imr { pub const OFFSET: u32 = 0x0; pub const REGISTER_ADDRESS: u32 = super::ADDRESS + OFFSET; pub struct ReadonlyCache([bool;19]); impl ::core::ops::Index<u8> for ReadonlyCache { type Output = bool; fn in...
use rusqlite::{Connection, Result, NO_PARAMS}; use crate::schema::user::{NewUser, User}; const SQLITE_DB: &'static str = "./sqlite.db"; #[derive(Copy, Clone)] pub struct Sqlite; impl juniper::Context for Sqlite {} impl Sqlite { pub fn get_user(&self, id: i32) -> Result<User> { let conn = Connection::op...
use std::sync::Arc; use crate::aabb::Aabb; use crate::hitable::{FlipNormals, HitRecord, Hitable, XYRect, XZRect, YZRect}; use crate::material::Material; use crate::ray::Ray; use crate::Vec3; pub struct Boxx { pmin: Vec3, pmax: Vec3, list_ptr: Vec<Arc<dyn Hitable>>, } impl Boxx { pub fn new(p0: Vec3, ...
// SPDX-FileCopyrightText: 2020 Sveriges Television AB // // SPDX-License-Identifier: Apache-2.0 use std::ptr; use jni_sys; use libc::c_void; use crate::init_args::InitArgs; pub struct VM { pub vm: *mut jni_sys::JavaVM, pub env: *mut jni_sys::JNIEnv, } impl VM { pub fn new(init_args: InitArgs) -> Optio...
use sai::{Component, async_trait}; use bb8::{Pool, RunError}; use bb8_postgres::PostgresConnectionManager; use std::str::FromStr; use mockall::{automock}; #[derive(Component)] #[lifecycle] pub struct Db { pool: Option<Pool<PostgresConnectionManager<tokio_postgres::NoTls>>> } #[async_trait] impl sai::ComponentLife...
use shipyard::prelude::*; #[system(Test)] fn run() -> usize { 0 } fn main() {}
fn main() { let x = 1; let c = 'c'; // There’s one pitfall with patterns: like anything // that introduces a new binding, they introduce // shadowing. For example: match c { x => println!("x: {} c: {}", x, c), } println!("x: {}", x); // x => matches the pattern and introdu...
pub struct WindowBuffer { pub buffer: Vec<u32>, width: usize, height: usize, } impl WindowBuffer { pub fn new(width: usize, height: usize) -> Self { Self { buffer: vec![0; width * height], width, height, } } pub fn set_pixel(&mut self, x: usi...
extern crate num; use num::Complex; use std::collections::HashSet; use std::io::{self, Read}; type Result<T> = ::std::result::Result<T, Box<dyn ::std::error::Error>>; fn main() -> Result<()> { let mut input = String::new(); io::stdin().read_to_string(&mut input)?; part1(&input)?; part2(&input)?; ...
extern crate serde_json; extern crate params; extern crate iron; extern crate router; use params::FromValue; use iron::status; use iron::headers::ContentType; use router::{Router}; use iron::prelude::*; fn json(_: &mut Request) -> IronResult<Response> { //let json: String = serde_json::to_string(data).unwrap(); ...
pub mod primitives; pub mod test_enum; pub mod test_struct;
use crate::proc::{RouteHandle, RequestContext}; use regex::Regex; type Handle = Box<dyn RouteHandle>; /// List of routes that are grouped and can be enabled/disabled all at once. pub struct RouteMatchGroup { arr: Vec<RouteMatch>, } pub struct RouteMatch { regex: Regex, handle: Handle, } impl RouteMatchG...
use rand::Rng; use std::num::Wrapping; use std::time::Instant; fn main() { let start = Instant::now(); let mut checked = 0; let mut total_checked = 0; while start.elapsed().as_secs() < 20 { let word = random_word(); let hash = djb2(&word); checked += 1; total_checked += ...
#[doc(inline)] pub use self::output::{IOutput, Output}; mod output; #[cfg(test)] mod compile_test { #![allow(dead_code)] use super::*; fn dyn_output(o: &Output) -> &dyn IOutput { o } }
/* We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once; for example, the 5-digit number, 15234, is 1 through 5 pandigital. The product 7254 is unusual, as the identity, 39 × 186 = 7254, containing multiplicand, multiplier, and product is 1 through 9 pandigital. Find...
/* * All four are legal and equal * * (A) fn functionName (data: type) -> type { operations } * (B) let closureName = |data: type| -> type { operations }; * (C) let closureName = |data| { operations }; * (D) let closureName = |data| operations; */ fn main() { // (D) A...
extern crate openal; extern crate hound; extern crate time; extern crate rand; extern crate tcod; extern crate yaml_rust; mod util; mod scheduler; mod map; mod game; mod effects; mod ui; mod sound; use tcod::console::{Console, Root, Renderer, FontLayout, FontType}; use tcod::colors; use tcod::system; use tcod::input;...
#![crate_name = "piston"] #![deny(missing_docs)] #![warn(dead_code)] #![feature(macro_reexport)] //! A user friendly game engine written in Rust. // Reexported crates. extern crate "input" as input_lib; extern crate "event" as event_lib; extern crate "window" as window_lib; #[macro_reexport(quack, quack_get, quack_se...
#![allow(unused_imports)] use tracing::{info, warn, debug, error, trace, instrument, span, Level}; use error_chain::bail; use std::io::stdout; use std::io::Write; use std::sync::Arc; use url::Url; use std::ops::Deref; use qrcode::QrCode; use qrcode::render::unicode; use ate::prelude::*; use ate::error::LoadError; use ...
use embedded_hal::PwmPin; pub struct OverheadLight<P1, P2, P3, P4> where P1: PwmPin<Duty = u16>, P1: PwmPin<Duty = u16>, P3: PwmPin<Duty = u16>, P4: PwmPin<Duty = u16>, { brightness_c1: P1, brightness_c2: P2, color_c1: P3, color_c2: P4, } impl<P1, P2, P3, P4> OverheadLight<P1, P2, P3, ...
extern crate proc_macro; #[macro_use] extern crate quote; use proc_macro::TokenStream; mod attr; mod ctx; mod derive; mod r#impl; mod str_util; #[proc_macro_attribute] pub fn steit_derive(args: TokenStream, input: TokenStream) -> TokenStream { let args = syn::parse_macro_input!(args as syn::AttributeArgs); l...
#[allow(unused_imports)] use serde_json::Value; #[derive(Debug, Serialize, Deserialize)] pub struct JobStatisticsJobNodeWorker { /// The sleep-to-work ratio of this worker; how much time it spends sleeping compared to working. #[serde(rename = "stw")] pub stw: Option<f32>, /// A representation of the t...
use chip8_rs; use chip8_rs::{DisplayWindow, Key, KeyState}; use minifb; use std::convert::TryFrom; use std::{env, process, thread, time}; use chip8_rs::debugger::{Chip8Debugger, Debugger}; /// Get the filename from the command line. /// Fragile implementation, either use clap or some kind of ui to choose a rom fn get...
use std::collections::btree_map::Entry::{Occupied, Vacant}; use std::collections::BTreeMap; use std::collections::HashSet; extern crate rand; #[derive(Debug)] pub struct OutEventAndNextStateAndUserCondValue { pub out_msg: String, pub to_state: String, pub user_guard_result: String, } #[derive(Debug, Parti...
use crate::table::DecompressionTable; use bitstream::{BitDStreamReverse, BitDstreamStatus}; /// Decomprssion State context. Multiple ones are possible #[derive(Debug)] struct FseDState { state: usize, } impl FseDState { fn new(bit_stream: &mut BitDStreamReverse, table_log: u32, input: &[u8]) -> Self { ...
struct Solution {} impl Solution { pub fn is_isomorphic(s: String, t: String) -> bool { let mut arr = vec![None; 512]; let s = s.chars().collect::<Vec<char>>(); let t = t.chars().collect::<Vec<char>>(); for i in 0..s.len() { if arr[s[i] as usize] != arr[t[i] as usize + ...
use actions::AppAction; use redux::{DispatchFunc, Middleware, Store}; use structs::app::AppState; pub struct CommandBarMiddleWare {} impl Middleware<AppState> for CommandBarMiddleWare { fn dispatch( &self, store: &Store<AppState>, action: AppAction, next: &DispatchFunc<AppState>, ...
use std::rc::Rc; trait Food { fn eat(&self); } #[derive(Default, Debug)] struct Apple { label: i32, } impl Food for Apple { fn eat(&self) { println!("eat apple {}", self.label); } } #[derive(Default,Debug)] struct Ramen {} impl Food for Ramen { fn eat(&self) { println!("eat ramen"...
use std::cmp::Ordering; use std::rc::Rc; use crate::lisp_value::{Bool, LispValue}; pub fn add(arguments: &[Rc<LispValue>]) -> Rc<LispValue> { let res = arguments.iter().fold(0, |acc, x| acc + x.unwrap_number()); Rc::new(LispValue::Int(res)) } pub fn sub(arguments: &[Rc<LispValue>]) -> Rc<LispValue> { le...
pub struct Solution; impl Solution { pub fn title_to_number(s: String) -> i32 { let mut ans: i32 = 0; for c in s.chars() { ans *= 26; ans += c as i32 - 'A' as i32 + 1; } ans } } #[cfg(test)] mod tests { use super::*; #[test] fn test_solution...
// // Copyright 2021 Hans W. Uhlig. All Rights Reserved. // // 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 app...
// Copyright 2020 Datafuse Labs. // // 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 ...
#[allow(unused_imports)] use serde_json::Value; #[derive(Debug, Serialize, Deserialize)] pub struct SnapshotPendingPendingItem { /// The system supplied unique ID used for sorting and paging. #[serde(rename = "id")] pub id: String, /// The /ifs path that will snapshotted. #[serde(rename = "path")] ...
use super::primality; use crate::{gcd, Factorize}; use rug::{Assign, Integer}; use std::collections::VecDeque; pub struct BrentsRho; impl BrentsRho { pub fn factor_generic<T>(num: T) -> Vec<Integer> where Integer: From<T>, { let num = Integer::from(num); Self::factor(num) } ...
extern crate json; use std::io::prelude::*; use std::fs::File; use std::path::PathBuf; use std::env; use std::ops::Index; //TODO: Cleanup move env vars away from this struct. #[derive(Debug)] pub enum ConfigError { FileNotFound(String), FileContentsInvalid, InvalidConfigOption(String, String), Json...
use std::fmt; use ring::{aead, digest, pbkdf2, rand}; use ring::rand::SecureRandom; use super::Crypto; use common::error::*; pub fn init_crypto(password: &str) -> Box<Crypto> { info!("Initializing crypto: `{}`", ChaCha20Poly1305::name()); let crypto = Box::new(ChaCha20Poly1305::new(password.as_bytes()) ...
use ic_cdk::storage; use ic_cdk_macros::*; #[pre_upgrade] fn pre_upgrade() { storage::stable_save((storage::get::<u32>(),)).unwrap(); } #[post_upgrade] fn post_upgrade() { //panic!("here!"); let (from_stable_storage,): (u32,) = storage::stable_restore().unwrap(); let value: &mut u32 = storage::get_m...
use std::fmt; use std::marker::PhantomData; use std::mem; use crate::reflect::runtime_types::RuntimeTypeEnumOrUnknown; use crate::reflect::EnumDescriptor; use crate::reflect::ProtobufValue; use crate::Enum; use crate::EnumFull; /// Protobuf enums with possibly unknown values are preserved in this struct. #[derive(Eq,...
pub mod binary; #[allow(dead_code)] #[cfg(test)] pub mod tests; pub mod tries;
pub mod vector3; pub use self::vector3::Vector3;
use super::*; pub struct MemoryStore<H> { pub inner: Vec<H>, } impl<H: Clone> MemoryStore<H> { pub fn new() -> Self { MemoryStore { inner: vec![] } } pub fn transaction(&mut self) -> MemoryTransaction<H, Self> { MemoryTransaction::new(self) } } impl<H: Clone> Default for MemorySt...
use nom::Slice; use nom_locate::LocatedSpan; use serde::{Deserialize, Serialize}; use std::{ fmt::{self, Formatter}, iter, }; #[cfg(target_arch = "wasm32")] use wasm_bindgen::prelude::*; pub type RawSpan<'a> = LocatedSpan<&'a str>; /// A definition of a span of source code. This doesn't actually hold the code...
use image as im; use piston_window as pw; use piston; use rand::Rng; use std::thread; use std::sync::mpsc; use std::sync::mpsc::{SyncSender, Sender, Receiver, TryRecvError}; // use std::time::{Instant, Duration}; use piston_play:: {Buffer}; // const DRAW_BATCH_SIZE:usize = 255; // #[derive(Debug)] // struct DrawComman...
//! Public Type Declarations use crate::interp::Interp; pub use crate::value::Value; // Molt Numeric Types /// The standard integer type for Molt code. /// /// The interpreter uses this type internally for all Molt integer values. /// The primary reason for defining this as a type alias is future-proofing: at /// so...
use crate::common::{Triple, URI}; use fasthash::city; use rdf::node::Node; use rdf::uri::Uri; use std::collections::HashMap; pub struct URIIndex { map: HashMap<URI, Node>, } impl URIIndex { pub fn new() -> Self { let mut idx = URIIndex { map: HashMap::new(), }; idx.map.inse...
use diesel::prelude::*; use diesel::r2d2::{self, ConnectionManager}; type Pool = r2d2::Pool<ConnectionManager<SqliteConnection>>; pub fn establish_connection() -> Pool { let connspec = std::env::var("DATABASE_URL").expect("DATABASE_URL"); let manager = ConnectionManager::<SqliteConnection>::new(connspec); let p...
pub mod card; pub mod client_handler; pub mod req_token; pub mod requests; pub mod scryfall_errors;
use amphora::Daemon; const BINARY_NAME: &str = env!("CARGO_PKG_NAME"); fn main() { xecute::DaemonProcess::start(BINARY_NAME, "Menmos Storage Server", Daemon::new()) }
#![allow(invalid_value)] fn main() { let _b: fn() = unsafe { std::mem::transmute(0usize) }; //~ ERROR: encountered a null function pointer }
#[macro_use] extern crate log; use actix_web::{web, App, HttpResponse, HttpServer, Responder, http}; use actix_cors::Cors; use anyhow::Result; use dotenv::dotenv; use listenfd::ListenFd; use sqlx::postgres::PgPool; use std::env; use meilisearch_sdk::client::Client; use meilisearch_sdk::indexes::Index; // import item ...
use crate::context::CoinsActivationContext; use crate::prelude::TryFromCoinProtocol; use crate::standalone_coin::{InitStandaloneCoinActivationOps, InitStandaloneCoinTaskHandle, InitStandaloneCoinTaskManagerShared}; use crate::utxo_activation::common_impl::{get_activation_result, priv_key_bu...
struct Solution {} impl Solution { pub fn self_dividing_numbers(left: i32, right: i32) -> Vec<i32> { let mut result = Vec::new(); for n in left..=right { if n % 10 == 0 { continue; } let mut current = n; while current > 0 { ...
#[derive(Clone, PartialEq)] pub struct Lambda { pub arg_name: String, pub body: Expr, } impl Lambda { fn call(mut self, arg: Expr) -> Expr { self.body = self.body.eval(); match self.body { Expr::Var(s) => s.replace(self.arg_name, arg), Expr::Lambda(l) => l.replace(se...
struct Solution {} impl Solution { pub fn min_add_to_make_valid(s: String) -> i32 { let mut result = 0; let mut balance = 0; for c in s.chars() { balance += if c == '(' { 1 } else { -1 }; if balance == -1 { result += 1; balance += 1; ...