text
stringlengths
8
4.13M
//! Private configuration settings example file. Will be copied into the correct location by the build script. pub const DB_URL: &'static str = "mysql://username:password@hoste.com/databasename"; pub const API_KEY: &'static str = "1111111111222222222333333333"; pub const DB_CREDENTIALS: &'static str = "mysql://user...
#[doc = "Register `MCR` reader"] pub type R = crate::R<MCR_SPEC>; #[doc = "Register `MCR` writer"] pub type W = crate::W<MCR_SPEC>; #[doc = "Field `CKPSC` reader - HRTIM Master Clock prescaler"] pub type CKPSC_R = crate::FieldReader; #[doc = "Field `CKPSC` writer - HRTIM Master Clock prescaler"] pub type CKPSC_W<'a, RE...
mod token; mod scanner; mod parser; mod interpreter; mod environment; use std::{env, sync::Mutex}; use std::process; use std::io; use std::fs; use std::sync::atomic::{AtomicBool, Ordering}; use interpreter::{Interpreter, RuntimeError}; use token::{Token, TokenType}; use scanner::Scanner; use parser::{ParseError, Pars...
//! Tests auto-converted from "sass-spec/spec/core_functions/math" #[allow(unused)] use super::rsass; // From "sass-spec/spec/core_functions/math/abs.hrx" mod abs { #[allow(unused)] use super::rsass; mod error { #[allow(unused)] use super::rsass; // Ignoring "too_few_args", error t...
use crate::crypto::hash::{Hashable, H256}; use crate::experiment::performance_counter::PayloadSize; use bincode::serialize; use std::cell::RefCell; use std::hash::Hash; /// A unique identifier of a transaction output, a.k.a. a coin. #[derive(Serialize, Deserialize, Debug, Copy, Clone, PartialEq, Eq, Hash)] pub struct...
use std::io::Read; // 析构函数 // 所谓“析构函数”(destructor)是与“构造函数”(constructor)相对应的概念。 // “构造函数”是对象被创建的时候调用的函数。 // “析构函数”是对象被销毁的时候调用的函数。 // Rust 中没有统一的“构造函数”这个语法,对象的构造是直接对每个成员进行初始化完成的, // 一般将对象的创建封装到普通静态函数中。 // 相对于构造函数,析构函数有更重要的作用。 // 它会在对象消亡之前由编译器自动调用,特别适合承担对象销毁时释放所拥有资源的作用。 // 比如, // Vec 类型在使用的过程中,会根据情况动态申请内存,当变量的生命周期结束时,就会触...
#![allow(overflowing_literals)] use super::decoder::*; use super::*; pub mod rtype; pub mod stype; pub mod itype; pub mod ujtype; pub mod utype; pub mod sbtype; #[cfg(test)] mod implementer_test; pub fn handle_fence(_regfile: &mut [u32], bytes: &[u8], _pc: &mut u32) -> Result<(), ExecutionError> { let opcode = ...
use itertools::Itertools; use kurbo::{ BezPath, Line, ParamCurve, ParamCurveArclen, ParamCurveNearest, PathSeg, Point, Shape, }; pub trait BezPathExt { fn divide_at_intersections( &self, other: &BezPath, ) -> (Vec<BezPath>, Vec<Point>); fn divide_between_intersections( &self...
extern crate slackbot; extern crate bearbot; extern crate regex; extern crate dotenv; extern crate iron; use slackbot::{SlackBot, Sender}; use bearbot::handlers; use dotenv::dotenv; use std::env; use std::thread; use iron::prelude::*; use iron::status; fn main() { dotenv().ok(); let username = env::var("US...
pub use {Deserialize, Removed, ReprC, Serialize, WithSchema, Serializer, Deserializer, Introspect, introspect_item, IntrospectItem, SavefileError, load, save, load_noschema, save_noschema, Introspector, IntrospectionResult,IntrospectorNavCommand,IntrospectedElementKey, Schema, SchemaStruct, SchemaPrimitive, Sc...
use crate::validator::config::Config; use crate::validator::Validator; use clap::{App, Arg, ArgMatches, SubCommand}; use dotenv; use log::{error, trace}; use std::process; use toml; mod validator; fn main() { // load environment variables from .env file if dotenv::dotenv().is_err() { eprint!("failed t...
#[doc = "Register `ECCR` reader"] pub type R = crate::R<ECCR_SPEC>; #[doc = "Register `ECCR` writer"] pub type W = crate::W<ECCR_SPEC>; #[doc = "Field `ADDR_ECC` reader - ECC fail address"] pub type ADDR_ECC_R = crate::FieldReader<u32>; #[doc = "Field `BK_ECC` reader - ECC fail bank"] pub type BK_ECC_R = crate::BitRead...
use crate::custom_types::exceptions::{index_error, value_error}; use crate::custom_var::{downcast_var, CustomVar}; use crate::int_var::IntVar; use crate::looping::{self, TypicalIterator}; use crate::method::{NativeMethod, StdMethod}; use crate::name::Name; use crate::operator::Operator; use crate::runtime::Runtime; use...
extern crate rayon; use rayon::prelude::*; use super::{Chunk, Chunks}; use crate::internal_data_structure::raw_bit_vector::RawBitVector; impl super::Chunks { /// Constructor. pub fn new(rbv: &RawBitVector) -> Chunks { let n = rbv.len(); let chunk_size: u16 = Chunks::calc_chunk_size(n); ...
fn main() { let arr = [1, 2, 3]; let bb = bbQQ(); println!("{}", arr[2]); println!("{}", bb); } fn bbQQ() -> i32 { // warning help: convert the identifier to snake case: `bb_qq` 303 }
use super::ValueDef; use crate::{qjs, Map}; use serde::{Deserialize, Serialize}; use std::{ fmt, fmt::{Display, Formatter, Result as FmtResult}, }; #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, qjs::IntoJs, qjs::FromJs)] #[serde(untagged, rename_all = "lowercase")] #[quickjs(untagged, rename_all = ...
use futures::{Future, Stream}; use netlink_packet_core::{ header::flags::{NLM_F_ACK, NLM_F_CREATE, NLM_F_EXCL, NLM_F_REQUEST}, NetlinkFlags, NetlinkMessage, NetlinkPayload, }; use netlink_packet_route::RtnlMessage; use super::AddressHandle; use crate::{Error, ErrorKind, Handle}; lazy_static! { // Flags f...
// Copyright 2015 The GeoRust Developers // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed...
use super::TokenCredential; use azure_core::TokenResponse; use chrono::{DateTime, TimeZone, Utc}; use oauth2::AccessToken; use serde::{ de::{self, Deserializer}, Deserialize, }; use std::str; use url::Url; const MSI_ENDPOINT_ENV_KEY: &str = "IDENTITY_ENDPOINT"; const MSI_SECRET_ENV_KEY: &str = "IDENTITY_HEADER...
use proconio::{input, marker::*}; use std::*; fn main() { input! { chars: Chars, } let mut isYes = false; for i in 0..chars.len() { if i % 2 == 0 { if !chars[i].is_uppercase() { isYes = true; }else{ isYes = false; } ...
use crate::async_message_handler_with_span; use crate::{ db::{ self, session::{InternalSession, SessionId}, DbExecutor, }, span::{AsyncSpanHandler, SpanMessage}, }; use actix::prelude::*; use color_eyre::eyre::Report; use db::user::UserId; use tracing::info; use tracing::{debug, span...
use regex::Regex; use std::collections::{HashMap, HashSet}; use std::num::ParseIntError; use std::str::FromStr; fn input_gen(input: &str) -> (u32, HashMap<u32, OPCODE>, &str) { let mut parts = input.split("\n\n\n"); let part1 = parts.next().unwrap(); let (part1_answer, op_map) = run_samples( part1 ...
use std::env; use std::process; use std::time::SystemTime; use minigrep::Config; fn main() { let config = Config::new(env::args()).unwrap_or_else(|err| { eprintln!("Problem parsing arguments: {}", err); process::exit(1); }); println!("\t Searching for \"{}\" in file: {}\n\n\n", config.que...
use _rustgrimp::importgraph::ImportGraph; use _rustgrimp::layers::{find_illegal_dependencies, Level}; use serde_json::{Map, Value}; use std::collections::{HashMap, HashSet}; use std::fs; #[test] fn test_large_graph() { let data = fs::read_to_string("tests/large_graph.json").expect("Unable to read file"); let v...
use std::{ collections::HashMap, os::raw::c_void, sync::{ atomic::{AtomicBool, AtomicUsize, Ordering::SeqCst}, Mutex, }, }; #[ctor::ctor] unsafe fn initialize_allocation_recording() { tree_sitter::set_allocator( Some(ts_record_malloc), Some(ts_record_calloc), ...
/* * Copyright (c) 2013, David Renshaw (dwrenshaw@gmail.com) * * See the LICENSE file in the capnproto-rust root directory. */ use std; use common::*; use message; pub type SegmentId = u32; pub struct SegmentReader<'self> { messageReader : &'self message::MessageReader<'self>, segment : &'self [u8] } p...
//! As easier to use interface for `uritemplate` crate. use std::fmt; use uritemplate::{IntoTemplateVar, TemplateVar}; /// A URI Template. /// /// See IETF RFC 6570. pub struct UriTemplate(uritemplate::UriTemplate); /// #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum IfEmpty { /// Assign empty value. S...
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT license. */ use crate::common::ANNResult; use super::ArcConcurrentBoxedQueue; use super::{scratch_traits::Scratch}; use std::time::Duration; pub struct ScratchStoreManager<T: Scratch> { scratch: Option<Box<T>>, scratch_...
pub struct Camera { pub eye: glam::Vec3, pub target: glam::Vec3, pub up: glam::Vec3, pub aspect: f32, pub fovy: f32, pub znear: f32, pub zfar: f32, } impl Camera { pub fn build_view_projection_matrix(&self) -> glam::Mat4 { let view = glam::Mat4::look_at_rh(self.eye, self.target,...
#[macro_use] extern crate quick_error; use itertools::Itertools; use rayon::prelude::*; use intcode::Intcode; use std::borrow::Cow; use std::env; use std::io; use std::num::ParseIntError; quick_error! { #[derive(Debug)] pub enum SuperError { IoError(err: io::Error) { from() } ParseIntError(e...
use config::Config; use demangle::demangle as demangle_tww; use failure::{Error, ResultExt}; use linker::{LinkedSection, SectionKind}; use regex::{Captures, Regex}; use rustc_demangle::demangle as demangle_rust; use std::collections::HashMap; use std::fs::File; use std::io::{prelude::*, BufWriter}; use std::str; pub f...
use crate::{ core::Policy, persistence::{Persistence, PersistenceResult}, }; use log::trace; use rusqlite::InterruptHandle; use serde_json::Value; use std::collections::BTreeMap; pub struct Timed<P: Persistence>(P); impl<P: Persistence> Timed<P> { pub fn new(inner: P) -> Timed<P> { Timed(inner) ...
use hound; fn main() { let spec = hound::WavSpec { channels: 2, sample_rate: 48100, bits_per_sample: 32, sample_format: hound::SampleFormat::Float, }; let mut writer = hound::WavWriter::create("out.wav", spec).unwrap(); let song = mod_player::read_mod_file("mod_files/CH...
use std::cmp::Ordering; use itertools::Itertools; use std::collections::VecDeque; use amethyst::{ core::{ alga::linear::EuclideanSpace, math::{Point2, Vector2}, Time, Transform, Named }, derive::SystemDesc, ecs::{Entities, Join, Read, ReadExpect, Write, ReadStorage, S...
#![feature(test)] extern crate test; #[cfg(test)] mod tests { use super::*; use test::Bencher; use std::sync::Arc; use std::rc::Rc; // 3ns #[bench] fn bench_rc_string_clone(b: &mut Bencher) { let s = Rc::new(String::from("Hello")); b.iter(|| { test::black_box(s....
#![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 Trial { #[serde(default, skip_serializing_if = "Option::is_none")] pub status: Option<trial::Status>, #...
pub mod edge; pub mod graph_store; mod graph_store_test; mod storage; pub mod vertex;
// This file is part of rdma-core. 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/rdma-core/master/COPYRIGHT. No part of rdma-core, including this file, may be copied, modified, propagated, or distributed ...
/* chapter 4 syntax and semantics move semantics */ fn main() { let n = vec![1, 2, 3]; fn take(n: Vec<i32>) { // what happens here isn’t important. } take(n); println!("n[0] is: {}", n[0]); } // output should be: /* n[0] is: 1 */
/// #proof of concept fn main() { welcome(); } fn welcome() { println!("welcome select a option \n"); println!("1- encrypt a string"); println!("2- encrypt a file"); println!("3- decrypt"); }
#![warn(clippy::pedantic, clippy::nursery)] // @formatter:off #![allow( clippy::module_name_repetitions, clippy::wildcard_imports, clippy::enum_glob_use, clippy::empty_enum, clippy::too_many_lines, clippy::non_ascii_literal, clippy::option_if_let_else, clippy::option_option, clippy::...
use std::time::Duration; use bonsaidb_core::{ connection::{AccessPolicy, Connection, ServerConnection}, document::KeyId, permissions::{Permissions, Statement}, test_util::{ Basic, BasicByBrokenParentId, BasicByParentId, BasicCollectionWithNoViews, BasicCollectionWithOnlyBrokenParentId, ...
/// Implementation of CART regression / classification trees, based on Elements of /// statistical learning (ESL). use ndarray::prelude::*; /// Defines a decision tree region, based on a given feature space and the associated /// labels. #[derive(PartialEq, Debug, Clone)] struct Region { x: Array2<f64>, y: Arra...
use crate::{grpc_server::RequestItem, GrpcServer, MockBuilder}; impl GrpcServer { /// Finds one or more matched requests for a given request builder. /// /// ## Returns /// * [`None`]: when the given [`MockBuilder`] is not registered using the `setup()` function. /// * Empty Vector: when no request...
use crate::{ errors::{PeerStoreError, Result}, network_group::{Group, NetworkGroup}, peer_store::{ addr_manager::AddrManager, ban_list::BanList, types::{ip_to_network, AddrInfo, BannedAddr, MultiaddrExt, PeerInfo}, Behaviour, Multiaddr, PeerScoreConfig, ReportResult, Status, ...
#[doc = "Reader of register SPINLOCK14"] pub type R = crate::R<u32, super::SPINLOCK14>; impl R {}
#[doc = r"Register block"] #[repr(C)] pub struct FLT { #[doc = "0x00 - control register 1"] pub cr1: CR1, #[doc = "0x04 - control register 2"] pub cr2: CR2, #[doc = "0x08 - interrupt and status register"] pub isr: ISR, #[doc = "0x0c - interrupt flag clear register"] pub icr: ICR, #[d...
//! Implementation crate for `multiversion`. extern crate proc_macro; mod cfg; mod dispatcher; mod match_target; mod multiversion; mod target; mod util; use proc_macro2::TokenStream; use quote::{quote, ToTokens}; use syn::{parse::Nothing, parse_macro_input, punctuated::Punctuated, ItemFn}; #[proc_macro_attribute] pu...
mod structure; use crate::structure::Graph; use crate::structure::{AdjencyMatrix, AdjencyMatrixNotOriented}; type ValueType = u16; const NB_VERTEX: usize = 10; const INFINITE: ValueType = 0; const SRC: usize = 0; const DST: usize = 5; fn main() { let mut data = vec![INFINITE; NB_VERTEX * NB_VERTEX]; let mut g...
use ndarray::Array2; use util::*; fn main() -> Result<(), Box<dyn std::error::Error>> { let timer = Timer::new(); let mut input = input::lines::<u8>(&std::env::args().nth(1).unwrap()); input.sort(); let mut adapters = vec![0; 1]; adapters.append(&mut input); adapters.push(adapters[adapters.len(...
#![doc = "generated by AutoRust 0.1.0"] #![allow(unused_mut)] #![allow(unused_variables)] #![allow(unused_imports)] use super::{models, API_VERSION}; #[non_exhaustive] #[derive(Debug, thiserror :: Error)] #[allow(non_camel_case_types)] pub enum Error { #[error(transparent)] Catalog_GetSecret(#[from] catalog::ge...
fn main() { println!("{:?}", "STDOUT".chars()); eprintln!("{:?}", "STDERR".chars()); }
extern crate libc; use std::env; use std::process; use std::str::FromStr; use std::ffi::CStr; // adapted from https://github.com/fengcen/hostname/blob/master/src/lib.rs extern "C" { fn gethostname(name: *mut libc::c_char, size: libc::size_t) -> libc::c_int; } pub fn get_hostname() -> Option<String> { let mut...
//! # Organix, organic application //! //! `Organix` provides an opinionated way to build application with //! multiple services independent from each other but still require //! communication channels. //! //! With `Organix` it is possible to design the different components //! of your application in isolation from ea...
use sp_core::{Pair, sr25519}; use sc_service; use sp_runtime::traits::{Verify, IdentifyAccount}; use runtime::{AccountId, GenesisConfig, Signature, genesis::testnet_genesis}; // Note this is the URL for the telemetry server //const STAGING_TELEMETRY_URL: &str = "wss://telemetry.polkadot.io/submit/"; /// Specialized `...
mod session; pub use session::WsChatSession;
// 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 std::vec; pub fn extract_active_bits(value: u64) -> vec::Vec<u8> { let mut bit_vec: vec::Vec<u8> = Vec::new(); for i in 0..64 { if (value & (1 << i)) > 0 { bit_vec.push(i); } } return bit_vec; }
pub mod app; pub mod network; pub mod webgl; use app::App; use js_sys::Object; use std::cell::RefCell; use std::rc::Rc; use wasm_bindgen::prelude::*; use wasm_bindgen::JsCast; use web_sys::console; use web_sys::Document; use web_sys::HtmlCanvasElement; use web_sys::KeyboardEvent; use web_sys::MouseEvent; use web_sys::...
use dirs; use std::env; use std::path::PathBuf; #[derive(Debug, Clone)] pub struct Directories { pub log_dir: PathBuf, pub themes_dir: PathBuf, pub fonts_dir: PathBuf, pub config_dir: PathBuf, pub project_dir: PathBuf, } impl Directories { pub fn new(config_dir: Option<String>, project_dir: Op...
use crate::HandlerResult; use wapc_guest::host_call; use wascc_codec::blobstore::Blob; use wascc_codec::blobstore::Container; use wascc_codec::blobstore::{BlobList, FileChunk, StreamRequest, Transfer}; use wascc_codec::blobstore::{ OP_CREATE_CONTAINER, OP_GET_OBJECT_INFO, OP_LIST_OBJECTS, OP_REMOVE_CONTAINER, O...
#[doc = "Register `GPIOD_AFRL` reader"] pub type R = crate::R<GPIOD_AFRL_SPEC>; #[doc = "Register `GPIOD_AFRL` writer"] pub type W = crate::W<GPIOD_AFRL_SPEC>; #[doc = "Field `AFR0` reader - AFR0"] pub type AFR0_R = crate::FieldReader; #[doc = "Field `AFR0` writer - AFR0"] pub type AFR0_W<'a, REG, const O: u8> = crate:...
#[macro_use] extern crate graphql_client; #[macro_use] extern crate serde_derive; extern crate serde; extern crate serde_json; #[derive(GraphQLQuery)] #[graphql( query_path = "tests/operation_selection/queries.graphql", schema_path = "tests/operation_selection/schema.graphql", response_derives = "Debug", )...
extern crate hid; extern crate cp211x_uart; use std::time::Duration; use cp211x_uart::{HidUart, UartConfig, DataBits, StopBits, Parity, FlowControl}; fn run() -> Result<(), cp211x_uart::Error> { let manager = hid::init()?; for device in manager.find(Some(0x10C4), Some(0xEA80)) { let handle = device.op...
#[macro_use] extern crate criterion; extern crate red_mod; use criterion::Criterion; fn criterion_benchmark(_: &mut Criterion) { // c.bench_function("hash", move |b| { // // This will avoid timing the to_vec call. // b.iter_with_setup(|| std::collections::HashMap::<u64, &str>::new(), |mut data| hash_...
use crate::null_collider::NullCollider; use crate::sphere_collider::SphereCollider; use crate::plane_collider::PlaneCollider; use crate::mesh_collider::MeshCollider; use crate::aligned_box_collider::AlignedBoxCollider; /// How [crate::Collider] generics are passed into [crate::PhysicsSystem]. /// /// As it turns out, ...
use std::str::FromStr; use num::BigInt; pub struct MersenneNumber { index: BigInt, } impl MersenneNumber { pub fn new<T>(i: T) -> MersenneNumber where BigInt: From<T>, { let int = BigInt::from(i); MersenneNumber { index: int } } //pub fn nth(n: isize) -> BigInt {} } p...
use super::{Response,ReqErr}; use std::env; use std::io::Read; use std::fs::File; use std::fs::read_dir; use std::path::Path; use std::net::TcpStream; use regex::Regex; const WEB_SERVER_NAME: &'static str = "jrp338-kqj094-web-server/0.1"; /* read_stream */ // takes in a TcpStream and reads contents into buffer //...
use crate::listnode::*; pub fn merge_two_lists(l1: Option<Box<ListNode>>, l2: Option<Box<ListNode>>) -> Option<Box<ListNode>> { if l1.is_none() { return l2 } if l2.is_none() { return l1 } let mut dummy = Box::new(ListNode::new(0)); let mut p1 = l1; let mut p2 = l2; let ...
use azure_core::errors::{AzureError, UnexpectedHTTPResult}; use hyper::body; use hyper::client::ResponseFuture; use url::Url; #[derive(Debug)] pub struct PerformRequestResponse { pub(crate) url: Url, pub(crate) response_future: ResponseFuture, } impl PerformRequestResponse { pub fn url(&self) -> &Url { ...
/* * Copyright (C) 2019-2022 TON Labs. All Rights Reserved. * * Licensed under the SOFTWARE EVALUATION License (the "License"); you may not use * this file except in compliance with the License. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed...
use core::ops::Drop; use fs::Stat; /// VNode represents an in-memory inode pub trait VNode: Sync + Send { /// Read from the node fn read(&mut self, data: &mut [u8], offset: u64) -> Result<u64, ::common::error::Error> { return Err(err!(EINVAL)); } /// Write to the node fn write(&mut self, da...
use quinn::{ConnectError, ConnectionError, EndpointError, ParseError, ReadToEndError, WriteError}; #[derive(Debug, thiserror::Error)] pub enum Error { #[error("IO Error: {0}")] Io(#[from] std::io::Error), // #[error("ReadToEnd: {0}")] // ReadToEnd(#[from] ReadToEndError), #[error("ConnectionError:...
use libip6tc_sys as sys; use std::ffi::CString; use std::mem::{forget, size_of, size_of_val}; use std::net::Ipv6Addr; // use std::os::raw::c_int; use std::alloc::{handle_alloc_error, AllocInit, AllocRef, Global, Layout, ReallocPlacement}; use std::fmt; use std::marker::PhantomData; use std::ptr::NonNull; const ALIGN: ...
#![no_std] #![no_main] extern crate panic_halt; use riscv_rt::entry; use gd32vf103_hal as hal; use hal::prelude::*; use hal::pac as pac; extern "C" { fn enable_mcycle_minstret(); // fn disable_mcycle_minstret(); // fn trap_entry(); // fn irq_entry(); } #[entry] fn main() -> ! { unsafe { enable_m...
//! <https://github.com/EOSIO/eosio.cdt/blob/4985359a30da1f883418b7133593f835927b8046/libraries/eosiolib/contracts/eosio/privileged.hpp#L40-L160> use crate::{NumBytes, Read, Write}; /// Tunable blockchain configuration that can be changed via consensus #[derive( Read, Write, NumBytes, Clone, Defaul...
/* * Copyright Stalwart Labs Ltd. See the COPYING * file at the top-level directory of this distribution. * * Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or * https://www.apache.org/licenses/LICENSE-2.0> or the MIT license * <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your * optio...
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("Failed parse"); ...
use super::ImageSize; use deb_architectures::Architecture; use std::str::FromStr; /// The hash, size, and path of a file that this release file points to. #[derive(Debug, Default, Clone, Hash, PartialEq)] pub struct ReleaseEntry { pub sum: String, pub size: u64, pub path: String, } impl ReleaseEntry { ...
/* Copyright (c) 2023 Uber Technologies, Inc. <p>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 <p>http://www.apache.org/licenses/LICENSE-2.0 <p>Unless required by applicable law or agreed to...
mod gen1; mod gen2; mod gen3; fn main() { gen1::gen1(); println!("{}","###########"); gen2::gen2(); println!("{}","###########"); gen3::gen3(); }
use lazy_static::*; fn load_key(name: &str) -> Vec<u8> { let raw = std::env::var(name).expect(name); raw.split(',') .map(|byte| { let trimmed = byte.trim(); if trimmed.starts_with("0x") || trimmed.starts_with("0X") { u8::from_str_radix(&trimmed[2..], 16).unwrap(...
extern crate rusty_aes; use crate::rusty_aes::utils::padder; /* Implement PKCS#7 padding A block cipher transforms a fixed-sized block (usually 8 or 16 bytes) of plaintext into ciphertext. But we almost never want to transform a single block; we encrypt irregularly-sized messages. One way we account for irregularly...
pub mod entities; pub trait Searchable { type Credentials; } pub trait Repository<T> { // Since different databases use different Ids, // I think I should be able to parameterize over it. type Id; fn all(&self) -> Vec<T>; fn get(&self, id: &Self::Id) -> Option<T>; fn save(&mut self, dat...
use crate::error::{Error, Result}; use crate::input::DbValue; use crate::model::{Model, Models}; use crate::query::Query; use indexmap::IndexMap; use rusqlite::{params, Connection, OptionalExtension, NO_PARAMS}; use std::sync::Arc; pub struct Db { pub conn: Connection, pub models: Arc<Models>, } impl Db { ...
use once_cell::sync::Lazy; use regex::Regex; use syn::{ braced, parenthesized, parse::{Parse, ParseStream}, punctuated::Punctuated, token, Attribute, Error, Field, Ident, LitStr, Result, Token, Visibility, }; pub struct ItemStruct { pub attrs: Vec<Attribute>, pub vis: Visibility, pub struct...
fn get_digits(input: u32) -> Vec<u32> { input .to_string() .chars() .map(|d| d.to_digit(10).unwrap()) .collect() } fn check_adjacent_digits(input: &[u32]) -> bool { for i in 0..input.len() - 1 { if input[i] == input[i + 1] { return true; } } ...
// If you'd like to wait for a `process::Child` to finish, you must call // `Child::wait`, which will return a `process::ExitStatus` use std::process::Command; fn main() { let mut child = Command::new("sleep").arg("5").spawn().unwrap(); let _result = child.wait().unwrap(); println!("reached end of main")...
use types::*; use board::Board; pub trait Bot { fn get_move(&mut self) -> Move; fn update_round(&mut self, round: u32); fn update_board(&mut self, board: Board); fn set_setting(&mut self, setting: Setting); }
use super::lex; use ast_types::*; use nom::*; use std::{mem, str}; // --------------- Some Helper Macros ------------------ // implement the parseable trait for a type, using a interface // similar to named! macro_rules! impl_parse { ($t:ty, $input:ident, $d:block) => ( impl Parseable for $t { ...
//! Tests invoking an API defined in a custom backend. use bonsaidb::{ client::{url::Url, Client}, core::{ custom_api::CustomApi, permissions::{Actionable, Dispatcher, Permissions}, test_util::{Basic, TestDirectory}, }, server::{Backend, Configuration, ConnectedClient, CustomSer...
//! `Small Box` optimization: store small item on stack and fallback to heap for large item. //! //! # Usage //! //! First, add the following to your `Cargo.toml`: //! //! ```toml //! [dependencies] //! smallbox = "0.8" //! ``` //! //! Next, add this to your crate root: //! //! ```rust //! extern crate smallbox; //! ``...
use std::collections::VecDeque; use failure::Error; fn rotate_cw(circle: &mut VecDeque<usize>, n: usize) { for _ in 0..n { let marble = circle.pop_front().unwrap(); circle.push_back(marble); } } fn rotate_ccw(circle: &mut VecDeque<usize>, n: usize) { for _ in 0..n { let marble = c...
#![forbid(unsafe_code)] //! Obtains the dependency list from a compiled Rust binary by parsing its panic messages. //! Recovers both crate names and versions. //! //! ## Caveats //! * If the crate never panics, it will not show up. //! The Rust compiler is very good at removing unreachable panics, //! so we can...
use std::collections::HashMap; use super::common::{Instruction, Value}; fn get_value(map: &HashMap<char, isize>, value: &Value) -> isize { match value { &Value::Raw(ref val) => *val, &Value::Register(register) => *map.get(&register).unwrap_or(&0), } } pub fn parse(data: &str) -> isize { l...
//! All new handlers should be declared in this module mod register; pub mod game; pub mod packet; pub use self::register::register;
use proc_macro::TokenStream; use quote::{quote, ToTokens}; use std::collections::HashSet; use std::hash::Hash; use syn::export::TokenStream2; use syn::parse::{Parse, ParseBuffer}; use syn::parse_macro_input; use syn::Error; use yew_router_route_parser::{CaptureVariant, MatcherToken}; struct S { /// The routing str...
extern crate ez_pixmap; extern crate fltk; use fltk::{enums::*, prelude::*, *}; const PXM: &[&str] = &[ "50 34 4 1", " c black", "o c #ff9900", "@ c white", "# c None", "##################################################", "### ############################## ####", "### ooo...
/*! This library provides field accessor traits,and emulation of structural types. # Features These are the features this library provides: - [Derivation of the 3 accessor traits for every public field](./docs/structural_macro/index.html) (GetField/GetFieldMut/IntoField). - [Declaration of trait aliases for access...
//! The VAPIX v3 parameters interface at `/axis-cgi/param.cgi`. use crate::*; use serde::{Deserialize, Serialize}; use std::collections::BTreeMap; use std::convert::TryFrom; use std::fmt; use std::str::FromStr; /// A device's legacy parameters API. pub struct Parameters<'a, T: Transport>(&'a Client<T>, String); impl...