text
stringlengths
8
4.13M
use crate::{BotResult, CommandData, Context}; use std::sync::Arc; #[command] #[short_desc("https://youtu.be/la9C0n7jSsI")] #[bucket("songs")] #[no_typing()] async fn flamingo(ctx: Arc<Context>, data: CommandData) -> BotResult<()> { let (lyrics, delay) = _flamingo(); super::song_send(lyrics, delay, ctx, data)...
//! Everything related to parsing/resolving templates is located in this module or it's submodules. //! //! # Syntax //! //! The syntax is heavily inspired by <https://handlebarsjs.com/>. //! //! ## Comment blocks //! //! Document template blocks. Will not be copied over to final output. //! //! ### Syntax //! //! `{{!...
fn main() { windows::build! { Windows::Win32::System::Pipes::CreatePipe, Windows::Win32::Security::SECURITY_ATTRIBUTES, Windows::Win32::Foundation::HANDLE, Windows::Win32::Foundation::BOOL, Windows::Win32::Foundation::CloseHandle, Windows::Win32::Storage::FileSystem::...
use super::*; #[cfg(unix)] use nix::{cmsg_space, sys::socket, sys::uio, unistd}; use std::os; #[cfg(unix)] use std::os::unix::io::IntoRawFd; #[derive(Clone)] pub struct SocketForwarder(Fd); pub struct SocketForwardee(pub(crate) Fd); pub fn socket_forwarder() -> (SocketForwarder, SocketForwardee) { let (send, receive)...
//! This module provides the data structures that represent system information. //! //! They're always the same across all platforms. use std::io; pub use std::time::Duration; pub use std::net::{Ipv4Addr, Ipv6Addr}; pub use std::collections::BTreeMap; pub use chrono::{DateTime, Utc, NaiveDateTime}; pub use bytesize::B...
use std::collections::HashMap; pub fn memory_reallocate(vector: Vec<u32>) -> u32 { let mut memory = Memory::new(); memory.init(vector); let steps = memory.reallocate(); steps } struct Memory { banks: Vec<u32>, length: usize, } impl Memory { fn new() -> Memory { Memory { ...
use std::fmt; #[derive(Debug, PartialEq)] pub struct Clock { hours: i32, minutes: i32, } const MAX_HOURS: i32 = 24; const MAX_MINUTES: i32 = 60; impl Clock { pub fn new(hours: i32, minutes: i32) -> Self { let h = (hours as f32 + (minutes as f32 / MAX_MINUTES as f32).floor()) as i32 % MAX_HOURS; ...
//! # Aero //! Aero is a new modern, unix based operating system. It is being developed for educational purposes. //! //! ## Code organization and architecture //! The code is divided into different *modules*, each representing a *subsystem* of the kernel. //! //! **Notes**: \ //! - Unix: <https://en.wikipedia.org/wiki...
use std::process::Command; use std::env; use std::path::Path; use std::str::from_utf8; fn main() { let out_dir = env::var("OUT_DIR").unwrap(); // build cuda device library let compile_out = format!("{}/hello.o", out_dir); let nvcc_out = Command::new("nvcc") .args(&["hello/hello...
pub enum State { WaitingHandshake, WaitingForResponse, Connected, }
// Copyright 2013 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 ...
// Problem 36 - Double-base palindromes // // The decimal number, 585 = 1001001001 (binary), is palindromic in both bases. // // Find the sum of all numbers, less than one million, which are palindromic in // base 10 and base 2. // // (Please note that the palindromic number, in either base, may not include // leading ...
use rand::prelude::*; pub fn run() { let mut test_runner = TestRunner::new(vec![ Box::from(NonSwitchingContestant), Box::from(SwitchingContestant), ]); let results = test_runner.compare_strategies(1_000_000); println!("{:#?}", results); } struct TestRunner { contestants: Vec<Box<d...
use std::net::SocketAddr; use chrono::prelude::*; use hydroflow::hydroflow_syntax; use hydroflow::scheduled::graph::Hydroflow; use hydroflow::util::{UdpSink, UdpStream}; use lattices::map_union::MapUnionSingletonMap; use lattices::{Max, Merge}; use crate::protocol::{EchoMsg, VecClock}; pub(crate) async fn run_server...
use std::fmt::Write; use crate::{ custom_client::OsuTrackerPpEntry, embeds::{Author, Footer}, util::{constants::OSU_BASE, numbers::with_comma_int}, }; pub struct OsuTrackerMapsEmbed { author: Author, description: String, footer: Footer, } impl OsuTrackerMapsEmbed { pub fn new(pp: u32, ent...
mod fixtures; use fixtures::{server, server_no_stderr, Error, FILES}; use http::StatusCode; use reqwest::blocking::Client; use rstest::rstest; use select::document::Document; use select::predicate::Text; #[rstest( cli_auth_file_arg, client_username, client_password, case("tests/data/auth1.txt", "joe",...
#[macro_use] extern crate clap; extern crate c8asm; use std::path::Path; use std::fs::File; use std::io::Read; use std::io::Write; use clap::{Arg, App}; use c8asm::parser::Stream; fn main() { let matches = App::new("c8asm") .version(crate_version!()) .author("Francis A. <francisagyapong2@gmail.c...
#[derive(Clone, Copy, PartialEq, Eq)] #[rustfmt::skip] /// 1 bit unsigned pub enum U1 { N0, N1, } impl U1 { /// Constructs self from byte /// # Panics /// Panics if assirtion `shift < 8` failed pub fn from_byte(value: u8, shift: u8) -> U1 { assert!(shift < 8); match (value >> shift)...
fn main() { pkg_config::probe_library("libsecret-1").unwrap(); }
use super::*; impl Renderer { pub fn canvas(&self) -> Rc<web_sys::HtmlCanvasElement> { Rc::clone(&self.canvas) } pub fn reset_size(&mut self) { let canvas_size = Self::reset_canvas_size(&self.canvas, self.device_pixel_ratio); let sw = canvas_size[0] as i32; let sh = canvas_...
#[derive(PartialEq, Eq, Clone, Debug)] pub struct Variable(pub String); #[derive(PartialEq, Eq, Clone, Debug)] pub enum Expr { Nil, Var(Variable), } #[derive(PartialEq, Eq, Debug, Clone)] pub enum Op { AtomEq(Expr, Expr), AtomNeq(Expr, Expr), } #[derive(PartialEq, Eq, Debug, Clone)] p...
mod action_items; mod navigation_icon; mod title; pub use action_items::*; pub use navigation_icon::*; pub use title::*; use crate::bool_to_option; use gloo::events::EventListener; use wasm_bindgen::prelude::*; use web_sys::Element; use yew::prelude::*; #[wasm_bindgen(module = "/build/mwc-top-app-bar.js")] extern "C...
#[doc = "Register `SR1` reader"] pub type R = crate::R<SR1_SPEC>; #[doc = "Field `TIM2F` reader - TIM2F"] pub type TIM2F_R = crate::BitReader; #[doc = "Field `TIM3F` reader - TIM3F"] pub type TIM3F_R = crate::BitReader; #[doc = "Field `TIM4F` reader - TIM4F"] pub type TIM4F_R = crate::BitReader; #[doc = "Field `TIM5F` ...
use std::sync::mpsc; use crate::midi::MidiMessage; use crate::button_map::control_name; pub const KEYS_CHANNEL: u8 = 3; pub const PARAMS_CHANNEL: u8 = 0; pub enum InstrumentMessage { NoteOn(usize, f64), NoteOff(usize), ParamChange(usize, f64), } pub struct MidiController { keys_down: [bool; 128], ...
type SegTreeIndex = i32; pub trait SegTreeMonoid: Copy { fn empty(start: SegTreeIndex, end: SegTreeIndex) -> Self; fn append(&self, other: &Self) -> Self; } pub trait SegTreeOp<T>: Copy { fn apply(&self, start: SegTreeIndex, end: SegTreeIndex, value: &mut T); fn combine(&mut self, other: &Self); } im...
//! Db executor actor use diesel; use diesel::mysql::MysqlConnection; use diesel::r2d2::{ConnectionManager, Pool, PoolError, PooledConnection}; use crate::utils::env::ENV; pub type MysqlPool = Pool<ConnectionManager<MysqlConnection>>; pub type MysqlPooledConnection = PooledConnection<ConnectionManager<MysqlConnection>...
use framework::{app, App, Canvas, Size, Ui}; use serde::{Deserialize, Serialize}; #[derive(Clone, Debug, Serialize, Deserialize)] struct Event { kind: String, event: String, } #[derive(Clone, Debug, Serialize, Deserialize)] struct EventViewer { size: Size, events: Vec<Event>, y_scroll_offset: f32,...
// Copyright 2021 <盏一 w@hidva.com> // 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,...
use pyo3::prelude::*; use pyo3::wrap_pyfunction; use druid::{AppLauncher, Widget, WindowDesc}; use crochet::{self, AppHolder, Button, DruidAppData, Label}; mod safe_ref; use safe_ref::SafeRef; struct PyAppLogic { py_app: PyObject, } impl PyAppLogic { fn run(&mut self, cx: &mut crochet::Cx) { // We...
// Rust Bitcoin Library // Written in 2014 by // Andrew Poelstra <apoelstra@wpsoftware.net> // To the extent possible under law, the author(s) have dedicated all // copyright and related and neighboring rights to this software to // the public domain worldwide. This software is distributed without // any warranty. ...
use std::io::{self, BufReader, BufWriter, SeekFrom, prelude::*}; use std::net::{ToSocketAddrs, TcpStream, TcpListener}; use std::convert::TryInto; #[cfg(test)] mod tests; const OPERATION_READ: u8 = 0xFF; const OPERATION_SEEK: u8 = 0xFE; const SEEK_FROM_START: u8 = 0; const SEEK_FROM_END: u8 = 1; const SEEK_FROM_CURR...
#[macro_use] extern crate failure; extern crate url; use failure::{Error, ResultExt}; use std::ffi::{OsStr, OsString}; use std::fs::{DirEntry, File, OpenOptions, ReadDir}; use std::ops::{Deref, Div}; use std::path::{Path, PathBuf}; use std::io::{BufReader, Read}; use std::iter::Map; type Result<T> = std::result::Resu...
use async_std::io; use async_std::net::{Shutdown, TcpListener, TcpStream, ToSocketAddrs}; use async_std::prelude::*; use async_std::task; use hyper::service::{make_service_fn, service_fn}; use hyper::{Body, Request, Response, Server, Client}; use std::convert::Infallible; use std::net::SocketAddr; const SOCKS5_VERSIO...
use std::collections::HashMap; use super::type_table::{TypeTableEntry, TypeTableType}; pub struct EventTypeTable { table: TypeTableType } impl TypeTableEntry for EventTypeTable { fn get(&self, key: u16) -> String { let result = self.table.get(&key); match result { Some(r) => r.clon...
use std::thread; fn main(){ let mut handles = vec![]; for _ in 0..5000 { handles.push( thread::spawn( do_nothing));} for handle in handles { let _result = handle.join();} } fn do_nothing(){ let _ = 1;}
extern crate rand; use rand::seq::SliceRandom; use std::collections::hash_map::Entry; use std::collections::HashMap; use std::io::prelude::*; use std::io::BufReader; pub struct WordSet { words_by_len: Vec<Vec<String>>, len_ids: HashMap<usize, usize>, } impl WordSet { pub fn from_reader(reader: &mut std::io::Read)...
#![doc = "generated by AutoRust 0.1.0"] #[cfg(feature = "package-2020-11")] mod package_2020_11; #[cfg(feature = "package-2020-11")] pub use package_2020_11::{models, operations, API_VERSION}; #[cfg(feature = "package-2020-04")] mod package_2020_04; #[cfg(feature = "package-2020-04")] pub use package_2020_04::{models, ...
#[doc = "Reader of register IO_SEL"] pub type R = crate::R<u32, super::IO_SEL>; #[doc = "Writer for register IO_SEL"] pub type W = crate::W<u32, super::IO_SEL>; #[doc = "Register IO_SEL `reset()`'s with value 0"] impl crate::ResetValue for super::IO_SEL { type Type = u32; #[inline(always)] fn reset_value() ...
#[macro_use] pub mod set; #[allow(unused_macros)] #[macro_export] macro_rules! set [ ($($e: expr),*) => ({ let mut s = set::Set::new(); $(s.add($e);)* s }) ]; fn main() { let mut s = set::Set::<f32>::new(); // float set let mut s2 = set::Set::<String>::new(); // string set ...
extern crate actix; extern crate actix_web; use crate::tentacle::{TentacleClient, TentacleConfigError}; use actix_web::{HttpResponse, Query, State}; use bytes::BufMut; use bytes::Bytes; use chrono::NaiveDateTime; use config; use config::Config; use futures::Stream; use serde::Deserialize; use std::str::FromStr; use st...
use structopt::StructOpt; mod clean; mod error; mod helpers; mod new; mod open; mod watch; #[derive(StructOpt, Debug)] /// Make and use playgrounds locally. #[structopt(bin_name = "cargo", usage = "cargo playground <SUBCOMMAND>")] enum Opts { // FIXME: See if this can be hidden from help message /// Internal ...
mod command; mod direction; mod game; mod point; mod snake; use crate::game::Game; use std::io::stdout; fn main() { Game::new(stdout(), 10, 10).run(); }
#[cfg(test)] mod test; use std::env; use lazy_static::lazy_static; use crate::{ bson::{doc, Bson, Document}, client::auth::ClientFirst, cmap::{Command, Connection, StreamDescription}, compression::Compressor, error::Result, hello::{hello_command, run_hello, HelloReply}, options::{AuthMech...
use cgmath::Vector3; use cgmath::InnerSpace; type Vec3 = Vector3<f32>; use super::util::Ray; use super::util::Hit; use super::random_in_unit_sphere; use super::rand_f32; pub struct Lambertian { pub albedo: Vec3 } impl Material for Lambertian { fn scatter(&self, ray_in: &Ray, hit: &Hit) -> Option<(Vec3, Ray)>...
pub mod i8080; pub mod instruction; pub mod interconnect; pub mod io; pub mod mmu; pub mod pic; use log::error; use self::{ i8080::I8080, instruction::{Instruction, Opcode}, interconnect::Interconnect, io::{basic_io::BasicIO, IO}, mmu::{basic_mmu::BasicMMU, Mmu, Rom}, }; use failure::Error; pub ...
#![feature(proc_macro_hygiene, decl_macro)] extern crate toml; #[macro_use] extern crate rocket; #[macro_use] extern crate rocket_contrib; #[macro_use] extern crate serde_derive; #[macro_use] extern crate diesel; mod config; mod controller; mod db; mod repository; mod schema; use config::toml_config::read_toml; use...
#[doc = "Reader of register CH4_CTR"] pub type R = crate::R<u32, super::CH4_CTR>; #[doc = "Writer for register CH4_CTR"] pub type W = crate::W<u32, super::CH4_CTR>; #[doc = "Register CH4_CTR `reset()`'s with value 0"] impl crate::ResetValue for super::CH4_CTR { type Type = u32; #[inline(always)] fn reset_va...
// El discurso de Zoe // // Copyright (C) 2016 GUL UC3M // // This program 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. // // Th...
#[cfg(test)] use std::cmp::Ordering; use std::{sync::Arc, time::Duration}; use derivative::Derivative; #[cfg(test)] use serde::de::{Deserializer, Error}; use serde::Deserialize; use crate::{ client::auth::Credential, event::cmap::{CmapEventHandler, ConnectionPoolOptions as EventOptions}, options::ClientOp...
struct State { x: isize, y: isize, wx: isize, wy: isize, } fn main() { let input = std::fs::read_to_string("../input.txt").unwrap(); let state = State { x: 0, y: 0, wx: 10, wy: 1, }; let state = input .split("\n") .filter(|l| !l.is_empty...
use crate::shared::tree_node::TreeNode; struct Solution; use std::cell::RefCell; use std::collections::VecDeque; use std::rc::Rc; /// https://leetcode.com/problems/path-sum/ impl Solution { pub fn has_path_sum(root: Option<Rc<RefCell<TreeNode>>>, target_sum: i32) -> bool { Solution::recursive(root, targe...
fn main() { let answer = String::from_utf8(std::fs::read("input/day6").unwrap()) .unwrap() .split("\n\n") .map(|group| { group .chars() .filter(|&c| !c.is_whitespace()) .collect::<std::collections::HashSet<_>>() .len...
use crate::error::MQTTClientError; pub type Result<T> = std::result::Result<T, MQTTClientError>; pub type Error = MQTTClientError;
/* * 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 */ /// UsageAttributionValues : Fields in Usage Summary by tag(s). #[derive(Clone, Debug, PartialEq, Ser...
use lazy_regex::{lazy_regex, Lazy}; use regex::Regex; use std::{ borrow::Cow, fmt::{self, Display}, }; /// Parses the given str into an vec of commands. /// Each command has to be on its own line. /// This method does not allocate any strings. /// ```rust /// # use std::fs::File; /// # use std::io::Read; /// #...
use serde::{Serialize, Deserialize}; use super::WithTransport; use crate::transport::ws; use crate::transport::{AsyncConnect, AsyncAccept}; #[allow(clippy::upper_case_acronyms)] #[derive(Debug, Serialize, Deserialize)] #[serde(tag = "proto", rename_all = "lowercase")] pub enum TransportConfig { Plain, WS(WebS...
// 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::{constants::TITLE_KEY, utils}, failure::{format_err, Error, ResultExt}, fidl::encoding::OutOfLine, fidl_fuchsia_ledger::{ ...
use bevy::prelude::*; use crate::components::{Player, PlayerState}; use crate::constants::{GRAVITY, PLAYER_HORIZONTAL_SPEED, PLAYER_INITIAL_VERTICAL_SPEED}; pub fn action( time: Res<Time>, keyboard_input: Res<Input<KeyCode>>, mut player_query: Query<(&mut Player, &mut Transform)>, ) { for (mut player, mut pla...
use crate::common::{ self, factories::prelude::*, snitches::{CorePanic, RegistrarSnitch, ReqProcessorPanic, TransactionPanic, TransportSnitch}, }; use ::common::ipnetwork::IpNetwork; use ::common::rsip::{self, prelude::*}; use models::transport::RequestMsg; use sip_server::{core::impls::UaProcessor, ReqProc...
use std::{net::Shutdown, time::Duration}; use bytes::BytesMut; use mio::{event::Event, net::TcpStream, Interest, Poll, Token}; use rustls::ServerSession; use crate::{ config::Opts, proto::{MAX_BUFFER_SIZE, MAX_PACKET_SIZE}, server::tls_server::Backend, tcp_util, tls_conn::{ConnStatus, TlsConn}, };...
use crate::client_handler::ClientHandler; use std::sync::{Arc, RwLock}; use crate::node_type::NodeType; use libp2p::{PeerId, build_development_transport, Swarm}; use libp2p::identity::Keypair; use crate::network_behaviour_composer::NetworkBehaviourComposer; use futures::Async; use futures::stream::Stream; use std::coll...
pub mod json; pub mod ron; pub mod toml; pub mod yaml;
#![feature(proc_macro_hygiene, decl_macro)] #[macro_use] extern crate rocket; #[get("/")] fn index() -> &'static str { "Hello world from REST_API" } #[get("/notes/<noteid>")] fn get_note_id(noteid: usize) -> String { format!("NoteId is: {}", noteid) } #[get("/notes")] fn get_notes() -> String { create_n...
#[macro_use] extern crate log; #[macro_use] extern crate serde_derive; mod utils; use flexi_logger::{DeferredNow, Level, LevelFilter, LogSpecification, Logger, Record}; pub use self::utils::find_sub_commands; pub use self::utils::print_error_and_exit; pub use self::utils::sub_command_path; use console::Style; use st...
#[doc = "Multi-Counter Watchdog Sub-counters 0/1\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2r...
mod prelude; pub use crate::prelude::*; pub const RANGED_MELEE_MULT: f64 = 0.25; //when ranged unit is being attacked by a melee, their damage goes down significantly pub const END_FIGHT_HEAL_AMOUNT: f64 = 0.1; //after a fight, all surviving units heal for this fraction of their max hp #[derive(Debug,Copy,Clone,Seria...
use std::collections::HashMap; use nom::{ bytes::complete::{take}, number::complete::{be_i16, be_u16, be_u32}, sequence::{tuple}, }; use crate::{R, GlyphId, FontError}; use crate::parsers::{*}; use crate::opentype::{Maxp, parse_lookup_list, coverage_table}; use itertools::{Itertools}; #[derive(Default, Cl...
pub fn map<T, S>(input: Vec<T>, mut function: impl FnMut(T) -> S) -> Vec<S> { let mut result = Vec::new(); for item in input { result.push(function(item)); } result }
extern crate tiny_http; extern crate rusqlite; extern crate url; extern crate core; use rusqlite::*; struct Score { name: String, highscore: i64, } fn main() { let conn = Connection::open("scores.db").unwrap(); conn.execute(" create table if not exists score ( name text not ...
extern crate stopwatch; use stopwatch::Stopwatch; use std::error::Error; use wasmtime::*; fn main() -> Result<(), Box<dyn Error>> { let engine = Engine::default(); let store = Store::new(&engine); let module = Module::from_file( &engine, "../rust_wasm/target/wasm32-unknown-unknown/release...
pub use super::disrusm::instr::*; pub use super::disrusm::mnem::*; pub use super::disrusm::operand::*; pub use super::disrusm::sib::*; pub use super::disrusm::utils::*; pub use super::disrusm::x86::*; pub use dis2ir::operand::*; #[derive(Copy, Clone, Debug)] pub struct Mnem2Ir {} impl Mnem2Ir { pub fn new() -> M...
impl super::Ppu { // cpu writes to 0x2000, PPUCTRL pub fn write_controller(&mut self, byte: u8) { // VRAM address increment per CPU read/write of PPUDATA self.address_increment = match byte & (1<<2) == 0 { // (0: add 1, going across; 1: add 32, going down) true => 1, fa...
pub mod matrix; pub mod point; pub mod tuple; pub mod util; pub mod vector;
use std::collections::BinaryHeap; use std::collections::HashSet; use std::collections::VecDeque; fn count_bits(mut x: i32) -> i32 { let mut counter = 0; while x > 0 { if x & 1 > 0 { counter += 1; } x /= 2; } counter } fn is_wall(magic: i32, pos: (i32, i32)) -> bool ...
use super::{shared::mask_32::DepthVector32, shared::vector_256::DelimiterClassifierImpl256, *}; use crate::{ classification::{quotes::QuoteClassifiedBlock, ResumeClassifierBlockState}, debug, input::{error::InputError, InputBlock}, FallibleIterator, }; use std::marker::PhantomData; const SIZE: usize = ...
use tinytemplate::{TinyTemplate, format_unescaped}; use std::path::{PathBuf, Path}; use serde_derive::Serialize; use crate::Error; #[derive(Serialize)] struct Context { name: String, author: String, } pub fn generate_project(root_dir: PathBuf, name: String, author: String) -> Result<(), Error> { use std::...
pub struct Parser {} impl Parser { fn parse_instruction(line: &str) {} } fn get_file_content(filename: String) -> String { return std::fs::read_to_string(filename).expect("Error reading file content"); } #[cfg(test)] mod tests { use super::*; #[test] fn test_add() { let result = Parser::p...
extern crate controller_rs; extern crate num_complex; extern crate pnet; extern crate serde_yaml; extern crate astroalgo; extern crate chrono; extern crate num_traits; use num_traits::float::FloatConst; use chrono::offset::Utc; use astroalgo::earth_position::LonLat; use astroalgo::hzpoint::HzPoint; use astroalgo::eq...
use actix::MailboxError; use elasticsearch::Error as ElasticError; use serde_json::error::Error as SerializeJsonError; use thiserror::Error as ThisError; use url::ParseError as UrlParseError; use crate::response::ItemError; use core::fmt::Error as SerializeError; use std::io::Error as IoError; #[derive(ThisError, De...
use crate::gui::make_dropdown_list_option; use crate::{ gui::{BuildContext, Ui, UiMessage, UiNode}, scene::commands::{ lod::{ AddLodGroupLevelCommand, AddLodObjectCommand, ChangeLodRangeBeginCommand, ChangeLodRangeEndCommand, RemoveLodGroupLevelCommand, RemoveLodObjectCommand, ...
pub use plugin::plugin_client::PluginClient; #[cfg(unix)] use tokio::net::UnixStream; use std::collections::HashMap; use std::str; use tonic::transport::{Endpoint, Uri}; use std::convert::TryFrom; use std::process::{Command, Child, Stdio}; use tower::service_fn; use std::sync::Mutex; use std::sync::Arc; pub mod plugi...
use crate::{ options::StructOptions, value::{GenericStruct, GenericValue}, }; pub fn generate_structs(struct_value: &GenericStruct, options: &StructOptions) -> String { let mut buffer = String::new(); generate_struct_declarations(&mut buffer, struct_value, options); buffer } fn generate_struct_dec...
use super::*; pub(crate) fn bind_command(ctx: &Context) -> CommandResult { match (ctx.parts.get(0), ctx.parts.get(1)) { (None, None) => { let keybinds = &ctx.config.borrow().keybinds; for (k, v) in keybinds.iter() { let output = Output::new() .fg(...
use super::BaseHandler; use crate::handler::PythonToken; use pyo3::prelude::*; use std::sync::{Arc, Mutex}; use streamson_lib::handler; #[pyclass(extends=BaseHandler)] #[derive(Clone)] pub struct IndexerHandler { pub indexer_inner: Arc<Mutex<handler::Indexer>>, } #[pymethods] impl IndexerHandler { /// Create ...
use std::io::{Result, Write}; use std::borrow::Cow; use pulldown_cmark::{Tag, Event}; use crate::gen::{State, States, Generator, Document}; #[derive(Debug)] pub struct Image<'a> { dst: Cow<'a, str>, title: Cow<'a, str>, caption: Vec<u8>, } impl<'a> State<'a> for Image<'a> { fn new(tag: Tag<'a>, gen:...
use lazy_static::lazy_static; use rocksdb::DB; use crate::utils::*; lazy_static!{ static ref DATABASE : DB = { let data_path = get_var("PASSKEEPER_DATA_PATH"); DB::open_default(data_path).unwrap_or_else(failed_with("unable to open data base")) }; } #[inline(always)] pub fn get_database() -> &'s...
extern crate rpg; use rpg::{Inv,InvWork,BuildBase, Vendor, Coin, Item, States,Actions}; fn main () { let mut bag = Inv::new(Some([10,10])); let sword = Item::new(Items::Weapons(Weapon { attr: vec!(WeaponBase::Speed(10),WeaponBase::Dmg(15)), ...
fn base10_pal(x: usize) -> bool { let mut xi = x; let mut rev = 0; while xi > 0 { rev = rev * 10 + xi % 10; xi /= 10; } rev == x } fn base2_pal(x: usize) -> bool { (x.clone().reverse_bits() >> x.leading_zeros()) == x } fn main() { let mut sum = 0; for i in 1..=1_000_0...
use super::{Pages, Pagination, ReactionVec}; use crate::{ commands::osu::UserValue, embeds::{RankingEmbed, RankingEntry, RankingKindData}, BotResult, Context, }; use std::{collections::BTreeMap, sync::Arc}; use twilight_model::channel::Message; type Users = BTreeMap<usize, RankingEntry>; pub struct Rank...
use std::fs::File; use std::io::{BufRead, BufReader}; fn calc_fuel(mass: i32) -> i32 { let fuel = mass / 3 - 2; if fuel < 0 { return 0; } else { return fuel + calc_fuel(fuel); } } fn main() { let f = File::open("input_2.txt"); let reader = BufReader::new(f.unwrap()); let...
use secret_integers::*; const BLOCK_SIZE: usize = 64; type State = [U32; 16]; type Key = Vec<U8>; type Nonce = Vec<U8>; type Block = [U8; 64]; type Constants = [u32; 4]; type Index = usize; type RotVal = usize; pub fn classify_u32s(v: &[u32]) -> Vec<U32> { v.iter().map(|x| U32::classify(*x)).collect() } fn line(...
use crate::domain::{model::Favorite, repository::IRepository}; pub fn list_favorites<T: IRepository>(repo: &T) -> anyhow::Result<Vec<Favorite>> { repo.get_all() }
pub fn experiments() { let rule_4: &str = " All objects have a lifetime which constrains which scopes they may be moved out of. "; println!("Rule 4: {}", rule_4); // let trait_object: &AsRef<str> = { // // let string: &str = "I am a string".as_ref(); // let string = "I a...
#![allow(missing_docs)] use criterion::{BatchSize, Criterion}; use grease::{repository::Repository, version}; use std::{path::Path, time::Duration}; #[allow(unused_results)] fn criterion_benchmark(c: &mut Criterion) { let p = Path::new("/usr/local/gentoo"); c.bench_function("repo.categories", move |b| { ...
use super::page::Page; use super::setintrecord::SetIntRecord; use super::setstringrecord::SetStringRecord; use std::fmt; use anyhow::Result; pub const CHECKPOINT: i32 = 0; pub const START: i32 = 1; pub const COMMIT: i32 = 2; pub const ROLLBACK: i32 = 3; pub const SETINT: i32 = 4; pub const SETSTRING: i32 = 5; #[der...
use std::os::raw::c_uint; static NS_EVENT_MODIFIER_FLAG_CAPSLOCK: c_uint = 1 << 16; static NS_EVENT_MODIFIER_FLAG_SHIFT: c_uint = 1 << 17; static NS_EVENT_MODIFIER_FLAG_CONTROL: c_uint = 1 << 18; static NS_EVENT_MODIFIER_FLAG_OPTION: c_uint = 1 << 19; static NS_EVENT_MODIFIER_FLAG_COMMAND: c_uint = 1 << 20; static NS_...
pub struct Infinity { current: usize } impl Infinity { pub fn new() -> Infinity { Infinity { current: 1 } } } impl Iterator for Infinity { type Item = usize; fn next(&mut self) -> Option<usize> { self.current += 1; Some(self.current) } }
pub mod capabilities; mod client; mod command; mod command_batch; mod objects; mod traits; mod utils; pub use crate::client::Client; pub use crate::command::{Command, CommandResult}; pub use crate::command_batch::CommandBatch; pub use crate::objects::{ Device, Devices, Location, Locations, PagedLocation, Room, Ro...
#![no_main] #![no_std] use keyboard as _; // global logger + panicking-behavior + memory layout #[cortex_m_rt::entry] fn main() -> ! { defmt::info!("info"); defmt::trace!("trace"); defmt::warn!("warn"); defmt::debug!("debug"); defmt::error!("error"); keyboard::exit() }
mod str; use std::convert::{TryInto, TryFrom}; use thiserror::Error; use derive_more::Into; use serde::Deserialize; pub use self::str::str; #[derive( Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Into, Deserialize, )] pub struct Sim(u8); impl Sim { pub fn value(&self) -> u8 { self.0 } } ...