text stringlengths 8 4.13M |
|---|
#![allow(dead_code)]
use crate::{aocbail, utils};
use utils::{AOCResult, AOCError};
pub fn day9() {
let input = utils::get_input("day9");
let bad_value = find_bad_value(input, 25).unwrap();
println!("encoding_error part 1: {}", bad_value.1);
let input = utils::get_input("day9");
println!("encodin... |
use std::collections::HashSet;
use std::io;
use std::io::Read;
fn main() {
let mut input = String::new();
io::stdin().read_to_string(&mut input).unwrap();
println!("{}", input.split("\n\n").map(|x| {
x.chars().filter(|y| y.is_ascii_lowercase()).collect::<HashSet<char>>().len()
}).sum::<usize>()... |
use std::collections::HashMap;
use std::iter::FromIterator;
struct Pos {
x: i32,
y: i32,
}
fn create_map() -> HashMap<char, Pos> {
let iter = "123456789.0".chars().enumerate()
.map(|(n, c)| { (c, Pos{ x: (n as i32) % 3, y: (n as i32) / 3 } ) });
HashMap::<char, Pos>::from_iter(iter)
}
fn dis... |
use scanner_proc_macro::insert_scanner;
#[insert_scanner]
fn main() {
let (n, x) = scan!((usize, usize));
let ab = scan!((usize, usize); n);
let mut dp = vec![false; x + 1];
dp[0] = true;
for (a, b) in ab {
let mut nxt = vec![false; x + 1];
for y in 0..x {
if y + a <= x... |
use std::cmp;
use std::collections::BTreeMap;
type PreReqVec = Vec<char>;
type NodeMap = BTreeMap<char, PreReqVec>;
#[derive(Debug, Clone)]
struct Job {
node: char,
end_time: u32
}
#[derive(Debug, Clone)]
struct Worker {
queue: Vec<Job>
}
impl Worker {
fn get_node_end_time(&self, node: char) -> Opti... |
//! https://github.com/lumen/otp/tree/lumen/lib/parsetools/src
use super::*;
test_compiles_lumen_otp!(leex);
test_compiles_lumen_otp!(yecc);
test_compiles_lumen_otp!(yeccparser);
test_compiles_lumen_otp!(yeccscan imports "lib/stdlib/src/erl_scan", "lib/stdlib/src/io");
fn relative_directory_path() -> PathBuf {
s... |
use std::{
collections::HashMap,
sync::{Arc, Mutex},
};
use crate::events::SenseiEvent;
use super::database::WalletDatabase;
use bitcoin::{Transaction, Txid};
use lightning::chain::chaininterface::BroadcasterInterface;
use tokio::sync::broadcast;
pub struct SenseiBroadcaster {
pub debounce: Mutex<HashMap... |
use std::fmt;
use std::io;
use std::result;
/// A convenient type alias for `Result<T, snap::Error>`.
pub type Result<T> = result::Result<T, Error>;
/// `IntoInnerError` occurs when consuming an encoder fails.
///
/// Consuming the encoder causes a flush to happen. If the flush fails, then
/// this error is returned,... |
#![crate_name = "fserve"]
extern crate either;
#[macro_use] extern crate log;
extern crate env_logger;
extern crate mio;
#[macro_use] extern crate mioco;
extern crate rand;
extern crate base64;
extern crate time;
mod controller;
mod model;
mod messagebuilder;
mod state;
mod utils;
use either::*;
use mio::tcp::TcpStr... |
// 並列処理を実装。
// lib.rs から SortOrder 列挙型を読み込む。
use super::SortOrder;
// rayon クレートを読み込む。
use rayon;
// std::cmp から Ordering を読み込む。
use std::cmp::Ordering;
// 並列処理を実行するかどうかの閾値。
const PARALLEL_THRESHOLD: usize = 4096;
// pub 修飾子でモジュール (このファイル) 外から呼び出し可能となる。
// 型パラメータを <T> で導入する。ただし、大小比較ができるものに型を制限するために、
// <T: Ord + Sen... |
extern crate time;
extern crate rustc_serialize;
use rustc_serialize::base64::{FromBase64, ToBase64, Config, CharacterSet, Newline};
fn main() {
let t = time::now();
println!("{:?}", t.to_timespec());
let pt = t.to_timespec().sec as i32;
println!("{:?}", pt);
let mut ip: *const i32 = &pt;
let ... |
extern crate gstreamer as gst;
use gst::prelude::*;
fn main() {
gst::init().unwrap();
let main_loop = glib::MainLoop::new(None, false);
let input_pipeline = gst::Pipeline::new("file-pipeline");
let output_pipeline = gst::Pipeline::new("output-pipeline");
let uri = "file:///e:/test.mp4";
let ur... |
//! This module contains all the OpenGEX structures as specified. The module tries to stay as close
//! to the OpenGEX structures as possible.
//!
//! Some of the documentation might be subjected to copyright by Eric Lengyel. For more detailed
//! documentation, please go to http://opengex.org.
use std::collections::H... |
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)]
#[cfg(feature = "Security_Authorization_AppCapabilityAccess")]
pub mod AppCapabilityAccess;
|
use crate::codegen::module_codegen::CodeGenModule;
use crate::logger;
use std::collections::HashMap;
use std::process;
use inkwell::context::Context;
pub struct Master<'a> {
context: &'a Context,
logger: logger::logger::Logger<'a>,
modules: HashMap<&'a str, CodeGenModule<'a>>,
}
impl<'a> Master<'a> {
... |
// script_manager.rs
//
// Copyright (c) 2019, Univerisity of Minnesota
//
// Author: Bridger Herman (herma582@umn.edu)
//! Script manager
use std::collections::HashMap;
use std::fmt;
use crate::entity::EntityId;
use crate::traits::Update;
use wasm_bindgen::prelude::*;
#[wasm_bindgen(module = "/assets/wre.js")]
ex... |
#[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::SYSCONFIG {
#[doc = r"Modifies the contents of the register"]
#[inline(always)]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&R... |
//! The following is derived from Rust's
//! library/std/src/io/mod.rs at revision
//! dca3f1b786efd27be3b325ed1e01e247aa589c3b.
/// Enumeration of possible methods to seek within an I/O object.
///
/// It is used by the [`Seek`] trait.
///
/// [`Seek`]: std::io::Seek
#[derive(Copy, PartialEq, Eq, Clone, Debug)]
#[cfg... |
use failure::*;
#[derive(Debug, Fail)]
pub enum TransactionError {
#[fail(display = "Could not load the file: {:?}", 0)]
LoadError(std::io::Error),
#[fail(display = "Could not load the file: {:?}", 0)]
ParseError(serde_json::Error),
#[fail(display = "Could not load the file: {:?}", 0)]
Error(&'... |
fn somma(n1: i32, n2: i32){
println!("The sum is: {}", n1+n2);
}
fn main() {
somma(3, 5);
} |
use crate::{error::ClientError, network::request_async, Result};
use isahc::config::RedirectPolicy;
use isahc::prelude::*;
use serde::Deserialize;
const API_ENDPOINT: &str = "https://api.mmoui.com/v4/game/WOW/filedetails";
const ADDON_URL: &str = "https://www.wowinterface.com/downloads/info";
/// Return the wowi API ... |
use super::*;
struct PlayerState {
step_animation: f32,
}
impl PlayerState {
pub fn new() -> Self {
Self {
step_animation: 0.0,
}
}
pub fn update(&mut self, player: &Player, delta_time: f32) {
self.step_animation += player.target_velocity.len() * delta_time;
}
}... |
#![recursion_limit = "512"]
mod app;
mod components;
mod utils;
use prc::hash40::{set_custom_labels, Hash40};
use wasm_bindgen::prelude::*;
// This is the entry point for the web app
#[wasm_bindgen]
pub fn run_app() -> Result<(), JsValue> {
utils::set_panic_hook();
yew::start_app::<app::App>();
Ok(())
}
... |
use proconio::input;
use std::cmp::Reverse;
use std::collections::HashSet;
fn main() {
input! {
n: usize,
st: [(String, u32); n],
};
let mut ti = Vec::new(); // original
let mut seen = HashSet::new();
for (i, (s, t)) in st.iter().enumerate() {
if seen.contains(s) {
... |
use serde_json::{Value,Result};
use serde::{Deserialize,Serialize};
///定义输入keystore文件格式,用于转换json格式文件
#[derive(Serialize, Deserialize)]
struct KeyStore{
version:u8,
id:String,
address:String,
crypto:Crypto,
}
#[derive(Serialize,Debug,Deserialize)]
struct Crypto{
ciphertext:String,
cipher:String... |
#[derive(Copy, Clone, PartialEq)]
pub enum TokenType {
Illegal,
Eof,
Comment,
Quasiquote,
Symbol,
Keyword,
Number,
Float,
String,
RParen,
LParen,
Quote,
Unquote,
At,
Mark,
}
impl ::std::fmt::Display for TokenType {
fn fmt(&self, f: &mut ::std::fmt::Format... |
use crate::{alphavantage::AlphaVantage, buy::Backtest, config::Config, mysql_db::{Database}, stockplotter::StockPlotter};
pub struct StockRS {
pub alphavantage: AlphaVantage,
pub database: Database,
pub stockplotter: StockPlotter,
pub stocks: Vec<String>,
pub backtest: Backtest,
}
impl StockRS {
... |
use hyper_tls::HttpsConnector;
use hyper::Client;
use serde::{Serialize, Deserialize};
use bytes::buf::ext::BufExt;
#[derive(Serialize, Deserialize, Debug)]
struct Echo {
args: Args,
headers: Headers,
url: String
}
#[derive(Serialize, Deserialize, Debug)]
struct Args {
foo1: String,
foo2: String,
... |
#![doc = "Peripheral access API for TM4C129X microcontrollers (generated using svd2rust v0.17.0)\n\nYou can find an overview of the API [here].\n\n[here]: https://docs.rs/svd2rust/0.17.0/svd2rust/#peripheral-api"]
#![deny(const_err)]
#![deny(dead_code)]
#![deny(improper_ctypes)]
#![deny(legacy_directory_ownership)]
#![... |
#[doc = "Reader of register AFRH"]
pub type R = crate::R<u32, super::AFRH>;
#[doc = "Writer for register AFRH"]
pub type W = crate::W<u32, super::AFRH>;
#[doc = "Register AFRH `reset()`'s with value 0"]
impl crate::ResetValue for super::AFRH {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Typ... |
use wasm_bindgen::JsValue;
use wasm_bindgen_test::*;
use js_sys::*;
#[wasm_bindgen_test]
fn length() {
fn test(s: &str) {
assert_eq!(JsString::from(s).length(), s.len() as u32);
}
test("Mozilla");
test("");
}
#[wasm_bindgen_test]
fn char_at() {
let s = JsString::from("Brave new world");
... |
pub fn square_of_sum(n: i64) -> i64 {
let sum = (1..(n+1)).fold(0, |acc, x| acc + x);
sum * sum
}
pub fn sum_of_squares(n: i64) -> i64 {
(1..(n+1)).map(|x| x * x).fold(0, |acc, x| acc + x)
}
pub fn difference(n: i64) -> i64 {
square_of_sum(n) - sum_of_squares(n)
}
|
use itertools::Itertools;
use std::cmp;
use std::fmt;
use std::path::Display;
#[derive(Debug, Clone, Copy, PartialEq)]
struct Vec2 {
x: i64,
y: i64,
}
#[derive(Copy, Clone, PartialEq, Debug)]
enum State {
Floor,
Empty,
Occupied,
}
#[derive(Clone, Copy, PartialEq)]
struct Tile {
prev_state: Sta... |
// 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... |
const CRC_TABLE: [u16; 16] = [
0x0000, 0xCC01, 0xD801, 0x1400, 0xF001, 0x3C00, 0x2800, 0xE401,
0xA001, 0x6C00, 0x7800, 0xB401, 0x5000, 0x9C01, 0x8801, 0x4400];
pub fn crc_16(crc: u16, byte: &u8) -> u16 {
// compute checksum of lower four bits of byte
let mut tmp = CRC_TABLE[(crc & 0x0Fu16) as usize];... |
use crate::proto::helloworld::{HelloReply, HelloRequest};
use crate::proto::helloworld_grpc::{Greeter, GreeterServer};
use grpc;
pub struct GreeterService;
impl Greeter for GreeterService {
fn say_hello(
&self,
_: grpc::RequestOptions,
req: HelloRequest,
) -> grpc::SingleResponse<Hello... |
mod btree;
use btree::Btree;
fn main() {
let tfp = "chicchai.db";
let wal = "chicchai.log";
let mut btree = match Btree::<String, String>::new(&tfp.to_string(), &wal.to_string(), 100, 100)
{
Ok(v) => v,
Err(e) => {
println!("err {}", e.description());
return;
... |
use std::str::from_utf8;
use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
use crate::decode::Decode;
use crate::encode::Encode;
use crate::mysql::protocol::TypeId;
use crate::mysql::type_info::MySqlTypeInfo;
use crate::mysql::{MySql, MySqlData, MySqlValue};
use crate::types::Type;
use crate::Error;
impl T... |
use proc_macro2::TokenStream as TokenStream2;
use proc_macro2::{Ident, Span};
use proc_macro_error::{abort, ResultExt};
use syn::{self, ext::IdentExt, spanned::Spanned, Field, Lit, Meta, MetaNameValue, Visibility};
use self::GenMode::*;
use super::parse_attr;
pub struct GenParams {
pub mode: GenMode,
pub glob... |
/*
Copyright (c) 2015, 2016 Saurav Sachidanand
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, di... |
// 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.
#![warn(missing_docs)]
//! `timekeeper` is responsible for external time synchronization in Fuchsia.
mod diagnostics;
mod network;
mod rtc;
use {
cr... |
// 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.
//! AccountManager manages the overall state of Fuchsia accounts and personae on
//! a Fuchsia device, installation of the AuthProviders that are used to o... |
// This file is Copyright its original authors, visible in version control
// history.
//
// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
// or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
// You may... |
use std::convert::TryInto;
use std::io;
fn main() {
let mut buf = String::new();
let stdin = io::stdin();
stdin
.read_line(&mut buf)
.expect("Failed to read first line.");
buf.clear();
stdin
.read_line(&mut buf)
.expect("Failed to read paper list.");
let mut pape... |
//! Human-readable logging and statuses.
// TODO: Sort the tags while converting `&[&TagParam]` to `Vec<Tag>`.
use chrono::{Local, TimeZone, Utc};
use chrono::format::DelayedFormat;
use chrono::format::strftime::StrftimeItems;
use crossbeam::queue::SegQueue;
use serde_json::{Value as Json};
use std::cell::RefCell;
us... |
mod task;
use sea_orm::*;
use std::env;
use task::Entity as Task;
type Error = Box<dyn std::error::Error>;
#[async_std::main]
async fn main() -> Result<(), Error> {
let db_url = env::var("DB_URL")?;
let db = Database::connect(db_url).await?;
let rows = Task::find().all(&db).await?;
println!("{:?... |
// Creates a basic neuron with 3 inputs.
// Associated YT NNFS tutorial: https://www.youtube.com/watch?v=Wo5dMEP_BbI
fn main() {
let inputs = vec![1.0, 2.0, 3.0];
let weights = vec![3.1, 2.1, 8.7];
let bias = 3.0;
let output = inputs[0] * weights[0] +
inputs[1] * weights[1] +
... |
mod separable_sss; pub use separable_sss::*;
mod ssss_utils; pub use ssss_utils::*;
|
use audio_core::ReadBuf;
use audio_core::Translate as _;
use audio_device::alsa;
use audio_generator::{self as gen, Generator as _};
fn generate_audio() -> anyhow::Result<()> {
let mut pcm = alsa::Pcm::open_default(alsa::Stream::Playback)?;
let config = pcm.configure::<i16>().install()?;
let mut writer = ... |
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
pub mod flight_provider;
pub mod flight_provider_request;
mod raw_models; |
use super::*;
use nix::{ioctl_none, ioctl_readwrite, ioctl_write_ptr};
pub type nvme_admin_cmd = nvme_passthru_cmd;
// #define NVME_IOCTL_ID _IO('N', 0x40)
// #define NVME_IOCTL_ADMIN_CMD _IOWR('N', 0x41, struct nvme_admin_cmd)
// #define NVME_IOCTL_SUBMIT_IO _IOW('N', 0x42, struct nvme_user_io)
// #define NVME_IOCT... |
use crate::chunked::ChunkedDecoder;
use async_dup::{Arc, Mutex};
use async_std::io::{BufReader, Read, Take};
use async_std::task::{Context, Poll};
use std::{fmt::Debug, io, pin::Pin};
pub enum BodyReader<IO: Read + Unpin> {
Chunked(Arc<Mutex<ChunkedDecoder<BufReader<IO>>>>),
Fixed(Arc<Mutex<Take<BufReader<IO>>... |
//! This module provides unified diff functionality.
//!
//! It is available for as long as the `text` feature is enabled which
//! is enabled by default:
//!
//! ```rust
//! use similar::TextDiff;
//! # let old_text = "";
//! # let new_text = "";
//! let text_diff = TextDiff::from_lines(old_text, new_text);
//! print!... |
use rlua::{Lua};
use scripting::{ScriptTable};
use {Error};
/// Keeps track of the scripting engine and data in it.
pub struct ScriptRuntime {
lua: Lua,
}
impl ScriptRuntime {
/// Creates a new runtime.
pub fn new() -> Self {
let lua = Lua::new();
ScriptRuntime {
lua,
... |
use aoc2018::*;
use std::str;
fn main() -> Result<(), Error> {
// only read once so we can use references into it to avoid copying the string.
let lines = lines!(input!("day3.txt"), String, Skip, Pair<u32, u32>, Pair<u32, u32>)
.collect::<Result<Vec<_>, Error>>()?;
let mut duplicates = 0;
// ... |
fn main() {
//if else statement
let number = 3;
if number < 5 {
println!("condition was true");
} else {
println!("condition was false");
}
// if else if
let anothernumber = 6;
if anothernumber % 4 == 0 {
println!("number is divisible by 4");
} else if anoth... |
use serde::{Deserialize, Serialize};
use std::convert::TryInto;
lazy_static! {
static ref REQUEST_HEADER_SIZE: u64 = bincode::serialized_size(&RequestHeader::default())
.expect("Unable to get size of default RequestHeader.");
}
/// All possible algorithms that can be requested.
#[allow(non_camel_case_type... |
pub mod v0;
pub mod v1;
pub struct AsciiDots;
impl AsciiDots {
pub const DOTS: &'static str = "..";
pub const CHAR_LEN: usize = 2;
}
pub struct UnicodeDots;
impl UnicodeDots {
pub const DOTS: char = '…';
pub const CHAR_LEN: usize = 1;
}
|
pub mod survey_dto;
pub use survey_dto::*; |
//! Some well-known cryptographic algorithms, broken down into their primitive components for
//! analysis.
|
// 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 crate::{
hardware::Hardware,
twin::{self, resolve_relation},
twins::{
drone_twin::{
states::{DroneTwinState, LaunchedState, ReadyState},
DroneTwin,
},
launchpad_twin::{LaunchpadTwin, LaunchpadTwinState},
mission_twin::{MissionTwin, MissionTwinState... |
use std::fs;
use std::collections::HashMap;
fn binary_space (instructions: &str, max: &u32) -> u32 {
let mut low = 0;
let mut current = max / 2;
for code in instructions.chars() {
if code == 'B' || code == 'R' {
low += current;
}
current = current / 2
}
return lo... |
// Copyright 2021 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to ... |
mod kv;
use kv::KVStore;
fn main() {
let store = KVStore {host: String::from("http://127.0.0.1:8500")};
println!("{:#?}", store.get(String::from("foo/bar/bar")));
println!("{}", store.put(String::from("foo/bar/bar"), String::from("foo")))
} |
// SPDX-License-Identifier: MIT
// Copyright (c) 2021-2022 brainpower <brainpower at mailbox dot org>
use crate::Opt;
impl<'a> std::fmt::Debug for Opt<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"Opt {{\n sopt: {:?},\n lopt: {:?},\n help: {:?},\n value: {... |
// Copyright 2020-2021, The Tremor Team
//
// 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 agr... |
mod puzzle;
use crate::puzzle::Puzzle;
use crate::puzzle::puzzle1;
fn main() {
solve_puzzle(&puzzle1::Puzzle1 {});
}
fn solve_puzzle<T>(puzzle: &dyn Puzzle<T>){
let input = include_str!("puzzle1.txt");
let parsed_input = puzzle.parse_input(input);
let result1 = puzzle.part1(&parsed_input);
prin... |
#[allow(unused_imports)]
use proconio::{
input, fastout
};
fn solve(d: f32, t: f32, s: f32) -> String {
let ans: String;
let time = d / s;
if time > t {
ans = "No".to_string();
} else {
ans = "Yes".to_string();
}
ans
}
fn run() -> Result<(), Box<dyn std::error::Error>> {
... |
/*
https://leetcode.com/problems/triangle/
*/
use std::cmp;
struct Solution;
impl Solution {
pub fn minimum_total(triangle: Vec<Vec<i32>>) -> i32 {
let rows = triangle.len();
let mut dp = vec![vec![]; rows];
dp[0].push(triangle[0][0]);
let mut minimum = dp[0][0];
for ... |
use rskafka_proto::{ApiKey, ErrorCode};
use rskafka_wire_format::error::ParseError;
use std::borrow::Cow;
use thiserror::Error;
#[derive(Debug, Error)]
#[error("kafka client error")]
pub enum Error {
#[error("missing {0} in config")]
IncompleteConfig(&'static str),
#[error("io error")]
Io(#[from] std:... |
//! https://github.com/lumen/otp/tree/lumen/lib/megaco/src/flex
use super::*;
test_compiles_lumen_otp!(megaco_flex_scanner);
fn relative_directory_path() -> PathBuf {
super::relative_directory_path().join("flex")
}
|
pub use crate::models::{Transaction, Wallet, WatchWallet, RestoreWallet, ListWallet, Backup};
use crate::usages::{
USAGE, USAGE_TRANSACTION, USAGE_BALANCE, USAGE_LISTWALLET,
USAGE_WATCHADDRESS, USAGE_RESTOREWALLET, USAGE_BACKUP, USAGE_GETWALLET
};
#[derive(Debug, Eq, PartialEq)]
pub enum Cmd {
Transaction(... |
use super::*;
#[test]
fn sends_message_when_timer_expires() {
run!(
|arc_process| {
(
Just(arc_process.clone()),
milliseconds(),
strategy::term(arc_process.clone()),
)
},
|(arc_process, milliseconds, message)| {
... |
use anyhow::anyhow;
use std::sync::Arc;
use std::thread;
fn main() -> anyhow::Result<()> {
for _ in 0..100 {
let thread = Arc::new(ste::spawn());
let mut threads = Vec::new();
for _ in 0..2 {
let thread = thread.clone();
let t = thread::spawn(move || {
... |
use crate::librb::socklen_t;
use libc;
use libc::sockaddr;
use libc::sockaddr_in;
use libc::sockaddr_in6;
extern "C" {
pub type sockaddr_x25;
pub type sockaddr_un;
pub type sockaddr_ns;
pub type sockaddr_iso;
pub type sockaddr_ipx;
pub type sockaddr_inarp;
pub type sockaddr_eon;
pub type sockaddr_dl;
... |
use super::*;
// `returns_binary` in integration tests
// `is_the_same_as_float_to_binary_2_with_scientific_20` in integration tests
#[test]
fn is_dual_of_binary_to_float_1() {
with_process_arc(|arc_process| {
TestRunner::new(Config::with_source_file(file!()))
.run(&strategy::term::float(arc_p... |
pub fn add(x: i32, y: i32) -> i32 {
x + y
}
#[ test ]
fn test_add() {
assert_eq!(0, add(0, 0));
assert_ne!(0, add(0, 1));
} |
use std::fmt;
use std::error::Error;
use value::Value;
use value::Value::*;
use self::FilterError::*;
#[derive(Debug)]
pub enum FilterError {
InvalidType(String),
InvalidArgumentCount(String),
InvalidArgument(u16, String), // (position, "expected / given ")
}
impl FilterError {
pub fn invalid_type<T... |
#![cfg(target_arch = "x86_64")]
use std::arch::x86_64::*;
use crate::detail::sandwich::{sw012, sw_mm_three, sw_mm_two};
use crate::detail::sse::{dp_bc, hi_dp_bc, rcp_nr1, rsqrt_nr1};
use crate::util::ApplyTo;
use crate::{Branch, Line, Plane, Point};
#[derive(Default)]
pub struct EulerAngles {
pub roll: f32,
... |
/// Custom string implemenation.
///
/// There is a lot of unsafe code here. Many of the features here can and were implementable in
/// terms of safe code using enums, and various components of the standard library. We moved to
/// this representation because it significanly improved some benchmarks in terms of time a... |
mod architecture;
/// File-related utilities.
///
/// Most utilities defined in this module are higher-level abstractions over `std::fs`, but common
/// operations nonetheless.
pub mod file;
pub mod notify;
mod platform;
pub use architecture::Architecture;
pub use platform::Platform;
|
pub struct Solution;
impl Solution {
pub fn set_zeroes(matrix: &mut Vec<Vec<i32>>) {
let m = matrix.len();
if m == 0 {
return;
}
let n = matrix[0].len();
if n == 0 {
return;
}
let mut zero_row = vec![false; m];
let mut zero_col... |
fn main() {
let input = include_str!("day12.txt");
let split = input.split("\n");
let v: Vec<&str> = split.collect();
let mut x = 0;
let mut y = 0;
let mut direction = "e";
for thing in v {
if thing.chars().nth(0).unwrap() == 'N' {
let removedfirst = thing.chars().next(... |
use std::collections::HashSet;
use proconio::input;
fn main() {
input! {
n: u8,
m: usize,
a: [[u8]; m],
};
let mut ans = 0;
for bits in 0..(1 << m) {
let mut b = HashSet::new();
for i in 0..m {
if bits >> i & 1 == 1 {
for &y in &... |
use std::ops::{Sub, Add, AddAssign, Neg};
use std::cmp::{PartialOrd, Ord, Ordering};
use std::mem;
use std::f32;
use std::slice;
use vector::Vector3;
/// A point in 3D space.
///
/// Points are represented as cartesian coordinates with an `x`, `y`, and `z` position, as well as
/// a `w` homogeneous coordinate for the... |
use game::*;
#[test]
/// Test the index fn
fn first_last_test() {
#![allow(unused_variables)]
let deck = Deck::new();
let first = deck[0];
let last = deck[51];
let f_tup = first.to_string_pair();
let l_tup = last.to_string_pair();
assert!(f_tup.0 == "Ace" && f_tup.1 == "Diamond");
asser... |
// Copyright 2021 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 scanner_proc_macro::insert_scanner;
#[insert_scanner]
fn main() {
let x = scan!(i64);
let ans = if x >= 0 {
x / 10
} else if x % 10 == 0 {
x / 10
} else {
x / 10 - 1
};
println!("{}", ans);
}
|
use crate::{stark_hash, Felt};
/// HashChain is the structure used over at cairo side to represent the hash construction needed
/// for computing the class hash.
///
/// Empty hash chained value equals `H(0, 0)` where `H` is the [`stark_hash()`] function, and the
/// second value is the number of values hashed togethe... |
extern crate flate2;
extern crate tar;
use flate2::read::GzDecoder;
use flate2::write::GzEncoder;
use flate2::Compression;
use std::fs::File;
use std::path::Path;
use tar::Archive;
pub fn decompress_tgz(tar_path: &Path, output_dir: &Path) -> Result<(), std::io::Error> {
// let path = "archive.tar.gz";
//
let t... |
#[doc = "Reader of register CLKCR"]
pub type R = crate::R<u32, super::CLKCR>;
#[doc = "Writer for register CLKCR"]
pub type W = crate::W<u32, super::CLKCR>;
#[doc = "Register CLKCR `reset()`'s with value 0"]
impl crate::ResetValue for super::CLKCR {
type Type = u32;
#[inline(always)]
fn reset_value() -> Sel... |
use std::fs::File;
use std::io::prelude::*;
use std::collections::HashMap;
pub fn lines_from_file(filename: &str) -> Vec<String> {
let mut file = match File::open(filename) {
Ok(file) => file,
Err(_) => panic!("no such file"),
};
let mut file_contents = String::new();
file.read_to_strin... |
use ggez::event;
use block::Block;
use color::Color;
use coord::Coord;
use ggez::Context;
use ggez::graphics;
use square::Square;
use consts::SCORE_LINE;
use ggez::graphics::Font;
use consts::{WINDOW_HEIGHT, WINDOW_WIDTH};
use consts::{GAME_FIELD_POS_X, GAME_FIELD_POS_Y};
use consts::{GAME_FIELD_HEIGHT, GAME_FIELD_WIDT... |
extern crate native_windows_derive as nwd;
extern crate native_windows_gui as nwg;
use std::cell::RefCell;
use std::rc::Rc;
use nwg::NativeUi;
use nwd::NwgUi;
use nwg::stretch::{geometry::{Size, Rect},style::{Dimension, FlexDirection, JustifyContent, Style},};
const PT_10: Dimension = Dimension::Points(10.0);
const... |
use instant_segment::{Search, Segmenter};
use std::collections::HashMap;
fn main() {
let mut unigrams = HashMap::default();
unigrams.insert("choose".into(), 80_000.0);
unigrams.insert("chooses".into(), 7_000.0);
unigrams.insert("spain".into(), 20_000.0);
unigrams.insert("pain".into(), 90_000.0);
... |
#![crate_name = "cabocha"]
#![crate_type = "lib"]
#![crate_type = "dylib"]
#![crate_type = "rlib"]
mod chunk;
pub mod consts;
pub mod parser;
mod sys;
mod token;
mod tree;
mod utils;
|
rustler::atoms! {
ok,
error,
}
|
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.