text
stringlengths
8
4.13M
extern crate rustc_serialize; extern crate toml_config; use std::path::Path; use self::toml_config::ConfigFactory; #[derive(RustcDecodable, RustcEncodable)] pub struct Config { pub redis: RedisConfig, pub server: ServerConfig, pub source: SourceConfig, } impl Config { pub fn redis_url(&self) -> Strin...
use tui::Terminal; use tui::backend::CrosstermBackend; use std::io::Stdout; use crate::runtime::data::launches::structures::{Launch, Rocket}; use tui::layout::{Layout, Direction, Constraint, Alignment}; use tui::widgets::{Clear, Block, Borders, Paragraph, Table, Row}; use tui::text::Text; use crate::runtime::renderer::...
use proptest::prelude::*; use unicode_segmentation::*; proptest! { #[test] fn frequencies(input in any::<String>()) { let freqs = huffman_encoding::frequencies(input.as_str()); let graphemes = UnicodeSegmentation::graphemes(input.as_str(), true).collect::<Vec<&str>>(); // The sum of the...
use std::borrow::Borrow; use std::path::PathBuf; use std::process::Command; use std::str; use serde_json::Value; #[derive(Debug)] pub struct VideoFile { pub path: String, pub streams: Vec<CodecStream>, } #[derive(Debug)] pub struct CodecStream { pub codec_name: String, pub codec_type: String, pub...
#![allow(dead_code)] use std::ascii; use std::str; use bstr::{ByteSlice, ByteVec}; pub fn nice_raw_bytes(bytes: &[u8]) -> String { match str::from_utf8(bytes) { Ok(s) => s.to_string(), Err(_) => escape_bytes(bytes), } } pub fn escape_bytes(bytes: &[u8]) -> String { let escaped = bytes ...
/*! Redis Serialization Protocol相关的解析代码 */ use std::io::{Read, Result}; use byteorder::ReadBytesExt; use crate::to_string; /// Redis Serialization Protocol解析 pub trait RespDecode: Read { /// 读取并解析Redis响应 fn decode_resp(&mut self) -> Result<Resp> { match self.decode_type()? { Type::String...
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)]...
use std::fmt; use std::sync::Arc; use std::sync::Mutex; use std::time::Duration; use backend::*; use output_log::*; use output_state::*; #[ derive (Clone) ] pub struct Output { state: Arc <Mutex <OutputState>>, prefix: String, notice: bool, debug: bool, } impl Output { #[ inline ] pub fn new ( backend: Opti...
pub fn demo() { // let v = Vec!{1,2,3} // println!(v) }
pub fn is_armstrong_number(num: u32) -> bool { let digits = get_digits(num); let len = digits.len() as u32; let armstrong_number: u32 = digits .into_iter() .map(|x| x.pow(len)) .sum(); armstrong_number == num } fn get_digits(num: u32) -> Vec<u32> { let mut digits: Vec<u32>...
extern crate rand; use rand::Rng; use std::fmt; type IP = (u8, u8, u8, u8); trait Printable { fn print(&self) -> (); } impl Printable for IP { fn print(&self) { let (o0, o1, o2, o3) = *self; println!("{}.{}.{}.{}", o0, o1, o2, o3); } } pub struct UUID { data: [u8; 16], } impl fmt::...
//! # commands //! //! All command implementations. use std::{ fs::create_dir, path::PathBuf }; use config::RuntimeConfig; use pipeline::Pipeline; use prettytable::Table; use wordpress::Plugin; /// Get all plugins which are being managed. pub fn get_managed_plugins(config: &RuntimeConfig) -> Vec<Plugin> { ...
//! Contains functionality particular to the BCM2837 board. //! //! There is no published documenation for the BCM2837 board in particular, but a lot of the //! specifications are similar to the [BCM2835] and [BCM2836]. //! //! [BCM2835]: https://www.raspberrypi.org/documentation/hardware/raspberrypi/bcm2835/BCM2835-AR...
use crate::{ domain, interface::{BlockHeight, BlockTimestamp, EpochHeight}, }; use near_sdk::serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] #[serde(crate = "near_sdk::serde")] pub struct BlockTimeHeight { pub block_height: BlockHeight, pub block_timestamp: B...
use std::io::{Error, ErrorKind}; use paho_mqtt::{AsyncClient, Message}; use serde_json::from_str; use crate::external_interface::announce_blackbox; use crate::mqtt_broker_manager::{REGISTERED_TOPIC, UNREGISTERED_TOPIC}; use super::structs::{Command, CommandType}; /** * Converts the `Command` struct to a string t...
use std::fmt::Debug; use async_trait::async_trait; use data_types::sequence_number_set::SequenceNumberSet; use tokio::sync::watch::Receiver; use wal::WriteResult; use crate::dml_payload::IngestOp; /// An abstraction over a write-ahead log, decoupling the write path from the /// underlying implementation. pub(super) ...
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. mod remote_client; mod utils; use { crate::{ buffer::{BufferProvider, OutBuf}, device::{Device, TxFlags}, error::Error, ...
// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. pub fn parse_http_generic_error( response: &http::Response<bytes::Bytes>, ) -> Result<smithy_types::Error, smithy_xml::decode::XmlError> { crate::ec2_query_errors::parse_generic_error(response.body().as_ref()) } #[allow(unused_mut...
use crate::desktop::{Desktop, DesktopMode}; pub struct Monitor { pub name: String, pub alias: Option<String>, desktops: Vec<Desktop>, } impl Monitor { pub fn new(name: String) -> Self { let mut monitor = Self { name, alias: None, desktops: Vec::new(), ...
use actix_web::{web, App, HttpResponse, HttpServer, Responder}; use serde::{Serialize, Deserialize}; static NACOS_SERVER: &str = "http://127.0.0.1:8848/nacos"; static PROVIDER_NAME: &str = "rust-microservice"; static PROVIDER_HOST: &str = "127.0.0.1"; static PROVIDER_PORT: i32 = 8080; mod nacos; #[derive(Serialize, ...
#![allow(dead_code)] #![allow(unused_variables)] use is_executable::IsExecutable; use std::env::var_os; use std::path::Path; pub struct WinowManager { name: String, command: String, commment: String, exists: bool, } pub type WinowManagerList = Vec<WinowManager>; pub fn get_wm_list(available: Option<boo...
use std::{path::PathBuf, str::FromStr}; use anyhow::Result; use serde_derive::Deserialize; use sqlx::{Connection, ConnectOptions}; use sqlx::sqlite::SqliteConnectOptions; use structopt::StructOpt; use tokio::{self, fs::File, io::AsyncReadExt}; #[derive(Debug, StructOpt)] #[structopt(name = "list_servants")] struct Op...
use bindgen; use build; use console::style; use emoji; use error::Error; use indicatif::HumanDuration; use manifest; use npm; #[allow(unused)] use quicli::prelude::*; use readme; use std::fs; use std::result; use std::time::Instant; use PBAR; #[derive(Debug, StructOpt)] pub enum Command { #[structopt(name = "init"...
pub use VkPipelineDynamicStateCreateFlags::*; #[repr(u32)] #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum VkPipelineDynamicStateCreateFlags { VK_PIPELINE_DYNAMIC_STATE_CREATE_NULL_BIT = 0, } use crate::SetupVkFlags; #[repr(C)] #[derive(Clone, Copy, Eq, PartialEq, Hash)] pub struct VkPipelineDynamicStateCr...
//! Controller widgets use druid::widget::prelude::*; use druid::{InternalLifeCycle, LensExt, Rect, WidgetExt, WidgetPod}; use crate::consts; use crate::data::EditorState; use crate::edit_session::EditSession; use crate::widgets::{CoordPane, FloatingPanel, GlyphPane, Toolbar}; /// the distance from the edge of a flo...
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use std::fmt::{self, Display, Formatter}; use std::ops::Deref; // NOTE: The "witness" types UnicastAddr and MulticastAddr - which provide the // invariant...
#[path = "with_empty_list_arguments/with_loaded_module.rs"] mod with_loaded_module; test_substrings!( without_loaded_module_when_run_exits_undef_and_parent_does_not_exit, vec!["{parent, alive, true}"], vec!["Process (#PID<0.3.0>) exited abnormally.", "undef"] );
use super::{ object_heap::{ function::HeapFunction, hir_id::HeapHirId, int::HeapInt, list::HeapList, struct_::HeapStruct, tag::HeapTag, text::HeapText, HeapData, HeapObject, }, object_inline::{ builtin::InlineBuiltin, int::InlineInt, port::{InlineReceivePort, InlineSe...
pub type Result<T> = std::result::Result<T, Error>; #[derive(Debug)] pub enum ErrorKind { IoError(std::io::Error), Utf8Error(std::str::Utf8Error), Other(String), } #[derive(Debug)] pub struct Error { kind: ErrorKind, } impl Error { pub fn new<T>(kind: T) -> Error where T: Into<ErrorKind>...
use n3_machine_ffi::{Machine, Program, SignalHandler, WorkHandler, WorkStatus}; use n3_torch_ffi::PyMachine; pub struct PyMachineBase<T> where T: PyMachine + 'static, { inner: T, handler: Option<WorkHandler>, } impl<T> PyMachineBase<T> where T: PyMachine + 'static, { pub fn new(inner: T) -> Self {...
use gl; use std; use std::ffi::{CString, CStr}; use std::collections::HashMap; use std::cell::RefCell; #[derive(Debug)] pub struct ShaderPart { id: u32, } impl ShaderPart { pub fn from_source(source: &CStr, kind: gl::types::GLenum) -> Result<ShaderPart, String> { let id = shader_from_source(source, ki...
use rand::{thread_rng, Rng}; /// room number as usize so it can index into the map. pub type RoomNum = usize; pub const NUM_OF_ROOMS: RoomNum = 20; /// The game map in Hunt the Wumpus is laid out as a dodecahedron. The vertices /// of the dodecahedron are considered rooms, and each room has 3 adjacent rooms. /// A r...
pub const NET_PORT: u16 = 32870; use std::net::UdpSocket; /// Opens UDP socket for client on a random open port. pub fn open_client_socket() -> std::io::Result<UdpSocket> { UdpSocket::bind("0.0.0.0:0") } /// Opens UDP socket for server on configured port. pub fn open_server_socket() -> std::io::Result<UdpSocket>...
use clap::{App, Arg, ArgMatches, SubCommand}; pub fn get_matches() -> ArgMatches<'static> { let file_arg = Arg::with_name("file") .short("f") .long("file") .takes_value(true) .required(true) .value_name("file name") .help("The file name (required)"); let collect...
use mini_core::Sync; pub struct Struct3 { pub field1: &'static [u8], pub field2: i32, } unsafe impl Sync for Struct3 {} pub static STRUCT3: Struct3 = Struct3 { field1: b"level1", field2: 1, };
#![allow(dead_code)] //! Standard clipboard formats. //! //! Header: Winuser.h //! //! Description is taken from [Standard Clipboard Formats](https://msdn.microsoft.com/en-us/library/windows/desktop/ff729168%28v=vs.85%29.aspx) ///A handle to a bitmap (HBITMAP). pub const CF_BITMAP: u32 = 2; ///A memory object containi...
use gio::prelude::*; use gtk::prelude::*; use rt_graph::{ConfigBuilder, GraphWithControls, TestDataGenerator}; use std::{ env::args, }; fn main() { env_logger::init(); let application = gtk::Application::new(Some("com.github.fluffysquirrels.rt-graph.gtk-example"), gio:...
use game_lib::bevy::prelude::*; use std::ops::{Add, AddAssign, Sub, SubAssign}; #[derive(Clone, Copy, PartialEq, Debug, Default, Reflect)] #[reflect(Component)] pub struct AxisAlignedBoundingBox { bottom_left: Vec2, size: Vec2, } impl AxisAlignedBoundingBox { pub fn new(bottom_left: Vec2, size: Vec2) -> S...
#![allow(dead_code)] use near_sdk::{serde_json::json, AccountId, PendingContractTx}; use near_sdk_sim::*; use oysterpack_near_stake_token::{ domain::{Gas, YoctoNear}, interface::{Config, ContractBalances}, }; pub struct FinancialsClient { contract_account_id: AccountId, } impl FinancialsClient { pub ...
use procon_reader::ProconReader; fn main() { let stdin = std::io::stdin(); let mut rd = ProconReader::new(stdin.lock()); let n: usize = rd.get(); let t: Vec<usize> = rd.get_vec(n); macro_rules! chmin { ($a: expr, $b: expr) => { $a = std::cmp::min($a, $b); }; } ...
use game_lib::bevy::{ prelude::*, reflect::Reflect, render::camera::{CameraProjection, DepthCalculation, WindowOrigin}, }; #[derive(Debug, Clone, Reflect)] #[reflect(Component)] pub struct ScaledOrthographicProjection { /// Automatically calculated from zoom. pub left: f32, /// Automatically c...
mod blog; mod blog_clusters; mod hlf_parser; mod shared; /** * Auto matically convert raw markdown blogs to my serveral blog web pages */ mod tag; mod template_blog; mod template_cluster; mod template_homepage; use blog_clusters::BlogClusters; use shared::HTMLTemplate; use template_blog::BlogTemplate; use template_c...
pub struct ProconReader<R: std::io::Read> { reader: R, } impl<R: std::io::Read> ProconReader<R> { pub fn new(reader: R) -> Self { Self { reader } } pub fn get<T: std::str::FromStr>(&mut self) -> T { use std::io::Read; let buf = self .reader .by_ref() ...
//! A map backed by contract storage. use std::{convert::TryInto, marker::PhantomData}; use oasis_contract_sdk::{storage::Store, types::address::Address}; use crate::cell::Cell; /// A map backed by contract storage. pub struct Map<'key, K, V> { /// Unique map identifier. key: &'key [u8], _key: PhantomDa...
use aes::Aes256; use block_modes::Cbc; use block_modes::{BlockMode, BlockModeError}; use rand::Rng; use block_modes::block_padding::Pkcs7; use sha2::{Sha256, Digest}; type Aes256Cbc = Cbc<Aes256, Pkcs7>; /// This function takes in a password and data, encrypting using AES256. Returns (ciphertext, iv). pub f...
use liblumen_alloc::erts::exception::InternalResult; use liblumen_alloc::erts::term::prelude::*; use liblumen_alloc::erts::Process; use super::f64; pub fn decode<'a>(process: &Process, bytes: &'a [u8]) -> InternalResult<(Term, &'a [u8])> { let (f, after_f_bytes) = f64::decode(bytes)?; let float = process.floa...
//! Reference following avoids reference expressions by replacing their usages //! with original referenced value. //! //! Here's a before-and-after example: //! //! ```mir //! $0 = Foo | $0 = Foo //! $1 = $0 | $1 = $0 //! $2 = call ... with $1 | $2 = call ... with $0 //! ``` //! //! Th...
//! Implementation of Finite State Automata in both Nondeterministic and Deterministic forms, //! together with a set of conversions, processing, analysis, and visualization utilities. #![warn(missing_copy_implementations)] #![warn(missing_debug_implementations)] #![warn(trivial_casts)] #![warn(trivial_numeric_casts)]...
extern crate jlib; use jlib::api::ipfs::hash::only_hash; use std::fs::File; use std::io::prelude::*; fn big_file_hash() { // let mut f = File::open("/mnt/c/Users/zTgx/Desktop/github.com.c/ipfs/1.png").unwrap(); let mut f = File::open("/mnt/c/Users/zTgx/Desktop/github.com.c/ipfs/1.jpg").unwrap(); ...
// Copyright 2017 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. //! Bindings for the Zircon fdio library #[allow(bad_style)] pub mod fdio_sys; use { ::bitflags::bitflags, fidl_fuchsia_device::ControllerSynchro...
//! General Purpose Input/Output use core::marker::PhantomData; use crate::pac; /// Extension trait to split GLB peripheral into independent pins, registers and other modules pub trait GlbExt { /// Splits the register block into independent pins and modules fn split(self) -> Parts; } pub use uart_sig::*; //...
use std::marker::PhantomData; use num::traits::NumAssignRef; use num::integer::Integer; use super::checker::PrimeChecker; use extra_ops::{ModPow, RandInt}; pub struct MillerRabinChecker<N> { witnessess: usize, _phantom: PhantomData<N> } impl<N> MillerRabinChecker<N> { pub fn new(witnessess: usize) -> S...
#[cfg(all(not(target_arch = "wasm32"), test))] mod test; use liblumen_alloc::erts::exception; use liblumen_alloc::erts::process::Process; use liblumen_alloc::erts::term::prelude::Term; use crate::erlang::charlist_to_string::charlist_to_string; use crate::erlang::string_to_float::string_to_float; #[native_implemented...
use wasm_bindgen::prelude::*; #[wasm_bindgen] extern { #[wasm_bindgen(js_namespace = console)] fn log(s: &str); fn func1(s: &str); } #[wasm_bindgen(module = "/src-js/func.js")] extern { fn func2(s: &str); } #[wasm_bindgen] pub fn run(msg: &str) { log(msg); func1(msg); func2(msg); }
use super::*; pub fn login_config(cfg: &mut web::ServiceConfig) { cfg.service(do_login_phone) .service(do_login_refresh) .service(do_login_status) .service(do_logout); } #[get("/login")] async fn do_login(req: HttpRequest, stream: web::Payload) -> Result<HttpResponse, Error> { let mut ...
///! Filter code generation. use crate::ir; use crate::print; use crate::print::ast::{self, Context}; use crate::print::value_set; use log::trace; use proc_macro2::{Ident, Span, TokenStream}; use quote; use serde::Serialize; use utils::unwrap; /// Ast for a filtering funtion. #[derive(Serialize)] pub struct Filter<'a...
#![feature(try_blocks)] #[macro_use] extern crate clap; use clap::{App, Arg}; use rusoto_core::Region; use std::collections::HashMap; use std::fs::{File, OpenOptions}; use std::io::BufReader; use std::io::{self, prelude::*}; use std::{fmt, thread, time}; use tsunami::*; const AMI: &str = "ami-04db1e82afa245def"; #[...
// Copyright 2020 IOTA Stiftung // // 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 in w...
use alloc::string::String; use alloc::vec::Vec; #[derive(Debug, PartialEq)] pub struct Abi { pub version: String, pub types: Vec<AbiType>, pub structs: Vec<AbiStruct>, pub actions: Vec<AbiAction>, pub tables: Vec<AbiTable>, pub ricardian_clauses: Vec<AbiRicardianClause>, pub error_messages:...
mod hpa_map; pub use self::hpa_map::HPAMap; mod inter_link; pub use self::inter_link::{InterLink, LinkId}; mod chunk; pub use self::chunk::{Chunk, CHUNK_SIZE};
use crate::model::map::Gold; use crate::model::map::MapSection; use crate::model::miner::MinerId; pub type RoundResults = (MinerId,Gold,Gold); #[derive(Debug, Clone)] pub enum MiningMessage { Start(MapSection), Stop, ResultsNotification(RoundResults), ILeft(MinerId), TransferGold(Gold), ByeBye...
mod front_of_house; mod back_of_house { use crate::front_of_house::serving::take_payment; pub fn fix_incorrect_order() { super::front_of_house::serving::serve_order(); take_payment(); } } pub use back_of_house::fix_incorrect_order; pub fn eat_at_restaurant() { front_of_house::hosting::...
use std::ascii::AsciiExt; use std::borrow::ToOwned; use std::env; use std::fs; use std::io::{self, Read}; use std::ops::Deref; use std::path::PathBuf; use csv; use csv::index::Indexed; use rustc_serialize::{Decodable, Decoder}; use CliResult; use select::{SelectColumns, Selection, NormalSelection}; use util; #[deri...
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
enum CanNeverExist {} fn never_returns() -> CanNeverExist { CanNeverExist {} } fn main() { let value = never_returns(); }
// 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 ...
// Copyright © 2016-2017 VMware, Inc. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 use std::collections::HashMap; use rabble::{self, Pid, Envelope, ConnectionMsg, ConnectionHandler, CorrelationId}; use msg::Msg; use super::messages::{AdminMsg, AdminReq, AdminRpy}; /// The connection handler for Admin C...
use libc::{c_char, c_int}; pub type AssertCB = unsafe extern "C" fn(*const c_char, c_int, *const c_char); #[link(name = "kernaux")] extern "C" { #[link_name = "kernaux_assert_do"] pub fn assert_do(file: *const c_char, line: c_int, msg: *const c_char); #[link_name = "kernaux_assert_cb"] pub static mut...
use P36::prime_factor_multiplicity; pub fn totient(n: u32) -> u32 { let prime_factors = prime_factor_multiplicity(n); prime_factors .iter() .fold(1, |acc, (p, m)| acc * (p - 1) * p.pow(m - 1)) } #[cfg(test)] mod tests { use super::*; #[test] fn test_totient() { assert_eq!(t...
// Copyright 2018 TAP, Inc. All Rights Reserved. extern crate ws; extern crate lazy_static; use std::sync::Mutex; use std::env; lazy_static::lazy_static! { static ref SENDERS: Mutex<Vec<ws::Sender>> = Mutex::new(Vec::new()); } struct EchoHandler { me: ws::Sender, } impl ws::Handler for EchoHandler { fn on_me...
use arrow::record_batch::RecordBatch; use mutable_batch::MutableBatch; use schema::Projection; /// A [`Buffer`] is an internal mutable buffer wrapper over a [`MutableBatch`] /// for the [`BufferState`] FSM. /// /// A [`Buffer`] can contain no writes. /// /// [`BufferState`]: super::BufferState #[derive(Debug, Default)...
use crate::error::{Error, Result}; use parquet::record::{Field, Row}; use serde::de::{self, Deserialize, Visitor}; use serde::forward_to_deserialize_any; type KeyVal<'de> = (Value<'de>, Value<'de>); #[derive(Clone, Debug, PartialEq)] enum Value<'de> { Name(&'de str), Field(&'de Field), Seq(Vec<KeyVal<'de>...
#[macro_use] extern crate fail; mod imp; mod rpc; #[cfg(test)] mod tests; use jsonrpc_core::{self, Result}; use jsonrpc_derive::rpc; use crate::rpc::Rpc; pub struct StorageBuilder; impl StorageBuilder { pub fn build(rpc: Rpc) -> impl Store { imp::MemoryStorage::new(rpc) // unimplemented!() ...
#[macro_export] macro_rules! fs_fn { ( $( #[$meta:meta] )* fn $test_name:ident $params:tt ($test_dir:ident) -> $return:ty $body:block ) => { $( #[$meta] )* fn $test_name $params -> $return { let $test_dir = test_dir::TestDir::new(); let res = $block ...
#![allow(dead_code)] // https://www.techiedelight.com/huffman-coding/ use std::cmp::Ordering; use std::collections::BinaryHeap; use std::collections::HashMap; use std::fmt; use std::cmp::Reverse; // Used for min heap, this fixed all my problems with all nodes on the left lol #[derive(Debug, Clone)] pub struct HuffCode...
use enumset::EnumSet; use super::{ast::AstError, cst, cst::CstError, hir::HirError}; use crate::{ mir::MirError, module::Module, position::{Offset, PositionConversionDb}, rich_ir::{ReferenceKey, RichIrBuilder, ToRichIr}, string_to_rcst::ModuleError, }; use derive_more::From; use itertools::Itertool...
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
// `last` menerima input iter dan menghasilkan `Option<T>` elemen terakhir fn main() { let a = [1, 2, 3]; assert_eq!(a.iter().last(), Some(&3)); // output `a.iter().last()`: Some(&3) }
use hackscanner_lib::*; use simplelog::TerminalMode; /// Assert that the `ratings` contain a Rating with the path matching `path` and a rating matching `score` /// /// If `equals_score` is `true` the rating has to exactly equal `score`, otherwise it can also be bigger fn assert_contains_entry_with_score( ratings: ...
struct User { id: i32, } impl User { pub fn table_name() -> String { "user".to_owned() } } fn main() { println!("{}", User::table_name()); }
#![cfg(target_arch = "wasm32")] extern crate wasm_bindgen_test; use wasm_bindgen_test::*; use rsfoo; wasm_bindgen_test_configure!(run_in_browser); #[wasm_bindgen_test] fn pass() { assert_eq!(1 + 1, 2); } #[wasm_bindgen_test] fn test() { let res = rsfoo::greet("test"); assert_eq!(res, "Hey test, wasm say...
use fyrox::{ core::pool::Handle, engine::resource_manager::ResourceManager, scene::{node::Node, Scene}, }; pub struct Level { root: Handle<Node>, } impl Level { pub async fn new(resource_manager: ResourceManager, scene: &mut Scene) -> Self { let root = resource_manager .request...
use crate::socket; use serde::Deserialize; use crate::database as db; use deadpool_postgres::Pool; use crate::utils::cache_short; pub async fn user(user_id: db::UserID, pool: Pool) -> Result<Box<dyn warp::Reply>, warp::Rejection> { let user = match db::user(pool, user_id).await? { Some(info) => info, ...
use std::env; use std::io::{self, BufRead}; struct VM { memory: Vec<i64>, ip: usize, input: Vec<i64>, output: Vec<i64>, } impl VM { fn new(program: &Vec<i64>, input: Vec<i64>) -> Self { VM { memory: program.clone(), ip: 0, input, output: Vec:...
use yew::prelude::*; pub struct Nodejs {} pub enum Msg {} impl Component for Nodejs { type Message = Msg; type Properties = (); fn create(_: Self::Properties, _: ComponentLink<Self>) -> Self { Nodejs {} } fn update(&mut self, _msg: Self::Message) -> ShouldRender { true } ...
use procon_reader::ProconReader; fn main() { let stdin = std::io::stdin(); let mut rd = ProconReader::new(stdin.lock()); let n: usize = rd.get(); let m: usize = rd.get(); let mut g = vec![vec![]; n]; for _ in 0..m { let a: usize = rd.get(); let b: usize = rd.get(); let ...
// Copyright 2014 The Servo 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>, at ...
#![no_std] #![no_main] #[allow(unused)] use panic_halt; mod tnarx; use core::fmt::Write; use embedded_graphics::fonts::Font12x16; use embedded_graphics::prelude::*; use hd44780_driver::{Cursor, CursorBlink, HD44780}; use ili9341; use shift_register_driver::sipo::ShiftRegister16; use ssd1306::prelude::*; use ssd1306:...
use clippy_utils::higher; use clippy_utils::{ can_move_expr_to_closure_no_visit, diagnostics::span_lint_and_sugg, is_expr_final_block_expr, is_expr_used_or_unified, match_def_path, paths, peel_hir_expr_while, source::{reindent_multiline, snippet_indent, snippet_with_applicability, snippet_with_context},...
use super::{ boolean::{False, True}, private::Sealed, }; /// Type-level negation (NOT). pub trait Negation: Sealed { /// Logical conclusion of the negation of `Self`. type Output; } /// Type-level conjunction (AND). pub trait Conjunction<L>: Sealed { /// Logical conclusion of the conjunction of `S...
#![allow(non_camel_case_types)] #![allow(dead_code)] #![allow(missing_copy_implementations)] use std::ffi::CString; use std::mem; use std::slice; use std::str; use cql_ffi::value::CassValue; use cql_ffi::error::CassError; use cql_ffi::collection::map::MapIterator; use cql_ffi::collection::set::SetIterator; //use cql...
use std::cmp::{max, min}; use std::collections::{HashMap, HashSet}; use itertools::Itertools; use whiteread::parse_line; // FIXME: すべてのテストケースに通らない // dfs 深さ優先探索 fn main() { let (n, q): (usize, usize) = parse_line().unwrap(); // 0が余分にある let mut tree: Vec<Vec<usize>> = vec![vec![]; n + 1]; let mut ctree...
#[derive(Debug)] #[allow(dead_code)] struct Rectangle { width: u32, height: u32, } #[allow(dead_code)] impl Rectangle { fn can_hold(&self, other: &Rectangle) -> bool { self.width > other.width && self.height > other.height } } pub fn add_two(a: i32) -> i32 { a + 2 } pub fn greeting(name: ...
extern crate csv; use std::collections::HashMap; use std::collections::TreeMap; use std::collections::HashSet; use std::collections::hash_map::Occupied; use std::collections::hash_map::Vacant; fn main() { println!(">> RECSYS welcome!"); let current_user_id = 20930; let fp = &Path::new("./../data/blog-po...
//! Commitment management mod account; mod blockhash; pub use self::account::{AccountChange, AccountCommitment, AccountState, Storage}; pub use self::blockhash::BlockhashState;
//! Types and parsers for various [`SHOW`][sql] schema statements. //! //! [sql]: https://docs.influxdata.com/influxdb/v1.8/query_language/explore-schema/ use crate::common::ws1; use crate::identifier::{identifier, Identifier}; use crate::impl_tuple_clause; use crate::internal::{expect, ParseResult}; use crate::keywor...
//! Handles the `/ipfs/bitswap/1.0.0` and `/ipfs/bitswap/1.1.0` protocols. This //! allows exchanging IPFS blocks. //! //! # Usage //! //! The `Bitswap` struct implements the `NetworkBehaviour` trait. When used, it //! will allow providing and reciving IPFS blocks. use crate::block::Block; use crate::ledger::{Ledger, M...
#![cfg_attr(not(feature = "std"), no_std)] use band_bridge; #[cfg(feature = "std")] use borsh::BorshDeserialize; use frame_support::{decl_error, decl_event, decl_module, decl_storage, dispatch}; use frame_system::{self as system}; use sp_std::prelude::*; /// The pallet's configuration trait. pub trait Trait: system::...
fn problem1() -> u64 { (1..1000) .filter(|n| n % 3 == 0 || n % 5 == 0) .fold(0, |acc, n| acc + n) } fn problem2() -> u64 { let mut a = 1; let mut b = 2; let mut sum = 0; while b < 4_000_000 { if b % 2 == 0 { sum += b; } let tmp = a; a = ...
use std::io::{Read, Result as IOResult}; use nalgebra::Vector3; use crate::lump_data::{LumpData, LumpType}; use crate::PrimitiveRead; #[derive(Copy, Clone, Debug)] pub struct Plane { pub normal: Vector3<f32>, pub dist: f32, pub edge_type: i32 } impl LumpData for Plane { fn lump_type() -> LumpType { LumpTy...