text stringlengths 8 4.13M |
|---|
pub mod blocks;
pub use self::blocks::Blocks;
pub mod defs_ok_false;
pub use self::defs_ok_false::DefsOkFalse;
pub mod defs_ok_true;
pub use self::defs_ok_true::DefsOkTrue;
pub mod objs_bot_profile;
pub use self::objs_bot_profile::ObjsBotProfile;
pub mod objs_bot_profile_icons;
pub use self::objs_bot_profile_icons::Obj... |
fn main() {
let (x, y, a, b) = {
let mut s = String::new();
std::io::stdin().read_line(&mut s).unwrap();
let mut ws = s.trim_end().split_whitespace();
let x = ws.next().unwrap().parse().unwrap();
let y = ws.next().unwrap().parse().unwrap();
let a = ws.next().unwrap().... |
use hlt::direction::Direction;
use hlt::entity::Entity;
use hlt::input::Input;
use hlt::map_cell::MapCell;
use hlt::map_cell::Structure;
use hlt::position::Position;
use hlt::ship::Ship;
use std::cmp::min;
use std::collections::BinaryHeap;
use std::cmp::Ordering;
pub struct GameMap {
pub width: usize,
pub heig... |
use crate::{
border::BorderBuilder,
brush::Brush,
core::{
color::Color,
inspect::{CastError, Inspect, PropertyInfo},
pool::Handle,
},
expander::ExpanderBuilder,
formatted_text::WrapMode,
grid::{Column, GridBuilder, Row},
inspector::editors::{
Layout, Prope... |
// Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(default, deny_unknown_fields)]
pub struct StateSyncConfig {
// Size of chunk to request for state synchronization
pub chunk... |
//! Event builder
use crate::{Entity, Event, EventBuilder, EventData};
use chrono::Utc;
use uuid::Uuid;
/// Purge event builder
///
/// Build an [`Event`] from a session id, used to purge entities. Purging deletes the entities.
/// It keeps the event history but sets the `data` property of all events related to the e... |
// q0024_swap_nodes_in_pairs
struct Solution;
use crate::util::ListNode;
impl Solution {
pub fn swap_pairs(head: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
let mut list = head;
let mut buf = vec![];
while let Some(l) = list {
buf.push(l.val);
list = l.next;
... |
pub trait DigitalInput: Send {
fn get_value(&self) -> bool;
} |
use anyhow::Result;
use super::super::ascii85::decode;
pub fn flip_every_other_bit(n: u8) -> u8 {
let mask = 0b0101_0101;
n ^ mask
}
pub fn rotate_right(n: u8) -> u8 {
let last_bit = n & 1;
(n >> 1) | (last_bit << 7)
}
#[test]
fn test_flip_every_other_bit() {
let input = 0b1010_1010;
let exp... |
use std::collections::BTreeMap;
use std::fs;
use eyre::Result;
use serde::Serialize;
use tera::Context;
use crate::content::posts::{PostItem, PostRef};
use crate::markdown::markdown_to_html;
use crate::paths::AbsPath;
use crate::{item::RenderContext, item::TeraItem, site_url::SiteUrl};
use super::posts::PostRefConte... |
use std::sync::{Arc, Mutex};
use std::collections::HashMap;
use serde::{Serialize, Deserialize};
use std::net::{SocketAddr};
use super::mempool::{Mempool};
use super::message::{Message, ServerSignal};
use super::blockchain::{BlockChain};
use mio_extras::channel::Sender as MioSender;
use crossbeam::channel::{Receiver, S... |
use std::any::Any;
pub trait Animal : Any {
fn speak(&self) -> &'static str;
}
|
use api_client::ApiClient;
use utils::decode_list;
use serde_json::value::Value;
use std::collections::hash_map::HashMap;
use errors::*;
// Struct for Cookbook List from /_latest URL
#[derive(Debug)]
pub struct Cookbooks {
count: usize,
cookbooks: Vec<String>,
client: ApiClient,
}
// Struct for Cookbook M... |
pub mod fps;
pub mod tracing;
|
pub fn abbreviate(phrase: &str) -> String {
// phrase.split_whitespace().fold(String::new(), |mut acc, s| {
// acc.push(s.chars().next().unwrap());
// acc
// })
phrase
.split_whitespace()
.flat_map(|word| {
word.split('-').map(move |split_word: &str| {
if split_word
.chars(... |
use rand::Rng;
use crate::Number;
use super::Term;
///A term which computes a random value each time it is called
pub struct RandomTerm<T: Number>
{
min: Box<dyn Term<T> + Send + Sync>,
max: Box<dyn Term<T> + Send + Sync>
}
impl<T: Number> RandomTerm<T>
{
///A term which randomly generates values betwe... |
struct Solution;
const CHAR_LE: u8 = 'e' as u8;
const CHAR_BE: u8 = 'E' as u8;
const CHAR_0: u8 = '0' as u8;
const CHAR_9: u8 = '9' as u8;
const CHAR_DOT: u8 = '.' as u8;
const CHAR_POS: u8 = '+' as u8;
const CHAR_NEG: u8 = '-' as u8;
const CHAR_SPACE: u8 = ' ' as u8;
use std::collections::HashMap;
#[derive(Debug, P... |
use crate::utils::lines_from_file;
use std::time::Instant;
pub fn main() {
let start = Instant::now();
assert_eq!(part_1_test(), 127);
// println!("part_1 {:?}", part_1());
assert_eq!(part_2_test(), 62);
println!("part_2 {:?}", part_2());
let duration = start.elapsed();
println!("Finishe... |
extern crate oxygengine_composite_renderer as renderer;
#[macro_use]
extern crate oxygengine_core as core;
use core::{
assets::{asset::AssetId, database::AssetsDatabase},
error::*,
Scalar,
};
use js_sys::{Array, Uint8Array};
use renderer::{
composite_renderer::*, font_asset_protocol::FontAsset, font_fa... |
use std::collections::{BTreeMap, HashMap};
use rbatis::crud::{CRUD, Skip};
use rbatis::plugin::page::{Page, PageRequest};
use crate::domain::domain::SysRes;
use crate::domain::dto::{ResEditDTO, ResPageDTO};
use crate::domain::vo::SysResVO;
use crate::error::Error;
use crate::error::Result;
use crate::service::CONTEXT... |
use std::env::args;
use std::result::Result;
use regex::Regex;
#[derive(Debug, Clone)]
struct Passport {
byr: String, //(Birth Year)
iyr: String, //(Issue Year)
eyr: String, //(Expiration Year)
hgt: String, //(Height)
hcl: String, //(Hair Color)
ecl: String, //(Eye Color)
pid: String, //(Pa... |
use ape;
use core;
use diesel;
use diesel_migrations;
use id3;
use getopts;
use image;
use hyper;
use iron::IronError;
use iron::status::Status;
use lewton;
use metaflac;
use regex;
use serde_json;
use std;
use toml;
error_chain! {
foreign_links {
Ape(ape::Error);
Diesel(diesel::result::Error);
... |
// Copyright (C) 2021 Deeper Network Inc.
// SPDX-License-Identifier: Apache-2.0
// 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
//
// Unle... |
#[doc = "Register `VERR` reader"]
pub type R = crate::R<VERR_SPEC>;
#[doc = "Field `MINREV` reader - Minor Revision"]
pub type MINREV_R = crate::FieldReader;
#[doc = "Field `MAJREV` reader - Major Revision"]
pub type MAJREV_R = crate::FieldReader;
impl R {
#[doc = "Bits 0:3 - Minor Revision"]
#[inline(always)]
... |
pub use self::artist_builder::*;
pub use self::code_builder::*;
pub use self::comp_builder::*;
pub use self::event_builder::*;
pub use self::fee_schedule_builder::*;
pub use self::hold_builder::*;
pub use self::order_builder::*;
pub use self::organization_builder::*;
pub use self::organization_invite_builder::*;
pub us... |
pub mod collectible;
pub mod dialog_box;
pub mod side_panel;
use self::{collectible::*, dialog_box::*, side_panel::*};
use crate::utils::rgba_to_raui_color;
use oxygengine::user_interface::raui::core::prelude::*;
use serde::{Deserialize, Serialize};
#[derive(PropsData, Debug, Default, Copy, Clone, Serialize, Deserial... |
#[doc = "Register `PRAR_PRG` reader"]
pub type R = crate::R<PRAR_PRG_SPEC>;
#[doc = "Register `PRAR_PRG` writer"]
pub type W = crate::W<PRAR_PRG_SPEC>;
#[doc = "Field `PROT_AREA_START` reader - Bank 1 PCROP area start configuration bits"]
pub type PROT_AREA_START_R = crate::FieldReader<u16>;
#[doc = "Field `PROT_AREA_S... |
use std::collections::BTreeMap;
use std::collections::btree_map;
use super::errors::*;
use super::models::*;
/// Adds the into_model() method for all types that supports ConvertToModel.
pub trait Merge {
/// Convert the current type to a model.
fn merge(&mut self, other: Self) -> Result<()>;
}
impl<T> Merge f... |
use crate::ast;
use crate::{Parse, ParseError, ParseErrorKind, Parser, Peek, Resolve, Spanned, Storage, ToTokens};
use runestick::Source;
use std::borrow::Cow;
/// A label, like `'foo`
#[derive(Debug, Clone, Copy, ToTokens, Spanned)]
pub struct Label {
/// The token of the label.
pub token: ast::Token,
///... |
pub struct Publisher {
connected: bool,
}
|
use crate::eval::{Expr, ExprSource};
use crate::value::NixValue;
use gc::{Finalize, Gc, GcCell, Trace};
use std::{collections::HashMap, path::PathBuf};
/// A parent Expr's scope is used to provide tooling for its child Exprs.
/// This enum would provide four scope types:
/// - None: Used for calculated literals. For e... |
use std::io::{self, *};
fn main() {
let mut rd = io::BufReader::new(io::stdin());
let mut n: usize;
let mut s = String::new();
rd.read_line(&mut s).unwrap();
n = s.trim().parse::<usize>().unwrap();
let rst = [0, 1, 0, 0, 2, 10, 4, 40, 92, 352, 724, 2680, 14200, 73712, 365596]
... |
use crate::parser::Error;
use crate::schedule_at;
use crate::time_domain::RuleKind::*;
#[test]
fn exact_date() -> Result<(), Error> {
assert_eq!(
schedule_at!(r#"2020Jun01 open"#, "2020-05-31"),
schedule! {}
);
assert_eq!(
schedule_at!(r#"2020Jun01:10:00-12:10"#, "2020-06-01"),
... |
// ClientMode
#![forbid(unsafe_code)]
#![deny(missing_docs)]
use anyhow::Result;
use std::str::FromStr;
/// Valid modes that `s3du` can operate in.
#[derive(Debug, Eq, PartialEq)]
pub enum ClientMode {
/// CloudWatch mode is available when compiled with the `cloudwatch`
/// feature.
#[cfg(feature = "cloudw... |
// io is a stl that can be used to handle user inputs
// Rust automatically imports several packages by default which is called prelude, this helps in
// keeping the code less verbose https://doc.rust-lang.org/std/prelude/index.html
use std::io;
use rand::Rng;
use std::cmp::Ordering;
fn main() {
println!("Guessin... |
use crate::cartridge::Mirror;
impl super::Ppu {
pub fn read(&mut self, address: usize) -> u8 {
match address {
0x0000..=0x1FFF => self.mapper.borrow().read(address),
0x2000..=0x3EFF => self.read_nametable(address),
0x3F00..=0x3FFF => {
let a = address % ... |
use crossbeam_channel::RecvTimeoutError::*;
use serde::{Deserialize, Serialize};
use std::thread;
use std::time::{Duration, Instant};
mod system;
use system::Lighting;
mod environment;
use environment::Environment;
mod state;
use state::RoomState;
mod commands;
use commands::handle_cmd;
use crate::errors::Error;
us... |
use std::convert::TryInto;
use std::future::Future;
use hyper::upgrade::OnUpgrade;
use sha1::{Digest, Sha1};
use crate::{
Body, Error, FromRequest, HeaderName, HeaderValue, IntoResponse, Method, Request, Response,
ResponseBuilder, Result, StatusCode,
};
use tokio_tungstenite::tungstenite::protocol::Role;
pub... |
use crate::errors::Errcode;
use std::os::unix::io::RawFd;
use nix::sys::socket::{socketpair, AddressFamily, SockType, SockFlag, send, MsgFlags, recv};
pub fn generate_socketpair() -> Result<(RawFd, RawFd), Errcode> {
match socketpair(
AddressFamily::Unix,
SockType::SeqPacket,
None,
... |
#[cfg(feature = "extern")]
pub mod ex;
#[cfg(feature = "python")]
pub mod py;
mod test;
/// The freely-jointed chain (FJC) model thermodynamics in the isometric ensemble approximated using a Legendre transformation.
pub mod legendre;
use super::
{
treloar_sums,
treloar_sum_0_with_prefactor
};... |
#![allow(non_snake_case)]
#[allow(unused_imports)]
use std::io::{self, Write};
#[allow(unused_imports)]
use std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque};
#[allow(unused_imports)]
use std::cmp::{max, min, Ordering};
macro_rules! input {
(source = $s:expr, $($r:tt)*) => {
let... |
fn try_parse(s: String) -> i32 {
unimplemented!();
}
fn main() {
let input = include_str!("../../input");
let sum: i32 = input.lines().map(|x| x.parse::<i32>().unwrap()).sum();
println!("{}", sum);
}
|
#[no_mangle]
pub extern fn physics_single_chain_efjc_thermodynamics_isotensional_asymptotic_alternative_end_to_end_length(number_of_links: u8, link_length: f64, link_stiffness: f64, force: f64, temperature: f64) -> f64
{
super::end_to_end_length(&number_of_links, &link_length, &link_stiffness, &force, &temperature)... |
use std::collections::HashMap;
use std::error::Error;
use std::path::Path;
use log::debug;
use uuid::Uuid;
use crate::csv::inference::ColumnInference;
use crate::db::utils::to_table_parameters;
use crate::db::{Db, Header, Rows};
use crate::parser::collector::Collector;
use crate::parser::rewriter::Rewriter;
use crate... |
use std::fs;
use serde_json::json;
use websrv::{WebSrv, StatusCode, Method, Route, Request};
static ROUTES: &'static [Route] = &[
Route {path: "/hello", method: Method::GET, func: hello_world},
Route {path: "/hello_rust", method: Method::GET, func: hello_rust},
Route {path: "/forbidden", method: Method::GE... |
use std::vec::Vec;
pub struct SHA3 {
input_bytes: Vec<u8>,
current_state: [[u64; 5]; 5],
block_size: u64,
digest_size: u64,
n_r: u64,
c: u64
}
impl SHA3 {
const OFFSET: [[u8; 5]; 5] = [
[0, 36, 3, 41, 18],
[1, 44, 10, 45, 2],
[62, 6, 43,... |
/// The writer is responsible for turning structures into bytes in a file.
use std::{
io::{self, SeekFrom},
marker::PhantomData,
};
use bitwriter::BitWriter;
use crate::{
frame::Frame,
headers::{MetadataBlock, MetadataBlockStreamInfo},
};
pub struct HeaderWriter<W, S> {
w: W,
stream_info: Met... |
// don't allow orphan method
fn main() {
// Add code here
} |
use yew::prelude::*;
use yew_router::prelude::*;
use crate::route::MyRoute;
pub struct Header {
// props: Props,
_link: ComponentLink<Self>,
}
impl Component for Header {
type Message = ();
type Properties = ();
fn create(_props: Self::Properties, _link: ComponentLink<Self>) -> Self {
Self { _link }
}
fn u... |
use azuki_tac::InstId;
pub enum Value {
Int(i64),
StackPointer {
frame: u32,
value: InstId,
offset: u32,
},
HeapPointer {},
}
|
use std::any::Any;
use std::cell::RefCell;
use euclid::{Point2D, Size2D, Transform2D, Vector2D};
use glium::glutin::event::{ElementState, Event, MouseButton, MouseScrollDelta, WindowEvent};
use glium::{Display, DrawError, Frame};
use log::debug;
use crate::event_handling::{EventHandler, FnEventHandler};
use crate::ge... |
use super::free_variables::find_free_variables;
use crate::{ir::*, types::Type};
use std::collections::HashMap;
pub fn infer_environment(module: &Module) -> Module {
Module::new(
module.type_definitions().to_vec(),
module.foreign_declarations().to_vec(),
module.foreign_definitions().to_vec(... |
#![allow(incomplete_features)]
#![cfg_attr(not(test), no_std)]
use pc_keyboard::{DecodedKey, KeyCode};
use pluggable_interrupt_os::vga_buffer::{BUFFER_WIDTH, BUFFER_HEIGHT};
use core::borrow::BorrowMut;
use pluggable_interrupt_os::println;
const WIDTH: usize = BUFFER_WIDTH;
const HEIGHT: usize = BUFFER_HEIGHT - 2;
c... |
use clap::{App, Arg};
mod csv;
mod text;
fn main() -> Result<(), ()> {
let matches = App::new("HyperLogLog CLI")
.version("0.1")
.author("Adam Shirey <adam@shirey.ch>")
.about("Efficiently approximates distinct count of input values.")
.arg(
Arg::with_name("error-rate")... |
/// Errors for translators. These are separate so new translators can easily be created in a modular fashion.
pub mod errors;
// We export each translator by name
#[cfg(feature = "translator-fluent")]
mod fluent;
#[cfg(feature = "translator-fluent")]
pub use fluent::{FluentTranslator, FLUENT_TRANSLATOR_FILE_EXT};
// ... |
pub mod transaction;
pub mod verifier;
pub use tockb_types as types;
pub use tockb_types::config;
|
use exonum::crypto::{Hash, PublicKey};
use super::proto;
/// Wallet information stored in the database.
#[derive(Clone, Debug, ProtobufConvert)]
#[exonum(pb = "proto::Queue", serde_pb_convert)]
pub struct Queue {
/// `PublicKey` of the queue.
pub key: PublicKey,
/// Name of the queue.
pub name: String,... |
use std::{fs::File, path::PathBuf, time::Instant};
use assembly_fdb::{mem::Database, sqlite::try_export_db};
use color_eyre::eyre::WrapErr;
use mapr::Mmap;
use rusqlite::Connection;
use structopt::StructOpt;
#[derive(StructOpt)]
/// Turns an FDB file into an equivalent SQLite file
struct Options {
/// The FD sour... |
use std::borrow::Borrow;
use std::io::BufRead;
/// The indices of each column in the VCF data lines
enum VCFColumn {
CHROMOSOME = 0,
POS = 1,
ID = 2,
REF = 3,
ALT = 4,
QUAL = 5,
FILTER = 6,
INFO = 7,
FORMAT = 8,
}
static FIRST_DATA_COLUMN: usize = VCFColumn::FORMAT as usize + 1;
/... |
mod bytes_ext;
mod codec;
mod mctypes;
mod packet;
pub mod packets;
pub use codec::{Error, MinecraftCodec};
pub use packet::{Packet, PacketBuilder, PacketDirection, PacketId, PacketStage, PacketType};
pub fn cast_packet<P: packet::Packet + 'static + Send>(packet: Box<dyn Packet>) -> P {
*packet.into_any().downcas... |
use super::{
options::{ApplyContract, DoNotApplyContracts, DoNotUseCallback, UseCallback},
primitives::{embed_primitives, embed_primitives_without_io, CONSTANTS},
vm::VirtualMachineCore,
};
use crate::{
compiler::{compiler::Compiler, constants::ConstantMap, program::Program},
core::instructions::Den... |
use crate::config;
use crate::mcc::agent::speciated_agent_queue::SpeciatedAgentQueue;
use crate::mcc::maze::speciated_maze_queue::SpeciatedMazeQueue;
pub struct VariedSizeController {
//pub(crate) agent_entries: Vec<VariedSizeEntry>,
//pub(crate) maze_entries: Vec<VariedSizeEntry>,
}
impl VariedSizeController {
... |
extern crate image;
extern crate imageproc;
extern crate rusttype;
extern crate conv;
use decoder::*;
use decoder_class::*;
use decoder_usecase::*;
use image::{GenericImage, ImageBuffer, Pixel};
use imageproc::definitions::{Clamp, Image};
use conv::ValueInto;
use std::f32;
use std::i32;
use std;
use imageproc::pixelops... |
use super::{Fid, FidIter};
impl<'iter> Fid {
/// Creates an iterator over FID's bit vector.
///
/// # Examples
/// ```
/// use fid_rs::Fid;
///
/// let fid = Fid::from("1010_1010");
/// for (i, bit) in fid.iter().enumerate() {
/// assert_eq!(bit, fid[i as u64]);
/// }
//... |
use clang::*;
use std::io::Write;
use super::gen_context::GenContext;
use super::symbol_status::SymbolStatus;
use super::compile_entity_children;
use super::CType;
pub fn gen(gen_context: &mut GenContext, entity: Entity) {
if let Some(mut entity_name) = entity.get_name() {
// Check if available
m... |
use crate::{directory::Directory, persistence::vec_to_bytes};
use super::{super::*, *};
use std::{self, io, u32};
/// This data structure assumes that a set is only called once for a id, and ids are set in order.
#[derive(Debug, Clone)]
pub(crate) struct IndexIdToOneParentFlushing {
pub(crate) cache: Vec<u32>,
... |
use std::collections::HashMap;
fn process_group_union(group : &str) -> usize {
let mut total : Vec<char> =
group.chars()
.filter(|c| c.is_ascii_alphabetic())
.collect();
total.sort();
total.dedup();
total.len()
}
fn process_group_intersection(group : &str) -> usize {
... |
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::Arc;
use std::{thread, time};
use sharedlock_rs::SharedLock;
#[test]
fn test_dead_lock() {
let lock = SharedLock::new(0);
let guard1 = lock.write();
assert!(guard1.is_ok());
let guard2 = lock.write();
assert!(guard2.is_err()... |
use super::appsdb::AppDataBase;
pub fn backup() {
let mut database = AppDataBase::new();
let apps = database.get_apps();
for app in apps {
app.backup();
}
} |
pub fn simple_borrow_test() {
println!("{}", "-------------------------------");
let s1 = String::from("hello");
let s2 = s1;
// If we use s1,it will report a error;
// println!("{} has moved to s2",s1);
// error type: value used here after move
println!("{} has moved to s2", s2);
... |
use super::WidgetDimensions;
#[derive(Clone, Copy)]
pub struct LayoutHacks {
pub expand_horizontally: bool,
pub expand_vertically: bool,
// NYEO NOTE: It's completely OK for these to be settable to arbitrary values because the min/max constraints will be handled in tailor()
pub preferred_width: Option... |
// This file is part of Substrate.
// Copyright (C) 2018-2020 Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// 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
//
// ht... |
use crate::arena::{block, resource, BlockMut, BlockRef};
use crate::libs::random_id::U128Id;
use std::rc::Rc;
#[derive(Clone)]
pub enum TableTool {
Selecter(Rc<Selecter>),
Craftboard(Rc<Craftboard>),
Pen(Rc<Pen>),
Eraser(Rc<Eraser>),
Character(Rc<Character>),
Boxblock(Rc<Boxblock>),
TerranB... |
//! Acquisition functions
use nalgebra::DVector;
use statrs::distribution::{Continuous, Normal, Univariate};
/// Expected improvement utility function.
#[derive(Debug)]
pub struct ExpectedImprovement {
/// Exploitation-exploration trade-off parameter
pub xi: f64,
}
impl Default for ExpectedImprovement {
... |
#![no_std]
pub use embedded_hal as ehal;
pub use esp8266 as target;
pub use esp8266_hal_proc_macros::{interrupt, ram};
#[cfg(feature = "rt")]
pub use xtensa_lx_rt::{entry, exception};
#[cfg(all(feature = "rt", feature = "interrupt"))]
#[macro_use]
pub mod interrupt;
pub mod efuse;
pub mod flash;
pub mod gpio;
pub m... |
#![cfg_attr(feature = "clippy", feature(plugin))]
#![cfg_attr(feature = "clippy", plugin(clippy))]
/*
Copyright 2017 Takashi Ogura
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
... |
use crate::directory::Directory;
use crate::error::Error;
use crate::inherit::InheritEdition;
use crate::manifest::Edition;
use serde::de::value::MapAccessDeserializer;
use serde::de::value::StrDeserializer;
use serde::de::{self, Deserialize, Deserializer, Visitor};
use serde::ser::{Serialize, Serializer};
use serde_de... |
use crate::util::lines_from_file;
pub fn day20() {
println!("== Day 20 ==");
let input = lines_from_file("src/day20/input.txt");
let a = part_a(&input);
println!("Part A: {}", a);
let b = part_b(&input);
println!("Part B: {}", b);
}
fn part_a(input: &Vec<String>) -> usize {
solve(input, 2)... |
use std::collections::HashMap;
use itertools::Itertools;
fn find_house(n: u64) -> u64 {
let mut houses: HashMap<u64, u64> = HashMap::new();
for i in 1..=(n / 10) {
for j in (i..=(n / 10)).step_by(i as usize) {
*houses.entry(j).or_insert(0) += i * 10;
}
}
houses.into_iter(... |
/// Variable argument version of `syscall`
#[macro_export]
macro_rules! syscall {
($nr:ident) => {
$crate::syscall1($crate::nr::$nr, 0)
};
($nr:ident, $a1:expr) => {
$crate::syscall($crate::nr::$nr, &[$a1 as usize])
};
($nr:ident, $a1:expr, $a2:expr) => {
$crate::syscall($cra... |
use crate::{
table::table_name::TableName,
test_support::test_models::{Body, ModelsMock, People, Pet},
test_support::MockWithTxMethods,
RowProjectionQuery, Rows,
};
use futures::FutureExt;
#[derive(Clone, PartialEq, Debug)]
struct MockDatum {
tables: Vec<MockRows>,
}
impl From<ModelsMock> for Mock... |
//! signal implementation for Redox, following http://pubs.opengroup.org/onlinepubs/7908799/xsh/signal.h.html
#![no_std]
#![feature(asm, const_fn, core_intrinsics, global_asm)]
extern crate errno;
extern crate platform;
#[cfg(target_os = "linux")]
#[path = "linux.rs"]
pub mod sys;
#[cfg(target_os = "redox")]
#[path... |
use crate::{properties, util};
use serde::Deserialize;
#[derive(Debug, Deserialize)]
pub struct Ellipse {
#[serde(rename = "mn")]
pub match_name: String,
#[serde(rename = "nm")]
pub name: String,
#[serde(rename = "d", default = "util::one_please")]
pub direction: f64,
#[serde(rename = "p")]... |
tonic::include_proto!("ns/ns");
|
use boxer::array::BoxerArrayF32;
use boxer::{ValueBox, ValueBoxPointer};
use gleam::gl::*;
use std::rc::Rc;
#[no_mangle]
fn gleam_uniform_2f(_ptr_gl: *mut ValueBox<Rc<dyn Gl>>, location: GLint, v0: GLfloat, v1: GLfloat) {
_ptr_gl.with_not_null(|gl| gl.uniform_2f(location, v0, v1));
}
#[no_mangle]
fn gleam_uniform... |
use anyhow::Result;
use crate::error::*;
use std::collections::BTreeMap;
#[derive(Clone)]
pub struct Client {
api_token: String,
host: String,
}
impl Client {
pub fn new(api_token: Option<String>, host: String) -> Self {
Client {
api_token: api_token.unwrap_or_else(|| "".into()),
... |
#[macro_use]
extern crate postgres_derive;
#[macro_use]
extern crate postgres;
use postgres::{Connection, TlsMode};
use postgres::types::WrongType;
mod util;
#[test]
fn defaults() {
#[derive(Debug, ToSql, FromSql, PartialEq)]
enum Foo {
Bar,
Baz,
}
let conn = Connection::connect("pos... |
#[doc = "Reader of register RANGE_COND"]
pub type R = crate::R<u32, super::RANGE_COND>;
#[doc = "Writer for register RANGE_COND"]
pub type W = crate::W<u32, super::RANGE_COND>;
#[doc = "Register RANGE_COND `reset()`'s with value 0"]
impl crate::ResetValue for super::RANGE_COND {
type Type = u32;
#[inline(always... |
mod bitvec_const;
mod neg;
mod add;
mod sub;
mod mul;
mod smod;
mod sdiv;
mod udiv;
mod urem;
mod srem;
pub mod prelude {
pub use super::{
BitvecConst,
Neg,
Add,
Mul,
Sub,
UnsignedDiv,
SignedDiv,
SignedModulo,
UnsignedRemainder,
Signed... |
extern crate ssh;
use std::fs::File;
use ssh::public_key;
pub fn main() {
let keypair = (public_key::ED25519.generate_key_pair)(None);
let mut buffer = File::create("server.key").unwrap();
keypair.export(&mut buffer);
}
|
use std::fs::File;
use std::io::{self, Cursor, Read, Write};
use std::path::Path;
use anyhow::Result;
use libosu::{
data::{Mode, Mods},
replay::{Buttons, Replay, ReplayActionData},
timing::Millis,
};
#[cfg(feature = "replay-data")]
fn compare_action_data(replay: &Replay, replay2: &Replay) -> Result<()> {
... |
pub use super::number::types::Type;
pub use super::number::classes::Class;
pub use super::number::rcodes::RCode;
pub use super::number::opcodes::OpCode;
pub use super::number::errors::IdentifierError;
pub use super::name::{Name,DNSNameReader};
pub use super::number::DNSNumberReader;
use self::record::{Question,Resourc... |
use vek::*;
#[derive(Copy, Clone, Debug, PartialEq,Serialize, Deserialize)]
pub enum SpellBounds {
Sphere(Vec3<f32>, f32),
Ray(Vec3<f32>, Vec3<f32>),
}
#[derive(Copy, Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum SpellShape {
Sphere(f32),
Ray(f32),
} |
fn main() {
let data1 = (10, 'x', 12, 183.19, 'q', false, -9);
let mut data2: (u16, char, i16, f64, bool, char, i16);
data2 = data1;
}
|
use serde::{Deserialize, Serialize};
use smart_default::SmartDefault;
#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum ConvolutionTileSize {
Lowest,
Low,
Medium,
High,
}
#[derive(Clone, Debug, Deserialize, PartialEq, SmartDefault, Serialize)... |
use bonuses;
/// An object which tracks circumstance bonus values.
pub struct CircumstanceBonus {
tracker: bonuses::StackingTracker,
}
impl CircumstanceBonus {
/// Create an instance of CircumstanceBonus.
pub fn new() -> CircumstanceBonus {
CircumstanceBonus {
tracker: bonuses::StackingTracker::new()
}
}
}... |
mod bindings;
mod broadcaster;
mod watcher;
pub use broadcaster::Broadcaster;
pub use watcher::MoebiusWatcher;
|
//! An HTTP log monitoring tool.
//!
//! Provides a summary information and alerts of HTTP traffic.
#[macro_use]
extern crate assert_matches;
use clap::{AppSettings, Clap};
use csv::Reader;
use processor::Record;
use std::collections::VecDeque;
use std::error::Error;
use std::io;
use std::process;
pub mod alerts;
pub... |
extern crate rand;
use std::fmt;
use std::{thread, time};
use std::process;
use rand::{thread_rng, Rng};
trait State : fmt::Display {
fn do_clock(&self, hour: u32) -> Box<State>;
fn do_use(&self, context: Box<&Context>);
fn do_alarm(&self, context: Box<&Context>);
fn do_phone(&self, context: Box<&Cont... |
use log::trace;
use std::sync::Arc;
use super::style::Style;
pub type GridCell = Option<(String, Option<Arc<Style>>)>;
pub struct CharacterGrid {
pub width: u64,
pub height: u64,
pub should_clear: bool,
dirty: Vec<bool>,
characters: Vec<GridCell>,
}
impl CharacterGrid {
pub fn new(size: (u6... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.