text
stringlengths
8
4.13M
use clap::{crate_version, App, Arg}; /// Creates a static clap application for parsing the arguments pub fn get_app() -> clap::App<'static> { let default_exec = if cfg!(windows) { "start" } else if cfg!(macos) { "open" } else { "xdg-open" }; App::new("fuzzy-pdf") .v...
use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt, ByteOrder}; use super::*; use super::sodium; use std::io::{Read, Write}; use openssl; use std::cmp::min; use std::num::Wrapping; use algorithm::*; use encoding::{ReadValue, WriteValue}; pub enum PublicKey { RSAEncryptSign(openssl::crypto::rsa::RSA), Ed...
use nix::unistd::{Gid, Uid}; use std::fs::File; use std::io::{self, BufRead}; #[derive(Clone)] pub struct User { pub name: String, pub password: String, pub uid: Uid, pub gid: Gid, pub sgids: Vec<Gid>, pub comment: String, pub home: String, pub shell: String, } macro_rules! system { ...
use crate::doctor::Doctor; use crate::error::AppError; use crate::tickets::Ticket; use actix_session::Session; use actix_web::{get, post, web, HttpResponse, Result}; use deadpool_postgres::Client; use deadpool_postgres::Pool; use scrypt::{scrypt_check, scrypt_simple, ScryptParams}; use serde::Deserialize; use serde_jso...
pub struct ProcessedRoute { pub head: String, pub tail: Option<String> } pub fn process_route(route: String) -> Option<ProcessedRoute> { if route.len() == 0 { return None } let mut split = route.split("/"); match split.next() { Some(head) => { match split.next() { Some(tail) => { ...
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT license. */ pub trait Scratch { fn clear(&mut self); }
use std::collections::HashMap; fn main() { let input ="F6J)1YB 6LV)SG3 K7G)GD2 JC1)Y2W 43D)SP2 YQV)JKG TD4)7SZ H8T)43D T1S)H8Y 1BW)H7F PDV)93Q 2HK)Z93 37L)1FF 35Y)MZH 7NY)DWF YLS)5B6 N66)QLD T9K)TMS JZF)7TC 9QD)YRG 5T2)CYY DBP)FG7 JVN)N7N Q78)K9T 6CZ)D66 WD3)LNP 7YB)Y9T Z3S)115 2PD)RC7 XZS)DZD PCP)3YG QYH)3CV F3M)...
use crate::error::*; use crate::file::*; use crate::tables::*; use winmd_macros::*; #[type_code(2)] pub enum TypeDefOrRef { TypeDef, TypeRef, TypeSpec, } #[type_code(5)] pub enum HasCustomAttribute { MethodDef, Field, TypeRef, TypeDef, Param, InterfaceImpl, MemberRef, TypeS...
// =============================================================================================== // Imports // =============================================================================================== use super::{PMM, Page, Frame}; use core::ops::{Index, IndexMut}; use core::ptr::Unique; use x86::current::pag...
fn main() { another_function(5); print_labeled_measurement(5, 'h'); let r = five(); println!("The value of r is: {r}"); } fn another_function(x: i32) { println!("The value of x is: {x}"); } fn print_labeled_measurement(value: i32, unit_label: char) { println!("The measurement is: {value}{unit_...
pub mod toml; pub mod dependencies;
use std::io::stdin; fn main() { exec("++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++."); } fn exec(code: &str) { let mut memory: [u8; 30000] = [0; 30000]; let mut pointer: usize = 0; let code_arr = code_to_char_array(code); let mut i = 0...
/* * 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 */ /// SyntheticsCiTestMetadata : Metadata for the Synthetics tests run #[derive(Clone, Debug, PartialEq...
extern crate csv; extern crate elma; use WR; use Targets; use DataRow; use std::io::prelude::*; use elma::Time; pub fn read_targets_table() -> Vec<Targets> { let mut tst = Vec::new(); let mut r = csv::Reader::from_file("targets.csv").unwrap(); for record in r.records() { if let Ok(row) = record { ...
use std::collections::BTreeSet; use std::fmt; use std::path::{Path, PathBuf}; use anyhow::Result; use clap::{ArgAction, Parser, ValueEnum}; use fs_err as fs; use crate::build_options::find_bridge; use crate::project_layout::ProjectResolver; use crate::{BridgeModel, CargoOptions}; /// CI providers #[derive(Debug, Clo...
use crate::connection::Throughput; use crate::estimate::{ChangeEstimates, Estimates}; use crate::report::{BenchmarkId, ComparisonData, MeasurementData}; use anyhow::{Context, Result}; use chrono::{DateTime, Utc}; use linked_hash_map::LinkedHashMap; use std::collections::HashSet; use std::ffi::OsStr; use std::fs...
use ash::vk; use ash::extensions::khr; use ash::version::DeviceV1_0; use super::{ Instance, Surface, Device }; pub struct Swapchain { loader: khr::Swapchain, handle: vk::SwapchainKHR, format: vk::SurfaceFormatKHR, images: Vec<vk::Image>, views: Vec<vk::ImageView>, } pub enum SwapchainCreationErro...
pub mod sharedlock; pub use sharedlock::SharedLock; #[derive(Debug)] pub enum Error { DeadLockError, Poisoned, } pub type Result<T> = std::result::Result<T, Error>; impl std::fmt::Display for Error { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Err...
use crate::Ray; use crate::Vec3; #[derive(Clone, Debug, PartialEq, Copy)] pub struct AABB { pub min: Vec3, pub max: Vec3, } impl AABB { pub fn new(a: Vec3, b: Vec3) -> Self { Self { min: a, max: b } } pub fn min(a: f64, b: f64) -> f64 { if a < b { a } else { ...
use std::{ fmt::Debug, ops::{Deref, DerefMut}, }; use crate::util::{impl_deref_wrapped, impl_from_repeated}; use librespot_core::FileId; use librespot_protocol as protocol; use protocol::metadata::VideoFile as VideoFileMessage; #[derive(Debug, Clone, Default)] pub struct VideoFiles(pub Vec<FileId>); impl_d...
extern crate cgmath; #[macro_use] extern crate glium; extern crate aperture; use cgmath::prelude::*; use glium::glutin; use glium::Surface; use std::thread::sleep; use std::time::{Duration, SystemTime}; #[derive(Copy, Clone)] struct Vertex { position: [f32; 3], } implement_vertex!(Vertex, position); fn main() { ...
#[link(name="hello", kind="static")] extern{ fn hello(); fn c_add( a: i32, b: i32 ) -> i32 ; } fn main() { unsafe { hello(); } let a = 10 ; let b = 20 ; let ans = unsafe { c_add( a, b ) }; println!("ans is {}", ans ); }
#[doc = "Register `APB1FZR1` reader"] pub type R = crate::R<APB1FZR1_SPEC>; #[doc = "Register `APB1FZR1` writer"] pub type W = crate::W<APB1FZR1_SPEC>; #[doc = "Field `DBG_TIMER2_STOP` reader - Debug Timer 2 stopped when Core is halted"] pub type DBG_TIMER2_STOP_R = crate::BitReader<DBG_TIMER2_STOP_A>; #[doc = "Debug T...
#![doc = "generated by AutoRust 0.1.0"] #![allow(non_camel_case_types)] #![allow(unused_imports)] use serde::{Deserialize, Serialize}; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct RoleAssignmentApprovalActorIdentity { #[serde(rename = "principalId", default, skip_serializing_if = "Option::i...
use crate::distribution::{Continuous, ContinuousCDF}; use crate::function::{beta, gamma}; use crate::is_zero; use crate::statistics::*; use crate::{Result, StatsError}; use rand::Rng; use std::f64; /// Implements the [Student's /// T](https://en.wikipedia.org/wiki/Student%27s_t-distribution) distribution /// /// # Exa...
use crate::{ define_node_command, get_set_swap, scene::commands::{Command, SceneContext}, }; use rg3d::{ core::{color::Color, pool::Handle}, resource::texture::Texture, scene::{graph::Graph, node::Node}, }; define_node_command!(SetDecalDiffuseTextureCommand("Set Decal Diffuse Texture", Option<Textu...
use radmin::uuid::Uuid; use serde::{Deserialize, Serialize}; use crate::schema::organizations; use radmin::chrono::{DateTime, Utc}; #[derive(Debug, PartialEq, Clone, Serialize, Deserialize, Queryable, Identifiable, AsChangeset)] #[table_name = "organizations"] pub struct OrganizationInfo { pub id: Uuid, pub n...
use std::collections::BTreeMap; use crate::db::Db; use crate::db::entities::Candidate; pub async fn tally(db: &Db) -> sqlx::Result<(String, Vec<(String, String, bool)>)>{ let mut tally = Tally::new(db).await?; //TODO: use a transaction to prevent the data from changing while we read it let mut round_id = 1; ...
use slotmap::{Key, SlotMap}; // ------------------------------------------------------------------------------------------------- // TODO lots of unwraps here, should at least give useful error messages pub struct Forest<K, I> where K: Key { nodes: SlotMap<K, ForestNode<K, I>>, } impl<K, I> Forest<K, I> where K...
// Copyright 2019 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. use { crate::{ models::{DisplayInfo, Suggestion}, story_context_store::ContextEntity, story_manager::StoryManager, sugg...
use crate::Rolls; #[cfg(test)] mod unit_tests; pub fn score(rolls: &Rolls) -> u16 { foo(rolls.0.iter(), 1) } // variable-width fold // Item is an associated type fn foo<'a>(mut rolls: impl Iterator<Item = &'a u8> + Clone, frame_number: usize) -> u16 { // base case: if frame_number > 10 { return 0...
use crate::utils::file2vec; pub fn day11(filename: &String){ let contents = file2vec::<String>(filename); let contents:Vec<Vec<Seat>> = contents.iter().map(|x| x.to_owned().unwrap().chars().fold(Vec::new(), |mut acc, c| { acc.push(Seat::from_char(&c)); acc }) ).coll...
fn main() { panic!("panicking furiously"); }
/// CreateStatusOption holds the information needed to create a new Status for a Commit #[derive(Debug, Default, Clone, Serialize, Deserialize)] pub struct CreateStatusOption { pub context: Option<String>, pub description: Option<String>, pub state: Option<String>, pub target_url: Option<String>, } im...
use std::env; use std::fs::File; use std::io::prelude::*; use std::path::Path; pub fn get_file_content(file_path: &str) -> Vec<char> { let work_dir = env::current_dir().unwrap(); let full_file_path = work_dir.join(Path::new(file_path)); let mut file = File::open(full_file_path).unwrap(); let mut c...
//! # The XML `<BlockLibrary>` format //! //! This is use in: //! - The `res/ui/ingame/blocksdef.xml` file
#[doc = "Register `APB1_FZ` reader"] pub type R = crate::R<APB1_FZ_SPEC>; #[doc = "Register `APB1_FZ` writer"] pub type W = crate::W<APB1_FZ_SPEC>; #[doc = "Field `DBG_TIMER2_STOP` reader - Debug Timer 2 stopped when Core is halted"] pub type DBG_TIMER2_STOP_R = crate::BitReader<DBG_TIMER2_STOP_A>; #[doc = "Debug Timer...
use util::*; const LEN: usize = 'z' as usize - 'a' as usize + 1; fn main() { let timer = Timer::new(); let count: usize = input::vec::<String>(&std::env::args().nth(1).unwrap(), "\n\n") .iter() .map(|s| { let mut answered: [bool; LEN] = [false; LEN]; for c in s.replace(...
// 借用和生命周期 // 生命周期 // 一个变量的生命周期就是它从创建到销毁的整个过程。 pub fn first() { let v = vec![1, 2, 3, 4, 5]; // v 的生命周期开始 { let center = v[2]; // center 的生命周期开始 println!("{}", center); } // center 的生命周期结束 println!("{:?}", v); } // v 的生命周期结束 // 如果一个变量永远只能有唯一一个入口可以访问的话,那就太难使用了。 // 因此,所有权还可以借用。 // 所有权借用 ...
use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt}; use std::io::{self, Read, Write}; use crate::errors::{message::ErrorKind::*, ErrorKind, Result, ResultExt}; #[derive(Clone, Debug)] pub struct MessageHeader { command: [u8; 12], payload_size: u32, checksum: [u8; 4], } pub const MESSAGE_MAGIC: &[...
/*! # Davidson Diagonalization The Davidson method is suitable for diagonal-dominant symmetric matrices, that are quite common in certain scientific problems like [electronic structure](https://en.wikipedia.org/wiki/Electronic_structure). The Davidson method could be not practical for other kind of symmetric matrices...
use crate::animals::Animal; use crate::species::default::Canine; use crate::species::Species; use std::fmt; /// Dog pub struct Dog { name: Option<String>, species: Canine, } impl Dog { pub fn new(name: Option<String>) -> Self { Dog { name, species: Canine {}, } ...
// Copyright 2018 The Exonum Team // // 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 i...
use std::collections::{HashMap, HashSet}; use std::io::{self, BufRead}; use std::iter::once; type Rule = [(usize, usize); 2]; type Rules = HashMap<String, Rule>; type Ticket = Vec<usize>; fn parse_rule(line: &str) -> Option<(String, Rule)> { let mut it1 = line.split(": "); let name = it1.next()?.to_string(); ...
#![doc = include_str!("../README.md")] #![cfg_attr(not(feature = "std"), no_std)] #![cfg_attr(debug_assertions, warn(missing_docs))] #![cfg_attr(not(debug_assertions), deny(missing_docs))] #![deny(unconditional_recursion)] use core::{ fmt::{ Debug, Display, }, num::{ FpCategory, ParseIntError, }, str::Fro...
#![crate_type="lib"] #![crate_name="wasmlib"] #[macro_use] extern crate lazy_static; pub mod host_api; pub use host_api::*; pub mod resource; pub use resource::*;
fn main() { let numbers = vec![1, 2, 3, 4, 5]; let value = &numbers[0]; println!("value: {}", value); }
use hilbert_qexp::eisenstein::eisenstein_series_from_lvals; use hilbert_qexp::elements::{square_root_mut, HmfGen}; use flint::fmpq::Fmpq; use flint::fmpz::Fmpz; pub fn eisensten_series(k: u64, prec: usize) -> HmfGen<Fmpq> { assert!(2 <= k && k <= 10); let l_vals = [ ("48", "1"), ("480", "11"), ...
fn profile_for<T: AsRef<[u8]>>(email: T) -> Vec<u8> { let mut output = "email=".as_bytes().to_vec(); let cleaned: Vec<&u8> = email .as_ref() .into_iter() .filter(|c| !(**c == b'&' || **c == b'=')) .collect(); output.extend(cleaned); output.extend_from_slice("&uid=10&rol...
use option_lock::*; use std::sync::Arc; #[test] fn option_lock_guard() { let a = OptionLock::from(1); assert!(!a.is_locked()); let mut guard = a.try_lock().unwrap(); assert!(a.is_locked()); assert_eq!(a.try_lock().unwrap_err(), OptionLockError::Unavailable); assert_eq!(a.try_take(), Err(OptionL...
use std::{ cell::{Ref, RefCell, RefMut}, rc::Rc, }; pub struct State<T>(Rc<RefCell<T>>); impl<T> Clone for State<T> { fn clone(&self) -> Self { Self(self.0.clone()) } } impl<T> State<T> { pub fn new(x: T) -> Self { Self(Rc::new(RefCell::new(x))) } pub fn get_mut(&self) ->...
#[derive(Debug)] pub enum Task { //RunDnsResolver, }
use std::io::{stdout, Write}; fn main() { let args = std::env::args(); let argc = args.len(); // compute the width to print numbers in the range `0..argc` let width: usize = if argc <= 10 { 1 } else if argc <= 100 { 2 } else if argc <= 1_000 { 3 } else if argc <= 10...
/* TODO setup external file for testing - examples? multiple targets? why is this so complex see if &self can be named anything else - is it like python classes? */ use std::ops::{Mul,Div,Add,Sub}; // allows println to show struct - https://doc.rust-lang.org/book/ch05-02-example-structs.html #[derive(Debug)] #[deriv...
use amethyst::{ assets::AssetStorage, core::ecs::{Join, Read, ReadStorage, SystemData, World}, error::Error, renderer::{ bundle::{RenderOrder, RenderPlan, RenderPlugin, Target}, pipeline::{PipelineDescBuilder, PipelinesBuilder}, pod::ViewArgs, rendy::{ command...
pub fn large_group_positions(s: String) -> Vec<Vec<i32>> { if s.len() < 3 { return vec![]; } let bytes = s.as_bytes(); let mut ans = vec![]; ans.push(vec![0, 1]); let mut pre_c = bytes[0]; let mut start = 0; let mut end = 0; for i in 1..bytes.len() { if bytes[i] == pr...
const INF: i64 = 1 << 61; use std::cmp::min; struct Graph { edges: Vec<Vec<(usize, i64, i64, i64)>>, // adjacent list n: usize } impl Graph { fn new(n: usize) -> Self { Graph { edges: vec![Vec::new(); n], n, } } fn add(&mut self, from: usize, to: usize, cap...
use std::ffi::CStr; use std::mem; use std::slice; use vkr::{vk, Builder, Loader}; fn get_memory_type_index( memory_properties: &vk::PhysicalDeviceMemoryProperties, memory_type_bits: u32, property_flags: vk::MemoryPropertyFlags, ) -> Option<u32> { for i in 0..memory_properties.memory_type_count { ...
// Ennen makrojen ajamista macro_rules! impl_from { ($Small: ty, $Large: ty) => { impl From<$Small> for $Large { #[inline] fn from(small: $Small) -> $Large { small as $Large } } } } impl_from!(u16, u32); impl_from!(u16, u64); // Makrojen aja...
use actix_web::{web, Responder}; use chrono::NaiveDateTime; use rbatis::core::value::DateTimeNow; use crate::domain::domain::SysRes; use crate::domain::dto::{EmptyDTO, IdDTO, ResAddDTO, ResEditDTO, ResPageDTO}; use crate::domain::vo::RespVO; use crate::service::CONTEXT; use rbatis::plugin::snowflake::new_snowflake_id;...
#![feature(proc_macro_non_items)] #![feature(use_extern_macros)] extern crate procmacro2; fn main() { procmacro2::misc_syntax!( where while abcd : u64 >> 1 + 2 * 3; where T: 'x + A<B='y+C+D>;[M];A::f ); }
/// Used to verify the server's authenticity to the client. pub fn stupid_hash(mut value: crate::data::EOThree) -> crate::data::EOThree { value += 1; 110905 + (value % 9 + 1) * ((11092004 - value) % ((value % 11 + 1) * 119)) * 119 + value % 2004 } mod packet_processor; pub use packet_processor::PacketProcessor...
use std::ops::{Add}; trait Animal { fn create(name: &'static str) -> Self; fn name(&self) -> &'static str; fn talk(&self) { println!("{} cannot talk", self.name()); } } struct Human { name: &'static str } struct Cat { name: &'static str } impl Animal for Human { fn create(name:...
// #![feature(trait_alias)] use async_std::io; use tide_validator::{HttpField, ValidatorMiddleware}; #[async_std::main] async fn main() -> io::Result<()> { let mut app = tide::new(); let mut validator_middleware = ValidatorMiddleware::new(); let is_number = |_field_name: &str, field_value: Option<&str>| { ...
mod filterload; mod getdata; pub mod inv; mod message_trait; mod ping; mod version; pub use filterload::*; pub use getdata::*; pub use inv::InvMessage; pub use message_trait::*; pub use ping::*; pub use version::*;
mod db; pub use db::Rocksdb;
pub fn hamming_distance(strand1: &str, strand2: &str) -> Result<u32, &'static str> { if strand1.len() != strand2.len() { return Result::Err("Lenth of strands not equal!") } let strand1_bases = strand1.chars(); let strand2_bases = strand2.chars(); let base_pairs = strand1_bases.zip(strand2...
// Copyright (c) 2019 Alain Brenzikofer // // 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...
mod test; const fn roman_lut(numeral: &char) -> Option<usize> { match numeral { 'I' => Some(1), 'V' => Some(5), 'X' => Some(10), 'L' => Some(50), 'C' => Some(100), 'D' => Some(500), 'M' => Some(1000), _ => None, } } const fn arabic_lut(digit: &us...
// use anyhow::Result; // pub fn find_matches(reader: impl std::io::BufRead, pattern: &str, mut writer: impl std::io::Write) -> Result<()> { // for line in reader.lines() { // if let Ok(l) = line { // if l.contains(pattern) { // writeln!(writer, "{}", l)?; // } // ...
#[cfg(test)] mod tests { use super::*; #[test] fn example() { assert_eq!("-6,-3-1,3-5,7-11,14,15,17-20", solution::range_extraction(&[-6,-3,-2,-1,0,1,3,4,5,7,8,9,10,11,14,15,17,18,19,20])); assert_eq!("-3--1,2,10,15,16,18-20", solution::range_extraction(&[-3,-2,-1,2,10,15,16,18,19,20])); ...
use oxygengine::prelude::*; use serde::{Deserialize, Serialize}; #[derive(Debug, Copy, Clone)] pub enum LevelError { /// (provided, expected) CellsStringSizeDoesNotMatchSize(usize, usize), UnsupportedObjectCharacter(char), UnsupportedTileCharacter(char), } #[derive(Debug, Default, Clone, Serialize, De...
// Copyright lowRISC contributors. // Licensed under the Apache License, Version 2.0, see LICENSE for details. // SPDX-License-Identifier: Apache-2.0 #![deny(warnings)] #![deny(unused)] #![deny(unsafe_code)] use std::env; use std::fs; use std::path::Path; use rom_ext_config::parser::ParsedConfig; use rom_ext_image::...
// Copyright 2013 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 ...
extern crate nom; #[macro_use] extern crate enum_display_derive; pub mod ir; pub mod parser;
use expectest::prelude::be_equal_to; use sql::data_manager::DataManager; #[test] fn saves_to_one_row_table() { let data_manger = DataManager::default(); drop(data_manger.save_to("table_name", vec!["1".to_owned()])); expect!(data_manger.get_range_till_end("table_name", 0)) .to(be_equal_to(vec![ve...
/// An enum to represent all characters in the TaiTham block. #[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)] pub enum TaiTham { /// \u{1a20}: 'ᨠ' LetterHighKa, /// \u{1a21}: 'ᨡ' LetterHighKha, /// \u{1a22}: 'ᨢ' LetterHighKxa, /// \u{1a23}: 'ᨣ' LetterLowKa, /// \u{1a24}: 'ᨤ' ...
pub use num::rational::Ratio; use conv::{ValueFrom, ApproxFrom, ValueInto, ApproxInto}; use num::integer::Integer; /// A trait defining how an integer can be scaled by ratios of various types. /// `T` is the type of the ratio, `I` is the intermediate promotion type. /// E.g., to correctly scale i8 by Ratio<u32>, we wo...
extern crate nix; #[cfg(feature = "signalfd")] use nix::sys::signalfd::SignalFd; #[cfg(feature = "signalfd")] use nix::sys::signal; #[cfg(feature = "signalfd")] use nix::unistd; #[cfg(feature = "signalfd")] fn main() { print!("test test_signalfd ... "); let mut mask = signal::SigSet::empty(); mask.add(si...
pub fn lsp(series: &str, num: usize) -> Result<u32, &str> { if num > series.len() { return Result::Err("Span longer than length of digit series") } if num == 0 { return Result::Ok(1); } if !series.chars().all(|ch| ch.is_digit(10)) { return Result::Err("Non-digit cha...
use tendermint::abci; use tendermint::rpc::endpoint::abci_query::AbciQuery; use relayer_modules::Height; use crate::chain::Chain; use crate::error; pub mod client_consensus_state; /// The type of IBC response sent back for a given IBC `Query`. pub trait IbcResponse<Query>: Sized { /// The type of the raw respon...
use preexplorer::prelude::*; fn main() -> anyhow::Result<()> { let domain = (1..15).map(|i| (i as f64).sqrt()); let image: Vec<Vec<f64>> = (1..15) .map(|i| { (0..10) .map(|j| { let j = j as f64; let i = i as f64; //...
#[doc = "Register `FMC_SR` reader"] pub type R = crate::R<FMC_SR_SPEC>; #[doc = "Field `ISOST` reader - ISOST"] pub type ISOST_R = crate::FieldReader; #[doc = "Field `PEF` reader - PEF"] pub type PEF_R = crate::BitReader; #[doc = "Field `NWRF` reader - NWRF"] pub type NWRF_R = crate::BitReader; impl R { #[doc = "Bi...
#[macro_use] extern crate clap; use bellman::groth16; use bls12_381::{Bls12, Scalar}; use std::collections::{HashMap, HashSet}; pub mod async_serial; pub mod bls_extensions; pub mod circuit; pub mod crypto; pub mod endian; pub mod error; pub mod gfx; pub mod gui; pub mod net; pub mod rpc; pub mod serial; pub mod servi...
use std::ops::{Deref, DerefMut}; use std::sync::{Mutex, MutexGuard, RwLock, RwLockReadGuard, RwLockWriteGuard}; // Lock Shenanigans pub struct RwLockOption<T> { lock: RwLock<Option<T>> } impl<T> RwLockOption<T> { pub fn new() -> Self { RwLockOption{lock: RwLock::new(None)} } pub fn read<'a>(&'...
use std::cmp::min; use std::io::{BufWriter, stdin, stdout, Write}; #[derive(Default)] struct Scanner { buffer: Vec<String> } impl Scanner { fn next<T: std::str::FromStr>(&mut self) -> T { loop { if let Some(token) = self.buffer.pop() { return token.parse().ok().expect("Fail...
#[cfg(any(target_os = "ios", target_os = "android", target_os = "emscripten"))] #[macro_use] extern crate log; #[cfg(any(target_os = "ios", target_os = "android", target_os = "emscripten"))] extern crate android_log; pub use common; use noise::{NoiseFn, Perlin, Seedable}; pub use rand; use rand::prelude::*; use specs:...
pub mod colag; extern crate rand; use std::time::{SystemTime, Duration}; use std::mem; use std::fmt; use std::collections::{HashSet}; use std::thread; use std::sync::Arc; use rand::Rng; use rand::distributions::{Range, Sample}; use colag::{Domain, NUM_PARAMS}; const COLAG_TSV: &'static str = "./COLAG_2011_ids.txt"...
use super::TemplateProviderError; use crate::service::template::manager::{TemplateManager, TemplateManagerError}; use crate::service::template::template::Template; use async_trait::async_trait; use serde::Deserialize; use serde_json::Value as JsonValue; use std::fs::{read_to_string, File}; use std::io::BufReader; use s...
use std::path; use friday_error::{FridayError, frierr}; use friday_logging; use wav; use std::fs::File; use std::fs; #[derive(Clone)] pub struct Files { root: path::PathBuf } impl Files { pub fn new(root: path::PathBuf) -> Result<Files, FridayError> { if root.is_dir() { Ok(Files { ...
pub(crate) mod generate; #[proc_macro] pub fn rspg(input: proc_macro::TokenStream) -> proc_macro::TokenStream { generate::generate(input.into()) .unwrap_or_else(|err| err.to_compile_error()) .into() }
use std::cell::Cell; fn main() { let c=Cell::new(10); c=4; //c.set(20); println!("{}",c.get()); }
use std::collections::HashMap; use super::super::gc::GcObject; use super::value::{Value, Object}; pub struct Scope { parent: Option<GcObject<Scope>>, defines: HashMap<String, Box<Object>>, } impl Scope { #[inline(always)] pub fn new(parent: Option<GcObject<Scope>>) -> Self { Scope { ...
use std::iter; use syn::{Ident, DeriveInput, Data, DataStruct, Fields}; use quote::Tokens; use accepts; use composites::Field; use enums::Variant; use overrides::Overrides; pub fn expand_derive_tosql(input: DeriveInput) -> Result<Tokens, String> { let overrides = Overrides::extract(&input.attrs)?; let name =...
#[cfg(feature = "windows")] macro_rules! target { () => { "windows" }; } #[cfg(feature = "macos")] macro_rules! target { () => { "macos" }; } #[cfg(feature = "prefix")] macro_rules! target { () => { "prefix" }; } macro_rules! title { () => { concat!( ...
use proconio::input; fn main() { input! { n: i64, k: i64, } let mut a = n; for _ in 1..=k { a = f(a); } println!("{}", a); } fn f(x: i64) -> i64 { g1(x) - g2(x) } fn g1(x: i64) -> i64 { let mut s: Vec<_> = format!("{}", x).chars().collect(); s.sort(); ...
use super::component::*; use crate::system::WriteComp; pub trait EntityCommon: PartialEq + Eq{ fn add<'e, 'd: 'e, T: Component>(&'e self, storage: &'e mut WriteComp<'d, T>, comp: T) -> &'e Self; fn remove<'e, 'd: 'e, T: Component>(&'e self, storage: &'e mut WriteComp<'d, T>) -> &'e Self; }
//! copyright (c) 2020 by shaipe //! mod timer; use timer::Timer; fn main() { let mut t = Timer::new(); t.start(|x, interval|{ println!("{:?} -- {:?}", x, interval); }); }
extern crate slack; use date; use reply::CHANNEL; static mut day: &'static str = ""; pub fn send_mention(cli: &mut slack::RtmClient) { let today_string = date::get_day_of_week(); let today = match today_string.as_str() { "Mon" => "月", "Tue" => "火", "Wed" => "水", "Thu" => "木", ...
#![recursion_limit="1024"] extern crate common; extern crate proc_macro; extern crate proc_macro2; extern crate syn; extern crate quote; use common::{StorageType}; use proc_macro::{TokenStream}; use proc_macro2::{Span}; use syn::{Data, DeriveInput, Ident, Meta, parse_macro_input}; use quote::quote; #[allow(non_snake...