text
stringlengths
8
4.13M
// 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 ...
//! The types: Such as strings or integers use std::fmt; #[cfg(feature = "smol_str")] use smol_str::SmolStr; #[cfg(not(feature = "smol_str"))] type SmolStr = String; /// An anchor point for a path, such as if it's relative or absolute #[derive(Clone, Debug, PartialEq)] pub enum Anchor { Absolute, Relative, ...
mod greet; fn main() { println!("Hello,World!"); greet::greet("Alpha"); }
pub mod home; pub mod role_created; pub mod dropdown_viewdetail; pub mod tab_setting; pub mod tab_permission; pub mod tab_users;
use proc_macro::TokenStream; use quote::quote; use syn::{ext::IdentExt, Error, FnArg, ItemFn, Pat}; use crate::{ args, args::{Argument, RenameRuleExt, RenameTarget}, utils::{ generate_default, get_crate_name, get_rustdoc, parse_graphql_attrs, remove_graphql_attrs, visible_fn, GeneratorResul...
mod options; use std::convert::TryInto; use liblumen_alloc::erts::exception; use liblumen_alloc::erts::process::Process; use liblumen_alloc::erts::term::prelude::*; use crate::runtime::process::monitor::is_down; use crate::runtime::registry::pid_to_process; use crate::erlang::demonitor_2::options::Options; #[nativ...
#[doc = r"Value read from the register"] pub struct R { bits: u32, } #[doc = r"Value to write to the register"] pub struct W { bits: u32, } impl super::SSCTL2 { #[doc = r"Modifies the contents of the register"] #[inline(always)] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &...
#[doc = "Reader of register TTMLM"] pub type R = crate::R<u32, super::TTMLM>; #[doc = "Writer for register TTMLM"] pub type W = crate::W<u32, super::TTMLM>; #[doc = "Register TTMLM `reset()`'s with value 0"] impl crate::ResetValue for super::TTMLM { type Type = u32; #[inline(always)] fn reset_value() -> Sel...
//! Types implementing the [Serializer] trait. //! //! There are currently three implementations: //! //! * SerdeSerializer uses the `serde` and `serde_json` crate to serialize //! the test inputs (of arbitrary Serializable type) to a `.json` file. //! //! * [ByteSerializer] encodes and decodes values of type `Vec<u8>`...
// Copyright 2023 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 ...
// auto generated, do not modify. // created: Mon Feb 22 23:57:02 2016 // src-file: /QtWidgets/qlineedit.h // dst-file: /src/widgets/qlineedit.rs // // header block begin => #![feature(libc)] #![feature(core)] #![feature(collections)] extern crate libc; use self::libc::*; // <= header block end // main block begin ...
use nalgebra as na; use na::{ Vector3, Matrix3, Matrix3x1, Matrix1x3, Matrix1, VectorN, MatrixN, }; use na::{DefaultAllocator, DimName, RealField}; use na::allocator::Allocator; use super::Timestamp; use crate::dwt_utils::{ dwt_ticks_to_us, // dwt_us_to_ticks, dwt_time_diff, }; ty...
pub fn demo() { println!("变量与可变性"); let v = 123; println!("创建 v = {}", v); let mut v = true; println!("隐藏后 v = {}", v); v = false; println!("添加mut关键字可修改变量 mut v = {}", v); const NUM: i32 = 456; println!("常量NUM: {} 不可变且全部大写命名,需在创建时声明类型且不可变更", NUM); }
foreigner_class!(class One { self_type One; private constructor = empty; }); foreigner_class!(class Two { self_type Two; private constructor = empty; }); foreigner_class!(class Foo { self_type Foo; private constructor = empty; method Foo::f(&self) -> (One, Two); });
mod with_local_pid; use proptest::strategy::{Just, Strategy}; use liblumen_alloc::erts::process::Process; use liblumen_alloc::erts::term::prelude::Encoded; use crate::erlang::unlink_1::result; use crate::test::strategy; use crate::test::{with_process, with_process_arc}; #[test] fn without_pid_or_port_errors_badarg(...
use crate::prelude::*; use std::os::raw::c_void; use std::ptr; #[repr(C)] #[derive(Debug)] pub struct VkCommandBufferInheritanceInfo { pub sType: VkStructureType, pub pNext: *const c_void, pub renderPass: VkRenderPass, pub subpass: u32, pub framebuffer: VkFramebuffer, pub occlusionQueryEnable:...
//! Work with HTTP bodies as streams of Kubernetes resources. use super::multi_response_decoder::MultiResponseDecoder; use crate::internal_events::kubernetes::stream as internal_events; use async_stream::try_stream; use bytes05::Buf; use futures::pin_mut; use futures::stream::Stream; use hyper::body::HttpBody as Body;...
pub mod state; use state::{CaseState, Direction, State}; extern crate sdl2; use sdl2::event::Event; use sdl2::image::{InitFlag, LoadTexture}; use sdl2::keyboard::Keycode; //use sdl2::mouse::MouseButton; //use sdl2::pixels::Color; use sdl2::rect::Rect; use sdl2::render::Texture; //use sdl2::video::{Window, WindowCont...
pub mod names; pub mod string; pub mod prelude;
use crate::ast::Literal; use crate::lexer::*; use crate::parsers::expression::recursing_primary_expression; use crate::parsers::token::identifier::*; /// *pseudo_variable* | *variable* pub(crate) fn variable_reference(i: Input) -> NodeResult { alt((pseudo_variable, map(variable, |v| Node::from(v))))(i) } /// *con...
test_stdout!( without_pid_returns_false, "false\nfalse\nfalse\nfalse\nfalse\nfalse\nfalse\nfalse\nfalse\nfalse\nfalse\n" ); test_stdout!(with_pid_returns_true, "true\n");
// source: https://github.com/extrawurst/godot-vs-rapier/blob/master/logic/src/utils.rs use gdnative::prelude::*; pub trait NodeExt { /// Gets a node at `path`, assumes that it's safe to use, and casts it to `T`. /// /// # Safety /// /// See `Ptr::assume_safe`. fn get_typed_node<T, P>(&self, pa...
use chrono::{DateTime, Utc}; use diesel::{self, ExpressionMethods, PgConnection, QueryDsl, RunQueryDsl}; use serde::{Deserialize, Serialize}; use auth::{create_jwt, PrivateClaim, Role}; use errors::Error; use crate::schema::games; use crate::utils::create_slug_from_id; #[derive(Debug, Identifiable, Serialize, Deseri...
extern crate num; extern crate nue; use super::{Com, Core, SenderBus, Permission}; use std::sync::mpsc::{Receiver, SyncSender, sync_channel}; use std::io::Read; use std::collections::VecDeque; struct Bus<W> { sender: SenderBus<W>, selected: bool, enabled: bool, } #[derive(Default)] struct DStack<W> { ...
// adc.rs - contains all 8 functions to support adc instructions use super::addressing::{self, Operation}; use crate::memory::{RAM, *}; pub fn adc_immediate( operand: u8, pc_reg: &mut u16, accumulator: &mut u8, mut status_flags: &mut u8, cycles_until_next: &mut u8, ) { *accumulator = addressin...
use std::fs::read_to_string; fn main() { let (img, mut min_n0, mut num_1x2, mut render) = (read_to_string("in8.txt").unwrap(), 151, 0, [[2; 25]; 6]); let mut digits = img.chars(); for _ in 0 .. img.len() / 150 { let mut nums = [0; 3]; for y in 0..6 { for x in 0..25 { let dig = digits.next().unwrap...
// region: lmake_readme include "readme.md" //! A //! **mem4 is a simple memory game made primarily for learning the Rust programming language and Wasm/WebAssembly with Virtual Dom Dodrio and WebSocket communication** //! //! version: 19.9.10 //! Look also at the workspace readme on https://github.com/LucianoBesti...
use crate::builder; use eosio::AccountName; use serde::{Deserialize, Serialize}; builder!("/v1/chain/get_info", GetInfo, Info); #[derive(Serialize, Clone)] pub struct GetInfo {} pub const fn get_info() -> GetInfo { GetInfo {} } pub type ChainId = String; pub type BlockId = String; pub type BlockNum = u32; pu...
#[macro_use] extern crate glium; extern crate image; mod player; fn main() { player::play(); }
use super::{ get_span_of_entire_for_loop, make_iterator_snippet, IncrementVisitor, InitializeVisitor, EXPLICIT_COUNTER_LOOP, }; use clippy_utils::diagnostics::{span_lint_and_sugg, span_lint_and_then}; use clippy_utils::source::snippet_with_applicability; use clippy_utils::{get_enclosing_block, is_integer_const}; us...
#![allow(warnings, unused_unsafe)] use abi_stable::StableAbi; #[repr(u8)] #[derive(StableAbi)] #[sabi(kind(WithNonExhaustive( size = 1, align = 1, assert_nonexhaustive = TooLarge, )))] #[sabi(with_constructor)] pub enum TooLarge { Foo, Bar, Baz(u8), } #[repr(u8)] #[derive(StableAbi)] #[sabi(k...
use super::combine::Combine; pub trait PrimeChecker { type Value; // returns // false if |value| is not a prime // true otherwise fn check(&self, value: &Self::Value) -> bool; fn combine<C>(self, checker: C) -> Combine<Self::Value, Self, C> where Self: Sized, C: Prim...
#![allow(dead_code)] use crate::{ components::*, ecs::{systems::ParallelRunnable, *}, }; use smallvec::SmallVec; use std::collections::HashMap; pub fn build() -> impl ParallelRunnable { SystemBuilder::<()>::new("ParentUpdateSystem") // Entities with a removed `Parent` .with_query(<(Entity, ...
//! Common functions, definitions and extensions for parsing and code generation //! of `#[graphql(rename_all = ...)]` attribute. use std::str::FromStr; use syn::parse::{Parse, ParseStream}; /// Possible ways to rename all [GraphQL fields][1] or [GrqphQL enum values][2]. /// /// [1]: https://spec.graphql.org/October...
use std::string::CowString; use std::fmt; use std::collections::HashMap; use std::rc::Rc; use std::ops::Deref; use error::{CompileError, CompileErrorKind, RuntimeError}; use datum::Datum; use runtime::{Inst, MemRef, RDatum, RuntimeData, Closure}; /// Syntax variables #[derive(Copy, Clone, PartialEq)] pub enum Syntax ...
use std::process::Command; use std::io::{self, Write}; // use std::env; fn main() { let output = Command::new("php.exe") .env("PATH", r#"C:\Applications\phpstack\php74"#) .arg("-v") .output() .expect("Gagal menjalankan perintah"); io::stdout().write_all(&output.stdout).unwrap(); }
use bit_set::BitSet; use fxhash::FxHashMap; use std::default::Default; use aspect::{Aspect, Matcher}; use component::{Component, ComponentManager}; pub type Entity = usize; pub struct EntityEditor<'a> { pub entity: Entity, entity_manager: &'a mut EntityManager, } impl<'a> EntityEditor<'a> { fn new(entit...
extern crate advent_lib; use advent_lib::chris::day_1::{Direction, TurnDirection, direction_now_facing, string_to_turn_direction, day_1}; use advent_lib::input_reader; #[test] fn direction_facing_test() { assert_eq!(direction_now_facing(TurnDirection::Left, Direction::South), Direction::East); assert_eq!(direction...
use mime_guess::Mime; use orfail::OrFail; use std::io::{BufRead, BufReader, Read, Write}; use url::Url; #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum HttpMethod { Head, Get, // rofis original method. Watch, } #[derive(Debug)] pub struct HttpRequest { method: HttpMethod, path: St...
#[doc = r"Value read from the register"] pub struct R { bits: u16, } #[doc = r"Value to write to the register"] pub struct W { bits: u16, } impl super::DMACTL5 { #[doc = r"Modifies the contents of the register"] #[inline(always)] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, ...
//! O2Jam chart parser module use nom::*; use crate::chart::{Note, TimingPoint}; fn string_from_slice(s: &[u8]) -> String { String::from_utf8_lossy(s).into_owned() } macro_rules! string_block { ($i:expr, $n:expr) => (flat_map!($i, take!($n), map!(take_until!("\0"), string_from_slice))); } mod ojm; // TODO...
use std::fs; use std::time::Instant; use regex::Regex; fn main() { let start = Instant::now(); let tst_tickets = TicketValidator::from_file("example.txt"); let mut tickets = TicketValidator::from_file("input.txt"); // part 1 let mut tst_scanning_error_rate = 0; for nearby_ticket in &tst_ticke...
//! `ast` contains the Abstract Syntax Tree (`AST`) representation. use crate::{Identifier, Position}; /// An Abstract Syntax Tree with the position in the file. #[derive(Debug, Clone, PartialEq)] pub struct AST { /// The `AST` type. pub ast: ASTType, /// The position in a file of the `AST`. pub posit...
// -*- rust -*- // error-pattern: mismatched types fn f(x: &int) { log_err x; } fn h(x: int) { log_err x; } fn main() { let g: fn(int) = f; g(10); g = h; g(10); }
use NodeId; /// /// A `Node` builder that provides more control over how a `Node` is created. /// pub struct NodeBuilder<T> { data: T, child_capacity: usize, } impl<T> NodeBuilder<T> { /// /// Creates a new `NodeBuilder` with the required data. /// /// ``` /// use id_tree::NodeBuilder; ...
use serde::{Serialize, Serializer, Deserialize, Deserializer}; use serde::de::Visitor; #[derive(Debug, Clone)] pub struct Uuid(pub uuid::Uuid); impl Into<uuid::Uuid> for Uuid { #[inline] fn into(self) -> uuid::Uuid { self.0 } } impl From<uuid::Uuid> for Uuid { #[inline] fn from(u: uuid::U...
/* | bin.rs - | Index for the bot | */ /* ! Remember ! This bot is fully annotated */ /* | Imports the discord crate. | Note ~ This crate must be specified in Cargo.toml, like with any other crate. */ extern crate discord; /* | As follows: | 1. Client for Discord Rest API | 2. Enum of Event Received over a websoc...
// Based on schedule.wsdl.xml // targetNamespace="http://www.onvif.org/ver10/schedule/wsdl" // xmlns:xs="http://www.w3.org/2001/XMLSchema" // xmlns:pt="http://www.onvif.org/ver10/pacs" // xmlns:tsc="http://www.onvif.org/ver10/schedule/wsdl" // <xs:import namespace="http://www.onvif.org/ver10/pacs" schemaLocation="../...
use ggez::{GameResult, Context}; use ggez::graphics::Image; use std::collections::HashMap; use rand::{self,Rng}; use bomb::{self,Bomb,FuseLength}; use car::{self,Car}; use center::draw_centered; use checkpoint::*; use globals::*; use hex::{HexPoint, HexVector}; #[derive(Debug)] pub struct Assets { checkpoint_lin...
// 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 ...
/*! This crate provides an implementation of the [Snappy compression format](https://github.com/google/snappy/blob/master/format_description.txt), as well as the [framing format](https://github.com/google/snappy/blob/master/framing_format.txt). The goal of Snappy is to provide reasonable compression at high speed. On a...
#[cfg(test)] mod tests { use pygmaea::token_type::TokenType::*; use pygmaea::token_type::*; const TOKEN_TYPES: [TokenType; 27] = [ Plus, Minus, Asterisk, Slash, Assign, Bang, LessThan, GreaterThan, Equal, NotEqual, Comm...
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)] #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn BackupEventLogA<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::HANDLE>, Param1: ::windows::core::IntoParam<'...
extern crate fnv; extern crate nx; mod item_provider; mod my_node; use item_provider::*; fn main() { let pro = ItemProvider::new(); println!("{:?}", pro.get_item_data(2190000)); println!("{:?}", pro.get_item_data(2190001)); }
use clippy_utils::{ diagnostics::span_lint_and_sugg, get_async_fn_body, is_async_fn, source::{snippet_with_applicability, snippet_with_context, walk_span_to_context}, visitors::expr_visitor_no_bodies, }; use rustc_errors::Applicability; use rustc_hir::intravisit::{FnKind, Visitor}; use rustc_hir::{Block...
use crate::config::get_config; use crate::fs::write_telegram_chat_id; use crate::telegram::{Api, ParseMode, SendMessageParams}; use crate::unwrap_err; use nanoid; use std::thread; use std::time::Duration; pub fn gen_secret() { println!("{}", nanoid::simple()); } pub fn telegram_setup() { let token = nanoid::g...
#![allow(clippy::unreadable_literal)] // Each sub-module represents a C-level struct to respective IOCTL request // and idiomatic Rust struct around it. use winapi::shared::minwindef; mod info; mod query_info; mod status; mod wait_status; pub use self::info::BatteryInformation; pub use self::query_info::BatteryQuer...
use std::fmt::{Debug, Display, Formatter}; use std::ops::Mul; use crate::matrix::Matrix4; use crate::number_traits::Float; use crate::vector::Vector3; #[derive(Debug, Clone)] pub struct Quaternion<T> where T: Debug, { scalar_part: T, vector_part: Vector3<T>, } impl<T> Quaternion<T> where T: Debug + F...
use hashbrown::HashSet; use regex::Regex; use std::iter::FromIterator; pub fn run() { let input = include_str!("input/day4bigboi.txt").trim(); println!("{}", exercise_1(&input)); println!("{}", exercise_2(&input)); } fn exercise_1(input: &str) -> usize { let mut lines = input.lines(); let mut vali...
//#![deny(warnings)] extern crate futures; extern crate hyper; extern crate hyper_tls; extern crate tokio_core; extern crate url; //use std::env; use std::io::{self, Write}; use url::form_urlencoded; use url::Url; use futures::Future; use futures::stream::Stream; use hyper::{Method, Body, Client, Request}; use hype...
//! Rusty Engine's custom collision detection implementation. use crate::sprite::Sprite; use bevy::prelude::*; use serde::{Deserialize, Serialize}; use std::{ collections::HashSet, f32::consts::{PI, TAU}, hash::Hash, }; pub(crate) struct PhysicsPlugin; impl Plugin for PhysicsPlugin { fn build(&self, ...
use core::alloc::Layout; use core::cmp; use core::convert::{TryFrom, TryInto}; use core::fmt::{self, Debug, Display, Write}; use core::iter::FusedIterator; use core::marker::PhantomData; use core::mem; use core::ptr; use anyhow::*; use heapless::Vec; use thiserror::Error; use crate::borrow::CloneToProcess; use crate:...
//! Timer-based management of operator activators. use std::cmp::Ordering; use std::collections::BinaryHeap; use std::rc::Weak; use std::time::{Duration, Instant}; use timely::scheduling::Activator; use crate::scheduling::AsScheduler; /// A scheduler allows polling sources to defer triggering their /// activators, ...
use std::fs::File; use std::io::{Read, Write}; use gtk::prelude::*; // Module for aggregating analysis information mod analysis; // Module for maintaining application state mod app; use crate::app::AppContext; // Module for coordinate systems mod coords; // Errors mod errors; use crate::errors::*; // GUI module m...
//! ## Build Example //! //! ```text //! . //! ├── build.rs //! ├── Cargo.toml //! ├── clib //! │   ├── meson.build //! │   ├── squid.h //! │   └── squid.c //! └── src //! └── lib.rs //! ``` //! //! build.rs: //! //! ``` //! extern crate meson; //! use std::env; //! use std::path::PathBuf; //! //! fn main() { //! ...
use std::{collections::HashMap, fmt::Display}; use async_trait::async_trait; use data_types::{Table, TableId}; use super::TablesSource; #[derive(Debug)] pub struct MockTablesSource { tables: HashMap<TableId, Table>, } impl MockTablesSource { #[allow(dead_code)] // not used anywhere pub fn new(tables: Ha...
use amq_protocol::protocol::AMQPClass; use failure::{Backtrace, Context, Fail}; use std::fmt; use crate::api::ChannelState; /// The type of error that can be returned in this crate. /// /// Instead of implementing the `Error` trait provided by the standard library, /// it implemented the `Fail` trait provided by the...
// `without_number_errors_badarg` in unit tests test_stdout!(with_atom, "atom\n"); test_stdout!(with_small_integer, "1\n0\n");
// Copyright (c) 2021 Quark Container Authors / 2018 The gVisor Authors. // // 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 ...
pub trait Clock: Send + Sync { fn now(&self) -> i64; }
use super::internals::svm_engine_state::SVMEngineState; use super::internals::svm_error::SVMError; use super::internals::opcode::{OpcodeValue, OpCode}; use super::svm_program::SVMProgram; pub struct SVMEngine { engine_state: SVMEngineState } impl SVMEngine { pub fn new(program: SVMProgram) -> SVMEngine { ...
use nannou::prelude::*; use crate::extensions::f32::*; pub type ContourRing = Vec<Point2>; fn to_nannou_contour_ring( rows: u16, columns: u16, container: &Rect, raw_contour_ring: &Vec<Vec<f64>>, ) -> ContourRing { let contour_ring: ContourRing = raw_contour_ring .iter() .map(move ...
#[doc = "Reader of register ADC4R"] pub type R = crate::R<u32, super::ADC4R>; #[doc = "Writer for register ADC4R"] pub type W = crate::W<u32, super::ADC4R>; #[doc = "Register ADC4R `reset()`'s with value 0"] impl crate::ResetValue for super::ADC4R { type Type = u32; #[inline(always)] fn reset_value() -> Sel...
// The functions replacing the C macros use the same names as in libc. #![allow(non_snake_case, unsafe_code)] use linux_raw_sys::ctypes::c_int; pub(crate) use linux_raw_sys::general::{ siginfo_t, WCONTINUED, WEXITED, WNOHANG, WNOWAIT, WSTOPPED, WUNTRACED, }; #[inline] pub(crate) fn WIFSTOPPED(status: u32) -> bool...
use super::computing_script::*; use super::derived_state; use super::derived_state::{DerivedStateData}; use super::super::script_type_description::*; use super::super::streams::*; use super::super::symbol::*; use super::super::error::*; use desync::Desync; use gluon::*; use gluon::compiler_pipeline::{Compileable}; use...
use self_cell::self_cell; pub type I32Ref<'a> = &'a i32; self_cell!( pub struct I32Cell { owner: i32, #[covariant] dependent: I32Ref, } ); pub type Ast<'a> = Vec<&'a str>; self_cell!( pub struct StringCell { owner: String, #[covariant] dependent: Ast, ...
pub fn run_client() { println!("run dbus from client .... "); } use dbus::blocking::Connection; use std::time::Duration; pub enum Variant {} pub fn run_dbus( service: &str, obj_path: &str, method: &str, ) -> Result<Vec<String>, Box<dyn std::error::Error>> { let conn = Connection::new_session()?; ...
// Copyright (c) 2018-2022 Ministerio de Fomento // Instituto de Ciencias de la Construcción Eduardo Torroja (IETcc-CSIC) // 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 ...
//! Code to decode [`MutableBatch`] from pbdata protobuf use generated_types::influxdata::pbdata::v1::{ column::{SemanticType, Values as PbValues}, Column as PbColumn, DatabaseBatch, PackedStrings, TableBatch, }; use hashbrown::{HashMap, HashSet}; use mutable_batch::{writer::Writer, MutableBatch}; use schema::...
use crate::points::Point2D; use std::collections::HashSet; use std::error::Error; use std::iter::FromIterator; use std::str::FromStr; const INPUT: &str = include_str!("../input/2019/day3.txt"); pub fn part1() -> i32 { let wires: Vec<Path> = parse_input(); let wire_one: &Vec<Point2D> = &wires[0].locations; ...
use std::{thread, time::Duration}; #[no_mangle] pub extern "C" fn async_call(cb: extern fn(i32)) { println!("RUST: Doing some heavy work..."); thread::sleep(Duration::from_secs(2)); cb(1); } #[no_mangle] pub extern "C" fn async_call2() -> i32 { println!("RUST: Doing some heavy work..."); thread::sleep(Dura...
// Raspberry Pi2 pub const GPIO_BASE: u32 = 0x3F200000; // other // pub const GPIO_BASE: u32 = 0x20000000; // Raspberrp Pi+ or Raspberry Pi2 pub const LED_GPFSEL: isize = GPIO_GPFSEL4; pub const LED_GPFBIT: i32 = 21; pub const LED_GPSET: isize = GPIO_GPSET1; pub const LED_GPCLR: isize = GPIO_GPCLR1; pub const LED_GPIO...
use std::io; use std::io::Read; use std::io::Write; use byteorder::{WriteBytesExt,ReadBytesExt,BigEndian}; use utils::*; #[derive(Clone, Debug)] pub struct PlaySoundEffect{ pub x: f64, pub y: f64, pub sound: u32, pub volume: u8 } impl PlaySoundEffect{ pub fn send<W: Write>(self, out_stream: &mut W...
use std; use core::time::Time; use super::iter::*; use ::error::Error; pub type LogError = Error; pub type LogResult<T> = std::result::Result<T,LogError>; #[repr(C)] pub struct FileHeader { magic : u32, version : u8, msg_header_size : u8, file_header_size : u8, } impl FileHeader { pub fn msg_head...
use std::borrow::Cow; use std::convert::AsRef; use std::fmt; use std::hash::{Hash, Hasher}; use std::iter; use std::str; use std::str::FromStr; extern crate blake2; use blake2::{Blake2b, VarBlake2b}; extern crate digest; use digest::{Input, VariableOutput}; extern crate byteorder; use byteorder::{BigEndian, ByteOrder...
use std::collections::VecDeque; use input_i_scanner::InputIScanner; use join::Join; fn main() { let stdin = std::io::stdin(); let mut _i_i = InputIScanner::from(stdin.lock()); macro_rules! scan { (($($t: ty),+)) => { ($(scan!($t)),+) }; ($t: ty) => { ...
use crate::{MetricKind, MetricObserver, Observation}; use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::Arc; /// A monotonic counter #[derive(Debug, Clone, Default)] pub struct U64Counter { state: Arc<AtomicU64>, } impl U64Counter { pub fn inc(&self, count: u64) { self.state.fetch_add(count...
use std::convert::Infallible; use crate::env::Environment; use axum::{ body::{Bytes, Full}, extract::Extension, handler::{get, post}, response::{self, IntoResponse}, routing::BoxRoute, AddExtensionLayer, Router, }; use http::{Response, StatusCode}; use serde::Serialize; use serde_json::json; u...
use cogs_gamedev::{ ease::Interpolator, grids::{Direction4, Rotation}, }; use crate::{ assets::Assets, boilerplates::{FrameInfo, GamemodeDrawer, RenderTargetStack}, modes::playing::{ draw_space, simulating::{AdvanceMethod, STEP_TIME_ON_DEMAND}, }, simulator::{ ...
#[doc = "Reader of register UR12"] pub type R = crate::R<u32, super::UR12>; #[doc = "Reader of field `SECURE`"] pub type SECURE_R = crate::R<bool, bool>; impl R { #[doc = "Bit 16 - Secure mode"] #[inline(always)] pub fn secure(&self) -> SECURE_R { SECURE_R::new(((self.bits >> 16) & 0x01) != 0) }...
#![no_main] #![no_std] use stm32l4xx_hal as hal; use ws2812_spi as ws2812; #[macro_use] extern crate cortex_m_rt as rt; use crate::hal::delay::Delay; use crate::hal::prelude::*; use crate::hal::spi::Spi; use crate::hal::stm32; use crate::rt::entry; use crate::rt::ExceptionFrame; use crate::ws2812::Ws2812; use cortex_m...
use std::fs; use crate::image::Image; pub fn write(image: &Image, filename: &str) -> std::io::Result<()> { let mut s = format!("P3\n{} {}\n255\n",image.width(),image.height()); for p in &image.pixels { s.push_str(&format!("{} {} {}\n", (p.r()*255.99) as u8, (p.g()*255.99) as u8, (p.b() *2...
use core::{ fmt::Debug, ops::{Add, AddAssign, Div, DivAssign, Sub, SubAssign}, }; use serde::{Deserialize, Serialize}; #[derive(Default, Clone, Copy, Debug, Serialize, Deserialize)] pub struct Vec3f(pub f32, pub f32, pub f32); impl Vec3f { pub fn len2(&self) -> f32 { self.0 * self.0 + self.1 * sel...
use super::h1; use futures::{future, Future, Poll}; use http; use http::header::{HeaderValue, TRANSFER_ENCODING}; use tracing::{debug, warn}; pub const L5D_ORIG_PROTO: &str = "l5d-orig-proto"; /// Upgrades HTTP requests from their original protocol to HTTP2. #[derive(Clone, Debug)] pub struct Upgrade<S> { inner: ...
pub fn find() -> Option<u32> { let sum:u32 = 1000; for a in 1..sum-2 { for b in a+1..sum-1 { for c in b+1..sum { if a*a + b*b == c*c { if a+b+c == sum { println!("{} {} {}",a,b,c); return Some(a*b*c); } } } } } None }
use std::{fmt, ops::Deref}; use tui::style::{Color, Modifier, Style}; #[derive(Clone, Debug, PartialEq)] pub struct ColoredString { input: String, style: Style, } /// The trait that enables something to be given color. /// /// You can use `colored` effectively simply by importing this trait /// and then using...
use std::collections::HashMap; pub fn get_recursive_cache(seed: &mut Vec<u64>, days: u64) -> u64 { let mut cache: HashMap<i64, u64> = HashMap::new(); seed.iter() .map(|fish| get_fishes((days - fish) as i64, &mut cache)) .sum() } pub fn get_fishes(iteration: i64, cache: &mut HashMap<i64, u64>)...
// Copyright 2019-2020 PolkaX. Licensed under MIT or Apache-2.0. /// Type alias to use this library's [`IpldCborError`] type in a `Result`. pub type Result<T> = std::result::Result<T, IpldCoreError>; /// Errors generated from this library. #[derive(Debug, thiserror::Error)] pub enum IpldCoreError { /// JSON seria...
//! Do not use this crate directly. //! //! This is the immplementation crate for `hdbconnect` and `hdbconnect_async`. //! //! If you need a synchronous driver, use `hdbconnect`. //! //! If you need an asynchronous driver, use `hdbconnect_async`. //! // only enables the `doc_cfg` feature when the `docsrs` configuratio...
use crate::worker::component::{self, Component, ComponentId, DATABASE}; use crate::worker::internal::schema::SchemaComponentData; use spatialos_sdk_sys::worker::{Schema_DestroyComponentData, Worker_ComponentData, Worker_Entity}; use std::collections::HashMap; use std::ptr; use std::slice; #[derive(Debug)] pub struct E...