text
stringlengths
8
4.13M
// Copyright 2020 The Grin Developers // // 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 agree...
use std::io::{Write, Result as IOResult}; use ansi_term::ANSIStrings; use fs::File; use output::file_name::{FileName, FileStyle}; use style::Colours; /// The lines view literally just displays each file, line-by-line. pub struct Render<'a> { pub files: Vec<File<'a>>, pub colours: &'a Colours, pub style:...
#![feature(asm)] #![feature(thread_local)] use std::thread; #[thread_local] static mut TLS_DATA: usize = 1; #[thread_local] static mut TLS_BSS: usize = 0; fn main() { unsafe { asm!("xchg bx, bx" : : : "memory" : "intel", "volatile") }; unsafe { TLS_DATA += 1; TLS_BSS += 1; println!("...
mod fixes; mod problem; mod inspection_impl; struct InspectionRegistrar { } trait Inspection { fn register(holder: InspectionRegistrar); } struct A { } impl A { fn foo(&mut self) -> i32 { 32 } } fn main() { let a = A {}; let c = A::foo; }
use std::panic; use rocket::{self, http::{ContentType, Header, Status, StatusClass}, local::Client}; use diesel::connection::SimpleConnection; use horus_server::{self, routes::dist::*}; use test::{run_test, sql::*}; #[test] fn legacy_redirect() { run(|| { let client = get_client(); let req = clie...
extern crate time; extern crate serde; extern crate serde_json; extern crate sha2; use sha2::{Sha256, Digest}; use std::fmt::Write; #[debug(Serialize, Clone, Debug)] struct Transaction { sender: String, reciever: String, amount: f32, } #[debug(Serialize, Debug)] pub struct Blockheader { timestamp: i6...
pub mod vector{ use std::ops::{Add, Sub, Mul, BitXor}; use std::f64::EPSILON as F_EPSILON; // Clone is so we have the clone() method available for out struct // Copy is so everytime we attempt to give away ownership we clone() instead #[derive(Debug, Clone, Copy)] pub struct Vector{ pub x: f64, pub y: f64, ...
#![feature(option_filter)] use std::io::{self, Read}; mod lex; mod parse; use lex::Lexer; use lex::Token; use parse::parse_object; fn main() { let mut buffer = String::new(); if io::stdin().read_to_string(&mut buffer).is_ok() { let mut lexer = Lexer { chars: buffer.chars().peekable(), ...
use itertools::Itertools; trait Distance<T> { fn manhattan_distance(self, t: Self) -> T; } type Coordinate = (i32, i32); impl Distance<i32> for Coordinate { fn manhattan_distance(self, to: Coordinate) -> i32 { (self.0 - to.0).abs() + (self.1 - to.1).abs() } } #[derive(Debug, PartialEq, Eq, Clone, Copy, Ha...
use crate::algorithms::human::Human; use crate::algorithms::monte_carlo::MonteCarlo; use crate::algorithms::random::Random; use crate::game::Game; use crate::utils::plural; use itertools::Itertools; mod action; mod algorithms; mod card; mod game; mod player; mod power; mod resources; mod table; mod utils; mod wonder; ...
#![deny(clippy::all)] //! Riddle crate containing common utilities and types needed by platform implementations //! and which other crates can use to interact with a platform service without needing to //! know or genericize for the platform system type being used. //! //! Most types in here are either consumed or ree...
pub use self::arch::*; #[cfg(target_arch = "x86")] #[path="x86/tss.rs"] mod arch; #[cfg(target_arch = "x86_64")] #[path="x86_64/tss.rs"] mod arch;
mod ast; mod builtin; mod common; mod error; mod parse; mod pattern; use common::*; use std::io::Read; fn repl(verbose: bool) { let mut i = 0; let mut buf = String::new(); let mut env = builtin::totals(); // I copied this from clap: https://kbknapp.github.io/clap-rs/src/clap/macros.rs.html#632-640 ...
use std::collections::HashSet; use std::io::{self, BufRead}; fn main() { let numbers = io::stdin() .lock() .lines() .map(|x| x.unwrap().parse().unwrap()) .collect::<Vec<_>>(); let mut seen = HashSet::new(); let mut sum = 0; for num in numbers.iter().cycle() { if ...
use std::io; use std::pin::Pin; use std::task::{Context, Poll}; use std::net::{SocketAddr, IpAddr, Ipv4Addr}; use futures::executor::block_on; use tokio::io::{AsyncRead, AsyncWrite}; use tokio::net::{TcpStream, TcpListener}; use async_trait::async_trait; use super::{AsyncConnect, AsyncAccept, IOStream}; use crate::dn...
use crate::*; pub fn init_struct(globals: &mut Globals) -> Value { let id = globals.get_ident_id("Struct"); let class = ClassRef::from(id, globals.builtins.object); let class = Value::class(globals, class); globals.add_builtin_class_method(class, "new", struct_new); class } fn struct_new(vm: &mut ...
#[cfg(test)] mod tests { use compiled_uuid::uuid; use uuid::Uuid; // const _: Uuid = uuid!("F9168C5E-CEB2-4FAA-B6BF-329BF39FA1G4"); const _: Uuid = uuid!("F9168C5E-CEB2-4FAA-B6BF-329BF39FA1E4"); const _: Uuid = uuid!("F9168C5ECEB24FAAB6BF329BF39FA1E4"); const _: Uuid = uuid!("550e8400-e29b-41d4...
//! Additional, experimental, strategies. //! //! Some more strategies are available here, if the `experimental-strategies` feature flag is //! enabled. //! //! Note that these strategies **are not part of the API stability guarantees** and may be changed, //! renamed or removed at any point in time. They are also not ...
fn main() { println!("Hello, Rust world! - 日本語はどうだ!"); }
use std::collections::HashMap; use crate::util::time; pub fn day21() { println!("== Day 21 =="); let input = "src/day21/input.txt"; time(part_a, input, "A"); time(part_b, input, "B"); } #[derive(Copy, Clone, Hash, Debug, Eq, PartialEq)] enum Operation { Add, Sub, Div, Mul, Eql, } ...
extern crate marafet_parser as parser; extern crate marafet_util as util; use std::io::{Write, Result}; use std::collections::HashMap; use parser::{Ast, Block}; use parser::css::{Rule, Selector}; use util::join; pub struct Settings<'a> { pub block_name: &'a String, pub vars: &'a HashMap<String, String>, } ...
#![deny(missing_docs)] use std::{ops, slice, u32}; use std::default::Default; use std::time::Duration; /// The number of buckets in a latency histogram. pub const NUM_BUCKETS: usize = 26; /// The maximum value (inclusive) for each latency bucket in /// tenths of a millisecond. pub const BUCKET_BOUNDS: [Latency; NUM_...
use blake2::{Blake2b, Digest}; use std::error::Error; use std::fs; use std::io; use std::path::PathBuf; pub(crate) trait PathUtilities { /// Returns a file's Blake2 hash. fn blake2(&self) -> io::Result<String>; /// Returns all files within a directory, optionally of certain `sizes`. fn files_within(&s...
pub const ENDPOINT_IN: u8 = 0x80; pub const ENDPOINT_OUT: u8 = 0x00; pub const STLINK_RX_EP: u8 = 1 | ENDPOINT_IN; pub const STLINK_TX_EP: u8 = 2 | ENDPOINT_OUT; pub const STLINK_TRACE_EP: u8 = 3 | ENDPOINT_IN; pub const STLINK_CMD_SIZE_V2: usize = 16; pub const STLINK_GET_VERSION: u8 = 0xF1; pub const STLINK_DEBUG_...
//! Pieces pertaining to the HTTP message protocol. use std::borrow::Cow; use std::fmt; use bytes::BytesMut; use header::{Connection, ConnectionOption, Expect}; use header::Headers; use method::Method; use status::StatusCode; use uri::Uri; use version::HttpVersion; use version::HttpVersion::{Http10, Http11}; pub use...
use std::error::Error as StdError; use std::fmt; use std::marker::PhantomData; pub use err::Error; pub use hyper::Error as HttpError; pub use hyper::error::Result as HttpResult; use hyper::status::StatusCode; #[derive(Debug)] pub enum ErrorTiming { AtNetwork, AtRequest, AtResponse, } #[derive(Debug)] pub...
use crate::completions::{Completer, CompletionOptions}; use nu_protocol::{ engine::{EngineState, StateWorkingSet}, Span, }; use reedline::Suggestion; use std::sync::Arc; #[derive(Clone)] pub struct VariableCompletion { engine_state: Arc<EngineState>, } impl VariableCompletion { pub fn new(engine_state...
const MINIMUM_VALUE: u32 = 206_938; const MAXIMUM_VALUE: u32 = 679_128; // I'm not _unhappy_ with this implementation, but it's simplistic. // You really want to look at AxlLind's: // https://github.com/AxlLind/AdventOfCode2019/blob/master/src/bin/04.rs // It's a thing of beauty, and runs in a fraction of the time of ...
#[doc = "Register `MID` reader"] pub type R = crate::R<MID_SPEC>; #[doc = "Field `MID` reader - Magic ID"] pub type MID_R = crate::FieldReader<u32>; impl R { #[doc = "Bits 0:31 - Magic ID"] #[inline(always)] pub fn mid(&self) -> MID_R { MID_R::new(self.bits) } } #[doc = "magic ID\n\nYou can [`re...
fn is_prime(curr_n: u32, primes: &Vec<u32>) -> bool { let sqr = (curr_n as f64).sqrt().ceil() as u32; let mut prime_range = primes.iter().take_while(|x| **x <= sqr); prime_range.all(|p| curr_n % p != 0) } pub fn nth(n: u32) -> Option<u32> { if n == 0 { return None; } let (mut last_...
mod day1; mod day2; mod day3; fn main() { if false { day1::main(); day2::main(); } day3::main(); }
pub use crate::common::{Const, Id, Op2}; #[derive(PartialEq, Eq, Debug, Clone)] pub enum Expr<Ty> { Var(Id), Const(Const), Op2(Op2, Box<Expr<Ty>>, Box<Expr<Ty>>), Fun(Id, Ty, Box<Expr<Ty>>), App(Box<Expr<Ty>>, Box<Expr<Ty>>), If(Box<Expr<Ty>>, Box<Expr<Ty>>, Box<Expr<Ty>>), Let(Id, Box<Expr...
use std::collections::HashSet; use color_eyre::eyre::{eyre, WrapErr}; use color_eyre::Result; use cursive::{CbSink, Cursive, CursiveExt}; use cursive::direction::Orientation::Vertical; use cursive::traits::{Nameable, Resizable, Scrollable}; use cursive::views::{Dialog, EditView, LinearLayout, ListView, TextView}; use ...
use std::collections::HashMap; use std::error::Error; use rusoto_core::credential::{ChainProvider, ProvideAwsCredentials}; use rusoto_core::param::{Params, ServiceParams}; use rusoto_core::Region; use rusoto_signature::SignedRequest; use serde_json::json; /// The authentication options to be passed into the main auth...
use ansi_colors::*; fn main(){ let mut pass = ColouredStr::new("ansi_coloring"); pass.white(); pass.bold(); pass.hidden(); println!("{}",pass); }
use iced::{ button, executor, Application, Button, Column, Command, Element, Row, Subscription, Text, }; use crate::jsonrpc::{self, JsonRpc}; use crate::statuses::{self, Statuses}; pub struct App { record_status_buttons: Vec<RecordStatusButton>, button: button::State, statuses: Statuses, jsonrpc: ...
pub fn run(){ let mut numbers:Vec<i32>=vec![10,7,100,87,99,65,2,1,34,0]; numbers.sort(); println!("Assending order sort: {:?}", numbers); //Smallest Number println!("Smallest Number: {}", numbers[0]); numbers.reverse(); println!("Desending order sort: {:?}", numbers); //Largest Number...
#[doc = "Register `TAFCR` reader"] pub type R = crate::R<TAFCR_SPEC>; #[doc = "Register `TAFCR` writer"] pub type W = crate::W<TAFCR_SPEC>; #[doc = "Field `TAMP1E` reader - Tamper 1 detection enable"] pub type TAMP1E_R = crate::BitReader<TAMP1E_A>; #[doc = "Tamper 1 detection enable\n\nValue on reset: 0"] #[derive(Clon...
pub mod error; pub mod process; pub mod util; pub use checksec; pub use goblin; pub use ropr;
#![feature(no_std)] #![feature(lang_items)] #![feature(core)] #![feature(asm)] #![no_std] use prelude::*; #[macro_use] extern crate core; mod std { pub use core::fmt; pub use core::cmp; pub use core::ops; pub use core::iter; pub use core::option; pub use core::marker; } mod prelude; #[macro_use] mod macros; ...
extern crate std; use app; pub fn new_directory(directory: &str) -> std::io::Result<()> { std::fs::create_dir(directory)?; Ok(()) } pub fn new_file(file_path: &str) -> std::io::Result<()> { std::fs::write(file_path, b"")?; Ok(()) } pub fn temp_file() -> String { let timestamp = std::time::System...
use std::fmt::Debug; use bitflags::{ bitflags, __bitflags, __impl_bitflags }; use crate::prelude::*; use crate::scene::Scene; use crate::interaction::{ Interactions, BaseInteraction, Sample }; use crate::sampler::Sampler; use crate::math::*; use crate::math::Transform; mod point; pub use self::point::PointLight; bitf...
/* * Datadog API V1 Collection * * Collection of all Datadog Public endpoints. * * The version of the OpenAPI document: 1.0 * Contact: support@datadoghq.com * Generated by: https://openapi-generator.tech */ /// UsageIndexedSpansResponse : A response containing indexed spans usage. #[derive(Clone, Debug, Par...
use specs::{Component, VecStorage}; #[derive(Debug, Component)] #[storage(VecStorage)] pub struct Note { pub line_layer: i32, pub line_index: i32, pub note_type: i32, pub time: f32, pub direction: i32, }
use uuid::Uuid; use serde::{Serialize, Deserialize, }; use std::collections::HashMap; #[derive(Debug, PartialEq, Serialize, Deserialize, Clone)] enum Predicate { AND(Vec<Predicate>), OR(Vec<Predicate>), Not(Box<Predicate>), TRUE, FALSE, EQ(SPValue, SPValue), // use SPValue::ID to fetch the v...
//! Common utilities use rand::Rng; // Public types /// 2x2 Matrix pub type Mat2 = [f32; 4]; /// 2x3 Matrix pub type Mat2d = [f32; 6]; /// 3x3 Matrix pub type Mat3 = [f32; 9]; /// 4x4 Matrix pub type Mat4 = [f32; 16]; /// Quaternion pub type Quat = [f32; 4]; /// Dual Quaternion pub type Quat2 = [f32; 8]; /// 2 Dimen...
extern crate clap; use clap::{App, Arg, ArgMatches}; extern crate reqwest; use reqwest::{Client, Response, Url}; #[macro_use] extern crate hyper; use hyper::header::Headers; extern crate serde_json; use std::collections::BTreeMap; use std::error::Error; use std::fmt; use std::fs::{File, OpenOptions}; use std::io; u...
extern crate quux; fn main() { let mut y = 2; { let x = || { 7 + y }; let retval = quux::quux00(x); println!("retval: {:?}", retval); } y = 5; println!("y : {:?}", y); }
/* Copyright 2019-2023 Didier Plaindoux 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...
// Copyright 2019. The Tari Project // SPDX-License-Identifier: BSD-3-Clause use crate::{ keys::{PublicKey, SecretKey}, ristretto::{RistrettoPublicKey, RistrettoSecretKey}, }; pub(crate) fn get_keypair() -> (RistrettoSecretKey, RistrettoPublicKey) { let mut rng = rand::thread_rng(); let k = RistrettoS...
/// Computes the `Address` of an `Account / Template`. /// /// The algorithm must be deterministic. pub trait ComputeAddress<T> { type Address; fn compute(item: &T) -> Self::Address; }
use util::mem::{read_u16, read_u32, write_u16, write_u32}; use super::{PAL_MASK, PAL_SIZE}; pub struct Palette { pub(crate) data: [u8; PAL_SIZE as usize], } impl Default for Palette { fn default() -> Self { Palette { data: [0; PAL_SIZE as usize], } } } impl Palette { pub ...
use std::path::{Path, PathBuf}; use std::process::{self, Command}; use std::{env, fs, io}; use crate::{redoxer_dir, status_error, target}; //TODO: Rewrite with hyper or reqwest, tar-rs, sha2, and some gzip crate? fn download<P: AsRef<Path>>(url: &str, path: P) -> io::Result<()> { Command::new("curl") .arg...
fn main() { // vertex shader let a = " #version 110 uniform mat4 matrix; attribute vec2 position; attribute vec3 color; varying vec3 v_color; void main() { gl_Position = vec4(position, 0.0, 1.0) * matrix; v_color = color; } ";...
use crate::types::linalg::dimension::Dimension; use sdl2::event::{Event, WindowEvent}; use sdl2::keyboard::Scancode; use sdl2::video::{GLContext, Window}; use sdl2::Sdl; use std::ffi::c_void; pub struct Demo { sdl: Sdl, window: Window, _gl_context: GLContext, // Make sure that current gl_context isn't drop...
fn main() { let x: u32 =5; println!("our number is {}",x); { let mut x=x; loop { println!("and now {}",x); x=x-1; if x==0 { break; } } } println!("but our number is fine {}",x); }
use std::collections::hash_map::{Entry, HashMap}; use actix::prelude::*; use futures::{future, Future}; #[cfg(feature = "python")] use cpython::{PyDict, Python, ToPyObject}; use crate::opentracing::tags::{IkrellnTags, KnownTag, OpenTracingTag}; #[derive(Default)] pub struct TraceParser; impl Actor for TraceParser {...
mod r#async; mod sync; use std::sync::atomic::AtomicU64; pub use r#async::BufferUnorderedBatchedAsync; use serde_derive::{Deserialize, Serialize}; pub use sync::BufferUnorderedBatchedSync; #[derive(Debug)] pub struct BufferUnorderedBatchedStats { pub buffer: AtomicU64, pub buffer_total: AtomicU64, pub pa...
#![cfg_attr(feature = "clippy", allow(unstable_features))] #![cfg_attr(feature = "clippy", feature(plugin))] #![cfg_attr(feature = "clippy", plugin(clippy))] #![cfg_attr(feature = "clippy", deny(warnings))] use std::borrow::Borrow; use std::hash::{BuildHasher,Hash}; use std::collections; pub trait MapLike<'a, K: 'a, ...
use cpal::{SampleRate, Stream}; use ringbuf::{Consumer, RingBuffer}; use srt_media::{ source::{ filters::{AudioFilter, AudioFormat}, SrtSource, StreamDescriptor, }, FrameData, NextFrameResult, }; use stainless_ffmpeg::prelude::*; const SAMPLE_RATE: SampleRate = SampleRate(48_000); fn main() { pretty_e...
use std::iter; use std::str::Chars; use peekmore::PeekMore; use crate::token::*; #[derive(Debug)] pub struct ScannerError { pub line: usize, pub desc: String, } #[derive(Debug)] pub struct Scanner<'a> { iter: peekmore::PeekMoreIterator<Chars<'a>>, buff: Vec<char>, line: usize, } impl<'a> Iterato...
use serde::{Deserialize, Serialize}; #[derive(Serialize, Debug)] pub struct Info { pub apiversion: String, #[serde(skip_serializing_if = "Option::is_none")] pub author: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] pub color: Option<String>, #[serde(skip_serializing_if = "Op...
//! Defines the `MoveGenerator` trait. use std::mem::uninitialized; use std::cmp::max; use uci::SetOption; use board::*; use moves::*; use value::*; use evaluator::Evaluator; use bitsets::*; use utils::BoardGeometry; /// A trait for move generators. /// /// A `MoveGenerator` holds a chess position and can: /// /// *...
// &'static is a "lifetime specifier", something you'll learn more about later pub fn hello() -> &'static str { "Hello, World!" } // This stub file contains items which aren't used yet; feel free to remove this module attribute // to enable stricter warnings. #![allow(unused)] pub fn expected_minutes_in_oven() -> ...
#![feature(plugin)] #![feature(proc_macro)] #![plugin(rocket_codegen)] extern crate maud; extern crate rocket; use maud::{html, Markup}; use std::borrow::Cow; #[get("/<name>")] fn hello<'a>(name: Cow<'a, str>) -> Markup { html! { h1 { "Hello, " (name) "!" } p "Nice to meet you!" p {"🥁Hi,...
extern crate iron; extern crate router; use iron::prelude::*; use router::router; mod handlers; static SERVER_ADDR: &str = "localhost:3000"; fn main() { let router = router!( index: get "/" => handlers::index, index_name: get "/:name" => handlers::index_name ); let _server = Iron::new(ro...
// Copyright 2019 The Tari Project // SPDX-License-Identifier: BSD-3-Clause //! A commitment is like a sealed envelope. You put some information inside the envelope, and then seal (commit) it. //! You can't change what you've said, but also, no-one knows what you've said until you're ready to open (open) the //! envel...
use crate::lib::error::DfxError; use ring::error::Unspecified; use std::boxed::Box; use std::path::PathBuf; use thiserror::Error; #[derive(Error, Debug)] pub enum IdentityError { #[error("Identity already exists.")] IdentityAlreadyExists(), #[error("Identity {0} does not exist at '{1}'.")] IdentityDo...
use std::collections::HashMap; use serde::ser::{Error, SerializeMap}; use serde::{Serialize, Serializer}; use crate::{Element, Value}; use crate::error::TychoError; use crate::ident::ValueIdent; use crate::into::ident::Ident; use crate::serde::ser::TychoSerializer; use std::fmt; pub struct MapSerializer { conten...
// Copyright 2020 The MWC Developers // // 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...
use dors::DorsError; use dors::{all_tasks, run, run_with_args}; #[test] fn test_workspace_only() { [ "check", "should-be-on-member", "should-run-before-only-once", "should-run-after-only-once", "should-not-run-befores-on-members", ] .iter() .for_each(|task| asser...
// implements the voxel volume submodule pub struct Voxel { } impl Voxel { }
#![deny(clippy::pedantic)] #![allow(clippy::used_underscore_binding)] mod otp; use clap::Clap; use colored::Colorize; use itertools::Itertools; use onep_backend_api as api; use onep_backend_op as backend; use std::{collections::BTreeMap, convert::TryFrom}; use term_table::{ row::Row, table_cell::{Alignment, T...
pub mod peer; pub use peer::Peer;
#[doc = r"Register block"] #[repr(C)] pub struct RegisterBlock { #[doc = "0x00 - TIM14 control register 1"] pub cr1: CR1, _reserved1: [u8; 0x0a], #[doc = "0x0c - TIM14 Interrupt enable register"] pub dier: DIER, _reserved2: [u8; 0x02], #[doc = "0x10 - TIM14 status register"] pub sr: SR, ...
use sensor_value::SensorValue; use telegram_bot::types::refs::UserId; use actix_files as axtix_fs; use actix_identity::{CookieIdentityPolicy, IdentityService}; use actix_rt::System; use actix_web::web::{Bytes, Data}; use actix_web::HttpRequest; use actix_web::HttpResponse; use actix_web::{web, App, HttpServer, Respond...
pub mod config; pub mod devices; pub mod healthcheck; pub mod index; pub mod integrations; pub mod notifications; pub mod sessions; pub mod settings;
#[doc = "Reader of register HSEM_C2IER"] pub type R = crate::R<u32, super::HSEM_C2IER>; #[doc = "Writer for register HSEM_C2IER"] pub type W = crate::W<u32, super::HSEM_C2IER>; #[doc = "Register HSEM_C2IER `reset()`'s with value 0"] impl crate::ResetValue for super::HSEM_C2IER { type Type = u32; #[inline(always...
use hello_tf::InferRequest; use std::fs; use std::slice; use tensorflow::Tensor; use hello_tf::infer_client::InferClient; use tokio::runtime::Builder; fn main() { let rt = Builder::new_current_thread().enable_all().build().unwrap(); rt.block_on(async { let mut client = InferClient::connect("http://loc...
fn main() { let age:u32 = 1; if age>12{ println!("Hello world"); } else{ println!("Go out side"); } }
use core::marker::Copy; use core::ops::{Div, Rem}; pub fn div_rem<T: Copy + Div<T,Output=T> + Rem<T,Output=T>>(x: T, y: T) -> (T, T) { (x / y, x % y) }
use crate::isa; pub struct Decoder { table: [Option<isa::Opcode>; 256], } impl Decoder { pub fn new() -> Self { Decoder { table: build_opcode_table(), } } pub fn opcode(&self, code: u8) -> Option<isa::Opcode> { self.table[code as usize] } } // Build an array o...
// SPDX-License-Identifier: Apache-2.0 use mmap::Protections; use sgx_types::page::Flags; /// Convert `Protections` to `Flags` pub fn p2f(prot: Protections) -> Flags { let mut flags = Flags::empty(); if prot.contains(Protections::READ) { flags |= Flags::R; } if prot.contains(Protections::WRI...
use crate::error::RPCError; use ckb_jsonrpc_types::Alert; use ckb_logger::error; use ckb_network::NetworkController; use ckb_network_alert::{notifier::Notifier as AlertNotifier, verifier::Verifier as AlertVerifier}; use ckb_sync::NetworkProtocol; use ckb_types::{packed, prelude::*}; use ckb_util::Mutex; use jsonrpc_cor...
use clap::Clap; use itertools::Itertools; /// Largest palindrome product /// /// A palindromic number reads the same both ways. The /// largest palindrome made from the product of two /// 2-digit numbers is 9009 = 91 × 99. /// /// Find the largest palindrome made from the product /// of two 3-digit numbers. #[derive(C...
use crate::{ rels::Dir2D, symmetry::{Rot, DEG_0, DEG_180}, }; use std::{ collections::{HashMap, HashSet}, hash::Hash, }; #[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] pub struct TileDesc<T: Eq + Hash> { // How many symmetries are there? pub cardinality: usize, // Side type -> Rotations ...
extern crate tch; use tch::{Tensor, no_grad}; #[macro_use(c)] extern crate cute; fn _drop_rightmost_dim(t: Tensor) -> Tensor { let t = t.narrow(t.ld() as i64, 0, 1); t.reshape(&t.size().as_slice()[..t.ld()]) } pub trait TensorUtil { /// Last dimension fn ld(&self) -> usize; fn eshape(&self, i: us...
// This file is part of Substrate. // Copyright (C) 2019-2020 Parity Technologies (UK) Ltd. // SPDX-License-Identifier: Apache-2.0 // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // ht...
#[macro_use] extern crate log; fn main() { // RUST_LOG=info cargo run --bin output-log env_logger::init(); info!("starting up"); warn!("oops, nothing implemented!"); }
mod curve25519; // mod dh_group_sha1; pub use self::curve25519::Curve25519; // pub use self::dh_group_sha1::DhGroupSha1; use connection::Connection; use packet::Packet; pub enum KexResult { Ok(Packet), Done(Packet), Error, } pub trait KeyExchange { fn process(&mut self, conn: &mut Connection, packet...
extern crate rand; use std::env; mod vec3; use crate::rand::Rng; use rayon::prelude::{IndexedParallelIterator, IntoParallelIterator, ParallelIterator}; use vec3::Vec3; #[derive(Copy, Clone, Debug)] struct Ray { origin: Vec3, direction: Vec3, } impl Ray { fn new(origin: Vec3, direction: Vec3) -> Ray { ...
use crate::pool::TxPool; use ckb_types::core::TransactionView; use ckb_types::packed::ProposalShortId; use futures::future::Future; use tokio::prelude::{Async, Poll}; use tokio::sync::lock::Lock; pub struct FetchTxRPCProcess { pub tx_pool: Lock<TxPool>, pub proposal_id: Option<ProposalShortId>, } impl FetchTx...
use auto_impl::auto_impl; trait Supi {} #[auto_impl(Fn)] trait Foo: Supi { fn foo(&self, x: u32) -> String; } fn main() {}
use iron::Handler; use std::io::Read; use serde_json; use iron::Iron; use iron::IronResult; use iron::IronError; use iron::Request; use iron::Response; use iron::status; use router::Router; struct DrawHandler { } impl DrawHandler { pub fn new() -> DrawHandler { DrawHandler {} } } #[derive(Debug, Serialize,...
use lazy_static::lazy_static; use super::*; macro_rules! matchtest { ($name:ident, $fun:expr, $given:expr, $expected:expr) => { #[test] fn $name() { let prefix = "# "; let prefix_pattern= Regex::new(&format!(r"^(?P<head>\s*){}(?P<tail>.*?)$", prefix)).unwrap(); a...
#![allow(non_upper_case_globals)] #![allow(non_camel_case_types)] #![allow(non_snake_case)] include!(concat!(env!("OUT_DIR"), "/bindings.rs")); extern crate libc; use std::ffi::CString; use std::os::raw::c_char; pub enum History { KeepLast {n: u32}, KeepAll } pub enum Durability { Volatile, TransientLocal,...
pub use crate::ast::expressions::Expression; use crate::ast::parser; use crate::ast::stack; #[macro_export] macro_rules! sexp { ($e: expr) => { Some(Box::new($e) as Box<dyn Expression>) }; } #[macro_export] macro_rules! exp { ($e: expr) => { Box::new($e) as Box<dyn Expression> }; } #[...
#[doc = "Register `PMCR` reader"] pub type R = crate::R<PMCR_SPEC>; #[doc = "Register `PMCR` writer"] pub type W = crate::W<PMCR_SPEC>; #[doc = "Field `I2C1FMP` reader - I2C1 Fm+"] pub type I2C1FMP_R = crate::BitReader; #[doc = "Field `I2C1FMP` writer - I2C1 Fm+"] pub type I2C1FMP_W<'a, REG, const O: u8> = crate::BitWr...
extern crate libcub; extern crate rusqlite; use libcub::{list_notes, Limit, SortOrder}; use rusqlite::{params, Connection}; /// Bootstraps a test db with a table with a similar schema to the Bear notes db /// and some notes. fn bootstrap(conn: &Connection) { conn.execute( "CREATE TABLE ZSFNOTE ( ...
use super::ast::{Expr, ExprKind, Symbol}; use super::partial_types::PartialType::Unknown; use super::parser::parse_expr; use super::pretty_print::*; use super::type_inference::*; #[test] fn parse_and_print_literal_expressions() { let tests = vec![ // i32 literal expressions ("23", "23"), ("...