text
stringlengths
8
4.13M
#![allow(unused_imports)] #![allow(unused_must_use)] use std::io; use std::fs::File; use rust::boxes::{Box_, Boxes}; use rust::command::Command; fn main() -> std::io::Result<()> { let stdin = io::stdin(); let mut _reader = stdin.lock(); // Uncomment these two lines to read the commands // from a...
use rust_imgui as imgui; use rust_imgui::ImVec4; use rust_imgui::imstr::ImStr; use std::collections::VecDeque; pub struct ConsoleLine { color: ImVec4, text: String, } pub struct ImGuiConsole { max_entries: usize, scroll_to_bottom: bool, entries: VecDeque<ConsoleLine>, entry_count: usize, } impl ImGuiConsole { ...
use std::io::Write; use std::path::{Path, PathBuf}; use std::process::Command; use std::{env, str}; use crate::base::log::CommandLogExt; use crate::base::{Error, Result}; use crate::domain::executable::SearchPaths; use tempfile::NamedTempFile; static GENERIC_RESOLVER_SOURCE_CODE: &str = r" #define _GNU_SOURCE #inclu...
use puzzle::puzzle::Puzzle; struct Part1; struct Part2; impl Puzzle for Part1 { fn solve(input: &str) { let mut current_cals :usize = 0; let mut elfs :Vec<usize> = Vec::new(); for line in input.split('\n').into_iter() { if line.is_empty() { elfs.push(current_c...
fn main(){ use std::f32; use std::io::stdin; let mut input = String::new(); // We don't care about the return value of read_line - "_" tells the compiler that. let _ = stdin().read_line(&mut input); let vector_size: i32 = input.trim().parse::<i32>().unwrap(); let mut num_positive: i32 ...
#[doc = r"Register block"] #[repr(C)] pub struct TASKS_CHG { #[doc = "0x00 - Enable channel group."] pub en: EN, #[doc = "0x04 - Disable channel group."] pub dis: DIS, } #[doc = "EN (w) register accessor: an alias for `Reg<EN_SPEC>`"] pub type EN = crate::Reg<en::EN_SPEC>; #[doc = "Enable channel group....
use std::collections::HashSet; #[allow(unused_imports)] use log::{debug, error, info, trace}; use bitcoin::{Script, Transaction, Txid}; use electrum_client::tokio::io::{AsyncRead, AsyncWrite}; use electrum_client::Client; use self::utils::{ELSGetHistoryRes, ELSListUnspentRes, ElectrumLikeSync}; use super::*; use cr...
#[macro_use] extern crate log; extern crate cryptoexchange; extern crate exonum; use cryptoexchange::service; use exonum::helpers::fabric::NodeBuilder; fn main() { exonum::helpers::init_logger().unwrap(); NodeBuilder::new() .with_service(Box::new(service::ExchangeService)) .run(); }
use crate::{ProtocolSupportDecoder, ProtocolSupportEncoder}; impl<T> ProtocolSupportEncoder for Option<T> where T: ProtocolSupportEncoder, { fn calculate_len(&self, version: &crate::ProtocolVersion) -> usize { 1 + self .as_ref() .map(|e| e.calculate_len(version)) .un...
#[cfg(any(feature = "client", feature = "primitives"))] use std::str::FromStr; use nimiq_primitives::networks::NetworkId; use tsify::Tsify; use wasm_bindgen::prelude::wasm_bindgen; #[cfg(any(feature = "client", feature = "primitives"))] use wasm_bindgen::prelude::JsError; #[cfg(feature = "primitives")] use wasm_bindge...
extern crate memcache; extern crate rand; use rand::distributions::Alphanumeric; use rand::{thread_rng, Rng}; use std::iter; use std::thread; use std::thread::JoinHandle; use std::time; fn gen_random_key() -> String { return iter::repeat(()) .map(|()| thread_rng().sample(Alphanumeric)) .take(10) ...
use std::collections::{HashMap, HashSet}; // For convenience, we re-export some core types from our internal API: pub use protocol::common::{ ObjectId, FieldName, FieldValue }; // Represents a single field in an object. pub struct Field { pub key: FieldName, // Note that the value will be opaque ...
use std::{io, cmp::Ordering}; #[derive(Debug, Eq, Ord, PartialEq, PartialOrd)] struct Employee { name: String, department: String } impl Employee { pub fn new (name:String, department: String) -> Self { Employee { name, department } } } fn receive_input_string(...
//Anything related to POST requests for heroku logs and it's properties goes here. use super::{LogDrain, LogSession}; use crate::framework::endpoint::{HerokuEndpoint, Method}; /// Log Drain Create /// /// Create a new log drain. /// /// [See Heroku documentation for more information about this endpoint](https://devce...
use rand::Rng; use crate::{hittable::{Hittable, HitRecord}, ray::Ray}; // pub struct HittableList<T: ?Sized> { // pub objects: Vec<Box<dyn Hittable>>, // } pub trait HittableList: Send + Sync { fn hit_top<'a>(&'a self, ray: &Ray, rng: &mut impl Rng) -> Option<HitRecord<'a>>; } impl<'r, T: Hittab...
// 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 criterion::{black_box, criterion_group, criterion_main, Criterion}; use rand::{rngs::StdRng, Rng, SeedableRng}; use sandpiles_parallel::Field; pub fn criterion_benchmark(c: &mut Criterion) { let mut rng = StdRng::seed_from_u64(346345234); let mut sample_field: Field<u32> = Field::new(1000, 1000); samp...
pub struct Solution {} impl Solution { pub fn min_distance(word1: String, word2: String) -> i32 { let word1 = word1.as_bytes(); let word2 = word2.as_bytes(); let mut dp = vec![0; word2.len() + 1]; for idx1 in 0..=word1.len() { let mut history = std::i32::MAX; ...
use core::intrinsics; mod cmath { use libc::{c_float, c_double}; #[link_name = "m"] extern "C" { pub fn acosf(n: c_float) -> c_float; pub fn asinf(n: c_float) -> c_float; pub fn atanf(n: c_float) -> c_float; pub fn tanf(n: c_float) -> c_float; pub fn acos(n: c_doub...
/* Trabalho de Organização de Computadores Luiza Torello Vieira Victor Azadinho Miranda 1 Algoritmo a ser entregue Imagine um pipeline o qual você possa desprezar hazards de recursos e de dados. Você deve apenas se preocupar com desvios condicionais. Escreva um programa e...
// Macros = Meta programming // Match an expression and perform some operation // Code is expanded and compiled // Macros can match: expr, ident, block, stmt, par, path, meta, ty, tt macro_rules! my_macro { () => { println!("First macro") }; } // macro_rules! name { // ($name: expr) => { // ...
use std::{collections::HashMap}; use std::collections::VecDeque; #[derive(Clone)] struct Unit { name: String, quantity: u64, } impl Unit { fn new( data: &str ) -> Unit { let r: Vec<&str> = data.trim().split(' ').collect(); Unit { name: r[1].to_owned(), quantity: r[0].to_owned().parse().unwrap() } } } #[deriv...
use support::project; #[test] fn test_git_clean_checks_for_git_in_path() { let project = project("git-clean_removes").build(); let result = project.git_clean_command("-y").env("PATH", "").run(); assert!( !result.is_success(), "{}", result.failure_message("command to fail") ); ...
use super::rootfs::mount_fs_at; use super::*; use rcore_fs::vfs; use rcore_fs_devfs::DevFS; use rcore_fs_mountfs::MountFS; use rcore_fs_ramfs::RamFS; use self::dev_fd::DevFd; use self::dev_null::DevNull; use self::dev_random::DevRandom; use self::dev_sgx::DevSgx; use self::dev_shm::DevShm; use self::dev_zero::DevZero...
use regex::Regex; use shared::*; use std::collections::HashSet; #[derive(Debug, PartialEq, Eq, Hash, Clone)] struct Rect { id: usize, left: usize, top: usize, width: usize, height: usize, } #[derive(Debug, PartialEq, Eq, Hash, Clone)] struct SquareInch { x: usize, y: usize, } fn main() { ...
use std::ops::Mul; use u256::U256; // P = 2^256 - 2^32 - 2^9 - 2^8 - 2^7 - 2^6 - 2^4 - 1 const P_D1: u128 = 0xFFFFFFFF_FFFFFFFF_FFFFFFFE_FFFFFC2F; const P_MINUS_2_D1: u128 = 0xFFFFFFFF_FFFFFFFF_FFFFFFFE_FFFFFC2D; const P: U256 = U256 { d0: 0xFFFFFFFF_FFFFFFFF_FFFFFFFF_FFFFFFFF, d1: P_D1, }; // const G_X: U25...
pub mod config; pub mod status;
extern crate itertools; extern crate regex; extern crate walkdir; #[cfg(feature = "rayon")] extern crate rayon; ///CifarDataset is Top Level Struct of cifar_10_loader. /// ///CifarDataset include labels of Cifar10, train_datas, test_datas and their count. /// pub struct CifarDataset { ///Cifar10 lables. /// ...
extern crate linux_embedded_hal as hal; #[macro_use] extern crate influx_db_client; extern crate sht3x; extern crate sys_info; use hal::{Delay, I2cdev}; use influx_db_client::{Client, Point, Points, Value, Precision}; use sht3x::{SHT3x, Address, Repeatability}; use std::time::{SystemTime, UNIX_EPOCH}; fn main() { ...
use crate::display::{Row, RowFormatter, RowStorage}; use crate::rtc::DateTime; use core::fmt::{self, Write}; #[derive(Debug, Clone, PartialEq)] pub struct IdleStateData { // TODO - storage for logs pub missed_calls: usize, pub system_time: DateTime, // TODO row storage or heapless::String? // row...
use crate::event::*; use crate::board_message::*; use crate::console::*; use zzt_file_format::dosstring::DosString; /// A scroll has a few horizontal borders in it that are all drawn in a similar manner. This /// represents the type of border to draw. #[derive(PartialEq)] enum ScrollBorder { /// The border at the top...
#[doc = "Register `P6IV` reader"] pub struct R(crate::R<P6IV_SPEC>); impl core::ops::Deref for R { type Target = crate::R<P6IV_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<P6IV_SPEC>> for R { #[inline(always)] fn from(reader: crate::R<P6IV_SP...
use List::{Cons, Nil}; use ListRc::{ConsRc, NilRc}; use std::ops::Deref; use std::rc::Rc; #[derive(Debug)] enum List { Cons(i32, Box<List>), Nil, } #[derive(Debug)] enum ListRc { ConsRc(i32, Rc<ListRc>), NilRc, } struct MyBox<T>(T); impl<T> MyBox<T>{ fn new(x: T) -> MyBox<T> { MyBox(x) ...
use std::cell::RefCell; use std::cmp; use std::collections::HashMap; use std::rc::Rc; use crate::dispatch::*; use crate::log_entry::*; use crate::message::*; use crate::state::State; // broadcastTime ≪ electionTimeout ≪ MTBF const HEARTBEAT_INTERVAL_MS: u64 = 50; const ELECTION_TIMEOUT_MS: u64 = 500; // FIXME: Random...
// This file is part of Substrate. // Copyright (C) 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 // // http://www.a...
// This file is part of tmx // Copyright 2017 Sébastien Watteau // // 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 ...
#![allow(dead_code)] #![feature(stmt_expr_attributes)] #![feature(try_blocks)] #![feature(await_macro, async_await, futures_api)] #[macro_use] extern crate log; #[macro_use] extern crate taikai; #[macro_use] extern crate tokio; #[macro_use] extern crate futures; #[macro_use] extern crate enum_primitive; #[cfg(test)] ...
use crate::ast::*; use conch_parser::ast::builder::{AtomicDefaultBuilder, Builder}; use conch_parser::parse::ParseError; use std::path::PathBuf; mod includes; mod vars; #[derive(Debug)] pub enum Err { /// Failed to build the layout for a file resolved from an include statement. IncludeParse(PathBuf), /// ...
use machine::state::State; use machine::state::mem::ByteAt; /// load byte pub fn ldb(state: &mut State, x: u8, y: u8, z: u8) { // Load operands let op1: u64 = state.gpr[y].into(); let op2: u64 = state.gpr[z].into(); // Execute let a = op1.wrapping_add(op2); // Load from memory let res: i8...
use crate::core::matcher::{Matcher, Matcherable}; pub fn abort () -> Matcherable<bool> { Matcherable::new(true) }
use alloc::string::String; use alloc::vec::Vec; use std::ffi::CString; use std::os::raw::c_char; use super::super::time::timer_slack::TIMERSLACK; use super::thread::ThreadName; use crate::prelude::*; use crate::util::mem_util::from_user::{check_array, clone_cstring_safely}; #[macro_use] mod macros; // Note: // Prctl...
/// This is the real game implementation, /// extern crate nalgebra; extern crate petgraph; extern crate ggez; use engine::logical::Update; use engine::graphics::{Draw, Graphics, DrawPrimitives, DrawMode, Color}; use petgraph::graph::{Graph, NodeIndex}; use std::ops::{Index, IndexMut}; use nalgebra::*; mod engine;...
#[derive(Clone, PartialEq, ::prost::Message)] pub struct C2s { ///历史原因,目前已废弃,填0即可 #[prost(uint64, required, tag="1")] pub user_id: u64, } #[derive(Clone, PartialEq, ::prost::Message)] pub struct S2c { ///Qot_Common.QotMarketState,港股主板市场状态 #[prost(int32, required, tag="1")] pub market_hk: i32, ...
pub mod dive_segment; pub mod gas;
//! The `FluentValue` enum represents values which can be formatted to a String. //! //! The [`ResolveValue`][] trait from the [`resolve`][] module evaluates AST nodes into //! `FluentValues` which can then be formatted to Strings using the i18n formatters stored by the //! `FluentBundle` instance if required. //! //! ...
use async_graphql::{Context, Object, Result}; use sqlx::postgres::PgPool; use sqlx::Done; #[derive(Clone)] pub struct Xiangmu { pub id: i32, pub xmbh: Option<String>, pub xmmc: Option<String>, pub xmfzr: Option<String>, pub xmlx: Option<String>, pub gclzl: Option<String>, pub gcllr: Option<...
use onvif as tt; use validate::Validate; use yaserde_derive::{YaDeserialize, YaSerialize}; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "axt", namespace = "axt: http://www.onvif.org/ver20/analytics" )] pub struct MotionRegionConfigOptions { // The total number of Mot...
// Copyright (c) 2013-2016 Sandstorm Development Group, Inc. and contributors // Licensed under the MIT License: // // 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, inc...
use super::*; /// Sound heard by one of your units #[derive(Clone, Debug)] pub struct Sound { /// Sound type index (starting with 0) pub type_index: i32, /// Id of unit that heard this sound pub unit_id: i32, /// Position where sound was heard (different from sound source position) pub position...
use std::borrow::Cow; use std::fmt::Write; use crate::renderer::TypeRefRenderer; use crate::type_ref::{CppNameStyle, Dir, FishStyle, NameStyle, StrEnc, StrType, TemplateArg, TypeRef, TypeRefKind}; use crate::writer::rust_native::element::RustElement; use crate::writer::rust_native::type_ref::TypeRefExt; use crate::{se...
use std::hash::Hasher; use std::mem; use std::slice; use crate::hash::Hashable; macro_rules! impl_write { ($(($ty:ident, $meth:ident),)*) => {$( impl<H: Hasher> Hashable<H> for $ty { fn hash(&self, state: &mut H) { state.$meth(*self) } #[allow(trivial_c...
use std::collections::HashSet; use std::fs; #[derive(Debug)] enum Operation { Acc, Nop, Jmp, } #[derive(Debug)] struct Instruction { operation: Operation, value: i32, } impl Instruction { fn parse(line: &str) -> Self { let op_and_value: Vec<&str> = line.split(" ").collect(); l...
impl Solution { // T - O(n); S - O(n) // idea: use a vec![] to simulate a stack // 1. '(' | '[' | '{': push stack // 2. ')' | ']' | '}': if the stack is not empty, we check the top item to see if they match pub fn is_valid(s: String) -> bool { let mut stack = vec![]; // s.cha...
extern crate rand; extern crate pnet; extern crate ctrlc; use std::net::IpAddr; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; use rand::random; use pnet::packet::util; use pnet::packet::ip::IpNextHeaderProtocols; use pnet::packet::icmp::{echo_request, IcmpTypes}; use pnet::transport::Transpor...
use bencher::Bencher; use treexml::Document; pub fn baseline(b: &mut Bencher) { b.iter(|| { let expected_answer = String::from("test"); let document = Document::parse(super::BASELINE.as_bytes()).unwrap(); let root = document.root.unwrap(); let result = root.text.clone(); assert_eq!(result, Some(...
use oatie::doc::*; #[derive(Serialize, Deserialize, Debug, Clone)] pub enum UserToSyncCommand { // Connect(String), Commit(String, Op, usize), Log(String), TerminateProxy, } #[derive(Serialize, Deserialize, Debug, Clone)] pub enum SyncToUserCommand { // Client id assignment, initial doc, initial v...
/** * [83] Remove Duplicates from Sorted List * * Given the head of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well.   Example 1: Input: head = [1,1,2] Output: [1,2] Example 2: Input: head = [1,1,2,3,3] Output: [1,2,3]   Constraints: The...
extern crate primitives; use primitives::*; fn main() { s02tuples(); s03array(); }
use postoffice::check::{Format,Field,check}; use postoffice::resp::{is_successfull,with_data}; use postoffice::client::channel; use json::JsonValue; use crate::book; use lazy_static::lazy_static; use std::sync::Mutex; use std::collections::HashMap; use mio::{Events, Token, Waker, Poll}; use std::thread; use std::time::...
use super::{do_query, MyState}; use rocket::{get, response::status::NotFound, State}; use serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize, Debug)] struct Swap { id: String, } #[derive(Serialize, Deserialize, Debug)] struct Swaps { swaps: Vec<Swap>, } #[derive(Serialize, Deserialize, Debug)] ...
use anyhow::Result; use std::collections::HashMap; fn main() -> Result<()> { eprintln!("{:?}", Game::new(&[9,6,0,10,18,2,1]).epoch(30000000)); Ok(()) } struct Game { epoch: usize, x: usize, last: HashMap<usize, usize>, previous: HashMap<usize, usize> } impl Game { pub fn new(start: &[usiz...
// if pub fn run() { let age: u8 = 22; let check_id = false; let client = true; // if else if age >= 21 && check_id || client{ println!("Welcome!") } else if age < 21 && !check_id{ println!("Where Id?") } else { println!("Go Home.") } // shorthand let ca...
// Copyright (c) The Starcoin Core Contributors // SPDX-License-Identifier: Apache-2.0 use anyhow::Result; use starcoin_logger::prelude::*; use std::path::Path; use std::time::Duration; //TODO use notify to implement. //TODO move to a suitable crate pub fn wait_until_file_created(file_path: &Path) -> Result<()> { ...
//! Simple thread pool //! //! # Usage //! //! ```rust //! use slave_pool::ThreadPool; //! const SECOND: core::time::Duration = core::time::Duration::from_secs(1); //! //! static POOL: ThreadPool = ThreadPool::new(); //! //! POOL.set_threads(8); //Tell how many threads you want //! //! let mut handles = Vec::new(); //!...
//! Module for storing structs and enums that are used in other modules. use rust_decimal::Decimal; use serde::Deserialize; ///Transaction type enum. Instruct serde how to deserialize by renaming to lowercase. #[derive(Debug, Deserialize, PartialEq, Clone)] #[serde(rename_all = "lowercase")] pub enum TransactionType ...
use rustc_middle::mir; use crate::*; #[derive(Debug, Copy, Clone)] pub enum Dlsym {} impl Dlsym { // Returns an error for unsupported symbols, and None if this symbol // should become a NULL pointer (pretend it does not exist). pub fn from_str<'tcx>(name: &str) -> InterpResult<'tcx, Option<Dlsym>> { ...
// Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 use std::fs::{File, OpenOptions}; use std::io::{Seek, SeekFrom}; use std::path::PathBuf; use std::result; use std::sync::{Arc, Mutex}; use arch::DeviceType; use device_manager::mmio::MMIO_CFG_SPACE_OFF; u...
// //! Copyright 2020 Alibaba Group Holding Limited. //! //! 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 appl...
use fall_log::*; use tracing::Span; #[actix_rt::main] async fn main() -> std::io::Result<()> { let _ = FallLog::new("fall-log".to_string(), std::io::stdout()).init(); let span = Span::from(OpenTrace::default()); let _enter = span.enter(); let mut fs = vec![]; for i in 1..10 { // span.record...
use anyhow::Result; use std::collections::HashMap; use xenon::compute::{Job, JobDescription, JobErrorType, QueueErrorType, QueueStatus, Scheduler}; use xenon::credentials::Credential; const XENON_ENDPOINT: &str = "http://localhost:50051"; async fn create_slurm_scheduler() -> Result<Scheduler> { let credential = C...
#[derive(Debug)] struct Point { x: i32, y: i32, z: i32, } type TempPoint = Point; fn main() { let mut point = Point { x: 0, y: 0, z: 0 }; point.y = 5; let borrowed_point = &mut point; let another_point = &mut point; let another_point1 = &mut point; let another_point2 = &mut point; ...
use crate::issues::{Issue, IssueType, Severity}; pub fn validate(gtfs: &gtfs_structures::Gtfs) -> Vec<Issue> { let route_issues = gtfs .routes .values() .filter(empty_name) .map(make_missing_name_issue); let stop_issues = gtfs .stops .values() .filter(emp...
use ezgame::gfx::*; use super::{ ChunkPosition, ChunkVertex }; /// the geometry and position uniform of a chunk pub struct ChunkMesh { pub geo: ChunkGeometry, pub pos: ChunkPosBind, } /// geometry of a given chunk pub type ChunkGeometry = Geometry<ChunkVertex, u32>; /// position bind group of a chunk pub typ...
use super::{ data::{ItemKind, ResolverDataCollector}, TypeKind, }; use crate::{hir::Class, infer::Type, HirDatabase}; use std::collections::HashMap; impl<'a, DB> ResolverDataCollector<&'a DB> where DB: HirDatabase, { pub fn resolve_class(&mut self, class: &Class) -> Result<(), ()> { self.begin_...
pub use argon2::Error as Argon2Error; use argon2::{Config, ThreadMode}; // Taken from https://github.com/nimiq/core-js/blob/c98d56b2dd967d9a9c9a97fe4c54bfaac743aa0c/src/main/generic/utils/crypto/CryptoWorkerImpl.js#L146 const MEMORY_COST: u32 = 512; const PARALELLISM: u32 = 1; pub fn compute_argon2_kdf( password:...
// Copyright 2020 WHTCORPS INC. Licensed under Apache-2.0. use std::path::Path; use std::sync::{Arc, Mutex, RwLock}; use std::time::Duration; use std::{thread, usize}; use futures::executor::block_on; use grpcio::{ChannelBuilder, EnvBuilder, Environment, Error as GrpcError, Service}; use ekvproto::deadlock::create_de...
#[macro_use] extern crate serde_derive; extern crate serde; extern crate toml; extern crate notify; #[macro_use] extern crate error_chain; #[macro_use] extern crate log; extern crate env_logger; #[macro_use] extern crate lazy_static; mod global; mod config; mod backup_entity; mod backup; fn main() { let config...
use serde::{Deserialize, Serialize}; use std::fmt::Display; use std::{ cell::{Cell, RefCell}, collections::HashMap, io::Read, }; use itertools::Itertools; use tar::{Archive, EntryType}; use v8; use crate::v8util::create_uint8array_from_bytes; use std::convert::TryFrom; #[derive(Clone, Hash, Eq, PartialEq, Deb...
#[doc = r"Register block"] #[repr(C)] pub struct RegisterBlock { _reserved0: [u8; 0x05c4], #[doc = "0x5c4 - Programmable capacitance of XC1 and XC2"] pub xosc32mcaps: XOSC32MCAPS, _reserved1: [u8; 0xf8], #[doc = "0x6c0..0x6d4 - Unspecified"] pub xosc32ki: XOSC32KI, } #[doc = "XOSC32MCAPS (rw) re...
use log::info; use specs::{ world::EntitiesRes, Component, Entities, Join, NullStorage, Read, ReadStorage, System, VecStorage, World, WorldExt, WriteStorage, }; #[derive(Default)] pub struct DeltaTime(pub f64); #[derive(Default)] pub struct MousePos(pub (f64, f64)); #[derive(Default)] pub struct ArenaSize(pub...
use core::str::FromStr; use crate::provisioning::error::{Error, ErrorKind}; use heapless::consts::{U128, U256}; use heapless::{String, Vec}; use serde::{Deserialize, Serialize}; //from edgelet-core pub trait CoreProvisioningResult { fn device_id(&self) -> &str; fn hub_name(&self) -> &str; } #[derive(Clone,...
use advent_of_code_2022::{read, parse}; use itertools::Itertools; use nom::branch::alt; use nom::bytes::complete::tag; use nom::character::complete::{u8, u64}; use nom::combinator::{map, value}; use nom::IResult; use nom::multi::separated_list1; use nom::sequence::tuple; use std::cell::RefCell; use std::collections::Ve...
//! Specifies logic to read problem and routing matrix from json input. //! mod model; pub use self::model::*; mod reader; pub use self::reader::PragmaticProblem;
use amethyst::ecs::prelude::{Component, DenseVecStorage}; #[derive(Debug, new)] pub struct BeatmapButton { pub beatmap: String, } impl Component for BeatmapButton { type Storage = DenseVecStorage<Self>; }
use std::io::{self, BufRead, Write}; use http::{header, request, response, Request, Version}; use httparse; use util::wrap_error; use Error; pub fn write_request_header<T, W: Write>(writer: &mut W, req: &Request<T>) -> io::Result<()> { let (_, authority, path) = wrap_error(request::get_target_components(req))?; ...
use libc::{c_char}; #[repr(C)] pub struct LinkedList { pub size: i32, pub head: *mut Node, pub tail: *mut Node, } #[repr(C)] pub struct Node { pub data: Data, pub next: *mut Node, } #[repr(C)] pub struct Data { pub number: f32, pub string: *const c_char, } #[no_mangle] pub extern "C" fn ...
use cargo_snippet::snippet; //#[snippet("PrimeFactorization")] //fn prime_factorization2(x: i64) -> std::collections::BTreeMap<i64, i64> { // (std::iter::once(2).chain((3..).step_by(2))) // .scan(x, |state, i| match *state { // 1 => None, // _ => { // let divisor = if i *...
#![feature(stmt_expr_attributes, proc_macro_hygiene)] fn main() { let msg = emit::format!("A string {template: 42}"); assert_eq!("A string 42", msg); }
use std::cmp::{max, min, PartialEq}; use super::Point; use super::Size; pub struct Rectangle { pub x : i32, pub y : i32, pub width : i32, pub height : i32 } impl Rectangle { pub fn new(x : i32, y : i32, width : i32, height : i32) -> Rectangle { Rectangle { x: x, y: y, ...
fn main() { aoc_2019_03::part2() }
use std::fs; #[derive(Default, Debug, Copy, Clone)] struct Point { x: i32, y: i32, } #[derive(Default, Debug)] struct Path { direction: String, len: i32, point1: Point, point2: Point } impl Path { fn step_to_point(&self, point: &Point) -> i32 { match self.direction.as_ref() { ...
// Copyright (c) The Starcoin Core Contributors // SPDX-License-Identifier: Apache-2.0 //! This module defines all the gas parameters and formulae for instructions, along with their //! initial values in the genesis and a mapping between the Rust representation and the on-chain //! gas schedule. use crate::gas_meter:...
use std::{thread, time}; const ENV_HEIGHT: usize = 30; const ENV_WIDTH: usize = 30; fn print_2d_vec(v: &Vec<Vec<u32>>) { for i in v.iter() { for j in i.iter() { if *j > 0 { print!("{}[41m{}{}[40m ",27 as char, j, 27 as char); } else { print!("{} ", ...
/// This generates Device Plugin code (in v1beta1.rs) from pluginapi.proto fn main() { tonic_build::configure() .build_client(true) .out_dir("./src/util") .compile(&["./proto/pluginapi.proto"], &["./proto"]) .expect("failed to compile protos"); }
// This file is part of Substrate. // Copyright (C) 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 // // http://www.a...
// This file is part of Substrate. // Copyright (C) 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 // // http://www.a...
use crate::assets::{AssetPack,AssetStorage}; use specs::{World}; use crate::render::types::{Texture}; use crate::render::components::{SpriteSheet}; use crate::render::{FontAsset}; pub enum S2DAssetPack { } impl AssetPack for S2DAssetPack { } impl S2DAssetPack { pub fn register_all_storage(world:&mut World)...
// 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 ...
// This file is part of Substrate. // Copyright (C) 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 // // http://www.a...
/** * [113] Path Sum II * * Given the root of a binary tree and an integer targetSum, return all root-to-leaf paths where the sum of the node values in the path equals targetSum. Each path should be returned as a list of the node values, not node references. A root-to-leaf path is a path starting from the root and e...