text stringlengths 8 4.13M |
|---|
use crate::types::{ContractCall, TransactionArgumentView, TypeTagView};
use starcoin_vm_types::token::stc::stc_type_tag;
use starcoin_vm_types::transaction_argument::TransactionArgument;
use std::path::PathBuf;
use std::process::Command;
#[test]
fn test_view_of_type_tag() {
let ty_tag = stc_type_tag();
let s = ... |
extern crate piston_window;
use piston_window::*;
const WINDOW_W : u32 = 800;
const WINDOW_H : u32 = (0.866 * WINDOW_W as f64) as u32;
const DEPTH : u32 = 7;
fn main() {
let window: PistonWindow = WindowSettings::new("Hello Piston!", [WINDOW_W, WINDOW_H])
.exit_on_esc(true).into();
for e in window {
e.draw_2d... |
extern crate bindgen;
use std::env;
use std::path::PathBuf;
use std::process::Command;
fn main() {
// Tell cargo to tell rustc to link the system bzip2
// shared library.
// The bindgen::Builder is the main entry point
// to bindgen, and lets you build up options for
// the resulting bindings.
... |
use bigint::*;
use hmac::*;
use std::sync::mpsc::{Sender, Receiver};
use ::utils::diffie_hellman::*;
use super::utils::*;
use super::messages::*;
use super::{P,G};
const I : &str = "email@email.com";
pub fn client(to_server: Sender<String>, from_server: Receiver<String>) {
println!("\tClient: Generate keys");
... |
// Copyright (c) 2022 PHPER Framework Team
// PHPER is licensed under Mulan PSL v2.
// You can use this software according to the terms and conditions of the Mulan
// PSL v2. You may obtain a copy of Mulan PSL v2 at:
// http://license.coscl.org.cn/MulanPSL2
// THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WIT... |
extern crate rand;
use rand::Rng;
use std::io;
use std::process::exit;
fn main() {
let rock = &String::from("Rock");
let paper = &String::from("Paper");
let scissor = &String::from("Scissor");
let mut input = String::new();
println!("Type Rock, Paper, or Scissor");
match io::stdin().read_line... |
#![no_std]
#![no_main]
#![feature(custom_test_frameworks)]
#![test_runner(rust_os::test_runner)]
#![reexport_test_harness_main = "test_main"]
use core::panic::PanicInfo;
use rust_os::println;
#[cfg(not(test))]
#[panic_handler]
fn panic(info: &PanicInfo) -> ! {
println!("{}", info);
loop {}
}
#[cfg(test)]
#[p... |
use std::fmt;
use thiserror::Error;
use async_trait::async_trait;
#[derive(Error, Debug)]
pub enum Error {
#[error("wrong cas")]
Cas(Cas),
#[error("repo is disconnected")]
Disconnect(#[from] std::io::Error),
}
#[derive(Clone, Copy, Debug)]
pub struct Cas(u32);
impl fmt::Display for Cas {
fn fmt(... |
use crate::command::DisplayCommand;
use layout::layout_box::LayoutBox;
pub type PaintFn = dyn Fn(&LayoutBox) -> Option<DisplayCommand>;
pub type DisplayList = Vec<DisplayCommand>;
pub struct PaintChain<'a>(Vec<&'a PaintFn>);
pub struct PaintChainBuilder<'a> {
paint_fns: Vec<&'a PaintFn>,
}
impl<'a> PaintChain<'... |
//--------------------------------------------------------------------------------------------//
// other imports
use std::fmt;
use osmgraphing::network::Graph;
use osmgraphing::routing;
//--------------------------------------------------------------------------------------------//
// own imports
mod astar;
//---... |
pub fn _func() {
println!("This is function.");
}
// In function signatures, you must declare the type of each parameter
pub fn _func_with_params(x: i8, y: f32) {
println!("The value of x is: {} and of y: {}", x, y);
}
pub fn _func_that_returns(x: i8) -> i8 {
x * 10
}
pub fn _closures() {
// similar to arrow... |
pub struct Solution {}
impl Solution {
pub fn h_index(citations: Vec<i32>) -> i32 {
let len = citations.len();
let (mut low, mut high) = (0, len);
while low < high {
let mid = low + (high - low - 1) / 2;
if len - mid > citations[mid] as usize {
low = ... |
use std::fs;
use std::path::Path;
fn main() {
// println!("{:?}", path.u)
walk_path("./")
}
fn walk_path(path_o: &str) {
let paths = fs::read_dir(path_o).unwrap();
for path in paths {
let path_d = path.unwrap().path();
let path_type = dectect_path(&path_d);
if path_type == "dir... |
// Copyright 2021 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 ... |
use std::collections::HashMap;
use std::io::{Cursor, Read};
use byteorder::{LittleEndian, ReadBytesExt};
/**
* 'jwt' guest API bindings for rust
*
* it can be called from rust code compiled into wasm and executed by my-own-cluster
*
* you can use it by adding that in your rust source files at the beginning :
... |
extern crate tonic_build;
fn main() {
tonic_build::configure()
.build_server(true)
.type_attribute(".", "#[derive(serde::Serialize, serde::Deserialize)]")
.compile(&["proto/mayastor.proto"], &["proto"])
.unwrap_or_else(|e| {
panic!("mayastor protobuf compilation failed: ... |
//! Graph library.
#![warn(missing_docs)]
pub mod data;
pub use self::data::Data;
pub mod io;
pub use self::io::{Read, Write, DataResult, Error as IoError, ErrorKind as IoErrorKind};
#[cfg(test)]
mod tests {
#[test]
fn it_works() {
assert_eq!(2 + 2, 4);
}
}
|
use crate::common::names::*;
use crate::mir::trees as mir;
use crate::mir::ops::Bop;
use super::mir_gen;
pub fn add_word() -> Bop {
match mir::Type::word() {
mir::Type::I32 => Bop::Add_i32,
mir::Type::I64 => Bop::Add_i64,
_ => unreachable!(),
}
}
pub fn mul_word() -> Bop {
match mi... |
use futures::{IntoFuture, Poll};
use tower_service::Service;
/// A `Service` implemented by a closure.
pub struct ServiceFn<T> {
f: T,
}
impl<T> ServiceFn<T> {
/// Returns a new `NewServiceFn` with the given closure.
pub fn new(f: T) -> Self {
ServiceFn { f }
}
}
impl<T, F, Request> Service<R... |
// image_formats::image
// by Desmond Germans, 2019
#[derive(Default)]
pub struct ImageBuffer {
pub width: usize,
pub height: usize,
pub data: Vec<u32>,
}
impl ImageBuffer {
pub fn new(width: usize,height: usize) -> ImageBuffer {
ImageBuffer {
width: width,
height: hei... |
use std::fmt::Debug;
use nom::{
bytes::complete::{tag, take_while, take_while_m_n},
multi::{many0, many1},
sequence::tuple,
combinator::map,
branch::alt,
character::complete::digit0,
IResult,
};
#[derive(Debug, Clone)]
struct Parsed {
molecules: Vec<Molecule>,
}
#[derive(Debug, Clone)]... |
// Copyright 2020 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 ... |
use std::io;
pub fn solve(data_dir: String, day : usize, part : usize) -> io::Result<()> {
println!("No solution for AOC Day {} Part {} using input from {}", day, part, data_dir);
Ok(())
} |
use os_bootinfo::{FrameRange, MemoryMap, MemoryRegion, MemoryRegionType};
use memory::*;
pub struct AreaFrameAllocator<'a> {
memory_map: &'a mut MemoryMap,
currently_usable: usize,
currently_in_use: usize,
}
impl<'a> AreaFrameAllocator<'a> {
pub fn new(memory_map: &'a mut MemoryMap) -> Self {
... |
#[doc = "Register `POWERCLR` reader"]
pub struct R(crate::R<POWERCLR_SPEC>);
impl core::ops::Deref for R {
type Target = crate::R<POWERCLR_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<crate::R<POWERCLR_SPEC>> for R {
#[inline(always)]
fn from(reader: ... |
use super::*;
#[test]
fn parse_ugen_plugins_path() {
let mut options = Options::default();
options.ugen_plugins_path = Some(vec![
"/foo/bar".to_string(),
"/home/ugens".to_string(),
"/some/more".to_string(),
]);
assert_eq!(
Some(String::from("/foo/bar:/home/ugens:/some/mo... |
// Copyright 2019 Conflux Foundation. All rights reserved.
// Conflux is free software and distributed under GNU General Public License.
// See http://www.gnu.org/licenses/
use crate::{
message::{Message, RequestId},
sync::{
message::{
Context, GetBlockHeadersResponse, Handleable, Key, KeyC... |
// OpenAOE: An open source reimplementation of Age of Empires (1997)
// Copyright (c) 2016 Kevin Fuller
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including wi... |
use std::collections::BTreeMap;
use tpscube_core::{Cube3x3x3, CubeFace, LastLayerRandomization, PLLAlgorithm};
fn main() {
let mut counts = BTreeMap::new();
for _ in 0..10000000 {
let cube = Cube3x3x3::random_last_layer(
CubeFace::Top,
LastLayerRandomization::OrientedRandomState... |
use std::str::FromStr;
pub type Chapter = u8;
pub type Verse = u8;
use crate::book::Book;
#[derive(Debug)]
pub struct Reference {
book: Book,
chapter: Option<Chapter>,
verse: Option<Verse>,
}
impl FromStr for Reference {
type Err = &'static str;
fn from_str(s: &str) -> Result<Self, Self::Err> {... |
use std::fmt;
/// Represents scalar types such as Int, String, and Boolean.
/// Scalars cannot have fields.
///
/// *ScalarTypeDefinition*:
/// Description<sub>opt</sub> **scalar** Name Directives<sub>\[Const\]opt</sub>
///
/// Detailed documentation can be found in [GraphQL spec](https://spec.graphql.org/draft/#s... |
/// Link Simulator
///
/// Copyright (C) 2019 PTScientists GmbH
///
/// 17.04.2019 Eric Reinthal
use std::net;
use std::time;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
extern crate term;
//must be an outbound address of the active link connected to the sender test counterpart
const SOURCE... |
// Copyright 2020 WHTCORPS INC Project Authors. Licensed Under Apache-2.0
use std::sync::Arc;
use ekvproto::interlock::KeyCone;
use violetabftstore::interlock::::collections::HashSet;
use fidel_timeshare::PrimaryCausetInfo;
use fidel_timeshare::BlockScan;
use super::{scan::InnerFreeDaemon, Event, ScanFreeDaemon, Sca... |
use std::io::{self, Read};
use std::string::String;
use std::vec::Vec;
fn main() {
let mut buffer = String::new();
io::stdin().lock().read_to_string(&mut buffer).unwrap();
let numbers: Vec<u32> = buffer
.split('\n')
.filter(|&x| x != "")
.map(|x| x.parse().unwrap())
.collec... |
use std::convert::TryInto;
#[repr(u32)]
#[derive(PartialEq)]
enum Opcode {
ADD = 1,
MUL = 2,
IN = 3,
OUT = 4,
JNEZ = 5,
JEZ = 6,
LT = 7,
EQ = 8,
REL = 9,
HALT = 99,
}
impl From<u32> for Opcode {
fn from(n: u32) -> Self {
use Opcode::*;
let opcode = n % 100;
... |
use std::io::{self, ErrorKind};
use std::iter;
use std::num::ParseIntError;
use std::str::{self, FromStr};
use super::rule::TransitionRule;
use super::timezone::{LeapSecond, LocalTimeType, TimeZone, Transition};
use super::Error;
pub(super) fn parse(bytes: &[u8]) -> Result<TimeZone, Error> {
let mut cursor = Curs... |
use Tensor::Rank2Tensor;
use Tensor::Rank1Tensor;
use Function::functiontraits::*;
use Learner::learnertraits::*;
use Optimizer::optimizertraits::Optimizer;
use rand::Rng;
use rand;
use rand::distributions::{Range, IndependentSample};
pub struct Activation_Layer<T: IsFunction> {
m_inputs: u64,
m_outputs: u64,... |
extern crate rand;
#[derive(PartialEq, Clone, Copy)]
enum Symbol {
O,
X,
Blank
}
#[derive(PartialEq)]
enum Winner {
Tie,
Player(Symbol),
NoWinner
}
impl std::fmt::Display for Symbol {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "{}", match *self {
Symbol::O => "O",
Symbo... |
// My original plan:
// Lets parse the input and build some claims
// A claim shall have
// - ID
// - Recangle
// - x
// - y
// - width
// - height
// Maybe, in order to feed the factory
// a claim can return a iterable that contains for each point (x, y)
// A factory is a HashMap<x, y>.
// for claim in c... |
#[cfg(test)]
mod tests {
#[test]
fn it_works() {
assert_eq!(2 + 2, 4);
}
}
trait QueryString<T> {
fn decode(query_string: &str) -> Option<T>;
fn encode(t: &T) -> &str;
// ?size=1&name=josip (1, "josip")
// fn combine<V>(&self, &qs: QueryString<V>) -> &QueryString<(V, T)>;
}
|
mod hasher;
pub(crate) use hasher::TypeIdHasher;
use core::hash::{Hash, Hasher};
/// Custom `TypeId` to be able to deserialize it.
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, PartialOrd, Ord)]
#[cfg_attr(feature = "serde1", derive(serde::Serialize, serde::Deserialize))]
pub struct TypeId(pub(crate) u128);
im... |
//! An IRC server
#![cfg_attr(test, feature(test))]
#![feature(box_syntax)]
#![feature(slice_patterns)]
#![feature(lookup_host)]
#![feature(fnbox)]
#![allow(unused_imports)]
#![allow(missing_docs)]
#[macro_use]
extern crate log;
extern crate env_logger;
extern crate bytes;
extern crate num;
extern crate rand;
exter... |
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - ID code register"]
pub id: ID,
#[doc = "0x04 - Control register"]
pub ctl0: CTL0,
}
#[doc = "ID (r) register accessor: an alias for `Reg<ID_SPEC>`"]
pub type ID = crate::Reg<id::ID_SPEC>;
#[doc = "ID code register"]
pub mod... |
extern crate util;
extern crate termion;
use std::process;
use termion::{color, style};
use util::{get_notes, get_books, Note, Book};
pub fn run(book: Option<String>, all: bool) -> () {
match book {
Some(book) => {
let notes = get_notes(&book).unwrap_or_else(|e| {
println!("Cou... |
// Copyright 2020 WHTCORPS INC
//
// 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 writing, sof... |
#![feature(alloc)]
#![feature(allocator_api)]
#![feature(const_fn)]
#![feature(try_trait)]
#![no_std]
extern crate alloc;
extern crate uefi;
use alloc::heap::{Alloc, AllocErr, Layout};
use core::ops::Try;
use uefi::memory::MemoryType;
use uefi::system::SystemTable;
static mut UEFI: *mut SystemTable = 0 as *mut Syste... |
// Automatically generate README.md from rustdoc.
use std::env;
use std::fs::{self, File};
use std::io::Write;
use std::path::{Path, PathBuf};
fn generate_readme() {
// Check for environment variable "SKIP_README". If it is set,
// skip README generation
if env::var_os("SKIP_README").is_some() {
r... |
use {Parcel, Error};
use std::io::prelude::*;
impl Parcel for char
{
fn read(read: &mut Read) -> Result<Self, Error> {
use std::convert::TryFrom;
let bytes = u32::read(read)?;
Ok(char::try_from(bytes)?)
}
fn write(&self, write: &mut Write) -> Result<(), Error> {
(*self as... |
// following pointers from http://norvig.com/lispy.html
use std::io::{stdout, stdin, Write};
use std::collections::HashSet;
// special characters
fn is_id(c: &char, tbl: &HashSet<char>) -> bool {
tbl.contains(c)
}
// whitespace
fn is_ws(c: &char) -> bool {
c == &' ' || c == &'\n' || c == &'\t'
}
#[derive(Deb... |
use std::ops::Add;
use std::ops::Sub;
#[derive(Clone, Copy, Eq, PartialEq, Hash, Debug)]
pub struct V {
pub x: i8,
pub y: i8,
}
impl Default for V {
fn default() -> Self {
V { x: 0, y: 0 }
}
}
impl Add<V> for V {
type Output = V;
fn add(self, rhs: V) -> Self {
V {
... |
pub trait TypeEquals<T> {}
impl<T> TypeEquals<T> for T {}
pub fn assert_type_eq<T1, T2>()
where T1: TypeEquals<T2>
{}
|
fn main() {
const SERIAL_NUMBER: usize = 8868;
{
let mut max_value = 0;
let mut max_coord = (0, 0);
for x in 1..=(300 - 2) {
for y in 1..=(300 - 2) {
let mut value = 0;
for offset_x in 0..=2 {
for offset_y in 0..=2 {
... |
use super::decimals::precision;
use super::LogicError;
/// Find the longest coin with the most decimal places in a vector of coins
fn longest_coin(coins: &[f64]) -> u32 {
coins.iter().map(|x| precision(*x).unwrap()).max().unwrap()
}
/// Normalize a vector of coins by multiplying every coin with a given factor.
fn... |
// generate a bunch of deviation surveys by permuting various
// lists of options.
#[macro_use]
extern crate itertools;
mod kop; // kick-off point
mod method; // survey computation method
mod north; // north reference
mod survey; // utilities to write out header an... |
fn main() {
let name = String::from("Anas Ahmed");
let fname = &name[0..4]; // [start..end] range syntax
let lname = &name[5..];
println!("{} {}", fname, lname);
let mut s = String::from("hello world");
let word = first_word(&s);
println!("{}", word);
s.clear();
// println!("{}", ... |
use crate::intcode::*;
use std::collections::HashMap;
use std::fmt;
#[derive(Debug, Clone, Copy, PartialEq)]
enum Direction {
Up,
Left,
Down,
Right,
}
impl Direction {
fn x(&self) -> i32 {
match self {
Up => 0,
Down => 0,
Left => -1,
Right =>... |
use std::fs;
fn react_polymer(buffer: &mut Vec<u8>) -> usize {
while buffer.len() > 1 {
let old_size = buffer.len();
for i in 0..buffer.len() - 1 {
let current = buffer[i];
let next = buffer[i + 1];
if (current.is_ascii_lowercase() && current.to_ascii_uppercase()... |
#[macro_use] extern crate tracing;
pub mod args;
pub mod commands;
pub mod ctx;
pub mod manager;
mod module;
mod raw_args;
pub use module::CommandsModule;
/// A convenience module containing common imports.
pub mod prelude {
pub use crate::commands::{Command, CommandInfo};
pub use crate::ctx::{CommandCtx, Co... |
#![crate_type = "dylib"]
#![no_std]
#![allow(ctypes)]
#![feature(link_args)]
extern "rust-intrinsic" {
pub fn transmute<T,U>(val: T) -> U;
pub fn size_of<T>() -> uint;
}
#[no_mangle]
pub extern fn load_module() -> int {0}
#[no_mangle]
pub extern fn reload_module() -> int {0}
#[no_mangle]
pub extern fn unlo... |
#![deny(warnings)]
use serde::{Serialize, Deserialize};
use crate::util::tx::Tx;
pub fn test(){
println!("utxo");
}
#[derive(Debug,Serialize, Deserialize,PartialEq, Clone)]
pub struct Utxo{
pub time:u64,
pub input:Tx,
pub output:Tx
}
impl Utxo {
pub fn new(input: Tx, output:Tx) -> Utxo {
... |
use std::{any::Any, sync::Arc};
use async_trait::async_trait;
use datafusion::{
arrow::{
array::{
Array, ArrayRef, BooleanBuilder, Int64Builder, ListBuilder, StringBuilder,
UInt16Builder, UInt32Builder,
},
datatypes::{DataType, Field, Schema, SchemaRef},
reco... |
// This example records audio and plays it back in real time as it's being
// recorded.
use fon::{mono::Mono32, Audio, Sink};
use pasts::exec;
use wavy::{Microphone, MicrophoneStream, Speakers, SpeakersSink};
/// An event handled by the event loop.
enum Event<'a> {
/// Speaker is ready to play more audio.
Pla... |
extern crate piston_window;
extern crate music;
use piston_window::*;
#[derive(Copy, Clone, Hash, PartialEq, Eq)]
enum Music {
Piano,
}
fn main() {
let window: PistonWindow = WindowSettings::new("Test music", [640, 480])
.exit_on_esc(true)
.build()
.unwrap();
music::start::<Music... |
#![cfg(test)]
#[allow(unused_imports)]
use tracing::{info, warn, debug, error, trace, instrument, span, Level};
use std::result::Result;
use crate::error::*;
use rand::{RngCore};
use super::*;
#[test]
fn test_secure_random() {
crate::utils::bootstrap_test_env();
let t = 1024;
for _ in 0..t {
let... |
/*
* @lc app=leetcode id=344 lang=rust
*
* [344] Reverse String
*
* https://leetcode.com/problems/reverse-string/description/
*
* algorithms
* Easy (63.82%)
* Total Accepted: 530.8K
* Total Submissions: 822.1K
* Testcase Example: '["h","e","l","l","o"]'
*
* Write a function that reverses a string. The ... |
#![cfg_attr(not(feature = "use_std"), no_std)]
#[cfg(feature = "use_std")]
mod vec;
pub const MAX_BITS: usize = 32;
const BYTE_BITS: usize = 8;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct BitPack<B> {
buff: B,
cursor: usize,
bits: usize
}
impl<B> BitPack<B> {
#[inline]
pub fn new(buff: B)... |
use std::fmt;
macro_rules! new_ty {
($ty: ident; $size: expr) => {
#[derive(Clone)]
pub struct $ty([u8; $size]);
impl Default for $ty {
fn default() -> Self {
Self([0; $size])
}
}
impl fmt::Debug for $ty {
fn fmt(&self, f... |
pub use self::point::Point;
pub use self::size::Size;
pub use self::vector2f::Vector2f;
pub use self::rectangle::Rectangle;
mod point;
mod size;
mod rectangle;
mod vector2f;
|
pub mod thompson_max;
pub mod ucb_tuned;
pub mod random;
pub mod option;
use rand::Rng;
pub use thompson_max::ThompsonMax;
pub use ucb_tuned::UcbTuned;
pub use random::RandomSearch;
pub use option::Optional;
pub trait Distribution: Clone
{
type ScoreType;
/// returns a default distribution
fn new() -> Self;... |
//! Module with protobuf generated files from `schema/exonum`.
// For rust-protobuf generated files.
#![allow(bare_trait_objects)]
#![allow(renamed_and_removed_lints)]
include!(concat!(env!("OUT_DIR"), "/exonum_proto_mod.rs"));
|
#![feature(const_caller_location)]
#![feature(const_fn)]
#![feature(core_intrinsics)]
#![feature(negative_impls)]
#![feature(test)]
#![cfg_attr(not(feature = "std"), no_std)]
// #![cfg_attr(feature = "kern", feature(const_fn))]
#[cfg(feature = "std")]
pub use std as core;
#[cfg(feature = "std")]
pub use std as alloc... |
use std::str::FromStr;
use common::{default_puzzle, BadInput, Puzzle};
struct Password {
policy_min: usize,
policy_max: usize,
policy_char: char,
password: String,
}
impl Password {
fn is_valid_v1(&self) -> bool {
let count = self
.password
.chars()
.fi... |
use crate::typer;
use crossterm::{
cursor::{self, MoveTo, MoveToNextLine},
event::{self, Event, KeyCode},
execute, queue,
style::{self, Color, Colors, SetColors, SetForegroundColor},
terminal::{self, disable_raw_mode, enable_raw_mode, ClearType},
};
use std::io::Write;
const INFO: &str = "To exit, ... |
use http::{header, response::Builder, Response};
use hyper::Body;
use serde::Serialize;
#[derive(Debug)]
pub enum JsonError {
Serialize(serde_json::Error),
Http(http::Error),
}
pub trait ResponseExt {
fn json<T>(self, json: &T) -> Result<Response<Body>, JsonError>
where
T: Serialize;
}
impl R... |
mod clean_zone;
mod cluster;
mod database;
mod device_manager;
mod ddml;
mod fs;
mod idml;
mod pool;
mod raid;
mod vdev_block;
mod vdev_file;
|
#![allow(dead_code)]
use std::ops::{ Mul, Add, AddAssign };
use super::vec3::Vec3;
use super::utility::clamp;
#[derive(Debug, Copy, Clone)]
pub struct Color(pub f64, pub f64, pub f64);
impl Color {
pub fn rf64(&self) -> f64 {
self.0
}
pub fn gf64(&self) -> f64 {
self.1
}
pub fn bf64(&sel... |
// Copyright 2012 Derek A. Rhodes. All rights reserved.
// This library is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as
// published by the Free Software Foundation; either version 2 of the
// licence, or (at your option) any later version.
// ... |
mod event;
mod listener;
mod listener_handle;
mod listener_settings;
mod listener_settings_builder;
pub use event::*;
pub use listener::*;
pub use listener_handle::*;
pub use listener_settings::*;
pub use listener_settings_builder::*;
|
extern crate rand;
extern crate num_bigint as bigint;
use bigint::*;
pub fn get_nist_prime() -> BigUint {
BigUint::parse_bytes(b"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f... |
use super::console;
#[derive(Hash, PartialEq, Eq, Copy)]
pub enum Key {
A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z,
Up, Down, Left, Right, Space, Control, Alt, Shift, Enter, Esc,
N1, N2, N3, N4, N5, N6, N7, N8, N9, N0, Plus, Minus, Backspace
}
impl Key {
pub f... |
use std::io;
pub enum AppError {
Code { full: usize, short: u16 },
Message(String),
IOWrapper(io::Error),
Unknown,
}
impl AppError {
pub fn print_kind(&self, mut to: &mut impl io::Write) -> io::Result<()> {
let kind = match self {
AppError::Code { full: _, short: _ } => "Code",... |
use crate::hash::hash;
use std::sync::Arc;
mod kinds;
pub use kinds::*;
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum Child {
Node {
relative_offset: usize,
node: Arc<Node>,
},
Token {
relative_offset: usize,
token: Arc<Token>,
},
}
impl Child {
pub fn len(... |
use rust_ml::rust_ml;
rust_ml! {
add1 :: u8 -> u8
add1 a = a + 1
}
fn main() {
assert_eq!(add1(3), 4);
}
|
use gloo_utils::errors::JsError;
use thiserror::Error as ThisError;
/// All the errors returned by this crate.
#[derive(Debug, ThisError)]
pub enum Error {
/// Error returned by JavaScript.
#[error("{0}")]
JsError(JsError),
/// Error returned by `serde` during deserialization.
#[cfg(feature = "json... |
#[doc = "Register `STAT1` reader"]
pub struct R(crate::R<STAT1_SPEC>);
impl core::ops::Deref for R {
type Target = crate::R<STAT1_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<crate::R<STAT1_SPEC>> for R {
#[inline(always)]
fn from(reader: crate::R<STA... |
fn push_int_twice(v: &mut Vec<i32>, n: &i32) {
v.push(*n);
v.push(*n);
}
// fn push_int_twice(v: &mut Vec<i32>, n: &i32) {
// }
fn main() {
let mut my_vector = vec![0];
let my_int_reference = &my_vector[0];
push_int_twice(&mut my_vector, my_int_reference);
}
|
use crate::events::Completable;
use crate::units::player_unit_system_upgradepath::PlayerUnitSystemUpgradePath;
use serde_derive::{Deserialize, Serialize};
#[repr(u32)]
#[derive(Debug, Default, Serialize, Deserialize, Clone, Copy, Hash, Eq, PartialEq)]
pub enum PlayerUnitSystemKind {
#[default]
#[serde(rename =... |
use collections::string::String;
use collections::string::ToString;
use rcc;
use Peripheral;
use IRQType;
pub struct DMARegisters {
}
pub struct DMAStreamRegisters {
}
pub enum Channel {
Channel0 = 0,
Channel1 = 1,
Channel2 = 2,
Channel3 = 3,
Channel4 = 4,
Channel5 = 5,
Channel6 = 6,
... |
// 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... |
//! https://developer.mozilla.org/en-US/docs/Web/Events
use crate::{Attribute, Callback, Event};
use wasm_bindgen::JsCast;
pub use web_sys::{
AnimationEvent, HashChangeEvent, KeyboardEvent, MouseEvent, TransitionEvent,
};
use web_sys::{EventTarget, HtmlInputElement, HtmlTextAreaElement};
/// an event builder
pub ... |
/// This is a doubly-linked list implementation with forward pointers being owners and backward
/// pointers being unsafe pointers. The goal is to write the unsafe code involving the backward
/// links as similarly as the safe code for the forward links to avoid rampant stupidity.
use std::borrow::Borrow;
use std::bor... |
//! This module contains enum Error.
//! Error type represents all possible errors that can occur when dealing
//! with the generic or any dedicated-exchange API
use std::error;
use std::fmt;
#[derive(Debug)]
pub enum Error {
ServiceUnavailable,
BadParse,
InvalidLogin,
InvalidArguments,
RateLimitE... |
pub mod bencode_ref;
pub mod decode_opt;
pub mod decode; |
mod utils;
use wasm_bindgen::prelude::*;
// blowfish
#[macro_use] extern crate hex_literal;
mod c2_chacha20;
mod blowfish_cbc;
mod crypto_aes;
mod crypto_blowfish;
mod chacha20_poly1305;
// aesgcmsiv
extern crate aes_gcm_siv;
use aes_gcm_siv::{Aes256GcmSiv, AesGcmSiv}; // Or `Aes128GcmSiv`
use aead::{Aead, NewAea... |
fn num_divisors(input:u32) -> u32 {
let limit = f32::sqrt(input as f32) as u32;
let mut total = 2;
for i in 2..(limit+1) {
if input%i == 0 {
total += 2;
}
}
if limit*limit == input { total -= 1; }
total
}
fn main() {
let mut triangle_number = 0;
for i in 1..... |
use ast::*;
use lexer::Lexer;
use token::Token;
pub struct Parser<'a> {
lexer: Lexer<'a>,
unused_lookahead: Option<Token>,
had_error: bool,
}
impl<'a> Parser<'a> {
pub fn new(lexer: Lexer<'a>) -> Parser<'a> {
Parser { lexer, unused_lookahead: None, had_error: false }
}
pub fn had_erro... |
extern crate rand;
fn main() {
let seed: i64 = generate_seed();
println!("{:?}", seed);
}
use rand::Rng;
fn generate_seed() -> i64 {
return rand::thread_rng().gen_range(1_000_000_000, 10_000_000_000);
}
|
// Copyright (c) 2015 Alcatel-Lucent, (c) 2016 Nokia
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
// * Redistributions of source code must retain the above copyright
// notice,... |
use std::io::{Result, Error, ErrorKind};
use async_stream::try_stream;
use bytes::{BytesMut, Buf};
use futures_core::stream::Stream;
use tokio::io::AsyncReadExt;
use tokio::net::tcp::ReadHalf;
trait SighFactoryExt {
fn peek_u16(&self, offset: usize) -> Option<u16>;
fn peek_u32(&self, offset: usize) -> Option<... |
use super::{
expression::clone_filter, Event, Expression, Irp, ParameterSpec, RepeatMarker, Vartable,
};
use log::trace;
use std::{
collections::HashMap,
ops::{Add, BitAnd, BitOr, BitXor, Neg, Not, Rem, Shl, Shr, Sub},
rc::Rc,
};
/**
* Here we build the decoder nfa (non-deterministic finite automation... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.