text
stringlengths
8
4.13M
use super::*; /////////////////////////////////////////////////////////////////// //param_type_test /////////////////////////////////////////////////////////////////// use super::param_type::*; #[test] fn test_parse_param_type_success() -> Result<(), Error> { let tests = vec![ (Bytes::from_static(&[0x0, 0...
use crate::bot::constants::*; use crate::bot::room::*; use crate::telegram::helpers::*; use crate::telegram::messages::send_message; use crate::ternary; use redis::Commands; use reqwest::Client; use serde::{Deserialize, Serialize}; pub struct TgMethods; impl TgMethods { pub const GET_UPDATES: &'static str = "getU...
use crate::renderer::Renderer; type Point = (i32, i32); pub struct Ink { pub id: usize, pub points: Vec<Point>, } impl Ink { pub fn new(id: usize) -> Self { Self { id, points: Vec::new() } } pub fn add_point(&mut self, point: Point) { self.points...
// #[cfg(all( // any(target_arch = "x86", target_arch = "x86_64"), // all(target_feature = "aes", target_feature = "sse2") // ))] // #[path = "./x86.rs"] // mod platform; // // NOTE: // // Crypto: AES + PMULL + SHA1 + SHA2 // // https://github.com/rust-lang/stdarch/blob/master/crates/std_detect/src/d...
/// LeetCode Monthly Challenge problem for March 24th, 2021. pub struct Solution {} impl Solution { /// Given two arrays A and B of equal size, the advantage of A with respect /// to B is the number of indices i for which A[i] > B[i]. /// /// Returns a permutation of A that maximizes its advantage wit...
extern crate curl; extern crate dmbc; extern crate exonum; extern crate rand; extern crate serde; extern crate serde_json; #[macro_use] extern crate log; extern crate env_logger; use dmbc::currency::assets::AssetId; use dmbc::currency::wallet::Wallet as EvoWallet; //use dmbc::service::builders::fee; //use dmbc::servic...
use rand::Rng; #[derive(Debug, Clone)] pub struct Vec3 { pub x: f64, pub y: f64, pub z: f64, } impl std::ops::Neg for Vec3 { type Output = Self; fn neg(self) -> Self { Self { x: -self.x, y: -self.y, z: -self.z, } } } impl std::ops::Add for...
use std::fs::File; use std::io::ErrorKind; use std::io; use std::io::Read; fn main() { handle_error1(); let result = read_username_from_file(); println!("{:?}",result); let res2 = simple_read_username_from_file(); let d = res2.unwrap(); println!("{:?}",d); let res3 = return_all_type_error()...
use crate::location::{Location,Span,Positioned}; use crate::ast::{ Statement, Statements, Directive, ByteValue, IncludeType, ArgType, MacroDefinition, MacroStatement, SpriteType, MacroIdentifier }; use crate::lexer::{Token,TokenType,LexerError}; use crate::lexer; use crate::expressi...
use channel; use endpoint; use failure::Error; use futures::sync::mpsc; use futures::{self, Future, Sink, Stream}; use futurize; use gcmap::{HashMap, MarkOnDrop}; use headers::Headers; use identity; use proto; use ptrmap; use std::net::SocketAddr; use tokio; use xlog; macro_rules! wrk_try { ($self:ident, $x:expr) ...
#[macro_use] extern crate puruda; extern crate peroxide; use puruda::*; use peroxide::fuga::*; use std::error::Error; use std::fs::{rename, read_dir}; //use std::io::{BufRead, BufReader}; use std::process::Command; fn main() -> Result<(), Box<dyn Error>> { //let link = File::open("link.txt")?; //let reader = ...
use crate::processor_module::ProcessorModule; pub struct SmoothingModule { alpha: f32, previous_output: Option<Vec<f32>>, } impl SmoothingModule { pub fn new(alpha: f32) -> Self { Self { alpha: alpha, previous_output: None, } } } impl ProcessorModule for Smooth...
use itertools::Itertools; static FILE: &str = include_str!("../inputs/13.txt"); #[derive(Clone, Copy, Debug)] struct Bus { id: usize, ttl: usize, } lazy_static! { static ref LINES: (&'static str, &'static str) = FILE.split_once('\n').unwrap(); static ref TIMESTAMP: usize = LINES.0.parse().unwrap(); ...
use super::ParseContext; use crate::ast::{ Expression, JsonValue, comma::CommaExpression, json_object::JsonObjectExpression, property_assignment::PropertyAssignmentExpression, }; use crate::tokens::Token; use super::errors::UnexpectedTokenError; use crate::parsing::{ParseResult, parse}; use crate::a...
fn main() { let _ = 12; print!("{}", _); }
use super::*; pub fn do_rename(oldpath: &str, newpath: &str) -> Result<()> { println!("rename: oldpath: {:?}, newpath: {:?}", oldpath, newpath); let current = current!(); let fs = current.fs().lock().unwrap(); let (old_dir_path, old_file_name) = split_path(&oldpath); let (new_dir_path, new_file_n...
use alloc::vec::Vec; use keccak::KeccakF1600; use util::Hash; pub struct Shake128(KeccakF1600); impl Shake128 { pub fn new(n: usize) -> Self { Self(KeccakF1600::new(1344, 256, n)) } } impl Default for Shake128 { fn default() -> Self { Self::new(128 / 8) } } impl Hash for Shake128 { ...
use chrono::NaiveDateTime; use diesel::prelude::*; use diesel::pg::PgConnection; use schema::horus_images; use models::traits::passwordable; #[derive(AsChangeset, Queryable, Serialize, Identifiable, Insertable)] #[table_name = "horus_images"] pub struct HImage { pub id: String, pub title: Option<String>, ...
use cosmwasm_std::{ log, to_binary, Api, CanonicalAddr, Coin, CosmosMsg, Decimal, Env, Extern, HandleResponse, HandleResult, HumanAddr, LogAttribute, Querier, StdError, StdResult, Storage, Uint128, WasmMsg, }; use crate::{ bond::deposit_farm_share, state::{read_config, state_store}, }; use crate::quer...
use std::collections::HashMap; fn main() { let mut v: Vec<i32> = Vec::new(); // Vec new macro vec! and auto infer (default i32 type v.push(5); v.push(6); v.push(7); let v = vec![1, 2, 3, 4]; let third: &i32 = &v[2]; println!("The third element is {}", third); // v.get(index) reurn...
//! PoT gossip functionality. use crate::state_manager::PotProtocolState; use futures::{FutureExt, StreamExt}; use parity_scale_codec::Decode; use parking_lot::{Mutex, RwLock}; use sc_network::config::NonDefaultSetConfig; use sc_network::PeerId; use sc_network_gossip::{ GossipEngine, MessageIntent, Syncing as Goss...
use crate::hardware::{Cpu, Flag, RegU16, RegU8}; use crate::memory::Memory; use std::fmt; mod instruct_fn; pub struct Instruct { pub opcode: u8, pub inst: InstructType, pub desc: String, pub ticks: u8, } pub enum InstructType { Load(RegU8, RegU8), // Source, destination LoadPlus(Reg...
use crate::days::day20::{Picture, parse_input, default_input, compute_borders}; use std::collections::HashMap; pub fn run() { println!("{}", picture_str(default_input()).unwrap()) } pub fn picture_str(input : &str) -> Result<i64, ()> { picture(parse_input(input)) } pub fn picture(pictures : HashMap<i64, Pict...
use ::comfy_table::*; use ::crossterm::style::style; use ::std::collections::BTreeMap; use ::pueue::state::State; use ::pueue::task::Task; pub fn has_special_columns(tasks: &BTreeMap<usize, Task>) -> (bool, bool) { // Check whether there are any delayed tasks. // In case there are, we need to add another colu...
use anyhow::Result; use rusoto_core::Region; use rusoto_s3::{ListObjectsV2Request, Object, S3Client, S3}; use structopt::StructOpt; use tokio; #[derive(StructOpt, Debug)] #[structopt(name = "s3_list_objects")] struct Options { #[structopt(short, long)] bucket: String, } impl Options { fn create_initial_re...
pub trait Deque { type Elem; fn is_empty(&self) -> bool; fn push_front(&mut self, elem: Self::Elem); fn pop_front(&mut self) -> Option<Self::Elem>; fn push_back(&mut self, elem: Self::Elem); fn pop_back(&mut self) -> Option<Self::Elem>; } pub fn is_empty<T: Deque>(q: &T) -> bool { Deque::i...
use crate::constant::ConstantRef; #[cfg(feature = "llvm-9-or-greater")] use crate::debugloc::*; use crate::function::{Function, FunctionAttribute, FunctionDeclaration, GroupID}; use crate::llvm_sys::*; use crate::name::Name; use crate::types::{FPType, Type, TypeRef, Typed, Types, TypesBuilder}; use std::collections::{B...
use quote::{quote_spanned, ToTokens}; use super::{ DelayType, FlowProperties, FlowPropertyVal, OperatorCategory, OperatorConstraints, OperatorWriteOutput, Persistence, WriteContextArgs, RANGE_1, }; use crate::graph::{OpInstGenerics, OperatorInstance}; /// > 1 input stream of type `(K, V1)`, 1 output stream of...
// Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution. // // 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 http://opensource.org/licenses/MIT>,...
use env_logger; use log::LevelFilter; use num_derive::FromPrimitive; // For converting intcode into enums use num_traits::FromPrimitive; use std::cell::Cell; // For multiple mutable references // For converting intcode into enumss #[derive(Clone, Copy, PartialEq)] pub enum Status { WaitForInput, NewOutput, Halt, }...
//use crate::endpoint; //use crate::file::model::RequestParameters; // //// なぜかファイルが見つからない //// TODO: ↑を直す //pub async fn get(query: &RequestParameters) -> Result<bytes::Bytes, Box<dyn //std::error::Error>> { // let client = reqwest::Client::new(); // // let resp = client.get(endpoint::FILE).query(query).send().a...
use actix_web::{web, get, post, HttpRequest, HttpResponse, Responder}; use serde::{Serialize, Deserialize}; #[derive(Debug, Serialize)] struct TrackInfo { title: String, author: String, length: u64, identifier: String, #[serde(rename = "isStream")] is_stream: bool, #[serde(rename = "isSeeka...
use hlist_macro::{HNil, HCons}; use error::*; use lua::*; impl<'lua> ToLuaMulti<'lua> for () { fn to_lua_multi(self, _: &'lua Lua) -> LuaResult<LuaMultiValue> { Ok(LuaMultiValue::new()) } } impl<'lua> FromLuaMulti<'lua> for () { fn from_lua_multi(_: LuaMultiValue, _: &'lua Lua) -> LuaResult<Self>...
use crate::{ cell::{Cell, HAlign, VAlign, DEFAULT_BLANK_CHAR, DEFAULT_H_ALIGN, DEFAULT_V_ALIGN}, options::Options, }; use std::borrow::Cow; /// Data type for creating a [`Row`] for the grid. /// /// [`Row`]: struct.Row.html pub struct Row { /// These options will be used if the equivalent is not provided ...
#[allow(dead_code)] #[allow(unused_variables)] struct Node { left: Link, right: Link, value: i32, } type Link = Option<Box<Node>>; #[allow(dead_code)] #[allow(unused_variables)] impl Node { fn valid(&self) -> bool { let left = match self.left { Some(ref left_node) => { ...
use warp::{Rejection, Reply}; use crate::{Database, User}; pub async fn list_users_handler(db: Database) -> Result<impl Reply, Rejection> { let db = db.lock().await; let users = db .clone() .into_iter() .map(|(_, v)| v) .collect::<Vec<User>>(); Ok(warp::reply::json(&users))...
/*! * Function of PortMidi Time. */ extern crate time; use std::io::timer; use std::time::duration; use std::comm; use std::comm::{channel, Sender, Receiver}; pub enum PtError { PtNoError = 0, /* success */ PtHostError = -10000, /* a system-specific error occurred */ PtAlreadyStarted, /* can...
//! Tests auto-converted from "sass-spec/spec/core_functions/color/hwb/error" #[allow(unused)] use super::rsass; // From "sass-spec/spec/core_functions/color/hwb/error/five_args.hrx" // Ignoring "five_args", error tests are not supported yet. // From "sass-spec/spec/core_functions/color/hwb/error/four_args.hrx" mod ...
use jsonrpc_core::{self, IoHandler, Params}; use jsonrpc_http_server::*; use jsonrpc_macros::Trailing; use serde::Serialize; use serde::de::DeserializeOwned; use serde_json::{self, Value}; use bigint::{U256, H256, M256, H2048, H64, Address, Gas}; use std::net::SocketAddr; use std::sync::{Arc, Mutex}; use std::sync::mp...
/// Find all prime numbers less than `n`. /// For example, `sieve(7)` should return `[2, 3, 5]`. pub fn sieve(n: u32) -> Vec<u32> { let mut is_prime: Vec<bool> = vec![true; n as usize]; let mut res: Vec<u32> = Vec::new(); for i in 2..n { if is_prime[i as usize] { let mut j = i + i; ...
/*! ```rudra-poc [target] crate = "array-tools" version = "0.2.10" [test] cargo_toolchain = "nightly" [report] issue_url = "https://github.com/L117/array-tools/issues/2" issue_date = 2020-12-31 rustsec_url = "https://github.com/RustSec/advisory-db/pull/665" rustsec_id = "RUSTSEC-2020-0132" [[bugs]] analyzer = "Unsaf...
extern crate mammut; extern crate toml; extern crate webbrowser; use std::io::prelude::*; use std::{error::Error, fs, io}; use self::mammut::{ apps::{AppBuilder, Scopes}, Mastodon, Registration, }; #[allow(dead_code)] fn main() -> Result<(), Box<Error>> { register()?; Ok(()) } #[allow(dead_code)] pu...
#![feature(slice_patterns)] use std::env::args; use std::error::Error; use std::fs::File; use std::io::{BufRead, BufReader}; use std::process::exit; use std::thread::sleep; use std::time::Duration; fn loop_impl( prev_idle: u64, prev_total: u64, ) -> Result<(u64, u64), Box<Error>> { let file = File::open("...
use xml::Element; use ::{Author, Category, Contributor, ElementUtils, Feed, Link, NS, Person, ViaXml}; /// [The Atom Syndication Format § The "atom:entry" Element] /// (https://tools.ietf.org/html/rfc4287#section-4.1.2) /// /// # Examples /// /// ``` /// use atom_syndication::Entry; /// /// let entry = Entry { /// ...
use std::process::{Command, Stdio}; use std::fs::OpenOptions; fn main() { let mut file = OpenOptions::new() .truncate(true) .write(true) .create(true) .open("foo.txt") .unwrap(); Command::new("ls") .args(&["-l", "-a"]) .stdout(file) ...
extern crate noise; use self::noise::*; pub struct RandomGenerator { fbm: Perlin, } impl RandomGenerator { pub fn new(seed: usize) -> Self { let r = RandomGenerator { fbm: Perlin::new() }; r.fbm.set_seed(seed); r } pub fn next(&self, point: &[f64]) -> f64 { let mut vs...
#[doc = "Reader of register CM0_CA_STATUS0"] pub type R = crate::R<u32, super::CM0_CA_STATUS0>; #[doc = "Reader of field `VALID16`"] pub type VALID16_R = crate::R<u16, u16>; impl R { #[doc = "Bits 0:15 - Sixteen valid bits of the cache line specified by CM0_CA_CTL.WAY and CM0_CA_CTL.SET_ADDR."] #[inline(always)...
#[doc = "Reader of register CMD"] pub type R = crate::R<u32, super::CMD>; #[doc = "Writer for register CMD"] pub type W = crate::W<u32, super::CMD>; #[doc = "Register CMD `reset()`'s with value 0"] impl crate::ResetValue for super::CMD { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { ...
//! 32-bits Memory arena for types implementing `Copy`. //! This Memory arena has been implemented to fit the use of tantivy's indexer //! and has *twisted specifications*. //! //! - It works on stable rust. //! - One can get an accurate figure of the memory usage of the arena. //! - Allocation are very cheap. //! - Al...
use std::collections::HashSet; use std::io::{self}; fn game_of_life(mut lights: Vec<Vec<bool>>, steps: usize, keep_corners: bool) -> usize { let neighbours: Vec<(i32, i32)> = vec![ (-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1), ...
use crate::http; use serde::{self, Deserialize}; #[derive(Debug, Deserialize)] pub struct Krate { pub max_version: String, } #[derive(Debug, Deserialize)] pub struct KrateResponse { #[serde(rename = "crate")] pub krate: Krate, } impl Krate { pub fn new(name: &str) -> Result<Krate, failure::Error> { ...
/// An enum to represent all characters in the ArabicPresentationFormsB block. #[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)] pub enum ArabicPresentationFormsB { /// \u{fe70}: 'ﹰ' ArabicFathatanIsolatedForm, /// \u{fe71}: 'ﹱ' ArabicTatweelWithFathatanAbove, /// \u{fe72}: 'ﹲ' ArabicDammatanI...
/// This is just a placeholder for the payload of types. You only need this if you implement /// your own type. /// /// If you use your own bin data, make sure: /// * The size must be exactly 3 words (3 * usize). /// * The struct must be word-aligned (usize-aligned). #[repr(C)] #[derive(Clone, Copy)] pub struct BinDa...
#[macro_export] macro_rules! map ( ( $($key:expr => $value:expr),+ ) => { { let mut m = ::std::collections::HashMap::new(); $( m.insert($key, $value); )+ m } }; () => { { ::std::collections::HashMap::new() ...
#[allow(dead_code)] #[derive(Clone, Copy)] struct Book { // `&'static str` is a reference to a string allocated in ro memory author: &'static str, title: &'static str, year: u32, } fn borrow_book(book: &Book) { println!("I immutably borrowed {} by {} - {} edition", book.title, book.author, book....
// BSD 2-Clause License // Copyright (c) 2019, Dimitris Spyropoulos // All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // 1. Redistributions of source code must retain the above copyright notice,...
// Copyright 2021 MaidSafe.net limited. // // This SAFE Network Software is licensed to you under The General Public License (GPL), version 3. // Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed // under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTI...
use xml::Element; use ::{ElementUtils, NS, ViaXml}; /// [The Atom Syndication Format § The "atom:link" Element] /// (https://tools.ietf.org/html/rfc4287#section-4.2.7) #[derive(Default)] pub struct Link { pub href: String, pub rel: Option<String>, pub mediatype: Option<String>, pub hreflang: Option<S...
#[doc = "Reader of register GPIOx_AFRL"] pub type R = crate::R<u32, super::GPIOX_AFRL>; #[doc = "Writer for register GPIOx_AFRL"] pub type W = crate::W<u32, super::GPIOX_AFRL>; #[doc = "Register GPIOx_AFRL `reset()`'s with value 0"] impl crate::ResetValue for super::GPIOX_AFRL { type Type = u32; #[inline(always...
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT license. */ #[cfg(target_os = "windows")] #[link(name = "kernel32")] extern "system" { fn OpenProcess(dwDesiredAccess: u32, bInheritHandle: bool, dwProcessId: u32) -> usize; fn QueryProcessCycleTime(hProcess: usize, lpCyc...
/*! ```rudra-poc [target] crate = "adtensor" version = "0.0.3" [[target.peer]] crate = "typenum" version = "1.12.0" [[target.peer]] crate = "generic-array" version = "0.14.4" [report] issue_url = "https://github.com/charles-r-earp/adtensor/issues/4" issue_date = 2021-01-11 rustsec_url = "https://github.com/RustSec/a...
use std::convert::TryInto; use std::fmt::{self, Debug, Formatter}; use aes::{ cipher::{ generic_array::{typenum::UTerm, GenericArray}, NewBlockCipher, }, Aes256, }; use block_modes::{block_padding::Pkcs7, BlockMode, Ecb}; use hmac::{Hmac, Mac, NewMac}; use sha3::Sha3_256; type U8Array<Size...
use super::{ shared::{mask_64, vector_256}, *, }; use crate::{ block, classification::mask::m64, debug, input::{InputBlock, InputBlockIterator}, FallibleIterator, }; use std::marker::PhantomData; super::shared::quote_classifier!(Avx2QuoteClassifier64, BlockAvx2Classifier, 64, u64); struct ...
use itertools::Itertools; pub type Locus = u8; // each allele had a particular locus is represented as an integer pub type Gamete = Vec<Locus>; pub type Chromosome = Vec<Gamete>; // a haploid organism has a single gamete per chromosome, a diploid organism has two gametes per chromosome, and so forth pub type Individua...
extern crate failure; extern crate romhack_backend; use failure::Error; use romhack_backend::{ build_iso, iso::writer::write_iso, open_config_from_patch, KeyValPrint, MessageKind, }; use std::alloc::{alloc as allocate, dealloc as deallocate, Layout}; use std::io::{self, BufWriter, Cursor, SeekFrom, Write}; use std...
fn main() { // enumerable kinds enum IpAddrKind { V4, V6, } let four = IpAddrKind::V4; let six = IpAddrKind::V6; fn route(ip_type: IpAddrKind) {} route(four); route(six); // structs of kind struct IpAddr_ { kind: IpAddrKind, address: String, ...
use anyhow::Result; use tui::style::{Color, Style}; use tui::widgets::{Block, Borders, Paragraph}; #[derive(Clone, PartialEq)] pub enum Mode { Normal, Insert, } pub struct TextField { current_value: String, mode: Mode, } impl Default for TextField { fn default() -> Self { Self { ...
use crate::{ embeds::{Author, Footer}, util::{constants::SYMBOLS, datetime::how_long_ago_text}, }; use chrono::{DateTime, Utc}; use std::fmt::Write; pub struct CommandCounterEmbed { description: String, footer: Footer, author: Author, } impl CommandCounterEmbed { pub fn new( list: Vec...
use { crate::{ error::Error, extractor::Extractor, future::{Poll, TryFuture}, generic::Tuple, input::param::Params, input::Input, }, std::marker::PhantomData, }; #[doc(hidden)] pub use tsukuyomi_macros::path_impl; pub trait Path { type Output: Tuple; ...
use std::collections::HashMap; const INPUT: &str = include_str!("../inputs/day_2_input"); pub fn solve() { let lines = INPUT.split_whitespace(); let mut pairs = 0; let mut triplets = 0; for line in lines { let mut hashmap = HashMap::new(); for char in line.chars() { let c...
#![feature(unboxed_closures)] extern crate script; use script::{require, logger, mkdir, require_env, copy, assert, as_str, abs_path, export}; pub fn main() { // Setup let mut logger = logger(); logger.clear(); logger.info(format!("building ruv")); // Build build(); logger.info(format!("Success!")); }...
#[doc = "Reader of register ETH_MACTxQPMR"] pub type R = crate::R<u32, super::ETH_MACTXQPMR>; #[doc = "Reader of field `PSTQ0`"] pub type PSTQ0_R = crate::R<u8, u8>; #[doc = "Reader of field `PSTQ1`"] pub type PSTQ1_R = crate::R<u8, u8>; impl R { #[doc = "Bits 0:7 - PSTQ0"] #[inline(always)] pub fn pstq0(&s...
// contains a reimplementation of Rust lang items and intrinsics // used inside Quasar pub mod intrinsics { extern "rust-intrinsic" { pub fn copy_nonoverlapping_memory<T>(src: *mut T, dst: *const T, count: uint); pub fn transmute<T, U>(e: T) -> U; pub fn uninit<T>() -> T; } } mod kinds...
#![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 TemplateSpec { #[serde(flatten)] pub azure_resource_base: AzureResourceBase, pub location: String, ...
#![feature(core_intrinsics)] mod buffer_pool; mod protocol; mod server; use std::collections::HashMap; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::Arc; use std::time::{Duration, Instant}; use bytes::Bytes; use clap::{command, Parser, Subcommand}; use futures::Stream; use tokio::sync::mpsc::Unbound...
// Lex Tokens from an input source // Author: Sebastian Schüller <schueller@ti.uni-bonn.de> use token::*; use token::TokenKind::*; use SrcPos; #[derive(Debug, Clone)] pub struct ParseContext<'a> { pub txt: &'a str, pub line_offsets: Vec<usize>, } impl<'a> From<&'a str> for ParseContext<'a> { fn from(src...
extern crate rand; //use std::io; use std::cmp::Ordering; use rand::Rng; fn main() { println!("Guess the number!"); let mut guesses = 0; let mut high = 1000; let mut low = 1; let secret_number = rand::thread_rng().gen_range(low, high); loop { println!("Please guess a number from 1 t...
use super::relay::relay_connection; use crate::utils::make_error; use std::error::Error; use tokio::io::AsyncReadExt; use tokio::net::TcpStream; use crate::config::TunnelConfig; pub fn valid_tls_version(buf: &[u8]) -> bool { if buf.len() < 3 { return false; } //recordTypeHandshake if buf[0]...
// Non-convensional componentwise operators. use num::Signed; use alga::general::{ClosedMul, ClosedDiv}; use core::{Scalar, Matrix, OwnedMatrix, MatrixSum}; use core::dimension::Dim; use core::storage::{Storage, StorageMut}; use core::allocator::SameShapeAllocator; use core::constraint::{ShapeConstraint, SameNumberO...
use crate::error::Error; use bytes::{Bytes, BytesMut}; /////////////////////////////////////////////////////////////////// //payload_queue_test /////////////////////////////////////////////////////////////////// use super::payload_queue::*; use crate::chunk::chunk_payload_data::{ChunkPayloadData, PayloadProtocolIdenti...
pub mod containers; pub mod image_box; pub mod interactive; pub mod space_box; pub mod text_box; use crate::{ props::{Props, PropsDef}, widget::{ node::{WidgetNode, WidgetNodeDef}, FnWidget, }, }; use serde::{Deserialize, Serialize}; use std::{collections::HashMap, convert::TryFrom}; #[der...
use crate::grid::{Cell, CellValue, Grid, Section}; use std::rc::Rc; pub static mut DEBUG: bool = false; #[derive(Copy, Clone, Eq, PartialEq, Debug)] pub enum Uniqueness { Unique, NotUnique, } #[derive(Eq, PartialEq, Debug)] pub enum SolveStatus { Complete(Option<Uniqueness>), Unfinished, Invalid,...
use draw::{Brush, Path, StrokeParams, Transform}; use ui_sys::{self, uiDrawContext}; /// Drawing context, used to draw custom content on the screen. pub struct DrawContext { ui_draw_context: *mut uiDrawContext, } impl DrawContext { /// Create a Context from a ui_draw_context pointer. /// /// # Unsafet...
// content-type: application/octet-stream // status: 204 No Content // ratelimit-limit: 1200 // ratelimit-remaining: 771 // ratelimit-reset: 1415984218 use std::borrow::Cow; use std::fmt; use hyper::client::response::Response; use hyper::header; use response::NamedResponse; use response; #[derive(Deserialize)] pub ...
use super::decipher::*; use super::parse_url; use super::sanitize; use super::VideoUrl; use nom::types::CompleteStr; use reqwest; use serde_json::{self, Value}; use std::io::prelude::*; use std::process::{Command, Stdio}; named!( ytconfig<CompleteStr, CompleteStr>, do_parse!( take_until_and_consume!("...
#[macro_export] macro_rules! bind_params_sqlx_mysql { ( $query:expr, $params:expr ) => {{ let mut query = $query; for value in $params.iter() { query = match value { Value::Null => query.bind(None::<bool>), Value::Bool(v) => query.bind(v), ...
#[doc = "Register `IER2` reader"] pub type R = crate::R<IER2_SPEC>; #[doc = "Register `IER2` writer"] pub type W = crate::W<IER2_SPEC>; #[doc = "Field `TIM8IE` reader - TIM8IE"] pub type TIM8IE_R = crate::BitReader; #[doc = "Field `TIM8IE` writer - TIM8IE"] pub type TIM8IE_W<'a, REG, const O: u8> = crate::BitWriter<'a,...
#[macro_use] extern crate serde_derive; use tcod::console::*; use tcod::map::Map as FovMap; mod lib; use crate::lib::*; fn main() { let root = Root::initializer() .font("arial10x10.png", FontLayout::Tcod) .font_type(FontType::Greyscale) .size(SCREEN_WIDTH, SCREEN_HEIGHT) .title("...
use std::error::Error; mod members; fn main() -> Result<(), Box<Error>>{ let members_json = std::fs::File::open("members.json")?; let members : members::Members = serde_json::from_reader(members_json)?; println!("{:?}", &members); Ok(()) }
use crate::intcode::Computer; use std::iter::empty; use std::collections::HashMap; use std::ops::{AddAssign, Add}; use crate::day11::Heading::*; use std::cmp::{min, max}; use std::hint::unreachable_unchecked; #[aoc_generator(day11)] fn gen(input: &str) -> Vec<i64> { Computer::parse_mem(input) } #[derive(Copy, Clo...
use cached::proc_macro::cached; use cached::UnboundCache; use anyhow::*; fn parse_input(input: &str) -> Result<Vec<u64>> { input .lines() .map(|s| s.parse::<u64>().map_err(|e| e.into())) .collect::<Result<Vec<_>>>() } #[cached( type = "UnboundCache<String, u64>", create= "{ Unboun...
use crate::arguments::PgArgumentBuffer; use crate::types::decode::Decode; use crate::types::encode::{Encode, IsNull}; use crate::value::{PgValue, PgValueFormat}; use bigdecimal::BigDecimal; use rbdc::decimal::Decimal; use rbdc::Error; use std::str::FromStr; impl Encode for Decimal { fn encode(self, buf: &mut PgArg...
// This file is part of network-constants. It is subject to the license terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/network-constants/master/COPYRIGHT. No part of network-constants, including this file, may be copied, modified, pro...
use super::{ apis::alpha_vantage, clock, config, strategies, trading::{Account, Broker, PriceData}, }; const COMMISSION: f64 = 0.01; // TD Ameritrade's trade commission pub struct SimBroker { capital: f64, unsettled_cash: f64, settle_date: Option<clock::LocalDate>, } impl SimBroker { pub ...
mod components; pub use crate::components::{AndGate, wiring}; fn main() { let mut and_gate = AndGate::default(); and_gate.settle(); println!("Inputs: {}, {} Output: {}", and_gate.input1.lock().unwrap(), and_gate.input2.lock().unwrap(), and_gate.output.lock().unwrap()); wiring::set_high(&mut and_gate....
use anyhow::{anyhow, Context, Result}; use libheif_rs::HeifContext; use log::debug; use xml::{ attribute::OwnedAttribute, name::OwnedName, reader::{EventReader, XmlEvent}, }; use crate::heif; /// AppleDesktop XMP metadata attribute. #[derive(PartialEq, Eq, Debug)] pub enum AppleDesktop { /// H24 varia...
use std::fs::File; use std::io::Write; use std::path::PathBuf; pub fn write_bytes_to(dir: &PathBuf, file: &str, blob: &[u8]) -> std::io::Result<()> { let mut path = dir.clone(); path.push(file); let mut f = File::create(path.to_str().unwrap())?; f.write_all(blob)?; f.flush()?; Ok(()) } #[cfg(t...
extern crate pomodoro; use std::process; use structopt::StructOpt; fn main() { let config = pomodoro::PomodoroConfig::from_args(); if let Err(e) = pomodoro::run(config) { eprintln!("Application error: {}", e); process::exit(1); } }
mod magic; mod admin;
use crate::{ cost_model::{instruction_cycles, transferred_byte_cycles}, syscalls::{ Debugger, LoadCell, LoadCellData, LoadHeader, LoadInput, LoadScript, LoadScriptHash, LoadTx, LoadWitness, }, type_id::TypeIdSystemScript, DataLoader, ScriptError, }; use ckb_chain_spec::consensus::TYP...