text stringlengths 8 4.13M |
|---|
use crate::vector::Vec3d;
use crate::ray::Ray;
#[derive(Clone, Debug)]
pub struct AABB
{
pub p_min: Vec3d,
pub p_max: Vec3d,
}
impl AABB
{
pub fn single(p: Vec3d) -> AABB
{
AABB{ p_min: p, p_max:p }
}
pub fn new(p1: Vec3d, p2: Vec3d) -> AABB
{
let p_min = Vec3d::comp_min(p1... |
use anyhow::Error;
use futures::future::join_all;
use itertools::Itertools;
use log::debug;
use stack_string::StackString;
use std::{
collections::HashMap,
ffi::OsStr,
fmt::Write,
path::{Path, PathBuf},
};
use stdout_channel::StdoutChannel;
use tokio::{
fs,
task::{spawn, spawn_blocking},
};
use ... |
use bitvec::prelude::{BitSlice, Lsb0};
use ndarray::{Array1, Array2};
use std::convert::TryFrom;
use std::io::Result;
#[derive(Clone, serde::Serialize, serde::Deserialize)]
pub struct Block {
pub indmap: Array1<u16>,
pub nvar: usize,
pub nuniq: usize,
pub clustsize: Array1<u16>,
pub rhap: Array2<u8... |
/**
* [371] Sum of Two Integers
*
* Given two integers a and b, return the sum of the two integers without using the operators + and -.
Example 1:
Input: a = 1, b = 2
Output: 3
Example 2:
Input: a = 2, b = 3
Output: 5
Constraints:
-1000 <= a, b <= 1000
*/
pub struct Solution {}
// submission codes start her... |
use std::ffi::OsStr;
use std::io::copy;
use std::io::Read;
use std::os::unix::ffi::OsStrExt;
use std::path::Path;
use ex::fs::File;
use ex::io;
use flate2::read::GzDecoder;
use lzma::LzmaReader;
use snafu::OptionExt;
use snafu::ResultExt;
use snafu::Snafu;
/// URL for Ubuntu glibc packages
pub static PKG_URL: &str = ... |
use serde::{Deserialize, Serialize};
pub mod get_service_health {
use super::*;
#[derive(Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct APIResponse {
pub message: String,
}
}
|
use immense::*;
use rand::*;
use std::fs::File;
#[derive(Debug)]
struct RandCube;
impl ToRule for RandCube {
fn to_rule(&self) -> Rule {
rule![
*thread_rng()
.choose(&[Tf::tx(0.1), Tf::tx(-0.1), Tf::tx(0.2), Tf::tx(-0.2)])
.unwrap() =>
c... |
use url::Url;
use std::ops::Add;
use std::rc::Rc;
use std::cell::RefCell;
mod listen_notes;
use listen_notes::{Podcast, Episode};
fn parse_url(url: &str) -> Option<Url> {
match Url::parse(url) {
Err(_) => None,
Ok(parsed_url) => Some(parsed_url),
}
}
fn main() {
let star_wars_7x7 = Rc::... |
pub struct Solution {}
impl Solution {
pub fn min_path_sum(grid: Vec<Vec<i32>>) -> i32 {
let mut dp = vec![0; grid[0].len()];
for (i, line) in grid.iter().enumerate() {
for (j, cost) in line.iter().enumerate() {
let mut val = std::i32::MAX;
val = val.min(... |
use std::cmp::Ordering::{Equal, Greater, Less};
use Classification::{Abundant, Deficient, Perfect};
#[derive(Debug, PartialEq, Eq)]
pub enum Classification {
Abundant,
Deficient,
Perfect,
}
pub fn classify(n: u64) -> Option<Classification> {
if n == 0 {
return None;
}
match aliquot_su... |
pub mod system_status {
use serde::{Deserialize, Serialize};
#[derive(Debug, Deserialize, Serialize, Clone, Copy)]
#[serde(rename_all = "camelCase")]
enum SystemStatusEvent {
SystemStatus,
}
#[derive(Debug, Deserialize, Serialize, PartialEq, Clone)]
#[serde(rename_all = "lowercase"... |
pub mod pass;
|
#[doc = "Register `RCCUTOFF` reader"]
pub struct R(crate::R<RCCUTOFF_SPEC>);
impl core::ops::Deref for R {
type Target = crate::R<RCCUTOFF_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<crate::R<RCCUTOFF_SPEC>> for R {
#[inline(always)]
fn from(reader: ... |
use std::io::{stdin, prelude::*};
use std::str::FromStr;
type Int = i128; // Need at least 96 bits, or else multiplication tricks.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Deal {
Rev,
Cut(Int),
Inc(Int),
}
impl Deal {
#[allow(dead_code)]
fn follow_card(self, size: Int, card: Int) -> Int ... |
pub static SETUP_STAGE: &str = "heltram_setup";
|
use crate::bucket_strainer::{Bucket, Rule};
use crate::Scalar;
/// Bucket rule that always gives specified score.
#[derive(Clone)]
pub struct FixedScoreRule {
/// Score value.
pub score: Scalar,
}
impl FixedScoreRule {
pub fn new(score: Scalar) -> Self {
Self { score }
}
}
impl<T> Rule<T> for... |
use sdl2::{
rect::Rect,
render::{Texture, WindowCanvas},
};
use crate::{
gr_type::grtype::{self, *},
input_type::inputtype::{self, *},
pcrlib_c::joyinfo_t,
scan_codes::{SDL_Scancode, SDL_SCANCODE_UNKNOWN},
scores::scores,
};
// Globals previously belonging to pcrlib_c.rs.
//
#[rustfmt::ski... |
#[cfg(test)]
mod tests {
use unicode_normalization::*;
use wasm_bindgen_test::*;
wasm_bindgen_test_configure!(run_in_browser);
#[wasm_bindgen_test]
fn run() {
for x in "test".nfc() {}
}
}
|
use actix::spawn as actix_spawn;
use actix_web::{test::block_fn, App, HttpServer};
use futures::{stream::Stream, Future};
use postgres_rest_actix::Config;
use std::{fs::read_to_string, thread::spawn as thread_spawn};
use tokio_postgres::{connect, NoTls};
pub fn setup_db(db_url: &'static str) {
let setup_sql_file_p... |
struct Solution;
#[allow(dead_code)]
impl Solution {
pub fn find_number_in2_d_array(matrix: Vec<Vec<i32>>, target: i32) -> bool {
for i in &matrix[..] {
if i.is_empty() {
return false;
} else if i[0] == target {
return true;
} else if i[0]... |
use super::*;
use crate::bb;
macro_rules! bus {
($($PER:ident => ($apbX:ty, $bit:literal),)+) => {
$(
impl crate::Sealed for crate::pac::$PER {}
impl RccBus for crate::pac::$PER {
type Bus = $apbX;
}
impl Enable for crate::pac::$PER {
... |
use std::env;
use app::goertzel::goertzel;
use std::io::{self,BufRead};
fn main() {
let args: Vec<String> = env::args().collect();
if args.len() != 3 {
println!("Usage: {} N K", args[0]);
std::process::exit(-1);
}
let n = args[1].parse::<usize>().unwrap();
let k = args[2].parse::<u32>().unwrap();... |
use std::collections::HashMap;
use base64;
use failure::format_err;
use log::{debug, info};
use regex::Regex;
use serde_json;
use serde_json::json;
use serde_derive::{Deserialize, Serialize};
use url::percent_encoding::{DEFAULT_ENCODE_SET, utf8_percent_encode};
use crate::config::JiraConfig;
use crate::errors::*;
use... |
extern crate proc_macro;
use quote::quote;
use proc_macro2::{Span, TokenStream};
use syn::{parse_macro_input, DeriveInput, Ident};
struct Idents {
item: Ident,
collection: Ident,
derives: Option<Vec<Ident>>,
}
impl Idents {
fn new(input: &DeriveInput) -> Result<Idents, String> {
let collecti... |
use std::collections::HashSet;
use crate::rule::{ Rule, Symbol };
use crate::lexer::Lexer;
use crate::util;
pub fn non_empty_list<'a>(args: &'a Vec<Symbol<'a>>) -> Rule<'a> {
Rule {
name: "non_empty_list",
choices: vec![
("one", vec![args[0].clone()]),
("more", vec![args[0]... |
extern crate binjs;
extern crate itertools;
use binjs::generic::{IdentifierName, InterfaceName, Offset, PropertyKey, SharedString};
use binjs::io::entropy;
use binjs::io::entropy::dictionary::{
DictionaryBuilder, FilesContaining, LinearTable, Options as DictionaryOptions,
};
use binjs::io::entropy::rw::TableRefStr... |
mod dimension;
mod error;
mod every;
mod ordinal;
mod schedule;
mod time;
mod utils;
mod weekday;
|
use serde::{Serialize, Deserialize};
use ate_auth::prelude::*;
#[derive(Debug, Serialize, Deserialize, Clone)]
struct MyData
{
pi: String,
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>>
{
ate::log_init(0, false);
let dio = DioBuilder::default()
.with_session_prompt().a... |
use super::rational::*;
use std::result::Result;
/// Top-level structure that contains all parsed metadata inside an image
#[derive(Debug)]
pub struct ExifData {
/// MIME type of the parsed image. It may be "image/jpeg", "image/tiff", or empty if unrecognized.
pub mime: String,
/// Collection of EXIF entries found ... |
/*
* Copyright 2018-2019 TON DEV SOLUTIONS LTD.
*
* Licensed under the SOFTWARE EVALUATION License (the "License"); you may not use
* this file except in compliance with the License. You may obtain a copy of the
* License at: https://ton.dev/licenses
*
* Unless required by applicable law or agreed to in writing... |
extern crate serde_json;
use utils::postgres_utils::*;
use utils::redis_utils::{RedisConnection, Cacheable, RedisError, REDIS_DEFAULT_EXPIRE_TIME};
use self::serde_json::json;
use utils::redis_utils::redis::Commands;
use std::collections::HashMap;
use std::fmt;
#[derive(Debug, Deserialize, Serialize, Clone)]... |
use core::any::type_name;
use shipyard::error;
use shipyard::*;
#[test]
fn no_pack() {
let world = World::new();
let (mut entities, mut usizes, mut u32s) =
world.borrow::<(EntitiesViewMut, ViewMut<usize>, ViewMut<u32>)>();
let entity1 = entities.add_entity((&mut usizes, &mut u32s), (0usize, 1u32))... |
// Ref: https://leetcode.com/problems/lru-cache/discuss/381773/Rust-safe-linked-list-%2B-hashmap-in-28ms
use std::cell::RefCell;
use std::collections::HashMap;
use std::rc::{Rc, Weak};
type NodeRef = Rc<RefCell<Node>>;
type WeakNodeRef = Weak<RefCell<Node>>;
type Link = Option<NodeRef>;
#[derive(Clone)]
struct Eleme... |
mod list;
mod new;
mod parse_code;
mod run_ngrok;
use crate::list::{list_404, list_500};
use crate::run_ngrok::run_ngrok;
use structopt::StructOpt;
#[derive(StructOpt)]
#[structopt(bin_name = "cargo")]
enum CommandLine {
Ngrok(Ngrok),
}
#[derive(StructOpt)]
/// Use ngrok traces to drive your development process.... |
// smart contract source code, written in Rust
// for more info: https://docs.near.org/docs/roles/developer/contracts/near-sdk-rs
use borsh::{BorshDeserialize, BorshSerialize};
use near_sdk::{env, near_bindgen};
use std::collections::HashMap;
#[global_allocator]
static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc... |
// Copyright (c) IxMilia. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
use std::borrow::Cow;
use std::fmt;
use std::fmt::{
Debug,
Formatter,
};
use ::{
DxfError,
DxfResult,
};
/// Contains the data portion of a `C... |
//! 对于静态语言项目,用户指定的文件服务器上存放的文件命名,规则如下:
//! - 主文件格式:<40位git版本号>.tar.xz
//! - 签名文件格式:<40位git版本号>.sig
//!
//! 其中,
//! - 主文件是所有待布署文件的打包
//! - 签名文件是一个文本文件,存放主文件的SHA1哈希值
#[cfg(test)]
mod test {}
|
#![allow(unused_imports)]
use std::mem::swap;
use num::integer::sqrt;
use proconio::{fastout, input, marker::*};
#[fastout]
fn main() {
input! {
mut n: isize,
mut m: isize,
k: isize
};
if m < n {
swap(&mut n, &mut m);
}
for x in 0..=m {
let t1 = n * x - k... |
use std::io::Cursor;
use criterion::{criterion_group, criterion_main, Criterion};
use symbolic_common::ByteView;
use symbolic_debuginfo::Object;
use symbolic_symcache::SymCacheWriter;
use symbolic_testutils::fixture;
fn bench_write_linux(c: &mut Criterion) {
c.bench_function("write_linux", |b| {
let buff... |
#[doc = "Register `CTIAPPCLEAR` writer"]
pub struct W(crate::W<CTIAPPCLEAR_SPEC>);
impl core::ops::Deref for W {
type Target = crate::W<CTIAPPCLEAR_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl core::ops::DerefMut for W {
#[inline(always)]
fn deref_mut(&mut... |
use crate::{trim_f64, Distance, Speed};
use histogram::Histogram;
use serde_derive::{Deserialize, Serialize};
use std::{cmp, f64, ops};
// In seconds. Can be negative.
// TODO Naming is awkward. Can represent a moment in time or a duration.
#[derive(Clone, Copy, Debug, PartialEq, PartialOrd, Serialize, Deserialize)]
p... |
use crate::RUST_VERSION;
use maud::{self, html, PreEscaped};
pub fn search_form(
action: &str,
placeholder: &str,
value: &str,
regex: bool,
) -> PreEscaped<String> {
html! {
form action=(action) {
div class="row" {
div class="col-md-12" style="margin-top: 20pt" {... |
use crate::hit::Hit;
use crate::hit::HitResult;
use crate::hittables::aabb::AABB;
use crate::math::quat::Quaternion;
use crate::math::vec3::Vec3;
use crate::ray::Ray;
use std::sync::Arc;
// first scale
// then rotate
// lastly translate
#[derive(Clone)]
pub struct Transform {
object: Arc<dyn Hit>,
pub positio... |
use minmaxheap::Heap;
fn main() {
let mut heap = Heap::new("max", 10).expect("Something did not work");
heap.add(20);
heap.add(10);
heap.add(5);
heap.add(100);
heap.add(2);
heap.add(40);
heap.add(40);
println!("{}", heap);
heap.invert();
println!("{}", heap);
}
|
use bytes::Bytes;
use futures::future::Future;
use http::StatusCode;
pub mod redis_ethereum_ledger;
pub mod redis_store_common;
#[cfg(test)]
pub mod test_helpers;
pub type IdempotentEngineData = (StatusCode, Bytes, [u8; 32]);
pub trait IdempotentEngineStore {
/// Returns the API response that was saved when the... |
//! If an extern token is provided, then this pass validates that
//! terminal IDs have conversions. Otherwise, it generates a
//! tokenizer. This can only be done after macro expansion because
//! some macro arguments never make it into an actual production and
//! are only used in `if` conditions; we use string liter... |
use std::collections::HashMap;
#[aoc_generator(day10)]
fn input_generator(input: &str) -> Vec<u64> {
input.lines().map(|x| x.parse::<u64>().unwrap()).collect()
}
fn use_all_adapters(input: &[u64]) -> (u32, u32, u32) {
let goal = input.iter().max().unwrap() + 3;
let mut input = input.to_vec();
input.pu... |
use clap::{crate_version, App, Arg, SubCommand};
pub mod bake;
pub mod command;
pub mod pack;
pub mod error;
use crate::bake::bake;
use crate::pack::pack;
use crate::error::PipelineError;
fn main() -> Result<(), PipelineError> {
let app = App::new("ROSE Next Pipeline Tool")
.version(crate_version!())
... |
use std::collections::HashMap;
mod lexicon;
mod segment;
mod jpn;
fn main() {
let lexemes = HashMap::new();
let x = lexicon::Lexicon { lexemes };
}
|
use crate::core::pbrt::{Float, consts::PI};
use crate::core::geometry::{Vector3f, Point2f, spherical_direction};
use super::MicrofacetDistribution;
use crate::core::reflection::*;
use std::fmt;
#[derive(Debug, Default, Clone, Copy)]
pub struct TrowbridgeReitzDistribution {
alphax: Float,
alphay: Float,
//... |
// Copyright 2015-2019 Parity Technologies (UK) Ltd.
// This file is part of Parity Ethereum.
// Parity Ethereum is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at yo... |
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - Control register"]
pub ctl0: CTL0,
#[doc = "0x04 - Clock configuration register 0 (RCU_CFG0)"]
pub cfg0: CFG0,
#[doc = "0x08 - Clock interrupt register (RCU_INT)"]
pub int: INT,
#[doc = "0x0c - APB2 reset regist... |
use core::sync::atomic::{AtomicUsize, Ordering};
use core::cell::UnsafeCell;
use core::ops::{Deref, DerefMut};
const FREE: usize = 0;
const BORROW_MUT: usize = 1;
const FROZEN: usize = 2;
pub struct FreezableRefCell<T> {
state: AtomicUsize,
value: UnsafeCell<T>,
}
unsafe impl<T: Send> Send for FreezableRefCe... |
pub fn is_prime(n: u32) -> bool {
return !(2..n - 1).any(|i| n % i == 0);
}
pub fn nth(n: u32) -> u32 {
let mut primes: Vec<u32> = vec![];
return (2..)
.filter(|candidate: &u32| {
if !primes.iter().any(|i| candidate % i == 0) {
primes.push(*candidate);
t... |
use core::{any::Any, fmt, future::Future, ops::ControlFlow, panic::Location};
use emit_core::{
ambient,
clock::Clock,
ctxt::Ctxt,
emitter::Emitter,
filter::Filter,
id::{SpanId, TraceId},
key::ToKey,
level::Level,
props::Props,
template::Template,
value::{ToValue, Value},
};
... |
struct Point
{
x: f64,
y: f64,
}
pub fn sub()
{
println!("sub");
struct_func();
}
pub fn struct_func()
{
let mut p : Point;
p = Point { x:1.0, y:2.0 };
p.x += 10 as f64;
println!("{:?}, {1}", p.x, p.y);
}
pub fn slice_func()
{
let xs: [i32; 5] = [1,2,3,4,5];
analyze_slice(&xs)... |
#[doc = "Register `CTRL` reader"]
pub struct R(crate::R<CTRL_SPEC>);
impl core::ops::Deref for R {
type Target = crate::R<CTRL_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<crate::R<CTRL_SPEC>> for R {
#[inline(always)]
fn from(reader: crate::R<CTRL_SP... |
#[cfg(feature = "futures_api")]
#[macro_use]
extern crate tracing;
use env_logger::Builder;
#[tokio::main]
async fn main() {
Builder::new().parse_default_env().init();
#[cfg(feature = "futures_api")]
general().await;
#[cfg(feature = "futures_api")]
market_data().await;
#[cfg(feature = "futures... |
use crate::backend::Statement;
use crate::lexer::*;
#[derive(Debug)]
pub struct Variable {
pub line: usize,
pub name: String,
}
#[derive(Debug)]
pub struct Assignment {
pub line: usize,
pub var: Variable,
pub string: String,
}
#[derive(Debug)]
pub struct Print {
pub line: us... |
/*
use -- import function
std -- standard library
io -- input/output
rand::Rng -- random crate
*/
use std::io;
use rand::Rng;
/*
cmp -- c++ module for comparing values
Ordering -- enum result of a comparison of two... |
extern crate rust_scheme;
use rust_scheme::interpreter::run_program;
fn main() {
//let program = "(begin (define pi 3.14159) (define r 10) (* pi (* r r)))";
//let program = "(begin (define (x y) (* y 5) (* y 10)) (x 8))";
//let program = "(/ (- (+ 1 (+ 1 1)) 5) 2)";
let program = "(begin (define (fact... |
//! Data representations of meta files.
use std::collections::{BTreeMap, HashMap};
use serde::{Deserialize, Serialize};
use crate::types::Value;
/// A metadata block, consisting of key-value pairs (aka "fields").
pub type Block = BTreeMap<String, Value>;
/// Represents a collection of metadata blocks.
/// Metadata... |
// Copyright 2016 Google Inc. All Rights Reserved.
//
// Licensed under the MIT License, <LICENSE or http://opensource.org/licenses/MIT>.
// This file may not be copied, modified, or distributed except according to those terms.
use {bincode, net2};
use errors::WireError;
use futures::{Async, Future, Poll, Stream, futu... |
extern crate num;
use num::complex::Complex;
use structopt::StructOpt;
#[derive(StructOpt, Debug)]
#[structopt(name = "newton")]
struct Opt {
#[structopt(short, long)]
polynomial: String,
#[structopt(short, long, default_value = "1.0")]
real: f64,
#[structopt(short, long, default_value = "1.0")]
... |
fn getline() -> String{
let mut __ret=String::new();
std::io::stdin().read_line(&mut __ret).ok();
return __ret;
}
fn main(){
println!("{}", getline().trim().replace("-", "").chars().count()/3);
}
|
use num_enum::{TryFromPrimitive, UnsafeFromPrimitive};
use std::collections::HashMap;
use std::convert::From;
use std::convert::TryInto;
use std::fmt::Write;
pub type Instructions = Vec<u8>;
pub type Operand = usize;
#[derive(
PartialEq, Hash, Eq, Copy, Clone, Debug, UnsafeFromPrimitive, TryFromPrimitive,
)]
#[re... |
/*
* @lc app=leetcode id=106 lang=rust
*
* [106] Construct Binary Tree from Inorder and Postorder Traversal
*
* https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/description/
*
* algorithms
* Medium (42.78%)
* Likes: 1236
* Dislikes: 26
* Total Accepted: 188.9K
*... |
/// Module that contains most of the functions exported to C.
use std::{slice, ptr};
use std::marker::PhantomData;
pub use tinfl::{tinfl_decompress, tinfl_decompress_mem_to_heap,
tinfl_decompress_mem_to_mem, tinfl_decompressor};
pub use tdef::{tdefl_compress, tdefl_compress_buffer, tdefl_compress_mem... |
#![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)]
pub type c<a> = a;
|
use std::str::FromStr;
use crate::types::{
AddAccountPayload, GenerateMultiSigAccountPayload, GetMultiSigAccountPayload,
MultiSigPermission, RemoveAccountPayload, SetAccountWeightPayload, SetThresholdPayload,
UpdateAccountPayload,
};
use super::*;
#[test]
fn test_generate_multi_signature() {
let cycl... |
use zmq;
use std::sync::{Arc, Mutex};
use std::cell::RefCell;
use std::collections::HashMap;
use serde_json;
use raw_message::RawMessage;
pub struct Shell {
transport: String,
key: String,
addr: String,
port: u32,
iopub_port: u32,
}
#[derive(Debug, PartialEq, Serialize)]
pub struct KernelInfoReply {
pr... |
/*!
Bitstream handles the writing and reading of bits in an optimized manner. bits are read in reverse order.
Some bit hacks are appplied here, it can be helpful to understand these
Bit Operations:
number of bits >> 3 == number of bytes
*/
pub type BitContainer = usize;
pub const BIT_CONTAINER_BYTES: usize = cor... |
//! A future that can be repeated if an error occurs or not all conditions are met.
//!
//! # Why `async move` shouldn't be allowed
//!
//! Let's consider the following example:
//!
//! ```rust
//! let mut counter = 0;
//! let res = repeatable!(async move {
//! counter += 1;
//! if counter > 1 { Ready(()) } else { ... |
use clap::Parser;
use std::path::{Path, PathBuf};
use tide::{
http::{
headers::{HeaderName, HeaderValue},
mime,
},
utils::After,
Request, Response, StatusCode,
};
use wasmtime::{component::*, Config, Engine, Store};
/// Represents state stored in the tide application context.
///
/// Th... |
use amethyst::derive::SystemDesc;
use amethyst::ecs::{Join, ReadStorage, System, SystemData, WriteStorage};
use crate::components::{Velocity, Acceleration};
#[derive(SystemDesc)]
pub struct VelocityUpdateSystem;
impl<'s> System<'s> for VelocityUpdateSystem {
type SystemData = (
WriteStorage<'s, Velocity>... |
extern crate peg;
fn main() {
peg::cargo_build("src/sate.rustpeg");
}
|
use std::env;
use std::time::Instant;
use rusty_boggle::boggler;
fn main() {
let args: Vec<String> = env::args().collect();
if args.len() != 2 {
panic!("Expected two arguments, got {}: {:?}", args.len(), args);
}
let dict_path = args.get(1).unwrap();
let mut dict = boggler::load_dictionar... |
/*!
# kiss3d
Keep It Simple, Stupid 3d graphics engine.
This library is born from the frustration in front of the fact that today’s 3D
graphics library are:
* either too low level: you have to write your own shaders and opening a
window steals you 8 hours, 300 lines of code and 10L of coffee.
* or high level but t... |
use coat::backend::winit::{AppEvent, Window};
use coat::*;
fn main() {
env_logger::init();
Window::new().title("dev: Widgets").run::<App>();
}
//========================//
// App Component //
//========================//
#[derive(Default)]
struct App;
#[derive(PartialEq, Eq)]
enum ActiveButton {
... |
use building_blocks_core::prelude::*;
use building_blocks_search::von_neumann_flood_fill3;
use building_blocks_storage::prelude::*;
use utilities::data_sets::sphere_bit_array;
use criterion::{criterion_group, criterion_main, BenchmarkId, Criterion};
fn flood_fill_sphere(c: &mut Criterion) {
let background_color ... |
fn main() {
for x in 1..101 {
let fizz = x % 3;
let buzz = x % 5;
if fizz == 0 && buzz == 0 {
println!("FizzBuzz");
continue;
}
if fizz == 0 {
println!("Fizz");
continue;
}
if buzz == 0 {
println!... |
use criterion::{criterion_group, criterion_main, BenchmarkId, Criterion};
use exercise4_1_3::{divide_and_conquer, divide_and_conquer_improved, search_all};
fn gen_random_array(n: usize) -> Vec<i64> {
use rand::Rng;
let mut arr = Vec::with_capacity(n);
let mut rng = rand::thread_rng();
for _ in 0..n {
... |
#[doc = "Register `FORCEPROTECT` reader"]
pub struct R(crate::R<FORCEPROTECT_SPEC>);
impl core::ops::Deref for R {
type Target = crate::R<FORCEPROTECT_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<crate::R<FORCEPROTECT_SPEC>> for R {
#[inline(always)]
... |
// This file is part of Substrate.
// Copyright (C) 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
//
// http://www.a... |
use crate::layout_object::TextSizeLayoutObject;
use crate::render_object::TextRenderObject;
use crate::properties::Label;
use crate::theme::Selector;
use crate::widget::{Template, Widget};
/// The `TextBlock` widget is used to draw text. It is not interactive.
///
/// # Properties
///
/// * `Label` - String used to ... |
// TODO: Remove when we use find_node,
#![allow(unused)]
use std::iter::Filter;
use std::slice::Iter;
use bip_util::bt::NodeId;
use bip_util::sha::{self, ShaHash, XorRep};
use rand;
use routing::bucket::{self, Bucket};
use routing::node::{Node, NodeStatus};
pub const MAX_BUCKETS: usize = sha::SHA_HASH_LEN * 8;
///... |
use std::io::{Cursor, BufReader, Read};
use streaming_platform::{start, Config};
fn main() {
let config_path = std::env::args().nth(1)
.expect("path to config file not passed as argument");
let file = std::fs::File::open(config_path)
.expect("failed to open config");
let mut buf... |
// Code from https://github.com/kaist-cp/cs492-concur/tree/master/lockfree
use wasm_bindgen::prelude::*;
use wasm_bindgen::prelude::*;
use core::mem::ManuallyDrop;
use core::ptr;
use core::sync::atomic::Ordering;
use core::mem::MaybeUninit;
use crossbeam_epoch::pin;
use crossbeam_epoch::{unprotected, Atomic, Guard, O... |
use crate::aggregate;
use uuid::Uuid;
pub trait DomainEvent<T: aggregate::Aggregate>: std::cmp::PartialEq + std::fmt::Debug {
fn apply(self, aggregate: &mut T);
}
#[derive(Debug, PartialEq)]
pub enum BalanceEvent {
DriverMadePayment(DriverMadePayment),
ClearanceSentToDriver(ClearanceSentToDriver),
Ri... |
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - control register 0"]
pub ctl0: CTL0,
#[doc = "0x04 - software trigger register"]
pub swt: SWT,
#[doc = "0x08 - DAC_OUT0 12-bit right-aligned data holding register"]
pub out0_r12dh: OUT0_R12DH,
#[doc = "0x0c - DA... |
use super::state::State;
use super::state_transition::StateTransition;
pub type StateDef<Entity> = Box<dyn State<Entity = Entity> + 'static>;
pub struct StateMachine<E> {
current_state: Option<StateDef<E>>,
previous_state: Option<StateDef<E>>,
global_state: Option<StateDef<E>>,
}
pub struct StateMachineB... |
#[derive(Debug)]
pub struct Algo<'a> {
vec: &'a mut Vec<isize>,
}
impl<'a> Algo<'a> {
pub fn new(vec: &'a mut Vec<isize>) -> Self {
Algo { vec: vec }
}
pub fn len(&self) -> usize {
self.vec.len()
}
pub fn is_sorted(&self) -> bool {
let mut sorted = true;
for i in... |
pub mod validator;
|
// https://leetcode.com/problems/maximum-split-of-positive-even-integers/
// You are given an integer finalSum. Split it into a sum of a maximum number of unique
// positive even integers.
// For example, given finalSum = 12, the following splits are valid (unique positive even
// integers summing up to finalSum): (12... |
use std::convert::Infallible;
use hyper::{Body, Client, Request, Response, Server};
use hyper::service::{make_service_fn, service_fn};
async fn http_get(url: &str) {
let url: hyper::Uri = url.parse().unwrap();
println!("GET {}", url);
let mut response = match Client::new().get(url).await {
Ok(resp... |
#[allow(unused_imports)]
use serde_json::Value;
#[derive(Debug, Serialize, Deserialize)]
pub struct AccessPointCreateParams {
/// Absolute file system path of access point.
#[serde(rename = "path")]
pub path: String,
}
|
extern crate clap;
extern crate dirs;
extern crate interactor;
extern crate tmux_interface;
extern crate url;
extern crate walkdir;
mod select;
mod tmux;
use clap::{App, Arg, SubCommand};
use regex::Regex;
use select::Selector;
use std::collections::HashMap;
use std::path::Path;
use std::process::{Command, Stdio};
us... |
use fun;
pub trait Forker<T: Send, R: Send> {
fn init(
&mut self,
mainFun : fun::mainFun<T, R>,
forkFun : fun::forkFun<T, R>
);
}
|
// https://github.com/rust-analyzer/text-size.git (e4d0f2b)
use cmp::Ordering;
use itertools::Itertools;
use std::{
cmp::{self, max},
convert::{TryFrom, TryInto},
fmt, iter,
num::TryFromIntError,
ops::{Add, AddAssign, Bound, Index, IndexMut, Range, RangeBounds, Sub, SubAssign},
u32,
};
#[derive... |
use std::str::FromStr;
#[derive(Debug, Clone)]
pub struct Board {
cells: Vec<bool>,
rows: usize,
columns: usize,
}
impl Board {
pub fn new(width: usize, height: usize) -> Board {
let mut cells = Vec::new();
for _ in 0..(width * height) {
cells.push(false);
}
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.