text stringlengths 8 4.13M |
|---|
use serde::de;
use serde::de::Deserializer;
use std::fmt;
use std::marker::PhantomData;
use std::path::PathBuf;
#[derive(Debug, serde::Deserialize)]
pub struct Config {
#[serde(deserialize_with = "path_or_seq_path")]
pub search_dir: Vec<PathBuf>,
}
// courtesy of https://stackoverflow.com/a/43627388
fn path_o... |
/// CloudAccountCreateParams : A cloud account object
#[allow(unused_imports)]
use serde_json::Value;
#[derive(Debug, Serialize, Deserialize)]
pub struct CloudAccountCreateParams {
/// (S3 only) The user id of the S3 account
#[serde(rename = "account_id")]
pub account_id: Option<String>,
/// The usern... |
extern crate alloc;
use thread_comm::ThreadInfo;
use typenum::Unsigned;
use self::alloc::heap::{Alloc,Heap};
use matrix::{Scalar,Mat,ResizableBuffer,RoCM};
use super::view::{MatrixView};
use composables::AlgorithmStep;
use util::capacity_to_aligned_layout;
use core::marker::PhantomData;
use core::{mem,ptr};
#[derive... |
use std::fmt;
use serde::{Deserialize, Serialize};
use uuid::Uuid;
use crate::player::PlayerInfo;
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq)]
pub enum Turn {
Pregame,
Intermission,
RedSpymasterThinking,
BlueSpymasterThinking,
RedOperativesGuessing,
BlueOperativesGuessing,... |
use super::IUserRepo;
use crate::repos::shared::query_structs::MetadataFindQuery;
use nettu_scheduler_domain::{User, ID};
use serde_json::Value;
use sqlx::{
types::{Json, Uuid},
FromRow, PgPool,
};
use tracing::error;
pub struct PostgresUserRepo {
pool: PgPool,
}
impl PostgresUserRepo {
pub fn new(poo... |
use std::{
env, fs,
io::{Read, Seek, SeekFrom},
path::{Path, PathBuf},
};
use {
byteorder::{LittleEndian, ReadBytesExt},
if_chain::*,
rayon::prelude::*,
reqwest::Url,
structopt::StructOpt,
walkdir::WalkDir,
};
use crate::error::{OtherErrors, Result};
fn try_parse_url(url: &str) ->... |
extern crate rand;
extern crate graphics;
extern crate gfx_graphics;
extern crate gfx;
extern crate gfx_device_gl;
extern crate input;
extern crate window;
extern crate glutin_window;
mod chip8;
mod utils;
use gfx::traits::*;
use gfx::memory::Typed;
use gfx::format::{DepthStencil, Formatted, Srgba8};
use input::{Butt... |
use std::marker::PhantomData;
use game::GameSituation;
pub trait SituationEvaluator
{
type Situation;
const MAX_SCORE: i32;
//Returns an evaluation of situation in the range [-MAX_SCORE, MAX_SCORE]
//From the perspective of the current player
fn evaluate_situation( situation: &Self::Situation ) ->... |
use std::cmp::min;
use std::collections::HashMap;
use std::str::FromStr;
use anyhow::{Error};
use regex::Regex;
use structopt::StructOpt;
use aoc2019::StandardOptions;
use aoc2019::io::read_data;
#[derive(Debug, Clone)]
struct RecipeItem {
units: i64,
material: String,
}
#[derive(Debug, Clone)]
struct Recip... |
use super::Expr;
#[test]
fn parse_single() {
assert_eq!(Expr::Single('a'),
"a".parse::<Expr>().unwrap());
}
#[test]
fn parse_empty() {
assert!("".parse::<Expr>().is_err());
}
#[test]
fn parse_sequence() {
assert_eq!(Expr::sequence(Expr::Single('a'),
Expr::Single('b')),
... |
/*!
In this module there're implementations & tests of `SimpleHTTP`.
*/
use std::collections::VecDeque;
use std::error::Error as StdError;
use std::future::Future;
use std::io::{self, Read, Write};
use std::pin::Pin;
use std::result::Result as StdResult;
use std::sync::{
atomic::{AtomicBool, Ordering},
Arc, Mu... |
/**
* [173] Binary Search Tree Iterator
*
* Implement the BSTIterator class that represents an iterator over the in-order traversal of a binary search tree (BST):
BSTIterator(TreeNode root) Initializes an object of the BSTIterator class. The root of the BST is given as part of the constructor. The pointer should b... |
use super::RouterStore;
use bytes::Bytes;
use futures::{future::err, Future};
use interledger_packet::{ErrorCode, RejectBuilder};
use interledger_service::*;
use std::str;
/// The router implements the IncomingService trait and uses the routing table
/// to determine the `to` (or "next hop") Account for the given requ... |
//Imports
mod utility;
use std::usize;
use utility::*;
pub mod vec3;
use vec3::*;
mod ray;
use ray::*;
mod color;
use color::*;
pub mod hittable;
use hittable::*;
use hittable::hittable_list::*;
pub mod camera;
use camera::*;
fn ray_color(ray: &Ray, world: &dyn Hittable, depth: i32) -> Color {
if depth <= 0 {... |
fn is_question(message: &str) -> bool {
message.trim().ends_with("?")
}
fn is_shouted(message: &str) -> bool {
// TODO Is it possible to do this in one pass? First check is because all() returns true on empty input.
message.chars().filter(|c| c.is_alphabetic()).count() != 0
&& message
.... |
use std::{io, mem, ops::RangeFrom, slice};
use byteorder::WriteBytesExt;
use log::error;
use nimiq_database_value::{FromDatabaseValue, IntoDatabaseValue};
use nimiq_hash::{Blake2bHash, Hash, HashOutput, Hasher};
use nimiq_serde::{Deserialize, Serialize};
use crate::{key_nibbles::KeyNibbles, trie::error::MerkleRadixTr... |
use crate::entities::models::{File, Folder};
use crate::entities::traits::folder::FolderStore;
use crate::entities::error::DataStoreError;
impl File {
pub fn folder(&self) -> Result<Folder, DataStoreError> {
let folder_service = resolve!(FolderStore);
folder_service.find_by_folder_id(self.folder_i... |
use proc_macro2::TokenStream as TokenStream2;
use quote::quote;
use rtfm_syntax::{ast::App, Context};
use crate::{
analyze::Analysis,
codegen::{locals, module, resources_struct, util},
};
pub fn codegen(
app: &App,
analysis: &Analysis,
) -> (
// const_app
Vec<TokenStream2>,
// task_mods
... |
use crate::data::error_info::ErrorInfo;
use crate::data::literal::ContentType;
use crate::data::primitive::{PrimitiveArray, PrimitiveObject};
use crate::data::Position;
use crate::data::{
ast::*, tokens::*, ArgsType, Context, Data, Literal, MemoryType, MessageData, MSG,
};
use crate::error_format::*;
use crate::imp... |
extern crate crossbeam;
use super::{
cmp_and_swap,
cmp_and_swap_func
};
use std::sync::Mutex;
use std::cmp::Ordering;
use std::marker::{
Send,
Sync,
PhantomData
};
use std::mem;
use std::sync::atomic::{
AtomicUsize,
Ordering as AtomicOrdering
};
struct TrackerAtomic {
locker: AtomicUs... |
// Copyright (c) <2015> <lummax>
// Licensed under MIT (http://opensource.org/licenses/MIT)
#![feature(libc)]
extern crate libc;
mod ffi;
pub mod client;
|
pub struct ATNDeserializationOptions {
read_only: bool,
verify_atn: bool,
generate_rule_bypass_transitions: bool,
}
impl ATNDeserializationOptions {
fn new_atndeserialization_options(
_CopyFrom: &ATNDeserializationOptions,
) -> ATNDeserializationOptions {
unimplemented!()
}
... |
use std::default::Default;
use std::fs;
use std::path::PathBuf;
use toml;
pub type Result<T> = std::result::Result<T, failure::Error>;
#[derive(Debug, Clone, Deserialize)]
pub struct User {
pub name: String,
pub password: String,
}
#[derive(Debug, Deserialize)]
pub struct ForumConfig {
pub user: User,
... |
pub mod app;
pub mod db_config;
pub mod handlers;
pub mod logic_layer;
pub mod schema_config;
pub mod errors;
pub mod auth; |
#[doc = "Reader of register SOPT2"]
pub type R = crate::R<u32, super::SOPT2>;
#[doc = "Writer for register SOPT2"]
pub type W = crate::W<u32, super::SOPT2>;
#[doc = "Register SOPT2 `reset()`'s with value 0"]
impl crate::ResetValue for super::SOPT2 {
type Type = u32;
#[inline(always)]
fn reset_value() -> Sel... |
use std::pin::Pin;
use crate::context::Context;
use crate::message::Message;
use futures::sink::Sink;
use futures::Future;
pub type Output<'a> = Pin<Box<dyn Future<Output = ()> + Send + 'a>>;
pub trait Actor: Sized + Send + 'static {
type Message: Message + Send + 'static;
type Sender: Sink<Self::Message> +... |
#[macro_use]
extern crate nom;
use std::string::String;
use std::collections::HashSet;
use itertools::Itertools;
use crate::parse::Claim;
use crate::vec2d::Vec2D;
mod parse;
mod vec2d;
/// Parse all the lines as claims.
fn parse_lines(lines: &[String]) -> Vec<Claim> {
lines.iter().map(|l| parse::claim(l)).col... |
//! Conversions into heavily used types.
mod try_future;
mod try_stream;
#[doc(inline)]
pub use self::{try_future::*, try_stream::*};
/// Trivial and transparent wrapper-type that provides [`IntoTryFuture`] and
/// [`IntoTryStream`] implementations for types which implement infallible
/// [`Future`] already, but don... |
use std::collections::BTreeMap;
use std::collections::HashMap;
use std::env;
use std::fmt;
use std::fs;
use std::path::Path;
use util::*;
const TITLE: &str = "# Leetcode Solutions in Rust";
const BODY: &str = "
This project demostrates how to create **Data Structures** and to implement **Algorithms** using programming... |
fn main() {
let (mut a, mut b) = default();
scanf!("{:u} {:u}", &mut a, &mut b);
let d = a / b;
let r = a % b;
let f = (a as f64) / (b as f64);
printf!("{d:u} {r:u} {f:.6f}\n");
}
|
use crate::physics::collision::chunk_triangles::*;
use crate::physics::collision::PlanetCollision;
use ncollide3d::query::PointProjection;
use ncollide3d::query::PointQuery;
use ncollide3d::shape::FeatureId;
// idk how it works. I just copied it from Ralith code
impl PointQuery<f64> for PlanetCollision {
fn projec... |
#[derive(Debug)]
pub enum A {
A,
C,
}
#[derive(Debug)]
pub enum B {
A,
B,
}
#[derive(Debug)]
pub enum S {
ASd(Box<A>, Box<S>),
BS(Box<B>, Box<S>),
Eps,
}
#[derive(Debug)]
pub enum SS {
S(Box<S>),
}
|
use crate::value::Value;
use crate::vm::{Chunk, Instruction, OpCode};
struct Disassambler<'a> {
chunk: &'a Chunk,
}
impl<'a> Disassambler<'a> {
fn new(chunk: &'a Chunk) -> Self {
Self { chunk }
}
fn disassemble(&self) {
let mut last_line = std::usize::MAX;
for (offset, inst) i... |
const MAX_RATE: f64 = 1.00f64;
const MODERATE_RATE: f64 = 0.90f64;
const MINIMUM_RATE: f64 = 0.77f64;
const BASE_RATE: i64 = 221;
pub fn production_rate_per_hour(speed: u8) -> f64 {
let base_yield = (BASE_RATE * speed as i64) as f64;
match speed {
1..=4 => base_yield * MAX_RATE,
5..=8 => base_y... |
#![recursion_limit = "96"]
#![cfg_attr(
all(not(debug_assertions), target_os = "windows"),
windows_subsystem = "windows"
)]
mod local_storage_plugin;
mod websocket_plugin;
fn main() {
// Initialize the logger
tracing_subscriber::fmt::init();
tauri::AppBuilder::new()
.plugin(local_storage_plugin::LocalS... |
use crate::partials::page;
use crate::DbConn;
use diesel::result::Error;
use maud::{html, Markup};
use rchdb::models::{NewReply, NewThread, Reply, Thread};
use rchdb::{delete, get, list, new, reply};
use rocket::response::status::{Created, NoContent};
use rocket_contrib::json::Json;
// Template Routes
#[get("/")]
pub ... |
use readers::prelude::*;
mod known_range_iterator;
mod unknown_range_iterator; |
// validbr - Brazilian registry validator, provides structures for representing CPF, CNPJ, RG, CNH, CEP and Credit Card Number!
//
// The MIT License (MIT)
//
// Copyright (c) Obliter Software (https://github.com/oblitersoftware/)
// Copyright (c) contributors
//
// Permission is hereby grant... |
use std::mem;
use byteorder::{ReadBytesExt, LittleEndian};
use crate::Result;
use crate::{Cache, ResolveToTypeDef};
use crate::core::db::Database;
use super::{Type, TypeTag, PrimitiveType, MethodDefSig, ParamKind, bits};
fn read_string<'db>(cursor: &mut &'db [u8]) -> Result<Option<&'db str>> {
let length = super::... |
use vec3::Vec3;
#[derive(Debug, Clone, Copy)]
pub struct Ray { pub origin: Vec3, pub direction: Vec3 }
impl Ray {
pub fn new(origin: Vec3, direction: Vec3) -> Self {
Ray { origin, direction }
}
pub fn point_at(&self, t: f32) -> Vec3 { self.origin + t*self.direction }
}
|
/**
* [21] Merge Two Sorted Lists
*
* Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
*
* Example:
*
* Input: 1->2->4, 1->3->4
* Output: 1->1->2->3->4->4
*
*
*/
pub struct Solution {}
pub use super::util::linked_lis... |
//! Tracing service.
use opentelemetry::{
global,
propagation::{Extractor, Injector, TextMapPropagator},
sdk::{
propagation::TraceContextPropagator,
trace::{Config, Sampler, TracerProvider as sdk_tracerprovider},
},
trace::{Span, TracerProvider},
Context, Key,
};
use std::colle... |
use crate::{bsp, cpu};
use cortex_a::{asm, regs::*};
// Boot Code
/// The entry of the kernel binary.
///
/// The function must be named `_start` because the linker is looking for
/// that name.
/// Linker script must place this function at 0x80_000
// Couldn't find much docs for this attribute, except https://github.... |
// https://stackoverflow.com/questions/46388386/what-exactly-does-derivedebug-mean-in-rust
// exists generics
#[derive(Debug)]
struct Employee {
first_name: &'static str,
last_name: &'static str,
salary: isize,
}
//like named tuple
struct Salary (i32, i32, i32);
enum Charge {
Ceo,
Leader{area: &'static str, emp... |
struct Solution;
use std::collections::HashSet;
impl Solution {
fn is_reflected(points: Vec<Vec<i32>>) -> bool {
let min = points.iter().map(|v| v[0]).min().unwrap();
let max = points.iter().map(|v| v[0]).max().unwrap();
let x = max + min;
let mut hs: HashSet<(i32, i32)> = HashSet:... |
//! Media service facade
use bt_topshim::btif::BluetoothInterface;
use bt_topshim::profiles::a2dp::{A2dp, A2dpCallbacksDispatcher, A2dpSink};
use bt_topshim::profiles::avrcp::{Avrcp, AvrcpCallbacksDispatcher};
use bt_topshim_facade_protobuf::facade::{
A2dpSourceConnectRequest, A2dpSourceConnectResponse, StartA2dpR... |
extern crate serde_derive;
use super::*;
use std::boxed::Box;
use std::io::Write;
#[derive(Deserialize)]
pub struct Entry {
pub url: String,
pub title_selector: String,
pub image_selector: String,
}
impl Entry {
pub fn get_page(&self) -> std::io::Result<Box<Scrapable + Send + Sync>> {
let std... |
mod api;
mod message;
use serde_json::{json, Value};
use tokio::io;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::{TcpListener, TcpStream};
use std::fs::File;
use std::fs::{self, DirBuilder};
use std::io::prelude::*;
use api::getfile;
use futures::future::try_join;
use futures::FutureExt;
use std::co... |
pub mod auth;
pub mod user;
pub mod project;
pub mod file; |
use std::collections::VecDeque;
const ALPHABET: &str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
#[derive(Debug)]
pub struct Rotor {
pub(super) state: VecDeque<char>,
notch: Option<char>,
}
impl Rotor {
pub fn new(set: &str, notch: char) -> Self {
let mut state = VecDeque::with_capacity(set.len());
f... |
// Copyright 2006 The Android Open Source Project
// Copyright 2020 Yevhenii Reizner
//
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use alloc::vec;
use alloc::vec::Vec;
use core::convert::TryFrom;
use core::num::NonZeroUsize;
use tiny_skia_path::IntSize;
u... |
extern crate rand;
use core::fmt::Display;
use core::ops::{Add, Mul, Sub, Div, AddAssign, MulAssign, SubAssign, DivAssign};
use thread_comm::ThreadInfo;
use composables::AlgorithmStep;
use matrix::view::MatrixView;
//Trait Definitions
pub trait ScalarConstants {
#[inline(always)]
fn one() -> Self;
#[inlin... |
//@compile-flags: -Zmiri-panic-on-unsupported
//@normalize-stderr-test: "OS `.*`" -> "$$OS"
fn main() {
extern "Rust" {
fn foo();
}
unsafe {
foo();
}
}
|
pub mod nu_dataframe;
pub mod nu_groupby;
pub use nu_dataframe::NuDataFrame;
pub use nu_groupby::NuGroupBy;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash, Serialize, Deserialize)]
pub enum PolarsData {
EagerDataFrame(NuDataFrame),
GroupBy(NuGroupBy),
}
|
use super::block::*;
use super::instructions::*;
use regalloc::Function as RFunction;
#[derive(Debug, Copy)]
pub struct Block {
pub label: usize,
pub start: InstIx,
pub len: u32,
}
impl Block {
pub fn new(label: usize, start: InstIx, len: u32) -> Self {
Self { label, start, len }
}
}
impl C... |
use coconut_sig::signature::Params as CParams;
use crate::SignatureGroup;
use crate::amcl_wrapper::group_elem::GroupElement;
/// Utility module to help with JS/WASM interfacing
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Public {
pub g: SignatureGroup,
pub h: SignatureGroup,
pub cparams: ... |
use point;
use wire;
#[derive(Clone, Copy, Debug)]
pub struct Component {
point : point::Point,
width : u8,
height : u8,
// inputs
// outputs
}
impl Component {
pub fn new (point : point::Point, width : u8, height : u8) -> Self {
Component {
point : point,
width : width,
he... |
use std::cmp::{max, min};
use noa_buffer::{
cursor::Position,
display_width::DisplayWidth,
paragraph_iter::Paragraph,
reflow_iter::{PrintableGrapheme, ReflowItem},
};
use noa_compositor::{
canvas::{CanvasViewMut, Grapheme},
compositor::Compositor,
surface::{HandledEvent, KeyEvent, Layout, R... |
use std::borrow::Cow;
use std::fmt::{self, Debug, Formatter};
use std::ops::{Deref, DerefMut};
use futures_core::future::BoxFuture;
use crate::database::Database;
use crate::error::Error;
use crate::pool::MaybePoolConnection;
/// Generic management of database transactions.
///
/// This trait should not be used, exc... |
use std::collections::VecDeque;
pub struct Solution {}
impl Solution {
pub fn max_sliding_window(nums: Vec<i32>, k: i32) -> Vec<i32> {
let k = k as usize;
let mut result = Vec::with_capacity(nums.len() + 1 - k);
let mut deque = VecDeque::with_capacity(k);
let mut max = std::i32::MI... |
struct Solution;
impl Solution {
fn get_no_zero_integers(n: i32) -> Vec<i32> {
let mut v: Vec<bool> = vec![true; 10000];
v[0] = false;
for i in 0..10 {
for j in 0..10 {
for k in 0..10 {
for l in 0..10 {
let x = i * 1000... |
use super::super::util::parse_usize;
use std::fmt;
#[derive(Debug, PartialEq, Eq, Copy, Clone)]
pub enum DanceMove {
Spin(usize),
Exchange(usize, usize),
Partner(char, char),
}
fn first_char(s: &str) -> char {
s.chars().next().unwrap()
}
impl DanceMove {
named!(pub parse(&str)-> DanceMove, alt_co... |
//! A Creative object defines the payload to be delivered to the end user. Creatives belong to
//! Advertisers and are associated with Line Items. The Creative object has interactions with
//! Creative Templates and Creative Assets / Video Assets as described in Creatives, Creative
//! Assets, Templates, Rules.
use cr... |
use super::{ClientMessage, Connect, Disconnect, Message, CLIENT_TIMEOUT, HEARTBEAT_INTERVAL};
use crate::server::Server;
use actix::*;
use actix::{Actor, AsyncContext, StreamHandler};
use actix_web_actors::ws;
use std::sync::Arc;
use std::time::Instant;
pub struct EventSession {
id: usize,
hb: Instant,
nam... |
use futures::executor::block_on;
use starcoin_chain_service::ChainAsyncService;
use starcoin_config::NodeConfig;
use starcoin_logger::prelude::*;
use starcoin_sync_api::SyncAsyncService;
use std::thread::sleep;
use std::{sync::Arc, time::Duration};
use test_helper::run_node_by_config;
pub fn test_sync() {
let firs... |
mod_def_reexport!{
cswapi,
cswap,
ldunci,
ldunc,
ldvtsi,
ldvts,
pregoi,
prego,
preldi,
preld,
presti,
prest,
stunci,
stunc,
syncdi,
syncd,
syncidi,
syncid,
sync,
}
|
extern crate amqp;
extern crate env_logger;
use serde_json;
#[derive(Serialize, Deserialize, Debug)]
pub struct PlasticHeartbeat {
}
pub fn from(data: &Vec<u8>) -> Result<PlasticHeartbeat, serde_json::error::Error> {
return serde_json::from_slice(&data);
}
|
use serde::ser::{SerializeSeq, SerializeStruct, SerializeTupleStruct, Serializer};
use serde::Serialize;
use serde_starlark::{FunctionCall, MULTILINE, ONELINE};
use super::{
Data, ExportsFiles, Load, Package, RustBinary, RustLibrary, RustProcMacro, SelectList,
};
// For structs that contain #[serde(flatten)], a q... |
pub mod common;
pub mod get_delay_statistics;
pub mod get_global_state;
pub mod get_user_info;
pub mod init_connect;
pub mod init_web_socket;
pub mod keep_alive;
pub mod notify;
pub mod qot_common;
pub mod qot_get_basic_qot;
pub mod qot_get_broker;
pub mod qot_get_capital_distribution;
pub mod qot_get_capital_flow;
pub... |
use crate::*;
use std::marker::PhantomData;
#[derive(Debug)]
pub struct Sum<S: Signal<R>, R: Rate = Hz44100> {
rate: PhantomData<*const R>,
signals: Vec<S>,
}
impl<S: Signal<R>, R: Rate> Sum<S, R> {
pub fn new<Signals: Into<Vec<S>>>(signals: Signals) -> Self {
Self {
rate: PhantomData... |
use std::fs;
use std::str::FromStr;
use anyhow::Result;
pub fn read_data<T: FromStr>(filepath: String, split_string: &str) -> Result<Vec<T>> {
let content = fs::read_to_string(filepath)?;
read_data_str(content, split_string)
}
pub fn read_data_str<T: FromStr>(content: String, split_string: &str) -> Result<Ve... |
use std::io;
use std::process::Command;
use std::sync::{Arc, Condvar, Mutex};
use std::thread::{Builder, JoinHandle};
#[derive(Debug)]
pub struct Client {
inner: Arc<Inner>,
}
#[derive(Debug)]
struct Inner {
count: Mutex<usize>,
cvar: Condvar,
}
#[derive(Debug)]
pub struct Acquired(());
impl Client {
... |
use clap::{App, Arg, ArgMatches, SubCommand};
pub fn parseArgs() -> ArgMatches<'static> {
let matches = App::new("aqui")
.version("1.0")
.author("Joel Edwards <joeledwards@gmail.com>")
.about("CLI HTTP client aimed at maximum human friendliness")
.subcommand(subcommandWithBody("dele... |
use dim2::{Line, Plane};
#[derive(Clone)]
pub struct BspNode {
pub plane: Option<Plane>,
pub front: Option<Box<BspNode>>,
pub back: Option<Box<BspNode>>,
pub lines: Vec<Line>,
}
impl BspNode {
pub fn new(lines: Option<Vec<Line>>) -> BspNode {
let mut bsp = BspNode {
plane: None... |
struct Solution;
impl Solution {
fn validate_stack_sequences(pushed: Vec<i32>, popped: Vec<i32>) -> bool {
let mut stack = vec![];
let mut it = popped.iter().peekable();
for x in pushed {
stack.push(x);
while let (Some(&a), Some(&&b)) = (stack.last(), it.peek()) {
... |
mod aggregator1;
mod aggregator2;
mod pair;
fn main() {
// aggregator1::listing_11_13();
// aggregator1::listing_10_14();
// aggregator2::listing_10_14_2();
pair::listing_10_16();
}
|
extern crate rusoto_core;
extern crate rusoto_dynamodb;
use std::collections::HashMap;
use std::str;
use rusoto_core::Region;
use rusoto_dynamodb::{
AttributeValue, DescribeTableInput, DynamoDb, DynamoDbClient, GetItemInput, ListTablesInput,
};
#[tokio::main]
async fn main() {
println!("Starting DynamoDb Exa... |
/// Spritesheet index
#[inline(always)]
pub fn ss_idx(x: u16, y: u16) -> u16 {
x / 8 + y / 8 * 16
}
pub fn make_weighted_vec<T: Copy>(items: &[(T, usize)]) -> Vec<T> {
let mut values = items.iter().map(|(v, t)| vec![*v; *t]).collect::<Vec<_>>();
let values = values
.iter_mut()
.reduce(|a, b... |
use crate::config;
use rocket_contrib::json::{Json, JsonValue};
use rocket::http::Status;
use crate::models;
use models::issues::{Issues, NewIssues, UpdateIssues};
use crate::database;
use database::issues as action;
#[get("/issues")]
pub fn view_all_issues(connection: config::Connection) -> JsonValue {
let res... |
extern crate pnet;
use log::*;
use std::error;
use std::process;
use pnet::packet::icmp::{IcmpTypes, echo_request, echo_reply, IcmpPacket};
use pnet::packet::icmpv6::{Icmpv6Types, MutableIcmpv6Packet};
use pnet::packet::ip::IpNextHeaderProtocols;
use pnet::packet::{Packet, PacketSize};
use pnet::transport::{
ipv4_... |
//! My answers to the challenges on chapter 1.
/// 1. Implement, as best as you can, the identity function in your favorite language (or the
/// second favorite, if your favorite language happens to be Haskell).
pub fn id<T>(x: T) -> T {
x
}
/// 2. Implement the composition function in your favorite language. It ... |
use core::fmt;
use cstr_core::CStr;
use num_traits::ToPrimitive;
use bad64_sys::*;
/// A system register
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, FromPrimitive, ToPrimitive)]
#[repr(u32)]
#[allow(non_camel_case_types)]
pub enum SysReg {
OSDTRRX_EL1 = SystemReg_REG_OSDTRRX_EL1 as u32,
DBGBVR0_EL1 = S... |
#![feature(convert)]
extern crate libc;
pub use error::{ Error, Result };
pub use globals::*;
pub use interfaces::{ Interfaces, Interface };
mod error;
mod ffi;
mod globals;
mod interfaces;
|
use derive_more::{Display, From};
pub type Result<T> = std::result::Result<T, Error>;
#[derive(From, Display, Debug)]
pub enum Error {
Io(std::io::Error),
#[cfg(feature = "crypto")]
OpenSsl(openssl::error::ErrorStack),
#[cfg(feature = "crypto")]
Bcrypt(bcrypt::BcryptError),
FailedToSendByte... |
use std::ops::Add;
impl Solution {
pub fn letter_combinations(digits: String) -> Vec<String> {
if digits.is_empty() { return Vec::new(); }
let maps = vec![
vec!["a", "b", "c"],
vec!["d", "e", "f"],
vec!["g", "h", "i"],
vec!["j", "k", "l"],
... |
use self::Letter::{
C, Csh, Db, D, Dsh, Eb, E, F, Fsh, Gb, G, Gsh, Ab, A, Ash, Bb, B
};
use std::num::Float;
use utils::modulo;
pub const TOTAL_LETTERS: u8 = 12;
#[deriving(Clone, PartialEq, PartialOrd, Show, Encodable, Decodable)]
pub enum Letter {
C, Csh, Db, D, Dsh, Eb, E, F, Fsh, Gb, G, Gsh, Ab, A, Ash, ... |
// Copyright 2012 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 ... |
struct Solution;
use std::collections::HashMap;
impl Solution {
fn find_strobogrammatic(n: i32) -> Vec<String> {
let mut res = vec![];
let hm: HashMap<char, char> =
vec![('0', '0'), ('1', '1'), ('6', '9'), ('8', '8'), ('9', '6')]
.into_iter()
.collect();
... |
extern crate RustFizzBuzz;
use RustFizzBuzz::rust_fizzbuzz;
#[test]
fn can_test() {
assert_eq!(1, 1);
}
#[test]
fn _1is_1() {
assert_eq!("1", rust_fizzbuzz::fizzbuzz(1));
}
#[test]
fn _3is_fizz() {
assert_eq!("fizz", rust_fizzbuzz::fizzbuzz(3));
}
#[test]
fn _5is_buzz() {
assert_eq!("buzz", rust_fi... |
/// NodeStateSmartfailExtended : Node smartfail state.
#[allow(unused_imports)]
use serde_json::Value;
#[derive(Debug, Serialize, Deserialize)]
pub struct NodeStateSmartfailExtended {
/// This node is dead (dead_devs).
#[serde(rename = "dead")]
pub dead: Option<bool>,
/// This node is down (down_devs)... |
// Copyright (c) The Libra Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::{FromProto, FromProtoBytes, IntoProto, IntoProtoBytes};
use std::fmt::Debug;
/// Assert that protobuf encoding and decoding roundtrips correctly.
///
/// This is meant to be used for `protobuf::Message` instances. For non-m... |
use std::env;
use std::fs;
use std::string::String;
fn main() {
let args: Vec<String> = env::args().collect();
let filename = &args[1];
println!("In file {}", filename);
let contents = fs::read_to_string(filename).expect("Something went wrong reading the file");
let split = contents.split_whites... |
extern crate energymon_builder;
fn main() {
energymon_builder::find_or_build("energymon-msr").unwrap();
}
|
// Reexport some often used types
pub use iota_streams_core::prelude::{
generic_array::{
ArrayLength,
GenericArray,
},
typenum::{
self,
marker_traits::Unsigned,
U16,
U32,
U64,
},
};
mod bytes;
pub use bytes::*;
mod external;
pub use external::*;
m... |
use bytes::{Buf, BufMut};
use futures::Poll;
use std::io;
use tokio_core::net::TcpStream;
use tokio_io::{AsyncRead, AsyncWrite};
#[cfg(feature = "tls")]
use tokio_tls::TlsStream;
#[derive(Debug)]
pub enum StreamType {
Tcp(TcpStream),
#[cfg(feature = "tls")]
Tls(TlsStream<TcpStream>),
}
impl From<TcpStream... |
// More info at: https://doc.rust-lang.org/rust-by-example/hello/print.html
fn main() {
// Print with optional patterns. Positional arguments {0:"Hello"} {1:"world"}
println!("{0}, {1}!", "Hello", "world");
}
|
use rand::distributions::Distribution;
use rand::distributions::Uniform;
use rand::Rng;
use crate::local_search::hill_climbing::HillClimbing;
use super::*;
pub use self::temperature::*;
pub trait Temperature<P>
where P: Problem
{
type State;
fn acceptance_probability(&self, new: &Solution<P>, current: &Sol... |
#[macro_use]
extern crate log;
extern crate simple_logger;
#[macro_use]
extern crate serde_derive;
use clap::ArgMatches;
use std::fs;
mod model;
use crate::model::*;
use std::thread;
pub fn run(matches: ArgMatches) {
let model_file = matches.value_of("model").unwrap();
info!("Model file is {}", model_file)... |
use http::Request;
mod auth;
pub use auth::Authorization;
pub trait RequestExt {
fn authorization(&self) -> Authorization<'_>;
}
impl<B> RequestExt for Request<B> {
#[inline]
fn authorization(&self) -> Authorization<'_> {
Authorization::new(self)
}
}
#[cfg(test)]
mod tests {
use super::*... |
#[doc = "Register `MAC_ADDR0H` reader"]
pub struct R(crate::R<MAC_ADDR0H_SPEC>);
impl core::ops::Deref for R {
type Target = crate::R<MAC_ADDR0H_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<crate::R<MAC_ADDR0H_SPEC>> for R {
#[inline(always)]
fn from(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.