text
stringlengths
8
4.13M
extern crate raster; use raster::{ editor::{blend, fill, resize}, open, save, transform, BlendMode, Color, Image, PositionMode, ResizeMode, }; struct Imagem { imagem: Image, salvar: String, } impl Imagem { fn obter_imagem() -> Self { if std::env::args().len() != 2 { panic!("Fa...
use shrev::{EventChannel, ReaderId}; use specs::prelude::{Read, Resources, System, Write}; use crate::event; pub struct EventSystem { reader: Option<ReaderId<event::Event>>, } impl EventSystem { pub fn new() -> Self { EventSystem { reader: None, } } fn process_event(event...
#[doc = "Reader of register APB1ENR2"] pub type R = crate::R<u32, super::APB1ENR2>; #[doc = "Writer for register APB1ENR2"] pub type W = crate::W<u32, super::APB1ENR2>; #[doc = "Register APB1ENR2 `reset()`'s with value 0"] impl crate::ResetValue for super::APB1ENR2 { type Type = u32; #[inline(always)] fn re...
use std::collections::BTreeMap; use models::messages::*; use models::{AppState, Canvas, ChannelID}; #[derive(Debug, Default)] pub struct MessageBuffer { messages: BTreeMap<MessageID, Message>, } impl MessageBuffer { pub fn new() -> Self { MessageBuffer { messages: BTreeMap::new(), ...
use proptest::strategy::{Just, Strategy}; use liblumen_alloc::erts::process::alloc::TermAlloc; use crate::erlang::binary_to_list_3::result; use crate::test::strategy; #[test] fn without_binary_errors_badarg() { run!( |arc_process| { ( Just(arc_process.clone()), ...
#[allow(unused_attributes)] #[link_args = "--js-library src/js/console.js"] extern "C" { pub fn init_console(); pub fn set_console_text(s: *const i8); pub fn set_console_color(s: *const i8); }
use crate::formats::{ReferenceFormat, ReferenceFormatSpecification, NAMES}; use crate::object::{ObjectId, UUID_LENGTH}; use crate::Result; use std::collections::{hash_map, HashMap}; use std::convert::TryInto; use std::io; use std::io::{BufRead, Read, Write}; use std::ops::Index; type NamesDataType = HashMap<ObjectId, ...
use crate::structs::parsed::weapons; use crate::structs::raw::{ common, equip_affix_excel_config_data, material_excel_config_data, weapon_curve_excel_config_data, weapon_excel_config_data, weapon_promote_excel_config_data, }; use crate::utils::{readable::Readable, remove_xml, texthash::TextHash}; use std::fs; ...
#[macro_use] extern crate diesel; #[macro_use] extern crate diesel_migrations; use anyhow::Result; use warp::{http::Method, Filter}; mod db; mod graphql; mod models; mod schema; pub async fn run() -> Result<()> { ::std::env::set_var("RUST_LOG", "warp_server"); env_logger::init(); let pool = db::setup()...
//! //! //! Create a `trait` definition //! use serde::Serialize; use crate::traits::SrcCode; use crate::{internal, AssociatedTypeDeclaration, FunctionSignature, Generic, SrcCodeVec}; use tera::{Context, Tera}; /// Represents a `trait` block. /// /// Example /// ------- /// ``` /// use proffer::*; /// let tr8t = Trai...
use crate::FunctionData; pub struct RemoveNopsPass; impl super::Pass for RemoveNopsPass { fn name(&self) -> &str { "nop elimination" } fn time(&self) -> crate::timing::TimedBlock { crate::timing::remove_nops() } fn run_on_function(&self, function: &mut FunctionData) -> bool { ...
extern crate clap; extern crate image; mod cli; mod utils; mod intervals; mod sorter; fn main() { let matches = cli::en(); let image_input_path = matches.value_of("INPUT").unwrap(); let image_output_path = format!("{}{}", utils::generate_id(), ".png"); println!("opening image..."); let mut img = image::open...
use std::io; use std::result; use std::fmt; #[derive(Debug)] pub enum Error { None, Io(io::Error), HomeAssistant(homeassistant::Error), Format(fmt::Error) } pub type Result<S> = result::Result<S, Error>; impl From<()> for Error { fn from(_err: ()) -> Error { Error::None } } impl From...
use firefly_diagnostics::Spanned; use firefly_syntax_base::*; use super::Fun; #[derive(Debug, Clone, Spanned)] pub struct Function { pub var_counter: usize, #[span] pub fun: Fun, } impl Eq for Function {} impl PartialEq for Function { fn eq(&self, other: &Self) -> bool { self.fun == other.fun ...
/* * Copyright 2019 The Exonum Team * * 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...
//! Implementation of the service which processes [`Command`]s from client and //! [`Event`]s. use std::{ cell::RefCell, collections::{HashMap, HashSet}, rc::{Rc, Weak}, }; use futures::StreamExt as _; use tokio::task::spawn_local; use crate::{ proto::{Command, Event}, rpc_connection::ServerRpcCo...
use std::collections::HashMap; #[allow(dead_code)] #[derive(PartialEq, Eq, Hash, Copy, Clone)] pub enum Stat { // primary Strength, Dexterity, Vitality, Intelligence, Mind, // offensive CriticalHitRate, Determination, DirectHitRate, // defensive Defense, ...
//! //! Channel Subscriber //! use super::Network; use crate::iota_channels_lite::utils::{payload::json::Payload, random_seed}; use iota::client as iota_client; use iota_streams::app::transport::tangle::{client::RecvOptions, PAYLOAD_BYTES}; use iota_streams::app::transport::Transport; use iota_streams::app_channels::{ ...
use crate::values::{Register, Value}; #[derive(Debug)] pub enum Operation { Halt, Set(Register, Value), Push(Value), Pop(Register), Equal(Register, Value, Value), GreaterThan(Register, Value, Value), Jump(Value), JumpTrue(Value, Value), JumpFalse(Value, Value), Add(Register, Val...
use crate::any::connection::AnyConnectionKind; use crate::any::options::{AnyConnectOptions, AnyConnectOptionsKind}; use crate::any::AnyConnection; use crate::connection::Connection; use crate::error::Error; impl AnyConnection { pub(crate) async fn establish(options: &AnyConnectOptions) -> Result<Self, Error> { ...
/** * 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...
// 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 ...
pub trait FromSingle
mod weather; mod config; mod wallpaper; mod worker; use std::{env, error::Error, fs::create_dir, io::{ErrorKind, Read}, path::Path}; use reqwest::{blocking::Client, header::{HeaderMap, HeaderValue}}; use serde::{Serialize, Deserialize}; pub use config::Config; pub use weather::get_weather; pub use worker::{Worker, M...
pub struct Clock { h:i32, m:i32 } // adding comment // !! looks like its off by one somewhere o well! impl Clock { pub fn new(hours: i32, minutes: i32) -> Self { let h_adjust = if hours < 0 { 24 }else { 0 }; let m_adjust = if minutes < 0 { 60 } else { 0 }; Clock{ h:h_adjust +( hours + minutes/...
mod delta; mod index; mod pack; use std::io; use std::path::{Path, PathBuf}; use std::sync::{Arc, Mutex}; use std::time::{Duration, Instant}; use dashmap::DashMap; use self::index::{FindIndexOffsetError, IndexFile, ReadIndexFileError}; use self::pack::{PackFile, ReadPackFileError}; use crate::object::database::Objec...
#[derive(Default, Debug)] pub struct OsSpecificConfig { pub enable_game_mode: bool, } // ============================================================ // ====================== Linux ========================= // ============================================================ #[cfg(target_os = "linux")] use crate...
/// References /// /// - they're pointers that ONLY borrow data fn references() { println!("--- REFERENCES ---"); let foo: &str = "baz"; println!("printing a reference {}\n", &foo); } /// Smart Pointers /// /// data structures that not only act like a pointer but also have /// - additional metadata /// - a...
use ptgui::prelude::*; use raylib::prelude::*; #[derive(PartialEq)] enum State { Empty, } fn main() { let (mut rl_handler, rl_thread) = raylib::init().size(1280, 720).title("Label test").build(); rl_handler.set_target_fps(60); let mut g_handler = GuiHandler::new(Colour::WHITE); g_handler ...
extern crate ardop_interface; extern crate async_std; #[macro_use] extern crate clap; extern crate futures; #[macro_use] extern crate log; extern crate stderrlog; use std::net::ToSocketAddrs; use std::process::exit; use std::str; use std::time::Duration; use async_std::task; use clap::{App, Arg}; use futures::prelude...
#[doc = "Writer for register C15IFCR"] pub type W = crate::W<u32, super::C15IFCR>; #[doc = "Register C15IFCR `reset()`'s with value 0"] impl crate::ResetValue for super::C15IFCR { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Write proxy for field `CTEIF15`"]...
use std::error::Error; pub mod add; pub mod clone; pub mod info; pub mod init; pub mod ls; pub mod unlink; pub trait Command { fn run(&self) -> Result<(), Box<dyn Error>> { Ok(()) } }
use juniper::FieldResult; use tokio; use super::model::{TodoItem, TodoList}; use super::Context; use crate::db::{todo_item, todo_list}; pub struct QueryRoot; #[juniper::object( // Here we specify the context type for this object. Context = Context, )] impl QueryRoot { #[graphql(description = "List of all todo ...
#[macro_use] extern crate lazy_static; #[macro_use] extern crate log; #[macro_use] extern crate prettytable; extern crate clap; use clap::{App, SubCommand, Arg}; use std::process::{Command, Output}; use std::io::Write; use regex::Regex; use prettytable::{Table, format}; use levenshtein::levenshtein; fn main() { /...
use std::sync::Arc; use crate::graphics::Format; use crate::graphics::Backend; use std::hash::Hasher; use std::hash::Hash; use super::BindingFrequency; #[derive(Debug, Clone, Copy, PartialEq, Hash, Eq)] pub enum InputRate { PerVertex, PerInstance } #[derive(Debug, Hash, Eq, PartialEq, Clone)] pub struct Shader...
mod channel; mod info; mod set; use crate::services::config::Config as BotConfig; use crate::services::database::guild::DBGuild; use self::channel::CHANNEL_COMMAND; use self::info::CONFIG_INFO_COMMAND; use self::set::SET_COMMAND; use crate::extensions::context::ClientContextExt; use crate::extensions::MessageExt; us...
// Copyright 2017 Dasein Phaos aka. Luxko // // 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 a...
use crate::types::{Size2i, Vector2i, Rgb8}; use std::fmt::*; #[derive(Debug)] pub struct Image { pub size: Size2i, pub data: Vec<u8> } impl Image { pub fn new(size: Size2i) -> Image { let mut data = Vec::<u8>::new(); let data_size = (size.width()*size.height()*3) as usize; data.re...
use crate::{ core::{Part, Solution}, utils::string::StrUtils, }; pub fn solve(part: Part, input: String) -> String { match part { Part::P1 => Day05::solve_part_one(input), Part::P2 => Day05::solve_part_two(input), } } pub struct Day05; impl Solution for Day05 { fn solve_part_one(in...
mod with_registered_name; use super::*; #[test] fn without_supported_item_errors_badarg() { with_process_arc(|arc_process| { TestRunner::new(Config::with_source_file(file!())) .run(&unsupported_item_atom(), |item| { let pid = arc_process.pid_term(); prop_assert_...
use super::*; use crate::parser::Parser; use std::str; // This gives us a colorful diff. #[cfg(test)] use pretty_assertions::assert_eq; fn format_helper(golden: &str) { let file = Parser::new(golden).parse_file("".to_string()); let mut fmt = Formatter::new(golden.len()); fmt.format_file(&file, true); ...
#[doc = "Reader of register PLLSAI2CFGR"] pub type R = crate::R<u32, super::PLLSAI2CFGR>; #[doc = "Writer for register PLLSAI2CFGR"] pub type W = crate::W<u32, super::PLLSAI2CFGR>; #[doc = "Register PLLSAI2CFGR `reset()`'s with value 0x1000"] impl crate::ResetValue for super::PLLSAI2CFGR { type Type = u32; #[in...
use crate::types::{Array, Str}; use crate::value::{FromValue, ToValue, Value}; macro_rules! value_i { ($t:ty) => { impl ToValue for $t { fn to_value(&self) -> $crate::Value { $crate::Value::i64(self.clone() as i64) } } impl FromValue for $t { ...
pub struct Solution; impl Solution { pub fn word_pattern(pattern: String, str: String) -> bool { use std::collections::hash_map::Entry; use std::collections::HashMap; let mut letter2word = HashMap::new(); let mut word2letter = HashMap::new(); let mut p = 0; let mut i...
use crate::{ conv, device::Device, native, Backend as B, GlContainer, PhysicalDevice, QueueFamily, Starc, }; use arrayvec::ArrayVec; use glow::HasContext; use hal::{adapter::Adapter, format as f, image, window}; use std::iter; use wasm_bindgen::JsCast; #[cfg(feature = "winit")] use wini...
//! Interact with the file system using io-uring use std::alloc::{alloc, dealloc, handle_alloc_error, Layout}; use std::cmp; use std::fs; use std::future::Future; use std::io; use std::mem::{self, ManuallyDrop}; use std::os::unix::io::{AsRawFd, FromRawFd, RawFd}; use std::path::Path; use std::pin::Pin; use std::ptr; u...
use std; import ctypes::*; import str::sbuf; import std::c_vec; import std::io::{print, println}; // --------------------------------------------------------------------------- #[link_args = "-L ../rust/build-make/llvm/x86_64-apple-darwin/Release+Asserts/lib"] native mod clang { type CXIndex; type CXTranslati...
//! Namespace cache. use backoff::{Backoff, BackoffConfig}; use cache_system::{ backend::policy::{ lru::{LruPolicy, ResourcePool}, refresh::{OptionalValueRefreshDurationProvider, RefreshPolicy}, remove_if::{RemoveIfHandle, RemoveIfPolicy}, ttl::{OptionalValueTtlProvider, TtlPolicy},...
pub mod console; pub mod cvar_system; pub mod event_loop; pub mod async;
// Copyright 2018 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-MIT or ...
#![allow(clippy::enum_glob_use)] use std::fmt::{self, Debug, Display}; use bitflags::bitflags; use serde::de::{self, Error as SerdeError, MapAccess, Unexpected, Visitor}; use serde::{Deserialize, Deserializer}; use toml::Value as SerdeValue; use winit::event::MouseButton; use winit::keyboard::Key::*; use winit::keybo...
//! fonctions printing a tree or a path use { crate::{ app::*, display::{DisplayableTree, Screen}, errors::ProgramError, launchable::Launchable, skin::{ExtColorMap, PanelSkin, StyleMap}, tree::Tree, }, crossterm::tty::IsTty, pathdiff, std::{ f...
pub fn square_of_sum(n: usize) -> usize { (1..=n).fold(0, |a, b| a + b).pow(2) } pub fn sum_of_squares(n: usize) -> usize { (1..=n).map(|a| a.pow(2)).sum() } pub fn difference(n: usize) -> usize { square_of_sum(n) - sum_of_squares(n) }
use std::{ pin::Pin, task::{Context, Poll}, }; use futures_core::ready; use pin_project_lite::pin_project; use crate::{ actor::Actor, fut::{ActorFuture, ActorStream}, }; pin_project! { /// Future for the [`finish`](super::ActorStreamExt::finish) method. #[derive(Debug)] #[must_use = "stre...
use std::fs; const NUM_COLS: usize = 31; const NUM_ROWS: usize = 323; const SLOPE_X: usize = 1; const SLOPE_Y: usize = 2; fn has_tree(map: [[bool; NUM_COLS]; NUM_ROWS], x: usize, y: usize) -> bool { map[y % NUM_ROWS][x % NUM_COLS] } fn main() { let contents = fs::read_to_string("input.txt") .expect("...
use std::fmt::{Debug, Display}; use std::hash::Hash; use std::path::Path; use ahash::{AHashMap, AHashSet}; use crate::data_structures::{Slab, SlabKey}; use crate::fenwick_tree::FenwickTree; use crate::traits::{CorpusDelta, Pool, SaveToStatsFolder, Stats}; use crate::{CompatibleWithObservations, PoolStorageIndex, ToCS...
impl Spanned for ast::Arg { fn span(&self) -> Span { aaaaaaaaaatoJson( balancingCharges.map(|balancingCharge| halResource( obj(), Seq(HalLink("self", ...
use anyhow::{Context, Result}; use rand::Rng; use serde::Deserialize; use std::{ fs::File, io::{stdin, BufRead, BufReader}, }; #[derive(Debug, Deserialize)] struct Quote { quotation: String, speaker: String, } fn main() -> Result<()> { let f = File::open("../datasets/quotes-2019-nytimes.json") ...
/* Copyright 2020 Timo Saarinen 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 in writing, software d...
use datafusion::common::tree_node::Transformed; use datafusion::error::Result as DataFusionResult; use datafusion::prelude::{lit, Column, Expr}; use super::MEASUREMENT_COLUMN_NAME; /// Rewrites all references to the [MEASUREMENT_COLUMN_NAME] column /// with the actual table name pub(crate) fn rewrite_measurement_refe...
use std::{thread, time}; use std::path::{Path}; use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; use log::{debug, info, warn, error}; use serde_derive::Deserialize; use signal_hook; mod amdgpu; mod control; use control::ControlCurve; fn main() { env_logger::from_env( env_logger::Env::de...
fn main() { #[derive(Debug, PartialEq)] struct Foo { lorem: &'static str, ipsum: u32, dolor: Result<String, String>, } let x = Some(Foo { lorem: "Hello World!", ipsum: 42, dolor: Ok("hey".to_string()), }); let y = Some(Foo { ...
use crate::graph::JsGraph; use js_sys::{Array, Function}; use std::collections::HashMap; use wasm_bindgen::prelude::*; #[wasm_bindgen(js_name = coarsen)] pub fn js_coarsen( graph: &JsGraph, groups: &Function, shrink_node: &Function, shrink_edge: &Function, ) -> Result<JsValue, JsValue> { let graph ...
// Copyright 2012 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-MIT or ...
// An attribute to hide warnings for unused code. #![allow(dead_code)] // c-type struct #[derive(Debug)] struct Person { name: String, age: u8, } // A unit struct struct Unit; // A tuple struct struct Pair(i32, f32); // A struct with two fields #[derive(Debug)] struct Point { x: f32, y: f32, } // Struc...
//! All this crate does is make bit masking //! operations a bit prettier. use std::ops::{ BitOrAssign, BitXorAssign, BitAndAssign, Not, BitAnd, }; /// The trait describing things which can have /// bit masks applied to them. All integer types /// (and `bool`) implement this trait. pub trait BitMa...
// 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 according to those terms. use crate::lexer::preproc...
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. //! The network manager allows clients to manage router device properties. #![deny(missing_docs)] #![deny(unreachable_patterns)] extern crate fuchsia_sys...
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)] #[link(name = "windows")] extern "system" {} #[repr(transparent)] pub struct AccessoryNotificationType(pub u32); impl AccessoryNotificationType { pub const None: Self = Self(0u32); pub const Phone:...
// Copyright 2018 by caixw, All rights reserved. // Use of this source code is governed by a MIT // license that can be found in the LICENSE file. // @api GET /users 获取用户列表 // @apitags t1,t2 // @apiservers admin // @apiquery page int default desc // @apiquery size int default desc // @apiquery state array.string [norm...
#[doc = "Reader of register COMP7_CSR"] pub type R = crate::R<u32, super::COMP7_CSR>; #[doc = "Writer for register COMP7_CSR"] pub type W = crate::W<u32, super::COMP7_CSR>; #[doc = "Register COMP7_CSR `reset()`'s with value 0"] impl crate::ResetValue for super::COMP7_CSR { type Type = u32; #[inline(always)] ...
use hal::{ format::Format, window::{ AcquireError, CreationError, Suboptimal, SurfaceCapabilities, SwapImageIndex, SwapchainConfig, }, }; use crate::Backend; #[derive(Debug)] pub struct Surface; impl hal::window::Surface<Backend> for Surface { fn supports_queue_family(&self, _family: &...
use std::collections::HashMap; use crate::error::ParameterError; use crate::error::{PolarError, PolarResult}; pub use super::bindings::Bindings; use super::counter::Counter; use super::rules::*; use super::sources::*; use super::sugar::Namespaces; use super::terms::*; use std::sync::Arc; enum RuleParamMatch { Tr...
pub struct Solution; impl Solution { pub fn reconstruct_queue(people: Vec<Vec<i32>>) -> Vec<Vec<i32>> { use std::cmp::Reverse; let mut people = people; people.sort_unstable_by_key(|p| (Reverse(p[0]), p[1])); let mut res = Vec::with_capacity(people.len()); for p in people { ...
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use crate::message::{Message, MessageReturn}; use crate::node::Node; use async_trait::async_trait; use failure::{format_err, Error}; use fuchsia_async as f...
use clap; use std::fs; use std::io; use std::io::Write; use std::path::PathBuf; use std::process; use std::rc::Rc; pub enum Command { Dedupe, PrintExtents, } pub struct Arguments { pub command: Command, pub database_path: Option <PathBuf>, pub minimum_file_size: u64, pub content_hash_batch_size: u64, pub exte...
extern crate gl; use core::ops::Add; use core::ops::Div; use core::ops::Mul; use core::ops::Neg; use core::ops::Sub; #[derive(Copy, Clone)] pub struct Vec1<T> { pub x: T, } #[allow(dead_code)] pub type Vec1f = Vec1<f32>; #[allow(dead_code)] pub type Vec1u = Vec1<u32>; #[allow(dead_code)] pub type Vec1i = Vec1<i16>...
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use fidl_fuchsia_ui_input::{self as input, KeyboardEvent, KeyboardEventPhase}; const HID_USAGE_KEY_ENTER: u32 = 0x28; const HID_USAGE_KEY_ESC: u32 = 0x29;...
/* * Copyright (c) 2022, United States Government, as represented by the * Administrator of the National Aeronautics and Space Administration. * All rights reserved. * * The RACE - Runtime for Airspace Concept Evaluation platform is licensed * under the Apache License, Version 2.0 (the "License"); you may not use...
use super::{Error, SassFunction}; use css::Value; use num_rational::Rational; use num_traits::{One, Zero}; use std::collections::BTreeMap; use value::{Number, Unit}; use variablescope::Scope; pub fn register(f: &mut BTreeMap<&'static str, SassFunction>) { def!(f, hsl(hue, saturation, lightness), |s: &Scope| Ok( ...
use reqwest::header::{AsHeaderName, HeaderValue}; use reqwest::Response; #[derive(Debug)] pub enum Error { Reqwest(reqwest::Error), Url(url::ParseError), InvalidHeaderValue, } impl From<reqwest::Error> for Error { fn from(value: reqwest::Error) -> Self { Error::Reqwest(value) } } impl Fro...
use lexer::{self, Token}; use std::iter::Peekable; use value::Value; struct Parser<I: Iterator<Item=Token>> { tokens: Peekable<I> } struct ParseError { msg: String } macro_rules! parse_error { ($($arg:tt)*) => ( return Err(ParseError{msg: format!($($arg)*)}) ) } impl<I: Iterator<Item=Token>>...
pub fn iter_map_collect<F, T, U>(entities: &Vec<T>, mapper: F) -> Vec<U> where F: FnMut(&T) -> U, { entities.iter().map(mapper).collect() } pub fn clear_console() { print!("{}[2J", 27 as char); } pub fn replace_item<T>(index: &usize, entities: &mut Vec<T>, new_item: T) { let index = index.clone(); ...
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)] #[link(name = "windows")] extern "system" {} #[repr(transparent)] pub struct PhotoImportAccessMode(pub i32); impl PhotoImportAccessMode { pub const ReadWrite: Self = Self(0i32); pub const ReadOnly:...
#![windows_subsystem="windows"] // https://stackoverflow.com/a/45520092/13378247 mod png; mod jpg; mod gif; mod svg; mod misc; use misc::{ Args, Options}; #[macro_use] extern crate sciter; use sciter::{ Value }; use std::{ env, thread }; struct EventHandler {} impl EventHandler { fn compressFile(&self, filename: V...
use std::sync::Arc; use crate::context::Context; use crate::error::Result; use crate::file::{Rick, SSTable}; use crate::index::MemIndex; #[cfg(test)] use crate::types::Offset; use crate::types::{Bytes, Entry, LevelId, ThreadId, Timestamp}; #[derive(Hash, PartialEq, Eq)] pub struct TableIdentifier { pub tid: Threa...
use bigint::{Gas, U256}; use std::rc::Rc; use evm::errors::{OnChainError, RuntimeError}; use evm::Precompiled; pub static BN128_ADD_PRECOMPILED: Bn128AddPrecompiled = Bn128AddPrecompiled; pub struct Bn128AddPrecompiled; impl Precompiled for Bn128AddPrecompiled { fn gas_and_step(&self, data: &[u8], gas_limit: Gas...
// Copyright (c) 2017 Martijn Rijkeboer <mrr@sru-systems.com> // // 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 dis...
{{#each inputs~}} let {{this.[0]}} = {{>choice.getter this.[1] use_old=true}}; {{/each~}} if true {{#each others_conditions}} && {{this}} {{/each}} { if old.is({{self_condition}}).maybe_true() && new.is({{self_condition}}).is_true() { trigger_{{call_id}}.push(({{>choice.arg_ids}})); } }
extern crate linked_list; // LinkedList in standard library is not usable, // the solution on Vector does not finish even in 6 hours fn forward( c : &mut linked_list::Cursor<i32>, times : usize ) -> i32 { let mut value : Option<&mut i32> = None; for _j in 0 .. times { value = c.next(); if value...
use gio::prelude::*; use soup::Session; use soup::traits::*; fn main() -> Result<(), glib::Error> { let session = Session::new(); let input = session .request_http("GET", "http://example.com")? .send(Option::<&gio::Cancellable>::None)?; let output = gio::WriteOutputStream::new(std::io::st...
use super::Graph; impl Graph { pub fn new(node_size: usize) -> Graph{ let mut edge: Vec<Vec<(usize,i64)>> = Vec::<Vec<(usize,i64)>>::with_capacity(node_size); for _ in 0..node_size { edge.push(vec![]); } Graph{ node_size, edge_size: 0, edge } } pub fn add_edge(&mut s...
use crate::{ impl_interfacetype::private_associated_type, my_visibility::{RelativeVis, VisibilityKind}, parse_utils::parse_str_as_ident, workaround::token_stream_to_string, *, }; use std::marker::PhantomData; use proc_macro2::TokenStream as TokenStream2; use quote::TokenStreamExt; use syn::ItemT...
#![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)]...
/* Project Euler Problem 16: 2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26. What is the sum of the digits of the number 2^1000? */ fn main() { let mut v = vec![0; 1000]; v[0] = 2; for _ in 1..1000 { let mut c = 0; for j in 0..1000 { v[j] = v[j]*2 + c; ...
use crate::file_util::read_non_blank_lines; use std::str::FromStr; use std::cmp::{min, max}; #[allow(dead_code)] pub fn run_day_nine() { let lines = read_non_blank_lines("assets/day_nine") .filter_map(|line| usize::from_str(line.as_str()).ok()) .collect::<Vec<usize>>(); let calculated_result =...
test_stdout!(errors_with_reason, "{caught, error, reason}\n");
extern crate toml; /// The config object for the operation of the bot. #[derive(Deserialize)] pub struct Config { /// Discord config object pub discord: Discord, // /// Database config object // pub database: Database, } /// Contains all fields related to discord, such as tokens. #[derive(Deserialize...
//! Helper utilities. use std::borrow::{Cow, ToOwned}; /// Be given a Cow for the "current" version of an object, /// and visit it. If the visitor makes any changes and doesn't /// error out, the new owned version will be returned. /// This is only necessary because a new scope is needed to move the cow. /// This will...
use lib::{clumps, frequency_table, Kmer, Nucl}; use std::{ fs, time::{Duration, Instant}, }; fn main() { let str = fs::read_to_string("oric_vibrio_cholerae").unwrap(); let genome: Vec<_> = str .chars() .filter(|c| !c.is_whitespace()) .map(|c| Nucl::from(c)) .collect(); ...