text
stringlengths
8
4.13M
use crate::{Newline, Style, Styles}; use crate::error::{StringifyResult}; use std::collections::{BTreeMap, HashMap}; use std::hash::Hash; use std::io::Write; pub trait Stringify2 { /// Stringify a datum. To achieve this, there are a number of /// knobs that can be twisted to achieve the desired result: //...
#[doc = "Register `AFRL` reader"] pub type R = crate::R<AFRL_SPEC>; #[doc = "Register `AFRL` writer"] pub type W = crate::W<AFRL_SPEC>; #[doc = "Field `AFR0` reader - 3:0\\]: Alternate function selection for port x pin y (y = 0..7) These bits are written by software to configure alternate function I/Os AFSELy selection...
use lazy_static::lazy_static; use regex::Regex; use std::{ convert::TryFrom, fmt::{self, Debug, Display}, ops::{Add, Div, Mul, RangeInclusive}, str::FromStr, }; #[derive(PartialEq, Eq, Hash)] pub struct Range<Idx = u32>(RangeInclusive<Idx>); impl<Idx> From<RangeInclusive<Idx>> for Range<Idx> { fn ...
//! MathML Operator Dictionary use ast::OperatorForm; pub struct Op { pub character: &'static str, pub form: OperatorForm, pub priority: u32, pub lspace: u8, pub rspace: u8, pub fence: bool, pub stretchy: bool, pub symmetric: bool, pub largeop: bool, pub movablelimits: bool, pub separator: bool,...
use md5; use crate::solutions::Solution; pub struct Day14 {} impl Solution for Day14 { fn part1(&self, input: String) { let answer = (0..std::u64::MAX) .filter(|&ind| is_otp_key(&input, ind)) .nth(63) .unwrap(); println!("{}", answer); } fn part2(&self...
use position::{Dir, Neighbors, Pos, START}; use serenity::{ async_trait, framework::{ standard::{ buckets::LimitedFor, help_commands, macros::{command, group, help, hook}, Args, CommandGroup, CommandResult, DispatchError, HelpOptions, }, St...
#[allow(unused_imports, dead_code)] mod codegen_test; #[allow(unused_imports)] mod features_test; #[allow(unused_imports)] mod mocks_test; #[allow(unused_imports)] mod validations_test;
use crate::utils::{check_auth, Ready}; use actix_web::{ dev::Payload, error::Error as ActixError, FromRequest, HttpRequest, HttpResponse, }; use diesel::Queryable; use serde::Serialize; use std::time::SystemTime; /// Full user object with all database information. #[derive(Serialize, Queryable, PartialEq, Debu...
#[cfg(test)] #[path = "../../../tests/unit/models/domain/load_test.rs"] mod load_test; use crate::models::common::{Dimensions, ValueDimension}; use std::cmp::Ordering; use std::iter::Sum; use std::ops::{Add, Mul, Sub}; const CAPACITY_DIMENSION_KEY: &str = "cpc"; const DEMAND_DIMENSION_KEY: &str = "dmd"; const LOAD_DI...
pub(crate) mod area; pub(crate) mod axis; pub(crate) mod axis_line; pub(crate) mod axis_tick; pub(crate) mod bar; pub(crate) mod point;
use super::*; impl ForeignKeyBuilder for PostgresQueryBuilder { fn prepare_foreign_key_drop_statement( &self, drop: &ForeignKeyDropStatement, sql: &mut SqlWriter, ) { write!(sql, "ALTER TABLE ").unwrap(); if let Some(table) = &drop.table { table.prepare(sql, ...
#[cfg(target_os = "windows")] #[path="win32/mod.rs"] pub mod api; #[cfg(target_os = "linux")] #[path="linux/mod.rs"] pub mod api; #[cfg(target_os = "macos")] #[path="cocoa/mod.rs"] pub mod api;
use std::string::String; use std::io::Read; use std::time::Duration; use hyper::Client; use hyper::header::UserAgent; use ratelimit::Ratelimit; use serde_json; // TODO: rate-limiting per API rules #[derive(Serialize, Deserialize, Debug, Default)] pub struct ReleaseGroup { pub id: String, pub title: String, ...
use tagme::{SurfaceFormSource, TagMeQuery}; use tantivy::{ directory::MmapDirectory, schema::*, Index, }; use log::info; use storage::fst::WikiAnchors; use storage::tantivy::TantivyWikiIndex; pub fn create_schema() -> Schema { let mut schema_builder = SchemaBuilder::default(); schema_builder.add_u64_fie...
// Generated by `scripts/generate.js` pub type VkAccelerationStructureInstance = super::super::khr::VkAccelerationStructureInstance; #[doc(hidden)] pub type RawVkAccelerationStructureInstance = super::super::khr::RawVkAccelerationStructureInstance;
use std::fmt; use std::collections::HashMap; use std::cmp::Ordering; use serde::{Serialize, Deserialize}; use crate::cards::{Hand, Card, Rank, Suit }; #[derive (Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub enum CombinationType { Point, Sequence, Set } impl fmt::Display for CombinationType { fn fmt...
use rand::{rngs::StdRng as StdRngImpl, RngCore, SeedableRng}; #[allow(clippy::module_name_repetitions)] #[derive(Clone, Debug)] pub struct StdRng(StdRngImpl); #[contract_trait] impl necsim_core::cogs::Backup for StdRng { unsafe fn backup_unchecked(&self) -> Self { self.clone() } } impl necsim_core::c...
const ERROR: u8 = 0b00; const EMPTY: u8 = 0b01; const FILLED: u8 = 0b10; const UNKNOWN: u8 = 0b11; #[ derive (Clone, Copy, Debug, Eq, PartialEq) ] #[ repr (transparent) ] pub struct Cell { bits: u8, } impl Cell { pub const ERROR: Cell = Cell { bits: ERROR }; pub const EMPTY: Cell = Cell { bits: EMPTY }; pub...
use stdweb::traits::*; use stdweb::unstable::TryInto; use stdweb::web::html_element::CanvasElement; use stdweb::web::{document, CanvasRenderingContext2d}; use crate::maze::{Maze, Cell, CellType}; const CELL_SIDE: u32 = 30; const STROKE_WIDTH: u32 = 29; pub struct Canvas { pub canvas: CanvasElement, pub ctx:...
use std::io; use std::io::File; fn main() { let mut file = File::create(&Path::new("write.txt")); for line in io::stdin().lines() { let result = file.write_str(format!("{}", line.unwrap())); println!("IoResult: {}", result); } }
#[doc = "Register `FTSR2` reader"] pub type R = crate::R<FTSR2_SPEC>; #[doc = "Register `FTSR2` writer"] pub type W = crate::W<FTSR2_SPEC>; #[doc = "Field `FT34` reader - Falling trigger event configuration bit of Configurable Event input"] pub type FT34_R = crate::BitReader<FT34_A>; #[doc = "Falling trigger event conf...
use std::fs::File; use std::io::Error; use flate2::read::GzDecoder; use flate2::write::GzEncoder; use flate2::Compression; use tar::Archive; pub fn compress() { // create a file wraped by GzEncoder and Builder let path = "tar_name.tar.gz"; let tar_gz = File::create(path).unwrap(); let enc = GzEncoder:...
trait Algorithm{ fn run_algorithm(); }
// Generic json responses use rocket_contrib::json::Json; use rocket::response::status::BadRequest; #[derive(Serialize, Deserialize, Debug)] pub struct JsonGeneric { pub satus: JsonGenericCodes, pub reason: String, } impl JsonGeneric { // return a new json code pub fn new_response(c: JsonGenericCodes,...
#[macro_use] extern crate glium; use glium::DisplayBuild; use glium::Surface; extern crate rand; use rand::distributions::{IndependentSample, Range}; #[derive(Debug, Default, Copy, Clone)] struct Vertex { position: [f64; 2], } #[derive(Debug)] struct Ball { vertex: Vertex, radius: f64, velocity: [f64...
use base64; use hex; use std::collections::HashMap; use std::str::from_utf8; pub fn rank_char_frequency(data: &Vec<u8>) -> i32 { // i took this from https://laconicwolf.com/2018/05/29/cryptopals-challenge-3-single-byte-xor-cipher-in-python/ // this is a HashMap of the character frequency in english let cha...
use std::env; struct TipResult { amt: f64, tip: f64, } fn main() { let args: Vec<_> = env::args().skip(1).filter_map(|i| i.parse().ok()).collect(); let tip = match &args[..] { [ref amt] => Some(get_tip(*amt, 15.0)), [ref amt, ref pct] => Some(get_tip(*amt, *pct)), _ => None, ...
use hyper; use hyper::client::{Client,Pool}; use hyper::net::HttpsConnector; use hyper::net::Openssl; use model::PrePayResult; use service::de_xml; use std::io::Read; use std::default::Default; use std::sync::Arc; use std::path::Path; use std::collections::BTreeMap; use uuid::Uuid; use md5; use config::Con...
fn main() { let s1 = gives_ownership(); let s2 = String::from("helloet tr"); // let s3 = takes_and_gives_back(s2); // // references_and_borrowing(); let te = first_word(&s2); println!("{}", te) } fn gives_ownership() -> String { let s = String::from("hello"); s } fn takes_and_gives_back...
#[doc = "Register `CSR1` reader"] pub type R = crate::R<CSR1_SPEC>; #[doc = "Field `PVDO` reader - Programmable voltage detect output This bit is set and cleared by hardware. It is valid only if the PVD has been enabled by the PVDE bit. Note: since the PVD is disabled in Standby mode, this bit is equal to 0 after Stand...
use crate::geo::Point3d; use float_cmp::approx_eq; /// modified from https://www.quora.com/What-is-an-efficient-algorithm-to-find-an-island-of-connected-1s-in-a-matrix-of-0s-and-1s const SIBLINGS: [(i32, i32); 8] = [(-1, -1), (0, -1), (1, -1), (-1, 0), (1, 0), (-1, 1), (0, 1), (1, 1)]; pub fn bfs(node: (usize, usize)...
#![cfg(test)] use std::f64; use test; use libc; extern { fn snprintf(buf: *mut libc::c_char, len: libc::size_t, fmt: *const libc::c_char, ...) -> libc::c_int; } fn f64_to_buf(buf: &mut [u8], fmt: &str, v: f64) -> usize { unsafe { snprintf(buf.as_mut_ptr() as *mut _, buf.len() as libc:...
extern crate hyper_lib; use hyper_lib::*; fn main() { let p1 = PolarCoord::new(3.0, 1.3); let p2 = p1.distant_point(5.0, 2.0); let c1 = p1.to_poincare_coord(); let c2 = p2.to_poincare_coord(); let slope = angle::get_from_slope(c1.slope(c2)); println!("V {}", slope); }
use axum::{ extract::{Query, State}, response::IntoResponse, }; use chrono::{Duration, Utc}; use serde::{Deserialize, Serialize}; use crate::{http_server::ResponseResult, *}; #[derive(Debug, Deserialize)] pub(crate) struct GithubOauthRequest { pub(crate) code: String, pub(crate) state: Option<String>,...
use super::redirect::Redirect; #[derive(Debug, Clone)] pub struct CommandParse { command: String, sub_command: String, option: Vec<String>, path: String, index: usize, pipe: Option<Box<CommandParse>>, redirect: Option<Redirect>, } impl CommandParse { pub fn new() -> Self { Self { command: St...
// This file is part of Substrate. // Copyright (C) 2019-2020 Parity Technologies (UK) Ltd. // SPDX-License-Identifier: Apache-2.0 // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // ht...
fn main() { let s = String::from("hello world"); // first_word and second_word work on 'String's let hello = first_word(&s); let world = second_word(&s); println!("{} {}", hello, world); // first_word works on slices of `String`s let word = first_word(&s[..]); println!("{}", word); ...
//! How to override the hard fault exception handler and the default exception handler #![deny(warnings)] #![no_main] #![no_std] extern crate cortex_m; extern crate cortex_m_rt as rt; extern crate panic_halt; use cortex_m::asm; use rt::{entry, exception, ExceptionFrame}; #[entry] fn main() -> ! { loop {} } #[e...
pub fn remove_element(nums: &mut Vec<i32>, val: i32) -> i32 { let mut l = 0; for r in 0..nums.len() { if nums[r] != val { nums[l] = nums[r]; l += 1; } } l as i32 } fn main() { let mut v = vec![3, 2, 2, 3]; assert_eq!(remove_element(&mut v, 3), 2); }
use crate::render::buffer::RenderBuffer; use crate::render::sprite::Sprite; pub fn index3(b: &mut RenderBuffer) { let pos = b.index_position; let offset = b.index_offset; let indices = &mut b.indices; indices[pos] = offset; indices[pos + 1] = offset + 1; indices[pos + 2] = offset + 2; b.ind...
use amethyst::{ assets::{AssetStorage, Handle, Loader}, core::{Named, Parent, Transform, TransformBundle}, derive::SystemDesc, ecs::{ Component, Entity, Join, NullStorage, Read, ReadStorage, System, SystemData, WorldExt, WriteStorage, }, }; #[derive(Default)] pub struct Zombie; im...
#[allow(unused_imports)] use super::util::prelude::*; use super::super::resource::ImageData; use super::chat_message::{self, Message}; use super::util::{Pack, PackDepth}; use super::Property; use super::{BlockMut, BlockRef}; use crate::libs::color::Pallet; use crate::libs::select_list::SelectList; use lazy_static::laz...
// testing some LLVM IR emitted by rustc pub fn rust_loop(a: isize, b: isize, v: &mut Vec<isize>) -> isize { let mut sum = 0; for i in v.iter() { sum += if i % 3 == 1 { i + a } else { i + b }; } for i in 0 .. 5 { v[i] = (i + 2) as isize; } sum }
#[doc = "Reader of register ADV_RAND"] pub type R = crate::R<u32, super::ADV_RAND>; #[doc = "Reader of field `ADV_RAND`"] pub type ADV_RAND_R = crate::R<u8, u8>; impl R { #[doc = "Bits 0:3 - Random ADV delay, to be used for ADV next instant calculation. The granularity is in BT slot"] #[inline(always)] pub ...
use crate::client::Client; use ureq::{Error, Request}; use serde::{Deserialize}; #[derive(Deserialize)] pub struct JournalInbound { pub from: String, pub id: String, pub price: String, pub text: String, pub timestamp: String, pub to: String, } #[derive(Deserialize)] pub struct JournalOutbound ...
use proconio::{fastout, input}; #[fastout] fn main() { input! { n_str: String, }; let acc: i64 = n_str .chars() .fold(0, |acc, c| c.to_digit(10).unwrap() as i64 + acc); println!("{}", if acc % 9 == 0 { "Yes" } else { "No" }); }
use std::alloc::System; use rayon::prelude::*; use stats_alloc::{StatsAlloc, INSTRUMENTED_SYSTEM}; use abin::{NewSStr, SStr, StrFactory}; use utils::*; #[global_allocator] static GLOBAL: &StatsAlloc<System> = &INSTRUMENTED_SYSTEM; pub mod utils; #[derive(Clone)] struct SrcList(Vec<SrcItem>); #[test] fn send_sync_...
// This file was generated by gir (https://github.com/gtk-rs/gir @ fbb95f4) // from gir-files (https://github.com/gtk-rs/gir-files @ 77d1f70) // DO NOT EDIT use Error; use IOStream; use TlsAuthenticationMode; use TlsCertificate; use TlsConnection; use ffi; use glib; use glib::StaticType; use glib::Value; use glib::obj...
#![feature(decl_macro, proc_macro_hygiene)] extern crate rocket; use rocket::{get, routes}; fn main() { rocket::ignite() .mount("/", routes![graphql_handler]) .launch(); } #[get("/")] fn graphql_handler() -> &'static str { "Static endpoint!" }
#![no_std] #![no_main] #[path = "../example_common.rs"] mod example_common; use example_common::*; use core::mem; use cortex_m_rt::entry; use defmt::panic; use embassy::executor::raw::Task; use embassy::executor::Executor; use embassy::time::{Duration, Timer}; use embassy::util::Forever; use embassy_nrf::peripherals;...
/*! This crate is a native Rust port of [Google's HighwayHash](https://github.com/google/highwayhash), which is a fast, keyed, and strong hash function. ## Caution HighwayHash (the algorithm) has not gone undergone extensive cryptanalysis like SipHash (the default hashing algorithm in Rust), but according to the aut...
/// The address where I/O peripherals are mapped to. pub const IO_BASE: usize = 0x3F000000; /// Power management addresses pub const ARM_POWER_MANAGEMENT_BASE: usize = IO_BASE + 0x100000; pub const ARM_POWER_MANAGEMENT_RSTC: usize = ARM_POWER_MANAGEMENT_BASE + 0x1C; pub const ARM_POWER_MANAGEMENT_WDOG: usize = ARM_POW...
#[doc = "Register `STGENC_PIDR5` reader"] pub type R = crate::R<STGENC_PIDR5_SPEC>; #[doc = "Field `PIDR5` reader - PIDR5"] pub type PIDR5_R = crate::FieldReader<u32>; impl R { #[doc = "Bits 0:31 - PIDR5"] #[inline(always)] pub fn pidr5(&self) -> PIDR5_R { PIDR5_R::new(self.bits) } } #[doc = "ST...
use std::collections::HashMap; use std::vec::Vec; #[derive(PartialEq, Debug, Clone, Copy)] pub enum TokenType { Null, Number, String, Quote, Boolean, LeftBracket, RightBracket, LeftSquareBracket, RightSquareBracket, Colon, Comma, } #[derive(PartialEq, Debug)] pub struct Tok...
mod map; pub use map::MapLoader;
use crate::utils::assert_send_transaction_fail; use crate::{Net, Spec, DEFAULT_TX_PROPOSAL_WINDOW}; use ckb_chain_spec::ChainSpec; use ckb_types::core::BlockNumber; use log::info; const MATURITY: BlockNumber = 5; pub struct CellbaseMaturity; impl Spec for CellbaseMaturity { crate::name!("cellbase_maturity"); ...
// 封装multi_get.rs,当前的multi_get是单层访问策略,需要封装为多层 // TODO: 有2个问题:1)单层访问改多层,封装multiGetSharding? 2) 需要解析key。如果需要解析key,那multiGetSharding还有存在的价值吗? // 分两步:1)在multi get中,解析多个cmd/key 以及对应的response,然后多层穿透访问; // 2)将解析req迁移到pipelineToPingPong位置,同时改造req buf。 // TODO:下一步改造:1)支持根据keys来自定义访问指令;2)getmulit在layer层按key hash。 use std...
//! [![github-img]][github-url] [![crates-img]][crates-url] [![docs-img]][docs-url] //! //! [github-url]: https://github.com/QnnOkabayashi/compiled-uuid //! [crates-url]: https://crates.io/crates/compiled-uuid //! [docs-url]: https://docs.rs/compiled-uuid/*/compiled_uuid //! [github-img]: https://img.shields.io/badge/...
#![no_main] #[macro_use] extern crate libfuzzer_sys; extern crate publicsuffix; use std::str; use publicsuffix::List; fuzz_target!(|data: &[u8]| { if let Ok(input) = str::from_utf8(data) { let list = List::from_path("/tmp/public_suffix_list.dat").unwrap(); let _ = list.parse_domain(input); } ...
// This will work on any meta.json file located in the directory use std::path::Path; use tantivy::Index; fn main() -> tantivy::Result<()> { let directory = Path::new("/tmp/tantivy/idxhn"); let dir_exists = directory.exists(); if dir_exists { println!("{}", "Found the tantivy index directory") ...
use reqwest; use serde::{Deserialize, Serialize}; use crate::errors::*; use crate::models::NoIdRestaurant; #[derive(Debug, Serialize, Deserialize)] struct Gnavi { pub id: String, pub name: String, pub latitude: String, pub longitude: String, pub address: String, } #[derive(Debug, Serialize, Deseri...
use super::*; pub fn expression() -> Expression { Expression { boostrap_compiler: boostrap_compiler, typecheck: typecheck, codegen: codegen, } } fn boostrap_compiler(_compiler: &mut Compiler) {} fn typecheck( resolver: &mut TypeResolver<TypecheckType>, _function: &TypevarFunct...
use std::fmt; use std::error; use std::error::Error; use super::operator::Operator; use super::Result; pub struct Integer(pub i32); impl Integer { pub fn parse(raw_int: &str) -> Result<(Integer, &str)> { let mut unsigned: u64 = 0; let is_neg: bool; let mut rest_of_expr = raw_int.trim_left(...
use tokio::net::unix::{OwnedReadHalf, OwnedWriteHalf}; use tokio::net::UnixStream; use tokio_util::codec::{ BytesCodec, Decoder, FramedRead, FramedWrite, LengthDelimitedCodec, LinesCodec, }; /// Helper creates a Unix `Stream` and `Sink` from the given socket, using the given `Codec` to /// handle delineation betwe...
use {syn, quote, abi}; pub struct SignatureIterator<'a> { method_sig: &'a syn::MethodSig, position: usize, } impl<'a> Iterator for SignatureIterator<'a> { type Item = (syn::Pat, syn::Ty); fn next(&mut self) -> Option<Self::Item> { while self.position < self.method_sig.decl.inputs.len() { if let &syn::FnArg:...
// Copyright 2020 ChainSafe Systems // SPDX-License-Identifier: Apache-2.0, MIT use encoding::{ de::{Deserialize, Deserializer}, ser::{Serialize, Serializer}, BytesDe, BytesSer, }; /// The result from getting an entry from Drand. #[derive(Clone, Debug, Default, Eq, PartialEq)] pub struct BeaconEntry { ...
use serde_json::{Value}; use crate::util::structural_identity as structural_identity; use std::collections::HashMap; pub fn translate(v : &Value, m : &HashMap<String, String>) -> Value { structural_identity::translate(v,m,&substitute) } pub fn substitute(v : &Value, m : &HashMap<String, String>) -> Value { ...
use programs::ProgramModel; use db::PostgresConnection as Connection; use postgres::error::Error; use postgres::rows::Row; use pgx::{queryx, FromRow}; #[derive(Debug)] pub struct OrgModel { pub id: i32, pub name: String, pub description: Option<String>, pub programs: Option<Vec<ProgramModel>>, pub ...
use std::path::PathBuf; use clap::Clap; #[derive(Clap, Debug)] #[clap(version = "0.1.0", author = "Toni Peter")] pub struct Args { pub database: PathBuf, #[clap(subcommand)] pub command: Command, } #[derive(Clap, Debug)] pub enum Command { Scan(ScanOpts), Show, } #[derive(Clap, Debug, Clone)] p...
// https://www.codewars.com/kata/scheduling-shortest-job-first-or-sjf fn sjf(jobs: &[usize], index: usize) -> usize { let cur = jobs[index]; jobs .iter() .enumerate() .filter(|&(i, x)| x < &cur || (i <= index && x == &cur)) .map(|(_, x)| x) .sum() } #[cfg(test)] mod tests { use super::*; ...
#[doc = r"Register block"] #[repr(C)] pub struct RegisterBlock { #[doc = "0x00 - channel configuration y register"] pub ch0cfgr1: CH0CFGR1, #[doc = "0x04 - channel configuration y register"] pub ch0cfgr2: CH0CFGR2, #[doc = "0x08 - analog watchdog and short-circuit detector register"] pub ch0awsc...
#![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 enum HealthState { Invalid, Ok, Warning, Error, Unknown, } #[derive(Clone, Debug, PartialEq, Serialize...
/// An enum to represent all characters in the MiscellaneousSymbolsandPictographs block. #[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)] pub enum MiscellaneousSymbolsandPictographs { /// \u{1f300}: '🌀' Cyclone, /// \u{1f301}: '🌁' Foggy, /// \u{1f302}: '🌂' ClosedUmbrella, /// \u{1f303}...
use crate::types::{ConsumerCount, MessageCount, ShortString}; use std::borrow::Borrow; #[derive(Clone, Debug)] pub struct Queue { name: ShortString, message_count: MessageCount, consumer_count: ConsumerCount, } impl Queue { pub(crate) fn new( name: ShortString, message_count: MessageCo...
use std::fs::File; use std::path::Path; use std::io::BufReader; use protobuf::stream::CodedInputStream; use misc::*; use zbackup::disk_format::*; #[ derive (Clone, Debug) ] pub struct DiskStorageInfo { raw: protobuf_types::StorageInfo, } impl DiskStorageInfo { #[ inline ] pub fn read ( coded_input_stream: & m...
#[doc = "Register `IOGCSR` reader"] pub type R = crate::R<IOGCSR_SPEC>; #[doc = "Register `IOGCSR` writer"] pub type W = crate::W<IOGCSR_SPEC>; #[doc = "Field `G1E` reader - Analog I/O group x enable"] pub type G1E_R = crate::BitReader<G1E_A>; #[doc = "Analog I/O group x enable\n\nValue on reset: 0"] #[derive(Clone, Co...
pub mod build; pub mod cache; pub mod identity; pub use build::BuildError; pub use cache::CacheError; pub use identity::IdentityError; /// The type to represent DFX results. pub type DfxResult<T = ()> = anyhow::Result<T>; /// The type to represent DFX errors. pub type DfxError = anyhow::Error; #[macro_export] macro...
use crate::{ db::HirDatabase, ids::{ BlockExpr, Constant, Export, Function, Identifier, Import, Item, Literal, Module, Path, Type, TypeDecl, }, items::{ ConstantData, ExportData, FunctionData, ImportData, ItemData, ItemKind, ModuleData, TypeDeclData, }, lower::{ ...
#[allow(unused_variables)] //Allows to create variables not used in any function fn main() { let var_a = String::from("Howdy!"); //É preciso garantir que var_a não é modificado, apos criar pointers, para que as referencias sejam atribuídas //Senão occorrer isso existe um erro de compilador let var_b = &...
#![feature(test)] use dev_util::impl_benchmark; impl_benchmark!(sha3, Sha3_224); impl_benchmark!(sha3, Sha3_256); impl_benchmark!(sha3, Sha3_384); impl_benchmark!(sha3, Sha3_512); impl_benchmark!(sha3, Shake128); impl_benchmark!(sha3, Shake256);
#[derive(Debug)] struct Students { name:String, english:i32, math:i32, physics:i32, } impl Students{ fn build(name:String, english:i32, math:i32, physics:i32)->Students { Students{name,english,math,physics} } fn best_mark(&self)->i32 { if self.english < self.mat...
use pretty_assertions::assert_eq; use sudo_test::{Command, Env, User}; use crate::{ Result, GROUPNAME, SUDOERS_ALL_ALL_NOPASSWD, SUDOERS_ROOT_ALL_NOPASSWD, SUDOERS_USER_ALL_NOPASSWD, USERNAME, }; macro_rules! assert_snapshot { ($($tt:tt)*) => { insta::with_settings!({ prepend_module_to...
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under both the MIT license found in the * LICENSE-MIT file in the root directory of this source tree and the Apache * License, Version 2.0 found in the LICENSE-APACHE file in the root directory * of this source tree. */ use c...
use std::{fs::File, path::Path}; use walkdir::WalkDir; pub fn rar_unpack(archive_path: &Path, destination_path: &Path) -> compress_tools::Result<()> { let path_as_string = archive_path.to_str().unwrap().to_string(); let archive = unrar::Archive::new(path_as_string); let result = archive.extract_to(destinat...
// Copyright 2017 Dmitry Tantsur <divius.inside@gmail.com> // // 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 ap...
pub(crate) mod having_date_validation; pub(crate) mod making_list; pub(crate) mod making_url_format; pub(crate) mod converting_to_rust_enum; pub(crate) mod enum_specific; pub(crate) mod checking_string_character; pub(crate) use self::having_date_validation::*; pub(crate) use self::making_list::*; pub(crate) use self::...
use std::cmp; use std::collections::HashMap; type Coordinate = (u32, u32); type Distance = u32; type Area = u64; fn calc_manhattan_distance(c1: &Coordinate, c2: &Coordinate) -> Distance { let v0 = cmp::max(c1.0, c2.0) - cmp::min(c1.0, c2.0); let v1 = cmp::max(c1.1, c2.1) - cmp::min(c1.1, c2.1); v0 + v1 } ...
use std::sync::{Arc, Future}; use std::cell::Cell; use std::task::{TaskBuilder, failing}; use worker::{Signaller, signaller}; pub enum WorkerStatus { Starting, Running, Stopped, Failed } // Represents the external view of the worker pub trait Worker { fn name<'a>(&'a self) -> &'a str; fn request_shutdown(&self)...
pub mod isr; pub mod nvic; pub mod sys;
#[doc = "Register `SR` reader"] pub type R = crate::R<SR_SPEC>; #[doc = "Field `B0OF` reader - Buffer 0 overflow flag"] pub type B0OF_R = crate::BitReader; #[doc = "Field `B1OF` reader - Buffer 1 overflow flag"] pub type B1OF_R = crate::BitReader; #[doc = "Field `B2OF` reader - Buffer 2 overflow flag"] pub type B2OF_R ...
use crate::gui::input::*; use crate::prelude::*; use quicksilver::prelude::*; use specs::prelude::*; // #[derive(Clone)] pub struct UiState { pub selected_entity: Option<Entity>, pub hovered_entity: Option<Entity>, pub grabbed_item: Option<Grabbable>, // TODO [0.1.4]: I think these four could go into f...
use crate::io::*; use crate::model::rnn::*; use crate::model::seq2seq::*; use crate::optimizer::{NewAdam, NewSGD}; use crate::trainer::{RnnlmTrainer, Seq2SeqTrainer}; use crate::types::*; use crate::util::*; use ndarray::{array, Array2, Axis, Ix2}; use std::collections::HashMap; fn gen_text() { const SAMPLE_SIZE: ...
use whiteread::parse_line; use std::collections::VecDeque; #[derive(Debug)] struct Point { x: i32, y: i32, } impl Point { fn new(p: (i32, i32)) -> Point { Point { x: p.0, y: p.1 } } fn man_distance(&self, rhs: &Point) -> i32 { (self.x - rhs.x).abs() + (self.y - rhs.y).abs() } ...
use crate::mem_table::MemTable; use crate::utils::files_with_ext; use crate::wal_iterator::WALEntry; use crate::wal_iterator::WALIterator; use std::fs::{remove_file, File, OpenOptions}; use std::io::prelude::*; use std::io::{self, BufWriter}; use std::path::{Path, PathBuf}; use std::time::{SystemTime, UNIX_EPOCH}; ///...
#![no_main] #![no_std] extern crate cortex_m_rt; extern crate panic_halt; use cortex_m_rt::{entry, exception}; #[entry] fn foo() -> ! { loop {} } #[exception] fn SysTick() { static mut COUNT: u64 = 0; if *COUNT % 2 == 0 { *COUNT += 1; } else { *COUNT *= 2; } } #[exception] fn S...
use linux_embedded_hal::I2cdev; use pcf8591::PCF8591; fn main() { let dev = I2cdev::new("/dev/i2c-1").unwrap(); let mut driver = PCF8591::new(dev); let data0 = driver.query_ain0().unwrap(); println!("Potentiometer: {}", data0); let data1 = driver.query_ain1().unwrap(); println!("Photoresistor...
struct Digits(u64); impl Iterator for Digits { type Item = u64; fn next(&mut self) -> Option<u64> { let next = if self.0 == 0 { None } else { Some(self.0 % 10) }; self.0 /= 10; next } } fn luhn_test(num: u64) -> bool { Digits(num).enumerate() .map(|(i, digit)| if (i % 2...
use crate::prelude::*; use md5::Digest; fn solve<F>(input: &str, mut f: F) -> u64 where F: FnMut(&[u8]) -> Digest, { let mut buffer = Vec::with_capacity(input.len() + 20); buffer.extend_from_slice(input.as_bytes()); let mut index_to_count_next = [0; 16]; let mut three_repetitions: Vec<(u64, u8)> =...
#[doc = "Register `SWIER2` reader"] pub type R = crate::R<SWIER2_SPEC>; #[doc = "Register `SWIER2` writer"] pub type W = crate::W<SWIER2_SPEC>; #[doc = "Field `SWI35` reader - SWI35"] pub type SWI35_R = crate::BitReader; #[doc = "Field `SWI35` writer - SWI35"] pub type SWI35_W<'a, REG, const O: u8> = crate::BitWriter<'...
use super::*; use crate::message::name::*; // An NSResource is an NS Resource record. #[derive(Default, Debug, Clone, PartialEq)] pub struct NsResource { pub ns: Name, } impl fmt::Display for NsResource { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "dnsmessage.NSResource{{NS: ...