text
stringlengths
8
4.13M
use std::collections::HashMap; use std::iter::FromIterator; type Chemicals = HashMap<String, Material>; struct System { cost: usize, pool: HashMap<String, usize>, chemicals: Chemicals, } impl System { fn new(chemicals: Chemicals) -> System { System { cost: 0, pool: Has...
use list::*; use std::fmt::Debug; use std::iter::empty; use std::iter::once; use std::rc::Rc; use symbols::Tag; use traces::Trace; use traces::TraceEnding; use trees::Tree::*; #[derive(Debug)] pub enum Tree<Tk> { Nil, Leaf(Tk, Tag), Node(Vec<Tree<Tk>>, Tag), } impl<Tk: 'static> Tree<Tk> { pub fn tag(&...
use derive::tree::{ObjectMember, ObjectMerge}; use proc_macro2::TokenStream; impl<'a> ObjectMerge<'a> { pub fn emit(&self) -> TokenStream { let name = self.name; let (impgen, tygen, wherec) = self.generics.split_for_impl(); let merge_members = self.members.iter().map(|member| member.emit_m...
use atoi::atoi; use memchr::memrchr; use sqlx_core::bytes::Bytes; use crate::error::Error; use crate::io::Decode; #[derive(Debug)] pub struct CommandComplete { /// The command tag. This is usually a single word that identifies which SQL command /// was completed. tag: Bytes, } impl Decode<'_> for Command...
//! Simple utility functions to help with parsing URIs. use std::{collections::HashMap, str::ParseBoolError}; use url::Url; pub(crate) fn segments(url: &Url) -> Vec<&str> { if let Some(iter) = url.path_segments() { let mut segments: Vec<&str> = iter.collect(); if segments.len() == 1 && segments[...
use std::io::{IoResult, MemReader}; use encoding::{DecoderTrap, Encoding}; // TODO: for the moment the first call to read() reads the whole // underlying reader at once and decodes it #[experimental] pub struct EncodingDecoder<R> { reader: R, encoding: &'static Encoding + 'static, content: Option<MemReader>, } im...
//! Provides PortablePdbCache support. //! //! This includes a reader and writer for the binary format. //! //! # Structure of a PortablePdbCache //! //! A PortablePdbCache(version 1) contains the following primary kinds of data, written in the following //! order: //! //! 1. Files //! 2. Source Locations //! 3. Addres...
use std::time::Duration; use crate::sound::{self, Sound}; use sdl2::audio::{AudioCallback, AudioSpecDesired}; struct SamplePlayer<'a> { samples: &'a Vec<f64>, offset: usize, } impl<'a> AudioCallback for SamplePlayer<'a> { type Channel = f32; fn callback(&mut self, out: &mut [f32]) { // shift...
//! Error module //! //! Contains API errors along with result types. use std::{fmt, io}; use std::result::Result as StdResult; use std::error::Error as StdError; use hyper::error::Error as HyperError; use rustc_serialize::json; use dto::FromDTOError; /// The result type of the API. pub type Result<T> = StdResult<T,...
use serde::{Deserialize, Serialize}; use std::io::{self, Write}; #[derive(Debug, Serialize, Deserialize)] pub struct Record<T> { pub timestamp: Timestamp, pub data: T, } pub struct Timestamp { secs: i64, tm: time::Tm, } impl Timestamp { pub fn new(secs: i64) -> Self { Self { secs, tm: time::at_utc(time...
use hashbrown::HashMap; /// Hold a dict of objects identified by their names. The purpose of this struct is for /// singleton pattern pub struct Objects<T> { objects: HashMap<String, T> } impl<T> Objects<T> { pub fn new(inputs: Vec<(&str, T)>) -> Objects<T> { Objects { objects: inputs.into_iter() ...
use std::cmp::{ min }; fn main(){ dijkstra(); } const I: usize = 10000; const V: usize = 7; fn dijkstra(){ let cost = [ [0, 5, 2, I, I, I, I], [5, 0, 4, 2, I, I, I], [2, 4, 0, 6,10, I, I], [I, 2, 6, 0, I, 1, I], [I, I,10, I, 0, 3, 5], [I, I, I, 1, 3, 0, 9], ...
use std::fmt; #[derive(Copy, Clone)] pub enum Color { Black, Red, Green, Yellow, Blue, Magenta, Cyan, White, BrightBlack, BrightRed, BrightGreen, BrightYellow, BrightBlue, BrightMagenta, BrightCyan, BrightWhite, Reset } impl Color { pub fn fgcode...
// Project Euler: Problem 43 extern crate euler; use euler::util::LexicographicPermutations; fn main() { println!("Finding sub-string divisible pandigital numbers.."); let sub_string_divisibles = LexicographicPermutations::from("0123456789") .filter(|s| { let d: Vec<u32> = s.char...
use std::{env, fs}; fn main() -> Result<(), Box<dyn std::error::Error>> { tonic_build::compile_protos("proto/network.proto")?; // Fix for `connect` gRPC method conflict let output_file = format!("{}/transport.rs", env::var("OUT_DIR")?); let source = fs::read_to_string(&output_file)?; fs::write( ...
pub mod error; pub mod processor; pub mod state; pub mod instruction; pub use solana_program; use crate::{error::TokenError, processor::Processor}; use solana_program::{ entrypoint::ProgramResult, pubkey::Pubkey, account_info::AccountInfo, entrypoint, program_error::PrintProgramError, }; solana_program::decl...
use crate::hkt::HKT; use crate::monoid::Monoid; // Cheating: all HKT instances exist for any B, // so HKT<B> here isn't about Self<B> having any meaning, // it's about folding on some Self<A> -- the HKT lets us // have an A to speak of. pub trait Foldable<B>: HKT<B> + Sized { fn reduce<F>(self, b: B, ba: F) -> B ...
fn main() { let tup = ("Apple", 1, 12); let (name, weight, price) = tup; println!("Name: {}", name); println!("Weight: {}", weight); println!("Price: {}", price); }
use protobuf::Message; use super::test_reflect_default_pb::*; #[test] fn test_regular() { let m = TestReflectDefault::new(); let descriptor = TestReflectDefault::descriptor_static(); let i = descriptor.get_field_by_name("i").unwrap(); assert_eq!(10, i.get_singular_field_or_default(&m).to_i32().unwra...
extern crate netfilter_queue as nfq; use nfq::handle::{Handle, ProtocolFamily}; use nfq::queue::{Verdict, VerdictHandler}; use nfq::message::{Message, IPHeader}; fn main() { let mut handle = Handle::new().ok().unwrap(); handle.bind(ProtocolFamily::INET).ok().unwrap(); let mut queue = handle.queue(0, Deci...
use clap::{App, Arg}; use env_logger::Env; use log_parser::parser; use std::time::Instant; #[macro_use] extern crate log; fn main() { let env = Env::default() .filter_or("MY_LOG_LEVEL", "info") .write_style_or("MY_LOG_STYLE", "always"); env_logger::init_from_env(env); let matches = App::n...
mod test_generated; pub mod compile_test; mod test; mod imp; pub use imp::generate_interface::generate_interface as generate_interface;
use io::Write; use std::{io, process::Command}; use std::fs; use std::fs::File; use std::io::Read; use std::path::{Path, PathBuf}; use std::process::Stdio; use clang::{Clang, Entity, EntityKind, Index}; const GENERATED_CODE_MARKER: &'static str = "\n\n/// Generated Code\n\n"; fn main() { println!("cargo:rerun-if...
// Copyright 2022 IOTA Stiftung // SPDX-License-Identifier: Apache-2.0 //! Implementation of [`PlaceholderSecretManager`]. use std::ops::Range; use async_trait::async_trait; use crypto::keys::slip10::Chain; use iota_types::block::{ address::Address, signature::Ed25519Signature, unlock::{Unlock, Unlocks},...
#![allow(dead_code)] use hdk::{ self, entry_definition::{ ValidatingEntryType }, holochain_core_types::{ cas::content::Address, dna::entry_types::Sharing, error::HolochainError, json::JsonString, hash::HashString } }; #[derive(Serialize, Deserialize, ...
use serde::Serializer; use rust_decimal::Decimal; const PRECISION: u32 = 4; pub fn fixed_precision_serializer<S: Serializer>(x: &Decimal, s: S) -> Result<S::Ok, S::Error> { s.serialize_str(&x.round_dp(PRECISION).to_string()) }
mod leader_for_topic; mod response_hdlr; mod query_metadata; mod query_api_versions; pub use leader_for_topic::find_broker_leader_for_topic_partition; pub use response_hdlr::handle_kf_response; pub use query_metadata::query_kf_metadata; pub use query_api_versions::kf_get_api_versions; pub use query_api_versions::kf...
use crate::common::*; pub(crate) trait TemplateExt { #[throws] fn render_newline(&self) -> String; #[throws] fn render_to(&self, path: impl AsRef<Path>) { let path = path.as_ref(); let text = self.render_newline()?; fs::write(&path, text).context(error::Filesystem { path })?; } } impl<T: Templa...
use rustc_serialize::json; use std::fs::File; use std::io::Read; use std::string::String; #[derive(RustcEncodable, RustcDecodable)] pub struct Config { pub enabled: bool, pub static_dir: String, pub api_address: String, pub static_address: String } impl Config { fn read_config_file(base_file: &str...
use objects::file_mode::FileMode; use objects::object::Object; use utils; pub struct Tree { header: String, content: String, } impl Tree { // fn new meta: String, content: String) -> Tree { // Tree { meta, content } // } pub fn new(s: &String) -> Tree { let null_offset = s.find('\...
fn main() { let mut s = String::new(); std::io::stdin().read_line(&mut s).unwrap(); let input: Vec<i32> = s.split_whitespace().map(|x| x.parse::<i32>().unwrap()).collect(); let base = input[0] % 1000; if input[0] / 1000 == 1 { println!("ABD"); } else { println!("ABC"); } }
#[doc = "Register `CTL0` reader"] pub struct R(crate::R<CTL0_SPEC>); impl core::ops::Deref for R { type Target = crate::R<CTL0_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<CTL0_SPEC>> for R { #[inline(always)] fn from(reader: crate::R<CTL0_SP...
//! Molt Benchmark Harness //! //! A Molt benchmark script is a Molt script containing benchmarks of Molt code. Each //! benchmark is a call of the Molt `benchmark` command provided by the //! `molt_shell::bench` module. The benchmarks are executed in the context of the //! the application's `molt::Interp` (and so ca...
mod patents; mod requests; use actix_web::web; pub fn concated_resources (cfg: &mut web::ServiceConfig) { patents::append_resources(cfg); }
use bellman::pairing::{Engine,}; use bellman::pairing::ff::{Field, PrimeField}; use bellman::{ConstraintSystem, SynthesisError}; use common::boolean::Boolean; use common::num::{Num, AllocatedNum}; trait Sbox<E: Engine> { fn apply_sbox<CS: ConstraintSystem<E>> ( cs: CS, num: &AllocatedNum<E>, ...
#![cfg_attr(not(feature = "std"), no_std)] pub use pallet::*; #[cfg(test)] mod mock; #[cfg(test)] mod tests; use frame_support::{ dispatch::DispatchError, ensure, storage::{with_transaction, TransactionOutcome}, traits::Get, traits::{Currency, ExistenceRequirement, ReservableCurrency}, }; use sp_runtime::trait...
struct Solution {} impl Solution { pub fn plus_one(digits: Vec<i32>) -> Vec<i32> { let mut digits = digits; let size = digits.len(); let mut carry = None; let last = match digits.get_mut(size - 1) { None => return digits, Some(v) => { *v += 1;...
#![feature(const_fn)] #![feature(existential_type)] /// A type decleration for the [`compose`] function. /// This *has* to carry around the F1 and F2 generic parameters, which stand for the 2 function being composed. pub existential type Composed<T1, T2, T3, F1, F2>: Fn(T1) -> T3; /// Composes 2 function's into a new...
//Rock Paper Scissors //Author: Nick Risinger (ncr13) extern crate rand; //I/O use use std::io; use std::io::Error; //Random use use rand::Rng; //enum for selected play enum RPS { Rock, Paper, Scissors } //enum for outcome of round enum Outcome { Win, Lose, Tie } //stores stats for game struct Stats { rocks...
use crate::input::{Show, ParserInfo}; pub use crate::expected::Expected; #[derive(Debug, Clone)] pub struct ParseError<C, E> { pub error: E, pub contexts: Vec<ParseContext<C>>, } #[derive(Debug, Clone)] pub struct ParseContext<C> { pub parser: ParserInfo, pub context: Option<C>, } impl<C, E> ParseEr...
use crate::common::*; #[derive(Debug, Deserialize, PartialEq, Serialize)] pub(crate) struct UtMetadata { pub(crate) msg_type: u8, pub(crate) piece: usize, #[serde( skip_serializing_if = "Option::is_none", default, with = "unwrap_or_skip" )] pub(crate) total_size: Option<usize>, } #[derive(Debug,...
// Copyright 2016 Mozilla // // 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 writing, software...
use std::io; fn read_as_char() -> Vec<char>{ let mut c = String::new(); io::stdin().read_line(&mut c).unwrap(); c.trim().split_whitespace() .map(|e| e.parse().ok().unwrap()).collect() } fn is_symbol(symbol: &char) -> bool{ let lib: Vec<char> = vec!['+', '-', '/', '*']; for i in &lib{ ...
#[macro_use] extern crate tokio; use binance::api::*; use binance::userstream::*; use binance::websockets::*; use binance::ws_model::{CombinedStreamEvent, WebsocketEvent, WebsocketEventUntag}; use futures::future::BoxFuture; use futures::stream::StreamExt; use serde_json::from_str; use std::sync::atomic::{AtomicBool, ...
use crate::implicit_search_request_parser::ImplicitPaperSearchRequest; use crate::storage::Paper; use lazy_static::lazy_static; use regex::Regex; pub fn markdown_v2_escape(text: &str) -> String { lazy_static! { static ref TELEGRAM_ESCAPE_REGEX_ESCAPE: [&'static str; 11] = ["{", "}", "[", "]", "...
/* * Copyright (c) 2020 - 2021. Shoyo Inokuchi. * Please refer to github.com/shoyo/jindb for more information about this project and its license. */ use crate::buffer::replacement::PageReplacer; use crate::constants::BufferFrameIdT; /// A clock eviction policy for the database buffer. pub struct ClockReplacer {} ...
use chrono::{NaiveDateTime, Utc}; use diesel::{insert_into, prelude::*, update}; use super::super::super::super::super::{ errors::Result, orm::{Connection, ID}, }; use super::super::schema::vpn_logs; #[derive(Queryable, Serialize, Clone)] #[serde(rename_all = "camelCase")] pub struct Item { pub id: ID, ...
/* This file is part of bacon. * Copyright (c) Wyatt Campbell. * * See repository LICENSE for information. */ mod adams; mod bdf; mod euler; mod rk; use crate::ivp::solve_ivp; use nalgebra::{VectorN, U1, U2}; fn exp_deriv(_: f64, y: &[f64], _: &mut ()) -> Result<VectorN<f64, U1>, String> { Ok(VectorN::<f64, ...
// This file is part of Substrate. // Copyright (C) Parity Technologies (UK) Ltd. // SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 // 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 Softwa...
use anyhow::Result; use async_trait::async_trait; use super::iface::Flush; pub trait StorageMappingStore: Flush { fn get_node_for_blob(&self, blob_id: &str) -> Result<Option<String>>; fn set_node_for_blob(&self, blob_id: &str, node_id: String) -> Result<()>; fn delete_blob(&self, blob_id: &str) -> Result...
// 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...
// use crate::{ // config::config::get, // helpers::{download::download, extract::extract, file::file_writer}, // schemas::store::Store, // }; use crate::{ structures::store::Store, utils::{config::get, download::download, extract::extract, file::file_writer}, }; use colored::Colorize; use itertool...
use opengl_graphics::{ GlGraphics, Texture, OpenGL }; use simplebar::SimpleBar; use graphics::math::Matrix2d; use graphics::Transformed; use graphics::Graphics; use graphics::image::Image as im; use graphics::context::Context; use image::*; use display::*; use texture::*; pub struct BarGraph { pub graph: Vec<Simp...
// vim: tw=80 //! Ensure that foreign functions can return () #![deny(warnings)] use mockall::*; #[automock(mod mock_ffi;)] extern "C" { #[allow(unused)] fn foo(); } #[test] fn returning() { let ctx = mock_ffi::foo_context(); ctx.expect().returning(|| ()); unsafe{mock_ffi::foo()}; }
// Lumol, an extensible molecular simulation engine // Copyright (C) Lumol's contributors — BSD license //! 3x3 matrix type. use std::iter; use std::ops::{Add, Div, Mul, Sub}; use std::ops::{AddAssign, DivAssign, MulAssign, SubAssign}; use std::ops::{Deref, DerefMut}; use num_traits::{One, Zero}; use crate::Vector3D...
use actix_web::{App, Error, HttpRequest, HttpResponse, HttpServer, web}; use actix_web_actors::ws; use crate::websocket::context::GateWs; mod websocket; async fn index(req: HttpRequest, stream: web::Payload) -> Result<HttpResponse, Error> { let resp = ws::start(GateWs { message: "Hi".to_string() }, &req, stream...
use morphorm::Cache; use crate::{Display, Entity, Event, Propagation, Context, Units, Visibility, WindowEvent}; /// Determines the hovered entity based on the mouse cursor position pub fn apply_hover(cx: &mut Context) { //println!("Apply Hover"); //let mut draw_tree: Vec<Entity> = cx.tree.into_iter().collect(...
use std::{ collections::{hash_map::IntoIter, HashMap}, convert::TryFrom, fmt::Display, }; use crate::errors::DiscoverError; use serde::{Deserialize, Serialize}; #[derive(Debug, Clone, Deserialize, Serialize)] pub enum SupportedProvider { #[serde(rename = "aws")] AWS, #[serde(rename = "digitalo...
// //! Copyright 2020 Alibaba Group Holding Limited. //! //! 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 ...
use cpu::Cpu; use super::InstrResult; use std::fmt; #[allow(unused_variables)] pub fn sec(cpu: &mut Cpu) -> Box<InstrResult> { set(Flag::Carry) } #[allow(unused_variables)] pub fn sed(cpu: &mut Cpu) -> Box<InstrResult> { set(Flag::Decimal) } #[allow(unused_variables)] pub fn sei(cpu: &mut Cpu) -> Box<InstrR...
mod symbol; extern crate yahoo_finance_api; extern crate clap; extern crate chrono; extern crate crossbeam; use clap::{App, Arg}; use chrono::prelude::*; use crossbeam::channel::{unbounded}; use crate::symbol::{Range, TickerInfo}; fn main() { let args = App::new("Stock Tracking cli") .about("A tool to...
use std::process::Command; use tokio_process::CommandExt; // extension trait for std::process::Command; use std::process::Stdio; use libc; use std::thread::sleep; use std::time::Duration; use std::sync::atomic::{AtomicU32, Ordering}; static CHILD: AtomicU32 = AtomicU32::new(0); fn main() { // foreground_std_lib(...
use std::f64::consts::PI; /** * Referencing Other Modules and Crates * * モジュール内のアイテムは、モジュールのフルパス `std::f64::consts::PI` で参照することができます。 * * もっと簡単な方法は use キーワードです。 * これを使用すると、フルパスでなくてもコード全体で * 使用したいモジュールの特定の項目を指定することができます。 * 例えば use std::f64::consts::PI を使うと、メイン関数で識別子 PI を使う事ができます。 * * std は Rustの標準ライブラリのクレートであ...
use cursive::Cursive; use cursive::views::{TextView, IdView, LinearLayout, BoxView, Panel}; use cursive::view::SizeConstraint; use cursive::align::VAlign; use cursive::direction::Orientation; use std::cell::RefCell; use std::rc::Rc; use solver::Solver; use board::Board; use pos::Pos; use std::string::String; pub s...
use curl::easy::{Easy, Form}; use deflate::deflate_bytes_gzip; use serde::{ ser::{SerializeStruct, Serializer}, Deserialize, Serialize, }; use std::collections::HashMap; use std::env::var; use std::fs::File; use std::io; use std::io::prelude::*; use std::path::Path; use std::str::FromStr; /// Representation of...
#![feature(mpsc_select)] #[macro_use] extern crate log; extern crate crc; extern crate crypto; extern crate time; extern crate rand; pub mod logger; pub mod tcp; pub mod ucp; pub mod timer; pub mod client; pub mod server; pub mod socks5; pub mod cryptor; mod protocol { use std::vec::Vec; pub const VERIFY_DA...
use std::sync::mpsc; use std::process; use glfw::Context; use crate::Size; use crate::events::Event; use crate::window_base::WindowProps; type EventCallbackFn = fn(&mut Box<dyn Event>); /// Represents the data of a window struct WindowData { /// The title of the window title: &'static str, /// The size of the wind...
use super::{Context, Registry}; use std::any::Any; pub trait AsAny: Any { fn as_any(&self) -> &dyn Any; fn as_any_mut(&mut self) -> &mut dyn Any; } /// Used to define a state of a widget. /// /// A state is used to operate on the properties (components) of the widget, its parent or children. pub trait State:...
use std::{ clone::Clone, convert::TryFrom, fmt::{self, Debug, Display}, rc::Rc, }; use crate::{error as e, value::Value}; #[derive(PartialEq, Eq, Hash)] pub enum HashMapKey { Keyword(Rc<String>), String(Rc<String>), Symbol(Rc<String>), Number(i128), Bool(bool), Nil, } impl Clo...
extern crate num_derive; use num::{ToPrimitive}; use std::str::FromStr; use std::convert::TryFrom; use std::rc::Rc; use indextree::Arena; use indextree::Node; use indextree::NodeId; macro_rules! opcode { ($op:tt) => { crate::chunk::Opcode::to_u8(&crate::chunk::Opcode::$op).unwrap() }; } #[derive(Debu...
use core::mem::transmute; use sdl2_sys::SDLK_a; use sdl2_sys::SDLK_d; use sdl2_sys::SDLK_s; use sdl2_sys::SDLK_w; use sdl2_sys::SDL_Event; use sdl2_sys::_bindgen_ty_7; use sdl2_sys::SDLK_DOWN; use sdl2_sys::SDLK_ESCAPE; use sdl2_sys::SDLK_LEFT; use sdl2_sys::SDLK_RETURN; use sdl2_sys::SDLK_RIGHT; use sdl2_sys::SDLK_SPA...
mod models; use models::booking_models::booking_commands::BookingCommands; use models::booking_models::booking_data::{BlockData, BookingData}; use models::customer_models::customer_data::Customer; use models::service_models::service_data::Service; use models::staff_models::staff_data::Staff; use chrono::prelude::*; ...
#[macro_export] macro_rules! target_path { ($path:tt) => { &format!("target/debug/{}", $path) }; } #[macro_export] macro_rules! delete_file { ($path:tt) => { ::std::fs::remove_file($path).expect(&format!("File: {} can not delete.", $path)); }; } #[macro_export] macro_rules! create_file...
use nom::branch::alt; use nom::character::complete::{char, one_of}; use nom::multi::many0; use nom::IResult; use std::convert::TryFrom; static BRAINFUCK_BYTES: &[u8] = b"><+-.,[]"; #[derive(Debug, Clone, Eq, PartialEq)] pub struct TokenTree(pub Vec<Token>); impl TokenTree { pub fn from_str(program: &str) -> Self...
extern crate nalgebra; #[derive(Copy, Clone)] pub struct Vertex { pub position: [f32; 3], pub texcoord: [f32; 2], pub normal: [f32; 3], } implement_vertex!(Vertex, position, texcoord, normal);
/** * Copyright (c) 2019, Jesús Rubio <jesusprubio@member.fsf.org> * * This source code is licensed under the MIT License found in * the LICENSE.txt file in the root directory of this source tree. */ #[cfg(test)] use leg::*; #[test] fn should_work() { head("leg", Some("🔈"), Some("1.0.0")); info("Inform...
#![cfg_attr(rustfmt, rustfmt::skip)] use super::*; fn docs_of (attrs: &'_ [Attribute]) -> impl '_ + Iterator<Item = &'_ Attribute> { attrs .iter() .filter(|a| a.path.is_ident("doc")) } pub(in crate) fn derive ( args: Args, attrs: &'_ mut Vec<Attribute>, pub_: &'_ Visibility, Str...
use core::ptr::write_volatile; use core::ptr::read_volatile; pub unsafe fn write(reg: u32, value: u32) { write_volatile(reg as *mut u32, value) } pub unsafe fn read(reg: u32) -> u32 { read_volatile(reg as *mut u32) } pub unsafe fn set_bits(reg: u32, v: u32) { let val = read(reg); write(reg, val | v);...
//! --- Day 25: Cryostasis --- //! //! As you approach Santa's ship, your sensors report two important details: //! //! First, that you might be too late: the internal temperature is -40 degrees. //! //! Second, that one faint life signature is somewhere on the ship. //! //! The airlock door is locked with a code; your...
use actix::Addr; use futures::future::{err, join_all, ok, Either, Future}; use rayon::prelude::*; use sqlparser::ast::{Expr, Function}; use std::{ borrow::{Borrow, BorrowMut}, collections::HashMap, sync::Arc, }; use tokio_postgres::{ tls::{MakeTlsConnect, TlsConnect}, Socket, }; use super::select_t...
use postgres::types::{FromSql, IsNull, ToSql, Type, BYTEA, INT8, JSON, JSONB}; use serde::{de::DeserializeOwned, Serialize}; use std::{error::Error, fmt}; #[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)] pub struct BorrowedJson<'a, T>(pub &'a T); impl<'a, T> ToSql for BorrowedJson<'a, T> where T: Serialize + fm...
#[macro_use] extern crate measure_time; use mercator_db::space::Shape; use mercator_db::storage; use mercator_db::CoreQueryParameters; use mercator_db::DataBase; fn main() { // If RUST_LOG is unset, set it to INFO, otherwise keep it as-is. if std::env::var("RUST_LOG").is_err() { std::env::set_var("RUS...
// The Computer Language Benchmarks Game // http://benchmarksgame.alioth.debian.org/ // // contributed by the Rust Project Developers // contributed by Cristi Cobzarenco // contributed by TeXitoi // contributed by Matt Brubeck extern crate rayon; use std::io::{BufRead, BufReader, Write}; use std::{cmp, io}; use std::...
#[doc = r"Register block"] #[repr(C)] pub struct XIP_ENC { #[doc = "0x00 - Bits 31:0 of XIP AES KEY"] pub key0: KEY0, #[doc = "0x04 - Bits 63:32 of XIP AES KEY"] pub key1: KEY1, #[doc = "0x08 - Bits 95:64 of XIP AES KEY"] pub key2: KEY2, #[doc = "0x0c - Bits 127:96 of XIP AES KEY"] pub k...
//! A scene is essentially everything that the user can see or hear, and anything that interacts with that. mod node; pub use node::*; use std::sync::{RwLock, Arc, Weak}; use crate::events::EventHandlers; /// The scene contains everything that the user can see or hear, and anything that interacts with that. /// Cova...
//! Linker script. use drone_config::{addr, size, Layout}; use eyre::Result; use heck::{AsShoutySnakeCase, ToShoutySnakeCase}; use sailfish::TemplateOnce; use std::collections::BTreeMap; use std::fs; use std::path::Path; /// All types of data sections. pub const DATA_SECTIONS: &[&str] = &["data", "bss", "uninitialize...
/* * Copyright (c) 2020 - 2021. Shoyo Inokuchi. * Please refer to github.com/shoyo/jindb for more information about this project and its license. */ use crate::executor::{BaseExecutor, QueryMeta}; use crate::plan::insert::InsertPlanNode; use crate::relation::record::Record; use std::sync::{Arc, Mutex}; /// An exe...
/* * @lc app=leetcode id=1201 lang=rust * * [1201] Ugly Number III * * https://leetcode.com/problems/ugly-number-iii/description/ * * algorithms * Medium (24.98%) * Total Accepted: 5K * Total Submissions: 20.1K * Testcase Example: '3\n2\n3\n5' * * Write a program to find the n-th ugly number. * * Ug...
use actix_web::{ error, middleware, web, App, Error, HttpRequest, HttpResponse, HttpServer, }; use bytes::{Bytes, BytesMut}; use futures::StreamExt; use json::JsonValue; use serde::{Deserialize, Serialize};
use wasmly::DataType::*; use wasmly::*; fn main() -> std::io::Result<()> { let mut app = App::new(vec![Import::ImportFunction(ImportFunction::new( "console_log".to_string(), vec![I32], None, ))]); let d = Data::new(0, "Hello World!\0".as_bytes().to_vec()); app.add_data(d); ...
use rust_by_example::{mobile::*, web::*}; struct Point { x: i32, y: f32, } impl Computers for Point { fn int(&self) -> i32 { self.x } fn float(&self) -> f32 { self.y } } fn main() { let pressed = WebEvent::KeyPress('x'); // `to_owned()` creates an owned `String` from a ...
use std::env; use diesel::mysql::MysqlConnection; use diesel::r2d2::{ConnectionManager, Pool, PooledConnection, PoolError}; pub type MysqlPool = Pool<ConnectionManager<MysqlConnection>>; pub type MySqlPooledConnection = PooledConnection<ConnectionManager<MysqlConnection>>; fn init(database_url: &str) -> Result<Mysql...
pub mod def; pub mod dp; pub mod raft; pub mod sv; #[cfg(test)] mod test {}
extern crate projecteuler; use projecteuler::primes::*; fn main() { let mut primes = Primes::new(); let factorization = primes.factorize(600851475143); println!("{}", factorization.last().unwrap().0); }
// Copyright 2020 Contributors to the Parsec project. // SPDX-License-Identifier: Apache-2.0 /// This module contains both the constants defined in the TSS specification (tss module) /// but also the internal representaion of the TSS constants. /// Representation of the constants defined in the /// Constants -> TPM_A...
// This file is part of Substrate. // Copyright (C) Parity Technologies (UK) Ltd. // SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 // 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 Softwa...
#![allow(non_snake_case)] #[cfg(all(feature = "SignatureG1", feature = "SignatureG2"))] compile_error!("features `SignatureG1` and `SignatureG2` are mutually exclusive"); // Externs extern crate amcl_wrapper; #[macro_use] extern crate ps_sig; extern crate rand; #[macro_use] extern crate failure; extern crate serd...
use std::collections::BTreeMap; use crate::{protocol::Protocol, utils::Step}; #[derive(Clone, Debug, PartialEq, Eq)] pub struct State<TProtocol: Protocol> { /// The round this tendermint instance is currently in. pub current_round: u32, /// The Step this tendermint instance is currently in. pub curre...
extern crate url; use self::url::form_urlencoded; use std::collections::HashMap; use std::path::Path; use http::response::Response; use common::*; pub fn file2response(path: &Path) -> Response { let mut resp = Response::new(200); let path_buf = chroot_path(path, "public"); let file_content = binary_cat(pa...
// Copyright (c) The Starcoin Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::module::helpers::TransactionRequestFiller; use crate::module::map_err; use futures::future::TryFutureExt; use futures::FutureExt; use starcoin_account_api::{AccountAsyncService, AccountInfo}; use starcoin_config::NodeCon...