text
stringlengths
8
4.13M
use std::process::{Command, Stdio}; use sys_info::os_type; pub fn up() -> String { if os_type().unwrap() != "Linux" { let output = "up: unsupported"; // ill find a better way one day output.to_string() } else { let uptime = Command::new("uptime") .arg("-p") ...
extern crate serialize; use serialize::base64::{ToBase64, MIME}; use serialize::hex::{FromHex, ToHex}; use std::ops::BitXor; //Tuple struct used for a newtype struct XorVect(Vec<u8>); impl BitXor<XorVect, Vec<u8>> for XorVect { fn bitxor(&self, rhs: &XorVect) -> Vec<u8> { let &XorVect(ref left) = self; ...
//! //! Palindrome Number //! //! https://leetcode.com/problems/palindrome-number/ //! //! Determine whether an integer is a palindrome. //! //! An integer is a palindrome when it reads the same backward as forward. //! //! **Example 1:** //! ```text //! Input: 121 //! Output: tru //! ``` //! //! **Example 2:** //! `...
pub mod elf { #[cfg(test)] use proptest_derive::Arbitrary; #[repr(u32)] #[derive(Debug, PartialEq, PartialOrd, Clone, Copy, Hash, Eq)] #[cfg_attr(test, derive(Arbitrary))] pub enum Race { Dark = 1, High = 2, } #[repr(u32)] #[derive(Debug, PartialEq, PartialOrd, Clon...
use std::fmt; #[derive(Debug, Copy, Clone)] pub struct Align(usize); #[derive(Debug)] pub struct AlignErr; impl fmt::Display for AlignErr { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str("invalid alignment value") } } impl Align { pub fn new(x: usize) -> Result<Self, AlignErr...
use std::collections::*; use std::any::*; use crate::Application; use super::Event; /// an event-responding system, that operates on entities /// and their components. it's convention that systems /// are prefixed with an `S`. all the implementation of /// the `Systems` trait does is the `register` method, where /// ...
extern crate libc; extern crate snips_nlu_ffi; use snips_nlu_ffi::{NLURESULT, Opaque}; #[doc(hidden)] #[macro_export] macro_rules! export_c_symbol { ($alias:ident, fn $name:ident($( $arg:ident : $type:ty ),*) -> $ret:ty) => { #[no_mangle] pub extern "C" fn $alias($( $arg : $type),*) -> $ret { ...
pub mod system; pub mod files;
use buffer::CapacityError; use common::num::BeU16; use common::pretty; use error::Error; use gamenet_common::msg::AddrPackedSliceExt; use gamenet_common::msg::int_from_string; use gamenet_common::msg::string_from_int; use packer::Packer; use packer::Unpacker; use packer::Warning; use packer::sanitize; use packer::with_...
use crate::controller::il0371::*; use crate::controller::display_connector::{DisplayConnector, Result}; use crate::controller::gd7965::GD7965; use crate::display::EPaperDisplay; pub struct EPaper75TriColour<T : DisplayConnector> { controller: IL0371<T>, pub width: u16, pub height: u16, } impl<T: Display...
use super::{DoublyLinkedBinaryTree, Link, Node, NodePosi}; use crate::ch4::{ BinTree, BinTreeCursor, BinTreeCursorMut, MoveParentBinTree, MoveParentCursor, MoveParentCursorMut, }; /// 不可变游标. /// # Safety /// 游标类型的安全性和正确性关键在于以下几个不变式: /// /// 1. 保持树的基本不变式: /// 1) `root`指针非空,所指结点存在,且根结点(若存在)是它的左孩子(有根性). /// ...
use failure::Fail; use futures::Future; use hyper::Method; use stq_http::client::HttpClient; use stq_routes::model::Model as StqModel; use stq_routes::service::Service as StqService; use stq_types::*; use super::{ApiFuture, Initiator}; use config; use errors::Error; use models::*; use services::parse_validation_erro...
pub mod collections; pub mod cow_ptr; pub mod errors;
#![feature(proc_macro_hygiene, decl_macro)] #![allow(clippy::unit_arg)] mod bank; mod data; mod routes; #[macro_use] extern crate rocket; #[macro_use] extern crate lazy_static; #[macro_use] extern crate serde; use crate::data::*; use dashmap::DashMap; use dotenv::dotenv; use rocket::Request; use rocket_contrib::json...
use criterion::{criterion_group, criterion_main, Criterion}; use imdl::bench::{Bench, HasherBench}; fn bench(c: &mut Criterion) { let bench = HasherBench::init(); c.bench_function(&bench.name(), |b| b.iter(|| bench.iteration())); } criterion_group!(benches, bench); criterion_main!(benches);
extern crate ws; extern crate serde_json; use serde_json::builder::ObjectBuilder; use ws::{listen, Sender, Handler, Message, Handshake}; mod sudoku; use sudoku::SudokuPuzzle; fn json_message<T: ToString>(msg: T) -> String { let value = ObjectBuilder::new() .insert("message", msg.to_string()) .unw...
use std::io::println; use std::os; fn main() { let args = os::args(); let mut result = StrBuf::new(); for i in range(1, args.len()) { result.push_str(args[i]); if i != args.len() - 1 { result.push_str(" "); } } println(result.into_owned()); }
use Tensor::Rank2Tensor; use Tensor::Rank1Tensor; use Function::functiontraits::*; use Learner::learnertraits::*; use Optimizer::optimizertraits::Optimizer; use rand::Rng; use rand; use rand::distributions::{Range, IndependentSample}; pub struct Layer { m_weights: Rank2Tensor, m_bias: Rank1Tensor, m_input...
use std::collections::HashMap; use std::collections::hash_map::Entry; use crate::dispatcher::effect::Effect; use crate::dispatcher::environment::Environment; use crate::dispatcher::event::Event; use crate::dispatcher::entity::Entity; use crate::qupla::statement::typestmt::TypeStmt; #[derive(Clone)] pub struct Supervis...
// As long as this test compiles, it passes (test does not occur at runtime) use typed_builder::TypedBuilder; #[derive(PartialEq, TypedBuilder)] #[builder( build_method(vis="pub", into=Bar), builder_method(vis=""), builder_type(vis="pub", name=BarBuilder), )] struct Foo { x: i32, } pub struct Bar(Foo...
use unicode_segmentation::UnicodeSegmentation; use super::{Context, Module, ModuleConfig}; use crate::configs::git_branch::GitBranchConfig; use crate::formatter::StringFormatter; /// Creates a module with the Git branch in the current directory /// /// Will display the branch name if the current directory is a git r...
use super::{Formula, LitFrequencies, Literal, SatResult}; #[derive(Debug, Clone)] pub struct SolverState { pub formula: Formula, pub frequencies: LitFrequencies, pub assignments: Vec<Literal>, } impl From<Formula> for SolverState { fn from(formula: Formula) -> Self { Self { frequencies: LitFrequencies::from(...
#![feature(ip_addr)] #![feature(collections_drain)] #[macro_use] extern crate log; extern crate bevy; use std::collections::{HashMap, VecDeque}; use std::net::{Ipv4Addr, IpAddr, TcpStream}; use std::sync::mpsc::Sender; use std::sync::Arc; use bevy::net::arbiter::{WorkerInformation, Arbiter, ArbiterEvent, WorkDesignat...
use std::fmt; use ctxt::SemContext; use driver::cmd::Args; use gc::arena; use gc::Address; use gc::Collector; use gc::root::{get_rootset, IndirectObj}; use gc::swiper::card::CardTable; use gc::swiper::crossing::CrossingMap; use gc::swiper::full::FullCollector; use gc::swiper::large::LargeSpace; use gc::swiper::minor::...
extern crate libc; use std::mem; use std::slice; use std::marker; extern "C" { fn memset(s: *mut libc::c_void, c: libc::uint32_t, n: libc::size_t) -> *mut libc::c_void; } const PAGE_SIZE: usize = 4096; pub struct SystemVariables { null: isize, base: isize, } impl SystemVariables { pub fn base_addr(...
use std::io; use std::str::FromStr; fn print_with_space<T, I>(mut it: I) where I: Iterator<Item = T>, T: std::fmt::Display { if let Some(x) = it.next() { print!("{}", x); for x in it { print!(" {}", x); } } } fn parse<T>(x: &str) -> T where T: FromStr + st...
use injector::*; use std::sync::Arc; use std::sync::atomic::AtomicUsize; use std::sync::atomic::Ordering; use std::default::Default; #[derive(Clone)] pub struct MyTest0 { test1: Arc<MyTest1>, test2: Arc<MyTest2>, } impl MyTest0 { pub fn new(test1: Arc<MyTest1>, test2: Arc<MyTest2>) -> Self { Self ...
#[doc = "Register `DBGCLKSEL` reader"] pub struct R(crate::R<DBGCLKSEL_SPEC>); impl core::ops::Deref for R { type Target = crate::R<DBGCLKSEL_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<DBGCLKSEL_SPEC>> for R { #[inline(always)] fn from(read...
use structopt::StructOpt; /// handle client #[derive(Debug, StructOpt)] pub enum Client { /// Create client #[structopt(name = "create-client")] CreateClient(CreateClient), /// Update client #[structopt(name = "update-client")] UpdateClient(UpdateClient), /// Upgrade client #[structop...
use bytes; use error_chain::ChainedError; use futures; use futures::{Future, Sink, Stream}; use futures_cpupool; use hyper; use percent_encoding; use serde; use std; use tokio_core; use crate::Object; use crate::dlna; use crate::error::{ResultExt}; const CONNECTION_XML: &str = include_str!("connection.xml"); const CO...
extern crate shed; use anyhow; use async_stream::stream; use bincode::{DefaultOptions, Options}; use byteorder::{BigEndian, ReadBytesExt}; use derive_manifold::Manifold; use futures; use futures::{pin_mut, Stream, StreamExt}; use serde::{Deserialize, Serialize}; use shed::{ Action, Config, Encodable, History, Mani...
use super::cell::*; use super::fluid::*; use itertools::Itertools; use std::mem; use rand::{Isaac64Rng, Rng}; use noise::{Brownian2, perlin2}; use num_cpus; use crossbeam; const KILL_FLUID_COLOR_NORMAL: f64 = 0.009; // const SIGNAL_FLUID_SQRT_NORMAL: f64 = 5.0; const SIGNAL_FLUID_COLOR_COEFFICIENT: f32 = 300.0; const ...
#if defined(__3D_UI_KEYGUARD__) ApBegin(RS,CLSID_KEYGUARDAPP) WndBegin(KEYGUARD_WND_MAIN) WndSetStatusBarVisibleRC(VIEWSB_VISIABLE) WndSetSoftkeyVisibleRC(VIEWSK_INVISIABLE) WndSetAllSoftkeyRC({SK_NONE, SK_NONE, SK_UNLOCK}) #if defined(__3D_UI_KEYGUARD_GLOW__) WdgBegin(CLSID_IMAGEW...
use crate::io::Encode; use crate::protocol::Capabilities; // https://dev.mysql.com/doc/internals/en/com-query.html #[derive(Debug)] pub(crate) struct Query<'q>(pub(crate) &'q str); impl Encode<'_, Capabilities> for Query<'_> { fn encode_with(&self, buf: &mut Vec<u8>, _: Capabilities) { buf.push(0x03); //...
mod digits; mod euler; mod say; #[macro_use] extern crate itertools; use clap::Parser; /// Run a specific problem from Project Euler #[derive(Parser)] #[clap(author, version, about, long_about = None)] struct Args { /// Which Project Euler problem to run #[clap(value_parser)] problem: usize, } fn main()...
// SPDX-License-Identifier: Apache-2.0 /* * File: src/c/mod.rs * * C types and things for crossing the FFI boundary. * * Author: HTG-YT * Copyright (c) 2021 HTG-YT */ pub enum void { } pub type char = i8; pub type unsigned_char = u8; pub type float = f32; pub type short = i16; pub type unsigned_short = u16; ...
use std::env; use std::fs::File; use std::io::prelude::*; use std::io::BufReader; use std::path::Path; use std::process::Child; use std::process::Command; use std::sync::{Arc, Mutex}; use std::thread; use std::process::exit; fn main() { let root_config: Arc<Config> = Arc::new(get_config()); let config = Arc::c...
#![feature(destructuring_assignment)] #![feature(type_alias_impl_trait)] pub mod files; // #[path="day12/solution.rs"] mod day12; //#[path="day13/solution.rs"] mod day13; // #[path="day03/solution.rs"] mod day03; //#[path="day02/solution.rs"] mod day02; // #[path="day14/solution.rs"] mod day14; // #[path="day15/soluti...
// SQL use rusqlite::{Connection, Result, NO_PARAMS, Row, MappedRows, ToSql}; pub fn get_connection() -> Result<Connection> { Connection::open("ace_chat.db") } pub fn init() -> Result<()> { let conn = get_connection()?; conn.execute( "CREATE TABLE IF NOT EXISTS chat_rooms ( id integer...
struct Solution; use std::fmt; struct Range { start: i32, end: i32, } impl fmt::Display for Range { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if self.start == self.end { write!(f, "{}", self.start) } else { write!(f, "{}->{}", self.start, self.end) ...
use std::io::{self, BufRead}; use std::collections::BinaryHeap; use std::cmp::Ordering; #[derive(Eq, Copy, Clone)] struct Moose { id: i32, year: i32, strength: i32 } impl PartialEq for Moose { fn eq(&self, other: &Self) -> bool { self.strength == other.strength } } impl Ord for Moose { ...
#[macro_use] extern crate rocket; #[macro_use] extern crate rocket_contrib; #[macro_use] extern crate diesel; #[macro_use] extern crate diesel_migrations; mod models; mod repositories; mod schema; use models::*; use repositories::*; use rocket::fairing::AdHoc; use rocket::http::Status; use rocket::response::status; u...
extern crate collections; use collections::HashMap; use std::gc::Gc; use std::from_str::FromStr; use std::fmt; enum Value { Nil, Symbol(~str), String(~str), Number(int), Pair(~Value, ~Value), Lambda(~Value, ~Value) } // http://static.rust-lang.org/doc/0.10/std/from_str/trait.FromStr.html impl FromStr for...
use std::collections::HashMap; use std::fs::File; use std::io::Error; use std::io::prelude::*; use regex::{Regex}; fn main() -> Result<(), Error> { let mut parameters = HashMap::new(); parameters.insert(format!("a"), format!("b")); let result = render("test.txt", &parameters)?; println!("{}", result);...
use std::sync::mpsc::{channel, Receiver, RecvTimeoutError, Sender}; use std::time::Duration; pub struct TermSignal { tx: Sender<()> } /// In order to terminate the fs monitor loop we'll send a nonsense event that /// we can detect in the loop and croak when received. impl TermSignal { /// Tell the fs monitor loop...
use owo_colors::{OwoColorize, Style}; use structopt::StructOpt; use cargo_mextk::SYMBOLS_PROPER_NAMES; use cargo_mextk::Error; fn main() { if let Err(err) = cargo_mextk::main(cargo_mextk::Args::from_args()) { eprintln!( "{}", format!("Error: {}", err) .if_stderr_tt...
pub struct TokenValidator; impl TokenValidator { pub fn valid_numeral_char(character: char) -> bool { match character { '0'..='9' => true, _ => false } } pub fn valid_alphabetical_character(character: char) -> bool { match character ...
//! This proc macro derives a custom Multihash code table from a list of hashers. //! //! The digests are stack allocated with a fixed size. That size needs to be big enough to hold any //! of the specified hash digests. This cannot be determined reliably on compile-time, hence it //! needs to set manually via the `all...
// Copyright (c) The Starcoin Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::message::{NodeRequest, NodeResponse}; use anyhow::Result; use starcoin_crypto::HashValue; use starcoin_service_registry::{ ActorService, ServiceHandler, ServiceInfo, ServiceRef, ServiceStatus, }; #[async_trait::async...
use std::path::Path; use chrono::{offset::Utc, DateTime, NaiveDateTime}; use super::schema::*; #[derive(Clone, Debug, Insertable, Queryable)] #[table_name = "media"] pub struct Media { id: String, file_path: String, creation_date: NaiveDateTime, download_date: NaiveDateTime, } impl Media { pub f...
use crate::*; #[test] fn left_space_1() { expect(" 1").to_yield(1) } #[test] fn right_space_1() { expect("1 ").to_yield(1) } #[test] fn both_space_1() { expect(" 1 ").to_yield(1) } #[test] fn left_double_space_1() { expect(" 1").to_yield(1) } #[test] fn right_double_space_1() { expect("1 ").to_y...
//! retry impls for async-std retry_impl!(async_std::task::sleep); #[cfg(test)] mod test { use crate::RetryResult; use super::*; use crate::strategy::*; use async_std::task; use std::{ io, sync::{Arc, Mutex}, }; #[test] fn fail_on_three() { task::block_on(asy...
use std::cmp::Ord; use std::cmp::Ordering; mod ray; mod material; pub use self::ray::RayTraceRayHit; pub use self::material::RayTraceMaterialHit; pub struct RayTraceHitHeapEntry<T> { pub distance: f64, pub value: T } impl<T> RayTraceHitHeapEntry<T> { pub fn new(distance: f64, value: T) -> Self { Self { dist...
use std::env; use std::io; use std::io::prelude::*; use std::io::BufReader; use std::fs::File; fn main() { let path = env::current_dir().unwrap(); println!("{}", path.display()); }
#[macro_use] extern crate quickcheck; use rmpv::decode::read_value; use rmpv::encode::write_value; use rmpv::Value; fn mirror_test<T: Clone>(xs: T) -> bool where Value: From<T> { let mut buf = Vec::new(); write_value(&mut buf, &Value::from(xs.clone())).unwrap(); Value::from(xs) == read_value(&mut &bu...
use std::comm::{Sender, Receiver}; use std::default::Default; use collections::HashMap; use serialize::json; pub type GetSubkeysFunc = fn(&Instrument, Option<~str>) -> json::Json; pub type GetKeyFunc = fn(&Instrument, ~str) -> json::Json; pub type HasKeyFunc = fn(&Instrument, ~str) -> bool; /// Structure representi...
use std::fs::{metadata, read_dir}; use std::path::Path; use std::time::{Duration, Instant}; use std::env; extern crate crossbeam; extern crate num_cpus; fn get_size_of_files_in_dir_sequential(path: &Path) -> f64 { if path.is_file() { if let Ok(m) = metadata(path) { return m.len() as f64 } } match...
use crate::common::*; macro_rules! test_env { { args: [$($arg:expr),* $(,)?], $(cwd: $cwd:expr,)? $(input: $input:expr,)? $(err_style: $err_style:expr,)? tree: { $($tree:tt)* } $(, matches: $result:pat)? $(,)? } => { { let tempdir = temptree! { $($tree)* }; l...
use deltae::*; use std::error::Error; use std::str::FromStr; mod cli; fn main() -> Result<(), Box<dyn Error>> { //Parse command line arguments with clap let matches = cli::app().get_matches(); let method = DEMethod::from_str(matches.value_of("METHOD").unwrap())?; let color_type = matches.value_of("CO...
pub mod hosting; // This says that the submodule front_of_house::hosting is declared at src/front_of_house/hosting.rs
use alloc::boxed::Box; use alloc::string::String; use alloc::vec::Vec; use bmos_std::io::IOChannel; use bmos_std::kdebug; use bmos_std::syscall; use hashbrown::HashMap; use lazy_static::lazy_static; pub trait ShellBuiltin { fn execute(&self, arguments: Vec<&str>); } pub struct Echo; impl ShellBuiltin for Echo { ...
#[allow(unused_imports)] use serde_json::Value; #[derive(Debug, Serialize, Deserialize)] pub struct NdmpDiagnostics { /// #[serde(rename = "diagnostics")] pub diagnostics: Option <crate::models::NdmpDiagnosticsDiagnostics>, }
use neon::prelude::*; #[macro_use] extern crate neon; #[macro_use] extern crate neon_serde; #[macro_use] extern crate serde_derive; extern crate graphql_rs_native; use std::fs; fn parse_export(mut cx: FunctionContext) -> JsResult<JsValue> { let source_text = cx.argument::<JsString>(0)?.value(); let source = ...
mod type_resolve; pub use type_resolve::*; mod type_check; pub use type_check::*; mod alloc_frame; pub use alloc_frame::*; mod constant_folding; pub use constant_folding::*;
// Copyright 2019 Conflux Foundation. All rights reserved. // Conflux is free software and distributed under GNU General Public License. // See http://www.gnu.org/licenses/ /// The MSB is used to indicate if a node is in mem or on disk, /// the rest 31 bits specifies the index of the node in the /// memory region. ///...
use std::env; use raytracelib::camera::{Angle, Camera}; use raytracelib::material::{Dielectric, Diffuse, Light, Metal, Material, Scatter, ScatterResult}; use raytracelib::random::{random_vec3, random_vec3_range}; use raytracelib::vec3::{Color, Point3, Ray, Vec3}; use raytracelib::world::{Sphere, World}; use rand::rng...
use std::str::FromStr; use config::{Config, ConfigError, File, FileFormat, Source}; use serde::Deserialize; use structopt::StructOpt; use tantivy::merge_policy::*; pub const VERSION: &str = env!("CARGO_PKG_VERSION"); pub const HEADER: &str = r#" ______ __ _ ____ __ /_ __/__ ___ / / ...
use crate::Ink; use proc_macro2::{Ident, Span}; use quote::quote; use uuid::Uuid; mod knot; mod segment; mod stitch; use self::knot::print_knot; use self::segment::print_segments; pub fn pretty_print(name: &str, ink: Ink) -> String { let name = Ident::new(name, Span::call_site()); let entry = print_segments(...
use std::collections::HashMap; use crate::util::*; use crate::intcode::*; extern crate num_bigint; extern crate num_traits; fn drawgrid(grid:&HashMap<i64,i64>, minx:i64, maxx:i64, miny:i64, maxy:i64) { for i in miny..maxy+1 { for j in minx..maxx+1 { let offset = i*10000+j; if grid.contains_key(...
//! A Symbolic Executor for Falcon IL use crate::error::*; use falcon::architecture::Endian; use falcon::executor::eval; use falcon::il; use falcon::memory::{backing, paged}; use falcon::RC; use std::collections::HashMap; mod driver; mod hash_expression; mod memory; mod state; mod state_translator; mod successor; mod...
#[doc = "Register `PEDS` reader"] pub struct R(crate::R<PEDS_SPEC>); impl core::ops::Deref for R { type Target = crate::R<PEDS_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<PEDS_SPEC>> for R { #[inline(always)] fn from(reader: crate::R<PEDS_SP...
#[macro_use] extern crate bitflags; #[macro_use] extern crate ebpf_derive; pub extern crate ebpf_sys as ffi; pub mod map; pub mod prog; pub use map::Map; pub use prog::{Attach, Insn, Opcode, Program, Type}; pub const BPF_LICENSE_SEC: &str = "license"; pub const BPF_VERSION_SEC: &str = "version"; pub const BPF_MAPS_...
use std::float; use std::num::atan; fn angle(vector: (float,float)) -> float { let pi = float::consts::pi; match vector { (0f, y) if y < 0f => 1.5 * pi, (0f ,y) => 0.5*pi, (x, y) => atan(y/x) } } fn main() { let a=(5.0f,6.0f); let k = angle(a); println(fmt!("%f",k)); le...
const CHARS: &[u8] = b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; /// Note: This returns `a` for 0. /// /// Returns [None] if the value is is not a valid ideitifer. pub(crate) fn base54(init: usize) -> Option<String> { let mut n = init; let mut ret = String::new(); let mut base = 54; ...
use block_tools::{ blocks::Context, db::schema::blocks, dsl, dsl::prelude::*, models::Block, LoopError, }; use crate::blocks::text_block::TextBlock; impl TextBlock { pub fn edit_method(context: &Context, block_id: i64, args: String) -> Result<Block, LoopError> { let conn = &context.pool.get()?; let display = S...
mod dimacs_cnf; pub use dimacs_cnf::parse_dimacs_file;
// This file is part of Substrate. // Copyright (C) Parity Technologies (UK) Ltd. // SPDX-License-Identifier: Apache-2.0 // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.a...
use crate::instructions::base::bytecode_reader::BytecodeReader; use crate::instructions::base::instruction::{ Instruction, LocalVarsInstruction, NoOperandsInstruction, }; use crate::runtime::frame::Frame; fn i_store(frame: &mut Frame, index: usize) { let val = frame .operand_stack() .expect("op...
//! Instantiate a module, call functions, and read exports. use crate::{ error::{update_last_error, CApiError}, export::{wasmer_exports_t, wasmer_import_export_kind, NamedExport, NamedExports}, import::wasmer_import_t, memory::wasmer_memory_t, value::{wasmer_value, wasmer_value_t, wasmer_value_tag}...
pub trait Policy { fn initial(capacity: usize) -> usize; fn grow(capacity: usize) -> usize; fn shrink(size: usize, capacity: usize) -> usize; } #[allow(clippy::exhaustive_structs)] pub struct FixedPolicy; impl Policy for FixedPolicy { fn initial(size: usize) -> usize { size } fn grow(...
//! Custom derive support for the `signature` crate. //! //! This crate can be used to derive `Signer` and `Verifier` impls for //! types that impl `DigestSigner` or `DigestVerifier` respectively. #![crate_type = "proc-macro"] #![recursion_limit = "128"] #![deny(warnings, unused_import_braces, unused_qualifications)] ...
use std::rc::Rc; use bytemuck::{Pod, Zeroable}; use wgpu::util::DeviceExt; use super::mesh_pass::MeshPass; #[derive(Copy, Clone)] pub enum MaterialKind { Untextured, TexturedUnlit, Textured, TexturedNorm, TexturedNormMat, TexturedEmissive, } #[derive(Clone)] pub struct MaterialData { pub...
mod part1; mod part2; use part1::Grid3; use part2::Grid4; fn main() { let input = include_str!("../input.txt"); let mut grid3 = Grid3::new(input); for _ in 1..=6 { grid3.cycle(); } println!("Part1 solution: cubes in active state = {}", grid3.in_active_state()); let mut grid4 = Grid4::new(input);...
use std::io; fn fah_to_cel(choice : u8, deg : f64) -> f64{ if choice==1{ // choice==1 means cel to fahren ((deg-32.00)/9.00)*5.00 } else{ ((9.0*deg)/5.0)+32.0 } } fn main() { println!("Enter choice\n1.) Fahrenheit to Celsius\n2.) Celsius to Fahrenheit"); let mut ch = String::new(...
use crate::{ structure::inline_qos::KeyHash, dds::values::result::*, messages::submessages::submessage_elements::{ parameter_list::ParameterList, RepresentationIdentifier, }, structure::{parameter_id::ParameterId, inline_qos::StatusInfo}, }; // This is to be implemented by all DomanParticipant, Publisher...
fn main() { println!( "cargo:rustc-env=PROC_ARTIFACT_DIR={}", std::env::var("OUT_DIR").unwrap() ) }
pub use ipc::payloads::*; pub use ipc::*; use libnx::{svcAcceptSession, svcReplyAndReceive, waitHandles}; use std::mem; use std::slice; use std::time::Duration; #[derive(Copy, Clone, Hash, Debug, Eq, PartialEq)] pub struct IpcSession { pub handle: libnx::Handle, } impl IpcSession { pub unsafe fn query_point...
extern crate std; extern crate gl; extern crate glfw; use self::glfw::{ Context, Glfw, Key, Action, WindowEvent, Window as GlfwWindow }; use self::glfw::ffi::*; use std::collections::HashMap; type Handler = Box<(Fn<(),Output=()> + 'static)>; pub struct Window { _glfw: Glfw, pub w...
//! The binary used to run Vienna games. #![warn( clippy::all, clippy::cargo, clippy::nursery, clippy::pedantic, clippy::restriction, future_incompatible, nonstandard_style, rust_2018_compatibility, rust_2018_idioms, rustdoc, unused )] #![allow( clippy::float_arithmetic,...
use crate::*; use std::collections::HashMap; pub trait Statement { fn resolve(&self, _interp: &mut Interpreter) {} } impl Statement for Assignment { fn resolve(&self, interp: &mut Interpreter) { let k = self.var.name.clone(); let v = self.string.clone(); interp.variables.ins...
use tiny_skia::*; #[test] fn empty() { let pb = PathBuilder::new(); assert!(pb.finish().is_none()); } #[test] fn line() { let mut pb = PathBuilder::new(); pb.move_to(10.0, 20.0); pb.line_to(30.0, 40.0); let path = pb.finish().unwrap(); assert_eq!(path.bounds(), Rect::from_ltrb(10.0, 20.0,...
use svm_abi_layout as layout; use svm_sdk_std::{safe_try, Result, Vec}; use svm_sdk_types::value::{Primitive, Value}; use svm_sdk_types::{Address, Amount}; use crate::Cursor; pub enum TypeError { MissingTypeKind, InvalidTypeKind(u8), } enum TypeKind { None, Unit, Bool, Address, Amount, ...
// Lumol, an extensible molecular simulation engine // Copyright (C) Lumol's contributors — BSD license //! Testing physical properties of f-SPC water use lumol::input::Input; use std::path::Path; use std::sync::Once; static START: Once = Once::new(); #[test] fn constant_energy_ewald() { START.call_once(::env_l...
mod board; pub mod clock; pub mod export; #[cfg(test)] mod tests; use clock::{ClockRule, GameClock, Millisecond}; use serde::{Deserialize, Serialize}; use std::collections::{HashSet, VecDeque}; use bitmaps::Bitmap; use tinyvec::TinyVec; use crate::states::play::traitor::TraitorState; pub use crate::states::GameState...
pub mod data; pub mod geo; pub use self::data::{Filter::*, Query}; pub use self::geo::Location; use chrono::{Duration, Local}; #[derive(Debug, PartialEq)] pub struct CrimeData { pub related_crimes: Vec<Crime>, pub unrelated_crimes: Vec<Crime>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub...
use std::process::Command; fn main() { let mut cmd = Command::new("uname"); cmd.arg("-r"); match cmd.output() { Ok(output) => { println!("Your current version of kernel: {}", String::from_utf8_lossy(&output.stdout)) }, Err(e) => println!("Failed to exec the command: {}"...
use crate::schema::props_boost_categories; use chrono::NaiveDateTime; use serde::{Serialize,Deserialize}; #[derive(Queryable, Identifiable,Serialize,Deserialize, Debug, Clone)] #[primary_key(item_id)] #[table_name = "props_boost_categories"] pub struct PropsBoostCategory { pub item_id: i64, pub boost_time: i64...
use magick_rust; use std::str::FromStr; #[derive(PartialEq,Eq,Debug,Fail)] #[fail(display = "Unknown alpha channel option: {}", _0)] pub struct UnknownAlphaChannelOption(String); #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub enum AlphaChannel { Undefined, Activate, Associate, Background, Copy, ...
extern crate libc; extern crate emacs; use std::os::raw::{c_int, c_void, c_char}; use std::ptr::null_mut; use std::ffi::{CString, CStr}; use emacs::{get_environment, provide, bind_function, make_function, find_function}; use emacs::emacs_module::{emacs_env, emacs_value, intmax_t, ptrdiff_t, ...
// 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...