text
stringlengths
8
4.13M
use super::union_find; pub struct Grid { n: usize, qu: union_find::WeightedQuickUnion, unblocked: Vec<bool> } impl Grid { pub fn new(n: usize) -> Grid { let mut unbl = vec![false; n.pow(2)+2]; unbl[0] = true; unbl[n.pow(2)+1] = true; Grid { n, q...
use super::generate::Program; use super::generate::Function; use super::generate::Value; use super::parse::Operator; use std::io::{BufWriter, Write}; fn pullup<W: Write>(regs: &mut Vec<usize>, reg: usize, writer: &mut BufWriter<W>) { let mut index = 0; for (i, r) in regs.iter().enumerate() { if *r == ...
#[derive(Debug)] struct TrainOriginator { orig: String, dst: String, } #[derive(Debug)] struct Memento { orig: String, dst: String, } impl TrainOriginator { fn new() -> TrainOriginator { TrainOriginator { orig: "".to_string(), dst: "".to_string() } } fn save_to_memento(&self) -> M...
#[allow(non_snake_case)] pub mod measurement { extern crate nalgebra as na; use na::{Vector2, Vector3, Vector4}; use crate::ukf_type; use ukf_type::ukf::*; pub trait SensorMeasurement<T> {} pub trait DeviceSensor<T> { fn new() -> T; } pub trait HasSensorNoiseCovar<T, U>: Dev...
use libc; use std::io::{self, Result, Error, ErrorKind}; pub type MemoryId = libc::c_int; pub const INVALID_MEMORY_ID: MemoryId = -1; #[doc(hidden)] pub trait IsMinusOne { fn is_minus_one(&self) -> bool; } macro_rules! impl_is_minus_one { ($($t:ident)*) => ($(impl IsMinusOne for $t { fn is_minus_one(...
fn main() { let input: [i32; 6] = [1, 2, 3, 4, 10, 11]; let mut sum: i32 = 0; for x in input.iter() { sum += x; } println!("sum: {}", sum); }
//! This module provides the feature of search based `jump-to-definition`, inspired //! by https://github.com/jacktasia/dumb-jump, powered by a set of regular expressions //! based on the file extension, using the ripgrep tool. //! //! The matches are run through a shared set of heuristic methods to find the best candi...
// 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 ...
use anyhow::{bail, Context}; use nom::{ call, char, character::streaming::{anychar, digit1, line_ending}, complete, do_parse, many0, map_res, named, opt, take_while1, }; const INPUT: &[u8] = include_bytes!("input.txt"); #[derive(Debug, Clone)] struct Policy { pub character: char, pub bounds: (usiz...
use front::stdlib::value::{Value, ResultValue, to_value, from_value}; use front::stdlib::function::Function; use front::stdlib::object::{PROTOTYPE, Property}; /// Create new string pub fn make_string(_:Vec<Value>, _:Value, _:Value, this:Value) -> ResultValue { this.set_field("length", to_value(0i32)); Ok(Value...
use std::fs; use std::io; use std::path::Path; use std::io::Write; #[cfg(target_family = "unix")] use std::os::unix::fs::PermissionsExt; /// Checks for existence of the provided path, returning an error in case it doesn't exist. /// /// Mostly a convenient wrapper for spawning consistent [Error](../../error/struct.E...
// Copyright (c) The Starcoin Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::module::to_invalid_param_err; use jsonrpc_core::Result; use starcoin_config::NodeConfig; use starcoin_logger::prelude::LevelFilter; use starcoin_logger::LoggerHandle; use starcoin_rpc_api::debug::DebugApi; use std::str::F...
use std::cmp; use std::io; fn main() { let mut buf = String::new(); io::stdin().read_line(&mut buf).unwrap(); let mut iter = buf.split_whitespace(); let mut n: i64 = iter.next().unwrap().parse().unwrap(); let k: i64 = iter.next().unwrap().parse().unwrap(); // 0がでたら終了 // 暫定Nと同じ値がでたら終了 ...
pub struct URLBuilder { base_url: String, queries: Vec<(String, String)>, } impl<'a> URLBuilder { pub fn new(base_url: String) -> URLBuilder { URLBuilder { base_url, queries: vec![], } } pub fn add_queries(&mut self, queries: &mut Vec<(String, String)>) -> &...
use calculator::parsemath::parser::Parser; use calculator::parsemath::ast::Node::*; macro_rules! add { ($left_node:expr, $right_node:expr) => { Add(Box::new($left_node), Box::new($right_node)) } } macro_rules! negative { ($node:expr) => { Negative(Box::new($node)) } } macro_rules! m...
pub mod enemies; pub mod player;
// 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::auth_provider::{self, GoogleAuthProvider}; use crate::http::UrlLoaderHttpClient; use crate::web::DefaultStandaloneWebFrame; use failure::Error; ...
use crate::target::Target; use crate::climsg::CliMsg; use std::fs; pub struct MakeTarget { filename: String, target: Option<String>, remove: bool, input_file: String, output_file: String, } impl MakeTarget { pub fn new(filename: &str, remove: bool, input_file: &str, output_file: &str) -> Make...
#[doc = "Reader of register IE"] pub type R = crate::R<u32, super::IE>; #[doc = "Reader of field `RF0NE`"] pub type RF0NE_R = crate::R<bool, bool>; #[doc = "Reader of field `RF0WE`"] pub type RF0WE_R = crate::R<bool, bool>; #[doc = "Reader of field `RF0FE`"] pub type RF0FE_R = crate::R<bool, bool>; #[doc = "Reader of f...
use clap::{value_parser, Arg, Command}; use reproduce::{Config, Controller}; use std::num::NonZeroU64; use tokio::task; use tracing::{error, info}; #[tokio::main] pub async fn main() { tracing_subscriber::fmt::init(); let config = parse(); info!("{config}"); let mut controller = Controller::new(config)...
#[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::TPLOG5 { #[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 bootstrap_rs as bootstrap; use bootstrap::window::*; fn main() { let mut window = Window::new("Bootstrap Window").unwrap(); for message in window.message_pump() { println!("message: {:?}", message); if let Message::Close = message { break; } } }
use crate::{errors::*, os, strategy}; use failure::Fail; use memmap::Mmap; use std::{fs::File, io, path::Path}; pub const MIN_READ_BUF_SIZE: usize = os::PAGE_SIZE; pub const MAX_READ_BUF_SIZE: usize = 4 * 1024 * 1024; /// Allocate a memory buffer on the stack and initialize it for the reader /// /// This macro takes...
use std::path::Path; use std::fs; use goblin::{error, container}; use goblin::elf::{Elf, Sym}; use goblin::elf::program_header::ProgramHeader; use goblin::pe::{PE, export}; use scroll::{Pread, Pwrite}; use std::io::{Cursor, Write}; use goblin::mach::load_command::SIZEOF_SECTION_32; use goblin::pe::section_table::{IMAGE...
mod read_func; use read_func::read_func; fn main() { read_func(); println!("Hello, world!"); }
use bstr::{BStr, ByteSlice}; use std::fmt; use crate::object::Object; use crate::reference::{Direct, Error, ParseError}; use crate::repository::Repository; #[derive(PartialEq)] pub struct Symbolic { direct_peel: Option<Direct>, data: Vec<u8>, } impl Symbolic { pub fn from_bytes(reference: &[u8], peel: Op...
//! CLI config for the ingester using the RPC write path use std::path::PathBuf; use crate::gossip::GossipConfig; /// CLI config for the ingester using the RPC write path #[derive(Debug, Clone, clap::Parser)] #[allow(missing_copy_implementations)] pub struct IngesterConfig { /// Gossip config. #[clap(flatten...
/// A wrapper for a slice of references. /// /// Available only through a (possibly mutable) reference. /// /// ## Usage /// /// Can be created from (a (possibly mutable) reference to) a slice /// of (possibly mutable) references by means of the `From` trait or /// with the help of [`new`](#method.new) and [`new_mut`...
pub struct Symbol { importance: u8, } impl Symbol { pub fn new() -> Symbol { Symbol { importance: 5, } } } /*// Copyright (c) 2015 The Gus Project Developers. All rights reserved. // See the LICENSE file at the top-level directory of this distribution. // This file may not be copied, modified, or distribute...
// Copyright 2021 Chiral Ltd. // Licensed under the Apache-2.0 license (https://opensource.org/licenses/Apache-2.0) // This file may not be copied, modified, or distributed // except according to those terms. mod mapping_ops; mod case_breakable; mod case_cyclic; mod reducible_graph; mod graph_separable; mod graph_high...
pub mod week1; pub mod week2; pub mod week3; pub mod week4; pub mod week5;
#[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::PP { #[doc = r"Modifies the contents of the register"] #[inline(always)] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'w m...
use std::fmt::Display; use lambda_runtime::error::HandlerError; use thiserror::Error; #[derive(Error, Debug, PartialEq, Clone)] pub enum MetricForwarderError { #[error("Couldn't create CloudwatchLogsData from gunzipped json: {0}")] ParseStringToLogsdataError(String), #[error("Couldn't base64 decode aws lo...
#[macro_use] mod sender; #[macro_use] mod macros; mod utils; #[allow(non_snake_case)] #[allow(unused_parens)] #[allow(clippy::new_without_default)] pub mod client { //! Implements the model for the frames that a STOMP client can send, as specified in //! the [STOMP Protocol Specification,Version 1.2](https://...
mod grinbox_address; mod grinbox_message; mod grinbox_request; mod grinbox_response; mod tx_proof; pub use grin_wallet_libwallet::Slate; pub use parking_lot::{Mutex, MutexGuard}; pub use std::sync::Arc; pub use self::grinbox_address::{ hrp_bytes, GrinboxAddress, GRINRELAY_ADDRESS_HRP_MAINNET, GRINRELAY_ADDRESS_HRP_T...
use na::{Vector3}; pub struct Image { dimension: Vector2<f32> pixels: Vec<Vector3<f32>> } impl Image { fn to_ppm<W: Write>(&self, w: &mut W) { let _ = w.write("P3\n".as_bytes()); } fn to_png() { } }
#[macro_use] extern crate failure; use std::io::Read; use json_utils::json::JsValue; use la_rete::core::ruleset::*; use la_rete::core::Matcher; use la_rete::core::TrieBuildFailure; use la_rete::json::parse_ruleset as parse_json_ruleset; #[derive(Debug, Fail)] enum Failure { #[fail(display = "Failure::RulesetPars...
//! Day 16 use std::{cmp::PartialOrd, collections::HashSet}; use itertools::Itertools; trait Solution { fn part_1(&self) -> usize; fn part_2(&self) -> usize; } impl Solution for str { fn part_1(&self) -> usize { let (rules, _, tickets) = parsers::input(self).expect("Failed to parse the input"); ...
extern crate byteorder; extern crate crc; #[macro_use] extern crate failure; extern crate rand; mod cpu; mod flags; mod graphics; mod instruction; mod memory; mod register; mod rom; pub use cpu::Cpu; pub use instruction::{Condition, Instruction, Operation}; pub use rom::{Rom, RomFormat, Version};
extern crate gcd; #[test] fn sanity_value_ripped_from_wikipedia() { use gcd::gcd; assert_eq!(gcd(48, 18), 6i64); assert_eq!(gcd(54, 24), 6i64); assert_eq!(gcd(48, 180), 12i64); }
// This file is part of linux-epoll. It is subject to the license terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/linux-epoll/master/COPYRIGHT. No part of linux-epoll, including this file, may be copied, modified, propagated, or distri...
/// Windows-related functions use crate::G; use ncurses::*; use std::collections::HashMap; impl G { /// Look up a color attribute by the given name pub fn wcget(&self, c: &str) -> u32 { if let Some(attr) = self.color.get(c) { *attr } else { panic!("undeclared color {}",...
//! Token values. //! //! Token is a process-wide constant integer value associated with a string, //! similar to Symbol in Ruby or Atom in Erlang. use super::symbol; use std::str; use std::ffi::CStr; pub type Token = u32; /// Returns a token corresponded with `name`. /// /// # Examples /// /// ``` /// use plugkit::...
//! A TCP client //! //! Sends "hello world" to a server on port 8080, and echoes the response. To //! spawn the server, do: //! ```sh //! $ cargo run --example tcp-echo //! ``` use futures::prelude::*; use runtime::net::TcpStream; #[runtime::main] async fn main() -> Result<(), failure::Error> { let mut stream = ...
/* */ pub mod typedefs;
use juniper::graphql_interface; #[graphql_interface(for = Node2Value)] trait Node1 { fn id() -> String; } #[graphql_interface(impl = Node1Value, for = Node3Value)] trait Node2 { fn id(&self) -> &str; } #[graphql_interface(impl = Node2Value)] trait Node3 { fn id() -> &'static str; } fn main() {}
// Copyright 2019 The vault713 Developers // // 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 a...
pub use {frame_rate::*, timer::*}; mod frame_rate; #[macro_use] mod timer;
use std::{ fmt::{self, Debug}, str, }; #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] pub enum ProtobufType { Double, Float, Int32, Int64, Uint32, Uint64, Sint32, Sint64, Fixed32, Fixed64, Sfixed32, Sfixed64, Bool, String, Bytes, Repeated...
#![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 InjectedInputButtonChangeKind(pub i32); impl InjectedInputButtonChangeKind { pub const None: Self = Self(0i32); pub cons...
mod expr; pub use expr::*; mod number; pub use number::*; mod op; pub use op::*; mod var; pub use var::*;
#[macro_export] macro_rules! example_bad_value { () => (1i32) // ^^^^ERR mismatched types // ^^^^ERR expected (), found i32 // ^^^^NOTE expected type `()` // ^^^^MSG macro-expansion-inside-2.rs:7 }
#[doc = "Reader of register STAT"] pub type R = crate::R<u32, super::STAT>; #[doc = "Reader of field `ERROR`"] pub type ERROR_R = crate::R<bool, bool>; #[doc = "Reader of field `DIRECTION`"] pub type DIRECTION_R = crate::R<bool, bool>; impl R { #[doc = "Bit 0 - Error Detected"] #[inline(always)] pub fn erro...
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)] #[cfg(feature = "Security_Authentication_Web_Core")] pub mod Core; #[cfg(feature = "Security_Authentication_Web_Provider")] pub mod Provider; #[repr(transparent)] #[doc(hidden)] pub struct IW...
use std::collections::HashMap; use std::hash::Hash; use std::cmp::Eq; pub trait Counter<T>: Iterator<Item = T> { fn counter(self) -> HashMap<T, usize>; } impl<T: Hash + Eq, I: Iterator<Item = T>> Counter<T> for I { fn counter(self) -> HashMap<T, usize> { let mut res = HashMap::new(); for t in ...
// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. pub fn serialize_operation_cancel_rotate_secret( input: &crate::input::CancelRotateSecretInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize...
use std::fmt::Debug; #[cfg(test)] use pretty_assertions::assert_eq; use wce_formats::{BinaryConverter, GameVersion}; use wce_formats::binary_reader::BinaryReader; use wce_formats::binary_writer::BinaryWriter; use wce_formats::GameVersion::{Reforged, RoC, TFT}; use wce_formats::MapArchive; use crate::globals::MAP_INF...
extern crate bincode; use bincode::{deserialize_from, serialize_into}; extern crate app_dirs; use app_dirs::{app_root, AppDataType, AppInfo}; extern crate ggez; use ggez::conf::{Conf, WindowMode, WindowSetup}; use ggez::event; use ggez::event::{EventHandler, Keycode, Mod}; use ggez::graphics; use ggez::graphics::spri...
#![deny(clippy::all)] pub mod base64; pub mod hex; use anyhow::Result; use base64::*; pub fn hex_to_base64(hex: &str) -> Result<Base64> { let bytes = hex::hexstr_to_bytes(&hex)?; Ok(Base64::from(&bytes[..])) } pub fn base64_to_hex(b64: Base64) -> String { hex::bytes_to_hexstr(&b64.as_bytes()[..]) } #[cf...
pub(crate) mod liberica; use anyhow::Result; use std::path::{Path, PathBuf}; use std::process::Command; pub trait Jre { fn check_jre_archive<P: AsRef<Path>>(&self, path: P) -> Result<()>; fn check_jre_folder<P: AsRef<Path>>(&self, folder: P, zip: P) -> Result<()>; fn extract_jre<P: AsRef<Path>>(&self, f...
use P60::*; pub fn main() { println!("{}", max_hbal_height(4)); }
#[doc = "Reader of register RIS"] pub type R = crate::R<u32, super::RIS>; #[doc = "Reader of field `BOR1RIS`"] pub type BOR1RIS_R = crate::R<bool, bool>; #[doc = "Reader of field `MOFRIS`"] pub type MOFRIS_R = crate::R<bool, bool>; #[doc = "Reader of field `PLLLRIS`"] pub type PLLLRIS_R = crate::R<bool, bool>; #[doc = ...
use nom::bytes::complete::tag; use nom::character::complete::{alphanumeric1, multispace0}; use nom::combinator::opt; use nom::sequence::{preceded, terminated, tuple}; use crate::assembler::instruction_parsers::{Action, AssemblerInstruction}; use crate::assembler::label_parsers::label_declaration_parser; use crate::ass...
#![type_length_limit = "1214269"] // Our types are simply too powerful mod accumulate_metrics; mod cloudwatch_logs_parse; mod cloudwatch_send; mod deser_logs_data; mod error; use std::sync::{ Arc, Mutex, }; use aws_lambda_events::event::cloudwatch_logs::CloudwatchLogsEvent; use grapl_config::env_helpers::Fro...
fn read_clone<T>(read: &mut Vec<T>, start: usize, end: usize) -> Vec<T> where T: Clone { let mut el_read: Vec<T> = Vec::new(); let mut el: Option<T> = None; let mut foo: Vec<T> = Vec::new(); for _ in 0..read.len() - start { el_read.push(read.pop().unwrap()); } for _ in start..end + 1 { el = el_read.pop(); ...
/// Url2 Result Type pub type Url2Result<T> = Result<T, Url2Error>; #[derive(Debug, Clone, PartialEq, Eq)] /// Represents a Url2 Error pub struct Url2Error(Box<Url2ErrorKind>); impl Url2Error { /// access the Url2ErrorKind for this error pub fn kind(&self) -> &Url2ErrorKind { &self.0 } /// co...
//! Bindings to winapi's `PCCERT_CONTEXT` APIs. use std::ffi::OsString; use std::io; use std::mem; use std::os::windows::prelude::*; use std::ptr; use crypt32; use winapi; use Inner; /// Wrapper of a winapi certificate, or a `PCCERT_CONTEXT`. #[derive(Debug)] pub struct CertContext(winapi::PCCERT_CONTEXT); unsafe ...
//! Xuantie extended CSRs // Extended state registers for performance cores pub mod mxstatus; // 0x7C0 pub mod mhcr; // 0x7C1 pub mod mcor; // 0x7C2 // pub mod mccr2; // 0x7C3 // pub mod mcer2; // 0x7C4 pub mod mhint; // 0x7C5 pub mod mrmr; // 0x7C6 pub mod mrvbr; // 0x7C7 // pub mod mcer; // 0x7C8 // pub mod mcounter...
//! A Kodi repository server, with specific support for serving addons straight out of Git //! repositories. Uses an extra directory on disk to cache `.zip` files. use std::borrow::Cow; use std::ffi::OsStr; use std::path::Path; use std::fs; const IDS_XPATH: &str = "/addons/addon/@id"; /// Retrieve addon IDs from rep...
use core::alloc::Layout; use core::fmt; use core::mem; use core::ptr::{self, NonNull}; use core::slice; use core::str; use hashbrown::HashMap; use lazy_static::lazy_static; use firefly_arena::DroplessArena; use firefly_system::sync::RwLock; use super::{Atom, AtomError}; lazy_static! { /// The atom table used by...
static mut N: usize = 0; static mut ITEMS: Vec<usize> = Vec::new(); #[no_mangle] pub extern "C" fn set(x: usize) { unsafe { N = x } } #[no_mangle] pub extern "C" fn get() -> usize { unsafe { N } } #[no_mangle] pub extern "C" fn push(x: usize) { unsafe { ITEMS.push(x) } } #[no_mangle] pub extern "C" fn s...
pub use anyhow; pub use bevy; pub use crossbeam; pub use derive_more; pub use rand; pub use rand_pcg; pub use serde; pub use serde_json; pub use tracing; /// Temporary fix for bevy's derive macros since some of them rely on /// `crate::X` items existing when using a re-exported bevy #[macro_export] #[rustfmt::skip] //...
use crate::prelude::*; use std::os::raw::c_void; #[repr(C)] #[derive(Debug)] pub struct VkDisplayModeCreateInfoKHR { pub sType: VkStructureType, pub pNext: *const c_void, pub flags: VkDisplayModeCreateFlagBitsKHR, pub parameters: VkDisplayModeParametersKHR, }
pub mod library_items;
#![deny(unsafe_code)] // #![deny(warnings)] extern crate cortex_m; // #[macro_use(block)] // extern crate nb; use embedded_hal::blocking::delay::DelayMs; use embedded_hal::blocking::i2c::{Write, WriteRead}; pub struct Pcm5122<I2C> { i2c: I2C, dac_addr: u8, } impl<I2C, E> Pcm5122<I2C> where I2C: WriteRe...
use std::{ thread::spawn, collections::HashMap, net::TcpStream, sync::Once, }; extern crate httpserv; use httpserv::*; static SETUP: Once = Once::new(); fn setup_httpserv() { SETUP.call_once(|| { spawn(|| { Httpserv::new(Config { root: "./tests/webroot".into(), hostname: "localhos...
extern crate clap; extern crate kcacheext; use clap::{App, Arg}; use std::error::Error; use std::fs::File; use std::io::prelude::*; fn main() { let matches = App::new("kcache_extract") .version(env!("CARGO_PKG_VERSION")) .author("marcograss") .about("Extract a decrypted iOS 64-bit kernelca...
extern crate regex; #[macro_use] extern crate itertools; use regex::Regex; use itertools::Itertools; use std::env; use self::Opcode::*; mod literals; use literals::FloatOrInteger; struct Lexeme<'a, T:Node>{ pos: usize, type_name: &'a str, istr: &'a str, value: Option<Value<'a, T>>, } pub struct BinOp...
// 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 failure::Error; use fidl_fuchsia_sys::FileDescriptor; use fuchsia_async as fasync; use fuchsia_component::client::{launch_with_options, launcher, Launc...
mod unit_extension; #[derive(Deserialize,Debug,PartialEq,Default,Clone)] pub struct Weapon { pub name: String, #[serde(default)] pub reach: i32, #[serde(default)] pub attacks: f64, #[serde(default)] pub hit: i32, #[serde(default)] pub wound: i32, #[serde(default)] pub rend: ...
use crate::core::language::Language; // use std::slice::SliceIndex; /// The current node stack along with it's hash. Used for context comparison. #[derive(Debug, Default, Clone)] pub(super) struct NodeWalkerStack<'tree> { nodes: Vec<tree_sitter::Node<'tree>>, } impl<'tree> NodeWalkerStack<'tree> { fn new() ->...
use std::thread; use std::path::PathBuf; use std::fs::File; use std::io::{Read, Write}; use std::process::Command; use std::ffi::OsStr; use futures::IntoFuture; use futures::sync::oneshot::{channel, Sender, Receiver}; use hex_database::{Track, utils::fingerprint_from_file}; use hex_music_container::{Container, Configu...
use metric::{Attributes, DurationHistogram, Metric}; #[track_caller] pub fn assert_catalog_access_metric_count(metrics: &metric::Registry, name: &'static str, n: u64) { let histogram = metrics .get_instrument::<Metric<DurationHistogram>>("catalog_op_duration") .expect("failed to read metric") ...
// Copyright (c) 2021 Quark Container Authors / 2018 The gVisor Authors. // // 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 ...
use std::fs; fn main() { let contents = fs::read_to_string("input.txt") .expect("Failed to read file"); let mut numbers = Vec::new(); for line in contents.trim().split("\n") { let num: i32 = line.parse().unwrap(); numbers.push(num); } for num1 in &numbers { for num2...
#[doc = "Reader of register ENABLE"] pub type R = crate::R<u32, super::ENABLE>; #[doc = "Writer for register ENABLE"] pub type W = crate::W<u32, super::ENABLE>; #[doc = "Register ENABLE `reset()`'s with value 0"] impl crate::ResetValue for super::ENABLE { type Type = u32; #[inline(always)] fn reset_value() ...
#[doc = r" Value to write to the register"] pub struct W { bits: u32, } impl super::INTENCLR { #[doc = r" Writes to the register"] #[inline] pub fn write<F>(&self, f: F) where F: FnOnce(&mut W) -> &mut W, { let mut w = W::reset_value(); f(&mut w); self.register.se...
// allows node variants to be used without prefix. use crate::Node::*; use std::fmt::{Display, Formatter, Result}; enum Node{ Part(u32, Box<Node>), End } impl Node{ fn new()-> Node{ End } fn prepend(self, elem: u32)-> Node{ Part(elem, Box::new(self)) } fn len(&self)->u32{ match self{ ...
use crate::event::{Prefix, RawEvent, Event}; use std::error::Error; const SPACE: char = ' '; const COLON: char = ':'; const CRLF: &str = "\r\n"; fn to_prefix_server(input: &str) -> Prefix { Prefix::Server { host: input } } fn is_specialalphanum(c: u8, special: &[u8]) -> bool { special.contains(&c) || nom::is...
use std::*; fn main() { let args: Vec<String> = env::args().skip(1).collect(); for char in args.connect(" ").chars() { let codepoint = char as u32; print!("{}", if (codepoint) > 0x20 && (codepoint) < 0x7f { char::from_u32(codepoint + 0xfee0).unwrap() } else { ...
pub mod test; pub type Hz = f64; pub fn mu(exp: i32, vector: &Vec<f64>) -> f64 { let fraction = vector.iter() .enumerate() .fold((0.0, 0.0), |acc, x| { let num_inc = (x.0 as f64).powi(exp) * x.1.abs(); let den_inc = x.1; (acc.0 + num_in...
use crate::call::HandlerData; use crate::libcalls; use crate::relocation::{ LocalTrapSink, Reloc, RelocSink, Relocation, RelocationType, TrapSink, VmCall, VmCallKind, }; use byteorder::{ByteOrder, LittleEndian}; use cranelift_codegen::{ir, isa, Context}; use std::mem; use std::ptr::{write_unaligned, NonNull}; use w...
use data_types::{CompactionLevel, ParquetFile, Timestamp}; use crate::components::{ divide_initial::multiple_branches::order_files, files_split::{target_level_split::TargetLevelSplit, FilesSplit}, }; use crate::file_classification::FileToSplit; /// Return a struct that holds 2 sets of files: /// 1. Either fi...
pub mod decoder; pub mod encoder; const HEADER_LENGTH: usize = 64; /// Converts an array of bytes to an u32 integer. pub fn convert_byte_array_to_int(mut arr: Vec<u8>, big_endian: bool) -> u32 { let mut number: u32 = 0; if big_endian { arr.reverse(); } for (index, num) in arr.into_iter().enu...
use std::io; use std::result; #[cfg(feature = "rusqlite")] use hex_gossip; #[cfg(feature = "rusqlite")] use rusqlite; pub type Result<T> = result::Result<T, Error>; #[derive(Debug)] pub enum Error { #[cfg(feature = "rusqlite")] Sqlite(rusqlite::Error), #[cfg(feature = "rusqlite")] Gossip(hex_gossip::E...
use std::thread; use std::sync::mpsc; static NTHREADS: usize = 8; fn main() { let (tx, rx) = mpsc::channel(); for id in 0..NTHREADS { let thread_tx = tx.clone(); thread::spawn(move || { thread_tx.send(id).unwrap(); println!("thread {} done", id); }); } ...
#[macro_use] extern crate criterion; use criterion::Criterion; pub fn test_iter() -> Vec<usize> { (0..12) .filter(|x| x % 2 == 0) .map(|x| x * x) .collect() } pub fn test_for() -> Vec<usize> { let n = 12; let mut result = Vec::with_capacity(n); for x in 0..n { if x % 2...
use std::fmt; pub enum UseBy { Local, Repo { author: String }, Web { source: String }, } impl fmt::Debug for UseBy { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::Local => Ok(()), Self::Repo { author } => write!(f, " by {}", author), ...
fn crab_pos(input: &str) -> impl Iterator<Item = u32> + '_ { input.trim().split(',').map(|tok| tok.parse().unwrap()) } fn part1(input: &str) -> u32 { let crabs = crab_pos(input).collect::<Vec<_>>(); least_costly_point(&crabs, fuel_cost) } fn part2(input: &str) -> u32 { let crabs = crab_pos(input).coll...
#![feature(proc_macro, wasm_custom_section, wasm_import_module)] extern crate exif; extern crate wasm_bindgen; use exif::{Reader, Tag, Value}; use wasm_bindgen::prelude::*; #[wasm_bindgen] pub fn read_metadata(vec: &[u8]) -> Vec<f64> { match metadata(vec) { Some((a, b)) => vec![a, b], None => vec...