text
stringlengths
8
4.13M
use std::{path::PathBuf, str::FromStr}; use clap::Clap; /// Options #[derive(Clap, Debug)] pub struct Opt { /// The file to compile pub file: PathBuf, /// Output file. Omit for default file (compile) or stdout (other actions). #[clap(short, long = "out")] pub out_file: Option<PathBuf>, /// T...
extern crate rustc_serialize; extern crate hyper; use std::io::Read; use rustc_serialize::json; use rustc_serialize::{Encodable, Encoder}; use hyper::status::StatusCode; pub const SERVER_ADDR: &'static str = "127.0.0.1:1980"; pub const BOT_ADDR: &'static str = "127.0.0.1:1981"; pub const HTML_ADDR: &'static str = "h...
use syn::Fields; pub mod fields; pub mod bit_index; pub use fields::build_clauses; use proc_macro2::TokenStream; use crate::attributes::{ ParentDataType }; //Compiles the clauses into a struct pub fn get_struct(fields : &Fields, name : &proc_macro2::Ident, parent_data_type : ParentDataType) -> (TokenStream, TokenSt...
use wasm_bindgen::prelude::*; #[wasm_bindgen] pub struct TicTacToe { board: Vec<String>, result: String, turn: i32, win: bool, } #[wasm_bindgen] impl TicTacToe { pub fn new() -> TicTacToe { console_error_panic_hook::set_once(); let board = (1..10).map(|_| { String::new(...
use wal::{WalBuilder, WritePayload}; type TestError = Box<dyn std::error::Error + Send + Sync + 'static>; type Result<T = (), E = TestError> = std::result::Result<T, E>; #[test] fn no_concurrency() -> Result { let dir = test_helpers::tmp_dir()?; let builder = WalBuilder::new(dir.as_ref()); let mut wal = b...
use quickcheck::Arbitrary; use quickcheck_macros::quickcheck; use tabled::{ builder::Builder, grid::util::string::{string_width, string_width_multiline}, settings::Style, Table, }; #[quickcheck] fn qc_table_is_consistent(data: Vec<Vec<isize>>) -> bool { let mut builder = Builder::default(); for...
use crate::scheduler::gc_work::ProcessEdgesWork; use crate::scheduler::{GCWork, GCWorker}; use crate::util::{ObjectReference, OpaquePointer}; use crate::vm::{Collection, VMBinding}; use crate::MMTK; use std::marker::PhantomData; /// A special processor for Finalizable objects. // TODO: we should consider if we want to...
use rustybox::Function; use std::env::Args; pub fn binding() -> (&'static str, Function) { ("yes", Box::new(yes)) } fn yes(_: Args) -> i32 { loop { println!("y") } 0 }
extern crate simplicity; use std::{cmp, fmt, ptr}; const IN_SIZE: usize = 8; /* A length-prefixed encoding of the following Simplicity program: * ((false &&& scribe (toWord256 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798)) &&& zero word256) &&& * witness (toWord512 0x787A848E71043D...
pub enum Progress { Waiting, Started, Packet(u8), } pub type ProgressFn = fn(Progress); pub fn noop(_: Progress) {}
use crate::config::AndroidConfig; use crate::ops::install; use anyhow::format_err; use cargo::core::{TargetKind, Workspace}; use cargo::util::process_builder::process; use cargo::util::CargoResult; use clap::ArgMatches; pub fn run(workspace: &Workspace, config: &AndroidConfig, options: &ArgMatches) -> CargoResult<()> ...
extern crate a01; extern crate rand; use std::env; use a01::*; use std::process; use std::net; use std::net::UdpSocket; use rand::Rng; use std::thread; use std::time::Duration; static MIN_JOB_TIME_MS : u32 = 6000; static MAX_JOB_TIME_MS : u32 = 6500; static MIN_SLEEP_TIME_MS : u64 = 100; static MAX_SLEEP_TIME_MS : u6...
use alloc::string::ToString; use core::fmt; use crate::base58; pub type Result<T> = core::result::Result<T, Error>; #[derive(Debug, PartialEq, Eq, Clone)] pub enum Error { /// Base58 encoding error Base58(base58::Error), /// secp256k1-related error Secp256k1(secp256k1::Error), /// hash error H...
use super::super::context::Context; use super::super::error::Result; use super::ToDuktape; #[cfg(feature = "value")] use value::Value; macro_rules! push_or_pop { ($dims:expr, $ctx: ident, $popc: expr) => { match $dims.to_context($ctx) { Ok(_) => {} Err(e) => { $ctx.p...
use druid::{Command, FileDialogOptions, FileSpec, Selector, Target}; use crate::dialogs::NewFileSettings; const IMAGE_FILE_TYPE: FileSpec = FileSpec::new("Images", &["bmp", "png", "gif", "jpg", "jpeg"]); pub(crate) const FILE_EXIT_ACTION: Selector = Selector::new("menu-exit-action"); pub(crate) const FILE_NEW_ACTION:...
extern crate dotenv; use actix_web::error; use actix_web::error::ErrorUnauthorized; use actix_web::{web, Error, HttpRequest, HttpResponse}; use postgres::NoTls; use r2d2::Pool; use r2d2_postgres::PostgresConnectionManager; use validator::Validate; use crate::accounts::*; use crate::auth::*; use crate::jwt::*; use cra...
//! # MIR: Mid-level IR //! We use MIR in optimizing and tracing JIT, MIR includes a few Waffle specific optimizations and it is lowered to LIR or MacroAssembler directly. pub mod basic_block; pub mod node; pub mod opcodes; pub struct MIRGraph { pub basic_blocks: Vec<basic_block::BasicBlock>, pub values: Vec<...
use crate::toCKB_typescript::utils::{case_builder::*, case_runner}; use tockb_types::{ config::{AUCTION_MAX_TIME, CKB_UNITS, LOCK_TYPE_FLAG, SINCE_TYPE_TIMESTAMP, XT_CELL_CAPACITY}, Error, }; const BTC_BURN_AMOUNT: u128 = 25_000_000; const TOCKB_CELL_CAPACITY: u64 = 3_750_000 * CKB_UNITS; const SINCE: u64 = LO...
extern crate image; // https://drive.google.com/drive/folders/14yayBb9XiL16lmuhbYhhvea8mKUUK77W use std::ops::Sub; use std::ops::Add; use std::ops::Mul; use std::path::Path; struct Point { x: f32, y: f32, z: f32, } impl Copy for Point {} impl Clone for Point { fn clone(&self) -> Point { *self...
use error::Result; use std::fmt; use std::path::Path; #[macro_use] mod utils; pub mod sys; #[cfg(feature = "zip")] pub mod zip; pub trait Handler: fmt::Debug { fn stat(&mut self, path: &Path) -> Result<::fs::stat::Stat>; fn read_dir(&mut self, path: &Path) -> Result<::fs::dir::ReadDirIterator>; fn open(&m...
//! Link: https://adventofcode.com/2019/day/14 //! Day 14: Oxygen System //! //! Out here in deep space, many things can go wrong. //! Fortunately, many of those things have indicator lights. //! Unfortunately, one of those lights is lit: //! the oxygen system for part of the ship has failed! //! //! According to t...
#[doc = "Register `HDP_CTRL` reader"] pub type R = crate::R<HDP_CTRL_SPEC>; #[doc = "Register `HDP_CTRL` writer"] pub type W = crate::W<HDP_CTRL_SPEC>; #[doc = "Field `EN` reader - EN"] pub type EN_R = crate::BitReader; #[doc = "Field `EN` writer - EN"] pub type EN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>...
use serde_json::Value; pub(crate) fn get_json_value_difference( reference: String, desire: &Value, current: &Value, ) -> Option<Value> { match (desire, current) { (Value::Bool(des), Value::Bool(cur)) => { if des != cur { Some(Value::String(format!( ...
//! The file tree generator. //! //! Unlike the other generators the file generator does not "connect" however //! losely to the target but instead, without coordination, merely generates //! a file tree and generates random acess/rename operations. use rand::{ distributions::{Alphanumeric, DistString}, seq::S...
#![doc = "generated by AutoRust 0.1.0"] #![allow(unused_mut)] #![allow(unused_variables)] #![allow(unused_imports)] use crate::models::*; use reqwest::StatusCode; use snafu::{ResultExt, Snafu}; pub mod operations { use crate::models::*; use reqwest::StatusCode; use snafu::{ResultExt, Snafu}; pub async f...
#[no_mangle] pub extern "C" fn banana() -> i32 { return 42; }
use cpal; use cpal::traits::{DeviceTrait, HostTrait, StreamTrait}; use std::sync::{Arc, Mutex, MutexGuard}; use circular_queue::CircularQueue; use friday_error; use friday_error::{frierr, propagate, FridayError}; use friday_logging; use crate::recorder::Recorder; use crate::RecordingConfig; use std::thread; use std::t...
use crate::features::syntax::StatementFeature; use crate::parse::visitor::tests::assert_stmt_feature; #[test] fn continue_no_label() { assert_stmt_feature( "with ({ a: 123 }) { a = 0; }", StatementFeature::WithStatement, ); }
#[doc = "Register `MACDR` reader"] pub type R = crate::R<MACDR_SPEC>; #[doc = "Field `RPESTS` reader - MAC MII Receive Protocol Engine Status When this bit is set, it indicates that the MAC MII receive protocol engine is actively receiving data, and it is not in the Idle state."] pub type RPESTS_R = crate::BitReader; #...
use objc::Encode; use objc::Encoding; use crate::foundation::NSPoint; use crate::foundation::NSSize; // https://developer.apple.com/documentation/foundation/nsrect #[derive(Clone, Copy, Debug, Default)] #[repr(C)] pub struct NSRect { pub origin: NSPoint, pub size: NSSize, } impl NSRect { pub fn new(origin: NSP...
use schema::pages; use std::time::SystemTime; use stq_api::pages::*; use stq_types::{PageId, PageSlug}; #[derive(From, Into, Queryable, Insertable, Identifiable)] #[table_name = "pages"] pub struct DbPage { pub id: PageId, pub slug: PageSlug, pub html: String, pub css: String, pub created_at: Syst...
#[doc = "Register `PUCRG` reader"] pub type R = crate::R<PUCRG_SPEC>; #[doc = "Register `PUCRG` writer"] pub type W = crate::W<PUCRG_SPEC>; #[doc = "Field `PU0` reader - Port G pull-up bit y (y=0..15)"] pub type PU0_R = crate::BitReader; #[doc = "Field `PU0` writer - Port G pull-up bit y (y=0..15)"] pub type PU0_W<'a, ...
use crate::*; pub fn init_method(globals: &mut Globals) -> Value { let proc_id = globals.get_ident_id("Method"); let class = ClassRef::from(proc_id, globals.builtins.object); globals.add_builtin_instance_method(class, "call", method_call); Value::class(globals, class) } pub fn method_call(vm: &mut VM,...
use nu_engine::CallExt; use nu_protocol::engine::{Command, EngineState, Stack}; use nu_protocol::{ ast::Call, Category, Example, IntoPipelineData, PipelineData, ShellError, Signature, Span, Spanned, SyntaxShape, Value, }; #[derive(Clone)] pub struct SeqChar; impl Command for SeqChar { fn name(&self) -> &s...
use std::ops::Range; use super::{ binding::{self, Buffer, BufferGroup, TextureBinding}, frame::Framebuffer, grid::Grid, model::{Material, Mesh, Model}, }; pub trait Vertex { fn desc<'a>() -> wgpu::VertexBufferDescriptor<'a>; } pub trait DrawModel<'a, 'b> where 'b: 'a, { fn draw_mesh( ...
fn main() { let x = 5i32; let y = { if x == 4i32 { 3i32} else { 6i32 }}; println!("{}" ,y); }
use crate::core::compiler::{Compilation, CompileKind, Doctest, Metadata, Unit, UnitOutput}; use crate::core::shell::Verbosity; use crate::core::{TargetKind, Workspace}; use crate::ops; use crate::util::errors::CargoResult; use crate::util::{add_path_args, CargoTestError, Config, Test}; use cargo_util::{ProcessBuilder, ...
use std::{ collections::HashMap, convert::{TryFrom, TryInto}, fmt::Debug, pin::Pin, }; use futures::{ future::ready, stream::{empty, once, select_all, BoxStream}, Future, FutureExt, Sink, SinkExt, Stream, StreamExt, TryFutureExt, TryStreamExt, }; use stomp_parser::{client::*, headers::*, se...
use openssl; use std; use serde_json; use url; use hyper; error_chain! { foreign_links { OpenSSL(openssl::error::ErrorStack); IOError(std::io::Error); JsonError(serde_json::Error); UrlParseError(url::ParseError); UriError(hyper::error::UriError); HTTPError(hyper::err...
#[macro_use] extern crate cluLog; #[derive(Debug, Default)] pub struct Point(u32, f32); fn main() { //init_clulog!(); cluLog::set_logger(cluLog::LogDefault::default()); let a = Point::default(); let b = Point(120, 1.345); test(&a, &b); } fn test(point: &Point, point_2: &Point) { ...
#[doc = "Register `CSR46` reader"] pub type R = crate::R<CSR46_SPEC>; #[doc = "Register `CSR46` writer"] pub type W = crate::W<CSR46_SPEC>; #[doc = "Field `CS46` reader - Context swap x Refer to Section 24.7.7: HASH context swap registers introduction."] pub type CS46_R = crate::FieldReader<u32>; #[doc = "Field `CS46` ...
// This module provides Randorst struct for generating // sorted random numbers in constant space // used to smoothly extract words from large file in random fashion // // Randorst is my rust implementation of the algorithm // proposed in the following paper: // Bentley, Jon & Saxe, James. (1980). Generating Sorted Lis...
use totsu::prelude::*; use totsu::*; use totsu_f64lapack::F64LAPACK; use std::str::FromStr; use plotters::prelude::*; use intel_mkl_src as _; use anyhow::Result; type La = F64LAPACK; type AMatBuild = MatBuild<La>; type AProbQCQP = ProbQCQP<La>; type ASolver = Solver<La>; /// main fn main() -> Result<()> { env_l...
//! See [`Idx`]. #![deny(clippy::pedantic, missing_debug_implementations, missing_docs, rust_2018_idioms)] /// An index type. #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct Idx(u32); impl Idx { /// Returns a new `Idx` for the usize. #[must_use] pub fn new(n: usize) -> Self { ...
#[doc = "Register `IOPSMENR` reader"] pub type R = crate::R<IOPSMENR_SPEC>; #[doc = "Register `IOPSMENR` writer"] pub type W = crate::W<IOPSMENR_SPEC>; #[doc = "Field `GPIOASMEN` reader - I/O port A clock enable during Sleep mode Set and cleared by software."] pub type GPIOASMEN_R = crate::BitReader; #[doc = "Field `GP...
use crate::nasdaq::gen; #[derive(Default, Debug, Clone, PartialEq, serde_derive::Serialize, serde_derive::Deserialize)] #[serde(rename_all = "camelCase")] pub struct InsidersRoot { pub data: Data, pub message: ::serde_json::Value, pub status: gen::Status, } impl crate::HasRecs for InsidersRoot { fn to...
use std::fmt; use std::fmt::Display; use rand::Rng; #[derive(Hash, Eq, PartialEq, Debug, PartialOrd, Ord, Clone, Copy)] pub struct Pos(pub u64); pub const START: Pos = Pos(0xfedcba9876543210); impl Pos { pub fn hole_index(&self) -> usize { for i in 0..16 { if (self.0 >> (4 * i)) & 15 == 15 {...
// Keccak-f[800] mod short_msg_kat_r288c512; mod short_msg_kat_r544c256; mod short_msg_kat_r640c160; // Keccak-f[400] mod short_msg_kat_r144c256; mod short_msg_kat_r240c160; // Keccak-f[200] mod short_msg_kat_r40c160; // Keccak{224, 256, 384, 512} mod short_msg_kat_224; mod short_msg_kat_256; mod short_msg_kat_384; mo...
use std::{fs, collections::HashSet}; const ROPE_LENGTH: usize = 10; type Instruction = (char, usize); #[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)] struct Point { x: isize, y: isize, } impl Point { fn touching(&self, other: &Self) -> bool { let x_distance = self.x - other.x; ...
use perseus::{define_app, ErrorPages, Template}; use std::rc::Rc; use sycamore::template; define_app! { templates: [ Template::<G>::new("index").template(Rc::new(|_| { template! { p { "Hello World!" } } })) ], error_pages: ErrorPages::new(Rc::new(|url,...
//! This module defines the `System.Core` namespace, imported by default in every binder. use binder::Binder; use symbols::Sym; use vm::{Vm, VirtualMachine}; use std::mem; lazy_static! { static ref SYSCORE_SYMBOL: Sym = { Sym::from("System.Prelude") }; } /// Imports all core parsers in the given v...
use std::sync::{Mutex, Arc}; use std::thread; use std::rc::Rc; fn hello_mutex() { let m = Mutex::new(5); { let mut num = m.lock().unwrap(); *num = 6; } println!("hello mutex: {:?}", m); } // won't work - closure takes ownership on first iteration fn shared_mutex_broken() { let co...
pub fn a_echo() { println!("a_echo"); }
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT license. */ use log::{debug, info, log_enabled, warn, Level}; use logger::trace_logger::TraceLogger; // cargo run --example trace_example fn main() { static LOGGER: TraceLogger = TraceLogger {}; log::set_logger(&LOGGER)...
extern crate project_euler; fn main() { println!( "Problem 1: {}", project_euler::multiples_of_3_and_5::solve(1000) ); println!( "Problem 2: {}", project_euler::even_fibonacci::solve(4_000_000) ); println!( "Problem 3: {}", project_euler::largest_pr...
extern crate ted_net_client; extern crate ted_gui; use ted_net_client as tedn; use std::thread; fn main(){ let mut args: Vec<String>=std::env::args().collect(); let address=if args.len()>1 {args.remove(1)} else {"127.0.0.1".to_string()}; let connection=tedn::connect(address); let tcp_stream=connection.tcp...
use anyhow::Result; use itertools::Itertools; use std::fs; fn do_the_thing(input: &str) -> Result<usize> { let mut joltages = input .lines() .map(|n| n.parse::<usize>().unwrap()) .sorted() .collect::<Vec<_>>(); joltages.insert(0, 0); joltages.push(joltages.last().unwrap() + ...
#[macro_use] extern crate log; extern crate wasi_common; extern crate wasmtime; extern crate wasmtime_wasi; extern crate websocket; use std::io::Cursor; use std::sync::mpsc; use std::sync::{Arc, Mutex, RwLock}; use std::thread; use std::vec::Vec; use wasi_common::virtfs::pipe::{ReadPipe, WritePipe}; use wasmtime::*; u...
use std; use meow; /* Function: all Return true if a predicate matches all characters If the string contains no characters */ fn all(ss: str, ff: fn&(char) -> bool) -> bool { str::loop_chars(ss, ff) } /* Function: map Apply a function to each character */ fn map(ss: str, ff: fn&(char) -> char) -> str { le...
fn main() { let mut x = 100; let r1 = &x; let r2 = &x; // ok: multiple shared borrows permitted x += 10; // error: cannot assign to x because it's borrowed let m = &mut x; // error: cannot borrow x as mutable because it's already borrowed as immutable let mut y = 100; let s1 = &mut y; let s2 = &mut y; // error...
use structopt::StructOpt; use std::{process::{Command, Stdio, Child}}; use std::fs::{self, File, DirEntry}; use std::io::{self, BufReader, Read}; use std::path::{Path, PathBuf}; use serde::Deserialize; use notify::{Watcher, RecursiveMode, watcher, DebouncedEvent }; use std::sync::mpsc::{channel, Receiver, Sender}; use ...
#[doc = r"Register block"] #[repr(C)] pub struct HC { #[doc = "0x00 - OTG_FS host channel-0 characteristics register (OTG_FS_HCCHAR0)"] pub char: CHAR, _reserved1: [u8; 0x04], #[doc = "0x08 - OTG_FS host channel-0 interrupt register (OTG_FS_HCINT0)"] pub int: INT, #[doc = "0x0c - OTG_FS host cha...
#[cfg(test)] #[path = "../../../../tests/unit/solver/mutation/ruin/route_removal_test.rs"] mod route_removal_test; use super::*; use crate::construction::heuristics::{group_routes_by_proximity, InsertionContext, RouteContext, SolutionContext}; use crate::models::problem::Job; use crate::solver::RefinementContext; ///...
/* * Datadog API V1 Collection * * Collection of all Datadog Public endpoints. * * The version of the OpenAPI document: 1.0 * Contact: support@datadoghq.com * Generated by: https://openapi-generator.tech */ /// SloType : The type of the service level objective. /// The type of the service level objective. #[d...
use core::*; use graphics::*; use math::*; use rand::*; use std::collections::*; use std::any::*; struct Component1(f32); struct Component2(i32, f64); struct Component3(String, f64, f64, String); struct NotRegistered(usize); /// Checks the creation of a simple 3d world and respectively the add/get functionality. /// ...
// =============================================================================== // Authors: AFRL/RQQA // Organization: Air Force Research Laboratory, Aerospace Systems Directorate, Power and Control Division // // Copyright (c) 2017 Government of the United State of America, as represented by // the Secretary of th...
use nanorand::RNG; use pyo3::prelude::*; #[pyclass] #[derive(Default)] pub struct ChaCha { inner: nanorand::ChaCha, } #[pymethods] impl ChaCha { #[new] pub fn new(rounds: u8) -> Self { Self { inner: nanorand::ChaCha::new(rounds), } } #[staticmethod] pub fn new_key(rounds: u8, key: [u8; 32], nonce: [u8; ...
#[doc = "Reader of register RCC_CPERCKSELR"] pub type R = crate::R<u32, super::RCC_CPERCKSELR>; #[doc = "Writer for register RCC_CPERCKSELR"] pub type W = crate::W<u32, super::RCC_CPERCKSELR>; #[doc = "Register RCC_CPERCKSELR `reset()`'s with value 0"] impl crate::ResetValue for super::RCC_CPERCKSELR { type Type = ...
use std::fmt; use std::fmt::Display; const DEFAULT_HEIGHT: f32 = 14.0; pub enum FontUnit { Pixel, Point, } impl Display for FontUnit { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { match self { FontUnit::Pixel => write!(fmt, "px"), FontUnit::Point => write!(fmt,...
use crate::models::{User}; use crate::data::{ContextBuilder, Context}; use crate::sql_mapper::{user_mapper}; use waiter_di::*; use tokio_postgres::{Row, Error}; use async_trait::async_trait; #[async_trait] // Interface pub trait IDaoUser: Send{ async fn get_user(&mut self, email: String)->Result<User, ()>; asy...
use protoc_rust::Customize; use std::path::Path; fn main() { let a = Path::new("src/proto").join("A").join("a.proto"); let b = Path::new("src/proto").join("B").join("b.proto"); protoc_rust::run(protoc_rust::Args { out_dir: "src", input: &[a.to_str().unwrap(),b.to_str().unwrap()], in...
use serenity::client::{Context, EventHandler}; use serenity::model::channel::Message; use serenity::framework::standard::macros::{command, group}; use serenity::framework::standard::CommandResult; use serenity::async_trait; #[group] #[commands(start, play_again, result, status)] struct Sequence; pub struct Handler; ...
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under both the MIT license found in the * LICENSE-MIT file in the root directory of this source tree and the Apache * License, Version 2.0 found in the LICENSE-APACHE file in the root directory * of this source tree. */ use s...
use crate::game::utils::*; use crate::game::Drawable; use std::io::{Error, Write}; pub struct Snake { head: Coord, body: Vec<Direction>, max_length: u16, } impl Snake { pub fn new(start_pos: Coord, len: u16) -> Snake { let head = start_pos; let body = vec![Direction::Right; len.into()...
use phasicj_jmm::JmmEvent;
extern crate chrono; extern crate rustc_serialize; use self::chrono::{DateTime, UTC}; use rustc_serialize::json::{ToJson, Json}; use std::collections::BTreeMap; #[derive(Debug, Clone)] pub struct Period { pub started_at: chrono::DateTime<UTC>, pub finished_at: chrono::DateTime<UTC> } #[derive(Debug, Clone, Rustc...
use common::*; use glw::gl_buffer::{GLArray, GLBuffer, Triangles}; use glw::gl_context::GLContext; use glw::shader::Shader; use glw::vertex; use nalgebra::Vec3; use state::App; use state::EntityId; use std::cell::RefCell; use std::collections::HashMap; use std::rc::Rc; // N.B.: Behaviors are unsafe because they take b...
use std::cmp::Ordering; use std::ops::Add; fn two_sum<T>(arr: &[T], sum: T) -> Option<(usize, usize)> where T: Add<Output = T> + Ord + Copy, { if arr.len() == 0 { return None; } let mut i = 0; let mut j = arr.len() - 1; while i < j { match (arr[i] + arr[j]).cmp(&sum) { ...
pub fn lsp(series: &str, n: usize) -> Result<u32, &str> { if series.len() < n { return Err("The series is not long enough."); } if n == 0 { return Ok(1); } let mut num_vec: Vec<u32> = Vec::new(); let mut char_iter = series.chars(); while let Some(c) = char_iter.next() { if let Some(i)...
// Find number of negative values in sorted matrix (descending order along both axis). // https://leetcode.com/problems/count-negative-numbers-in-a-sorted-matrix/ //----------------------------------------------------------------------------------- // Ω(n) O(n log m) | O(1) pub mod count_negatives { pub fn run(grid...
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under both the MIT license found in the * LICENSE-MIT file in the root directory of this source tree and the Apache * License, Version 2.0 found in the LICENSE-APACHE file in the root directory * of this source tree. */ use a...
mod intcode_machine; mod util; use intcode_machine::{run_all, Machine, State}; use std::collections::{HashMap, HashSet}; use std::io::{stdin, BufRead}; use util::error_exit; const C_NORTH: i64 = 1; const C_SOUTH: i64 = 2; const C_WEST: i64 = 3; const C_EAST: i64 = 4; const S_STILL: i64 = 0; const S_MOVED: i64 = 1; c...
mod line; use wasm_bindgen::prelude::*; #[wasm_bindgen] #[no_mangle] pub struct TextEditor { lines: Vec<line::Line>, // Holds all lines mode: String, // Language mode, i.e. Java or Python cur_line: u32, // Current line the editor is on is_newline: bool, // If the next inserted line is a new line } #[n...
//! This is the uncleaned result of XML deserialization. You probably want the objects and methods //! in the `geom::graph` module instead. extern crate serde; //use serde::{de::Error, Deserialize, Deserializer}; use serde::Deserialize; use crate::Error; /// A `Mesh` is the top-level structure representing a GEOM o...
#[doc = "Reader of register PCF1"] pub type R = crate::R<u32, super::PCF1>; #[doc = "Writer for register PCF1"] pub type W = crate::W<u32, super::PCF1>; #[doc = "Register PCF1 `reset()`'s with value 0"] impl crate::ResetValue for super::PCF1 { type Type = u32; #[inline(always)] fn reset_value() -> Self::Typ...
use lazy_static::lazy_static; use std::collections::HashMap; use crate::{parser::Square, BoardPosition, Castling, DenseBoard, PacoError, PlayerColor}; use lazy_regex::regex_captures; /// This module implements an extension of X-Fen that can represent settled Paco /// Ŝako boards (i.e. boards without an active chain)...
/* Copyright (c) 2023 Uber Technologies, Inc. <p>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 <p>http://www.apache.org/licenses/LICENSE-2.0 <p>Unless required by applicable law or agreed to...
#[macro_use] extern crate microstate; microstate!{ MicroMachine { New } states { New, Confirmed, Ignored } confirm { New => Confirmed } ignore { New => Ignored } reset { Confirmed => New Ignored => New } } fn main() { let mut machine = MicroMach...
use crate::precise::expression::Expr; pub struct Complex { pub real: Expr, pub imaginary: Expr, }
use crate::{ command::CommandError, domain::{model::Favorite, repository::IRepository, service::search}, interface::presenter::suggest, }; pub fn ls_at_favorite<T: IRepository>(repo: &T, key: String) -> anyhow::Result<Favorite> { let target = repo.get(&key); match target { Ok(Some(favorite)...
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under both the MIT license found in the * LICENSE-MIT file in the root directory of this source tree and the Apache * License, Version 2.0 found in the LICENSE-APACHE file in the root directory * of this source tree. */ use q...
#[doc = "Register `OFR1` reader"] pub type R = crate::R<OFR1_SPEC>; #[doc = "Register `OFR1` writer"] pub type W = crate::W<OFR1_SPEC>; #[doc = "Field `OFFSET1` reader - ADC offset number 1 offset level"] pub type OFFSET1_R = crate::FieldReader<u16>; #[doc = "Field `OFFSET1` writer - ADC offset number 1 offset level"] ...
use rtm::UserProfile; /// Retrieves a user's profile information. /// /// Wraps https://api.slack.com/methods/users.profile.get #[derive(Clone, Debug, Serialize, new)] pub struct GetRequest { /// User to retrieve profile info for #[new(default)] pub user: Option<::UserId>, /// Include labels for each ...
// Copyright 2020 The RustABC Authors. // // Code is licensed under Apache License, Version 2.0. pub mod compare_functions;
use std::cmp::Ordering; use std::collections::{BinaryHeap, HashMap}; use crate::util::lines_from_file; pub fn day15() { println!("== Day 15 =="); let input = lines_from_file("src/day15/input.txt"); let a = part_a(&input); println!("Part A: {}", a); let b = part_b(&input); println!("Part B: {}"...
use std::path::PathBuf; use log::*; use crate::agent; use crate::conf::*; pub struct PlayArgs { pub path: PathBuf, } pub async fn play(args: &PlayArgs) -> Option<bool> { // Attempt to parse configuration. let file = std::fs::File::open(&args.path).expect("Could not open file"); let conf: Conf = serd...
use crate::audio_decoder::AudioDecoder; use crate::filter_graph::FilterGraph; use crate::format_context::FormatContext; use crate::order::input::Input; use crate::stream::Stream; use crate::subtitle_decoder::SubtitleDecoder; use crate::tools; use crate::video_decoder::VideoDecoder; use ffmpeg_sys_next::AVMediaType; #[...
use std::error::Error; use std::fs::File; use std::io::{Read, Write}; use std::process::Command; use syn::visit_mut::VisitMut; use syn::{Block, Expr, Type}; /// TODO /// * string literals /// * Slices should be translated into raw pointers? /// * Slice indexing does not work /// * Alloc interface fn main() -> Result<...
use std::collections::HashMap; pub mod part1; pub mod part2; pub fn default_input() -> &'static str { include_str!("input") } pub fn run() { part1::run(); part2::run(); } pub fn parse_input(input : &str) -> Vec<HashMap<String, String>> { input.split("\n\n") .map(|p| { let map : ...
use super::error::ProtocolError; pub mod blink; pub mod breathe; pub mod neon; pub mod steady; #[derive(Debug, Clone, Copy)] pub enum Effect { Respiration(breathe::Speed), Steady(steady::Brightnes), Neon(neon::Speed), } impl Default for Effect { fn default() -> Self { Self::Respiration(breath...