text
stringlengths
8
4.13M
#![cfg_attr(not(feature = "std"), no_std)] #![feature(proc_macro_hygiene)] // for tests in a separate file use ink_lang as ink; #[ink::contract] mod ddc { use ink_prelude::string::String; use ink_prelude::vec::Vec; use ink_storage::{ collections::HashMap as StorageHashMap, lazy::Lazy, ...
use std::cmp::Ordering; use std::collections::BinaryHeap; use grid::Grid; use direction::Direction; use direction::Direction::*; use maze::Maze; use posn::Posn; use tile::Tile; #[derive(Copy, Clone, Debug, PartialEq, Eq)] struct Node { cost: Option<i32>, from: Direction, } impl Node { fn new() -> Node {...
use collections::BTreeSet; use constants::*; use kernel_std::*; use segment::Segment; pub struct Layout { map: BTreeSet<Segment>, free: Allocator, } impl Layout { pub fn new() -> Layout { Layout { map: BTreeSet::new(), free: Allocator::new() } } #[inline...
// id number A unique identifier for each domain record. // type string The type of the DNS record (ex: A, CNAME, // TXT, ...). // name string The name to use for the DNS record. // data string The value to use for the DNS record. // ...
#[macro_use] extern crate failure; use failure::Error; use std::process::Command; use std::process::Output; /// Represents a failed command (non-zero satus) #[derive(Fail, Debug)] #[fail(display = "Command failed: {}, output: {:?}", command, output)] pub struct CommandFail { command: String, output: Output, } impl...
// Copyright (c) 2019, Facebook, Inc. // All rights reserved. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use parser_rust as parser; use ocamlpool_rust::{ caml_raise, ocamlvalue::*, utils::{block_field, bool_field, str_...
use std::{fmt::Write, sync::Arc}; use prometheus::core::Collector; use twilight_model::{ application::{ command::CommandOptionChoice, component::{ button::ButtonStyle, select_menu::SelectMenuOption, ActionRow, Button, Component, SelectMenu, }, interaction::{ ...
fn som(x: i64, y: i64) -> i64 { x + y } fn maxi(x: i64, y: i64) -> i64 { if x > y { x } else { y } } fn mini(x: i64, y: i64) -> i64 { if x < y { x } else { y } } fn gcdi(m: i64, n: i64) -> i64 { let x = maxi(m.abs(), n.abs()); let y = mini(m.abs(), n.abs()); if x % y == 0 { y...
mod media; use media::Playable; struct Audio(String, String); struct Video(String, String); impl Playable for Audio { fn play(&self) { println!("Now Playing: {} by {}", self.0, self.1); } } impl Playable for Video { fn play(&self) { println!("Now Playing: {} by {}", self.0, self.1); }...
extern crate kmod; #[macro_use] extern crate log; extern crate env_logger; use std::env; use std::fs; fn main() { env_logger::init(); let ctx = kmod::Context::new().expect("kmod ctx failed"); let filename = env::args().nth(1).expect("missing argument"); let module = match fs::metadata(&filename) {...
#![feature(plugin, custom_derive)] #![plugin(rocket_codegen)] extern crate bindgen; extern crate rocket; use bindgen::builder; use rocket::request::Form; use rocket::response::NamedFile; use std::path::{Path, PathBuf}; #[get("/")] fn index() -> Option<NamedFile> { NamedFile::open(Path::new("static/index.html"))....
use nu_engine::CallExt; use nu_protocol::ast::Call; use nu_protocol::engine::{Command, EngineState, Stack}; use nu_protocol::{ Category, Example, IntoInterruptiblePipelineData, PipelineData, Signature, Span, Spanned, SyntaxShape, Value, }; #[derive(Clone)] pub struct Window; impl Command for Window { fn n...
pub type Runs = Vec<Run>; // only define the structs for the data I want to pull out #[derive(Debug,Serialize, Deserialize)] pub struct Run { pub status: String, pub result: String, pub user: User, } #[derive(Debug,Serialize, Deserialize)] pub struct User { pub meta: Meta, } #[derive(Debug,Serialize...
#![doc = "generated by AutoRust 0.1.0"] #![allow(non_camel_case_types)] #![allow(unused_imports)] use serde::{Deserialize, Serialize}; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CanonicalSupportPlanProperties { #[serde(rename = "provisioningState", default, skip_serializing_if = "Option::...
//! rocket_auth provides a ready-to-use backend agnostic API for authentication management. //! It supports connections for SQLite and Postgresql. It lets you create, delete, and authenticate users. //! The available features are: //! * `sqlite-db`: for interacting with a SQLite database using [`sqlx`]. //! * `postgre...
use std::fmt; #[derive(Debug)] struct User{ username: String, email: String, sign_in_count: u64, active: bool, } impl fmt::Display for User { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "({}, {}, {}, {})", self.username, self.email, self.sign_in_count, self.active)...
// This code is quite a bit different than the code you might be used to. Don't fear! I believe // in you! // // Please take a look at the accompanying README.md located in this directory for setup/test // instructions. // Here we import the `qrcode` crate (like a Ruby gem). It is also declared in the `./Cargo.toml`. ...
use crate::event::Event; use std::collections::VecDeque; #[derive(Debug, Clone, Hash, PartialEq, Eq)] pub struct EventQueue(VecDeque<Event>); impl EventQueue { pub fn new() -> Self { EventQueue(VecDeque::new()) } pub fn enqueu(&mut self, event: Event) { self.0.push_front(event); } ...
pub fn factorial(n: u16) -> u64 { match n { 0 => 1, _ => factorial(n - 1) * n as u64 } }
use crate::character::{ AbilityBoostChoice, AbilityBoostChoiceSet, AbilityScore, AbilityScoreSet, AbilityScoreType, Ancestry, Background, Class, Health, }; #[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)] pub enum Size { Tiny, Small, Medium, Large, Huge, Gargantuan, } pub ...
#[derive(Debug, PartialEq, Eq)] pub enum DivisionError { NotDivisible(NotDivisibleError), DivideByZero, } #[derive(Debug, PartialEq, Eq)] pub struct NotDivisibleError { dividend: i32, divisor: i32, } // This function should calculate `a` divided by `b` if `a` is // evenly divisible by b. // Otherwise...
//! Exposes the ``name!()`` macro, which can be used to assign type names to values. This can be //! used to implement in part the "Ghosts of Departed Proofs" pattern. Be very careful using this //! crate, and see the README for some caveats. use std::marker::PhantomData; #[macro_use] extern crate derivative; /// An...
use token::{Token, Type}; #[derive(Clone, Eq, PartialEq, Ord, PartialOrd)] pub struct Ast { pub node_val: Option<Token>, child_nodes: Vec<Ast> } pub trait AstTrait { fn push_child(&mut self, ast: Ast); fn pop_child(&mut self) -> Option<Ast>; fn get_child(&mut self, index: usize) -> Option<Ast>; ...
use kuragecc::ast::visualize_ast; use kuragecc::codegen::CodeGenerator; use kuragecc::error::VisualizeError; use kuragecc::lexer::Lexer; use kuragecc::parser::Parser; use kuragecc::semantics::SemanticAnalyzer; use std::fs; fn main() { let paths = vec![ // "example/main0.tmpc", // "example/main1.tm...
use crate::engine::basic_types::*; use crate::engine::*; #[derive(Clone, Debug)] pub struct ElementData { pub active: bool, pub position: Rect, pub rotation: f64, } pub struct Element { pub data: ElementData, pub components: Vec<Box<dyn Component>>, } impl Element { pub fn new(x: i32, y: i32, s...
use postgres::{Client, NoTls}; use serde::{Deserialize, Serialize}; #[derive(Debug, Serialize, Deserialize)] pub struct Claims { pub id: String, pub exp: usize, pub sub: String, } pub fn get_event_store_db_connection() -> Result<Client, postgres::Error> { Client::connect( crate::SECRETS .get("event_store_con...
// Copyright 2015 The Rust-Windows Project Developers. See the // COPYRIGHT file at the top-level directory of this distribution. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MI...
use crate::computer::*; use crate::human::*; use crate::player::Player; use rand::seq::SliceRandom; pub const CARDS: [u8; 13] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]; pub struct GameControl { human: HumanPlayer, computers: [ComputerPlayer; 3], } impl GameControl { pub fn create_game(human_name: &st...
use std::sync::atomic::compiler_fence; use std::sync::atomic::Ordering; #[link(name = "dmb")] extern "C" { pub fn __dmb(); } #[inline(always)] pub fn dmb() { compiler_fence(Ordering::SeqCst); unsafe { __dmb(); } compiler_fence(Ordering::SeqCst); }
#![cfg(test)] use super::*; use crate::physics::single_chain::test::Parameters; mod base { use super::*; use rand::Rng; #[test] fn init() { let parameters = Parameters::default(); let _ = WLC::init(parameters.number_of_links_minimum, parameters.link_length_reference, param...
// run simulate_nodes and main app to debug #![allow(unused_variables)] #[macro_use] extern crate diesel; use std::collections::{HashMap}; use mosquitto_client::{Mosquitto}; use std::io::{Error, ErrorKind}; use std::time::Duration; use std::thread; use std::cell::RefCell; use env_logger::Env; use log::{debug, info, w...
mod justification; mod keyring; mod mock; use crate::chain::{Chain, OpaqueExtrinsic}; use crate::grandpa::{verify_justification, AuthoritySet, Error, GrandpaJustification}; use crate::{ initialize, validate_finalized_block, ChainTip, CurrentAuthoritySet, Error as ErrorP, InitializationData, OldestKnownParent, ...
use serde_json::{Value}; use crate::ldtab_2_ofn::axiom_translation as axiom_translation; use crate::ldtab_2_ofn::annotation_translation as annotation_translation; use crate::util::parser as parser; /// Given an LDTab ThickTriple (encoded as a string), /// return its corresponding OFN S-expression encoded as a serde_...
use std::borrow::Cow; use std::convert::TryFrom; use std::fmt::Display; use std::fmt::Formatter; use std::fmt::Result as FmtResult; use std::fmt::Write; use pest::error::Error as PestError; use pest::Parser as PestParser; use super::Arg; use crate::parser::Parser; use crate::parser::Rule; /// A mnemonic with its arg...
fn main() { let size : usize = 1001; // Generate array let spiral_numbers = generate_spiral(size); //print_spiral(&spiral_numbers, size); // Calculate diagonal sum let sum = calculate_diagonal_sum(&spiral_numbers, size); println!("Diagonal sum: {}", sum); } fn generate_spiral(size: usize...
#![doc = "generated by AutoRust 0.1.0"] #![allow(non_camel_case_types)] #![allow(unused_imports)] use serde::{Deserialize, Serialize}; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct OperationsListResult { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<Operation>, ...
use std::env; use std::thread::{self, JoinHandle}; /// Spawns a new thread with the given code, or executes it directly if the environment variable `PERSEUS_CLI_SEQUENTIAL` is set to /// any valid (Unicode) value. Multithreading is the default. pub fn spawn_thread<F, T>(f: F) -> ThreadHandle<F, T> where F: FnOnce(...
use crate::avrcore::Avrcore; use std::fs; use regex::Regex; use std::str; enum FieldNumber { BCField = 1, AddrField = 2, RTField = 3, DatField = 4, CSField = 5 } impl FieldNumber { fn from_usize(value: usize) -> FieldNumber { match value { 1 => FieldNumber::BCField, ...
use error::*; use futures::future; use futures::{Future, Stream}; use mime; use multipart; use hyper; use hyper_tls::HttpsConnector; use std::path::PathBuf; use hyper::server::{self, Service}; use hyper::header::{Header, ContentDisposition, ContentType, DispositionParam}; use hyper::{Request, Response}; use multipart::...
use super::super::prelude::{ HINSTANCE , CursorService , IconService , Text , Cursor , Icon }; pub type Application = HINSTANCE; pub trait ResourceFunctionInApplication { fn loadCursor(&self , iconName : Text) -> Cursor; fn loadIcon(&self , iconName : Text) -> Icon; } impl ResourceFunctionInApplication for Appli...
#[cfg(test)] mod tests { use casper_engine_test_support::{Code, Hash, SessionBuilder, TestContextBuilder}; use casper_types::{ account::AccountHash, runtime_args, PublicKey, RuntimeArgs, SecretKey, U512, }; #[test] fn should_store_hello_world() { // Prepare the account. let ...
// https://doc.rust-lang.ru/book/ch03-05-control-flow.html // конвертер температур из единиц Фаренгейта в единицы Цельсия use std::io; fn converter(f: f32) -> f32 { let x = (5.0 / 9.0) as f32; ((f - 32.0) * x) as f32 } fn main() { loop { println!("\nВведите температуру в единицах Фаренгейта."); ...
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
/* https://projecteuler.net It was proposed by Christian Goldbach that every odd composite number can be written as the sum of a prime and twice a square. 9 = 7 + 2×12 15 = 7 + 2×22 21 = 3 + 2×32 25 = 7 + 2×32 27 = 19 + 2×22 33 = 31 + 2×12 It turns out that the conjecture was false. What is the smallest odd compos...
pub use self::graphemes_struct::Graphemes; /// Vector of graphemes mod graphemes_struct { extern crate unicode_segmentation; use unicode_segmentation::UnicodeSegmentation; use std::ops::{Deref, Index, IndexMut}; use std::fmt::{Display, Formatter}; use std::fmt; use len_trait::len::{Len, Empty, ...
use std::sync::mpsc; use std::sync::mpsc::{Receiver, Sender}; use std::sync::{Once, ONCE_INIT}; use std::thread; use std::time::{Duration, Instant}; use nats::Client; use config; pub fn publish(subject: String, msg: String) { let pipe = Pipe::get(); pipe.as_ref() .map(|p| p.sender.send((subject, msg)...
extern crate phrases; fn main() { println!("{}", phrases::english::hello()); println!("{}", phrases::japanese::goodbye()); }
use std::sync::Arc; use async_trait::async_trait; use common::error::Error; use common::result::Result; use identity::domain::user::{UserId, UserRepository}; use publishing::domain::content_manager::{ ContentManager, ContentManagerId, ContentManagerRepository, }; pub struct ContentManagerTranslator { user_re...
pub mod database_config; pub mod github; pub mod gitlab; pub mod global_config;
#![no_std] extern crate alloc; pub use plugin_map::*; pub use registry::*; pub mod info; mod plugin_map; mod registry; mod plugin;
#[doc = "Register `PFCR` reader"] pub type R = crate::R<PFCR_SPEC>; #[doc = "Register `PFCR` writer"] pub type W = crate::W<PFCR_SPEC>; #[doc = "Field `PF` reader - Pixel Format"] pub type PF_R = crate::FieldReader<PF_A>; #[doc = "Pixel Format\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[repr(u...
use seed::prelude::{Node, Orders}; pub trait ActionComponent<'a, A, M: 'static> { fn view(model: &A) -> Node<M>; fn handle(msg: M, model: &'a mut A, _: &'a mut impl Orders<M>); } pub trait Component<A, M> { fn view(model: &A) -> Node<M>; }
use crate::error::Error; #[derive(Debug)] pub struct Char { pub code: u8, pub row: u32, pub col: u16, } pub struct Chars<I: Iterator<Item = Result<u8, Error>>> { source: I, row: u32, col: u16, single_comment: bool, multi_comment: bool, } impl<I: Iterator<Item = Result<u8, Error>>> Fro...
// This file was generated mod barrier_wait_result_private { pub trait Sealed { } } /// Extension for [`BarrierWaitResult`](std::sync::BarrierWaitResult) pub trait IsntBarrierWaitResultExt: barrier_wait_result_private::Sealed { /// The negation of [`is_leader`](std::sync::BarrierWaitResult::is_leader) #[must_...
extern crate ralloc; mod util; use std::thread; fn make_thread() -> thread::JoinHandle<()> { thread::spawn(|| { let mut vec = Vec::new(); for i in 0..0xFFF { util::acid(|| { vec.push(0); vec[i] = i; }); } for i in 0..0xFFF ...
extern crate rand; use std::error::Error; use crate::lib::core::*; use crate::lib::feature::StaticFeature; use crate::lib::node; use crate::lib::star::StaticStarSecret; const MY_STAR_SECRET: StaticStarSecret = StaticStarSecret {}; const FEATURE_STAR_ALIAS: StaticFeature = StaticFeature { facet: "Star", point: "Alias...
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the root directory of this source tree. //! Basic polynomial operations. //! //! This module provides a set of function for basic polynomial operations, including: //! - Polynomi...
use nu_engine::CallExt; use nu_protocol::{ ast::Call, engine::{Command, EngineState, Stack}, Category, Example, IntoInterruptiblePipelineData, PipelineData, ShellError, Signature, Span, SyntaxShape, Value, }; #[derive(Clone)] pub struct SortBy; impl Command for SortBy { fn name(&self) -> &str { ...
#![feature(no_std, plugin)] #![no_std] #![plugin(arm_rt_macro)] extern crate stm32; extern crate rlibc; use stm32::stm32f4::*; #[entry_point] fn main() -> ! { // enable LED GPIOs (PG13 = green, PG14 = red) RCC.ahb1enr.set_gpiog_en(true); // set LED pins to "output" GPIOG.moder.set_mode(13, stm32...
use std::*; fn read_line() -> String { let mut line = String::new(); io::stdin().read_line(&mut line).unwrap(); line } fn main() { let mut a = vec![1, 2, 3]; // 这里相当于是 for i in a.into_iter(), 会发生 move, 所以 p16 会报错 // for i in a { // println!("i is {}", i); // } // println!("sum...
//! Chain specification for the evm domain. use evm_domain_test_runtime::{AccountId as AccountId20, GenesisConfig, Precompiles, Signature}; use sp_core::{ecdsa, Pair, Public}; use sp_domains::DomainId; use sp_runtime::traits::{IdentifyAccount, Verify}; use subspace_runtime_primitives::SSC; type AccountPublic = <Signa...
use syntax::tokens::{ TokenType, Token, BinOp, }; /* A sadly OOP approach on a lexer. * Potentially improved using a peekable iterator. */ pub struct Lexer { tokens: Vec<Token>, lines: u32, start: usize, pos: usize, top: usize, } impl Lexer { ...
/// runs shell commands #[macro_export] macro_rules! async_shell { () => {}; ($($t:tt)*) => { { $crate::__tokio_internal_builder!() .arg( $crate::__internal_command_builder!($($t)*) ).spawn()?.wait_with_output().await? } }; } /...
use criterion::{criterion_group, criterion_main, Criterion}; use once_cell::sync::Lazy; use rusttype::*; static DEJA_VU_MONO: Lazy<Font<'static>> = Lazy::new(|| { Font::try_from_bytes(include_bytes!("../fonts/dejavu/DejaVuSansMono.ttf") as &[u8]).unwrap() }); static OPEN_SANS_ITALIC: Lazy<Font<'static>> = Lazy::ne...
extern crate clap; use clap::{App, Arg}; use std::process; // imports the library crate that has a public API available to test! use minigrep::Config; fn main() { let matches = App::new("minigrep") .version("1.0") .author("James M. <jmstudyacc@gmail.com>") .about( "Searches a ...
use std::{ collections::VecDeque, io::{stdout, Write}, time::{Duration, Instant}, }; use futures::{future::FutureExt, select, StreamExt}; use futures_timer::Delay; use crossterm::{ cursor, event::{Event, EventStream, KeyCode}, execute, queue, terminal }; enum Direction { Up, Right...
#![allow(dead_code)] use std::marker::PhantomData; use std::string::String; /// Сущности struct User { user_id: u64, full_name: String, email: String, } struct Post<S> { post_id: u64, user: User, title: String, body: String, state: PhantomData<S>, } /// Состояния struct New; struct U...
//! Azure iot_hub crate for the unofficial Microsoft Azure SDK for Rust. This crate is part of a collection of crates: for more information please refer to [https://github.com/azure/azure-sdk-for-rust](https://github.com/azure/azure-sdk-for-rust). #![deny(missing_docs)] //! The IoT Hub crate contains a client that can ...
use std::io; fn main() { let mut pancakes: Vec<u32> = Vec::new(); let mut buffer: String = String::new(); io::stdin().read_line(&mut buffer) .expect("failed to read line"); pancakes = buffer .trim() .split_whitespace() .map(|x: &str| x.parse::<u32>().unwrap()) .collect(); print...
use std::env; use std::fs; use std::io; static PART2: bool = true; fn main() { let input: &String = &env::args().nth(1).unwrap(); let input_data = read_input(&input).unwrap(); let result = calc_fuel(&input_data); println!("Total fuel: {}", result); } fn read_input(path: &str) -> io::Result<Vec<...
pub mod control_rov; pub mod port_select; use ::errors::*; pub enum Trans { Quit, None, Switch(Box<Screen>), } pub trait Screen { fn init(&mut self, engine: &mut Engine) -> Result<()>; fn update(&mut self, engine: &mut Engine, delta: f64) -> Result<Trans>; fn render(&mut self, engine: &mut E...
use super::core::element::*; use super::core::level::Level; use std::fs; use unicode_segmentation::UnicodeSegmentation; pub fn element_to_unicode(element: Option<&Element>) -> &str { match element { Some(Element::Object(Object::FERRIS)) => return "🦀", Some(Element::Object(Object::ROCKET)) => retur...
mod support; use self::support::*; #[test] fn outbound_http1() { let _ = env_logger::try_init(); let srv = server::http1().route("/", "hello h1").run(); let ctrl = controller::new() .destination("transparency.test.svc.cluster.local", srv.addr) .run(); let proxy = proxy::new().controlle...
use {ContextRef, ValueRef, TypeRef, AtomicOrdering, SynchronizationScope, IntegerPredicateKind, FloatPredicateKind, AtomicBinaryOp}; use libc; cpp! { #include "ffi_helpers.h" #include "llvm/IR/Instructions.h" pub fn LLVMRustInstructionInsertAfter(inst: ValueRef as "llvm::Value*", ...
fn main() { let mut fib = vec![1, 2]; let mut ans = 2; while fib.last() < Some(&4000000) { let l = fib.len(); let n = fib[l - 1] + fib[l - 2]; fib.push(n); if n % 2 == 0 { ans += n; } } println!("{}", ans); }
extern crate crypto; extern crate image_base64; use crypto::digest::Digest; use crypto::md5::Md5; use std::fs; use std::fs::File; use std::io::Read; use std::io::Write; use std::path::Path; use std::path::MAIN_SEPARATOR; use std::str; use std::string::String; static FILE_NAME: &'static str = "nyan"; #[test] fn jpg_t...
extern crate regex; extern crate rustc_serialize; use std::env; use std::io::{self, Read, Write}; use std::fs::File; use regex::Regex; use rustc_serialize::base64::{ToBase64, STANDARD}; fn replace_contents(line: &str) -> String { let args: Vec<String> = env::args().collect(); let assets_dir = args[1].clone...
extern crate amqp; extern crate env_logger; use serde_json; use ofborg::worker; use ofborg::stats; use amqp::protocol::basic::{Deliver, BasicProperties}; pub struct StatCollectorWorker<E> { events: E, collector: stats::MetricCollector, } impl<E: stats::SysEvents + 'static> StatCollectorWorker<E> { pub fn...
use super::*; use crate::components::LogEntry; use crate::indices::EntityTime; use serde::{Deserialize, Serialize}; use std::collections::BTreeMap; #[derive(Default, Debug, Serialize, Deserialize)] pub struct BTreeTable<Id, Row> where Id: TableId, Row: TableRow, { data: BTreeMap<Id, Row>, } impl<Id, Row> ...
#![feature(plugin)] #![plugin(rocket_codegen)] extern crate rocket; extern crate kafka; use std::time::Duration; use kafka::producer::{Producer, Record, RequiredAcks}; use kafka::error::Error as KafkaError; fn send_message(message: String) -> Result<(), KafkaError> { let kafka_server = "rocket-kafka_kafka:9092"...
mod cmp; pub use self::cmp::*;
use axum_websockets::{ configuration::get_configuration, telemetry::{get_subscriber, init_subscriber}, Application, }; #[tokio::main] async fn main() -> Result<(), hyper::Error> { let subscriber = get_subscriber("actix_websockets".into(), "info".into(), std::io::stdout); init_subscriber(subscriber)...
fn main() { let code = String::from_utf8(std::fs::read("input/day8").unwrap()) .unwrap() .split_terminator("\n") .map(|instruction| { let mut instruction = instruction.split_whitespace(); ( instruction.next().unwrap().to_owned(), instru...
use crate::database::values::dsl::{ExprDb, SelectDb}; use nu_protocol::{ ast::Call, engine::{Command, EngineState, Stack}, Category, Example, IntoPipelineData, PipelineData, ShellError, Signature, Span, Type, Value, }; #[derive(Clone)] pub struct ExprAsNu; impl Command for ExprAsNu { fn name(&self) -...
use crate::*; use futures::Future; use std::fmt; use std::pin::Pin; use std::task::{Context, Poll}; pub struct TestDevice { pub device_info: DeviceInfo, pub device: Device<TestDeviceTransport>, } pub fn test_with_devices<FN, F>(_f: FN) where FN: Fn(TestDevice) -> F, F: Future<Output = Result<(), Error...
//! The [`Binder`] translates a [`Token`] stream into bound expressions //! that can then be translated into machine code. use prelude::*; use prelude::parse::*; use builder::Builder; use core::syscore; use expr::{BuiltIns, Unit}; use input::{Input, InputFile}; use intrinsics::import_intrinsics; use typesystem::{Membe...
use std::net::{ TcpStream, Shutdown, SocketAddr }; use std::time::Duration; fn main() { let mut open_ports = vec![]; for i in 1..=65535 { let ip = "192.168.0.1:".to_string(); let port = i.to_string(); let addr = ip + &port; let socket: SocketAddr = addr.parse().unwrap(); ...
use glam::Vec3; #[derive(Clone, Copy)] pub struct Ray { pub origin: Vec3, pub direction: Vec3, } impl Ray { pub fn new(origin: Vec3, direction: Vec3) -> Self { Ray { origin, direction } } }
use crate::base::id; use crate::base::BOOL; use crate::foundation::NSString; use crate::foundation::NSURL; // https://developer.apple.com/documentation/appkit/nsimage #[derive(Clone, Copy, Debug)] #[repr(C)] pub struct NSImage(id); impl NSImage { pub fn alloc() -> Self { Self(unsafe { msg_send!(class!(NSImage),...
use rand::Rng; use std::f32::consts; fn main() { let net = Network::new(vec![2,1,2]); println!("{:?}", net); let result = feedforward(net.biases, net.weights, vec![0.1, 0.5]); println!("{:?}", result); } #[derive(Debug)] struct Network { num_layer: u8, sizes: Vec<i16>, biases: Vec<Vec<f32>...
use astroplant_mqtt::{KitRpc, ServerRpcRequest}; fn main() { let (receiver, kits_rpc) = astroplant_mqtt::run( "mqtt.ops".to_owned(), 1883, "server".to_owned(), "abcdef".to_owned(), ); std::thread::spawn(move || { println!("Querying kit with serial 'k_develop'"); ...
#![cfg(test)] mod util; mod connect_obvious_tests; mod prune_tests; mod reg_tests; mod zero_area_loop_tests; mod graph_stitch_tests;
pub mod udp_server; pub mod data_structs; extern crate csv; extern crate chrono; extern crate byteorder; fn main() { // need to get these from command line let lines_to_skip: usize = 4; udp_server::socket_response("0.0.0.0", 13389, lines_to_skip); }
#[macro_use] extern crate criterion; use criterion::{BatchSize, Criterion}; use hacspec_p256::*; fn benchmark(c: &mut Criterion) { // TODO: allow key generation and make these random c.bench_function("P256 ECDH", |b| { b.iter_batched( || { let k = P256Scalar::from_hex( ...
extern crate tree_child; use tree_child::network::TcNet; use tree_child::newick; use tree_child::tree_child_sequence; use tree_child::tree::TreeBuilder; /// Test that we correctly construct a network if all trees are the same #[test] fn trivial_network() { let mut builder = TreeBuilder::new(); let tree_new...
use proconio::{fastout, input}; #[fastout] fn main() { input! { n: i64, mut a_list: [i128; n], } for a in a_list.iter() { if a == &0 { println!("0"); return; } } for a in a_list.iter() { if a >= &(1e18 as i128) { println!(...
use crate::error::Error; use crate::error::ErrorKind; use crate::kind::Kind; use crate::class::Class; use crate::dnssec; use crate::edns; use crate::ser::Serializer; use crate::ser::Serialize; use crate::de::Deserializer; use crate::de::Deserialize; use base64; use std::io; use std::net::IpAddr; use std::net::Ipv4Add...
use std::error::Error; use std::fmt::{self, Formatter}; #[derive(Debug)] pub struct FieldNotPresentError; impl fmt::Display for FieldNotPresentError { fn fmt(&self, f: &mut Formatter) -> fmt::Result { write!(f, "Mandatory field not present") } } impl Error for FieldNotPresentError { fn descriptio...
use lazy_static::lazy_static; use regex::Regex; use std::collections::HashMap; use std::io; use std::str::FromStr; use crate::base::Part; pub fn part1(r: &mut dyn io::Read) -> Result<String, String> { solve(r, Part::One) } pub fn part2(r: &mut dyn io::Read) -> Result<String, String> { solve(r, Part::Two) } ...
use std::env; use std::fs; use std::path::Path; use std::collections::HashMap; fn read_instructions(filename: &str) -> String{ let fpath = Path::new(filename); let abspath = env::current_dir() .unwrap() .into_boxed_path() .join(fpath); let content = fs::read_to_string(abspath) ...