text
stringlengths
8
4.13M
pub const QUIT: &str = "quit"; pub const GET_CONFIG: &str = "get_config"; pub const READ_PASSWORD: &str = "read_password"; pub const PRINT_STDOUT: &str = "print_stdout"; pub const PRINT_STDERR: &str = "print_stderr"; pub const RPC_URL_CHANGED: &str = "rpc_url_changed"; pub const SUB_COMMAND: &str = "sub_command"; pub ...
//! Module implementing the actual captioning task. //! Most if not all captioning logic lives here. use std::io; use std::ops::Deref; use std::sync::Arc; use image::{self, DynamicImage, FilterType, GenericImage, ImageFormat}; use rusttype::{point, Rect, vector}; use model::{Caption, ImageMacro, Size, DEFAULT_TEXT_S...
fn main() { println!("Hello, world!"); ownership(); let len = calculate_length(String::from("Hello")); println!("lenght of {} is {}",len.0, len.1); let s1 = String::from("Hello"); let len2 = calculate_length_passing_ref( &s1 ); println!("length of {} is {}", s1, len2 ); let mut newStr ...
extern crate syncbackup; use syncbackup::args::Args; use syncbackup::errorcode::ErrorCode; use syncbackup::sync::make_sync; fn main() { let help_message = "\n\nFor more information use \"--help\"\n"; let args = Args::new().unwrap_or_else( |err| { eprintln!("{}{}", err.err_message(), help_message); ...
// To be a senior, a member must be at least 55 years old and have a handicap greater than 7 fn open_or_senior(data: Vec<(i32, i32)>) -> Vec<String> { data.iter().map(|(years, handicap)| if years > &54 && handicap > &7 { "Senior".to_string() } else { "Open".to_string() }).collect() } #[test] fn returns_e...
use std::io::Error as IoError; use std::fmt; #[cfg(unix)] use std::os::unix::io::AsRawFd; use std::pin::Pin; use std::task::Context; use futures::Future; use futures::Poll; use pin_utils::pin_mut; use nix::sys::sendfile::sendfile; use nix::Error as NixError; use crate::fs::AsyncFileSlice; use crate::asyncify; ///...
use crate::config::color_palette::ColorPalette; use crate::config::controls::Controls; use serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize, Debug)] pub struct Config { pub controls: Controls, #[serde(default = "ColorPalette::default")] pub color_palette: ColorPalette, } impl Config { ...
use std::collections::HashMap; pub struct Solution; impl Solution { pub fn subarrays_div_by_k(a: Vec<i32>, k: i32) -> i32 { let mut prefix_sum = 0; let mut mod_map: HashMap<i32, i32> = HashMap::new(); // mapping <prefix_sum % k, count> for &x in a.iter() { prefix_sum += x; ...
pub fn foo() -> i32 { 42 }
//! Program entrypoint. #![cfg_attr(feature = "strict", deny(warnings))] use serum_common::pack::Pack; use serum_safe::error::{SafeError, SafeErrorCode}; use serum_safe::instruction::SafeInstruction; use solana_sdk::account_info::AccountInfo; use solana_sdk::entrypoint::ProgramResult; use solana_sdk::info; use solana...
#[doc = "Register `PD` reader"] pub struct R(crate::R<PD_SPEC>); impl core::ops::Deref for R { type Target = crate::R<PD_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<PD_SPEC>> for R { #[inline(always)] fn from(reader: crate::R<PD_SPEC>) -> Se...
use tiny_skia::*; #[test] fn line() { let mut pb = PathBuilder::new(); pb.move_to(10.0, 20.0); pb.line_to(90.0, 80.0); let path = pb.finish().unwrap(); let mut paint = Paint::default(); paint.set_color_rgba8(50, 127, 150, 200); paint.anti_alias = false; let mut stroke = Stroke::defaul...
// #[macro_use] // extern crate quicli; // use quicli::prelude::*; extern crate notify; use std::process::{Command, Stdio}; use notify::{DebouncedEvent, RecommendedWatcher, RecursiveMode, Watcher}; use std::sync::mpsc::channel; use std::time::Duration; fn watch() -> notify::Result<()> { // Create a channel to re...
//! Tests transitive dependencies. use a_proto::a::A; use b_proto::a::b::B; use c_proto::a::b::c::C; use duration_proto::google::protobuf::Duration; use timestamp_proto::google::protobuf::Timestamp; use types_proto::Types; #[test] fn test_b() { let duration = Duration { seconds: 1, nanos: 2, }...
pub mod dices; pub mod rejections;
use config; pub fn for_version(language: &String, version: &String) -> String { // Check version and set colour let versions = config::language(language.to_string()).unwrap(); let latest = versions["latest"].as_vec().unwrap(); let mut colour = "red"; for v in latest { if v.as_str().unwrap()...
// Copyright 2018 Grove Enterprises LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed ...
use std::borrow::{Borrow, BorrowMut}; use primitives::index_allocator::IndexAllocator; pub trait Like<T>: Into<T> + From<T> + Borrow<T> + BorrowMut<T> { fn virtual_borrow<R, F: FnOnce(&mut Self) -> R>(value: T, f: F) -> R { let mut v = value.into(); let result = f(&mut v); let _: T = v.int...
// 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 core::cmp::PartialEq; use subtle::Choice; use subtle::ConstantTimeEq; use crate::backend; #[cfg(feature = "u64_backend")] pub use backend::u64::field::*; /// A `FieldElement` represents an element of the field /// `2^252 + 27742317777372353535851937790883648493` /// /// The `FieldElement` type is an alias for...
extern crate ocl; #[macro_use] extern crate lazy_static; use ocl::ProQue; use ocl::Buffer; pub mod vector; pub mod matrix; pub mod traits; pub mod util; #[cfg(test)] mod tests; use traits::Parameter; use std::sync::Mutex; use std::collections::HashMap; use std::sync::MutexGuard; use std::ops::Deref; use std::ops::...
// Copyright (c) The Starcoin Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::{ account_config::constants::CORE_CODE_ADDRESS, identifier::Identifier, language_storage::ModuleId, }; use once_cell::sync::Lazy; /// The ModuleId for the TransactionTimeout module pub static G_TRANSACTION_TIMEOU...
extern crate optra; extern crate rdiff; extern crate crdt_fileset; extern crate notify; extern crate eventual; extern crate wamp; extern crate base64; extern crate getopts; extern crate byteorder; #[macro_use] extern crate log; extern crate env_logger; mod file_sync; mod history_store; mod communication; use std::thr...
use crate::{ error::NettuError, shared::{ auth::protect_account_route, usecase::{execute, UseCase}, }, }; use actix_web::{web, HttpRequest, HttpResponse}; use nettu_scheduler_api_structs::remove_user_from_service::*; use nettu_scheduler_domain::{Account, ID}; use nettu_scheduler_infra::Nettu...
// Copyright 2020 WHTCORPS INC. Licensed under Apache-2.0. mod test_analyze; mod test_checksum; mod test_select;
mod stream; use self::stream::Stream; use std::collections::HashMap; pub struct Session { pub accepted: bool, // Handeshake is done pub settings: HashMap<u16, u32>, pub streams: HashMap<u32, Stream> } impl Session { pub fn is_accepted(&self) -> bool { return self.accepted; } pub f...
#[doc = "Register `HFCLKSTATUS` reader"] pub struct R(crate::R<HFCLKSTATUS_SPEC>); impl core::ops::Deref for R { type Target = crate::R<HFCLKSTATUS_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<HFCLKSTATUS_SPEC>> for R { #[inline(always)] fn f...
extern crate futures; extern crate tokio_core; extern crate tokio_line; extern crate tokio_timer; extern crate tokio_io; use futures::future::{Future}; use futures::{Sink, Stream}; use futures::sync::mpsc::{self, UnboundedSender}; use tokio_timer::*; use std::{io, str}; use tokio_core::io::{Codec, EasyBuf,Io}; use tok...
+ (get started|hi|hello) - Hi! What's your name? + * % hi whats your name - Hi <star>. Do you like dogs? <call>await_answer yesno dog-answer</call> + dog answer * <get openended-answer> == yes => <set dogvar=yes> Cool. Do you like cats? <call>await_answer yesno cat-answer</call> * <get openended-answer> == no => <se...
#![allow(dead_code)] use std::path::Path; use std::collections::HashMap; use freetype; use sdl2; use sdl2::surface::Surface; use sdl2::render::Texture; use sdl2::rect::Rect; use string_utils::{is_line_ending}; const SOURCE_CODE_PRO: &'static [u8] = include_bytes!("source_code_pro/SourceCodePro-Regular.ttf"); stru...
use clap::Parser; use super::*; #[allow(dead_code)] #[derive(Parser)] #[clap(version = "1.5", author = "Tokera Pty Ltd <info@tokera.com>")] pub struct OptsToken { #[clap(subcommand)] pub action: TokenAction, } #[derive(Parser)] pub enum TokenAction { /// Generate a token with normal permissions from the ...
use perl_xs::{ SV, AV, IV }; xs! { package XSTest::Array; sub test_store(ctx, rv: SV, sv: SV) { if let Some(av) = rv.deref_av() { av.store(0, sv); } } sub test_fetch(ctx, av: AV) { match av.fetch::<SV>(0) { Some(ref sv) if sv.ok() => 1 as IV, ...
use super::*; use std::*; #[derive(Copy, Clone)] pub struct SockAddr { storage: libc::sockaddr_storage, len: usize, } // TODO: add more fields impl fmt::Debug for SockAddr { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("SockAddr") .field( "f...
/* * @lc app=leetcode id=44 lang=rust * * [44] Wildcard Matching * * https://leetcode.com/problems/wildcard-matching/description/ * * algorithms * Hard (23.67%) * Total Accepted: 206.3K * Total Submissions: 871.7K * Testcase Example: '"aa"\n"a"' * * Given an input string (s) and a pattern (p), implemen...
// https://leetcode.com/problems/maximum-white-tiles-covered-by-a-carpet/ // You are given a 2D integer array tiles where tiles[i] = [li, ri] represents that every tile j in // the range li <= j <= ri is colored white. // You are also given an integer carpetLen, the length of a single carpet that can be placed anywher...
// per-process data for the trap handling code in trampoline.S. // sits in a page by itself just under the trampoline page in the // user page table. not specially mapped in the kernel page table. // the sscratch register points here. // uservec in trampoline.S saves user registers in the trapframe, // then initializes...
#[derive(PartialEq, Debug)] struct Coords { x: i32, y: i32, } #[test] fn isomorphism_example() { let pair_to_coords = |pair: (i32, i32)| Coords { x: pair.0, y: pair.1, }; let coords_to_pair = |coords: Coords| (coords.x, coords.y); assert_eq!(pair_to_coords((1, 2)), Coords { x: 1...
use std::error::Error; use std::fmt; use url::ParseError; use url::Url; use ModuleResolutionError::*; /// Resolves module using this algorithm: /// https://html.spec.whatwg.org/multipage/webappapis.html#resolve-a-module-specifier pub fn resolve_import( specifier: &str, base: &str, ) -> Result<Url, ModuleResolution...
#[test] fn test_mkdir() { use rustix::fs::{access, mkdir, rmdir, stat, unlink, Access, FileType, Mode}; let tmp = tempfile::tempdir().unwrap(); mkdir(tmp.path().join("foo"), Mode::RWXU).unwrap(); let stat = stat(tmp.path().join("foo")).unwrap(); assert_eq!(FileType::from_raw_mode(stat.st_mode), Fi...
//! # How to use serde with rust-protobuf //! //! rust-protobuf 3 no longer directly supports serde. //! //! Practically, serde is needed mostly to be able to serialize and deserialize JSON, //! and **rust-protobuf supports JSON directly**, and more correctly according to //! official protobuf to JSON mapping. For that...
use amethyst::{ core::Transform, ecs::{Component, DenseVecStorage}, }; #[derive(Default)] pub struct TwoDimVector<T> { pub x: T, pub y: T, } #[derive(Component)] #[storage(DenseVecStorage)] pub struct TwoDimObject { pub size: TwoDimVector<f32>, pub position: TwoDimVector<f32>, pub hit_box_...
// This file is part of Substrate. // Copyright (C) Parity Technologies (UK) Ltd. // SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Softwa...
// 1 - Example to show that ownership // applies to more than memory management. // // In this case, the socket is closed // when it's owner goes out of scope // // This also works with Mutex<T>, Rc<T> and Files // use std::thread; // use std::time::Duration; // use std::net::TcpListener; // // fn open_socket_for_fiv...
fn main() { protobuf_codegen::protoc_gen_rust::protoc_gen_rust_main(); }
use rayon::prelude::*; fn check<I>(iter: I) where I: ParallelIterator + Clone, I::Item: std::fmt::Debug + PartialEq, { let a: Vec<_> = iter.clone().collect(); let b: Vec<_> = iter.collect(); assert_eq!(a, b); } fn check_count<I>(iter: I) where I: ParallelIterator + Clone, { assert_eq!(iter...
use super::module::Module; use super::object::*; use super::state::*; use crate::bytecode::block::BasicBlock; use crate::bytecode::instructions::Instruction; use crate::util::arc::Arc; use crate::util::deref_ptr::DerefPointer; use crate::util::ptr::*; pub struct CatchEntry { pub register: u16, pub jump_to: u16...
//@revisions: stack tree //@[tree]compile-flags: -Zmiri-tree-borrows fn main() { let mut x = 0; let y: *const i32 = &x; x = 1; // this invalidates y by reactivating the lowermost uniq borrow for this local assert_eq!(unsafe { *y }, 1); //~[stack]^ ERROR: /read access .* tag does not exist in the b...
extern crate glob; use std::path::Path; #[cfg(feature = "runtime")] fn main() { use std::env; if cfg!(feature = "static") { panic!("`runtime` and `static` features can't be combined"); } fn copy(src: &str, dst: &Path) { use std::fs::File; use std::io::{Read, Write}; let ...
use nimiq_genesis_builder::GenesisBuilder; use nimiq_keys::{Address, KeyPair as SchnorrKeyPair, SecureGenerate}; use nimiq_primitives::{coin::Coin, networks::NetworkId, policy::Policy}; use nimiq_serde::Serialize; use nimiq_transaction::{SignatureProof, Transaction}; use rand::{CryptoRng, Rng}; #[derive(Clone)] pub st...
fn main() { println!("Hello, world!"); let y = 6; another_function(5, 6); } fn another_function(x: i32, y: i32) { println!("Another function. X is {}, y is {}", x, y); }
use std::{os, float}; fn main() { let nums = os::args(); if nums.len() == 1 { println("No arguments provided!"); return } let mut count = 0.0; let sum : float = nums.iter().skip(1).fold(0.0, |s, n| { match float::from_str(*n) { Some(number) => { count += 1.0; s + number }, None => { ...
use std::convert::{ TryFrom, TryInto, }; use crate::{ seed::Seedable, state::State, }; fn fmix64(mut k: u64) -> u64 { k ^= k >> 33; k = k.wrapping_mul(0xff51afd7ed558ccd); k ^= k >> 33; k = k.wrapping_mul(0xc4ceb9fe1a85ec53); k ^= k >> 33; k } /// Implementation of [MurmurHash...
use std::result; enum ConcreteError { Foo, Bar } type Result<T> = result::Result<T, ConcreteError>; type Name = String; type Age = i32; fn main() { let name: Name = "a name".to_string(); println!("{}", name); let age1: i32 = 20; let age2: Age = 20; // they are the same, just aliases ...
use std::net::TcpListener; use hello2::ThreadPool; /* fn making_new_threads_without_any_limit() { let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); for stream in listener.incoming() { let stream = stream.unwrap(); thread::spawn(|| { hello::handle_connection(stream); ...
// planeshift/src/backends/lib.rs // // Copyright © 2018 The Pathfinder Project Developers. // // 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/MIT>, at your // option. This file may n...
// Copyright 2020 Datafuse Labs. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to ...
use crate::pool::{AccountSeqNumberClient, UnverifiedUserTransaction}; use anyhow::Result; use parking_lot::RwLock; use starcoin_executor::VMMetrics; use starcoin_state_api::AccountStateReader; use starcoin_statedb::ChainStateDB; use starcoin_storage::Store; use starcoin_types::{ account_address::AccountAddress, ...
//! Direct, unsafe bindings for Linux [`perf_event_open`][man] and friends. //! //! Linux's `perf_event_open` system call provides access to the processor's //! performance measurement counters (things like instructions retired, cache //! misses, and so on), kernel counters (context switches, page faults), and //! many...
use bgzf_rust_reader::BgzfReader; use std::str; #[test] fn test_total_uncompressed_length() { let reader = BgzfReader::new(String::from("bgzf_test.bgz")).unwrap(); let test_content = "This is just a bgzf test,lets see how it reacts. :). I think it will work fine, but who knows this is still a software. Unless you ...
use std::fmt; pub trait Location2D { fn get_location(self) -> Real2D; fn set_location(&mut self, loc: Real2D); } #[derive(Clone, Default, Debug, Copy)] pub struct Real2D { pub x: f64, pub y: f64, } impl fmt::Display for Real2D { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write...
use wasm_bindgen::prelude::*; #[wasm_bindgen] extern "C" { #[derive(Debug)] pub type Document; #[wasm_bindgen(method)] pub fn write(this: &Document, content: String); }
use crate::state::{Entity, State}; use crate::events::{BuildHandler, Event, EventHandler, Propagation}; use crate::widgets::{Button, ControlKnob, SliderEvent, Textbox, TextboxEvent, Label}; use crate::state::style::*; // const VALUE_SLIDER_STYLE: &str = r#" // slider // { // background-color: #2E2E...
// Make sure that creating a raw ptr next to a shared ref works // but the shared ref still gets invalidated when the raw ptr is used for writing. fn main() { unsafe { use std::mem; let x = &mut 0; let y1: &i32 = mem::transmute(&*x); // launder lifetimes let y2 = x as *mut _; ...
use args_parser::Args; /// Changes names of the files based on the user's requirements /// and also returns touple with original name and changed name pub fn process_name( entry: std::path::PathBuf, args: &Args, ) -> Result<(std::path::PathBuf, std::path::PathBuf), ()> { use log::info; use std::path::PathBuf; use...
extern crate num_rational; #[macro_use] extern crate nom; use num_rational::Rational32; use nom::branch::alt; use nom::bytes::complete::tag; use nom::character::complete::digit1; use nom::character::complete::multispace0; use nom::character::complete::multispace1; use nom::character::complete::not_line_ending; use no...
fn main(){ let mut v1 = vec![1, 2, 3, 4, 5]; let v2 = vec![0; 5]; println!("{:?}", v1); println!("{:?}", v2); v1[1] = 0; println!("{:?}", v1); for element in &v1{ println!("{}", element); } }
mod full { use std::{ env, fs::File, path::{Path, PathBuf}, process::{Command, Stdio}, }; fn test_full(crate_name: &str, old_version: &str, new_version: &str, expected_result: bool) { let prog = format!( r#" # wait for the actual output /^version ...
use std::io; use std::io::Write; use std::error::Error; use events; pub struct StdioCollector { _use_stderr: bool } unsafe impl Sync for StdioCollector {} impl StdioCollector { pub fn new() -> StdioCollector { StdioCollector { _use_stderr: false } } } impl super::Collector fo...
use qd_core::*; use qd_nat::*; use qd_vect::{vect, Vect}; use std::ops::Add; fn zip_sum<T: Clone + Add<T, Output = T>, N: Nat>( first: Vect<T, N>, second: Vect<T, N>, ) -> Vect<T, N> { let mut v1 = first; let v2 = second.freeze(); v1.freeze_mut() .iter_mut() .zip(v2.iter()) ...
use ray_tracing::HitInfo; use vector::Vector; /// A Ray in 3D-Space #[derive(Clone, Copy, Debug)] pub struct Ray { /// The starting Point of the Ray pub start: Vector, /// The direction where the Ray is headed /// /// should be normalized, but is not guaranteed to be pub direction: Vector, } impl Ray { /// cre...
#![feature(box_syntax)] use std::error::Error; /// Main Program fn main() -> Result<(), Box<dyn Error>> { let args = compiler::cli::Cli::init(); let config = compiler::config::Config::load(&args)?; compiler::Compiler::compile(config) }
#[doc = "Register `TTS` reader"] pub struct R(crate::R<TTS_SPEC>); impl core::ops::Deref for R { type Target = crate::R<TTS_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<TTS_SPEC>> for R { #[inline(always)] fn from(reader: crate::R<TTS_SPEC>) ...
// Copyright 2018 Grove Enterprises LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed ...
use imperative_rs::InstructionSet; #[derive(InstructionSet, PartialEq, Debug)] enum Star { #[opcode = "0b0*0*000y_xxxxxxxx"] Bin { x: u8, y: bool }, #[opcode = "0xf*_xy"] Hex { x: u8, y: u8 }, } #[test] fn encoding_star_opcodes() { { let mem = [ 0b00000001, 0b11111111, 0b000100...
extern crate time_ as time; #[cfg(feature = "decimal")] use std::str::FromStr; use sqlx::mysql::MySql; use sqlx::{Executor, Row}; use sqlx_test::{new, test_type}; test_type!(bool(MySql, "false" == false, "true" == true)); test_type!(u8(MySql, "CAST(253 AS UNSIGNED)" == 253_u8)); test_type!(i8(MySql, "5" == 5_i8, "0...
pub mod expr; pub mod read;
// This file is part of Substrate. // Copyright (C) Parity Technologies (UK) Ltd. // SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Softwa...
use rand::distributions::{Distribution, WeightedIndex}; use rand::Rng; use tcod::colors; use uuid::{Builder, Bytes, Uuid, Variant, Version}; use vector2d::Vector2D; use crate::component::{Mortality, Stats, AI}; use crate::map::Map; use crate::object::Object; use crate::traits::Generates; use super::room::RoomView; c...
// Copyright (c) 2019 Weird Constructor <weirdconstructor@gmail.com> // This is a part of WeirdGoban. See README.md and COPYING for details. extern crate hyper; extern crate futures; extern crate tokio_process; extern crate tokio; extern crate serde; extern crate serde_json; //use std::time::Duration; //use futures::...
use super::Cpu; use super::InstrResult; pub fn resolve(opcode: u8) -> Option<fn(&mut Cpu) -> Box<InstrResult>> { match opcode { 0x69 => Some(super::adc::imm), 0x65 => Some(super::adc::zero_page), 0x75 => Some(super::adc::zero_page_x), 0x6d => Some(super::adc::abs), 0x7d => S...
#![allow( dead_code, unused_variables, unused_imports, unused_must_use, non_shorthand_field_patterns, unreachable_patterns )] #[macro_use] extern crate lazy_static; mod err; pub mod lexer { pub mod lexer; pub mod token; } pub mod eval { pub mod builtins; pub mod environment; ...
// For lock-step multiplayer pub struct Step { pub forward: bool, pub backward: bool, pub left: bool, pub right: bool, pub rotation: f32 }
#[macro_use] extern crate lambda_runtime as lambda; #[macro_use] extern crate serde_derive; #[macro_use] extern crate log; extern crate simple_logger; use lambda::error::HandlerError; use std::error::Error; #[derive(Deserialize, Clone)] struct CustomEvent { x: i64, y: i64, } #[derive(Serialize, Clone)] stru...
mod prefixop; mod integral; mod id; mod group; mod boolean; mod string; mod letbinding; mod block; mod lambda; pub(crate) use prefixop::parse_prefix_op; pub(crate) use integral::parse_integral; pub(crate) use id::parse_id; pub(crate) use group::parse_group; pub(crate) use boolean::parse_bool; pub(crate) use string::pa...
mod errno; mod strings; use self::errno::Errno; use std::mem::uninitialized; use std::ptr::null_mut; pub use libc::{c_void, c_int}; use libc::{pthread_t, pthread_create}; #[cfg(target_os = "solaris")] use libc::{key_t, size_t, c_short, c_ushort}; #[cfg(target_os = "solaris")] const IPC_CREAT: c_int = 0o1000; #[cfg(ta...
//! MSVC C++ Demangling Tests //! We use msvc_demangler under the hood which runs its own test suite. //! Tests here make it easier to detect regressions. #![cfg(feature = "msvc")] #[macro_use] mod utils; use symbolic_common::Language; use symbolic_demangle::DemangleOptions; #[test] fn test_msvc_demangle_without_ar...
#[derive(Debug)] struct Mem { x: i32, cycle_count: i32, } struct CPU<F> where F: FnMut(&Mem) -> () { mem: Mem, cycle_listener: F, } impl<F> CPU<F> where F: FnMut(&Mem) -> () { fn new(cycle_listener: F) -> CPU<F> { CPU { mem: Mem { x: 1, c...
use std::collections::{HashMap, HashSet, VecDeque}; use std::error::Error; use std::fs::File; use std::io::{BufRead, BufReader}; use std::vec::Vec; fn collect_matching_words(mut words: Vec<String>) -> HashMap<String, Vec<String>> { let mut collected_words = HashMap::new(); for word in words.drain(..) { ...
use crate::{ commands::GlobalOpts, utils::{git, user}, }; use anyhow::{bail, Result}; use colored::Colorize; use git2::{Cred, Remote, Repository}; use log::{debug, info}; use std::{io, io::Write}; use structopt::StructOpt; #[derive(StructOpt, Debug)] pub struct Sync {} impl Sync { #[allow(clippy::unused_s...
fn main(){ let mut v = vec![1,2,3,4,5]; let len = v.len(); for i in 0..len/2{ let temp = v[i]; v[i] = v[len-i-1]; v[len-i-1] = temp; } println!("{:?}",v) }
use std::collections::HashMap; use std::hash::Hash; pub trait Unique { type Identifier: Eq + Hash; fn get_unique_identifier(&self) -> Self::Identifier; } pub struct DataStore<T: Unique> { data: HashMap<T::Identifier, T>, } impl<T: Unique> DataStore<T> { pub fn new() -> DataStore<T> { DataSto...
#[macro_use] extern crate cagra; #[test] fn test_graph_macro() { let _g = graph!(f64, { let x = 1.0; let y = 3.0; let z = x + y + 2.0 * x * y; }); }
use super::{ Value, Scope, }; #[derive(Debug, PartialEq, Eq, Clone)] pub struct Match { pub value: Value, pub matched: bool, pub is_lr: bool, pub start: Scope, pub end: Scope } impl Match { // New top level scope, no vars pub fn fail(scope: Scope) -> Self { Match { value: Value::None, ...
use std::fs::File; use std::io::BufReader; use std::io::BufRead; use nalgebra::{Vec2, Vec3, DMat}; use nalgebra::cross; use nalgebra::Norm; use nalgebra::new_identity; use vbuffer::VBuffer; fn one_mul(u: &Vec3<f32>, v: &Vec3<f32>) -> f32 { (u.x * v.x) + (u.y * v.y) + (u.z * v.z) } pub fn view_port(x: f32, y: f32, ...
use crate::default_log_pre; use crate::facades::categories; use crate::utils::binary_read_helper::binary_read_i64; use crate::{ReqContext, ResponseResult}; use function_name::named; use tracing::info; #[named] pub async fn get_category_metadata_list(req: ReqContext) -> ResponseResult { let slave_conn = req.db_conn...
use std::fmt; use std::num::NonZeroU32; use std::ops::Range; use std::u32; use string_interner::{StringInterner, Symbol}; #[derive(Copy, Clone, PartialEq, Eq, Ord, PartialOrd)] pub struct IdentifierIndex(NonZeroU32); macro_rules! identifiers { { $($name:ident = $str:expr,)* } => { const ALL_IDENTIFIERS: [...
#[derive(Debug)] struct Entity { id: u32, } impl Entity { fn new(id: u32) -> Entity { Entity { id: id } } } impl Drop for Entity { fn drop(&mut self) { println!("Dropping {}", self.id); } } fn main() { let three = outer(); println!("Leaving main"); // Dropping three } fn ...
use std::os::raw::c_char; use std::ffi::{CString, CStr}; extern { fn puts(s: *const c_char); fn strlen(s: *const c_char) -> usize; } fn main() { let s = "Hello, Rust World"; let s_null_term = CString::new(s).unwrap(); unsafe { puts(s_null_term.as_ptr()); } let n = unsafe { ...
use eventsourcing::{eventstore::MemoryEventStore, prelude::*, Result}; use eventsourcing_module::employee_event::model::*; use eventsourcing_module::employee_command::model::*; use eventsourcing_module::employee_state::model::*; use env_set_up::model::*; pub struct Employees; impl Aggregate for Employees { type E...
/* * Ory Kratos API * * Documentation for all public and administrative Ory Kratos APIs. Public and administrative APIs are exposed on different ports. Public APIs can face the public internet without any protection while administrative APIs should never be exposed without prior authorization. To protect the adminis...