text
stringlengths
8
4.13M
pub struct Solution; impl Solution { pub fn find_min_height_trees(n: i32, edges: Vec<Vec<i32>>) -> Vec<i32> { if n <= 2 { return (0..n).collect(); } let n = n as usize; let mut degree = vec![0; n]; let mut neighbor = vec![0; n]; for e in edges { ...
use std::ops::{ Index, Mul }; use ::vectors::{ AffineVector, Vector }; pub enum Cell { I1, J1, K1, W1, I2, J2, K2, W2, I3, J3, K3, W3, I4, J4, K4, W4, Row(u8), Column(u8), } impl Cell { pub fn to_column(&self) -> Cell { match self { &Cell::I1 => Cell::Column(0), &Cell::...
use glib::object::IsA; use glib::translate::*; use glib_sys::gpointer; use libc::c_void; use crate::AsNativeVTable; use crate::ChildOf; use crate::Class; use crate::ClassExt; use crate::Context; use crate::MetaClass; use crate::NativeClass; use crate::Value; pub trait ContextExtManual: 'static { fn evaluate_in_obj...
//! Various utils functions for caching and file management. use std::collections::hash_map::DefaultHasher; use std::ffi::OsStr; use std::hash::{Hash, Hasher}; use std::path::Path; use std::process::{Command, Output}; pub mod bytelines; mod io; pub use self::io::{ count_lines, create_or_overwrite, read_first_lin...
#[doc = r"Value read from the register"] pub struct R { bits: u32, } #[doc = r"Value to write to the register"] pub struct W { bits: u32, } impl super::IF2CMSK { #[doc = r"Modifies the contents of the register"] #[inline(always)] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, ...
extern crate mio; use mio::*; use mio::tcp::{TcpListener}; fn main() { const SERVER: Token = Token(0); let addr = "127.0.0.1:13265".parse().unwrap(); // set up the server socket let server = TcpListener::bind(&addr).unwrap(); // create a poll instance let poll = Poll::new().unwrap(); // st...
use crate::Definition; use lazy_static::lazy_static; use regex::Regex; use std::str::FromStr; // Domingler does not look for collisions below these IDs pub const ASSUMED_FIRST_WEAPON_ID: u32 = 801; pub const ASSUMED_FIRST_ARMOUR_ID: u32 = 270; pub const ASSUMED_FIRST_MONSTER_ID: u32 = 3500; pub const ASSUMED_FIRST_NAM...
use readlater::args::{Args, Command}; use structopt::StructOpt; pub fn main() { let args = Args::from_args(); match args.cmd { Command::Newsboat(cmd) => { match readlater::readable_article(cmd.url, cmd.title, cmd.desc, cmd.feed_title) { Ok(output) => { i...
#![feature(hash_drain_filter)] use std::collections::HashMap; use lru::LruCache; use async_std::{prelude::*,fs}; use desert::varint; mod storage; use storage::{Storage,FileStorage,RW}; pub type Position = (f32,f32); pub type BBox = (f32,f32,f32,f32); pub type QuadId = u64; pub type RecordId = u64; pub type IdBlock = ...
use clipboard_script::{is_jp}; use clipboard_master::{Master, ClipboardHandler, CallbackResult}; use clipboard_win::Clipboard; use std::io; #[inline(always)] ///Returns whether text contains only JP kana. pub fn is_furi_skip<T: AsRef<str>>(text: T) -> bool { let text = text.as_ref(); text.chars().all(|elem_c...
use serde::Serialize; #[derive(Clone, Debug, Serialize)] pub struct GmailAddress(String); impl GmailAddress { pub fn new(email: String) -> Self { GmailAddress(email) } } use std::fmt; impl fmt::Display for GmailAddress { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f,...
use sensor::Sensor; use std::cell::RefCell; use std::rc::Rc; pub struct SensorCollection { sensors : Vec<Rc<RefCell<Box<Sensor>>>>, } impl SensorCollection { // Creates empty sensor collection pub fn new() -> SensorCollection { SensorCollection { sensors : Vec::new() } } // Adds a sensor to the co...
//! Core infrastructure for the proxy application. //! //! Conglomerates: //! - Configuration //! - Runtime initialization //! - Admin interfaces //! - Tap //! - Metric labeling #![deny(warnings, rust_2018_idioms)] pub use linkerd2_addr::{self as addr, Addr, NameAddr}; pub use linkerd2_conditional::Conditional; pub u...
// Copyright 2016 `multipart` Crate Developers // // 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 exce...
use std::io; fn main() { let mut buffer = String::new(); io::stdin().read_line(&mut buffer).unwrap(); let input_vec: Vec<char> = buffer.chars().collect(); if input_vec[2] == input_vec[3] && input_vec[4] == input_vec[5] { println!("Yes"); } else { println!("No"); } }
use super::state_prelude::*; use crate::level_manager::LevelManager; pub struct LevelLoad { level_manager: LevelManager, } impl LevelLoad { pub fn new(level: Level) -> Self { Self { level_manager: LevelManager::new(level), } } pub fn with_delete_save(level: Level) -> Self ...
// Copyright 2022 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 ...
native "rust" mod rustrt { fn rust_file_is_dir(str path) -> int; } fn path_sep() -> str { ret _str.from_char(os_fs.path_sep); } type path = str; fn dirname(path p) -> path { auto sep = path_sep(); check (_str.byte_len(sep) == 1u); let int i = _str.rindex(p, sep.(0)); if (i == -1) { ret ...
// auto generated, do not modify. // created: Mon Feb 22 23:57:02 2016 // src-file: /QtCore/qloggingcategory.h // dst-file: /src/core/qloggingcategory.rs // // header block begin => #![feature(libc)] #![feature(core)] #![feature(collections)] extern crate libc; use self::libc::*; // <= header block end // main bloc...
fn solve(n: usize, m: usize, a: Vec<Vec<usize>>) { let mut freq = vec![0; n + 1]; for r in &a { for &x in r { freq[x] += 1; } } let max = freq.iter().copied().max().unwrap(); let lim = (m + 1) / 2; let mut ans = Vec::new(); if max > lim { ans = vec![0; m];...
use crate::configuration::{new_configuration, Configuration}; use command::CreatePostCommand; use db::SqlxPostDb; use domain::new_post_domain; use domain::PostDb; use domain::PostDomain; use std::time::Duration; pub struct ServiceRegistry { sqlx_post_db: Option<SqlxPostDb>, } impl ServiceRegistry { ...
#![feature(asm)] #![feature(linkage)] #![deny(warnings)] #[macro_use] extern crate log; extern crate alloc; use { alloc::collections::VecDeque, async_std::task_local, core::{cell::Cell, future::Future, pin::Pin}, git_version::git_version, kernel_hal::PageTableTrait, lazy_static::lazy_static, ...
//! Private module for selective re-export. See [`SequentialConsistencyTester`]. use crate::semantics::{ConsistencyTester, SequentialSpec}; use std::collections::{btree_map, BTreeMap, VecDeque}; use std::fmt::Debug; /// This tester captures a potentially concurrent history of operations and /// validates that it adhe...
extern crate slkparser; extern crate bencher; use bencher::Bencher; use bencher::benchmark_group; use bencher::benchmark_main; use slkparser::SLKScanner; fn bench_scanning_ability_data(b: &mut Bencher) { b.iter(|| { let slk_reader = SLKScanner::open("../resources/slk/AbilityData.slk"); for _ in ...
pub mod borrowing; pub mod enum_and_match; pub mod guess; pub mod lang_intro;
pub mod JSONObject { pub fn new(){ } }
use crate::{language_client::LanguageClient, types::WorkspaceEditWithCursor}; use anyhow::{anyhow, Result}; use jsonrpc_core::Value; use lsp_types::{Command, Location}; use serde::Deserialize; use std::path::PathBuf; // Runnable wraps the two possible shapes of a runnable action from rust-analyzer. Old-ish versions //...
// 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 zerocopy::ByteSlice; pub fn skip<B: ByteSlice>(bytes: B, skip: usize) -> Option<B> { if bytes.len() < skip { None } else { Som...
// Copyright 2022 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 ...
mod console_render; use console_render::framebuffer::Framebuffer; use console_render::color::Color; use console_render::geometry::{Line, Point}; use console_render::world::{Wall, World, Texture, TextureCell}; use std::f64::consts::PI; use std::io::{self}; fn texture_cell_generator<'a>(x:usize, y:usize) -> &'a TextureC...
macro_rules! check { ($n:expr, $expected:expr) => { println!("{:?}", $n.to_le_bytes()); assert_eq!($expected, $n.to_le_bytes()); } } fn main() { check!(1u8, [1]); check!(1u16, [1, 0]); check!(1u32, [1, 0, 0, 0]); check!(1u64, [1, 0, 0, 0, 0, 0, 0, 0]); check!(1u128, [1, 0, 0...
use serde::{Deserialize, Deserializer}; pub use de::MCProtoDeserializer; pub(crate) use de::Seq; mod de; pub(crate) mod read; pub fn deserialize<'de, T, D>(deserializer: D) -> Result<T, D::Error> where T: ?Sized + Deserialize<'de>, D: Deserializer<'de>, { Deserialize::deserialize(deserializer...
//! Demo ページ use yew::prelude::*; #[derive(Properties, Clone, PartialEq)] pub struct Props { pub demo_id: usize, } pub struct Demo { props: Props, } impl Component for Demo { type Message = (); type Properties = Props; fn create(props: Self::Properties, _: ComponentLink<Self>) -> Self { ...
// Copyright 2018 Fredrik Portström <https://portstrom.com> // This is free software distributed under the terms specified in // the file LICENSE at the top-level directory of this distribution. /*! Parse XML dumps exported from MediaWiki. This module parses [XML dumps](https://www.mediawiki.org/wiki/Help:Export) exp...
use core::marker::PhantomData; use crate::*; /// Generic helper for libm functions, abstracting over f32 and f64. <br/> /// # Type Parameter: /// - `T`: Either `f32` or `f64` /// /// # Examples /// ```rust /// use libm::{self, Libm}; /// /// const PI_F32: f32 = 3.1415927410e+00; /// const PI_F64: f64 = 3.141592653589...
use std::io; use super::super::{Key, Block}; use cipher; use mem; fn decrypt_chunk(key: &Key, prev: &mut Block, chunk: &[u8]) -> [u8; 8] { let input_block = mem::read_block(chunk); let mut decrypted_block = cipher::decipher(&key, input_block); decrypted_block[0] ^= prev[0]; decrypted_block[1] ^= prev[...
use super::super::controls::Knob; type FloatStream = Box<Iterator<Item=f64>>; pub struct FilterVolume { generator: FloatStream, value: Knob, } impl FilterVolume { pub fn new(generator: FloatStream, volume: Knob) -> FilterVolume { FilterVolume { generator: generator, value:...
mod aes; extern crate base64; extern crate rand; use std::fs::File; use std::io::prelude::*; use rand::Rng; fn main() { let plaintext = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa".as_bytes(); let ciphertext = random_cipher_encryption(&plaintext); let ecb = detection_oracle...
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)] #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn DisableThreadProfiling<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::HANDLE>>(performancedatahandle:...
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)] #[link(name = "windows")] extern "system" {} pub type GpioPinProviderValueChangedEventArgs = *mut ::core::ffi::c_void; pub type IGpioControllerProvider = *mut ::core::ffi::c_void; pub type IGpioPinProvider...
use franklin_crypto::bellman::bn256::{Bn256, Fr}; use franklin_crypto::bellman::Engine; use rand::{Rand, SeedableRng, XorShiftRng}; #[allow(dead_code)] use rescue_poseidon::generic_hash; use rescue_poseidon::poseidon::PoseidonParams; use rescue_poseidon::rescue::RescueParams; use rescue_poseidon::rescue::{ generic_...
use alloc::slice::Iter; #[derive(PartialEq, Debug, Clone)] pub enum KAuthVNodeAction { READ_DATA = 1 << 1, WRITE_DATA = 1 << 2, EXECUTE = 1 << 3, DELETE = 1 << 4, APPEND_DATA = 1 << 5, DELETE_CHILD = 1 << 6, READ_ATTRIBUTES = 1 << 7, WRITE_ATTRIBUTES = 1 << 8, READ_EXTATTRIBUTES = 1...
fn naive(n: usize, x: usize, m: usize) -> usize { let mut ans = 0; let mut y = x; for _ in 0..n { ans += y; y = y * y % m; } ans } fn main() { let stdin = std::io::stdin(); let mut rd = ProconReader::new(stdin.lock()); let n: usize = rd.get(); let x: usize = rd.get(...
use crate::auth; use crate::diesel::QueryDsl; use crate::diesel::RunQueryDsl; use crate::handlers::paginate::*; use crate::handlers::types::*; use crate::model::{ChatList, User, UserChat}; use crate::schema::unread_user_chat::dsl::*; use crate::schema::user_chat::dsl::id as user_chat_id; use crate::schema::user_chat::d...
// 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 ...
extern crate pine; use pine::ast::syntax_type::{SimpleSyntaxType, SyntaxType}; use pine::libs::plot; use pine::libs::print; use pine::runtime::data_src::{Callback, DataSrc, NoneCallback}; use pine::runtime::output::OutputData; use pine::runtime::AnySeries; const MA_SCRIPT: &str = " N = 5 ma = close // ma = (close + cl...
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)] #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct CharacterGrouping(pub ::windows::core::IInspec...
use futures_util::future::try_join_all; use lazy_static::lazy_static; use std::path::Path; use std::time::{Duration, UNIX_EPOCH}; use time::{OffsetDateTime, UtcOffset}; use tokio::fs::{self, DirEntry}; // HTML directory template const TEMPLATE: &str = r#"<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <me...
use crate::binding::http::{to_event, Headers}; use crate::Event; use actix_web::web::BytesMut; use actix_web::{web, HttpRequest}; use async_trait::async_trait; use futures::future::LocalBoxFuture; use futures::{FutureExt, StreamExt}; use http::header::{AsHeaderName, HeaderName, HeaderValue}; /// Implement Headers for ...
//! The per-partition data nested in a query [`QueryResponse`]. //! //! [`QueryResponse`]: super::response::QueryResponse use arrow::record_batch::RecordBatch; use data_types::TransitionPartitionId; /// Response data for a single partition. #[derive(Debug)] pub(crate) struct PartitionResponse { /// Stream of snap...
use super::abstract_container::AbstractContainer; pub trait ContainerFactory { fn new_container(&self) -> Box<dyn AbstractContainer>; } impl<F> ContainerFactory for F where F: Fn() -> Box<dyn AbstractContainer>, { fn new_container(&self) -> Box<dyn AbstractContainer> { self() } }
use crate::{ config::IoxConfigExt, physical_optimizer::chunk_extraction::extract_chunks, provider::{chunks_to_physical_nodes, DeduplicateExec}, QueryChunk, }; use datafusion::{ common::tree_node::{Transformed, TreeNode}, config::ConfigOptions, error::Result, physical_optimizer::PhysicalO...
extern crate pcap_file; use pcap_file::{PcapReader, PcapWriter}; static DATA: &'static[u8; 1455] = include_bytes!("test_in.pcap"); #[test] fn read() { let pcap_reader = PcapReader::new(&DATA[..]).unwrap(); //Global header len let mut data_len = 24; for pcap in pcap_reader { let pcap = pcap...
use std::collections::HashMap; #[derive(Debug)] struct Tower { name: String, weight: usize, subtowers: Option<Vec<String>>, } fn main() { let input = include_str!("../input2.txt"); println!("{}", day_7_part_1(input)); day_7_part_2(input); } fn day_7_part_1(input: &str) -> String { let tow...
use failure::Error; use flags::Flags; use instruction::{Condition, Instruction, Operation}; use memory::{Load, Memory, Store, VideoMemory}; use registers::Registers; use rom::Rom; use self::Condition::*; use self::Operation::*; #[derive(Default)] pub struct Cpu { memory: Memory, registers: Registers, fla...
use std::fmt::{self, Debug, Formatter}; use super::{FreeBlock, FreeBlockRef}; /// This struct is similar in nature to `Block`, but is used /// to store the size of the preceding data region when the block is free. /// /// When the next neighboring block is freed, a check is performed to /// see if it can be combined ...
use cursive::theme::BaseColor::*; use cursive::theme::Color::*; use cursive::theme::PaletteColor::*; use cursive::theme::*; use crate::config::Config; macro_rules! load_color { ( $cfg: expr, $member: ident, $default: expr ) => { $cfg.theme .as_ref() .and_then(|t| t.$member.clone())...
#![feature(llvm_asm)] extern "C" fn foo() { } fn main() { unsafe { llvm_asm!("callq $0" :: "s"(foo) :: "volatile"); } }
use super::{Color, Context}; #[allow(unused_variables)] pub fn clear(ctx: &mut Context, color: Color) { macroquad::prelude::clear_background(color); } #[allow(unused_variables)] pub fn draw_rectangle(ctx: &mut Context, x: f32, y: f32, w: f32, h: f32, color: Color) { macroquad::prelude::draw_rectangle(x, y, w,...
use audio_core::{Buf, Channel, Channels, ExactSizeBuf, ReadBuf}; /// Make a buffer into a read adapter that implements [ReadBuf]. /// /// # Examples /// /// ```rust /// use audio::Buf; /// use audio::io; /// /// let from = audio::interleaved![[1, 2, 3, 4]; 2]; /// let mut to = audio::interleaved![[0; 4]; 2]; /// /// l...
#![feature(proc_macro_hygiene, decl_macro)] #[macro_use] extern crate rocket; use rocket_contrib::templates::Template; use std::collections::HashMap; #[get("/")] fn index() -> Template { let mut context = HashMap::<String, String>::new(); context.insert("welcome".to_string(), "Welcome to Rocket !".to_string());...
#![allow(dead_code)] mod ep32; fn main() { ep32::run(); }
use std::collections::HashMap; use std::io::BufReader; use std::io::prelude::*; use std::net::{TcpListener, TcpStream}; use std::str; use std::thread; use http::request::Request; use http::response::Response; /// HTTP server #[derive(Clone)] pub struct Server { pub name: String, pub handlers: Vec<fn(Request, ...
//! Contains the `ColumnIndex`, `Row`, and `FromRow` traits. use crate::database::Database; use crate::decode::Decode; use crate::types::{Type, TypeInfo}; use crate::value::{HasRawValue, RawValue}; use serde::de::DeserializeOwned; /// A type that can be used to index into a [`Row`]. /// /// The [`get`] and [`try_get...
use std::io::Read; fn main() { let mut buf = String::new(); // 標準入力から全部bufに読み込む std::io::stdin().read_to_string(&mut buf).unwrap(); let mut iter = buf.split_whitespace(); let s: String = iter.next().unwrap().parse().unwrap(); let numbers: Vec<i32> = s.chars().map(|x| x.to_digit(10).unwrap() a...
use crate::error::ServiceError; use crate::models::user::User; use crate::Pool; use actix_identity::Identity; use actix_web::{error::BlockingError, web, HttpResponse}; use diesel::prelude::*; use serde::{Deserialize, Serialize}; #[derive(Deserialize)] pub struct AuthData { pub username: String, pub password: S...
#![deny(rust_2018_compatibility, rust_2018_idioms)] #[macro_use] extern crate gfx; // Reexport modules from gfx_voxel while stuff is moving // from Hematite to the library. pub use gfx_voxel::{array, cube}; use std::cmp::max; use std::f32::consts::PI; use std::fs::File; use std::path::{Path, PathBuf}; use std::time:...
use liblumen_alloc::erts::exception; use liblumen_alloc::erts::process::Process; use liblumen_alloc::erts::term::prelude::Term; /// `+/2` infix operator #[native_implemented::function(erlang:+/2)] pub fn result(process: &Process, augend: Term, addend: Term) -> exception::Result<Term> { number_infix_operator!(augen...
#![allow(non_camel_case_types, non_upper_case_globals, overflowing_literals)] pub mod plugin; use std::os::raw::*; // krb5/krb5.h:136 pub enum _profile_t {} pub type krb5_octet = u8; pub type krb5_int16 = i16; pub type krb5_ui_2 = u16; pub type krb5_int32 = i32; pub type krb5_ui_4 = u32; pub const VALID_INT_BITS...
// Copyright 2018 TiKV Project Authors. Licensed under Apache-2.0. #![cfg_attr(test, feature(test))] #![feature(core_intrinsics)] #![feature(ptr_offset_from)] #[macro_use] extern crate quick_error; #[cfg(test)] extern crate test; #[allow(unused_extern_crates)] extern crate tikv_alloc; mod buffer; mod byte; mod conve...
#![allow(missing_docs)] /// Converts AST to a pretty printed source string. pub mod pretty_print; use super::ast::*; pub use self::pretty_print::PrettyPrintVisitor; macro_rules! make_visitor { ($visitor_trait_name:ident, $($mutability:ident)*) => { #[cfg_attr(rustfmt, rustfmt_skip)] pub trait $v...
// Copyright 2016 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 ...
extern crate bootstrap_rs as bootstrap; extern crate bootstrap_gl as gl; extern crate stopwatch; use bootstrap::window::*; use gl::types::*; use std::time::{Duration, Instant}; use stopwatch::PrettyDuration; static VERTEX_POSITIONS: &'static [f32] = &[ -1.0, -1.0, 0.0, 1.0, -1.0, 0.0, 0.0, 1.0, 0.0, ];...
// Copyright 2022 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 agre...
use cipher::{self, Mode}; use encoding::base64::*; use std::fs; fn main() { println!("🔓 Challenge 10"); let cbc_cipher = cipher::new(Mode::CBC); let ct_base64: String = fs::read_to_string("challenges/data/chal10.txt") .unwrap() .lines() .collect(); let ct_bytes = Base64::from_s...
// -*- rust -*- import driver.session; import front.ast; import lib.llvm.False; import lib.llvm.llvm; import lib.llvm.mk_object_file; import lib.llvm.mk_section_iter; import middle.fold; import middle.metadata; import middle.trans; import middle.ty; import back.x86; import util.common; import util.common.span; import...
mod websocket; use crate::lttp::{ app_state::Update, server_config::ServerConfigUpdate, AppState, DungeonState, DungeonUpdate, GameState, LocationState, LocationUpdate, ServerConfig, }; use axum::{ extract::{ self, ws::{ Message, WebSocke...
extern crate rayon_logs; use itertools::Itertools; use itertools::{kmerge, merge}; use rayon::prelude::*; use rayon::{join, join_context, ThreadPool, ThreadPoolBuilder}; pub fn merge_n(input: &mut [u64], buffer: &mut [u64], n: usize) { let chunksize = input.len() / n; let inputs: Vec<&mut [u64]> = input.chunks...
// Copyright (c) 2020 DarkWeb Design // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish...
use crate::{ event::{log_schema, Event, Value}, sinks::util::{ http::{BatchedHttpSink, HttpClient, HttpSink}, service2::TowerRequestConfig, BatchConfig, BatchSettings, BoxedRawValue, JsonArrayBuffer, UriSerde, }, topology::config::{DataType, SinkConfig, SinkContext, SinkDescripti...
use piston::input::RenderArgs; use opengl_graphics::GlGraphics; use graphics::Context; pub trait Renderable { fn render(&mut self, ctx: &Context, gl: &mut GlGraphics); }
#![cfg_attr(not(feature = "std"), no_std)] /// A runtime module template with necessary imports /// Feel free to remove or edit this file as needed. /// If you change the name of this file, make sure to update its references in runtime/src/lib.rs /// If you remove this file, you can remove those references /// For m...
use std::time::Duration; use libusb::{DeviceDescriptor, DeviceHandle, Error, Result}; #[derive(Debug)] pub struct DeviceInfo { pub manufacturer: String, pub name: String, pub serial: String, } impl DeviceInfo { pub(super) fn read(handle: &DeviceHandle, descriptor: &DeviceDescriptor) -> Result<DeviceI...
use crate::cpu::CPU; use crate::memory_map::{IOMem, Mem, Mem16}; use crate::register::{Flag, Imm16, Imm8, Reg16, Reg8, SignedImm8}; use crate::{Either, ReadWriteError, Src}; use std::fmt; /// Describes a condition, used in jumps, calls and returns. /// It can be read to get the boolean value of the condition. #[deriv...
fn main() { println!("Forward Euler!"); }
#![allow(non_snake_case)] pub fn sum(slice: &[i32], default: i32) -> i32 { let mut iSum = default; for iVal in slice { let val = iVal; iSum = iSum + val; } iSum } pub fn distinct(vec: &Vec<i32>) -> Vec<i32> { let mut distinctVec: Vec<i32> = Vec::new(); for iVal in vec { ...
use core::mem::size_of; use color::*; use {EntryPoint, elf, kernel_proto}; use conf::Configuration; use uefi::status::*; use uefi::boot_services::protocols; use uefi::boot_services::{BootServices, AllocateType, MemoryDescriptor, MemoryType...
// Copyright 2015 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 ...
mod error; use gstreamer::glib::{MainLoop, SourceId}; use gstreamer::prelude::*; use gstreamer::*; use gstreamer_audio::{AudioFormat, AudioInfo}; use std::io::Write; use std::slice; use std::sync::{Arc, Mutex}; const CHUNK_SIZE: usize = 1024; /* Amount of bytes we are sending in each buffer */ const SAMPLE_RATE: u32 ...
pub mod treapimpl; pub use crate::treapimpl::v2::Treap;
use quicksilver::geom::Vector; #[derive(Clone, Debug, PartialEq)] pub struct Asteroid { pub pos: Vector, pub velocity: Vector, pub color: &'static str, } impl Asteroid { pub fn update(&mut self, time_delta: f32) { self.pos += self.velocity * time_delta; } } #[derive(Clone,Copy)] // Repre...
use crate::abst::{Controller, Input, Presenter}; pub struct Mock { inputs: Vec<Input>, expected: f64, } impl Mock { #[allow(dead_code)] pub fn new(inputs: impl IntoIterator<Item = Input>, expected: f64) -> Self { Self { inputs: inputs.into_iter().collect(), expected, } } } impl Controll...
use clippy_utils::diagnostics::span_lint_and_sugg; use clippy_utils::ty::same_type_and_consts; use clippy_utils::{meets_msrv, msrvs}; use if_chain::if_chain; use rustc_data_structures::fx::FxHashSet; use rustc_errors::Applicability; use rustc_hir::{ self as hir, def::{CtorOf, DefKind, Res}, def_id::LocalDef...
use std::convert::Into; use std::fmt::{Display, Formatter}; #[derive(Clone, Debug)] pub struct Node(pub String); impl Display for Node { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { write!(f, "{}", self.0) } } impl Node { pub fn new(key: String) -> Self { Self(key) } } ...
use std::char; use std::collections::BTreeSet; use fst::Map; const BYTES: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/unicode/name_fst.bin")); include!(concat!(env!("OUT_DIR"), "/unicode/names.rs")); fn query_fst(word: &str) -> Vec<char> { lazy_static! { static ref FST: Map<Vec<u8>> = Map::new(BYTE...
#[doc = "Reader of register SR"] pub type R = crate::R<u32, super::SR>; #[doc = "Reader of field `TAMP1F`"] pub type TAMP1F_R = crate::R<bool, bool>; #[doc = "Reader of field `TAMP2F`"] pub type TAMP2F_R = crate::R<bool, bool>; #[doc = "Reader of field `TAMP3F`"] pub type TAMP3F_R = crate::R<bool, bool>; #[doc = "Reade...
use objc_foundation::NSObject; use super::{AvCaptureInput, AvCaptureInputPort}; use super::super::AvCaptureDevice; /// Capture Device Input /// /// `AVCaptureDeviceInput` is a concrete sub-class of `AVCaptureInput` you use to capture data from /// an `AVCaptureDevice` object. pub struct AvCaptureDeviceInput { /// Th...
use std::io; fn main() { let mut buf = String::new(); io::stdin().read_line(&mut buf).unwrap(); let mut iter = buf.split_whitespace(); let a: i64 = iter.next().unwrap().parse().unwrap(); let b: i64 = iter.next().unwrap().parse().unwrap(); if a <= 8 && b <= 8 { println!("Yay!"); } ...
// Copyright 2023 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 dlal_component_base::{component, json, serde_json, Body, CmdResult}; component!( {"in": ["midi"], "out": ["midi"]}, [ "run_size", "sample_rate", "multi", {"name": "field_helpers", "fields": ["pattern"], "kinds": ["json"]}, {"name": "field_helpers", "fields": ["durati...