text
stringlengths
8
4.13M
//! Output. pub mod data; pub use self::data::*;
use std::error; /* 遇到错误时的处理流程 * * `?`表示遇到错误时返回; * * unwrap()解析错误类型 */ fn main() { ok_or(); } // 为 `Box<error::Error>` 取别名`DoubleResult`。 // // Box<Error>是一个 trait 对象, 用于底层错误类型不确定的情况 // // 这里不用自己定义新的error类型 type Result<T> = std::result::Result<T, Box<dyn error::Error>>; // ok_or() // // ok_or是Result类型的方法, 控...
use std::io::{Read, Write}; use errors::*; pub mod fs; pub const MAGIC_NUMBER: i32 = 0x3FD7_6C17; pub trait DataInput: Read { fn read_byte(&mut self) -> Result<u8> { let mut buffer = [0u8; 1]; if self.read(&mut buffer)? != 1 { bail!(ErrorKind::UnexpectedEOF( "Reached ...
//! Behavior tree nodes and internal node logic. use crate::status::Status; use std::fmt; /// Represents a generic node. /// /// The logic of the node is controlled by the supplied `Tickable` object. /// Nodes are considered to have been run to completion when they return either /// `Status::Succeeded` or `Status::Fa...
#[doc = "Reader of register PERFSEL2"] pub type R = crate::R<u32, super::PERFSEL2>; #[doc = "Writer for register PERFSEL2"] pub type W = crate::W<u32, super::PERFSEL2>; #[doc = "Register PERFSEL2 `reset()`'s with value 0x1f"] impl crate::ResetValue for super::PERFSEL2 { type Type = u32; #[inline(always)] fn...
#[doc = "Register `COUNT0_TX` reader"] pub type R = crate::R<COUNT0_TX_SPEC>; #[doc = "Register `COUNT0_TX` writer"] pub type W = crate::W<COUNT0_TX_SPEC>; #[doc = "Field `COUNT0_TX` reader - Transmission byte count"] pub type COUNT0_TX_R = crate::FieldReader<u16>; #[doc = "Field `COUNT0_TX` writer - Transmission byte ...
use crate::{ widget, widget::{ component::containers::flex_box::{flex_box, FlexBoxProps}, unit::flex::FlexBoxDirection, }, widget_component, Scalar, }; use serde::{Deserialize, Serialize}; #[derive(Debug, Default, Clone, Serialize, Deserialize)] pub struct HorizontalBoxProps { #[ser...
extern crate rand; use rand::Rng; fn bogosort_by<T,F>(order: F, coll: &mut [T]) where F: Fn(&T, &T) -> bool { let mut rng = rand::thread_rng(); while is_sorted_by(&order, coll) { rng.shuffle(coll); } } #[inline] fn is_sorted_by<T,F>(order: F, coll: &[T]) -> bool where F: Fn(&T,&T) -> boo...
#[doc = "Channel control\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write...
use collect_slice::CollectSlice; use crate::{Range, Size}; pub fn compute_strides<const N: usize>(shape: &Size<N>) -> Size<N> { let mut out = [0; N]; (0..N) .map(|i| shape[(i+1)..N].iter().product()) .collect_slice(&mut out); out } pub fn ravel_index<const N: usize>(index: &Size<N>, strid...
mod decode; mod encode; use self::decode::{Decode, DecodeContext}; use self::encode::{Encode, EncodeContext}; use crate::ast::WebidlBindings; use std::io; /// Encode the given Web IDL bindings section into the given write-able. pub fn encode<W>( section: &WebidlBindings, indices: &walrus::IdsToIndices, in...
use indexmap::IndexMap; use std::collections::HashSet; use syn::{Error, Ident, Result}; use crate::{ validation::{component::Component, AllComponents, AllQueries, AllUniques}, TypeId, }; #[derive(Debug)] pub struct Query { pub cached: bool, pub name: Ident, pub id: TypeId, pub children: Vec<At...
// to anyone reading this: I'm sorry, it's not exactly perfect. extern crate csv; extern crate serde; #[macro_use] extern crate serde_derive; extern crate serde_json; extern crate regex; extern crate sha2; extern crate chrono; use csv::ReaderBuilder; use std::collections::BTreeMap; use regex::Regex; use std::fs::{sel...
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ use core::marker::Unpin; use std::io; use serde::Deserialize; use serde::Serialize; use tokio::io:...
//! Sudoku grid use crate::parse_error::ParseError; use std::error::Error; use std::fs::File; use std::io::{BufRead, BufReader}; use std::path::Path; const SIZE: usize = 9; /// Grid cell #[derive(Copy, Clone)] pub struct Cell { /// Cell value pub value: Option<u32>, } impl Cell { /// Create new cell ...
extern crate image; extern crate log; extern crate nalgebra as na; extern crate simple_logging; use crate::geometry; use log::{error, info}; use std::mem::swap; #[derive(Debug)] pub struct GraphicsContext { pub tf_root: na::Isometry3<f32>, pub projection: na::Perspective3<f32>, //pub projection: na::Orth...
use amethyst::{ ecs::prelude::{ReadExpect, Resources, SystemData}, renderer::{ pass::DrawFlat2DDesc, rendy::{ factory::Factory, graph::{ render::{RenderGroupDesc, SubpassBuilder}, GraphBuilder, }, hal::{format::Forma...
#![no_std] use x86_64::PhysAddr; use x86_64::structures::paging::{FrameAllocator, Size4KiB, RecursivePageTable, PageTable, Page}; use x86_64::VirtAddr; use x86_64::structures::paging::mapper::Mapper; pub mod alloc; pub mod global; pub unsafe fn init(level_4_table_addr: usize) -> RecursivePageTable<'static> { let...
// Copyright 2018 Google LLC // // 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 ...
//! Extensions to the rust standard library pub use libutil::*;
use super::Fuse; use bytes::{Buf, BytesMut}; use std::{ fmt, io::{self, BufRead, Read, Write}, }; use tokio_util::codec::{Decoder, Encoder}; const INITIAL_CAPACITY: usize = 8 * 1024; pub struct FramedWrite<T, U> { inner: FramedWriteInner<Fuse<T, U>>, } pub(super) struct FramedWriteInner<T> { pub(supe...
use std::fs; const WIDTH: usize = 25; const HEIGHT: usize = 6; const LAYER_SIZE: usize = WIDTH * HEIGHT; fn get_layers(data: &[u8], lsize: usize) -> Vec<Vec<u8>> { data.chunks(lsize).map(|ch| ch.to_vec()).collect() } fn verify_data(data: &[u8], lsize: usize) -> u32 { let layers = get_layers(&data, lsize); ...
use std::{fmt, hash::Hash}; use chrono::{DateTime, Local}; use enum_map::Enum; #[derive(Debug, Enum, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum ItemType { Weapon, Character, } impl fmt::Display for ItemType { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self ...
use lisp_core::simple::Value as lcValue; use lisp_core::{ common::{BasicLispValue, CombinedLispOps, LispError}, lexpr, }; use rustyline::{error::ReadlineError, Editor}; use std::fmt::Display; use std::str::FromStr; pub fn read<T: From<lexpr::Value>>() -> Result<T> { let mut rl = Editor::<()>::new(); Ok...
use wasm_bindgen::prelude::wasm_bindgen; #[wasm_bindgen] #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Mode { Json, Jsonc, }
/*! * Functions related to any user interaction * * # Author * Doran Kayoumi <doran.kayoumi@heig-vd.ch> */ use read_input::prelude::*; /// Ask the user to enter an email address pub fn ask_for_email() -> String { input().msg("Username : ").get() } /// Ask the user for a password without checking the policy ...
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ pub trait AbstractDomain: Clone + Eq { fn bottom() -> Self; fn top() -> Self; fn is_bottom(&self) -> bool; fn is_...
use errors::*; use fern; use log::LogLevelFilter; use chrono::prelude::*; use oauth2::Token; mod router; mod app_config; mod require_authn; mod oauth_receiver; mod inventory; #[derive(Default, Serialize, Deserialize, StateData, Clone)] struct D2Session { #[serde(default)] pub token: Option<Token>, } impl D2Sess...
use std::env; use std::process; use std::time; use std::thread; mod runtime_manager; mod chip; mod opcodes; const ERROR_INVALID_ARGUMENTS: i32 = 0x0001; const ERROR_GAME_LOADING_FAILED: i32 = 0x0002; const FRAME_PER_SECONDS: f32 = 60.0; const MILLISECONDS_PER_FRAME: f32 = 1000.0 / FRAME_PER_SECONDS; const REAL_WIND...
#![doc = "generated by AutoRust 0.1.0"] #![allow(unused_mut)] #![allow(unused_variables)] #![allow(unused_imports)] use crate::models::*; use reqwest::StatusCode; use snafu::{ResultExt, Snafu}; pub mod lab { use crate::models::*; use reqwest::StatusCode; use snafu::{ResultExt, Snafu}; pub async fn list_...
use rand::distributions::Alphanumeric; use rand::{thread_rng, Rng}; pub(crate) fn random_password() -> String { thread_rng() .sample_iter(&Alphanumeric) .take(30) .map(char::from) .collect() }
extern crate proc_macro; use fnv::FnvHashMap; use inflector::Inflector; use lazy_static::lazy_static; use proc_macro2::{Ident, Span, TokenStream}; use quote::quote; use tf_demo_parser::demo::gameevent_gen::get_sizes; use tf_demo_parser::demo::gamevent::{GameEventDefinition, GameEventValueType}; use tf_demo_parser::dem...
impl Solution { pub fn reverse_words(s: String) -> String { let mut vec: Vec<&str> = s.trim().split(" ").collect(); let mut revStr = String::new(); vec.reverse(); for v in vec { if v == "" { continue; } ...
#[doc = "Register `EXTICR1` reader"] pub type R = crate::R<EXTICR1_SPEC>; #[doc = "Register `EXTICR1` writer"] pub type W = crate::W<EXTICR1_SPEC>; #[doc = "Field `EXTI0` reader - EXTIm GPIO port selection (m = 4 * (x - 1)) These bits are written by software to select the source input for EXTIm external interrupt. Othe...
extern crate dijkstra; #[cfg(test)] mod tests { use std::u32; use dijkstra::dijkstra::*; #[test] fn dijkstra_simple_test() { let graph = vec![ // Node 0 vec![Edge { node: 2, cost: 10 }, Edge { node: 1, cost: 1 }], // Node 1 vec![Edge { node: 3, cost: 2 }], // Node 2 vec![Edge { n...
extern crate gloss; use std::error::Error; use std::process; fn err_exit(err_msg: Box<Error>) { eprintln!("Error: {}", err_msg); process::exit(1); } fn main() { let matches = gloss::new_app(); let maybe_word : Option<&str> = matches.value_of("headword"); maybe_word.and_then::<Option<()>, _>(...
use std::ops::{Div, Rem}; use num::cast::ToPrimitive; use num::{pow, BigInt}; pub fn div_rem<T: Div<Output = T> + Rem<Output = T> + Copy>(x: T, y: T) -> (T, T) { let quotient = x / y; let remainder = x % y; (quotient, remainder) } pub fn power(b: BigInt, e: BigInt) -> BigInt { pow(b, e.to_usize().unw...
// This is where integration tests live. use rust_samples::string_functions::sub_string; #[test] fn compare_size_with_lifetimes_succeds() { let text = "Asante sana squash banana, wewe nugu mimi hapana"; assert_eq!("squash banana", sub_string(text, 12, 13)); } #[test] fn compare_size_with_lifetimes_zero_zero(...
pub fn get(v: u8, n: usize) -> bool { (v & (1 << n)) != 0 } pub fn set(v: u8, n: usize) -> u8 { v | (1 << n) } pub fn clr(v: u8, n: usize) -> u8 { v & !(1 << n) } pub fn get16(v: u16, n: usize) -> bool { (v & (1 << n)) != 0 }
pub mod webserver; pub mod options; mod handler; mod job; mod message; mod threadpool; mod worker;
use super::state::State; use super::databus::Databus; use super::instruction; use crate::cpu::instruction::Instruction; pub const NMI_VECTOR_ADDRESS: u16 = 0xFFFA; pub const RES_VECTOR_ADDRESS: u16 = 0xFFFC; pub const IRQ_VECTOR_ADDRESS: u16 = 0xFFFE; pub const STACK_OFFSET: u16 = 0x0100; pub struct Cpu { state:...
use lexer::Lexer; use lexer::Prop; use syntax::ast; use syntax::ast::P; use syntax::codemap; use syntax::codemap::CodeMap; use syntax::codemap::Span; use syntax::diagnostic; use syntax::ext::base::ExtCtxt; use syntax::ext::base::MacResult; use syntax::ext::build::AstBuilder; use syntax::parse::token; use syntax::util::...
//! Symbols and externs that `ralloc` depends on. //! //! This crate provides implementation/import of these in Linux, BSD, and Mac OS. //! //! # Important //! //! You CANNOT use libc library calls, due to no guarantees being made about allocations of the //! functions in the POSIX specification. Therefore, we use the ...
use near_sdk::ext_contract; use near_sdk::json_types::U128; #[ext_contract(ext_registry)] pub trait Registry { /// get Registred Validators pub fn get_validators(self) -> LookupMap<String, u32>; }
use colored::Colorize; use std::fmt; #[derive(Debug, Clone, PartialEq)] pub enum TokenType { Int, Float, Str, Char, Bool, Identifier, Keyword, Symbol, Operator, Whitespace, EOL, EOF, } impl fmt::Display for TokenType { fn fmt (&self, f: &mut fmt::Formatter) -> fmt::Result { use self::Tok...
use auto_impl::auto_impl; #[auto_impl(Arc, Box, Rc, &, &mut)] trait Big<'a, T: for<'b> Into<&'b str>> { type Type1; type Type2: std::ops::Deref; const FOO: u32; fn execute1<'b>(&'a self, arg1: &'b T) -> Result<Self::Type1, String> where T: Clone, <Self::Type2 as std::ops::Deref>:...
// // Copyright (c) 2017, 2020 ADLINK Technology Inc. // // This program and the accompanying materials are made available under the // terms of the Eclipse Public License 2.0 which is available at // http://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 // which is available at https://www.apache.or...
mod front_of_house { pub mod hosting { //fn add_to_waitlist() {} // function would still be private, even if module is public pub fn add_to_waitlist() { // `super` can be used as '..' - makes path relative to parent module // super::super::super::take_order(); // E: "too many...
use crate::Result; use crate::data::Server; use crate::data::{ Client, ClientType }; use crate::network::socket_io; use std::sync::Arc; use tokio::net::TcpListener; use tracing::error; /* The actual entry point to start the accept server. * So this is also the place to start tokio runtime. */ #[tokio::main] pub asyn...
use futures::channel::mpsc::{Receiver, Sender}; use futures_util::{SinkExt, StreamExt}; use log::{debug, warn}; use std::collections::HashMap; use std::net::SocketAddr; use tungstenite::protocol::Message; #[derive(Debug)] pub enum BrokerMessage { Relay(Message), NewClient(SocketAddr, Sender<Message>), DelC...
use crate::db::PostgresPool; use diesel::pg::PgConnection; use crate::diesel::RunQueryDsl; use crate::juniper::{Executor, FieldResult}; use juniper_eager_loading::{prelude::*, EagerLoading, HasOne}; //use juniper_from_schema::QueryTrail; use juniper_from_schema::graphql_schema_from_file; graphql_schema_from_file!("s...
/* * Slack Web API * * One way to interact with the Slack platform is its HTTP RPC-based Web API, a collection of methods requiring OAuth 2.0-based user, bot, or workspace tokens blessed with related OAuth scopes. * * The version of the OpenAPI document: 1.7.0 * * Generated by: https://openapi-generator.tech *...
//! A libunftp [`StorageBackend`](libunftp::storage::StorageBackend) that uses a local filesystem, like a traditional FTP server. //! //! Here is an example for using this storage backend //! //! ```no_run //! use unftp_sbe_fs::ServerExt; //! //! #[tokio::main] //! pub async fn main() { //! let ftp_home = std::env...
use derive_new::new; use amethyst::winit::{DeviceEvent, Event, Window, WindowEvent}; #[cfg(feature = "profiler")] use thread_profiler::profile_scope; use amethyst::core::{ ecs::prelude::{Join, Read, ReadExpect, ReadStorage, System, SystemData, Write, WriteStorage}, math::{convert, Unit, Vector3}, shrev::{...
use std::fs; use crate::models::enums; use crate::models::structs; const JSON_PATH: &str = "./submodules.json"; pub fn read_json() -> Result<Vec<structs::Submodule>, enums::Error> { let jsonfile = fs::read_to_string(JSON_PATH)?; let parsed: Vec<structs::Submodule> = serde_json::from_str(&jsonfile)?; Ok(pa...
mod test_support; use apllodb_immutable_schema_engine::ApllodbImmutableSchemaEngine; use apllodb_immutable_schema_engine_infra::test_support::{ sqlite_database_cleaner::SqliteDatabaseCleaner, test_setup, }; use apllodb_shared_components::{ ApllodbError, ApllodbResult, DatabaseName, Session, SessionWithoutDb, S...
pub struct Server { addr: String, } impl Server { pub fn new(addr: String) -> Self { Self { addr } } pub fn run(&self) { println!("Server listening on: {}", self.addr) } }
//////////////////////////////////////////////////////////////////////////////// // HERE BE DRAGONS //////////////////////////////////////////////////////////////////////////////// extern crate glium; mod draw; static mut STATE : Option<draw::draw::State> = None; #[no_mangle] pub extern "C" fn init(display : *const ...
use ajour_core::theme::ColorPalette; use iced::{button, checkbox, container, pick_list, scrollable, text_input, Background, Color}; pub struct SurfaceContainer(pub ColorPalette); impl container::StyleSheet for SurfaceContainer { fn style(&self) -> container::Style { container::Style { backgroun...
use std::convert::TryFrom; use fujiformer_geom::{IntRect, Point, Rect, Size}; use log::warn; use thiserror::Error; use crate::CelesteMap; #[derive(Debug, Clone)] pub struct Filler { rect: IntRect, } impl Filler { pub fn new(rect: IntRect) -> Self { Filler { rect } } pub fn shape(&self) -> I...
#[macro_export] macro_rules! new_module { ($mod_name:ident, $duration:expr, $code:block) => { use $crate::init::Args; pub fn init(scheduler: &mut clokwerk::Scheduler, args: &Args) { if let Err(err) = update(&args.addr, &args.cookie) { log::error!( "{} ...
struct Generator { current: usize, factor: usize, multiply: usize, } impl Generator { pub fn new(current: usize, factor: usize, multiply: usize) -> Generator { Generator { current, factor, multiply, } } } impl Iterator for Generator { type It...
use super::{param_header::*, param_type::*, *}; use bytes::{Buf, BufMut, Bytes, BytesMut}; use std::fmt; #[derive(Debug, Copy, Clone, PartialEq)] #[repr(C)] pub(crate) enum ReconfigResult { SuccessNop = 0, SuccessPerformed = 1, Denied = 2, ErrorWrongSsn = 3, ErrorRequestAlreadyInProgress = 4, ...
use std::ascii::AsciiExt; use std::collections::HashMap; use std::str; #[derive(PartialEq)] #[derive(Debug)] pub enum HTTPError { BadRequest, NotImplemented, VersionNotSupported, NotFound, } #[derive(Debug)] pub struct RequestLine<'a> { pub method: &'a str, pub target: &'a str, pub http_ve...
pub mod fund; pub mod vault; pub mod whitelist; pub use fund::Fund; pub use fund::FundType; pub use whitelist::Whitelist;
use std::collections::LinkedList; use std::iter::IntoIterator; fn main() { for (n, s) in NQueens::new(8).enumerate() { println!("Solution #{}:\n{}\n", n + 1, s.to_string()); } } fn permutations<'a, T, I>(collection: I) -> Box<Iterator<Item=LinkedList<T>> + 'a> where I: 'a + IntoIterator<Item=T> ...
use std::marker::PhantomData; use std::ptr; use crate::error::{check_status, Error}; use crate::receive_metadata::ReceiveMetadata; use crate::stream::StreamCommand; use crate::usrp::Usrp; use std::os::raw::c_void; /// A streamer used to receive samples from a USRP /// /// The type parameter I is the type of sample th...
use std::i32; use std::iter::Peekable; use std::slice::Iter; use itertools::Itertools; use regex::Regex; use crate::attribute::AttributeList; use crate::attribute_pool::AttributePool; use crate::component::{ComponentList, Operation, OperationCode}; use crate::util::to36String; /// A changeset represents a change to ...
extern crate hyper; extern crate rustc_serialize; extern crate bbs; use std::fs::{File, OpenOptions}; use std::io::{self, Read, Write}; use std::net::TcpStream; use hyper::Client; use hyper::server::{Request, Response, Server}; use hyper::status::StatusCode; use rustc_serialize::json; use bbs::Message; use bbs::{SERV...
use crate::db::types::{Branch, Currency}; use crate::models::transaction::InputUpdateTransaction; use crate::schema::money_nodes; use chrono::NaiveDateTime; use serde::{Deserialize, Serialize}; #[derive(GraphQLObject, Queryable, Debug, Serialize, Deserialize)] pub struct MoneyNode { pub id: i32, pub branch: Br...
pub mod calculate; pub mod config; pub mod element; pub mod render; pub mod shapes; #[macro_use] extern crate serde_derive;
#[macro_use] extern crate log; use std::{env, io}; use std::error::Error; use std::io::ErrorKind; use std::net::SocketAddr; use async_trait::async_trait; use log4rs::append::console::ConsoleAppender; use log4rs::config::{Appender, Root}; use log4rs::Config; use log4rs::encode::pattern::PatternEncoder; use log::LevelF...
use super::super::SQLiteDatabase; use crate::database::values::dsl::ExprDb; use nu_engine::CallExt; use nu_protocol::{ ast::Call, engine::{Command, EngineState, Stack}, Category, Example, IntoPipelineData, PipelineData, ShellError, Signature, Span, SyntaxShape, Type, Value, }; use sqlparser::ast::Statem...
use std::ops::Add; struct Point { x: i32, y: i32, } struct Rect<T> { width: T, height: T, } struct User { name: String, description: Option<String>, } trait Printable { fn print(&self); } struct Owner(i32); impl Owner { // Annotate lifetimes as in a standalone function. // 通...
use std::{fmt, str::FromStr}; use crate::error::Error; const OBJECT_KEYWORD: &str = "object"; const BOOLEAN_KEYWORD: &str = "boolean"; const STRING_KEYWORD: &str = "string"; const PASSWORD_KEYWORD: &str = "password"; const HOSTNAME_KEYWORD: &str = "hostname"; const INTEGER_KEYWORD: &str = "integer"; const ARRAY_KEYWO...
const INPUT: u32 = 5034; const FUEL_CELL_GRID_SIZE: usize = 300; const PART_ONE_SQUARE_SIZE: usize = 3; fn main() { let part_one_solution = solve_part_one(INPUT); println!("{},{}", part_one_solution.0, part_one_solution.1); let (c, size) = solve_part_two(INPUT); println!("{},{},{}", c.0, c.1, size); } ...
use std::fmt; #[derive(Debug)] pub enum Error { IOError(std::io::Error), NulError(widestring::NulError<u16>), MissingNulError(widestring::MissingNulError<u16>), } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Error::IOError(er...
pub(self) mod display; pub(self) mod input; pub(self) mod layout; pub mod look_and_feel; pub(self) mod ui; pub(self) mod widget; pub(self) mod window; pub use display::*; pub use input::*; pub use layout::*; pub use look_and_feel::Theme; pub use ui::{Selection, UI, UISource}; pub use widget::{AnyWidget, InternalWidget...
use registry::{Hive, Security}; use winapi::{shared::ntdef::LUID, um::{processthreadsapi::OpenProcessToken, securitybaseapi::AdjustTokenPrivileges, winbase::LookupPrivilegeValueW, winnt::LUID_AND_ATTRIBUTES, winnt::{HANDLE, SE_BACKUP_NAME, SE_PRIVILEGE_ENABLED, SE_RESTORE_NAME, TOKEN_PRIVILEGES}}}; use winapi::um::proc...
mod circuit; mod format; fn main() { let input_filename = std::env::args().nth(1) .expect("Input filename required."); let c = format::bench::read(&input_filename); format::bristol::print(&c); }
#![crate_id = "github.com/csherratt/cow-rs#cow:0.1"] #![comment = "An OpenGL function loader."] #![license = "ASL2"] #![crate_type = "lib"] #![crate_type = "dylib"] #![allow(experimental)] extern crate sync; pub mod btree; pub mod join;
fn main() { let r = Rect { height: 30, width: 40, }; println!("r = {:?}", r); println!("area = {}", r.area()); let r2 = Rect { width: 10, height: 17, }; println!("ch {}", r.can_hold(&r2)); let r3 = Rect::square(17); println!("r3 = {:?}", r3); } #[de...
#[macro_use] mod macros; use std::fmt; use std::ops::{BitAnd, BitAndAssign, BitOr, BitOrAssign, BitXor, BitXorAssign, Not}; pub trait MaskValue: Clone + Send + Sync + fmt::Debug + Into<isize> + PartialEq + Not<Output = MaskManager<Self>> + BitOr<Output = MaskManager<Self>> + BitXor<...
// This file is part of Substrate. // Copyright (C) 2017-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...
use std::fs::OpenOptions; use slog::Drain; use slog::Duplicate; use slog_scope::GlobalLoggerGuard; use crate::robot_map::*; /// Launches the logger, returning back a global guard object that <b>MUST NOT BE DROPPED!</b> pub fn launch_logger() -> GlobalLoggerGuard { let term_decorator = slog_term::TermDecorator::n...
extern crate log; //#[macro_use] extern crate plex; extern crate simplelog; use std::ops::Deref; pub mod plain; pub mod rust_lang; pub mod toml; #[macro_export] macro_rules! lexer_whitespace { ($provider: expr) => {{ let text = $provider.text(); let line = $provider.line(); let character ...
fn num_jewels_in_stones(j: String, s: String) -> i32 { let mut n = 0; for c in j.chars() { //n += s.matches(c).count(); for ss in s.chars() { if c == ss { n += 1; } } } n as i32 } fn main() { println!( "{}", num_jewel...
extern crate atlas_coverage_core; use atlas_coverage_core as e2e_cc; fn main() { let settings = e2e_cc::settings::from_root().unwrap(); e2e_cc::debug::print_existing(settings); }
/* Defining an Enum Let’s look at a situation we might want to express in code and see why enums are useful and more appropriate than structs in this case. Say we need to work with IP addresses. Currently, two major standards are used for IP addresses: version four and version six. These are the only possibilities fo...
extern crate brainrot; use std::env; use std::error::Error; use std::fs::File; use std::io::Read; fn main() { let args: Vec<String> = env::args().collect(); if args.len() != 2 { println!("Please provide one argument, that is the bf source file."); return; } let filename = &args[1]; ...
use failure::Error; use std::net::SocketAddr; use grpc::{ClientConf, ClientStubExt, RequestOptions}; use grpc_ring::ring_grpc::{GreeterClient, Greeter}; use grpc_ring::ring::{HelloReply, HelloRequest}; use grpc::Error as GrpcError; pub struct Remote { client: GreeterClient } impl Remote { pub fn new(addr: Sock...
use diesel::prelude::*; use sl_lib::models::*; use sl_lib::*; pub fn show() { use schema::posts::dsl::*; let connection = init_pool().get().unwrap(); let results = posts .filter(published.eq(true)) .limit(10) .load::<Post>(&connection) .expect("Error loading posts"); ...
/// Branch represents a repository branch #[derive(Debug, Default, Clone, Serialize, Deserialize)] pub struct Branch { pub commit: Option<crate::payload_commit::PayloadCommit>, pub effective_branch_protection_name: Option<String>, pub enable_status_check: Option<bool>, pub name: Option<String>, pub...
pub mod ingredient;
use serde::Serialize; #[derive(Debug, Serialize)] pub struct PaddleConfig { pub width: f32, pub height: f32, pub offset: f32, pub speed: f32, } impl Default for PaddleConfig { fn default() -> Self { PaddleConfig { width: 100f32, height: 10f32, offset: 10...
use num::traits::{Num, NumCast}; use std::f64; use super::deg::{Deg, ToDeg}; /// ToRad is the canonical trait to use for taking input in radians. /// /// For example the degrees type (Deg) implements the ToRad trait and thus /// degrees can be given as a parameter to any input that seeks radians. pub trait ToRad{ ...
//! Top-K, store `k` most frequent data points in stream. #[cfg(feature = "num-traits")] pub mod cmsheap; pub mod lossycounter;
use rand::Rng; use std::collections::HashSet; use std::env; use std::io; use std::process::{exit, Command}; fn cmd_hello() -> String { return "Hello, world!".to_string(); } fn cmd_sum(args: Vec<String>) -> String { let mut res = 0; for i in 2..args.len() { match args[i].parse::<i32>() { ...
use std::fmt::Debug; use std::sync::Arc; use crate::bxdf::TransportMode; use crate::light::Light; use crate::material::Material; use crate::math::*; use crate::interaction::SurfaceInteraction; mod geometric; pub use self::geometric::GeometricPrimitive; mod transformed; pub use self::transformed::TransformedPrimitive;...
use dotenv::Error as DotenvError; use serenity::Error as SerenityError; use sqlx::migrate::MigrateError; use sqlx::Error as SqlxError; use std::env::VarError; use std::error::Error as StdError; use std::fmt::{Display, Formatter, Result as FmtResult}; use std::io::Error as IoError; use std::result::Result as StdResult; ...