text stringlengths 8 4.13M |
|---|
use std::time::Instant;
use regex::Regex;
const INPUT: &str = include_str!("../input.txt");
fn read_input() -> impl Iterator<Item = (String, usize, usize, usize, usize)> {
let re = Regex::new(r"(?P<command>turn off|turn on|toggle) (?P<x1>\d+),(?P<y1>\d+) through (?P<x2>\d+),(?P<y2>\d+)").unwrap();
INPUT.lin... |
use std::sync::Arc;
use super::{Pages, Pagination};
use crate::{core::Context, embeds::PinnedEmbed, util::osu::ScoreOrder, BotResult};
use rosu_v2::prelude::{Score, User};
use twilight_model::channel::Message;
pub struct PinnedPagination {
ctx: Arc<Context>,
msg: Message,
pages: Pages,
user: User,
... |
// ARMv7M-M Memory Model
use std::ops::{ Index, IndexMut };
/// Addressable registers
pub enum Register {
// Thumb16 addressable
R0, R1, R2, R3,
R4, R5, R6, R7,
// Thumb32 addressable
R8, R9, R10, R11, R12,
// Stack Pointer
SPM,
SPP,
// Link Register
LR,
// Program... |
extern crate rand;
use std::io;
use std::num;
use rand::Rng;
fn main() {
const MAX : usize = 256;
let mut freq = [0; MAX];
let mut rng = rand::thread_rng();
for _ in 0..MAX*16384 {
let n = rng.gen_range(0, MAX);
freq[n] += 1;
}
let mut tdiff = 0;
for i in 0..MAX {
... |
use crate::{
codegen::{
builder::value,
unit::{Mutability, Slot},
AatbeModule, CompileError, ValueTypePair,
},
fmt::AatbeFmt,
ty::LLVMTyInCtx,
};
use parser::ast::{AtomKind, Expression, PrimitiveType, AST};
pub fn const_atom(module: &AatbeModule, atom: &AtomKind) -> Option<Value... |
use std::cmp::{max, min};
use std::fs;
use std::ops::RangeInclusive;
type Cuboid = [RangeInclusive<isize>; 3];
type RebootInstruction = (bool, Cuboid);
fn main() {
let filename = "input/input.txt";
let instructions = parse_input_file(filename);
println!("instructions: {:?}", instructions);
println!()... |
/// Represents a matrix in row-major order
// [[1,2,3],[1,2,3]]
//
pub type Matrix = Vec<Vec<f32>>;
/// Computes the product of the inputs `mat1` and `mat2`.
pub fn mat_mult(mat1: &Matrix, mat2: &Matrix) -> Matrix {
let (r1, c1) = size(mat1);
let (r2, c2) = size(mat2);
if r1 != c2 { panic!("Can't dot mult... |
/*
chapter 4
syntax and semantics
loop
*/
// this code will give this warning:
/*
warning: denote infinite loops with loop { ... },
#[warn(while_true)] on by default
*/
fn main() {
while true {
println!("i am stuck in the infinite loop \
again, so, please, help me a second time");
}
}
// out... |
//! Http context command handlers
//!
//! Contains actors that handles commands for HTTP endpoint
use actix_rt::time::timeout;
use actix_web::{http, web, HttpResponse};
use drogue_cloud_endpoint_common::{command::Commands, error::HttpEndpointError};
use drogue_cloud_service_common::Id;
use std::time::Duration;
const ... |
//! Module for all [`Handoff`]-related items.
pub mod handoff_list;
mod tee;
mod vector;
use std::any::Any;
use std::cell::RefMut;
pub use tee::TeeingHandoff;
pub use vector::VecHandoff;
/// Trait representing something which we can attempt to give an item to.
pub trait TryCanReceive<T> {
// TODO(mingwei): Isn'... |
use multihash::{wrap, Code, Multihash, MultihashDigest, Sha3_512};
#[test]
fn to_u64() {
assert_eq!(<u64>::from(Code::Keccak256), 0x1b);
assert_eq!(<u64>::from(Code::Custom(0x1234)), 0x1234);
}
#[test]
fn from_u64() {
assert_eq!(Code::from(0xb220), Code::Blake2b256);
assert_eq!(Code::from(0x0011_2233)... |
//! Project changelog (YEAR-MONTH-DAY)
/// Release 0.0.4 (2017-11-08)
///
/// * Partially sketched out a transfer matrix addressing issue#23
/// * Simplified the complicated extension/build system resolving issue#25
/// * The new extension/build system allows for framework specific backends.
/// * Worked on a Open... |
fn add(i:i32, j:i32) -> i32 {
i + j
}
fn main() {
let i = 3;
let j = 4;
println!("sum of {} and {} is: {}", i, j, add(i,j));
}
|
use petgraph::graph::Graph;
use petgraph::graph::NodeIndex;
use petgraph::graphmap::DiGraphMap;
use petgraph::graphmap::GraphMap;
use petgraph::visit::DfsPostOrder;
use petgraph::visit::IntoNodeReferences;
use petgraph::visit::NodeRef;
use petgraph::Incoming;
use petgraph::Outgoing;
use petgraph::Undirected;
fn main()... |
//! `Secret<T>` wrapper type for more carefully handling secret values
//! (e.g. passwords, cryptographic keys, access tokens or other credentials)
//!
//!
//! ### Usage
//! ```
//! use redactedsecret::{Secret, SecretString, SecretVec, SecretBox};
//! ```
//!
//!
//! ### Examples
//!
//! 1. Create a `Secret` on any typ... |
use unicode_segmentation::UnicodeSegmentation;
use widget::Widget;
use Size;
#[derive(Debug, PartialEq, Clone)]
pub struct Text {
pub lines: Vec<String>,
pub style: Option<String>,
}
impl Widget for Text {
fn render_content(&self, size: Size) -> Option<Vec<String>> {
let lines: Vec<String> = self.... |
#![warn(clippy::all)]
pub extern crate las as las_rs;
pub mod ascii;
pub mod base;
pub mod las;
pub mod tiles3d;
|
use amethyst::{
assets::{AssetStorage, Loader, ProgressCounter},
ecs::prelude::World,
renderer::{
PngFormat, SpriteSheet, SpriteSheetHandle, Texture,
TextureMetadata, SpriteSheetFormat, TextureHandle,
},
};
/// TODO: implement BmpFormat, JpgFormat, ...
pub fn load_image_png(
world: ... |
mod ring1 {
pub mod ring2 {
pub mod ring3 {
pub fn test() {
println!("{:?}", "test");
}
pub fn halo() {
println!("{:?}", "halo");
}
}
}
}
// use {self}
use ring1::ring2::{
self, // 这个代表 ring2 自己
ring3::{
... |
// _ _
// | |_| |__ ___ ___ __ _
// | __| '_ \ / _ \/ __/ _` |
// | |_| | | | __/ (_| (_| |
// \__|_| |_|\___|\___\__,_|
//
// licensed under the MIT license <http://opensource.org/licenses/MIT>
//
// crypt.rs
// defintions of the AES encryption, decryption, and PBKDF2 key derivation
// functions required t... |
extern crate dirs;
extern crate rusqlite;
use rusqlite::NO_PARAMS;
use rusqlite::{Connection, Error, Result};
#[path = "../constants/mod.rs"]
mod constants;
use constants::{DATABASE_FILE};
pub mod account;
static CREATE_PASSWORDS_TABLE_Q: &str = "create table if not exists passwords ( id integer primary key, accoun... |
#[derive(Debug, Clone, Eq, PartialEq)]
pub enum ExactTermType {
/// exact-match.
///
/// `'wild`: Items that include wild.
Exact,
/// prefix-exact-match
///
/// `^music`: Items that start with music.
PrefixExact,
/// suffix-exact-match
///
/// `.mp3$`: Items that end with .mp... |
use std::env;
use std::path::PathBuf;
fn main() {
let out_dir = PathBuf::from(env::var("OUT_DIR").unwrap_or("".to_string()));
tonic_build::configure()
.file_descriptor_set_path(out_dir.join("chat_descriptor.bin"))
.compile(&["../proto/chat.proto"], &["../proto"])
.unwrap();
}
|
use std::env;
use clap::{App, SubCommand, Arg};
use kvs::{Result, KvError, KvStore};
use std::process::exit;
fn main() -> Result<()> {
let kvs_app = App::new("kvs")
.version(env!("CARGO_PKG_VERSION"))
.subcommand(
SubCommand::with_name("get")
.arg(Arg::with_name("<KEY>"... |
// 2019-04-05
// Les Closures permettent de... j'ai pas encore compris
// Nous sommes dans une salle de sport et l'utilisateur demande à l'algorithme de
// lui créer un programme d'entraînement. L'algorithme a deux arguments :
// l'intensité des efforts à fournir
// un nombre aléatoire pour amener de la varié... |
#[macro_use]
extern crate log;
mod lexer;
mod parser;
use lexer::Token;
fn main() {
let string = "(add 2 (subtract 4 2))";
let tokens: Vec<Token> = lexer::tokenizer(string);
println!("Tokens: {:?}", tokens);
}
|
/*
Copyright (c) 2023 Uber Technologies, Inc.
<p>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
<p>http://www.apache.org/licenses/LICENSE-2.0
<p>Unless required by applicable law or agreed to ... |
#![no_std]
#![feature(start)]
#![no_main]
use ferr_os_librust::io;
extern crate alloc;
use alloc::vec::Vec;
use alloc::{format, string::String};
#[no_mangle]
pub extern "C" fn _start(heap_address: u64, heap_size: u64, args: u64, args_number: u64) {
ferr_os_librust::allocator::init(heap_address, heap_size);
... |
extern crate cuticula;
extern crate modifier;
#[cfg(test)]
mod image_spec {
use cuticula::{ Set, Transformer, Image };
use cuticula::image::{ Resize, Crop };
use std::path::Path;
fn expected_result() -> Vec<u32> {
vec![255, 255, 255, 255, 255, 255, 255, 255, 255, 0, 0, 0]
}
// Additi... |
fn main() {
let mut fd = libc::pollfd{fd: 0, events: 0, revents: 0};
loop {
let _ = unsafe{libc::poll(&mut fd, 1, -1)};
}
}
|
#![warn(missing_docs)]
use super::ops::tee::TEE;
use super::ops::union::UNION;
use super::{GraphNodeId, HydroflowGraph};
fn find_unary_ops<'a>(
graph: &'a HydroflowGraph,
op_name: &'static str,
) -> impl 'a + Iterator<Item = GraphNodeId> {
graph
.node_ids()
.filter(move |&node_id| {
... |
use crate::ram::Ram;
use std::fmt;
pub const PROGRAM_START: u16 = 0x200;
pub struct Cpu {
vx: [u8; 16],
pc: u16,
i: u16,
prev_pc: u16,
stack: Vec<u16>,
}
impl Cpu {
pub fn new() -> Cpu {
Cpu {
vx: [0; 16],
pc: PROGRAM_START,
i: 0,
prev_pc: 0,
stack: Vec::<u16>::new(),
}
}
pub fn run_instr... |
extern crate xml;
use crate::component2::{Component};
use std::io::BufWriter;
use xml::{EventReader, EventWriter, EmitterConfig, reader::XmlEvent, writer::events::XmlEvent as XmlEventW};
use std::error::Error;
fn props_from_xml(parser: &mut XMLParser) -> Result<(String, String), Box<Error>> {
let start_tag = pars... |
use crate::ast::expressions::{self, primitives, statements, tables, variables};
use crate::ast::stack;
use crate::interpreter::cache;
use std::collections::VecDeque;
use std::rc::Rc;
use std::cell::RefCell;
#[derive(Debug)]
pub struct Closure {
pub params: VecDeque<Box<dyn expressions::Expression>>,
pub varar... |
use std::env;
use std::fs;
use std::path::Path;
use std::collections::HashMap;
#[derive(Copy,Clone,Debug)]
struct AuntSue<'a>{
id:i32,
prop:& 'a str,
count:i32
}
fn read_sue_list(filename:&str)->String{
let fpath = Path::new(filename);
let abspath = env::current_dir()
.unwrap()
.in... |
#![allow(dead_code, unused_imports, unused_variables)]
use std::collections::{HashMap,HashSet};
const DATA: &'static str = include_str!("../../../data/06");
fn main() {
let points: Vec<(isize, isize)> = DATA
.lines()
.map(|line| line.split(", ").map(|n| n.parse::<isize>().unwrap()))
.map(... |
use super::{Backend, Component, Frame, State};
use tui::{
layout::Rect,
style::{Color, Style},
widgets::{Block, Borders, List, ListItem},
};
pub struct FormulaeList;
impl Component for FormulaeList {
fn render_to(frame: &mut Frame<Backend>, layout: Rect, state: &mut State) {
let packages_list ... |
pub mod ppu;
pub mod screen;
|
use crate::{WIDTH, HEIGHT, VF, Chip8};
use crate::screen::{Point, Buffer, Screen};
use rand::{Rng, rngs::ThreadRng};
/// (0nnn - SYS addr)
/// Jump to a machine code routine at nnn.
///
/// This instruction is only used on the old computers on which Chip-8 was originally implemented.
/// It is ignored by modern inter... |
#[doc = "Reader of register DDRCTRL_ADDRMAP9"]
pub type R = crate::R<u32, super::DDRCTRL_ADDRMAP9>;
#[doc = "Writer for register DDRCTRL_ADDRMAP9"]
pub type W = crate::W<u32, super::DDRCTRL_ADDRMAP9>;
#[doc = "Register DDRCTRL_ADDRMAP9 `reset()`'s with value 0"]
impl crate::ResetValue for super::DDRCTRL_ADDRMAP9 {
... |
#![recursion_limit = "1024"]
#[macro_use]
extern crate error_chain;
extern crate alto;
extern crate clap;
extern crate colored;
extern crate env_logger;
extern crate gstreamer as gst;
#[macro_use]
extern crate log;
extern crate pitch_calc;
extern crate termion;
extern crate ultrastar_txt;
// extern crate hyper;
// ext... |
use super::*;
use mathic::*;
pub struct SubGenerator {
scratch_gpr: Reg,
left_fpr: FPReg,
right_fpr: FPReg,
result: Reg,
left: Reg,
right: Reg,
}
impl MathICGenerator for SubGenerator {
fn generate_inline(
&mut self,
jit: &mut JIT<'_>,
state: &mut MathICGenerationSta... |
pub fn parse(text: &str) -> Option<Vec<Instruction>> {
let instructions: Vec<Instruction> = text.lines()
.map(|s| match parse_line(s) {
Some(instructions) => instructions,
None => vec![],
})
.fold(vec![], |mut collector, mut inst| {
collector.append(&mut ... |
use crate::{event_builder::EventBuilder, EnumEventData};
use crate::{Entity, Event};
use chrono::Utc;
use uuid::Uuid;
/// Generic event builder for an action specified by its EventData
#[derive(Debug)]
pub struct ActionEventBuilder<EDENUM>
where
EDENUM: EnumEventData,
{
payload: EDENUM,
session_id: Option<... |
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - QUADSPI control register"]
pub quadspi_cr: QUADSPI_CR,
#[doc = "0x04 - QUADSPI device configuration register"]
pub quadspi_dcr: QUADSPI_DCR,
#[doc = "0x08 - QUADSPI status register"]
pub quadspi_sr: QUADSPI_SR,
... |
use std::fmt::Display;
use bonsaidb_core::schema::CollectionName;
use serde::{Deserialize, Serialize};
use self::{integrity_scanner::IntegrityScan, mapper::Map};
#[derive(Debug, Serialize, Deserialize)]
pub struct ViewEntry {
pub view_version: u64,
pub key: Vec<u8>,
pub mappings: Vec<EntryMapping>,
p... |
#![feature(alloc_system)]
extern crate alloc_system;
extern crate fuse;
extern crate libc;
#[cfg(feature = "logging")]
extern crate log;
#[cfg(feature = "logging")]
extern crate simplelog;
extern crate tempdir;
extern crate time;
extern crate zip;
mod event;
mod fs;
use fs::AppImageFileSystem;
use std::env;
use std::... |
use crate::lib::environment::Environment;
use crate::lib::error::DfxResult;
use crate::lib::nns_types::account_identifier::{AccountIdentifier, Subaccount};
use crate::lib::nns_types::icpts::ICPTs;
use crate::lib::nns_types::{
BlockHeight, CyclesResponse, Memo, NotifyCanisterArgs, SendArgs, CYCLE_MINTER_CANISTER_ID,... |
/// Permutator. I don't recommend that you use this interface for obtaining the
/// permutations because in order to make the permute function as fast as
/// possible, safety was thrown away. That being said, HeapPermutor can be
/// faster than the iterator because it isn't required to create a new Vec for
/// each yi... |
// https://www.codewars.com/kata/weight-for-weight
use std::cmp::Ordering;
fn order_weight(s: &str) -> String {
let weight = |x: &str| x.chars().map(|c| c.to_digit(10).unwrap()).sum::<u32>();
let mut nums: Vec<&str> = s
.split_whitespace()
.collect();
nums.sort_unstable_by(|a, b| {
let res = weigh... |
use near_sdk::borsh::{self, BorshDeserialize, BorshSerialize};
use near_sdk::collections::LookupMap;
use near_sdk::json_types::{U128, U64};
use near_sdk::wee_alloc::WeeAlloc;
use near_sdk::{env, near_bindgen};
#[global_allocator]
static ALLOC: WeeAlloc = WeeAlloc::INIT;
pub type Base64String = String;
const VERSION:... |
//! nock implements a nock interpreter.
// Copyright (2017) Jeremy A. Wall.
//
// 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... |
use std::cmp::Ordering;
#[derive(Debug, Serialize, Deserialize)]
pub struct Entry<T, U> {
pub key: T,
pub value: U,
}
impl<T, U> Ord for Entry<T, U>
where
T: Ord,
{
fn cmp(&self, other: &Entry<T, U>) -> Ordering {
self.key.cmp(&other.key)
}
}
impl<T, U> PartialOrd for Entry<T, U>
where
... |
#![doc = "generated by AutoRust 0.1.0"]
#![allow(non_camel_case_types)]
#![allow(unused_imports)]
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct PolicyAssignmentProperties {
#[serde(rename = "displayName", default, skip_serializing_if = "Option::is_none")]... |
use delay_timer::cron_clock::{Schedule, ScheduleIteratorOwned};
use delay_timer::prelude::*;
use std::str::FromStr;
use std::sync::atomic::{
AtomicUsize,
Ordering::{Acquire, Release},
};
use std::sync::{
atomic::{AtomicI32, AtomicU64},
Arc,
};
use std::thread::{self, park_timeout};
use std::time::Durat... |
// https://github.com/rust-lang/rfcs/pull/2522
#![feature(type_ascription)]
use failure::Error;
use itertools::{process_results, FoldWhile, Itertools};
use maplit::hashset;
use std::fs;
fn main() -> Result<(), Error> {
println!("day 1, part 1 = {}", solve_day1_part1()?);
println!("day 1, part 2 = {}", solve_d... |
#[doc = "Register `FDCAN_TTLGT` reader"]
pub type R = crate::R<FDCAN_TTLGT_SPEC>;
#[doc = "Field `LT` reader - LT"]
pub type LT_R = crate::FieldReader<u16>;
#[doc = "Field `GT` reader - GT"]
pub type GT_R = crate::FieldReader<u16>;
impl R {
#[doc = "Bits 0:15 - LT"]
#[inline(always)]
pub fn lt(&self) -> LT_... |
//! Base traits for different implementations of JSONPath execution engines.
//!
//! Defines the [`Engine`] trait that provides different ways of retrieving
//! query results from input bytes, as well as [`Compiler`] which provides
//! a standalone entry point for compiling a [`JsonPathQuery`] into an [`Engine`].
pub m... |
pub mod aead_poly1305;
pub mod chacha20poly1305;
pub mod salsa20;
pub mod chacha20;
pub mod poly1305;
pub mod hmac_sha2_256;
pub mod sha2_256;
pub mod sha2_384;
pub mod sha2_512;
pub mod ed25519;
pub mod curve25519;
pub mod hacl_policies;
pub mod nacl;
|
//
// Copyright 2020 The Project Oak 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 required by applicable law o... |
mod empty;
pub use empty::*;
|
#[macro_use]
extern crate ispc;
extern crate embree_rs;
extern crate cgmath;
extern crate tobj;
extern crate docopt;
#[macro_use]
extern crate serde_derive;
extern crate rayon;
mod tile;
use std::path::Path;
use std::mem;
use std::ptr;
use cgmath::{Vector3, Vector4, InnerSpace};
use embree_rs::{Device, Geometry, Int... |
extern crate log;
extern crate specs;
extern crate simple_logger;
extern crate airmash_server;
use std::env;
use specs::Entity;
use airmash_server::*;
use airmash_server::protocol::GameType;
struct EmptyGameMode;
impl GameMode for EmptyGameMode {
fn assign_team(&mut self, player: Entity) -> Team {
Team... |
extern crate cursive;
extern crate glob;
extern crate regex;
extern crate pretty_env_logger;
#[macro_use] extern crate log;
use cursive::Cursive;
use cursive::traits::Scrollable;
use cursive::views::Dialog;
use cursive::views::SelectView;
use glob::glob;
use regex::Regex;
use std::env;
use std::collections::HashSet;
u... |
#[doc = "Register `MACSTNR` reader"]
pub type R = crate::R<MACSTNR_SPEC>;
#[doc = "Field `TSSS` reader - Timestamp subseconds The value in this field has the subsecond representation of time, with an accuracy of 0.46 ns. When TSCTRLSSR is set in Timestamp control Register (ETH_MACTSCR), each bit represents 1 ns. The ma... |
// This file is part of rdma-core. 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/rdma-core/master/COPYRIGHT. No part of rdma-core, including this file, may be copied, modified, propagated, or distributed ... |
extern crate regex;
use regex::Regex;
use std::env;
use std::process;
fn print_usage_and_exit() {
println!("Usage: tun HOST:PORT");
println!("--------------------");
println!("Forwards localhost:PORT to HOST:PORT via SSH tunnel.");
process::exit(1);
}
fn main() {
if env::args().count() != 2 { pri... |
use exporter::Cake;
// This function will make compilation fail if T does not implement Cake.
fn assert_is_cake<T: Cake>() {}
mod a {
use super::*;
// This struct name starts with a Vowel, so the Cake proc_macro will
// generate a NewSchoolCake struct, followed by its Cake trait
// implementation.
... |
//! Implements the Tockloader protocol.
//!
//! TockOS applications are loaded with `tockloader`.
//! This speaks to the TockOS bootloader using a specific
//! protocol. This crate implements that protocol so
//! that you can write future tockloader compatible bootloaders
//! in Rust!
#![no_std]
// ******************... |
use crate::er::{self, Result};
use crate::project::ProjectConfig;
use crate::utils::{self, CliEnv};
use failure::format_err;
use std::path::{Path, PathBuf};
use crate::server::{SyncSet, SyncBase, SyncSentCache, SshConn};
use crate::jitsi_env_file;
use std::fs;
/// Creates config folders in project, .env file used wit... |
use speedy::{Endianness, Readable, Writable};
/// Identifies the endianness used to encapsulate the Submessage, the
/// presence of optional elements with in the Submessage, and possibly
/// modifies the interpretation of the Submessage. There are
/// 8 possible flags. The first flag (index 0) identifies the
/// endia... |
use signal_msg::{self, SignalReceiver, SignalSender};
fn main() {
let (signal_sender, signal_receiver) = signal_msg::new();
signal_sender.prepare_signals();
println!("Waiting for a signal...");
let sig = signal_receiver.listen();
println!("Got signal: {:?}", sig.unwrap());
}
|
use std::sync::Arc;
use futures::future;
use futures::sink::SinkExt;
use tokio::net::UnixStream;
use tokio_util::codec::{Framed, LinesCodec};
use persist_core::error::Error;
use persist_core::protocol::{Response, RestoreRequest, RestoreResponse};
use crate::server::State;
pub async fn handle(
state: Arc<State>,... |
use actix_identity::IdentityPolicy;
use actix_session::UserSession;
use actix_web::Error;
use futures::future::{ready, Ready};
use std::rc::Rc;
struct SessionIdentityInner {
key: String,
}
pub struct SessionIdentiyPolicy(Rc<SessionIdentityInner>);
impl SessionIdentiyPolicy {
pub fn new() -> SessionIdentiyPol... |
use super::*;
use std::io::Read;
use super::bytecode::{Op, OpIterator};
pub struct CodeSection<'a> {
pub count: u32,
pub entries_raw: &'a [u8],
}
pub struct CodeIterator<'a> {
count: u32,
iter: &'a [u8]
}
pub struct FunctionBody<'a> {
pub local_count: usize,
pub body: &'a [u8],
}
pub struct ... |
extern crate byteorder;
use self::byteorder::{ReadBytesExt, WriteBytesExt, BigEndian, ByteOrder};
const MAGIC: &'static [u8] = b"tsrust.wal.0000\n";
const MAGIC_LEN: usize = 16;
use ::std::io::{BufWriter,BufReader};
use ::std::path::{Path,PathBuf};
use std::io::Write;
use std::io::Read;
use wal::MemoryWal;
/// Wri... |
use crate::controls::{Adapted, Control, HasLabel};
use crate::sdk;
use crate::types::{adapter, AsAny, Adapter, Spawnable};
use std::any::Any;
use std::marker::PhantomData;
pub struct StringVecAdapter<C: HasLabel + Spawnable> {
items: Vec<String>,
on_item_change: Option<sdk::AdapterInnerCallback>,
... |
use std::path::PosixPath;
use monster::{Skeleton, Mummy, Monster, SkeletonTy, MummyTy};
#[deriving(ToStr,Eq)]
pub enum Cell {
Floor = 0,
Wall,
Door,
Mummy,
Skeleton
}
pub struct Level {
priv monsters: ~[~Monster],
priv cell_data: ~[~[Cell]]
}
impl Level {
pub fn new (monsters: ~[~Mo... |
fn main()
{
println!("Hello World!");
}//End of main method |
//! # The segmented (`*.sd0`) compression format
//!
//! This format is used to deflate (zlib) the data served from the server to the client,
//! and to use less space in the pack archives.
//!
//! ## Serialization
//!
//! ```text
//! [L:5] 's' 'd' '0' 0x01 0xff
//! repeated:
//! [u32] length V (of the following ch... |
use anyhow::{anyhow, ensure, Error, Result};
use indexmap::{map::Entry, IndexMap};
use rand::prelude::*;
use std::{
cmp::Ordering,
collections::BinaryHeap,
convert::TryInto,
fmt,
hash::Hash,
io::{stdin, Read},
iter::Peekable,
str::FromStr,
vec,
};
use structopt::StructOpt;
// i took... |
use crate::prelude::*;
#[inline(always)]
pub fn byte_to_hex(b: u8) -> char {
debug_assert!(b < 16);
(if b < 10 { b'0' + b } else { b'a' - 10 + b }) as char
}
pub fn write_u64_to_buffer(buffer: &mut Vec<u8>, mut nr: u64) {
let start_len = buffer.len();
loop {
buffer.push((nr % 10) as u8 + b'0')... |
/*
* Slack Web API
*
* One way to interact with the Slack platform is its HTTP RPC-based Web API, a collection of methods requiring OAuth 2.0-based user, bot, or workspace tokens blessed with related OAuth scopes.
*
* The version of the OpenAPI document: 1.7.0
*
* Generated by: https://openapi-generator.tech
*... |
use proconio::{fastout, input};
#[fastout]
fn main() {
input! {
n: usize,
mut a_vec: [i64; n],
};
let mut ans: i64 = 0;
for i in 1..n {
let dif = a_vec[i - 1] - a_vec[i];
if dif > 0 {
ans += dif;
a_vec[i] += dif;
}
}
println!("{}"... |
// Copyright 2019 The Grin 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 agree... |
use std::fs::File;
use std::io::prelude::*;
use std::io::{BufReader, LineWriter};
use crate::editor::Editor;
impl Editor {
/// Load the contents of a file into the buffer, overwriting the current
/// contents of the buffer.
pub fn load(&mut self) {
if !self.filename.is_empty() {
// TOD... |
pub fn is_palindrome(x: i32) -> bool {
x.to_string().chars().rev().eq(x.to_string().chars())
}
fn main() {
assert!(is_palindrome(121));
assert!(!is_palindrome(10));
}
|
#[doc = "Register `DTCMCR` reader"]
pub type R = crate::R<DTCMCR_SPEC>;
#[doc = "Register `DTCMCR` writer"]
pub type W = crate::W<DTCMCR_SPEC>;
#[doc = "Field `EN` reader - EN"]
pub type EN_R = crate::BitReader;
#[doc = "Field `EN` writer - EN"]
pub type EN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc ... |
use core::{fmt, mem, slice};
use std::{panic, ptr};
use std::ffi::CStr;
use std::ffi::CString;
use std::time::Duration;
use libc;
use nix::sys::socket::Ipv4Addr;
use nix::sys::socket::SockAddr;
use nix::sys::time::TimeVal;
mod raw;
#[derive(Debug)]
pub struct DeviceAddress {
pub ip: Ipv4Addr,
pub netmask: Ip... |
#![allow(dead_code)]
use super::models::{FileExtension, FileName};
use super::shared::{ListenerData, Logs};
use maplit::hashmap;
use std::collections::HashMap;
use std::fs::read_dir;
use std::path::Path;
#[derive(Debug, Default)]
pub struct SmartOrganizer<'a> {
pub options: Vec<ListenerData>,
default_options: Ha... |
use crate::arena::Detection;
use crate::geometry::Direction;
use rand::seq::SliceRandom;
use std::collections::HashMap;
pub type Ai = fn(Detection) -> Option<Direction>;
fn walkable_tiles(walk_around: HashMap<Direction, bool>) -> Vec<Direction> {
walk_around
.iter()
.filter(|&(_, &walkable)| walka... |
extern crate espronceda;
use espronceda::parse::parse_code;
use swc_common::sync::Lrc;
use swc_common::SourceMap;
fn main() -> anyhow::Result<()> {
let source_map: Lrc<SourceMap> = Default::default();
parse_code(&source_map, "function a() {}")?;
Ok(())
}
|
extern crate advent_of_code_2017_day_16;
// use advent_of_code_2017_day_16::*;
|
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - Key register"]
pub iwdg_kr: IWDG_KR,
#[doc = "0x04 - Prescaler register"]
pub iwdg_pr: IWDG_PR,
#[doc = "0x08 - Reload register"]
pub iwdg_rlr: IWDG_RLR,
#[doc = "0x0c - Status register"]
pub iwdg_sr: IWDG_S... |
extern crate chrono;
use chrono::{DateTime, Utc};
use uuid::Uuid;
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Post {
summary: String,
contents: String,
author_handle: String,
date_time: DateTime<Utc>,
uuid: Uuid,
}
impl Post {
/*pub fn new(
summary: &str,
conten... |
extern crate kagura;
extern crate wasm_bindgen;
use wasm_bindgen::prelude::*;
#[wasm_bindgen(start)]
pub fn main() {
kagura::run(kagura::Component::new(0, update, render), "app");
}
type State = u64;
enum Msg {
CountUp,
}
struct Sub;
fn update(state: &mut State, msg: &Msg) -> Option<Sub> {
match msg {... |
use crate::prelude::*;
pub trait WorldCommands {
fn spawn_command<T: Component>(&mut self, component: T) -> Entity;
fn spawn_batch_commands<T: Component, I>(&mut self, bundle: I)
where
I: IntoIterator<Item = T>;
fn clear_commands(&mut self);
}
impl WorldCommands for World {
fn spawn_comm... |
//! Abstractions for PostgreSQL-specific return codes.
use sqlstate_macros::state;
use crate::Category;
pub mod class;
pub(crate) mod wrapper;
use self::class::*;
/// A representation for a PostgreSQL-specific `SQLSTATE` code.
#[state(non_standard)]
#[derive(Clone, Eq, PartialEq, Hash, Debug)]
#[non_exhaustive]
pu... |
#[test]
fn check_answer_validity() {
assert_eq!(42, 42);
} |
/// [`AlignmentHorizontal`] represents an horizontal alignment of a cell content.
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub enum AlignmentHorizontal {
/// Align to the center.
Center,
/// Align on the left.
Left,
/// Align on the right.
Right,
}
/// [`AlignmentVert... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.