text
stringlengths
8
4.13M
use std::collections::hash_map::Entry; use std::collections::{HashMap, HashSet}; use std::fmt::Write; use std::sync::{Arc, Mutex}; #[derive(Debug, Default, Clone)] pub struct IdResolver { /// name -> unique name names: Arc<Mutex<HashMap<String, String>>>, /// reserved names reserved: HashSet<&'static s...
use phi::data::Rectangle; use phi::gfx::{Renderable, Sprite}; use sdl2::render::Renderer; #[derive(Clone)] pub struct Background { pos: f64, // The amount of pixels moved to the left every second vel: f64, sprite: Sprite, } impl Background { pub fn load(renderer: &Renderer, path: &str, velocity:...
#![allow(proc_macro_derive_resolution_fallback)] use super::schema::person; #[derive(Queryable, AsChangeset, Serialize, Deserialize)] #[table_name = "person"] pub struct Person { pub id: i32, pub first_name: String, pub last_name: String, // pub age: i32, }
mod args; mod wage; mod enumit; use std::env; use std::io::{self, Write}; use std::process; use crate::args::Command; use crate::wage::Wage; fn main() { /// Run wageman with `std::env::args_os`, outputting to stdout. /// Error detail may be outputted to stderr. fn run() -> io::Result<()> { let args = env::args...
use iota_streams_core::{ prelude::{ HashMap, Vec, }, psk, }; pub trait PresharedKeyStore: Default { fn insert(&mut self, pskid: psk::PskId, psk: psk::Psk); fn filter<'a>(&'a self, psk_ids: &'_ psk::PskIds) -> Vec<psk::IPsk<'a>>; fn get<'a>(&'a self, pskid: &'_ psk::PskId) -> Opt...
#[doc = "Register `BIASCONF` reader"] pub struct R(crate::R<BIASCONF_SPEC>); impl core::ops::Deref for R { type Target = crate::R<BIASCONF_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<BIASCONF_SPEC>> for R { #[inline(always)] fn from(reader: ...
//! Encode a text source to a BinJS. extern crate binjs; extern crate clap; extern crate env_logger; use binjs::io::{CompressionTarget, Format}; use binjs::source::{Shift, SourceParser}; use binjs::specialized::es6::io::Encoder; use binjs::specialized::es6::Enrich; use std::fs; use std::io::*; use std::path::{Path, ...
use futures::stream::Stream as _; mod input; #[allow(clippy::type_complexity)] struct Expect { process: tokio_pty_process_stream::Process<input::buf::Stdin>, expectations: Vec<( regex::Regex, Box< dyn Fn(&mut tokio_pty_process_stream::Process<input::buf::Stdin>) + S...
//! Parses instructions in the following format: //! 0x1fff: //! LOADC 7 //! LOADC 8 //! ADD //! HCF use std::borrow::Cow; use std::error; use std::{fmt, str::Lines}; use crate::processor::Instruction; use super::{Byte, Memory, Word}; macro_rules! propagate { ( $res:expr ) => { match $re...
//! This example shows that the DMA abstraction is not made unsound by //! LLVM's load elimination. //! //! Note: This works only thanks to the compiler fences in `Transfer`'s //! methods. If they are removed, the `assert_eq` will fail. //! //! Here is a smaller self-contained example of how fences prevent load //! eli...
use core::fmt; use core::marker::PhantomData; use core::mem::ManuallyDrop; use core::ops::Deref; use core::ptr; use super::{Arc, ArcBorrow}; /// An `Arc`, except it holds a pointer to the T instead of to the /// entire ArcInner. /// /// An `OffsetArc<T>` has the same layout and ABI as a non-null /// `const T*` in C, ...
mod tree; use crate::tree::Tree; use crate::tree::TreeVisitor; use crate::tree::Visitor; use crate::tree::ElementCount; impl<T> ElementCount for &[T] { fn element_count(&self) -> usize { self.len() } } impl<T: ?Sized> ElementCount for Box<T> { fn element_count(&self) -> usize { 1 } } ...
struct Solution; use std::collections::hash_map::DefaultHasher; use std::collections::HashMap; use std::collections::HashSet; use std::hash::Hasher; struct Dict { same: HashSet<String>, capitlization: HashMap<u64, String>, vowel_error: HashMap<u64, String>, } impl Dict { fn new(wordlist: Vec<String>) ...
use crate::decode::Decode; use crate::encode::{Encode, IsNull}; use crate::error::BoxDynError; use crate::io::MySqlBufMutExt; use crate::protocol::text::{ColumnFlags, ColumnType}; use crate::types::Type; use crate::{MySql, MySqlTypeInfo, MySqlValueRef}; use std::borrow::Cow; const COLLATE_UTF8_GENERAL_CI: u16 = 33; co...
// This file is part of Substrate. // Copyright (C) Parity Technologies (UK) Ltd. // SPDX-License-Identifier: Apache-2.0 // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.a...
// Copyright 2020 WHTCORPS INC Project Authors. Licensed Under Apache-2.0 use std::cmp::{Ordering as CmpOrdering, Reverse}; use std::f64::INFINITY; use std::fmt::{self, Display, Formatter}; use std::fs::{self, File, Metadata, OpenOptions}; use std::io::{self, ErrorKind, Read, Write}; use std::path::Path; use std::path...
use std::collections::HashMap; /// 3. /// /// 给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。 /// /// 示例 1: /// /// 输入: "abcabcbb" /// 输出: 3 /// 解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。 /// 示例 2: /// /// 输入: "bbbbb" /// 输出: 1 /// 解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。 /// 示例 3: /// /// 输入: "pwwkew" /// 输出: 3 /// 解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3。 ...
use std::io::Write; use crate::query::OutputFormat; use crate::output::flat::{TABS_FORMATTER, LINES_FORMATTER, LIST_FORMATTER}; use crate::output::json::JsonFormatter; use crate::output::html::HtmlFormatter; use crate::output::csv::CsvFormatter; mod json; mod flat; mod html; mod csv; pub trait ResultsFormatter { ...
/// kind of this library Error #[derive(Fail, Debug, PartialEq)] pub enum ErrorKind { /// JSON parse error #[fail(display = "Json parse error")] JsonParse, /// Fetch failed error #[fail(display = "Fetch failed error")] FetchFailed, /// Wrong Token #[fail(display = "Wrong token")] Wro...
#[allow(unused_imports)] use tracing::{info, warn, debug, error, trace, instrument, span, Level}; use serde::{Serialize, Deserialize}; use rand::{RngCore}; use crate::utils::vec_serialize; use crate::utils::vec_deserialize; use super::*; /// Represents an initiailization vector used for both hash prefixing /// to cre...
use std::{collections::HashMap, iter::Peekable}; use itertools::Itertools; use pratt::{Affix, Associativity, PrattParser, Precedence}; use super::{ ast::{AstKind, AstNode}, expression::{Expression, ExpressionKind}, lexer::Lexer, operator::Operator, parser::{ParseError, Parser}, token::{calcula...
//@compile-flags: -Zmiri-permissive-provenance -Zmiri-backtrace=full //@only-target-x86_64-unknown-linux: support for tokio only on linux and x86 //@error-in-other-file: returning ready events from epoll_wait is not yet implemented //@normalize-stderr-test: " += note:.*\n" -> "" use tokio::time::{sleep, Duration, Inst...
use common::util::*; static UTIL_NAME: &'static str = "pathchk"; fn new_ucmd() -> UCommand { TestScenario::new(UTIL_NAME).ucmd() } #[test] fn test_default_mode() { // test the default mode { // accept some reasonable default let result = new_ucmd() .args(&["abc/def"]).run(); ...
use stm32f4xx_hal as hal; use embedded_hal::spi::FullDuplex; use hal::timer::{Instant, MonoTimer}; use nb::block; use crate::rgb::Rgb; // Reference implementation: // https://github.com/smart-leds-rs/ws2812-spi-rs/blob/fac281eb57b5f72c48e368682645e3b0bd5b4b83/src/lib.rs pub const LED_COUNT: usize = 4; const PI: f32...
use std::{cell, collections::VecDeque}; use super::*; const EPS: f32 = 1e-5; const GRAVITY: f32 = 50.0; const BALL_SWING_DISTANCE: f32 = 0.8; struct Collision { normal: Vec2<f32>, penetration: f32, } #[derive(Clone)] struct Ball { pos: Vec2<f32>, vel: Vec2<f32>, size: f32, stand: bool, } im...
//Copyright 2020 EinsteinDB Project Authors & WHTCORPS Inc. Licensed under Apache-2.0. //! This mod contains components to support rapid data import with the project //! `milevadb-lightning`. //! //! It mainly exposes one service: //! //! The `ImportSSTService` is used to ingest the generated SST files into EinsteinDB...
mod album; mod artist; mod config; mod ctx; mod nav; mod playback; mod playlist; mod promise; mod search; mod track; mod user; mod utils; pub use crate::data::{ album::{Album, AlbumDetail, AlbumLink, AlbumType, Copyright, CopyrightType}, artist::{Artist, ArtistAlbums, ArtistDetail, ArtistLink, ArtistTracks}, ...
// edition:2018 #![feature(async_await)] struct S; impl S { async unsafe fn f() {} } async unsafe fn f() {} async fn g() { S::f(); //~ ERROR call to unsafe function is unsafe f(); //~ ERROR call to unsafe function is unsafe } fn main() { S::f(); //~ ERROR call to unsafe function is unsafe f();...
use std::fs; fn find_pairs_that_sums_up_to(numbers: &[i64], sum: i64) -> Vec<(i64, i64)> { let mut pairs: Vec<(i64, i64)> = Vec::new(); for i in 0..numbers.len() { for l in i + 1..numbers.len() { if numbers[i] + numbers[l] == sum { pairs.push((numbers[i], numbers[l])) ...
//! Types and methods for looking up locations. //! //! Location search for Twitter works in one of two ways. The most direct method is to take a //! latitude/longitude coordinate (say, from a devide's GPS system or by geolocating from wi-fi //! networks, or simply from a known coordinate) and call `reverse_geocode`. T...
extern crate hyper; extern crate libgradr; use hyper::Ipv4Addr; use libgradr::database::postgres_db::PostgresDatabase; use libgradr::notification_listener::{GitHubServer, NotificationSource}; static PORT: u16 = 1337; #[cfg(not(test))] fn main() { let db = PostgresDatabase::new_development().unwrap(); let s...
// 数値型に変換する fn to_int(s: String) -> i64 { s.parse::<i64>().unwrap() } fn main() { proconio::input! { a: String, b: String, } let a_rev = a.chars().rev().collect::<String>(); let b_rev = b.chars().rev().collect::<String>(); let a_len = a.len(); let b_len = b.len(); let...
extern crate bercon; extern crate clap; extern crate crossbeam; extern crate glob; extern crate logwatcher; extern crate regex; use bercon::becommand::BECommand; use bercon::bepackets::RemotePacket; use bercon::rcon::RConClient; use clap::{App, Arg, SubCommand}; use glob::glob; use logwatcher::LogWatcher; use std::sync...
/// Read u64 to from file. /// NOTE! File will be interpreted in the current systems endianness pub unsafe fn read_u64(file: &mut ::std::fs::File) -> Result<u64, ::std::io::Error> { use std::io::Read; let mut elem_size = [0u8; 8]; file.read_exact(&mut elem_size)?; Ok(::std::mem::transmute(elem_size)...
use rustc_span::Symbol; use rustc_target::spec::abi::Abi; use crate::*; use shims::foreign_items::EmulateByNameResult; impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriInterpCx<'mir, 'tcx> {} pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { fn emulate_foreign_item_...
use super::atomic::{Atomic, IntCast}; use crate::types::ValueType; use std::{cell::Cell, marker::PhantomData, ops::Deref, slice}; pub trait Atomicity {} pub struct Atomically; impl Atomicity for Atomically {} pub struct NonAtomically; impl Atomicity for NonAtomically {} pub struct MemoryView<'a, T: 'a, A = NonAtomic...
use point::Point; use data::DataBatch; use ::{Value}; use std::cmp::Ordering; use std::mem::size_of; use std::rc::Rc; use std::cell::RefCell; use failure::{Error,bail,format_err}; use pivots; #[derive(Clone)] pub enum Node<D,P,V> where D: DataBatch<P,V>, P: Point, V: Value { Empty, Branch(Branch<D,P,V>), Data(u6...
use crate::instructions::base::bytecode_reader::BytecodeReader; use crate::instructions::base::instruction::{Instruction, NoOperandsInstruction}; use crate::runtime::frame::Frame; pub struct I2d(NoOperandsInstruction); impl I2d { #[inline] pub const fn new() -> I2d { return I2d(NoOperandsInstruction::...
use amethyst::{assets::Source, Error}; use std::{ convert::TryInto, fs::File, io::{self, Read, Seek}, path::Path, sync::Mutex, time::SystemTime, }; use zip::{ read::{AsciiLowercaseStr, AsciiLowercaseString}, ZipArchive, }; pub struct Pk3Source<R: Read + Seek = File> { modified: u64,...
/// Manipulate and access untrusted memory or functionalities safely mod alloc; mod slice_alloc; mod slice_ext; use super::*; pub use self::alloc::UNTRUSTED_ALLOC; pub use self::slice_alloc::{UntrustedSlice, UntrustedSliceAlloc}; pub use self::slice_ext::{SliceAsMutPtrAndLen, SliceAsPtrAndLen};
/* * @lc app=leetcode.cn id=10 lang=rust * * [10] 正则表达式匹配 */ // @lc code=start impl Solution { pub fn is_match(s: String, p: String) -> bool { let s = s.as_bytes(); let p = p.as_bytes(); let m = s.len(); let n = p.len(); let mut dp: Vec<Vec<bool>> = vec![vec![false;n+1];...
/// Number of Bytes needed to represent UV data. pub const UV_BYTES: i32 = 4; /// Number of Bytes needed to represent Pressure data. pub const PRESSURE_BYTES: i32 = 12; #[derive(Debug, Default)] pub struct Pressure { pub pressure: f32, pub altitude: f32, pub temperature: f32, } /// Number of Bytes needed ...
impl<'de> serde::Deserializer<'de> for crate::Variant<'de> { type Error = VariantDeserializeError; fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: serde::de::Visitor<'de> { #[allow(clippy::match_same_arms)] match self { crate::Variant::Array { element_signature, elements } =>...
fn main() { let x: (i32, f64, u8) = (500, 6.4, 1); let five_hundred = x.0; let six_point_four = x.1; let one = x.2; println!("({}, {}, {})", five_hundred, six_point_four, one); // Functions fn five() -> i32 { 5 } let x = five(); println!("The value of x is: {}", x)...
pub fn triangle_occupancy(out1: f64, in1: f64, out2: f64) -> f64 { 0.5 * in1 * in1 / ((out1 - in1) * (out2 - in1)) } pub fn trapezoid_occupancy(out1: f64, out2: f64, in1: f64, in2: f64) -> f64 { 0.5 * (-in1 / (out1 - in1) - in2 / (out2 - in2)) } pub fn occupancy(d11: f64, d12: f64, d21: f64, d22: f64) -> f64 ...
use pico_args::Arguments; use std::{ io::{Read, Write}, net::{SocketAddr, TcpStream}, process::exit, str::from_utf8, thread::spawn, }; struct Args { help: bool, server: SocketAddr, count: u32, threads: u32, } fn parse_socket_addr(s: &str) -> Result<SocketAddr, &'static str> { m...
// use codec::Encode; // use core::marker::PhantomData; // use iost_chain::IostAction; // use once_cell::sync::Lazy; // sync::OnceCell is thread-safe // use once_cell::sync::OnceCell; // sync::OnceCell is thread-safe // use sp_core::{sr25519::Pair, Pair as TraitPair}; // use std::sync::atomic::{AtomicU32, Ordering}; //...
// This file is part of Substrate. // Copyright (C) Parity Technologies (UK) Ltd. // SPDX-License-Identifier: Apache-2.0 // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.a...
use std::collections::BTreeMap; use std::fs; extern crate regex; use regex::Regex; extern crate lib; use lib::error::Error; const FILENAME: &str = "files/19/input.txt"; #[derive(Debug)] enum Rule { Simple(Vec<usize>), LeftRight(Box<Rule>, Box<Rule>), Char(String), } struct World<'a> { start: usize,...
//! Iterators with a given length and a known quantile point //! //! This module provides iterators of `N` floats with the value `x` for the quantile `q`, where //! `N`, `x` and `q` can be directly controlled. The floats are represented by `NotNan<f64>`, //! because this type implements `Ord`. //! //! The rule respecte...
use crate::irust::options::Options; use std::env; const VERSION: &str = "1.9.0"; pub fn handle_args(options: &mut Options) -> bool { let args: Vec<String> = env::args().skip(1).collect(); if !args.is_empty() { match args[0].as_str() { "-h" | "--help" => { println!( ...
use crate::{error::Error, sql_read_bytes::SqlReadBytes, ColumnData}; pub(crate) async fn decode<R>(src: &mut R) -> crate::Result<ColumnData<'static>> where R: SqlReadBytes + Unpin, { let recv_len = src.read_u8().await? as usize; let res = match recv_len { 0 => ColumnData::Bit(None), 1 => C...
use super::*; pub struct RandomQsc { desired_quorum_set_size: usize, desired_threshold: Option<usize>, weights: Vec<usize>, } impl RandomQsc { pub fn new( desired_quorum_set_size: usize, desired_threshold: Option<usize>, weights: Option<Vec<usize>>, ) -> Self { Rando...
use super::{ quad::{OrientedCubeFace, UnorientedQuad}, IsOpaque, }; use building_blocks_core::{prelude::*, Axis3Permutation}; use building_blocks_storage::dev_prelude::*; /// Contains the output from the `greedy_quads` algorithm. The quads can be used to generate a mesh. See the methods on /// `OrientedCubeFa...
extern "C" { fn set_progress(prog: f32); fn console_log(ptr: *const u8, length: u32); fn get_random(ptr: *const u8, length: u32); } pub fn get_seed() -> [u8; 16] { let seed = [0; 16]; unsafe { get_random(seed.as_ptr(), seed.len() as u32); } seed } pub fn log(s: &str) { unsafe { console_log(s.as_ptr(), s.len...
use crate::readers::Index; use super::StreamingIndexIterator; #[derive(Debug)] pub struct KnownSizeRefIter<'a> { // |lowerbounds| = |upperbounds| = |step| = |index| // |unfrozen_dims| < |index| // unfrozen_dims is in reverse order lowerbounds: &'a Vec<usize>, upperbounds: &'a Vec<usize>, steps: &'a Vec<usi...
use wasm_bindgen::prelude::*; use wasm_bindgen::JsValue; use web_sys; #[wasm_bindgen(start)] pub fn main() { print("main()"); } #[wasm_bindgen] pub fn print(name: &str) { web_sys::console::log_1(&JsValue::from_str(name)); } #[wasm_bindgen] pub fn fibonacci(n: u32) -> u32 { match n { 0 => 0, ...
use serde_json::Number; use joker::token::{StringLiteral, NumberLiteral, NumberSource}; pub trait IntoStringLiteral { fn into_string_literal(self) -> StringLiteral; } impl IntoStringLiteral for String { fn into_string_literal(self) -> StringLiteral { StringLiteral { source: None, ...
#![deny(unsafe_code)] #![deny(warnings)] #![allow(intra_doc_link_resolution_failure)] #![deny(missing_docs)] #![deny(missing_debug_implementations)] #![doc(test(attr(allow(unused_variables), deny(warnings))))] // enable no_std if feature "std" isn't present #![cfg_attr(not(feature = "std"), no_std)] #![allow( clipp...
struct Solution {} impl Solution { pub fn count_prime_set_bits(l: i32, r: i32) -> i32 { let mut result = 0; let candidates = vec![2, 3, 5, 7, 11, 13, 17, 19]; for mut n in l..=r { let mut b = 0; while n > 0 { b += n & 1; n = n >> 1; ...
pub mod hetzner; pub mod digital_ocean;
struct Solution; use std::collections::HashMap; #[allow(dead_code)] impl Solution { pub fn two_sum(nums: Vec<i32>, target: i32) -> Vec<i32> { let mut map: HashMap<i32, i32> = HashMap::new(); for (i, var) in nums.into_iter().enumerate() { if let Some(another_index) = map.get(&var) { ...
// * Daily Coding Problem May 15th 2021 // * [Medium] -- Uber // * Implement a 2D iterator class. It will be initialized with an array of arrays, and should implement the following methods: // next(): returns the next element in the array of arrays. If there are no more elements, raise an exception. // has_next(): r...
use chrono::{DateTime, Utc}; use serde::{Deserialize, Serialize}; use serde_json::Value; use std::collections::HashMap; #[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] pub struct KeyVaultErrorMessage { pub error: KeyVaultError, } #[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] pub st...
use std::io; use std::io::prelude::*; pub fn user_input(input: &mut String) -> io::Result<usize> { print!(">._.< "); let _ = io::stdout().flush(); let mut tmp_in = String::new(); let res = io::stdin().read_line(&mut tmp_in); match res { Ok(_) => { tmp_in.retain(|c| !c.is_whites...
// Copyright 2022 Datafuse Labs. // // 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 ...
#[doc = "Register `CRCCNF` reader"] pub struct R(crate::R<CRCCNF_SPEC>); impl core::ops::Deref for R { type Target = crate::R<CRCCNF_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<CRCCNF_SPEC>> for R { #[inline(always)] fn from(reader: crate::R...
use clap::ArgMatches; use std::io; use std::rc::Rc; use svm_gas::{resolvers::ExampleResolver, ProgramPricing}; use svm_program::{Program, ProgramVisitor}; use crate::Error; pub fn clap_app_validate() -> clap::App<'static> { use clap::*; App::new("validate") .about("Runs validation logic on a smWasm...
use image::Rgb; use image::RgbImage; use rusttype::{point, Font, PositionedGlyph, Scale}; fn get_args() -> (String, String) { let ver = env!("CARGO_PKG_VERSION"); let args = clap::App::new("text-to-image") .arg( clap::Arg::with_name("text") .long("text") .sho...
#![cfg_attr(feature = "external_doc", feature(external_doc))] #![cfg_attr(feature = "external_doc", doc(include = "../readme.md"))] #![feature(drain_filter)] #[macro_use] extern crate log; mod config; mod errors; pub(in crate) mod nm; mod portal; mod state_machine; mod utils; mod dhcp_server; mod dns_server; mod htt...
fn fuel_required(mass: i32) -> i32 { let naive = ((mass as f64 / 3.0).floor() - 2.0) as i32; if naive < 0 { 0 } else { naive } } fn total_fuel_required(mass: i32) -> i32 { let mut total_fuel_required = 0; let mut mass_left = mass; loop { mass_left = fuel_required(mas...
use crate::entity_id::EntityId; use core::iter::Map; #[allow(missing_docs)] pub struct WithId<I>(pub I); /// Creates iterator returning [`EntityId`]. /// /// [`EntityId`]: crate::entity_id::EntityId pub trait IntoWithId { /// Makes the iterator return the [`EntityId`] in addition to the component. /// ///...
use std::fs; use std::collections::VecDeque; use std::iter::FromIterator; use std::collections::HashMap; trait IParser { fn parse(line: &str) -> Self; } struct TimeStamp { year: i32, month: i32, day: i32, hour: i32, minute: i32, id: i32, sleep: bool, line: String, } impl TimeS...
fn main() { let mut n = default(); scanf!("{:usize}", &mut n); let s = &mut vec![default(); n]; for e in List::iter_mut(s) { scanf!("{:u}", e); } let mut q = default(); scanf!("{:u}", &mut q); let mut count: usize = 0; for _ in 0..q { let mut t = default(); ...
use super::*; /// Fallback to application by application #[derive(Debug, Clone)] pub struct SimpleApplication<P>(std::marker::PhantomData<P>); impl<P> Default for SimpleApplication<P> { fn default() -> Self { SimpleApplication(std::marker::PhantomData::default()) } } impl<P> Action<P> for SimpleAppli...
use std::collections::HashMap; use std::io; use std::io::Read; fn main() { let mut input = String::new(); let _ = io::stdin().read_to_string(&mut input); println!("{}", severity(&input.trim())); } const DOWN: bool = false; const UP: bool = true; fn severity(input: &str) -> usize { let mut layers = Ha...
mod char_iter; mod token; use std::collections::VecDeque; use std::str::CharIndices; use char_iter::CharIter; pub use token::SyntaxKind; use SyntaxKind::*; #[derive(Debug)] pub struct Lexer<'a> { chars: CharIter<'a>, } impl<'a> Lexer<'a> { pub fn new(input: &str) -> Lexer<'_> { Lexer { c...
use serde::{Deserialize, Serialize}; #[derive(Deserialize)] pub struct CreateSystemAdminUserRequest { #[serde(rename = "loginId")] pub login_id: String, pub password: String, #[serde(rename = "roleIds")] pub role_ids: Vec<String>, } #[derive(Serialize)] pub struct UserDto { pub id: String, #[serde(renam...
// This file is part of Substrate. // Copyright (C) Parity Technologies (UK) Ltd. // SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Softwa...
use std::ffi::OsStr; use std::path::{Path, PathBuf}; use std::sync::{Arc, RwLock}; use actix_web::http::StatusCode; use actix_web::{ App, Body, HttpRequest, HttpResponse, Json, Path as PathExtractor, Query, Result, State, }; use tinyfiledialogs::{open_file_dialog, select_folder_dialog}; use yore::Coordinates; use...
#![cfg_attr(not(feature = "std"), no_std)] use frame_support::{decl_event,decl_module,decl_storage,ensure,decl_error,dispatch::{DispatchResult},codec::{Encode,Decode}}; use frame_system::{ensure_signed}; //use serde_json::{json}; use frame_support::traits::Vec; use frame_support::sp_runtime::RuntimeDebug; use frame_sup...
struct Button; struct Props { label: Option<String>, } impl Props { pub fn label(mut self, value: String) -> Self { self.label = value.into(); self } } struct State { hovered: bool, } enum Msg { TouchMoved { inside: bool }, Touched, } enum Event { Action { count: usize }...
pub mod color_util; pub mod text_canvas; pub mod conversions; pub mod icon_spline; #[cfg(test)] pub mod test_util;
pub struct Tree { id: u32, l: u32, r: u32, d: u32, value: f64, } pub fn build_tree() -> Vec<Tree> { let mut tree: Vec<Tree> = vec![]; tree }
extern crate ocl; use ocl::{util, core, ProQue, Buffer}; // Number of results to print out: const RESULTS_TO_PRINT: usize = 20; // Our arbitrary data set size and coefficent: const DATA_SET_SIZE: usize = 2 << 20; const COEFF: f32 = 5432.1; // Our kernel source code: static KERNEL_SRC: &'static str = r#" __kerne...
use std::marker::PhantomData; #[derive(Clone)] pub struct ComponentType<T> { pub(crate) index: usize, i_love_pizza: PhantomData<T> } impl<T> ComponentType<T> { pub(crate) fn new(index: usize) -> Self { Self { index, i_love_pizza: PhantomData } } }
use hyper::http::{Response, header, StatusCode}; use hyper::Body; use crate::INTERNAL_SERVER_ERROR; async fn api_get_response() -> crate::Result<Response<Body>> { let data = vec!["foo", "bar"]; let res = match serde_json::to_string(&data) { Ok(json) => Response::builder() .header(header::CO...
use crate::shared::usecase::{execute, UseCase}; use crate::{error::NettuError, user::parse_vec_query_value}; use actix_web::{web, HttpRequest, HttpResponse}; use futures::future::join_all; use nettu_scheduler_api_structs::get_service_bookingslots::*; use nettu_scheduler_domain::{ booking_slots::{ get_servic...
// This file is part of Substrate. // Copyright (C) Parity Technologies (UK) Ltd. // SPDX-License-Identifier: Apache-2.0 // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.a...
#![feature(plugin_registrar, if_let)] extern crate rustc; extern crate syntax; use rustc::plugin::Registry; use syntax::ast::{ DUMMY_NODE_ID, EnumDef, Ident, Item, ItemMod, ItemEnum, Mod, MetaItem, MetaWord, MetaList, PathParameters, PathSegment, ViewItem, ViewItemUse, ViewPathList, PathListIdent, ...
const SDF1 : &str = r#"{ "Page": "start", "Revision": "000000000", "PreviousRevision": "000000000", "CreateDate": "2018/05/05 19:53:05.248-07:00", "RevisionDate": "2018/05/05 19:53:05.248-07:00", "RevisedBy": "user", "Comment": "" } <!--REVISION HEADER DEMARCATION> "#; const SDF2 : &str = r#"{ "Page"sdf2: "_us...
// Copyright (c) The Starcoin Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::block::{Block, BlockHeaderExtra, ExecutedBlock}; use crate::sync_status::SyncStatus; use crate::U256; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use starcoin_crypto::HashValue; use starcoin_vm_types::g...
use crate::{issuer,subject}; #[derive(Debug, Clone)] pub struct Builder { pub issuer:issuer::Issuer, pub subject:subject::Subject, pub certificate_path:String, pub key_path:String, pub key_size:u32 } impl Builder { pub fn new() -> Builder { Builder { issuer:issuer::Issuer::...
#[cfg(feature="jit")] fn main() { extern crate packed_simd; use bullet::packed_simd::jit; use bullet::prelude::Builder; use packed_simd::f32x8; let b = Builder::new(); let f = b.parse("x+1").unwrap(); let g = b.parse("x-1").unwrap(); let c = jit(&[f, g], &["x"]).unwrap(); for n in ...
#[allow(unused_imports)] use serde_json::Value; #[derive(Debug, Serialize, Deserialize)] pub struct StoragepoolNodepoolExtended { /// Indicates if enabling L3 is possible. L3 cannot be enabled if there are unprovisioned drives. #[serde(rename = "can_enable_l3")] pub can_enable_l3: bool, /// An array of...
use std::io::Write; use bytes::Bytes; use message::bencode; use std::io; use bip_bencode::{BDecodeOpt, BencodeRef, BConvert}; const REQUEST_MESSAGE_TYPE_ID: u8 = 0; const DATA_MESSAGE_TYPE_ID: u8 = 1; const REJECT_MESSAGE_TYPE_ID: u8 = 2; const ROOT_ERROR_KEY: &'static str = "PeerExtensionProtocolMessage"; /// ...
//! //! Variables in `Rust` //! //! Binding values to a variable name through `Rust` keyword `let` //! //! # Example //! //! ```rust //! let x = 5; //! //! let (x, y) = (1, 2); //! //! let x: i32 = 5; //! ``` //! //! Basically `Rust` variables are immutable bindings of value by default. //! If you want to change or upd...
use std::io::prelude::*; use std::fs::File; use std::collections::HashMap; use regex::Regex; type Grid = HashMap<(u32, u32), u32>; #[derive(Debug)] struct Claim { id: u32, x: u32, y: u32, width: u32, height: u32, } impl Claim { fn iter_claim(&self) -> IterClaim { IterClaim { ...
//! [`MatchData#offset`](https://ruby-doc.org/core-2.6.3/MatchData.html#method-i-offset) use artichoke_core::value::Value as ValueLike; use std::convert::TryFrom; use crate::convert::{Convert, RustBackedValue}; use crate::extn::core::exception::{Fatal, RubyException, TypeError}; use crate::extn::core::matchdata::Matc...
/** * FIBONACCI Calculator * required the user to enter a positive int value to be parse and the * fibonacci value will be given */ pub mod fibonacci { use std::io; pub fn main() { let mut user_val = String::new(); println!("Enter a number to get the Fibonacci value for:"); io::st...