text
stringlengths
8
4.13M
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version....
use exitfailure::ExitFailure; fn main() -> Result<(), ExitFailure> { let cli = library::Cli::get(); if cli.global { library::run_global()?; } else if let Some(path) = &cli.diff { library::run_diff(&path)?; } else { library::run_standard()?; } Ok(()) }
extern crate cgmath; extern crate gl; extern crate glfw; use std::collections::VecDeque; use std::ffi::CStr; use cgmath::*; //use cgmath::{Vector3, vec3, Matrix4, Vector2, vec2, Rad, Deg, Rotation3, Transform3, Transform, Decomposed, Quaternion, Euler}; use crate::landscape::{ACTUAL_WIDTH, AIR_STRIP, LAND_X, LAND_Z}...
use crate::db::queries::network_usage; use crate::db::queries::peer_count; use r2d2_postgres::PostgresConnectionManager; use std::{format, thread}; pub fn run(db_user: &str, db_password: &str) { let manager = PostgresConnectionManager::new( format!("postgres://{}:{}@localhost", db_user, db_password), ...
use std::{fs, io}; use thiserror::Error; #[derive(Error, Debug)] pub enum PackageError { #[error("Config does not exist does not exist")] ConfigNotExist, #[error("Config is not a file")] ConfigNotFile, #[error("Invalid toml: {0:?}")] ConfigIsInvalidToml(#[from] toml::de::Error), #[error("I/...
// Copyright (C) 2019 Frank Rehberger // // Licensed under the Apache License, Version 2.0 or MIT License #![feature(test)] // nightly feature required for API test::Bencher #[macro_use] extern crate test_generator; extern crate test; /* required for test::Bencher */ mod bench { // For all subfolders matching ...
mod number; mod float; mod vector; mod size; mod region; mod angle; use number::Number; use float::Float; pub use vector::{Vector, Position, Point, Scale, Delta}; pub use size::Size; pub use region::{Region, Viewport}; pub use angle::Angle;
use std::fs::File; use std::io::BufReader; use std::io::prelude::*; // extern crate syslog_reader; ////mod sys_log; use syslog_reader::sys_log::sys_log_data; static FILE_LOCATION: &'static str = "%HOMEPATH%/AppData/Local/visualsyslog/syslog1"; fn main() { println!("Hello World"); let f = File::open(FILE_LOCA...
use std::io::{self, Cursor, Read, Write}; use std::net::{SocketAddr, Shutdown}; use std::time::Duration; use std::sync::{Mutex, Arc}; pub type MockCursor = Cursor<Vec<u8>>; #[derive(Clone)] pub struct MockStream { reader: Arc<Mutex<MockCursor>>, writer: Arc<Mutex<MockCursor>> } impl MockStream { pub fn n...
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. //! This mod provides functions to remap a deno_core::deno_core::JSError based on a source map use deno_core; use deno_core::JSStackFrame; use sourcemap::SourceMap; use std::collections::HashMap; use std::str; pub trait SourceMapGetter { /// ...
use self::regex_cache::RegexCache; use super::raw_rule::RawPath; use super::raw_rule::RawRule; use super::RuleTrait; use crate::errors::*; use crate::rule::rule_path::RulePath; use crate::severity::Severity; use regex::Regex; use std::convert::TryFrom; mod regex_cache; /// Rule with compiled regular expression member...
use std::fs::File; use std::io::Read; use std::io::Result; fn main() { let s = read_file("sample.txt"); println!("{}", s.unwrap()); } fn read_file(file_name: &'static str) -> Result<String> { let mut f = try!(File::open(file_name)); let mut s = String::new(); try!(f.read_to_string(&mut s)); return Ok(s); }...
//! BEAM is the file format used in `.beam` files by the BEAM VM. //! //! The BEAM format is a binary chunked file format containing multiple sections. It starts with //! the magic file constant `FOR1`, which is based on the `FORM` header used in the original //! [Interchange File Format (IFF)](https://en.wikipedia.or...
#![forbid(unsafe_code)] #![warn(clippy::all, rust_2018_idioms)] mod resources_panel; mod advanced_search_container; mod app; pub mod army_build; pub mod army_setups_folder; pub mod army_setups_manager; mod ca_game; mod central_panel_state; pub mod factions; mod misc_folders; pub mod ymd_hms_dash_format; pub use app::...
use std::collections::HashMap; use proconio::input; use topological_sort::topological_sort; fn main() { input! { h: usize, w: usize, a: [[usize; w]; h], }; let mut min_max = Vec::new(); for i in 0..h { let values = a[i].iter().copied().filter(|&x| x >= 1).collect::<Vec...
#[doc = "Reader of register SR"] pub type R = crate::R<u32, super::SR>; #[doc = "Reader of field `C1VAL`"] pub type C1VAL_R = crate::R<bool, bool>; #[doc = "Reader of field `C2VAL`"] pub type C2VAL_R = crate::R<bool, bool>; #[doc = "Reader of field `C1IF`"] pub type C1IF_R = crate::R<bool, bool>; #[doc = "Reader of fie...
//! A group of attributes that can be attached to Rust code in order //! to generate a clippy lint detecting said code automatically. use clippy_utils::{get_attr, higher}; use rustc_ast::ast::{LitFloatType, LitKind}; use rustc_ast::LitIntType; use rustc_data_structures::fx::FxHashMap; use rustc_hir as hir; use rustc_h...
use ::itl::*; use ::itl::OpCode::*; use ::ast::Type; use ::ast::Operator; use std::collections::HashMap; pub struct Assembler { code: Vec<String>, locals: HashMap<String,usize>, params: HashMap<String,usize>, types: HashMap<String,Type>, stacksize: usize, } impl Assembler { fn build_stackframe...
use crate::eos_formats::format_action; use proc_macro2::TokenStream; use quote::{quote, quote_spanned, ToTokens}; use syn::parse::Parser; use syn::punctuated::Punctuated; use syn::{Ident, Token}; type ActionList = Punctuated<Ident, Token![,]>; pub fn abi(input_tokens: proc_macro::TokenStream) -> proc_macro::TokenStre...
// Copyright 2021 Datafuse Labs. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to ...
use crate::prelude::*; use std::os::raw::c_void; use std::ptr; #[repr(C)] #[derive(Debug)] pub struct VkPipelineMultisampleStateCreateInfo { pub sType: VkStructureType, pub pNext: *const c_void, pub flags: VkPipelineMultisampleStateCreateFlagBits, pub rasterizationSamples: VkSampleCountFlags, pub ...
use crate::generator::Generator; /// A sine tone generator. /// /// # Examples /// /// ```rust /// use audio_generator::{Generator, Sine}; /// /// let mut g = Sine::new(440.0, 44100.0); /// assert_eq!(g.sample(), 0.0); /// assert!(g.sample() > 0.0); /// ``` pub struct Sine { at: f32, step: f32, round_at: f...
use liblumen_alloc::erts::exception; use liblumen_alloc::erts::process::Process; use liblumen_alloc::erts::term::prelude::Term; /// `bxor/2` infix operator. #[native_implemented::function(erlang:bxor/2)] pub fn result( process: &Process, left_integer: Term, right_integer: Term, ) -> exception::Result<Term>...
pub mod utilities; use crate::utilities::Verify; use proffer::*; #[test] fn test_module_basic() { let m = Module::new("foo") .set_is_pub(true) .add_trait(Trait::new("Bar").set_is_pub(true).to_owned()) .add_function(Function::new("foo")) .add_struct(Struct::new("Thingy")) .a...
use amethyst::{ ecs::prelude::*, ui::UiTransform, }; use amethyst_imgui::imgui::{self, im_str}; use crate::Inspect; impl<'a> Inspect<'a> for UiTransform { type SystemData = (ReadStorage<'a, Self>, Read<'a, LazyUpdate>); const CAN_ADD: bool = true; fn inspect((storage, lazy): &mut Self::SystemData, entity: Entit...
use liblumen_alloc::erts::process::Process; use liblumen_alloc::erts::term::closure::*; use liblumen_alloc::erts::term::prelude::*; pub fn anonymous_closure(process: &Process) -> Term { process.anonymous_closure_with_env_from_slice( super::module(), INDEX, OLD_UNIQUE, UNIQUE, ...
use std::any::Any; use std::fmt; /* * Experimental * consider the use of this file a your own risk, eventually this will * be versioned and safe to use, currently it may change at whim. * Use of this api now may mean a lot of work keeping up with it. */ /// A trait for plugins that run workloads /// Any unimplemen...
use std::io; use std::net::SocketAddr; use tokio_core::net::{UdpSocket, UdpCodec, UdpFramed}; #[derive(Debug)] pub enum Message { Connect(String), Pub(String), Sub(String), Unsub(String), Ping(String), Ack(String), } const CONNECT: u8 = 0x01; const PUB: u8 = 0x02; const SUB: u8 = 0x03; const U...
use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt}; use std::io::Read; use crate::packet_type::PacketType; #[derive(Copy, Clone, Debug)] /// This header provides reliability information. pub struct StandardHeader { p_type: PacketType, // This is the sequence number so that we can know where in the seque...
extern crate xmachine; use xmachine::{Machine, Value}; pub fn xasm_println(xasm: &mut Machine) { println!("{}", xasm.pop()); } pub fn xasm_print(xasm: &mut Machine) { print!("{}", xasm.pop()); }
/** * Copyright © 2019 * Sami Shalayel <sami.shalayel@tutamail.com>, * Carl Schwan <carl@carlschwan.eu>, * Daniel Freiermuth <d_freiermu14@cs.uni-kl.de> * * This work is free. You can redistribute it and/or modify it under the * terms of the Do What The Fuck You Want To Public License, Version 2, * as published...
use libc::c_int; use curses; use {Error, Result, Character}; use super::Screen; pub struct Add<'a> { screen: &'a mut Screen, } impl<'a> Add<'a> { #[inline] pub unsafe fn wrap(screen: &mut Screen) -> Add { Add { screen: screen } } } impl<'a> Add<'a> { #[inline] pub fn string<S: AsRef<str>>(self, string: S) -...
pub mod collections; pub mod wish_lists; use rust_decimal::prelude::*; use std::fmt; use std::str; #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)] pub struct Price { amount: Decimal, currency: String, } impl Price { pub fn euro(amount: Decimal) -> Self { Price { amount, ...
// Heavily borrowed from Learn-WGPU // https://github.com/sotrh/learn-wgpu/tree/master/code/showcase/framework use futures::executor::block_on; use glam::{vec2, Vec2}; use wgpu::{SurfaceError, SurfaceFrame, TextureView}; use winit::{ event::{ElementState, Event, MouseButton, WindowEvent}, event_loop::EventLoop...
table! { albums (id) { id -> Integer, created_at -> Timestamp, name -> Text, } } table! { artists (id) { id -> Integer, created_at -> Timestamp, name -> Text, } } table! { genres (id) { id -> Integer, created_at -> Timestamp, ...
use std::convert::TryFrom; use crate::mechanics::{MultiplicationFactor, Multiplier}; use crate::mechanics::damage::DamageMultiplier::{DOUBLE, HALF, NONE, QUADRUPLE, QUARTER, SINGLE}; pub mod deal_damage; pub mod receive_damage; pub type DamageValue = u32; pub struct Damage { value: DamageValue, } impl Damage {...
// Copyright 2020, The Tari Project // // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the // following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following // disclai...
use crate::cli::Opts; use eyre::Report; use log::error; use serde::{de::DeserializeOwned, Deserialize, Serialize}; use serde_json::{de::IoRead, Deserializer}; use std::{fmt, io, net::TcpStream, time::Duration}; const CONNECT_BACKOFF: Duration = Duration::from_secs(1); const RETRY_BACKOFF: Duration = Duration::from_sec...
pub mod builder_trait_obj_strategy_state; pub mod classic_trait_objects_strategy_state; use builder_trait_obj_strategy_state::run as builder_t_obj_run; use classic_trait_objects_strategy_state::run as classic_t_obj_run; fn main() { builder_t_obj_run(); classic_t_obj_run(); }
//! The ELF ABI. 🧝 #![allow(non_snake_case)] #![cfg_attr( all(not(target_vendor = "mustang"), feature = "use-libc-auxv"), allow(dead_code) )] pub(super) const SELFMAG: usize = 4; pub(super) const ELFMAG: [u8; SELFMAG] = [0x7f, b'E', b'L', b'F']; pub(super) const EI_CLASS: usize = 4; pub(super) const EI_DATA:...
//! Traits for passing arguments to SQL queries. use crate::database::Database; use crate::encode::Encode; use crate::types::Type; use bitflags::_core::fmt::Debug; /// A tuple of arguments to be sent to the database. pub trait Arguments: Send + Sized + Default+ Debug + 'static { type Database: Database + ?Sized; ...
pub use kits::{to_c_char, to_str, CArray, CStruct, CR, CU64}; pub mod types; mod types_btc; mod types_eee; mod types_eth; pub mod mem_c; pub mod parameters; pub mod wallets_c; pub mod chain_btc_c; pub mod chain_eee_c; pub mod chain_eth_c; mod chain; mod chain_btc; mod chain_eee; mod chain_eth; pub mod kits; // pu...
use tictactoe::{Coordinates, Grid}; #[test] fn grid_coords_to_screen_coords() { let grid_coords = Coordinates { x: 2, y: 1 }; let screen_coords = Grid::grid_coords_to_screen_coords(&grid_coords); assert_eq!(screen_coords, Coordinates { x: 9, y: 1 }); }
use raytracer::camera::Camera; use raytracer::color::Color; use raytracer::options::Options; use raytracer::scene::Scene; use raytracer::vector::Vec3; use std::time::Instant; const WIDTH: u32 = 16_384; const HEIGHT: u32 = 10_240; const DEPTH: u8 = 255; const NAME: &str = "[16K][18.10]result"; fn setup_scene() -> Sce...
// unsinged fraction trait pub trait UFraction { fn new() -> Self; } // singed fraction trait pub trait Fraction { fn new() -> Self; } // irreducible fractions pub trait Irreducible {}
use crate::audio::Audio; use crate::cart::Cart; use crate::debug::Watch; use crate::gpu::Gpu; use crate::interrupts::Interrupt; use crate::joypad::Joypad; use crate::timer::Timer; use std::collections::HashSet; use std::path::PathBuf; use sdl2::audio::AudioQueue; use enumflags2::BitFlags; use log::{debug, info, log_ena...
use std::slice; fn split(v: &mut [i32]) -> (&[i32], &[i32]) { let p = v.len() / 2; (&v[..p], &v[p..]) } fn split_mut(v: &mut [i32]) -> (&mut [i32], &mut [i32]) { let p = v.len() / 2; let ptr = v.as_mut_ptr(); unsafe { let s1 = slice::from_raw_parts_mut(ptr, p); let next_p = pt...
use glob::PatternError; use regex::Error as RegexError; use rusqlite::SqliteError; use rustc_serialize::base64::FromBase64Error; #[cfg(unix)] use std::fs; use std::io; #[cfg(unix)] use std::os::unix::fs::PermissionsExt; use std::path::PathBuf; use std::string::FromUtf8Error; pub use self::MaskError::*; #[derive(Debug...
use crate::plot::plotters_backend::{Colors, DEFAULT_FONT, POINT_SIZE, SIZE}; use crate::plot::{FilledCurve, Line, Points, Size}; use crate::report::BenchmarkId; use plotters::data::float::pretty_print_float; use plotters::prelude::*; use std::path::PathBuf; pub fn regression( colors: &Colors, id: &Ben...
// auto generated, do not modify. // created: Mon Feb 22 23:57:02 2016 // src-file: /QtWidgets/qopenglwidget.h // dst-file: /src/widgets/qopenglwidget.rs // // header block begin => #![feature(libc)] #![feature(core)] #![feature(collections)] extern crate libc; use self::libc::*; // <= header block end // main bloc...
// Copyright 2021 Datafuse Labs. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to ...
use std::env; use std::path::PathBuf; fn main() -> Result<(), Box<dyn std::error::Error>> { let descriptor_path = PathBuf::from(env::var("OUT_DIR").unwrap()).join("runners_descriptor.bin"); tonic_build::configure() .build_server(true) .build_client(false) .file_descriptor_set_p...
#[doc = "Reader of register SECWM1R1"] pub type R = crate::R<u32, super::SECWM1R1>; #[doc = "Writer for register SECWM1R1"] pub type W = crate::W<u32, super::SECWM1R1>; #[doc = "Register SECWM1R1 `reset()`'s with value 0xff00_ff00"] impl crate::ResetValue for super::SECWM1R1 { type Type = u32; #[inline(always)]...
/** * Return the squared value of the sum of first n natural numbers */ pub fn square_of_sum(n: i32) -> i32 { let mut sum: i32 = 0; for i in 1..n + 1 { sum += i; } sum * sum } /** * Return the sum of the squared values of the first n natural numbers */ pub fn sum_of_squares(n: i32) -> i32 {...
use serde::Deserialize; #[derive(Clone, Debug, Deserialize)] pub struct Cfg { #[serde(default = "slack_bot_token")] pub slack_bot_token: String, #[serde(default = "slack_channel")] pub slack_channel: String, #[serde(default = "slack_file_name")] pub slack_file_name: String, } fn slack_bot_toke...
use super::Material; use crate::rtrs::textures::Texture; use crate::Color; use crate::HitRecord; use crate::Point; use crate::Ray; use std::sync::Arc; #[derive(Debug)] pub struct Dielectric { pub refraction_index: f64, pub albedo: Arc<dyn Texture>, } impl Dielectric { pub fn new(refraction_index: f64, alb...
//! # Resource Tables //! //! Copyright (c) 2018, Cambridge Consultants Ltd. //! See the top-level README.md for licence details. //! //! This is the code that is generic to all resource tables. Your specific //! resource table for your application should be defined elsewhere. // **************************************...
use std::{ cell::RefCell, collections::{HashMap, VecDeque}, net::SocketAddr, panic, rc::Rc, }; use byteorder::{BigEndian, WriteBytesExt}; use futures_util::{pin_mut, select, FutureExt, StreamExt}; use log::info; use ring::{hmac, rand}; use slotmap::DenseSlotMap; use naia_server_socket::{ Messa...
use { super::*, crate::errors::InvalidSkinError, crossterm::style::{ Color::{self, *}, }, lazy_regex::regex_captures, }; /// read a color from a string. /// It may be either /// - "none" /// - one of the few known color name. Example: "darkred" /// - grayscale with level in [0,24[. Example:...
use std::env; use std::fs::File; use std::io::{self, BufRead, BufReader}; fn joltage_difference(x: u64, y: u64) -> (u64, u64, u64) { let (mut a, mut b, mut c) = (0, 0, 0); match y - x { 0 => {} 1 => a += 1, 2 => b += 1, 3 => c += 1, _ => panic!("too much joltage"), }...
#[derive(Clone, Debug, Hash, PartialEq, Eq)] pub struct Tag { pub name: String, pub description: String, } impl Tag { pub fn new(name: String, description: String) -> Tag { Tag { name: name, description: description, } } }
mod backup_request_fragment; pub use self::backup_request_fragment::BackupRequestFragment; mod backup_resource_fragment; pub use self::backup_resource_fragment::BackupResourceFragment; mod bandwidth_resource; pub use self::bandwidth_resource::BandwidthResource; mod block_volume_request_fragment; pub use self::block_vol...
use regex::Regex; use std::io::BufRead; #[macro_use] extern crate lazy_static; fn main() { let args: Vec<_> = std::env::args().collect(); println!("{:?}", args); let file = std::fs::File::open(&args[1]).unwrap(); let mut lines = std::io::BufReader::new(file) .lines() .map(|line| line.un...
use actix::dev::{MessageResponse, ResponseChannel}; use actix::fut::{err, wrap_future}; use actix::prelude::Future; use actix::{ Actor, ActorContext, ActorFuture, Addr, AsyncContext, Context, Handler, Message, ResponseActFuture, Running, StreamHandler, WeakAddr, }; use actix_web::error::InternalError; use actix...
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)]...
fn main(args: vec[str]) { let vs: vec[str] = ["hi", "there", "this", "is", "a", "vec"]; let vvs: vec[vec[str]] = [args, vs]; for vs: vec[str] in vvs { for s: str in vs { log s; } } }
use crate::Span; #[derive(Debug, Copy, Clone, PartialEq)] pub(crate) enum TokenType { Letter, Number, Comment, Unknown, } impl From<char> for TokenType { fn from(c: char) -> TokenType { if c.is_ascii_alphabetic() { TokenType::Letter } else if c.is_ascii_digit() || c == ...
#[macro_use] extern crate serde_derive; #[macro_use] extern crate structopt; extern crate toml; mod get_config; use std::process::Command; use std::env; use get_config::{deploy_dependencies, deploy_pod, update_makefile, update_makefile_src, reset_makefile}; use structopt::StructOpt; use std::{thread, time}; #[derive(S...
use crate::prelude::*; use std::os::raw::c_void; use std::ptr; #[repr(C)] #[derive(Debug)] pub struct VkBufferViewCreateInfo { pub sType: VkStructureType, pub pNext: *const c_void, pub flags: VkBufferViewCreateFlagBits, pub buffer: VkBuffer, pub format: VkFormat, pub offset: VkDeviceSize, ...
use bevy::{prelude::Texture, render::texture::TextureFormat}; #[derive(Debug)] pub enum SamplingError { ReadOutOfBounds() } pub trait HeightmapData { /// Get the bounds of this heightmap (x, y). /// Sampled values must be in the [0, size-1] range. fn size(&self) -> (u16, u16); /// Sample a height...
// Fully qualified syntax untuk mencegah ambigu/kebingungan // // Misal kita punya 2 trait `Pilot` dan `Wizard` yang sama-sama // punya method `fly` dan kedua method diimplementasi ke struct yg sama yaitu `Human` // sedangkan struk `Human` sendiri mempunyai method `fly` // Bagaimana cara memanggil fungsi `fly` aga...
use std::time::Duration; use log::LevelFilter; pub const SEED: u64 = 645; pub const SIM_FACTOR: usize = 1; pub const GOBAN_SIZE: usize = 9; // pub const LOG_LEVEL: LevelFilter = LevelFilter::Info; // pub const LOG_LEVEL: LevelFilter = LevelFilter::Debug; pub const LOG_LEVEL: LevelFilter = LevelFilter::Trace; pub c...
//! # derp-rs //! //! A crappy knockoff of "grep" that exists only as a way to teach myself Rust. //! //! I have been paying attention to Rust for years, and have seen it //! evolve over time, but never actually tried to write any Rust code. //! //! For personal reasons, it has become of more interest recently, so //! ...
fn main() { let contents = std::fs::read_to_string("./res/input.txt").expect("Could not read file!"); let lines: Vec<&str> = contents.lines().collect(); let slopes = [(1,1),(3,1),(5,1),(7,1),(1,2)]; let mut count = 1; for slope in slopes.iter() { count *= count_trees(&lines, *slope); ...
use slasher::{ test_utils::{indexed_att, logger}, Config, Error, Slasher, }; use tempdir::TempDir; use types::Epoch; #[test] fn attestation_pruning_empty_wrap_around() { let tempdir = TempDir::new("slasher").unwrap(); let mut config = Config::new(tempdir.path().into()); config.validator_chunk_size ...
//! Contains components related to prefabs pub mod editor; pub mod editor_row; pub mod prefab_type_modal; pub mod scene; pub mod ui;
use super::fingerprint::Fingerprint; use crate::Result; use serde::{Deserialize, Serialize}; use std::{ collections::HashMap, fmt::Debug, path::{Path, PathBuf}, }; #[derive(Derivative, Clone, Debug, PartialEq, Eq, Deserialize, Serialize)] #[repr(C)] pub struct ArtifactCache { fingerprints: HashMap<Path...
use std::path::PathBuf; use freedesktop_entry_parser::parse_entry; pub struct AutostartUtils; impl AutostartUtils { pub fn show_only_in_lde(file: PathBuf) -> bool { let entry = parse_entry(file).unwrap(); if let Some(only_show_in) = entry.section("Desktop Entry").attr("OnlyShowIn") { o...
use time::{format_description::well_known::Rfc3339, OffsetDateTime, UtcOffset}; use crate::{InputValueError, InputValueResult, Scalar, ScalarType, Value}; /// A datetime with timezone offset. /// /// The input is a string in RFC3339 format, e.g. "2022-01-12T04:00:19.12345Z" /// or "2022-01-12T04:00:19+03:00". The out...
use proconio::{input, marker::Chars}; fn main() { input! { h: usize, w: usize, s: [Chars; h], }; let mut ans = 0; for i in 0..h { for j in 0..w { if s[i][j] == '#' { ans += 1; } } } println!("{}", ans); }
use crate::subcommands::Command; use log::info; use std::fs::{self, File}; use std::io::{ErrorKind, Read}; use std::path::{Path, PathBuf}; const FILE_NAME: &str = ".iforgot"; const BLANK_JSON: &str = "[]\n"; macro_rules! unwrap_or_err { ( $e:expr, $msg: tt) => { match $e { Ok(i) => i, ...
pub struct Circle { x: f64, y: f64, radius: f64 } // trait mirip interface pada golang // trait merupakan daftar definisi fungsi tanpa body trait HasArea { fn area(&self) -> f64; } // implementasi trait pada struct menggunakan keyword "for" impl HasArea for Circle { fn area(&self) -> f64 { ...
use std::sync::Arc; use proptest::strategy::{BoxedStrategy, Strategy}; use liblumen_alloc::erts::process::Process; use liblumen_alloc::erts::term::prelude::*; pub fn with_arity(arc_process: Arc<Process>, arity: u8) -> BoxedStrategy<Term> { (super::module_atom(), super::function()) .prop_map(move |(module...
pub trait Memory { fn get_u8(&self, addr: u16) -> u8; fn set_u8(&mut self, addr: u16, value: u8); fn get_range(&self, mut from: u16, to: u16) -> Vec<u8> { let mut result = Vec::new(); while from < to { result.push(self.get_u8(from)); from = from.overflowing_add(1).0...
#[derive(PartialEq)] pub struct ToDoListItem { pub label: String, pub completed: bool, } impl ToDoListItem { pub fn new(label: &str) -> Self { ToDoListItem { label: String::from(label), completed: false, } } }
/*! ```cargo [features] dont-panic = [] ``` */ #[cfg(feature="dont-panic")] fn main() { println!("--output--"); println!("Keep calm and borrow check."); } #[cfg(not(feature="dont-panic"))] fn main() { panic!("Do I really exist from an external, non-subjective point of view?"); }
use super::*; use std::ops::{Deref, DerefMut}; pub(super) struct List<L> (Option<L>); impl<L> List<L> { pub(super) fn make(size: usize, tail: Option<L>) -> Self where L: NewLink<Self> { (0 .. size).fold(Self(tail), |acc, _| Self(Some(L::new(acc)))) } } impl<L> DeepSafeDrop<L> for Li...
// This file was generated by gir (https://github.com/gtk-rs/gir) // from ../gir-files // DO NOT EDIT use crate::Cookie; #[cfg(any(feature = "v2_30", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_30")))] use crate::CookieJarAcceptPolicy; use crate::SessionFeature; use crate::URI; use glib::objec...
use structopt::StructOpt; #[derive(StructOpt)] pub enum Cli { Add { #[structopt(default_value = "", short = "t", long = "tags")] tags: String, description: String, }, Ls {}, Rm { number: u32, }, Mv { number: u32, status: String, }, }
//! Defines the consensus data structures to build a shared DAG. use std::collections::BTreeMap; use std::convert::TryInto; use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha512}; use failure::{bail, ensure, Fallible}; use crate::crypto::{aggregate_signature, sign, verify, verify_aggregate_signature, Publi...
#[macro_use] extern crate gfx; extern crate gfx_device_gl; extern crate gfx_gl; extern crate gfx_window_glutin; extern crate glutin; extern crate image; extern crate serde_json; extern crate ws; #[macro_use] mod pipeline; mod config; mod devices; mod passes; pub use crate::config::*; pub use crate::devices::*; pub us...
/* origin: FreeBSD /usr/src/lib/msun/src/e_asin.c */ /* * ==================================================== * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. * * Developed at SunSoft, a Sun Microsystems, Inc. business. * Permission to use, copy, modify, and distribute this * software is freel...
use crate::{expr::Expr, function::Function, token::Token}; #[derive(PartialEq, Clone, Debug, Eq)] pub enum Stmt { Expression { expression: Box<Expr>, }, Print { expression: Box<Expr>, }, Var { name: Token, initializer: Box<Expr>, }, Block { statements...
pub mod backend; pub mod balancing; pub mod http; pub mod server; use chrono::Local; use log::{Level, LevelFilter, Metadata, Record, SetLoggerError}; use serde::Deserialize; use serde_yaml; struct SimpleLogger; impl log::Log for SimpleLogger { fn enabled(&self, metadata: &Metadata) -> bool { metadata.leve...
fn main(){let mut t=0f32;let ts= |[x,y,z,r,w]:[f32;5]|{let q=(x*x+z*z).sqrt()- r;(q*q+y*y).sqrt()-w};let m=|l|move|s|(s,2.*(s as f32) /l-1.);let mut o=vec![vec![b' ';64];36];loop {let(p,q)=(t*3.).sin_cos();let(n,b)=(t*2.) .sin_cos();for(i,u)in(0..64).map(m(64. )){for(j,v)in(0..36).map(m(36.)){for (_,z)in(0..32).map(m(3...
use chrono::NaiveDateTime; use crate::schema::componentes_curriculares; #[derive(Serialize, Deserialize, Queryable)] pub struct ComponentesCurriculares { pub id: i32, pub nome: Option<String>, pub curso_id: Option<i32>, pub ch_semanal: f32, pub created_at: NaiveDateTime, pub updated_at: NaiveD...
use std::fmt; use crate::lexer::SumOp; use crate::lexer::MulOp; use crate::lexer::RelOp; use crate::token_stream::TokenStream; use crate::lexer::TokenType; use crate::lexer::LexerToken; use crate::token_stream::UnexpectedTokenError; use crate::graphviz::CreatesGraphviz; #[derive(Debug)] pub enum BinOp { Sum(S...
use super::*; mod with_atom_destination; mod with_local_pid_destination; #[test] fn without_atom_pid_or_tuple_destination_errors_badarg() { run!( |arc_process| { ( Just(arc_process.clone()), milliseconds(), strategy::term::is_not_send_after_desti...
fn main() { let mut s = String::from("hello world"); let word = first_word(&s); // results in 5 (where the space is) println!("first word: {}", word); s.clear(); // this empties the String. making it "" // word still has the value of 5 here but is only relevant in the context of our original //...
pub const EDITOR_VERSION: &str = "1.0.0"; pub const INPUT_BUFFER_SIZE: usize = 1; //MESSAGES pub const MESSAGE_ERROR_INVALID_UTF8: &str = "Invalid UTF-8 sequence"; pub const MESSAGE_ERROR_SETTING_TERMINAL_CONFIG: &str = "Couldn't instantiate editor"; pub const MESSAGE_ERROR_DIMENSION_INTEGER_PARSE: &str = "Dimension i...