text
stringlengths
8
4.13M
//! ## `MainActivity` //! //! `main_activity` is the module which implements the Main activity, which is the activity to //! work on termusic app /** * MIT License * * termail - Copyright (c) 2021 Larry Hao * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and ass...
pub mod download; pub mod info; pub mod publish;
// Copyright 2019 The Grin Developers // 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 t...
pub struct UnionFind { // number of items n: i32, // parents[i] is parent of i parents: Vec<i32>, // number of objects rooted at i sizes: Vec<i32>, } impl UnionFind { pub fn new(n: i32) -> Self { let mut parents: Vec<i32> = Vec::with_capacity(n as usize); let mut sizes...
/* * Slack Web API * * One way to interact with the Slack platform is its HTTP RPC-based Web API, a collection of methods requiring OAuth 2.0-based user, bot, or workspace tokens blessed with related OAuth scopes. * * The version of the OpenAPI document: 1.7.0 * * Generated by: https://openapi-generator.tech *...
#![feature(custom_derive, plugin)] #![plugin(diesel_codegen)] #[macro_use] extern crate diesel; extern crate num; mod access_token; mod schema; fn main() { }
#![allow(clippy::needless_return)] #![feature(portable_simd)] use core_simd::Simd; use core::convert::TryInto; use srng::SRng; use simd_aes::SimdAes; const DEFAULT_SEED: Simd<u8, 16> = Simd::from_array([ 178, 201, 95, 240, 40, 41, 143, 216, 2, 209, 178, 114, 232, 4, 176, 188, ]); #[allow(non_snake_case)] fn ...
use std::fmt; #[derive(Debug)] struct User { pub name: String, pub username: String } impl fmt::Display for User { fn fmt(&self, out: &mut fmt::Formatter) -> fmt::Result { write!(out, "{} <{}@kth.se>", self.name, self.username) } } fn getuser(id: &str) -> Option<User> { match id { ...
#[macro_use] extern crate bencher; extern crate exr; use exr::image::full::*; use bencher::Bencher; use std::fs; use exr::image::read_options; /// Read RLE image from file fn read_single_image(bench: &mut Bencher) { let path = "tests/images/valid/openexr/crowskull/crow_rle.exr"; bench.iter(||{ Image...
extern crate cron; extern crate chrono; #[cfg(test)] mod tests { use cron::Schedule; use std::str::FromStr; use chrono::*; #[test] fn test_readme() { let expression = "0 30 9,12,15 1,15 May-Aug Mon,Wed,Fri 2018/2"; let schedule = Schedule::from_str(expression).unwra...
use core::cell::UnsafeCell; use core::mem::MaybeUninit; use atomic_polyfill::{AtomicBool, Ordering}; /// Type with static lifetime that may be written to once at runtime. /// /// This may be used to initialize static objects at runtime, typically in the init routine. /// This is useful for objects such as Embassy's R...
// Copyright 2012-2015 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-MI...
#[doc = "Reader of register STGENC_CNTSR"] pub type R = crate::R<u32, super::STGENC_CNTSR>; #[doc = "Reader of field `EN`"] pub type EN_R = crate::R<bool, bool>; #[doc = "Reader of field `HLTDBG`"] pub type HLTDBG_R = crate::R<bool, bool>; impl R { #[doc = "Bit 0 - EN"] #[inline(always)] pub fn en(&self) ->...
use itertools::Itertools; #[allow(unused_macros)] macro_rules! parse_line { ( $t:ty ) => ( { let mut line = String::new(); ::std::io::stdin().read_line(&mut line).unwrap(); let mut iter = line.split_whitespace(); iter.next().unwrap().parse::<$t>().unwrap() ...
use std::{thread, time}; /* * CPU Flags * Made the decision to use a struct with separate flags rather * than fiddling with an F register using bitwise ops. Time will tell whether this was a good idea. * Zero Flag (Z) - Set to 1 when the result of a math operation is zero or two values match when using the CP instru...
use crate::z3::ast::{Ast, Bool}; use std::convert::TryInto; use std::ffi::CStr; use std::fmt; use z3_sys::*; use crate::z3::Context; use crate::z3::Model; use crate::z3::Optimize; use crate::z3::SatResult; use crate::z3::Z3_MUTEX; impl<'ctx> Optimize<'ctx> { /// Create a new optimize context. pub fn new(ctx: &...
use std::fs; #[derive(Debug)] struct Point { x: i32, y: i32, } #[derive(Debug)] struct LineSegment { start: Point, end: Point, wire_length: i32, } impl LineSegment { fn new(start: Point, end: Point, wire_length: i32) -> LineSegment { LineSegment { start, end, ...
#[cfg(target_os = "redox")] mod redox; #[cfg(target_os = "redox")] pub(crate) use self::redox::*; #[cfg(all(unix, not(target_os = "redox")))] mod unix; #[cfg(all(unix, not(target_os = "redox")))] pub(crate) use self::unix::*;
use crate::common::{self, *}; pub type Text = AMember<AControl<AText<TestableText>>>; #[repr(C)] pub struct TestableText { base: common::TestableControlBase<Text>, text: String, } impl HasLabelInner for TestableText { fn label(&self, _base: &MemberBase) -> Cow<str> { Cow::Borrowed(sel...
//! A reactive interface to the DOM. #![allow( clippy::missing_panics_doc, clippy::missing_errors_doc, clippy::must_use_candidate, clippy::module_name_repetitions, clippy::option_if_let_else )] pub mod element_list; pub mod render; use std::{cell::RefCell, collections::HashMap, mem, rc::Rc}; use re...
pub mod binary; pub mod unary; use crate::emitter::emitter::Emitter; use crate::emitter::environment::Value; use crate::lexer::token::Tokens; use crate::parser::node::expression::binary::BinaryNode; use crate::parser::node::expression::unary::UnaryNode; #[derive(Debug, PartialEq, Clone)] pub enum ExpressionNode { ...
use utils; pub fn problem_016() -> u32 { let n = 1000; let mut digits: Vec<u32> = vec![1]; for _ in 0..n { digits = utils::add_digit_array(&digits[..], &digits[..]) } digits.iter().fold(0, |a, &b| a + b) } #[cfg(test)] mod test { use super::*; use test::Bencher; #[test] ...
#[cfg(test)] use super::args_parser; mod args_parser_tests { #[test] fn get_position() { let item: String = String::from("Hello"); let mut collection: Vec<String> = vec![String::from("Hello"), String::from(" "), String::from("World!")]; let index = sup...
use assert_cmd::prelude::*; use kvs::{KvStore, Result, Storage, Index, LogPointer, FileId}; use predicates::ord::eq; use predicates::str::{contains, is_empty, PredicateStrExt}; use std::process::Command; use tempfile::TempDir; use walkdir::{WalkDir}; // `kvs` with no args should exit with a non-zero code. #[test] fn c...
use parameterized_macro::parameterized; #[parameterized( v = {"a", "b"}, w={1,2} )] fn my_test(v: &str, w: i32) {} fn main() {}
extern crate openldap; use openldap::*; use openldap::errors::*; fn some_ldap_function(ldap_uri: &str, ldap_user: &str, ldap_pass: &str) -> Result<(), LDAPError> { let ldap = try!(RustLDAP::new(ldap_uri)); ldap.set_option(codes::options::LDAP_OPT_PROTOCOL_VERSION, &codes::vers...
extern crate portmidi; extern crate rosc; #[derive(Debug)] pub enum RunError { IoError(::std::io::Error), OscError(rosc::OscError), MidiError(portmidi::Error), NoMidiDeviceAvailable, }
use lazy_static::lazy_static; use std::sync::RwLock; use std::fmt::{Display, Formatter, Result}; #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub struct Ident(pub usize); lazy_static! { static ref WORDS: RwLock<Vec<String>> = RwLock::new(Vec::new()); } impl Display for Ident { fn fmt(&self, f: &mut Forma...
use crate::{sys, text}; use std::ops::Deref; #[allow(dead_code)] pub struct Device { pub(crate) d3d11_device: sys::d3d11::Device, pub d2d_factory: sys::direct2d::Factory, d2d_device: sys::direct2d::Device, d2d_context: sys::direct2d::DeviceContext, pub(crate) dwrite_factory: text::Text, d3d11_c...
// Copyright (c) Facebook, Inc. and its affiliates. use anyhow::{anyhow, Result}; use chrono::prelude::*; use crossbeam::channel::{self, select, Receiver, Sender}; use enum_iterator::IntoEnumIterator; use json; use linux_proc; use log::{debug, error, info, trace, warn}; use procfs; use scan_fmt::scan_fmt; use std::coll...
#[doc = "Reader of register SEQ_NORM_CNT"] pub type R = crate::R<u32, super::SEQ_NORM_CNT>; #[doc = "Writer for register SEQ_NORM_CNT"] pub type W = crate::W<u32, super::SEQ_NORM_CNT>; #[doc = "Register SEQ_NORM_CNT `reset()`'s with value 0"] impl crate::ResetValue for super::SEQ_NORM_CNT { type Type = u32; #[i...
#[doc = "Reader of register CH_AL1_TRANS_COUNT_TRIG"] pub type R = crate::R<u32, super::CH_AL1_TRANS_COUNT_TRIG>; impl R {}
use std::{fmt::Display, marker::PhantomData}; use hecs::{Component, ComponentError, DynamicBundle, Entity, NoSuchEntity, RefMut, World}; use thiserror::Error; #[derive(Debug, Error)] pub struct ResourceTypeAlreadyExists; impl Display for ResourceTypeAlreadyExists { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) ...
/* Copyright ⓒ 2016 rust-custom-derive contributors. Licensed under the MIT license (see LICENSE or <http://opensource.org /licenses/MIT>) or the Apache License, Version 2.0 (see LICENSE of <http://www.apache.org/licenses/LICENSE-2.0>), at your option. All files in the project carrying such notice may not be copied, m...
use dominator::{class, html, Dom}; use futures_signals::signal::{Mutable, SignalExt}; use once_cell::sync::Lazy; use onitama_lib::{in_card, ServerMsg}; pub fn render_card(game: &Mutable<ServerMsg>, card: usize, rotated: bool) -> Dom { static CARD: Lazy<String> = Lazy::new(|| { class! { .style("...
use crate::model::enums::{NationStatus, SubmissionStatus}; use crate::model::{GameData, GameNationIdentifier, Nation, RawGameData}; use crate::snek::{snek_details, SnekGameStatus}; use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt}; use flate2::read::ZlibDecoder; use hex_slice::AsHex; use log::*; use std::error...
//! Species /// Pokemon Species #[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Hash, Debug)] #[derive(serde::Serialize, serde::Deserialize)] pub enum Species { Bulbasaur = 1, Ivysaur = 2, Venusaur = 3, Charmander = 4, Charmeleon = 5, Charizard = 6, Squirtle = 7, Wartortle = 8, Blastoise = 9...
#![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 AccountEntity { #[serde(flatten)] pub entity: Entity, #[serde(default, skip_serializing_if = "Option::i...
extern crate rustc_version; use rustc_version::Channel; fn main() { let version = rustc_version::version_meta(); if version.channel == Channel::Nightly { println!("cargo:rustc-cfg=nightly"); } }
use airmash_protocol::{MobType, PlaneType}; use fnv::FnvHashMap; use std::ops::Index; use std::time::Duration; use std::vec::Vec; use types::*; #[derive(Copy, Clone, Debug, Default)] pub struct HitCircle { pub radius: Distance, pub offset: Position, } #[derive(Debug, Clone)] pub struct PlaneInfo { // Rotation pu...
use serenity::{async_trait, model::gateway::Ready, prelude::*, framework::standard::StandardFramework }; use std::time::Instant; use std::error::Error; use crate::deribit; use crate::deribit::{Instruments, Data}; async fn manage_alerts(ctx: &Context) -> Result<(), Box<dyn Error>> { let mut info = ...
#[doc = "Register `IOPENR` reader"] pub type R = crate::R<IOPENR_SPEC>; #[doc = "Register `IOPENR` writer"] pub type W = crate::W<IOPENR_SPEC>; #[doc = "Field `IOPAEN` reader - IO port A clock enable bit"] pub type IOPAEN_R = crate::BitReader<IOPAEN_A>; #[doc = "IO port A clock enable bit\n\nValue on reset: 0"] #[deriv...
pub mod matric{ pub fn information(){ println!("Student Information"); } pub fn result(){ println!("Result Information"); crate::student::check(); } } fn check(){ println!("Public Method Access"); matric::information(); } mod intermediate{ fn information(){ println!("Access Information"...
#![feature(plugin, box_syntax)] #![allow(unstable)] #[no_link] #[plugin] extern crate dfagen; #[no_link] #[plugin] extern crate lalrgen; use Token::*; #[derive(Debug)] enum Token { Ident(String), IntLit(i64), StringLit(String), Whitespace, Other, Error, Equals, Star, IF, ELSE,...
use core::{ cmp::Ordering, convert::TryInto as _, ops::{ Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Rem, RemAssign, Shl, ShlAssign, Shr, ShrAssign, Sub, SubAssign, }, option::{ Iter, IterMut, }, }; use funty::{ IsInteger, IsSigned, }; /** Marks an integer for checke...
#[doc = "Register `C1EMR3` reader"] pub type R = crate::R<C1EMR3_SPEC>; #[doc = "Register `C1EMR3` writer"] pub type W = crate::W<C1EMR3_SPEC>; #[doc = "Field `MR64` reader - CPU Event mask on Event input x+64"] pub type MR64_R = crate::BitReader<MR64_A>; #[doc = "CPU Event mask on Event input x+64\n\nValue on reset: 0...
#![feature(const_raw_ptr_to_usize_cast)] use crate::{keyboard::{ConvertScanCodeAndPutQueue, GetKeyboardScanCode, IsOutputBufferFull}, pic::{self, SendEOI}, print_string}; pub extern "x86-interrupt" fn divided_by_zero() { CommonExceptionHandler( 0); } pub extern "x86-interrupt" fn debug() { CommonExceptionHandl...
use actix_web::{HttpResponse, Result, web, HttpRequest}; use crate::handlers::pg_pool_handler; use crate::db_connection::PgPool; use crate::models::comment::{Comment, NewComment, Commentlist}; // use crate::handlers::LoggedUser; pub fn index(_user: HttpRequest, pool: web::Data<PgPool>) -> Result<HttpResponse> { le...
extern crate gcc; extern crate regex; use std::process::Command; use std::env; use regex::Regex; fn main() { // 1. Build the object file from source using node-gyp. build_object_file(); // 2. Link the library from the object file using gcc. link_library(); } #[cfg(unix)] fn npm() -> Command { Co...
use crate::database::Database; use crate::errors::Result; use crate::linker::Linker; use crate::settings::Settings; use serde::{Deserialize, Serialize}; use std::cmp::{Ord, Ordering, PartialOrd}; use std::path::{Path, PathBuf}; #[derive(Clone, Debug, Default, Deserialize, Serialize)] pub struct SavePath { pub id: ...
/* * 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 */ /// Series : A metric to submit to Datadog. See [Datadog metrics](https://docs.datadoghq.com/developers/...
use rutie::{AnyException, Object, VM}; pub trait ArgsTreating<R> { fn unwrap_or_rb_raise(self) -> R; } impl<A, E> ArgsTreating<A> for Result<A, E> where A: Object, E: Into<AnyException> + std::fmt::Debug, { fn unwrap_or_rb_raise(self) -> A { match self { Ok(object) => object, ...
//! A module for working with USI protocol in a type-safe way. //! //! USI protocol defines commands sent from either GUIs or engines. //! Detail about USI protocol can be found at <http://shogidokoro.starfree.jp/usi.html>. //! //! # Data types representing commands defined in USI protocol. //! //! `GuiCommand` and `En...
// Copyright (c) 2016 The vulkano 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. All files in the project carrying such // notice may not be co...
use serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize, Debug)] pub struct SearchRecord { pub id: u32, pub score: u32, }
use chess::{Game, Piece, Color, ChessMove, MoveGen, Board, BoardStatus}; use crate::game_printer::to_square; use rand::prelude::*; use std::time::{Duration, Instant}; const MAX_VAL: i32 = 1001; const MIN_VAL: i32 = -1001; fn get_algo(algo: String) -> fn(Board, i32, bool) -> i32 { let stralgo = &*algo; return ...
use std::collections::HashMap; use crate::{SlotId, Stake}; pub type Id = u32; pub type Key = u32; pub type Idx = usize; #[derive(Debug, Clone)] pub struct Participant { pub id:Id, pub key:Key, pub weight:u32, signer_slots: HashMap<SlotId,bool>, } impl Participant { pub fn new(id:Id, key:u32, weig...
#![allow(dead_code)] use std::sync::{Mutex, MutexGuard, Condvar, WaitTimeoutResult}; use std::time::Duration; use std::ops::{Deref, DerefMut}; pub struct Monitor<T: Sized> { mutex: Mutex<T>, cvar: Condvar, } impl<T: Sized> Monitor<T> { pub fn new(val: T) -> Monitor<T> { Monitor { mutex: Mutex:...
/* * RIDB API Additional Functions 0.1 * * The Recreation Information Database (RIDB) provides data resources to citizens, offering a single point of access to information about recreational opportunities nationwide. The RIDB represents an authoritative source of information and services for millions of visitors to...
use battleship::*; use serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize, Debug)] pub struct Game { pub id: String, pub stake: i64, pub current_player_id: String, pub mediator: mediator::Mediator, pub winner_id: String, } #[derive(Serialize, Deserialize, Debug)] pub struct SettledGa...
// Copyright (c) 2016-2017 Chef Software Inc. and/or applicable contributors // // 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 // // Unl...
#[doc = "Writer for register CRYP_K0LR"] pub type W = crate::W<u32, super::CRYP_K0LR>; #[doc = "Register CRYP_K0LR `reset()`'s with value 0"] impl crate::ResetValue for super::CRYP_K0LR { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Write proxy for field `K2...
#![cfg_attr(all(feature = "mesalock_sgx", not(target_env = "sgx")), no_std)] #![cfg_attr(all(target_env = "sgx", target_vendor = "mesalock"), feature(rustc_private))] #[cfg(all(feature = "mesalock_sgx", not(target_env = "sgx")))] #[macro_use] extern crate sgx_tstd as std; use std::prelude::v1::*; ext...
//! # DEIP programming toolkit //! //! - [`Config`](./trait.Config.html) //! - [`Call`](./enum.Call.html) //! //! ## Overview //! //! ## Interface //! //! ### Dispatchable Functions //! //! [`Call`]: ./enum.Call.html //! [`Config`]: ./trait.Config.html // Ensure we're `no_std` when compiling for Wasm. #![cfg_attr(not...
use serde::{Deserialize, Serialize}; /// A constraint parameter in a column definition. #[derive(Clone, Eq, PartialEq, Hash, Debug, Serialize, Deserialize)] pub enum ColumnConstraintKind { // TODO: DEFAULT, CHECK, ... }
//! //! cd C:\Users\むずでょ\OneDrive\ドキュメント\practice-rust\kirimoti\max //! cargo check --example main-4 //! cargo run --example main-4 //! //! [crates.io](https://crates.io/) //! fn main() { let table = vec![ vec![-1, 3, -2, 10] ,vec![16, -15, 9, -7] ,vec![8, -11, 4, 5] ,vec![-6, 9, ...
//! This example showcases how to create multiple Executor instances to run tasks at //! different priority levels. //! //! Low priority executor runs in thread mode (not interrupt), and uses `sev` for signaling //! there's work in the queue, and `wfe` for waiting for work. //! //! Medium and high priority executors ru...
mod backup; mod builder; mod process; pub mod partial; use core::num::Wrapping; use crate::{ cogs::{ ActiveLineageSampler, CoalescenceSampler, DispersalSampler, EmigrationExit, EventSampler, Habitat, ImmigrationEntry, LineageReference, LineageStore, OptionallyPeekableActiveLineageSampler,...
use crate::{connection_status::ConnectionStatus, internal_rpc::InternalRPCHandle, protocol}; pub(crate) struct ConnectionCloser { status: ConnectionStatus, internal_rpc: InternalRPCHandle, } impl ConnectionCloser { pub(crate) fn new(status: ConnectionStatus, internal_rpc: InternalRPCHandle) -> Self { ...
use std::fmt; use std::collections::HashMap; use std::convert::TryFrom; use ansi_term::Colour::{Black, Yellow, White, RGB}; use ansi_term::{Style}; use chrono::{NaiveDate, Datelike, Weekday}; // bold, dimmed, italic, underline, blink, reverse, hidden, strikethrough, on use crate::constants::*; use lazy_static::lazy_...
#![deny( anonymous_parameters, bad_style, missing_copy_implementations, missing_debug_implementations, unused_extern_crates, unused_import_braces, unused_results, unused_qualifications, )] extern crate url; use rust_swagger_validator::swagger_schema::*; use std::path; #[test] fn test_...
use crate::InternSerializeRegistry; use core::{ borrow::Borrow, cmp, fmt, hash, ops::{Deref, Index, Range, RangeFrom, RangeFull, RangeInclusive, RangeTo, RangeToInclusive}, pin::Pin, }; use rkyv::{ ser::Serializer, string::{ repr::{ArchivedStringRepr, INLINE_CAPACITY}, ArchivedSt...
extern crate env_logger; pub fn init() { env_logger::init().unwrap(); } pub fn info(action: &str, message: &str) { info!("action={} {}", action, message); }
#![allow(dead_code)] // 静态方法 // 没有 receiver 参数的方法(第一个参数不是 self 参数的方法)称作"静态方法" // 静态方法可以通过 Type::FunctionName() 的方式调用 // 需要注意的是,即便我们的第一个参数是 Self 相关类型,只要变量名字不是 self, // 就不能使用小数点的语法调用函数 struct T(i32); impl T { // 这是一个静态方法 fn func(this: &Self) { println!("value {}", this.0); } } pub fn learn_static_m...
use super::auto::{AsAny, HasInner, OnFrame, Abstract}; use super::has_native_id::{HasNativeId, HasNativeIdInner}; use super::member::Member; use super::closeable::Closeable; use super::seal::Sealed; use super::window::{NewWindow, Window}; use super::tray::{NewTray, Tray}; use crate::{callbacks, types, ids}; use std::...
use std::time::Duration; const SECOND: std::time::Duration = Duration::new(1, 0); pub struct Timer { duration: Duration, message: Option<String>, } pub type Countdown = Timer; impl Timer { pub fn new(hours: u64, minutes: u64, seconds: u64, message: Option<String>) -> Timer { Timer { d...
extern crate ndarray; use std::collections::HashMap; use ndarray::{Array1, Array2}; #[macro_export] macro_rules! plydata { ($( $key:expr => $val:expr ),+) => {{ let mut map = ::std::collections::HashMap::<String, _>::new(); $( map.insert($key.into(), $val); )+ PlotlyData(map) }}; } pub...
//! JS Engine implemented by [QuickJs](https://crates.io/crates/quick-js). use core::convert::TryInto; use crate::{ error::{Error, Result}, js_engine::{JsEngine, JsValue}, }; /// QuickJS Engine. pub struct Engine(quick_js::Context); impl JsEngine for Engine { type JsValue = Value; fn new() -> Resul...
//! Representation of LV2 UIs. /// Representation of an LV2 UI. #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct UiInfo { // TODO }
//! # 135. 分发糖果 //! https://leetcode-cn.com/problems/candy/ //! 老师想给孩子们分发糖果,有 N 个孩子站成了一条直线,老师会根据每个孩子的表现,预先给他们评分。 //! 你需要按照以下要求,帮助老师给这些孩子分发糖果: //! 每个孩子至少分配到 1 个糖果。 //! 相邻的孩子中,评分高的孩子必须获得更多的糖果。 //! 那么这样下来,老师至少需要准备多少颗糖果呢? //! # 解题思路 //! 采用最少分配原则,每个人至少一个,左右遍历一次进行条件判断 pub struct Solution; impl Solution { pub fn candy(r...
use std::io; pub trait ProblemSolution { fn name(&self) -> &'static str; fn part1(&self) -> io::Result<i64>; fn part2(&self) -> io::Result<i64>; fn exec(&self) -> io::Result<()> { println!("{}::p1 {}", self.name(), self.part1()?); println!("{}::p2 {}", self.name(), self.part2()?); ...
use std::path::PathBuf; // Feels like this might not be the most // robust abstraction, but.. some helpful things // like solidifying where paths are. // Less noise and decent names in code // Could limit to wp #[derive(Debug)] pub struct ProjectItemPaths { pub from_project: ProjectPath, pub full_path: Project...
use crate::common::{self, *}; pub type Frame = AMember<AControl<AContainer<ASingleContainer<AFrame<TestableFrame>>>>>; #[repr(C)] pub struct TestableFrame { base: common::TestableControlBase<Frame>, label: String, label_padding: i32, child: Option<Box<dyn controls::Control>>, } impl<O: cont...
use arrayvec::ArrayString; use serde::{Deserialize, Serialize}; use std::str::FromStr; use thiserror::Error; pub type Username = ArrayString<[u8; 32]>; pub type Password = ArrayString<[u8; 32]>; #[derive(Clone, Copy, Debug, Serialize, Deserialize)] pub struct Account { username: Username, color: Color, } imp...
pub fn find() -> Option<usize> { let target = 1000; for a in 1..(target) { for b in (a)..(target-a) { let c = target - a - b; if a * a + b * b == c * c { return Some(a * b * c); } } } None }
use std::env::var; use std::process::Command; //use std::path::{Path}; fn main() { let manifest_dir = var("CARGO_MANIFEST_DIR").unwrap(); setup(&manifest_dir); // println!("cargo:rustc-link-search={}/../build-win32/dist/cpp", manifest_dir); // println!("cargo:rustc-link-search={}/../build-win32/d...
#![allow(clippy::identity_op)] #![allow(clippy::unusual_byte_groupings)] use std::ops::Shl; #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub enum Size { S32, S64, } #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub struct Register { pub size: Size, pub index: u8, } impl Register { pub fn sf(&self...
use futures_util::AsyncWriteExt; use hreq_h1::Error; mod common; #[async_std::test] async fn broken_chunked() -> Result<(), Error> { let conn = common::serve(|head, mut tcp, _| async move { assert_eq!(head, "GET /path HTTP/1.1\r\n\r\n"); // NB: Malformed chunked. let res = b"HTTP/1.1 200 ...
#![allow(dead_code)] const DEPTH: usize = 4; const WIDTH: usize = 240; const HEIGHT: usize = 360; pub type Color = [u8; DEPTH]; #[derive(Copy, Clone, PartialEq)] pub struct Vec2 { pub x: f32, pub y: f32, } impl Vec2 { pub fn new(x: f32, y: f32) -> Self { Self { x, y } } } #[derive(Copy, Clon...
// Copyright 2017 rust-ipfs-api 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...
extern crate bv; extern crate serde; extern crate serde_json; use common_tree::*; use bv::{BitVec, Bits}; use std::fs::File; use std::io::prelude::*; use std::error::Error; use std::path::Path; use range_min_max::RangeMinMax; pub struct Bp { tree: RangeMinMax } impl BpLoudsCommonTrait for Bp { fn isleaf (&sel...
use std::io::Write; fn main() { let d128 = std::fs::read_to_string("src/d32_impl.rs").unwrap(); // Generate d64.rs let d64 = d128.replace("u32", "u64"); let mut d64_out = std::fs::File::create("src/d64_impl.rs").unwrap(); writeln!( d64_out, "// **NOTE**: THIS FILE IS AUTO-GENERATED...
use std::marker::PhantomData; use std::ops::Add; use super::{Nat, S, Z}; impl Add<Z> for Z { type Output = Z; fn add(self, _rhs: Z) -> Z { self } } impl<N: Nat> Add<Z> for S<N> { type Output = S<N>; fn add(self, _rhs: Z) -> S<N> { self } } impl<N: Nat> Add<S<N>> for Z { ...
pub use handlers::*; mod whisper; pub use self::whisper::WhisperHandler;
// pub mod is_prime; // pub mod problem001; // pub mod problem002; // pub mod problem003; // pub mod problem004; // pub mod problem005; // pub mod problem006; // pub mod problem007; pub mod problem008;
#![allow(dead_code)] use super::{Cpu, Cycles}; use util::bits::Bits as _; #[inline] pub fn internal_multiply_cycles(mut rhs: u32, signed: bool) -> Cycles { // if the most significant bits of RHS are set (RHS is negative), we use !RHS so that we can // just check if they are zero instead to handle both the pos...
use futures_util::future::{select, Either}; use futures_util::{SinkExt, StreamExt}; use std::net::SocketAddr; use std::sync::{Arc, Mutex}; use std::thread; use std::time::Duration; use tokio::net::{TcpListener, TcpStream}; use tokio_tungstenite::accept_async; use tungstenite::{Message, Result}; use ferris_chat::savelo...
fn main() { let (n, a, b) = { let mut line = String::new(); std::io::stdin().read_line(&mut line).unwrap(); let mut ws = line.trim_end().split_whitespace(); let n: u32 = ws.next().unwrap().parse().unwrap(); let a: u32 = ws.next().unwrap().parse().unwrap(); let b: u32 ...
#![recursion_limit="200"] // Begin serde #![cfg_attr(feature = "serde_macros", feature(plugin, custom_derive))] #![cfg_attr(feature = "serde_macros", plugin(serde_macros))] extern crate serde; extern crate serde_json; #[cfg(feature = "serde_macros")] include!("serde_types.in.rs"); #[cfg(feature = "serde_codegen"...
use totsu::prelude::*; use totsu::MatBuild; use totsu::totsu_core::solver::{Operator, LinAlg}; use super::La; use super::laplacian::Laplacian; // pub struct ProbOpA { x_sz: usize, t_sz: usize, lap: Laplacian, one: MatBuild<La>, } impl ProbOpA { pub fn new(width: usize, heigh...