text stringlengths 8 4.13M |
|---|
/// contains ASCII to integer encoding
const STRING_TO_INT: [u8; 256] = build_stoi();
/// contains integer to ASCII encoding
const INT_TO_STRING: [u8; 6] = [
b'$', b'A', b'C',
b'G', b'N', b'T'
];
/// for complementing in the integer space; note that $ and N go to themselves
pub const COMPLEMENT_INT: [u8; 6]... |
use std::io::{self, Read};
fn main() -> io::Result<()> {
let mut input = String::new();
io::stdin().read_to_string(&mut input)?;
let sum1: u32 = input
.lines()
.map(|x| x.parse::<u32>().unwrap() / 3 - 2)
.sum();
println!("p1: {}", sum1);
let mut sum2: i32 = 0;
for val... |
use cosmwasm_std::{Coin, Decimal, Querier, StdResult, Uint128};
use crate::query::{SwapResponse, TaxCapResponse, TaxRateResponse, TerraQuery, TerraQueryWrapper};
/// This is a helper wrapper to easily use our custom queries
pub struct TerraQuerier<'a, Q: Querier> {
querier: &'a Q,
}
impl<'a, Q: Querier> TerraQue... |
use serde::Deserialize;
#[derive(Debug, Deserialize)]
pub struct Merge {
#[serde(rename = "mn")]
pub match_name: String,
#[serde(rename = "nm")]
pub name: String,
#[serde(rename = "mm")]
pub merge_mode: i64,
}
|
#[derive(Serialize, Deserialize, Debug)]
#[allow(non_snake_case)]
pub struct FilesystemChange {
pub Path: String,
pub Kind: u8,
}
|
//! # SQLite conversions and tooling
use std::fmt::Write;
use rusqlite::{types::ToSqlOutput, ToSql};
pub use rusqlite::{Connection, Error, Result};
use super::{
common::ValueType,
mem::{Database, Field},
};
impl<'a> ToSql for Field<'a> {
fn to_sql(&self) -> rusqlite::Result<ToSqlOutput<'_>> {
us... |
extern crate image;
extern crate noise;
extern crate rand;
extern crate cgmath;
use std::error::Error;
use glium::*;
use glium::backend::Facade;
use glium::uniforms::EmptyUniforms;
use glium::index::{PrimitiveType, NoIndices};
use glium::texture::{RawImage2d, Texture2d};
use self::image::{GenericImage, ImageBuffer, ... |
macro_rules! ElementId {
{$($name:ident),*} => {
#[allow(dead_code)]
struct ElementId {
$($name: String,)*
}
impl ElementId {
#[allow(dead_code)]
fn new() -> Self {
Self {
$($name: crate::libs::random_id::u32val... |
use std::io;
macro_rules! parse_input {
($x:expr, $t:ident) => ($x.trim().parse::<$t>().unwrap())
}
const MAX_W: i32 = 6999;
const MAX_H: i32 = 3000;
const GRAVITY: f32 = 3.711;
// V speed For a landing to be successful,
const MAX_DY: i32 = 40;
const MAX_DX: i32 = 20;
const MARGIN_SPEED: i32 = 5;
//
#[derive(Deb... |
#[doc = "Reader of register ACQUIRE"]
pub type R = crate::R<u32, super::ACQUIRE>;
#[doc = "Reader of field `P`"]
pub type P_R = crate::R<bool, bool>;
#[doc = "Reader of field `NS`"]
pub type NS_R = crate::R<bool, bool>;
#[doc = "Reader of field `PC`"]
pub type PC_R = crate::R<u8, u8>;
#[doc = "Reader of field `MS`"]
pu... |
use crate::lib::error::{DfxError, DfxResult};
use crate::lib::manifest::Manifest;
use crate::{error_invalid_argument, error_invalid_data};
use indicatif::{ProgressBar, ProgressDrawTarget};
use libflate::gzip::Decoder;
use semver::Version;
use std::fs;
use std::io::Write;
use std::path::Path;
use tar::Archive;
pub sta... |
// 移动语义
// 一个变量可以把它拥有的值转移给另外一个变量,称为“所有权转移”
// 赋值语句、函数调用、函数返回等,都有可能导致所有权转移。
// Rust 中所有权转移是所有类型的默认语义
// Rust 中的变量绑定操作,默认是 move 语义,执行了新的变量绑定后,原来的变量就不能再使用了!!!
// Rust vs. C++
// Rust: let v1: Vec<i32> = v2; 移动语义
// C++: std::vector<int> v1 = v2; 复制语义
// 对于“移动语义”,需要强调的一点是,“语义”不代表最终的执行效率。
// “语义”只是规定了什么样的代码是编译器可以接受的,以及它执行后... |
// SPDX-FileCopyrightText: 2020-2021 HH Partners
//
// SPDX-License-Identifier: MIT
use serde::{Deserialize, Serialize};
use crate::{Annotation, ExternalPackageReference};
use super::{Checksum, FileInformation, PackageVerificationCode, SPDXExpression};
/// ## Package Information
///
/// SPDX's [Package Information]... |
#[doc = "Register `WCFGR` reader"]
pub type R = crate::R<WCFGR_SPEC>;
#[doc = "Register `WCFGR` writer"]
pub type W = crate::W<WCFGR_SPEC>;
#[doc = "Field `DSIM` reader - DSI Mode"]
pub type DSIM_R = crate::BitReader;
#[doc = "Field `DSIM` writer - DSI Mode"]
pub type DSIM_W<'a, REG, const O: u8> = crate::BitWriter<'a,... |
#![doc = "generated by AutoRust 0.1.0"]
#![allow(unused_mut)]
#![allow(unused_variables)]
#![allow(unused_imports)]
use super::{models, API_VERSION};
#[non_exhaustive]
#[derive(Debug, thiserror :: Error)]
#[allow(non_camel_case_types)]
pub enum Error {
#[error(transparent)]
Job_GetStatistics(#[from] job::get_st... |
#![allow(dead_code, unused)]
pub type PTE = PageTableEntry;
pub const KERNBASE: u32 = 0x80000000;
pub const PDXSHIFT: usize = 22;
pub const PTXSHIFT: usize = 12;
pub const PAGESIZE: usize = 4096;
#[derive(Copy, Clone)]
pub enum Flag {
Present,
Writable,
User,
WriteThrough,
CacheDisable,
Acces... |
#[doc = "Reader of register STGENC_PIDR6"]
pub type R = crate::R<u32, super::STGENC_PIDR6>;
#[doc = "Reader of field `PIDR6`"]
pub type PIDR6_R = crate::R<u32, u32>;
impl R {
#[doc = "Bits 0:31 - PIDR6"]
#[inline(always)]
pub fn pidr6(&self) -> PIDR6_R {
PIDR6_R::new((self.bits & 0xffff_ffff) as u32... |
use std::collections::HashMap;
pub type Vector = HashMap<String, f64>;
pub type Matrix = HashMap<String, Vector>;
pub fn get_stochastic_matrix(link_matrix: &Matrix) -> Matrix {
let mut stochastic_matrix = Matrix::new();
for (src, vector) in link_matrix {
let mut sum = 0f64;
for (_, value) in vector {
... |
//! This exposes `Session`, the struct stored in the `Alloy`.
use std::sync::Arc;
use super::SessionStore;
use iron::typemap;
/// A session which provides basic CRUD operations.
pub struct Session<K: typemap::Key> {
key: K,
store: Arc<Box<SessionStore<K> + 'static + Send + Sync>>
}
impl<K: typemap::Key> Sess... |
fn read_line() -> String {
let mut line = String::new();
std::io::stdin().read_line(&mut line).unwrap();
line.trim_end().to_owned()
}
struct Sake {
v: u64,
p: u64,
}
fn main() {
let stdin = read_line();
let mut iter = stdin.split_whitespace();
let n = iter.next().unwrap().parse().unwra... |
extern crate fafnir;
extern crate mimirsbrunn;
extern crate num_cpus;
extern crate postgres;
use fafnir::Args;
fn run(args: Args) -> Result<(), mimirsbrunn::Error> {
let client = postgres::Client::connect(&args.pg, postgres::tls::NoTls).unwrap_or_else(|err| {
panic!("Unable to connect to postgres: {}", er... |
use super::cpu_registers::set_bit;
impl super::Ppu {
pub fn perform_memory_fetch(&mut self) {
match self.line_cycle % 8 {
0 => self.inc_coarse_x(),
1 => self.fetch_nametable_byte(),
3 => self.fetch_attribute_table_byte(),
5 => self.fetch_low_pattern_table_by... |
// Copyright (C) 2021 Subspace Labs, 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... |
//! MARC record representation.
//!
//! The code in this module supports records in the MARC format. It can be
//! used for processing both [bibliographic][] and [name authority][] records.
//!
//! [bibliographic]: https://www.loc.gov/marc/bibliographic/
//! [name authority]: https://www.loc.gov/marc/authority/
use ser... |
use super::atom::btn::Btn;
use super::molecule::modal::{self, Modal};
use isaribi::{
style,
styled::{Style, Styled},
};
use kagura::prelude::*;
use nusa::prelude::*;
pub struct Props {
pub data: String,
}
pub enum Msg {
Close,
Ok,
Input(String),
}
pub enum On {
Close,
Ok(String),
}
p... |
fn read_input(path: &str) -> Vec<u64> {
std::fs::read_to_string(path)
.unwrap()
.lines()
.map(|l| l.parse().unwrap())
.collect()
}
fn is_valid(index: usize, numbers: &Vec<u64>, look_behind_amount: usize) -> bool {
let possibilities = &numbers[(index - look_behind_amount)..index]... |
use std::path;
use crate::decode;
use crate::mmu::MMU;
use crate::registers::{CpuFlag, Registers};
pub struct CPU {
registers: Registers,
mmu: MMU,
/* Cycle related variables. */
total_cycles: usize,
cycles_remaining: u8,
ime: bool,
}
impl CPU {
pub fn new(path: &path::Path) -> CPU {
... |
#[macro_use]
extern crate lazy_static;
extern crate futures;
mod notify_cell;
mod movement;
mod tree;
pub mod buffer;
pub mod editor;
|
use super::Control;
use std::ffi::{CStr, CString};
use std::mem;
use ui::UI;
use ui_sys::{self, uiControl, uiLabel};
define_control! {
/// A non-interactable piece of text.
rust_type: Label,
sys_type: uiLabel
}
impl Label {
/// Create a new label with the given string as its text.
/// Note that la... |
/*
* Copyright 2018 Intel Corporation
*
* 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... |
pub use clap::{AppSettings, Parser};
use crate::input::{default::*, InputInterface};
/// Exchange backtesting framework
#[derive(Parser)]
#[clap(version = "0.0.1", author = "Andrew Sonin <sonin.cel@yandex.ru>")]
pub struct ArgumentParser {
/// Sets the file each line of which should contain absolute paths to the ... |
#[derive(Copy, Clone, Debug)]
pub struct RecordHeader {
header_type: u8,
message_type: u8,
local_message_type: u8
}
impl RecordHeader {
pub fn new(raw_header: u8) -> RecordHeader {
let t = (raw_header & 0b10000000) >> 7;
let mt = (raw_header & 0b01000000) >> 6;
let lmt = (raw_h... |
#[doc = "Register `ISR` reader"]
pub type R = crate::R<ISR_SPEC>;
#[doc = "Register `ISR` writer"]
pub type W = crate::W<ISR_SPEC>;
#[doc = "Field `TXE` reader - Transmit data register empty (transmitters) This bit is set by hardware when the I2C_TXDR register is empty. It is cleared when the next data to be sent is wr... |
use std::io::{stdin, Read};
use std::iter::Iterator;
use std::ops::Range;
const RANGES: [Range<usize>; 9] = [
000000..089000, // [000000, 088999]
111111..189000, // [111111, 188999]
222222..289000, // [222222, 288999]
333333..389000, // [333333, 388999]
444444..489000, // [444444, 488999]
55555... |
//! Errors for the binary proxy protocol.
/// An error in parsing a binary PROXY protocol header.
#[derive(thiserror::Error, Debug, PartialEq)]
pub enum ParseError {
#[error("Expected header to the protocol prefix plus 4 bytes after the prefix (length {0}).")]
Incomplete(usize),
#[error("Expected header to... |
use super::atom::btn::{self, Btn};
use super::atom::dropdown::{self, Dropdown};
use super::atom::text::Text;
use super::molecule::modal::{self, Modal};
use crate::arena::block;
use isaribi::{
style,
styled::{Style, Styled},
};
use kagura::prelude::*;
use std::rc::Rc;
use block::chat::channel::{ChannelPermissio... |
#[doc = "Register `MACRxFCR` reader"]
pub type R = crate::R<MACRX_FCR_SPEC>;
#[doc = "Register `MACRxFCR` writer"]
pub type W = crate::W<MACRX_FCR_SPEC>;
#[doc = "Field `RFE` reader - Receive Flow Control Enable"]
pub type RFE_R = crate::BitReader;
#[doc = "Field `RFE` writer - Receive Flow Control Enable"]
pub type RF... |
use crate::read_pattern::ReadPattern;
#[derive(Copy, Clone, Debug)]
pub struct AndPattern<L, R>(pub L, pub R);
impl<L, R> ReadPattern for AndPattern<L, R> where
L: ReadPattern,
R: ReadPattern {
fn read_pattern(&self, text: &str) -> Option<usize> {
let len_a = self.0.read_pattern(text)?;
l... |
use foc_types::types as t;
pub trait RotorPositionSensor {
fn set_count_to_zero(&mut self);
fn get_cpr(&self) -> t::ShaftTicks;
fn read_counts(&self) -> t::ShaftTicks;
fn read_rotor_position(&self) -> t::RotorAngleRadians;
} |
#![deny(rust_2018_idioms, warnings)]
#![deny(clippy::all, clippy::pedantic)]
use hyper::http;
use enumset::EnumSetType;
mod client;
mod models;
pub use client::TrcClient;
pub use models::message_result::MessageTestResult;
#[derive(Debug, EnumSetType)]
pub enum TestType {
LegacyDirectMethod,
LegacyTwin,
... |
fn main() {
let test = measure_persistence(13);
println!("{}", test);
let test2 = measure_persistence(1234);
println!("{}", test2);
let test3 = measure_persistence(9876);
println!("{}", test3);
let test4 = measure_persistence(199);
println!("{}", test4);
}
fn reduce(number: isize) -> is... |
#[test]
fn test_path_symlink() {
assert_wasi_output!(
"../../wasitests/path_symlink.wasm",
"path_symlink",
vec![],
vec![
(
"temp".to_string(),
::std::path::PathBuf::from("wasitests/test_fs/temp")
),
(
... |
use nu_protocol::{ShellError, Span};
use serde::{Deserialize, Serialize};
use std::{fmt::Display, path::PathBuf};
pub mod db;
pub mod db_column;
pub mod db_constraint;
pub mod db_foreignkey;
pub mod db_index;
pub mod db_row;
pub mod db_schema;
pub mod db_table;
#[derive(Clone, Debug, Serialize, Deserialize, Eq, Parti... |
use itertools::Itertools;
use std::collections::HashMap;
use std::fs;
fn main() {
let filename = "input/input.txt";
let (polymer, pair_insertion_rules) = parse_input_file(filename);
println!("polymer_template: {:?}", polymer);
println!("pair_insertion_rules: {:?}", pair_insertion_rules);
println!(... |
#[doc = "Reader of register GPIO_OUT_SET"]
pub type R = crate::R<u32, super::GPIO_OUT_SET>;
#[doc = "Writer for register GPIO_OUT_SET"]
pub type W = crate::W<u32, super::GPIO_OUT_SET>;
#[doc = "Register GPIO_OUT_SET `reset()`'s with value 0"]
impl crate::ResetValue for super::GPIO_OUT_SET {
type Type = u32;
#[i... |
use serde::de::DeserializeOwned;
use serde::ser::Serialize;
use serde_json::Value;
use std::marker::Sized;
use std::time::Duration;
use crate::{env, ServiceResult};
#[derive(Debug, Serialize)]
#[serde(tag = "type")]
#[serde(rename_all = "kebab-case")]
pub enum IdentificationRequest {
Barcode {
code: Strin... |
//Kata: https://www.codewars.com/kata/5765870e190b1472ec0022a2/train/rust
struct Tile {
visited: bool,
value: char,
}
impl Tile {
fn new(value: char) -> Self {
Self {
visited: false,
value,
}
}
}
struct Board {
tiles: Vec<Vec<Tile>>,
x_len: i32,
y_l... |
use std::fs::File;
use std::io;
use std::io::Read;
use std::path::Path;
use crate::solution::ProblemSolution;
pub struct Solution {}
impl ProblemSolution for Solution {
fn name(&self) -> &'static str {
return "problem_03";
}
fn part1(&self) -> io::Result<i64> {
let mut file = File::open(... |
#![cfg_attr(not(feature = "std"), no_std)]
use codec::{Encode, Decode};
use frame_support::{
decl_module,
decl_storage,
decl_event,
decl_error,
ensure,
StorageValue,
StorageMap,
Parameter,
dispatch,
debug
};
use sp_io::hashing::blake2_128;
use frame_system::ensure_signed;
use sp_runtime::DispatchError;
use s... |
use std::str;
use std::net::{SocketAddr, ToSocketAddrs};
use std::collections::HashMap;
use tokio::prelude::*;
use tokio::net::UdpSocket;
use tokio::prelude::Future;
use serde::{Deserialize, Serialize};
use chrono::{Utc, Local, DateTime};
use crate::shared::{MonamiMessage, MessageType};
use crate::shared::MonamiStat... |
pub mod entry_map;
pub mod laze_type;
pub mod semantic_param;
pub mod trans_ast;
pub mod trans_dec;
pub mod trans_exp;
pub mod trans_funcdec;
pub mod trans_stm;
pub mod trans_ty;
pub mod trans_var;
|
fn main() {
let r = longest_substring_without_repeating_chars("abcbd");
println!("{}", r); // 3
let r = longest_substring_without_repeating_chars("abcabcbb");
println!("{}", r); // 3
let r = longest_substring_without_repeating_chars("abcab");
println!("{}", r); // 3
let r = longest_substr... |
pub fn parse(data: &str) -> usize {
let mut offsets = data.lines().map(|line| {
line.trim().parse::<isize>().unwrap()
}).collect::<Vec<isize>>();
let length = offsets.len();
let mut idx: usize = 0;
let mut steps: usize = 0;
loop {
let offset = offsets[idx];
offsets[idx] ... |
use std::borrow::Borrow;
use std::convert::AsRef;
use std::path::Path;
use std::sync::Arc;
use buffer::{Buffer, File};
#[derive(Clone, Debug, PartialEq)]
pub struct Pane {
// Tabs inside a pane.
pub items: Vec<Item>,
pub active_item: Option<Item>,
}
impl Pane {
pub fn new() -> Pane {
Pane {
... |
use std::marker::PhantomData;
use std::any::Any;
use std::rc::Rc;
use subscriber::*;
use observable::*;
use unsub_ref::UnsubRef;
use std::sync::Arc;
pub struct MapState<FProj>
{
proj: Arc<FProj>
}
pub struct MapOp<FProj, V, Src>
{
proj: Arc<FProj>,
source: Src,
PhantomData: PhantomData<V>
}
pub trait... |
use crate::UpsertBuilder;
use storm::Entity;
pub trait SaveEntityPart: Entity {
fn save_entity_part<'a>(&'a self, k: &'a Self::Key, builder: &mut UpsertBuilder<'a>);
}
#[cfg(feature = "cache")]
impl<T> SaveEntityPart for cache_crate::CacheIsland<T>
where
T: SaveEntityPart,
{
fn save_entity_part<'a>(&'a se... |
use time::PreciseTime;
#[test]
fn big_blob_of_tests() {
let start = PreciseTime::now();
let matrix = create_graph_from_mysql();
let end = PreciseTime::now();
println!("{} seconds to start up.", start.to(end));
let from_ids = [2266, 17, 17, 9682, 3405];
let to_ids = [3002, 3002, 15031, 14658, 2... |
use crate::molecule::*;
#[derive(Clone, Copy)]
pub struct SmilesAtom {
atom: Atom,
from_organic_subset: bool,
}
impl SmilesAtom {
pub fn new(atom: Atom, from_organic_subset: bool) -> SmilesAtom {
SmilesAtom {
atom,
from_organic_subset,
}
}
pub fn get_atom(s... |
fn main() {
let ten_things="Apples Oranges Crows Telephones Light Sugar";
println!("Wait there are not 10 things in that list. Let's fix that.");
let mut stuff:Vec<&str> = ten_things.split(" ").collect::<Vec<&str>>();
println!("{:?}",stuff);
let mut more_stuff = vec!["Day", "Night", "Song", "Fri... |
// Copyright (C) 2021 Subspace Labs, 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... |
use crate::{
syntax::{SyntaxChildren, SyntaxExt, SyntaxTree},
Symbol,
};
use christmas_tree::{Discriminant, RootOwnership, TreeNode};
mod generated;
pub use self::generated::*;
pub fn children<R, P, C>(parent: &P) -> SyntaxChildren<R, C>
where
R: RootOwnership<SyntaxTree>,
P: AstNode<R>,
C: Discri... |
use rost::{compile, Declaration, Expr, FloatBits, IntegerBits, Type, TypeAnnotation, TypedExpr};
#[test]
fn basic_prog_1() {
let prog = "main = + 1 - func(2) 3";
compile(prog).unwrap();
}
#[test]
fn basic_prog_2() {
let prog = r#"
myfunc a b = + 1 - func(2) 3
main = myfunc (12, 13)"#;
match compile(pr... |
use super::packet::datatable::ParseSendTable;
use super::vector::{Vector, VectorXY};
use crate::consthash::ConstFnvHash;
use crate::demo::message::stringtable::log_base2;
use crate::demo::packet::datatable::SendTableName;
use crate::demo::parser::MalformedSendPropDefinitionError;
use crate::demo::sendprop_gen::get_prop... |
use futures::{self, Future, Stream};
use clickhouse_rs::Pool;
fn main() -> Result<(), Box<std::error::Error>> {
let query = std::env::args().nth(1)
.ok_or("please enter a query")?;
let pool = Pool::new("tcp://127.0.0.1:9000");
let fut = pool
.get_handle()
.and_then(move |c| {
... |
use proconio::input;
use proconio::marker::*;
use std::cmp::*;
fn gcd(n: usize,m: usize) -> usize{
assert!(n > m);
if m == 0{
return n
}
gcd(m,n % m)
}
fn lcm(n: usize,m: usize) -> usize{
assert!(n > m);
n / gcd(n,m) * m
}
fn main() {
input! {
n: usize,
m: usize,
... |
use image::bmp::BMPEncoder;
use image::ColorType;
use rayon::prelude::*;
use std::env;
use std::fs::File;
use std::io::{self, BufWriter};
use std::path::Path;
fn main() -> Result<(), io::Error> {
let args = env::args().skip(1).collect::<Vec<_>>();
if args.len() != 2 {
return Err(io::Error::new(
... |
pub struct Pong;
impl SimpleState for Pong {
fn on_start(&mut self, data: StateData<'_, GameData<'_, '_>>) {}
} |
tonic::include_proto!("gw/gw");
|
#[doc = "Register `ETH_DMAC0SFCSR` reader"]
pub type R = crate::R<ETH_DMAC0SFCSR_SPEC>;
#[doc = "Register `ETH_DMAC0SFCSR` writer"]
pub type W = crate::W<ETH_DMAC0SFCSR_SPEC>;
#[doc = "Field `ESC` reader - ESC"]
pub type ESC_R = crate::BitReader;
#[doc = "Field `ESC` writer - ESC"]
pub type ESC_W<'a, REG, const O: u8> ... |
// Copyright 2018 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.
#![deny(warnings)]
#![allow(unused)] // TODO(atait): Remove once there are non-test clients
use byteorder::{BigEndian, ByteOrder};
use protocol;
use protoc... |
use svm_abi_layout::layout;
use crate::{traits::Push, ByteSize, Encoder};
impl<W> Encoder<W> for bool
where
W: Push<Item = u8>,
{
fn encode(&self, w: &mut W) {
w.push(if *self {
layout::BOOL_TRUE
} else {
layout::BOOL_FALSE
});
}
}
impl ByteSize for bool {
... |
use aoc2019::io::slurp_stdin;
type Point = (i64, i64);
#[derive(Eq, PartialEq, Clone, Copy)]
enum Elem {
Open,
Wall,
Start,
Key(usize),
Door(usize),
}
type Map = aoc2019::grid::Grid<Elem>;
fn read_input(input: &str) -> Map {
let mut builder = aoc2019::grid::GridBuilder::new();
for c in ... |
// Copyright (c) 2019 - 2020 ESRLabs
//
// 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 ... |
// Copyright (c) The Starcoin Core Contributors
// SPDX-License-Identifier: Apache-2.0
use anyhow::{bail, Result};
use async_trait::async_trait;
use backoff::{backoff::Backoff, ExponentialBackoff};
use futures::{
task::{Context, Poll},
FutureExt, Stream,
};
use futures_timer::Delay;
use libra_logger::prelude::*... |
use glium::Display;
use glium::glutin::event::{VirtualKeyCode, ElementState, WindowEvent, MouseButton};
use glium::glutin::dpi::PhysicalPosition;
pub trait InputListener {
fn handle_char_ev(&mut self, ch: char) -> bool;
fn handle_key_ev(&mut self, key: Option<VirtualKeyCode>, pressed: bool) -> bool;
fn handle_mouse... |
// Carry-less Multiplication
#[inline]
fn cl_mul(a: u64, b: u64, dst: &mut [u64; 2]) {
dst[0] = 0;
dst[1] = 0;
for i in 0u64..64 {
if (b & (1u64 << i)) != 0 {
dst[1] ^= a;
}
// Shift the result
dst[0] >>= 1;
if (dst[1] & (1u64 << 0)) != 0 {
... |
use ansi_term::Style;
use ansi_term::Colour::{Purple, Yellow, Green};
use mime::Mime;
use error::CommandResult;
pub trait Asset {
fn get_id(&self) -> &str;
fn get_md5(&self) -> &str;
fn get_mime(&self) -> &Mime;
fn get_name(&self) -> &Option<String>;
fn get_source(&self) -> &str;
fn get_path(&s... |
/*
翻转字符串里的单词
给定一个字符串,逐个翻转字符串中的每个单词。
示例 1:
输入: "the sky is blue"
输出: "blue is sky the"
示例 2:
输入: " hello world! "
输出: "world! hello"
解释: 输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。
示例 3:
输入: "a good example"
输出: "example good a"
解释: 如果两个单词间有多余的空格,将反转后单词间的空格减少到只含一个。
说明:
无空格字符构成一个单词。
输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。... |
pub trait Summarizable {
fn summary(&self) -> String {
String::from("(Read more...)")
}
}
pub fn notify<T: Summarizable>(item: T) {
println!("Breaking news! {}", item.summary());
}
// multi
fn some_function<T: Display + Clone, U: Clone + Debug>(t: T, u: U) -> i32 {
}
|
extern crate libc;
pub mod source;
pub mod gs;
pub mod raw;
pub use source::InputSource;
pub use gs::Effect;
#[macro_export]
macro_rules! obs_module {
($INIT_FN:ident) => (
#[no_mangle]
pub extern fn obs_module_load() -> bool {
$INIT_FN()
}
)
}
|
use std::io::{self, Read};
fn main() {
let start_time = std::time::Instant::now();
let modules = load_modules().unwrap_or_else(|err| {
println!("Could not load input file!\n{:?}", err);
std::process::exit(1);
});
let part_1_fuel: i32 = modules.iter().copied().map(|module| fuel_for... |
use std::convert::TryFrom;
use std::ops::{BitOr, Mul, Neg, Shl};
#[derive(Debug)]
pub enum Expression {
Known(i32),
Unknown,
}
impl Expression {
pub fn check_hram(self) -> Self {
unimplemented!();
self
}
}
impl From<i32> for Expression {
fn from(x: i32) -> Self {
Self::Kno... |
fn main() {
let data_1 = create_data();
part_1(data_1);
}
fn part_1(mut program: Vec<usize>) {
program[1] = 12;
program[2] = 2;
run_program(&mut program);
println!("(pt1) Intcode @ position 0 = {}", program[0]);
}
fn run_program (program: &mut Vec<usize>) {
let mut pc = 0;
loop {
... |
use sdl2::{
pixels::{Color, PixelFormatEnum},
rect::Rect,
render::{Canvas, TextureAccess, TextureCreator, Texture, BlendMode},
ttf::{Font, Sdl2TtfContext},
video::{Window, WindowContext},
};
use std::collections::HashMap;
const ASCII_START: char = 32u8 as char;
const ASCII_END: char = 127u8 as char... |
use crate::error::{Error};
use crate::io_extra;
use crate::broadcaster::Broadcaster;
use std::{ thread };
use crossbeam::{ channel };
use tokio::prelude::*;
use tokio::net::TcpListener;
use futures::sync::mpsc;
/// This provides a way of sending to and receiving input to/from the interpreter. If
/// a socket address i... |
fn is_kprime(n: u32, k: u32) -> bool {
let mut primes = 0;
let mut f = 2;
let mut rem = n;
while primes < k && rem > 1{
while (rem % f) == 0 && rem > 1{
rem /= f;
primes += 1;
}
f += 1;
}
rem == 1 && primes == k
}
struct KPrimeGen {
k: u32,
... |
//! Named constants for NVIC ids specific to this chip
pub const CRYP: u32 = 79;
pub const HASH_RNG: u32 = 80; |
#[doc = "Register `WPSN_CURR` reader"]
pub type R = crate::R<WPSN_CURR_SPEC>;
#[doc = "Field `WRPSn` reader - Bank 1 sector write protection option status byte"]
pub type WRPSN_R = crate::FieldReader;
impl R {
#[doc = "Bits 0:7 - Bank 1 sector write protection option status byte"]
#[inline(always)]
pub fn w... |
// Copyright (c) The Starcoin Core Contributors
// SPDX-License-Identifier: Apache-2.0
use futures::lock::Mutex;
use std::collections::HashMap;
use std::sync::Arc;
use sgtypes::message::{AntFinalMessage, BalanceQueryResponse};
use sgtypes::s_value::SValue;
use anyhow::Result;
use libra_crypto::HashValue;
use libra_l... |
//! The implementation of route recognizer.
use {
failure::Error,
indexmap::{indexset, map::Entry, IndexMap, IndexSet},
std::{
cmp::{self, Ordering},
fmt, mem,
},
};
#[derive(Debug, Default, PartialEq)]
pub struct Captures {
params: Vec<(usize, usize)>,
wildcard: Option<(usize,... |
#![feature(test)]
extern crate test;
use acronym;
#[bench]
fn bench_mine(b: &mut test::Bencher) {
b.iter(|| {
acronym::abbreviate("");
acronym::abbreviate("Portable Network Graphics");
acronym::abbreviate("Ruby on Rails");
acronym::abbreviate("HyperText Markup Language");
... |
mod viewer;
use polyhedrator::*;
fn main() {
viewer::run();
}
|
use serde::{Deserialize, Serialize};
/// A language that was spoken in a movie or TV show
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Language {
/// The ISO 369-1 code for this language
pub iso_639_1: String,
/// The name of this language
pub name: String,
}
|
//! Contains an in memory write buffer that stores incoming data, durably.
#![deny(rust_2018_idioms)]
#![warn(
missing_copy_implementations,
missing_debug_implementations,
clippy::explicit_iter_loop,
clippy::use_self
)]
mod column;
mod database;
mod dictionary;
pub mod partition;
mod store;
mod table;... |
#[macro_use]
extern crate clap;
extern crate jwconv;
fn main() {
////////////////////
// Parse Arguments
////////////////////
let yml = load_yaml!("cli.yml");
let matches = clap::App::from_yaml(yml).get_matches();
////////////////////
// Convert
////////////////////
let data =... |
use bevy_math::{IVec2, UVec2, Vec4};
use super::*;
/// A layer
pub enum Layer {
/// A layer densely populated with tiles.
TileLayer {
/// The amount of tiles in the x and y axis.
size: UVec2,
/// Position offset of the layer, measured in tiles.
position: IVec2,
... |
fn main () {
let s = "パタトクカシーー";
let s: String = s.chars().step_by(2).collect();
println!("{}", s);
}
|
#[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::SL1CFG {
#[doc = r" Modifies the contents of the register"]
#[inline]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&R, &'w mu... |
/// The result of a tuning operation
#[derive(Clone)]
pub struct TuneResult(uhd_sys::uhd_tune_result_t);
impl TuneResult {
/// Returns the target RF frequency
pub fn target_rf_freq(&self) -> f64 {
self.0.target_rf_freq
}
/// Returns the target RF frequency constrained to the device's supported... |
#![allow(non_upper_case_globals)]
#![allow(non_camel_case_types)]
#![allow(non_snake_case)]
include!(concat!(env!("OUT_DIR"), "/bindings.rs"));
pub mod consts {
pub use super::{
ABS_RX, ABS_RY, ABS_X, ABS_Y, BTN_A, BTN_B, BTN_DPAD_DOWN, BTN_DPAD_LEFT, BTN_DPAD_RIGHT,
BTN_DPAD_UP, BTN_SELECT, BTN_S... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.