text
stringlengths
8
4.13M
use diesel::{PgConnection, RunQueryDsl}; use crate::models::Address; use crate::schema::physical_addresses; #[derive(Debug, PartialEq, Clone, Default, Insertable)] #[table_name = "physical_addresses"] pub struct AddressFactory { pub post_office_box: Option<String>, pub extension: Option<String>, pub stree...
#![cfg_attr(feature = "unstable", feature(test))] // Launch program : cargo run --release < input/input.txt // Launch benchmark : cargo +nightly bench --features "unstable" /* Benchmark results: running 5 tests test tests::test_part_1 ... ignored test tests::test_part_2 ... ignored test bench::bench_...
use std::io::{BufReader, Read}; use thiserror::Error; use crate::{ filler::{decode_fillers, Filler, FillersDecodeError}, internal::{CelesteIo, Lookup, LookupRef, Node, NodeReadError, NonRleString, StringReadError}, screen::{decode_screens, ScreensDecodeError}, Screen, }; #[derive(Debug)] pub struct C...
use super::Twzobj; use std::sync::Arc; pub type ObjID = u128; pub fn objid_from_parts(upper: u64, lower: u64) -> ObjID { ((upper as ObjID) << 64) | lower as ObjID } pub fn objid_parse(s: &str) -> Option<ObjID> { let mut s = s.trim(); let radix = 16; if s.contains(":") { /* parse upper and lower separately */ ...
#[cfg(target_os = "windows")] pub use windows::*; #[cfg(target_os = "linux")] pub use linux::*; use ash::vk::ExtensionProperties; use std::ffi::CStr; pub fn check_extensions_support( required: &[&'static CStr], supported: &[ExtensionProperties], ) -> Result<(), Vec<&'static str>> { let supported: Vec<_> ...
use crate::block::Block; use crate::transaction::{CellOutput, OutPoint, Transaction}; use crate::Capacity; use fnv::{FnvHashMap, FnvHashSet}; use numext_fixed_hash::H256; use serde_derive::{Deserialize, Serialize}; #[derive(Clone, Eq, PartialEq, Debug, Default, Deserialize, Serialize)] pub struct CellMeta { #[serd...
/// This file defines data transfer objects. use serde::{Deserialize, Serialize}; /// The information required to display a game in an overview table. #[derive(Serialize, Deserialize)] pub struct GameHeader { pub id: i64, pub description: String, pub members: Vec<Member>, } /// The information required to...
#![no_std] #![feature(start)] #![no_main] use ferr_os_librust::syscall; extern crate alloc; use alloc::string::String; use alloc::vec::Vec; #[no_mangle] pub extern "C" fn _start(heap_address: u64, heap_size: u64, _args: u64) { unsafe { ferr_os_librust::allocator::init(heap_address, heap_size); le...
//! A buffer is a memory location accessible to the video card. //! //! The purpose of buffers is to serve as a space where the GPU can read from or write data to. //! It can contain a list of vertices, indices, uniform data, etc. //! //! # Buffers management in glium //! //! There are three levels of abstraction in gl...
use crate::packets::{ open::OpenMessage, keepalive::KeepaliveMessage, update::UpdateMessage, }; #[derive(PartialEq, Eq, Debug, Clone, Hash)] pub enum Event { ManualStart, TcpConnectionConfirmed, BgpOpen(OpenMessage), KeepAliveMsg(KeepaliveMessage), UpdateMsg(UpdateMessage), Establis...
//! Internal attributes of the form `#[auto_impl(name(...))]` that can be //! attached to trait items. use proc_macro2::{Delimiter, TokenTree}; use proc_macro_error::{abort, emit_error}; use syn::{ spanned::Spanned, visit_mut::{visit_item_trait_mut, VisitMut}, Attribute, Meta, TraitItem, }; use crate::pro...
use std::ops::{Add, RangeBounds, Sub}; use crate::{ grid::config::Entity, grid::records::{ExactRecords, Records}, settings::object::{cell::EntityOnce, Object}, }; use super::util::bounds_to_usize; /// Row denotes a set of cells on given rows on a [`Table`]. /// /// [`Table`]: crate::Table #[derive(Debug)...
extern crate capnp; extern crate capnp_rpc; extern crate futures; extern crate tokio; extern crate rpc_fun; use std::net::SocketAddr; // use capnp::capability::Promise; // use capnp::Error; use capnp_rpc::twoparty::VatNetwork; use capnp_rpc::{rpc_twoparty_capnp, RpcSystem}; use futures::{Future, Stream}; use tokio::...
use std::convert::TryFrom; use std::convert::TryInto; use std::f64; use std::u32; use std::u8; use geo::polygon; use geo_types::{Geometry, Polygon}; use catalog::AsFeatureCollection; use rocket::http::Status; use serde_json::{to_string}; use rocket::{State, response::content::Json}; use rocket::response::status::BadReq...
extern crate seahash; extern crate jump_consistent_hash; use jump_consistent_hash::slot; #[test] #[ignore] fn simulate_rebalance() { let mut n = 1; for i in 1..10 { simulate(" mod", n, n + 1, bymod); simulate("slot", n, n + 1, slot); n += i; } } fn bymod(key: u64, len: usize) -> u3...
use std::collections::HashMap; use std::ffi::{CStr, CString}; use std::path::Path; use std::{mem, ptr}; use worker::{ffi, ComponentId, Connection, EntityId}; pub struct SnapshotOutputStream { pointer: *mut ffi::Worker_SnapshotOutputStream, _vtable: Box<ffi::Worker_ComponentVtable>, } impl Drop for SnapshotOut...
#![allow(clippy::unreadable_literal)] //! Gruvbox //! <https://github.com/morhetz/gruvbox> use iced::color; use crate::gui::styles::types::custom_palette::{CustomPalette, PaletteExtension}; use crate::gui::styles::types::palette::Palette; /// Gruvbox (night style) pub(in crate::gui::styles) fn gruvbox_dark() -> Cus...
#[derive(Clone, Copy, Debug, PartialEq)] pub enum Primitive { Boolean(bool), Number(f64), } impl From<bool> for Primitive { fn from(boolean: bool) -> Self { Self::Boolean(boolean) } } impl From<f64> for Primitive { fn from(number: f64) -> Self { Self::Number(number) } }
#[doc = "Register `HDP1R_PRG` reader"] pub type R = crate::R<HDP1R_PRG_SPEC>; #[doc = "Register `HDP1R_PRG` writer"] pub type W = crate::W<HDP1R_PRG_SPEC>; #[doc = "Field `HDP1_STRT` reader - HDPL barrier start set in number of 8-Kbyte sectors"] pub type HDP1_STRT_R = crate::FieldReader; #[doc = "Field `HDP1_STRT` writ...
use bevy::{app::AppExit, prelude::*}; use big_brain::{pickers, prelude::*}; #[test] fn steps() { println!("steps test"); App::new() .add_plugins(MinimalPlugins) .add_plugin(BigBrainPlugin) .init_resource::<GlobalState>() .add_startup_system(setup) .add_system_to_stage(Co...
use actix_web::{http::StatusCode, HttpResponse}; use serde::{Deserialize, Serialize}; use std::string::ToString; #[derive(sqlx::FromRow, Debug, Serialize, Deserialize)] pub struct FileResponse { pub name: String, pub link: String, } #[derive(Debug, Serialize, Deserialize, Display)] pub enum Status { SUCCES...
use crate::drivers::fe310_g002::{AONDriver, CLINTDriver, SPIDriver}; use register::{mmio::*, register_bitfields, register_structs}; register_bitfields! { u32, /// Ring Oscillator Configuration and Status HFROSCCFG [ /// Ring Oscillator Divider Register HFROSCDIV OFFSET(0) NUMBITS(6) [], ...
use std::iter::{Cycle, Peekable}; use tensorflow_protos::types::DataType; use std::fmt::Display; use codegen as cg; use protobuf; pub(crate) fn escape_keyword(name: &str) -> String { match name { "as" => format!("{}_", name), "break" => format!("{}_", name), "const" => format!("{}_", name),...
use crate::switch::ToCKBCellDataTuple; use crate::utils::config::{CKB_UNITS, PRE_UNDERCOLLATERAL_RATE, XT_CELL_CAPACITY}; use crate::utils::transaction::{get_price, get_sum_sudt_amount, is_XT_typescript, XChainKind}; use crate::utils::types::{Error, ToCKBCellDataView}; use ckb_std::ckb_constants::Source; use ckb_std::d...
// implements the IO display submodule pub fn show(/*image: &Image*/ window_name: &str) { } pub fn refresh() { // refresh image windows // don't sleep any threads. Not equivalent to wait(0) } pub fn wait(time: u128) { // refresh image windows if time > 0 { // sleep current thread for 'time' } els...
use menu::giphy::{GiphyPagination, GiphyResponse}; use serenity::framework::standard::{macros::command, Args, CommandError, CommandResult}; use serenity::model::channel::Message; use serenity::prelude::*; #[command] #[aliases("gif")] #[usage = "[keyword]"] async fn giphy(context: &Context, message: &Message, args: Arg...
use byteorder::{ByteOrder, LittleEndian}; use std::ops::{Deref, DerefMut}; /// Default, 64kb memory bus pub struct MemoryBus { ram: [u8; 1024 * 64], } impl MemoryBus { pub fn new() -> MemoryBus { MemoryBus { ram: [0; 1024 * 64] } } pub fn write_byte(&mut self, addr: u16, byte: u8) { ...
use pyo3::prelude::*; use pyo3::{PyObjectProtocol, exceptions}; // use pyo3::class::gc::{PyGCProtocol, PyVisit, PyTraverseError}; use std::fmt; #[pyclass] #[derive(Clone)] pub struct SeqMatrix { pub data: Vec<String>, rows: usize, cols: usize, } pub fn new_seqmatrix(sequences: Vec<String>) -> Result<SeqMa...
use crate::ui::color::Color; #[derive(Default)] pub struct Animation { start: (f64, f64), end: (f64, f64), start_time: i64, end_time: i64, } #[derive(Default)] pub struct Cursor { /// Position, (row, col). pub pos: Option<(f64, f64)>, /// Flag for disabling the movement animation. pub ...
extern crate num_bigint; use std::io::{self, Read}; use num_bigint::{BigUint}; fn main() -> io::Result<()> { // parsing gpg privatekey let mut buffer = Vec::new(); io::stdin().read_to_end(&mut buffer)?; let ns = &buffer[11..(11+128)]; let es = &buffer[(11+128+2)..(11+128+2+3)]; let n = BigUin...
#![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 ManagedPrivateEndpointListResponse { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Ve...
mod common; #[test] #[cfg(feature = "devkit-arm-tests")] pub fn test_swi() { let (cpu, _mem) = common::execute_arm( "swi", " b main b undefined_handler b swi_handler main: mov r0, #4 ldr r3, =return_point swi #6 r...
//! Manage the target observer //! //! The interogation that lading does of the target sub-process is intentionally //! limited to in-process concerns, for the most part. The 'inspector' does //! allow for a sub-process to do out-of-band inspection of the target but //! cannot incorporate whatever it's doing into the c...
/*! ```rudra-poc [target] crate = "arenavec" version = "0.1.1" [report] issue_url = "https://github.com/ibabushkin/arenavec/issues/1" issue_date = 2021-01-12 rustsec_url = "https://github.com/RustSec/advisory-db/pull/815" rustsec_id = "RUSTSEC-2021-0040" [[bugs]] analyzer = "UnsafeDataflow" bug_class = "PanicSafety" ...
pub mod response; use crate::config::MailConfig; use rocket::State; use rocket::response::content::Xml; use serde::Serialize; #[get("/.well-known/autoconfig/mail/config-v1.1.xml?<emailaddress>")] pub fn autoconfig_wellknown(config: &State<MailConfig>, emailaddress: String) -> Xml<String> { autoconfig(config, emai...
use ::*; pub fn set_element_css_size(target: Selector, size: (f64, f64)) -> HtmlResult<()> { let result = unsafe { emscripten_set_element_css_size( selector_as_ptr!(target), size.0 as c_double, size.0 as c_double, ) }; match parse_html_result(result) { ...
/* * 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 */ /// UsageSyntheticsBrowserResponse : Response containing the number of Synthetics Browser tests run for ...
extern crate reqwest; use reqwest::{header, blocking::multipart}; fn main() -> Result<(), Box<dyn std::error::Error>> { let mut headers = header::HeaderMap::new(); headers.insert("Authorization", "Bearer ACCESS_TOKEN".parse().unwrap()); headers.insert("X-Nice", "Header".parse().unwrap()); let form = m...
use mcfg::shared::builders::Builder; use mcfg::shared::packages::builders::{PackageBuilder, PackageSetBuilder}; use mcfg::shared::{Name, PackageSet}; use pretty_assertions::assert_eq; use std::collections::HashMap; use std::path::PathBuf; use std::str::FromStr; #[test] fn test_minimal_package_set() { let package_s...
pub struct Enumeration { enumerate_all: bool, enumerate_oks: bool, all: Option<usize>, oks: Option<usize>, } impl Enumeration { pub fn new(enumerate_all: bool, enumerate_oks: bool) -> Enumeration { Enumeration { enumerate_all, enumerate_oks, all: None, ...
use clap::{Arg, App}; #[derive(Debug, PartialEq)] pub enum Algo { Gradient, Ols } #[derive(Debug, PartialEq)] pub struct Config { pub file: String, pub algo: Algo, } impl Config { pub fn new() -> Self { let matches = App::new("learn") .version("0.1.0") .author("Simon Gala...
use sequence::{Sequence, MultiCache}; use buffer::Buffer; mod half; mod head; use self::half::{Half, AdvanceError}; use self::head::{Head, SenderHead, SenderHalf, ReceiverHead, ReceiverHalf}; #[derive(Debug)] pub struct Sender<S: Sequence, R: Sequence, T> { half: Option<SenderHalf<S, R, T>>, } #[derive(Debug)]...
#[doc = "Reader of register DDRPHYC_BISTGSR"] pub type R = crate::R<u32, super::DDRPHYC_BISTGSR>; #[doc = "Reader of field `BDONE`"] pub type BDONE_R = crate::R<bool, bool>; #[doc = "Reader of field `BACERR`"] pub type BACERR_R = crate::R<bool, bool>; #[doc = "Reader of field `BDXERR`"] pub type BDXERR_R = crate::R<boo...
mod text; mod util; use instant::Instant; use wasm_bindgen::prelude::*; use yew::events::IKeyboardEvent; use yew::{html, Component, ComponentLink, Html, ShouldRender}; #[wasm_bindgen(module = "/module.mjs")] extern "C" { type Chart; #[wasm_bindgen(constructor)] fn new() -> Chart; #[wasm_bindgen(meth...
extern crate asn1_der; use ::asn1_der::{ Asn1DerError, DerObject, DerTag, DerValue }; const RANDOM: &[u8] = include_bytes!("rand.dat"); #[test] fn test_ok() { // Test (de-)serialization fn test((bytes, object): &(&[u8], DerObject)) { // Test deserialization let deserialized = DerObject::deserialize(bytes.iter(...
use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use cosmwasm_std::{ HumanAddr, }; #[derive(Serialize, Deserialize, JsonSchema)] #[serde(rename_all = "snake_case")] pub struct InitMsg { pub poll: String, pub duration: u64, pub early_results_allowed: bool, } #[derive(Serialize, Deseriali...
#![recursion_limit = "256"] use assert_json_diff::assert_json_eq; use chrono::{DateTime, NaiveDateTime, Utc}; use kube_derive::CustomResource; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use std::collections::HashMap; // See `crd_derive_schema` example for how the schema generated from this struct ...
// #![warn(clippy::all, clippy::pedantic, clippy::nursery, clippy::cargo)] // #![allow(clippy::missing_const_for_fn)] // #![allow(clippy::multiple_crate_versions)] // #![allow(clippy::missing_errors_doc)] // #![allow(clippy::module_name_repetitions)] #[macro_use] extern crate eyre; #[macro_use] extern crate clap; #[ma...
use super::work::Work; use super::*; use enum_map::Enum; use spin::RwLock; use std::cmp; use std::collections::BinaryHeap; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::sync::{Arc, Condvar, Mutex}; /// A unique work-packet id for each instance of work-packet #[derive(Eq, PartialEq, Clone, Copy)] s...
use std::fs::File; use std::io::BufWriter; use std::path::Path; const BYTES_PER_PIXEL: u32 = 3; pub struct Bitmap { pub width: u32, pub height: u32, pub pitch: usize, pub pixels: Vec<u8>, } pub struct Font<'a> { pub bitmap: Bitmap, pub charmap: Vec<&'a str>, pub character_width: u32, ...
//! Directly plug a `main` symbol instead of using `#[entry]` #![deny(warnings)] #![no_main] #![no_std] extern crate cortex_m_rt as rt; extern crate panic_halt; #[no_mangle] pub unsafe extern "C" fn main() -> ! { loop {} }
mod map; mod tag; mod alt; #[cfg(test)] mod alt_tests; pub use map::map; pub use tag::tag; pub use alt::alt;
#![cfg(feature = "bench")] #![feature(test)] #![allow(non_snake_case)] #[macro_use] extern crate jsontests_derive; extern crate jsontests; extern crate test; #[derive(JsonTests)] #[directory = "jsontests/res/files/vmPerformance"] #[test_with = "jsontests::util::run_test"] #[bench_with = "jsontests::util::run_bench"] ...
use std::fs::File; use std::io::prelude::*; use yaml_rust::YamlLoader; pub struct MeshServerOptions { pub host: String, pub port: u16, pub meta_location: String, pub volume_urls: Vec<String>, pub replication: u16, } impl MeshServerOptions { pub fn new(config_path: &str) -> Result<MeshServerOpt...
#![feature(simd)] #[simd] #[derive(Clone, Copy, Debug)] #[allow(non_camel_case_types)] struct f32x3(f32, f32, f32); fn main() { let a = f32x3(1.0, 2.0, 3.0); let b = f32x3(0.5, 1.5, 2.5); let c = a - b; println!("{:?}", c); }
use crate::proc_macro::TokenStream; use quote::quote; use syn::{parse_macro_input, DeriveInput}; pub(crate) fn expand(input: TokenStream) -> TokenStream { let input = parse_macro_input!(input as DeriveInput); let struct_name = &input.ident; let trait_root_path = crate::root_path(&input); // split gene...
pub mod active_version; pub mod active_versions; pub mod constraint_kind; pub mod constraints; pub mod id; pub mod inactive_version; pub mod repository; pub mod version_number; use crate::entity::Entity; use apllodb_storage_engine_interface::ColumnDataType; use constraints::VersionConstraints; use id::VersionId; use s...
use sudo_test::{Command, Env, TextFile}; use crate::Result; #[test] fn it_works() -> Result<()> { let env = Env("").build()?; Command::new("su") .args(["-c", "true"]) .output(&env)? .assert_success()?; let output = Command::new("su").args(["-c", "false"]).output(&env)?; asse...
// vim: shiftwidth=2 use std::fs::OpenOptions; use std::io::Write; use std::process::Command; use crate::keys::Layout; fn convert_io_error<T>(whats_happening: &str, res: Result<T, std::io::Error>) -> Result<T, String> { match res { Ok(t) => Ok(t), Err(e) => Err(format!("Error {}: {}", whats_happening, e)) ...
use std::io::{self, Stdout, stdout, stdin}; use termion::{TermRead, IntoRawMode, RawTerminal}; use super::*; /// The default for `Context.word_fn`. pub fn get_buffer_words(buf: &Buffer) -> Vec<(usize, usize)> { let mut res = Vec::new(); let mut word_start = None; let mut just_had_backslash = false; ...
use std::fs; fn main() { // Read input file let contents = fs::read_to_string("input.txt").expect("Failed reading input file"); // Challenge1 let count1: usize = contents .split("\n\n") .map(|x| calc_group1(x)) .sum(); println!("Challenge1: {}", count1); // Challenge2 ...
use serde::Deserialize; use common::error::Error; use common::event::EventPublisher; use common::result::Result; use crate::domain::publication::{Image, Page, PublicationId, PublicationRepository}; #[derive(Deserialize)] pub struct PageDto { images: Vec<String>, } #[derive(Deserialize)] pub struct UpdatePagesCo...
use std::collections::HashMap; const START: i32 = 245182; const END: i32 = 790572; fn digits(n: i32) -> Vec<i32> { let mut digits = Vec::<i32>::new(); assert!(0 <= n && n < 1000000); let mut rest = n; for _ in 0..6 { digits.push(rest % 10); rest /= 10; } digits.reverse(); d...
// use std::collections::HashMap; // use std::collections::HashSet; use std::io::{self}; fn main() -> io::Result<()> { let f = "test.txt"; // let f = "input.txt"; let vec: Vec<String> = std::fs::read_to_string(f)? .lines() .map(|x| x.to_string()) .collect(); let vec: Vec<Vec<c...
#[derive(Debug, Serialize, Deserialize)] pub struct Claims { pub sub: String, pub exp: i64, }
use std::env; use std::fs::File; use std::io::Write; use std::path::Path; fn implement_tensor_construction() { fn implement_macro(supported_types: &[(&str, &str)], f: &mut File) { f.write_all(b" /// Populate either known size tensor or populate a /// tensor then derive the size based on pop...
fn main() { let name:&str="Ricky"; let address:&str = "Tangerang City"; let hobby:&str = "sports and music"; println!("my name : {} im from :{}, my hobby : {}",name,address,hobby); }
use std::fmt; #[derive(Clone)] struct Trouble { number: u32, } impl Trouble { fn new(number: u32) -> Trouble { Trouble { number: number, } } fn get_number(&self) -> u32 { self.number } } impl fmt::Display for Trouble { fn fmt(&self, f: &mut fmt::Formatter)...
use crate::db::users::User; use crate::routes::json_generic::JsonGeneric; use rocket::response::status::BadRequest; use rocket_contrib::json::Json; // Register a new device #[post("/", format = "json", data = "<request_data>")] pub fn register(mut request_data: Json<User>) -> Result<Json<User>, BadRequest<Json<JsonGen...
#[doc = "Register `APB1RSTR2` reader"] pub type R = crate::R<APB1RSTR2_SPEC>; #[doc = "Register `APB1RSTR2` writer"] pub type W = crate::W<APB1RSTR2_SPEC>; #[doc = "Field `LPUART1RST` reader - Low-power UART 1 reset"] pub type LPUART1RST_R = crate::BitReader<LPUART1RST_A>; #[doc = "Low-power UART 1 reset\n\nValue on re...
use crate::*; #[test] fn simple() { let vm = VM::new(); assert_eq!("nil", format!("{}", vm.wrap(Object::Nil))); assert_eq!("#undefined", format!("{}", vm.wrap(Object::Undef))); assert_eq!("#t", format!("{}", vm.wrap(Object::True))); assert_eq!("#f", format!("{}", vm.wrap(Object::False))); asse...
use amethyst::ecs::{Entity, ReadStorage}; use crate::components::Name; pub(crate) fn get_name<'s>(entity: Entity, default: &'s str, name_storage: &'s ReadStorage<'s, Name>) -> &'s str{ match name_storage.get(entity) { Some(name) => name.name(), _ => default } }
extern crate pythonvm; use std::path::PathBuf; use std::env; use pythonvm::{MockEnvProxy, PyResult, run_file}; #[test] fn test_hello_world() { let mut reader: &[u8] = b"\xee\x0c\r\n\xb0\x92\x0fW\x15\x00\x00\x00\xe3\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00@\x00\x00\x00s\x0e\x00\x00\x00e\x00\...
use crate::neuron::activations::Activation; use ndarray::Array1; pub fn tanh_activation(transfer: &Array1<f32>) -> Array1<f32> { transfer.map(|&x| (f32::exp(x) - f32::exp(-x)) / (f32::exp(x) + f32::exp(-x))) } pub fn tanh_derivative(transfer: &Array1<f32>) -> Array1<f32> { 1. - tanh_activation(transfer).map(|...
use crate::command_prelude::*; use cargo::ops; pub fn cli() -> App { subcommand("login") .about( "Save an api token from the registry locally. \ If token is not specified, it will be read from stdin.", ) .arg_quiet() .arg(Arg::new("token")) .arg(opt...
pub mod command_is_executing; pub mod errors; pub mod input; pub mod install; pub mod ipc; pub mod os_input_output; pub mod pty_bus; pub mod screen; pub mod utils; pub mod wasm_vm; use std::cell::RefCell; use std::path::PathBuf; use std::sync::mpsc; use std::thread; use std::{collections::HashMap, fs}; use std::{ ...
use std::collections::BTreeMap; pub fn transform(h: &BTreeMap<i32, Vec<char>>) -> BTreeMap<char, i32> { let mut output = BTreeMap::new(); for (score, vector) in h { for iter in vector { let mut char = iter.clone(); char.make_ascii_lowercase(); output.insert(char , *...
use std::collections::VecDeque; pub struct Snake<V, I> { pub radius: usize, pub state: VecDeque<V>, pub iter: I, }
use std::collections::{HashMap, VecDeque}; use crate::{ abstract_types::ImmutableSchemaAbstractTypes, version::id::VersionId, vtable::id::VTableId, }; use super::{vrr_entries_in_version::VrrEntriesInVersion, vrr_entry::VrrEntry}; /// Sequence of VrrEntry. #[derive(Clone, PartialEq, Hash, Debug, new)] pub struct ...
mod assets; mod dex_pallet; mod dex_xcmp; mod parachains; mod token_dealer; #[cfg(test)] mod test { use super::*; use codec::{Decode, Encode}; use sp_core::crypto; use sp_core::crypto::Ss58Codec; use sp_keyring::AccountKeyring; use sp_std::convert::TryInto; use std::time::Duration; use ...
use std::{ collections::HashMap, fs, path::{Path, PathBuf}, }; use kdl::{KdlDocument, KdlError, KdlIdentifier, KdlValue}; use miette::IntoDiagnostic; #[test] fn spec_compliance() -> miette::Result<()> { let input = PathBuf::from(env!("CARGO_MANIFEST_DIR")) .join("tests") .join("test_ca...
// Undo rename from Cargo.toml extern crate serde_crate as serde; use serde::{ de::{Deserialize, Deserializer}, ser::{Error as _, Serialize, Serializer}, }; use crate::JsOption; impl<'de, T> Deserialize<'de> for JsOption<T> where T: Deserialize<'de>, { /// Deserialize a `JsOption`. /// /// Th...
use std::collections::{HashMap, HashSet}; use std::str::FromStr; use crate::util::lines_from_file; pub fn day8() { println!("== Day 8 =="); let input = lines_from_file("src/day8/input.txt"); let a = part_a(&input); println!("Part A: {}", a); let b = part_b(&input); println!("Part B: {}", b); }...
use anyhow::{format_err, Error}; use libxml::parser::Parser; use libxml::tree::{self, Document, NodeType}; use libxml::xpath::Context; use std::{fmt, ops::Deref, rc::Rc}; #[derive(Debug)] pub enum Value { Element(Vec<Node>), Text(Vec<String>), None, } impl Value { pub fn into_element(self) -> Option<V...
mod components; mod raw_terminal_backend; mod ui; mod ui_state; pub use components::*; pub use raw_terminal_backend::*; pub use ui::*; pub use ui_state::*;
#![crate_name = "document"] #![feature(macro_rules)] use std::fmt; use std::rc::{Rc,Weak}; use std::cell::RefCell; use std::collections::hashmap::HashMap; // FIXME: Parents need to be weakref! // TODO: See about removing duplication of child / parent implementations. // TODO: remove clone from inner? // children // ...
use specs::{self, Component}; use components::InitFromBlueprint; #[derive(Clone, Debug, Deserialize)] pub enum Renderable { Shape(Shape), } #[derive(Clone, Debug, Deserialize)] pub struct Shape { pub width: u32, pub height: u32, pub color: [f32; 3], } impl Renderable { pub fn new_shape(width: u3...
#[cfg(test)] #[macro_use] extern crate serial_test; #[macro_use] extern crate log; use actix_web::{guard, middleware, web, App, HttpServer}; use std::env; mod controller; mod error; mod service; #[cfg(test)] mod test_util; fn get_address() -> String { match env::var("ADDRESS") { Ok(value) => value, ...
//! Argument parsing and checking. //! use libR_sys::*; //use crate::robj::*; use crate::robj::Robj; /// Convert a list of tokens to an array of tuples. #[macro_export] macro_rules! push_args { ($args: expr, $name: ident = $val : expr) => { $args.push((stringify!($name), Robj::from($val))); }; ($a...
use std::io::prelude::*; use std::net::{TcpStream,TcpListener,Ipv4Addr}; pub fn chat_server(){ let ip=Ipv4Addr::new(127,0,0,1); let port = 3090; let tcp_s=TcpListener::bind((ip,port)).unwrap(); for stream in tcp_s.incoming(){ let mut stream= stream.unwrap(); let mut buffer=[0;10...
//! Create options for [parse_opts](super::parse_opts). use super::malformed_html_handlers::{ErrorMismatchedTagHandler, MismatchedTagHandler}; /// Options for [parse_opts](super::parse_opts). pub struct ParseOptions { /// Defines the method for handling an end tag that doesn't match the currently opened tag. ...
use std::f64::consts::PI; #[allow(dead_code)] pub fn wspace(dt: f64, n: usize) -> Vec<f64> { let mut w = vec![0.0_f64; n]; for (i, w_in) in w.iter_mut().enumerate().take((n - 1) / 2) { *w_in = 2. * PI * (i as f64) / (dt * (n as f64)); } for (i, w_in) in w.iter_mut().enumerate().take(n).skip((n ...
use proc_macro2::{Span, TokenStream}; use syn; pub(crate) fn enum_count_inner(ast: &syn::DeriveInput) -> TokenStream { let n = match ast.data { syn::Data::Enum(ref v) => v.variants.len(), _ => panic!("EnumCount can only be used with enums"), }; // Used in the quasi-quotation below...
use super::{socket::Socket, DataService, Error}; use crate::command::device_data_security::{types::*, *}; use atat::atat_derive::AtatLen; use embedded_time::Clock; use heapless::{ArrayLength, Bucket, Pos}; use serde::{Deserialize, Serialize}; #[derive(Debug, Clone, Copy, Eq, PartialEq, Serialize, Deserialize, AtatLen)...
use crate::camera::{Camera, CameraConfig}; use crate::color::color; use crate::hittable::{ box3d::Box3D, bvh::BvhNode, constant_medium::ConstantMedium, hittable_list::HittableList, rect::{XyRect, XzRect, YzRect}, rotate::RotateY, translate::Translate, Hittables, }; use crate::material::{...
use super::*; use octocrab::models::{issues, User}; use reqwest::Url; use serde::*; type DateTime = chrono::DateTime<chrono::Utc>; // milestoned event should include only title // See: https://docs.github.com/en/developers/webhooks-and-events/events/issue-event-types#milestoned #[derive(Debug, Clone, Hash, Eq, Partia...
pub fn is_armstrong_number(num: u32) -> bool { let mut n = num; let mut digits = Vec::new(); while n > 0 { digits.push(n % 10); n /= 10; } let exponent = digits.len() as u32; let digitsum = digits.iter().map(|n| n.pow(exponent)).sum(); num == digitsum }
use crate::common::*; test! { name: expected_keyword, justfile: "foo := if '' == '' { '' } arlo { '' }", stderr: " error: Expected keyword `else` but found identifier `arlo` | 1 | foo := if '' == '' { '' } arlo { '' } | ^^^^ ", status: EXIT_FAILURE, } test! { ...
/* * 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 common::*; use event::{WindowSettings, EventIterator, EventSettings}; use event_handler::handle_event; use sdl2_window::*; use shader_version::opengl::*; use state::App; pub fn main() { debug!("starting"); let mut window = Sdl2Window::new( OpenGL_3_3, WindowSettings { title: "playform".to_string...