text
stringlengths
8
4.13M
pub fn redirect_body(target: &str) -> String { format!(r#"<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <title>Permanent Redirect</title> <meta http-equiv="refresh" content="0; url={}"> </head> <body> <p> The document has been moved ...
use std::collections::HashMap; use std::fs::read_to_string; fn main() { test("src/twelve-test1.txt"); test("src/twelve-test2.txt"); test("src/twelve-test3.txt"); test("src/twelve.txt"); } fn visit<'a, F, T>(routes: &'a HashMap<&'a str, Vec<&'a str>>, f: F) -> Vec<Vec<&'a str>> where F: Fn(&str, &[...
// Copyright 2019 Conflux Foundation. All rights reserved. // Conflux is free software and distributed under GNU General Public License. // See http://www.gnu.org/licenses/ #[macro_use] extern crate error_chain; #[macro_use] extern crate log; mod error; mod statedb_ext; #[cfg(test)] mod tests; pub use self::{ e...
use crate::prelude::*; #[system] #[read_component(Point)] #[read_component(Render)] #[read_component(FieldOfView)] #[read_component(Player)] pub fn entity_render(ecs: &SubWorld, #[resource] camera: &Camera) { let mut renderables = <(&Point, &Render)>::query(); let mut fov = <&FieldOfView>::query().filter(compo...
use std::io::stdin; use std::io::BufRead; struct Point(u32, u32); struct Instruction { action : String, from : Point, to : Point } fn parse_point(s : &str) -> Result<Point, String> { let parts = s.split(',').collect::<Vec<&str>>(); if parts.len() != 2 { return Err("expected format 'num1,num2'".to_str...
pub use super::parser_data::*; use std::cell::Cell; use super::radix10::*; use super::drop_row_request::DropRowRequest; use super::col_row_position_info::ColRowPositionInfo; ///Allows user to see position info from defined TagHandler function pub enum UserDataMode<'a> { RowItem(&'a StateInfo<'a>), XmlTag() } ...
use downcast_rs::DowncastSync; use crate::core::fmt; use crate::alloc::sync::Arc; pub trait MutexDataSync: DowncastSync { } impl_downcast!(sync MutexDataSync); pub struct MutexDataContainerSync(Option<Arc<dyn MutexDataSync>>); impl MutexDataContainerSync { pub const fn empty() -> Self { MutexDataConta...
// Generate a Content Security Policy based on simple to define JSON config. // This library will generate a CSP and return the correct header required to // run the CSP in either enforcement mode or report-only mode. // // Note: Enforcement mode will block content and requests so please test your // CSP setup first in...
extern crate chrono; use chrono::duration::Duration; use chrono::offset::TimeZone; use chrono::datetime::DateTime; pub const GIGASECOND: i64 = 1_000_000_000; pub fn after<Tz: TimeZone>(date: DateTime<Tz>) -> DateTime<Tz> { let datetime = date.checked_add(Duration::seconds(GIGASECOND)).unwrap(); DateTime::fro...
pub trait IIntersect<Other, Result> { fn intersect(&mut self, other: &Other) -> Option<Result>; }
//! This a library containing functions, structs, enums, traits and methods for common little problems while solving the Advent of Code. //! //! This library has a trait for converting Iterators, //! a struct and an enum for keeping track of a Position and a Direction, //! a trait for calculating the `manhatten-distanc...
//! The client implementation for the reqwest HTTP client, which is async by //! default. use super::{BaseHttpClient, Form, Headers, HttpError, HttpResult, Query}; use std::convert::TryInto; use maybe_async::async_impl; use reqwest::{Method, RequestBuilder, StatusCode}; use rspotify_model::ApiError; use serde_json::...
macro_rules! tags { { // Permit arbitrary meta items, which include documentation. $( #[$enum_attr:meta] )* $vis:vis enum $name:ident($ty:tt) $(unknown($unknown_doc:literal))* { // Each of the `Name = Val,` permitting documentation. $($(#[$ident_attr:meta])* $tag:iden...
pub struct Solution; impl Solution { pub fn my_atoi(str: String) -> i32 { if str.is_empty() { return 0; } let mut first = false; let mut neg = false; let mut ans: i32 = 0; for c in str.chars() { if first { match c { ...
use std::collections::LinkedList; use piston_window::{Context, G2d}; use piston_window::types::Color; use draw::draw_block; /// Snake color. (green) const SNAKE_COLOR : Color = [0.0, 0.80, 0.0, 1.0]; /// Direction of the snake. pub enum Direction { Up, Down, Left, Right, } impl Direction { pub fn opposit...
//! This module provides a feature to render `i` tags. use cursive::{theme::Effect, utils::markup::StyledString, views::TextView, View}; use crate::core::{dom::element::Element, layout::LayoutBox}; pub fn render(lbox: &LayoutBox, _element: &Element) -> Box<dyn View> { Box::new(TextView::new(StyledString::styled(...
use std::sync::Mutex; lazy_static::lazy_static!{ static ref RG: Mutex<RandGen> = Mutex::new(RandGen::new(1688165)); } pub fn rand(max: usize ) -> usize { RG.lock().unwrap().next_v(max) } pub struct RandGen { curr: usize, mul: usize, inc: usize, modulo: usize, } impl RandGen { pub fn ne...
#![allow(dead_code)] use std::borrow::BorrowMut; use std::collections::HashMap; use std::fmt; use std::fmt::Error; use std::io::{self, BufRead}; use std::mem; use std::str::FromStr; use std::vec; use std::vec::Vec; fn _mem() { let v = "".to_string(); println!("{:?} : {}", v, mem::size_of_val(&v)); } #[derive...
#[test] #[should_panic] fn test_templates_parsed_with_line_numbers_renders_them_in_errors() { panic!("Implementation specific: lax errors"); } #[test] #[should_panic] fn test_standard_error() { panic!("Implementation specific: error types"); } #[test] #[should_panic] fn test_syntax() { panic!("Implementat...
// Copyright 2017-2018 Maskerad Developers // // Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or // http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or // http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or distributed except accord...
#![feature(zero_one)] extern crate rpbrt; use std::rc::Rc; use std::num::One; use std::f32; use rpbrt::*; #[test] fn cylinder_test() { let xform = Rc::new(Transform::one()); let cylinder = Rc::new(Cylinder::new( &xform, &xform, false, 1.0, 1.0, -1.0, &Degree::new(360.0))); asser...
pub const EXIF_DATA_PREFIX: &[u8] = b"Exif\0\0";
#[allow(unused_imports)] use serde_json::Value; #[derive(Debug, Serialize, Deserialize)] pub struct AdsProviderSearch { #[serde(rename = "objects")] pub objects: Option<Vec <crate::models::AdsProviderSearchObject>>, /// Continue returning results from previous call using this token (token should come from ...
use crate::common::*; #[derive(StructOpt)] pub(crate) struct Arguments { #[structopt(flatten)] options: Options, #[structopt(subcommand)] subcommand: Subcommand, } impl Arguments { #[throws] pub(crate) fn run(self) { self.subcommand.run(self.options)?; } }
use futures::{ Async, AsyncSink, Future, Poll, Sink, Stream }; use futures::future::{ Shared }; use futures::stream::{ SplitSink, SplitStream }; use futures::sync::{ mpsc, oneshot }; use lsp_rs::{ ClientNotification, IncomingMessage, IncomingServerMessage, Me...
pub mod vector2; pub mod triangle;
pub struct Roman { n: u32, r: String, } impl Roman { pub fn from(n: u32) -> Roman { Roman { n: n, r: Roman::to_roman(n), } } #[warn(dead_code)] fn to_arab(&self) -> u32 { self.n } fn to_roman(mut n: u32) -> String { println!("{:...
// Copyright 2020-2021 IOTA Stiftung // SPDX-License-Identifier: Apache-2.0 mod alias; mod ed25519; mod nft; use iota_types::block::{address::Address, Error}; const ED25519_ADDRESS_INVALID: &str = "0x52fdfc072182654f163f5f0f9a621d729566c74d10037c4d7bbb0407d1e2c64x"; #[test] fn invalid_bech32() { let address = A...
#[macro_export] macro_rules! info { ($($arg:tt)*) => {{ extern crate chrono; use chrono::prelude::{Local, DateTime}; let now: DateTime<Local> = Local::now(); std::println!("[INFO ] [{}] [{}:{}] - {}", now.format("%Y-%m-%d %H:%M:%S").to_string(), std::file!(), std::line!(), std::form...
use std::sync::Mutex; use slog::{debug, error, info, trace, warn}; fn main() { let drain = slog_json::Json::default(std::io::stdout()); let drain = slog::Fuse(Mutex::new(drain)); let drain = slog::Fuse(slog_async::Async::default(drain)); let logger = slog::Logger::root(drain, slog::o!("process" => "lo...
use constants::{HIRAGANA_START, KATAKANA_START, LONG_VOWELS, TO_ROMAJI}; use utils::is_char_long_dash::*; use utils::is_char_slash_dot::*; use utils::is_char_katakana::*; use std; /// Convert [Katakana](https://en.wikipedia.org/wiki/Katakana) to [Hiragana](https://en.wikipedia.org/wiki/Hiragana) /// /// Passes through...
#[cfg(test)] mod clickhouse_bench; #[cfg(test)] mod clickhouse_end_to_end; #[cfg(test)] mod query_ir;
extern crate wasm_bindgen; #[allow(unused_imports)] use wasm_bindgen::prelude::*; #[wasm_bindgen] #[derive(Clone, Debug)] pub struct Mat3 { pub(crate) data: [f32; 9], } #[wasm_bindgen] impl Mat3 { #[wasm_bindgen(constructor)] pub fn new( n0: f32, n1: f32, n2: f32, n3: f32, ...
use crate::io::Encode; use crate::protocol::Capabilities; // https://dev.mysql.com/doc/internals/en/com-ping.html #[derive(Debug)] pub(crate) struct Ping; impl Encode<'_, Capabilities> for Ping { fn encode_with(&self, buf: &mut Vec<u8>, _: Capabilities) { buf.push(0x0e); // COM_PING } }
use crate::chess_structs::{Board, Color}; pub fn eval(board: &Board) -> i32 { let score: i32 = board.squares.iter() .flat_map(|squares| squares.iter() .map(|square| match square { None => 0, Some(piece) => match piece.color { Color::White =>...
use crate::{String, ToString}; /// Represents a decimal digit. #[repr(transparent)] pub struct DecDigit(pub u8); /// Represents an hex digit. #[repr(transparent)] pub struct HexDigit(pub u8); impl ToString for HexDigit { fn to_string(&self) -> String { let value = self.0; debug_assert!(value < 16...
use core::{ fmt, hash, }; use iota_streams_core::prelude::{Vec, hex,}; /// Variable-size array of bytes, the size is not known at compile time and is encoded in trinary representation. #[derive(PartialEq, Eq, Clone, Debug, Default)] pub struct Bytes(pub Vec<u8>); impl Bytes { pub fn new() -> Self { ...
use machine::state::State; pub fn flotu(state: &mut State, x: u8, y: u8, z: u8) { // Load operand let op1: u64 = state.gpr[z].into(); // Execute let mut res = op1 as f64; match y { // FIXME this might be incorrect 1 => unimplemented!(), 2 => unimplemented!(), 3 => unimple...
use std::collections::HashMap; use crate::screening::ScreeningSchedule; pub struct Schedules { pub screenings: HashMap<u32, ScreeningSchedule>, } impl Schedules { pub fn with(&mut self, id: u32) -> Option<&mut ScreeningSchedule> { self.screenings.get_mut(&id) } pub fn new() -> Self { ...
use std::fs::File; use std::io::{self, BufRead}; use std::collections::HashSet; fn part1(drifts: &[i32]) -> i32 { drifts.iter().sum() } fn part2(drifts: &[i32]) -> i32 { let mut seen = HashSet::new(); drifts.iter().cycle() .scan(0, |acc, x| { *acc = *acc + x; Some(*acc) ...
use mkit::{ cbor::{self, Cbor, FromCbor, IntoCbor}, db, Cborize, }; use std::{borrow::Borrow, convert::TryFrom, fmt, io}; use crate::{reader::Reader, util, vlog, Error, Result}; const ENTRY_VER1: u32 = 0x0001; #[derive(Clone, Debug, Eq, PartialEq, Cborize)] pub enum Entry<K, V, D> { MM { key: K,...
pub mod args; pub mod png; pub mod chunk; pub mod chunk_type; pub mod commands;
pub use self::allow_tearing::AllowTearing; mod allow_tearing; pub unsafe trait Feature { const FLAG: u32; type Structure: Sized; type Result; fn get_result(hr: i32, structure: &Self::Structure) -> Self::Result; }
token! { /// A content coding, used in the `Accept-Encoding` and `Content-Encoding` headers. ContentCoding => { /// The Brotli coding, as specified in [RFC7932]. /// /// [RFC7932]: https://tools.ietf.org/html/rfc7932 BROTLI => "br" => [], /// The Gzip coding, as specified...
extern crate iceccd; use iceccd::*; extern crate clap; use clap::{Arg, App}; extern crate get_if_addrs; extern crate resolve; extern crate local_socket; use local_socket::*; use std::thread; use std::sync::Mutex; use std::time::Duration; extern crate crossbeam; fn socket_thread(shared_chan: & Mutex<MsgChannel>, ...
use std::{ fs::File, io::{self, BufRead, BufReader}, }; fn main() -> io::Result<()> { let file = File::open("./input.txt")?; let reader = BufReader::new(file); let lines: Vec<String> = reader .lines() .map(|line| line.expect("Couldn't read line")) .collect(); let result...
extern crate buffer; #[macro_use] extern crate common; extern crate hexdump; extern crate itertools; extern crate libc; #[macro_use] extern crate log; extern crate mio; extern crate net; extern crate net2; extern crate rand; use buffer::Buffer; use buffer::BufferRef; use buffer::with_buffer; use hexdump::hexdump_iter;...
#![allow(unused_imports)] use itertools::Itertools; use proconio::{fastout, input, marker::*}; #[fastout] fn main() { input! { n: usize, aa: [usize; n] }; let s = aa .into_iter() .enumerate() .sorted_by_key(|&(_, a)| a) .map(|(i, _)| (i + 1).to_string()) ...
use std::cmp; use std::fmt; #[cfg(feature = "server")] use std::future::Future; use std::io::{self, IoSlice}; use std::marker::Unpin; use std::mem::MaybeUninit; use crate::rt::{Read, ReadBuf, Write}; use bytes::{Buf, BufMut, Bytes, BytesMut}; use tracing::{debug, trace}; use super::{Http1Transaction, ParseContext, Pa...
struct Map<T> { size: [u32; 2], map: Vec<T>, } impl Map<T> { pub(crate) fn new<T>(size: [u32; 2]) -> Map<T> { Map { size, map: vec![], } } pub(crate) fn set_pos(&mut self, pos: [u32; 2], value: T) { self.map[get_index(pos)] = value; } pub(cra...
use crate::diagram::{SequenceDiagram, TimelineEvent}; use crate::rendering::layout::{string_width, GridSize, ReservedWidth}; use crate::rendering::renderer::{RectParams, Renderer, LIGHT_PURPLE, MEDIUM_PURPLE}; use nalgebra::Point2; use std::cell::RefCell; use std::collections::HashSet; use std::rc::Rc; #[derive(Debug...
use std::os::raw::c_int; extern "C" { pub fn cclinkstampdep() -> c_int; } fn main() { println!("bin rdep: {}", rdep::rdep()); println!("cclinkstampdep: {}", unsafe { cclinkstampdep() }); }
use iron::{Handler, status, IronResult, Response, Request}; use bodyparser; use iron::prelude::*; use router::Router; use clients::hipchat::installation::Installation; use handlers::hipchat::HC_DATABASE; create_handler!(PostInstallation, |_: &PostInstallation, req: &mut Request| { let installatio...
use config::{FileFormat, Value}; use ipnet::{AddrParseError, Ipv4Net}; use iprange::IpRange; use std::collections::HashMap; /// CDN configuration. pub struct Config { /// IPs which may purge the cache (empty = deny all) pub acl_fastlypurge: IpRange<Ipv4Net>, /// IPs which may make requests (empty = allow a...
use hyper::Client; use hyper::client::Body; use std::io::Read; use std::collections::BTreeMap; use serde::de::DeserializeOwned; use serde_json::{to_vec, from_slice, from_reader}; use errors::{Result, HueError}; use ::hue::*; use ::json::*; /// Attempts to discover bridges using `https://www.meethue.com/api/nupnp` #...
//! Capture and report statistics for optimisation use std::{cmp::max, fmt::Display, time::Duration}; use indexmap::IndexMap; #[derive(Default, Debug)] pub struct Timings { timings: IndexMap<String, Duration>, } impl Timings { pub fn record<T: AsRef<str>>(&mut self, name: T, elapsed: Duration) { sel...
use crate::instructions::base::bytecode_reader::BytecodeReader; use crate::instructions::base::instruction::{Instruction, NoOperandsInstruction}; use crate::instructions::check_index; use crate::runtime::frame::Frame; pub struct AAStore(NoOperandsInstruction); impl AAStore { #[inline] pub fn new() -> AAStore ...
use crate::{Address, Amount}; use svm_sdk_std::{ensure, panic, Option}; /// Primitive value #[allow(missing_docs)] #[cfg_attr(any(test, feature = "debug"), derive(core::fmt::Debug))] #[derive(PartialEq)] pub enum Primitive { None, Unit, Bool(bool), Address(Address), Amount(Amount), I8(i8), ...
use std::{ fs, path::{Path, PathBuf}, }; use heck::{CamelCase, SnakeCase}; use crate::{ cmd, command::Verbosity, emit, errors::{CliError, Result}, utils::{print_status_in, Status}, }; const TEMPLATE_REPO_URL: &str = "https://github.com/oasislabs/template"; const TEMPLATE_TGZ_BYTES: &[u8] ...
use crate::core::definition; use crate::core::intermediary; use crate::core::error; pub struct DataContext<'a> { pub ident: syn::Ident, pub generics_ref: &'a syn::Generics, pub field_ident_vec: Vec<syn::Ident>, pub field_type_vec: Vec<proc_macro2::TokenStream>, } // Compiler needs to know that the Er...
/* * @lc app=leetcode id=307 lang=rust * * [307] Range Sum Query - Mutable * * https://leetcode.com/problems/range-sum-query-mutable/description/ * * algorithms * Medium (31.67%) * Likes: 987 * Dislikes: 70 * Total Accepted: 90.7K * Total Submissions: 285K * Testcase Example: '["NumArray","sumRange"...
use warp::{http::StatusCode, Filter, Rejection, Reply}; use serde::{Serialize, Deserialize}; type Result<T> = std::result::Result<T, Rejection>; #[derive(Debug, Serialize, Deserialize)] struct HttpResponse { message: String, } #[tokio::main] async fn main() { let home_route = warp::any().and_then(health_handle...
use failure::Error; use futures::{Future, IntoFuture}; use hyper::header::{Authorization, Headers}; use hyper::Method; use serde::de::Deserialize; use serde::ser::Serialize; use serde_json; use stq_http::client::HttpClient; use stq_types::*; mod orders; pub use self::orders::*; mod stores; pub use self::stores::*; ...
mod impls; mod center; mod pack; mod env; mod errors; mod storage; mod loader; pub use env::{Source,LocalFS,LoaderEnv}; pub use errors::{AssetLoadError}; pub use center::{StorageCenter,AssetID}; pub use storage::{AssetStorage,Handle}; pub use pack::{S2DAssetPack}; pub use loader::{Loader}; use crate::render::types::{B...
use uuid::Uuid; /// pub fn gen_uuid() -> String { Uuid::new_v4().to_string() } /// pub fn str_to_float(val: &str) -> Result<f64, String> { match val.parse::<f64>() { Ok(parsed) => Ok(parsed), Err(_) => Err(format!("Error parsing float from {}", val)), } } /// pub fn str_to_usize(val: &...
use crate::ansi::{style, BOLD, RED}; use crate::position::source_position::SourceSpan; pub type Result<T> = std::result::Result<T, Error>; pub enum ErrorKind { UnexpectedChar, UnexpectedToken, UndeclaredVariable, TypeMismatch, Redeclaration, } pub struct Error { kind: ErrorKind, msg: String, pos: Sou...
/// Link Simulator /// /// Copyright (C) 2019 PTScientists GmbH /// /// 17.04.2019 Eric Reinthal extern crate rand; use mio::{Events, Poll, PollOpt, Ready, Token}; use rand::Rng; use std::fmt; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex}; use std::thread; use std::time; #[macro_use] ...
use rlua::prelude::*; use std::collections::HashMap; use std::collections::HashSet; use crate::lua::util::*; #[derive(Clone, Default)] pub struct Global { pub counter: usize, pub turn_count: usize, pub is_debug: bool, pub var_watchers: HashMap<String, HashSet<usize>>, } impl Global { pub const GL...
/// Enum for the players. #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)] pub enum Player { P1, P2, } impl Player { /// Returns the next player. `P1` -> `P2` -> `P1` -> etc. pub fn next(&self) -> Player { match *self { Player::P1 => { Player::P2 }, ...
//! # The Fat Pointer Hack //! //! This crate showcases a silly hack to make user-defined fat pointers //! //! ## What? //! //! In the simplest case, you can use this to tag arbitrary references with a `usize`: //! ``` //! use fat_pointer_hack::{RefExt, FatRefExt}; //! //! let x = 5; //! //! // Create a tagged referen...
// Copyright © 2019 Bart Massey // [This program is licensed under the "MIT License"] // Please see the file LICENSE in the source // distribution of this software for license terms. ///! Functions to compute various statistics on a slice of ///! floating-point numbers. /// Type of statistics function. If the statist...
// Copyright 2016 Pierre-Étienne Meunier // // 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 super::adb; use crate::{ android::env::Env, util::cli::{Report, Reportable}, }; use once_cell_regex::regex; use std::str; #[derive(Debug)] pub enum Error { DumpsysFailed(super::RunCheckedError), InvalidUtf8(str::Utf8Error), NotMatched, } impl Reportable for Error { fn report(&self) -> Repo...
use comrak::nodes::AstNode; use crate::rules::common_checks::check_content; use crate::rules::extensions::VecExt; use crate::ruleset::RuleResult; crate fn check<'a>(root: &'a AstNode<'a>) -> RuleResult { let details = check_content(root, r"\([^)]+\)\[[^\]]+\]", None); RuleResult::new( "MD011", ...
use serde::{Deserialize, Serialize}; //use serde_json::Result; #[derive(Debug)] #[derive(Serialize, Deserialize)] pub struct Schedule { pub id: i32, pub hour: i32, pub minute: i32, pub watering_minute: i32, pub watering_second: i32 } #[derive(Debug)] #[derive(Serialize, Deserialize)] pub struct Se...
pub mod infix; pub mod location; pub mod name; pub mod source; pub mod tuple; pub use location::{Located, Position}; pub use name::Name; pub use tuple::Tuple;
use std::collections::{BTreeSet, HashSet}; use std::ops::Range; use rand::distributions::{Range as RandRange, Sample}; use rand::Rng; use itertools::Itertools; use sc::utils::indexmap::{IndexSetExt, sample as sample_indexset}; use corpus::{SentenceOrder, SentenceId}; use individual::Gene; fn it_count_between<I: Itera...
use nes_emulator::cassette; use nes_emulator::ram; use nes_emulator::bus; use nes_emulator::cpu; use nes_emulator::render; fn main() { let cassette = cassette::roms::Rom::new("./roms/sample1.nes"); let ram = ram::Ram::new(vec![0; 0x0800]); let mut bus = bus::Bus::new(cassette, ram); let mut register = ...
/* * @lc app=leetcode id=875 lang=rust * * [875] Koko Eating Bananas * * https://leetcode.com/problems/koko-eating-bananas/description/ * * algorithms * Medium (49.05%) * Likes: 465 * Dislikes: 52 * Total Accepted: 25.1K * Total Submissions: 51.1K * Testcase Example: '[3,6,7,11]\n8' * * Koko loves...
use crate::crypto::coin::Coin; use crate::exchanges::mandala::utils::{ DepthSnapshot, DepthUpdate, Order as MandalaOrder, WebsocketRequest, }; use crate::exchanges::mandala::{BINANCE_API_URL, BINANCE_WSS_URL}; use crate::CONFIG; use hashbrown::HashMap; use parking_lot::Mutex; use serde_json::Value; use std::sync::a...
#[doc = "Register `RUNSTATUS` reader"] pub struct R(crate::R<RUNSTATUS_SPEC>); impl core::ops::Deref for R { type Target = crate::R<RUNSTATUS_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<RUNSTATUS_SPEC>> for R { #[inline(always)] fn from(read...
use std::cell::RefCell; use Vector; use physics::collisions; use physics::surface::Surface; pub struct DebugView { pub vectors: Vec<(Vector, Vector)>, } pub struct Vertex { pub mass: f32, pub position: Vector, pub velocity: Vector, pub acceleration: Vector, pub is_static: bool, } impl Vertex...
use std::time::Duration; use sdl2::image::{self, InitFlag, LoadTexture}; use sdl2::pixels::Color; use sdl2::rect::{Point, Rect}; use sdl2::render::{Texture, WindowCanvas}; use sdl2::Sdl; use crate::direction::Direction; use crate::player::Player; use crate::window::{handle_event, init_window}; mod player; mod direct...
mod indexmap; mod influence; mod my_strategy; mod occupancy; mod pathfinding; mod quick_start_strategy; mod vis; use model::{Action, PlayerView}; use my_strategy::MyStrategy; use quick_start_strategy::QuickStartStrategy; use std::time::Instant; trait GameStrategy { fn get_action( &mut self, player...
use soma::docker; use soma::docker::{image_exists, image_from_prob_exists, image_from_repo_exists}; use soma::ops::{add, build, clean}; pub use self::common::*; mod common; #[test] fn test_build_clean() { let (_, mut data_dir) = temp_data_dir(); let mut env = test_env(&mut data_dir); let mut runtime = de...
extern crate ears; use ears::{AudioController, Music}; use std::thread::sleep; use std::time::Duration; fn main() { let mut music = Music::new("res/music.ogg").unwrap(); music.play(); while music.is_playing() { sleep(Duration::from_millis(1000)); } }
extern crate std; extern crate native; extern crate debug; use native::io::file::open; use std::rt::rtio::{Open, Read}; use std::os::{MemoryMap, MapReadable, MapWritable, MapFd}; fn main() { let path = "test.bin"; let file = match open(&path.to_c_str(), Open, Read) { Err(_) => { fail!("Something is terr...
use std::time::{Duration, Instant}; // Time resource, updated every frame pub struct Time { // Elapsed time since last frame pub delta_time: Duration, // Rate at which fixed updates are called pub fixed_step: Duration, // Time of the last fixed update pub last_fixed_update: Instant, }...
fn main() { aoc_2019_03::part1() }
// Copyright 2020 Parity Technologies // // 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 not be copied, modified, or distributed // except accor...
extern crate time; mod world; use std::cmp; use time::PreciseTime; use world::{Dir, LineWorld16, Tile, World}; fn best_tile<W>(world: &W) -> i32 where W: for <'a> World<'a> { world.iterate().fold(0i32, |best, (_, v)| cmp::max(v.to_i32(), best)) } fn total<W>(world: &W) -> i32 where W: for <'a> World<'a...
// Copyright 2018-2021 Cargill Incorporated // // 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...
// All UI elements for twoby20 are found under application/ui. // Each module contains the separate UI elements for the entire // application. pub mod menubar; pub mod user_profile;
// 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 std::fmt; use itertools::Itertools; #[derive(Debug)] enum Direction { Up, Down, Left, Right, } #[derive(Debug)] struct Move { direction: Direction, steps: u32, } #[derive(Debug, Clone, PartialEq, Hash, PartialOrd, Ord)] struct Point { x: i32, y: i32, } impl Eq for Point {} struct...
use std::borrow::Cow; #[cfg(unix)] use std::os::unix::ffi::OsStrExt; use std::path::Path; pub trait AsUnixPathBytes { fn as_unix_path(&self) -> Cow<'_, [u8]>; } impl AsUnixPathBytes for Path { #[cfg(not(unix))] fn as_unix_path(&self) -> Cow<[u8]> { use std::path::Component::*; let parts: ...
use piston_window::*; use piston_window::ButtonState; use piston_window::Button; pub fn start(mut state: crate::models::App) { let start_res = [500, 650]; let mut window: PistonWindow = WindowSettings::new("Hello Piston!", start_res) .exit_on_esc(true) .build() .unwrap(); let font_...
use crate::native::registry::Registry; use crate::runtime::frame::Frame; use crate::utils::numbers::f32_to_i32; pub fn init() { Registry::register( "java/lang/Float", "floatToRawIntBits", "(F)I", float_to_raw_int_bits, ); } pub fn float_to_raw_int_bits(frame: &mut Frame) { ...
// //! 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 ...
use crate::coord::Shift; use crate::drawing::area::IntoDrawingArea; use crate::drawing::backend::{BackendCoord, BackendStyle, DrawingBackend, DrawingErrorKind}; use crate::drawing::DrawingArea; use crate::style::{Color, FontDesc, RGBAColor}; pub struct MockedBackend { height: u32, width: u32, init_count: u...