text stringlengths 8 4.13M |
|---|
use crate::parser::token::Op;
use std::convert::From;
#[derive(Clone, Copy, Debug)]
pub enum BinOp {
Add,
Sub,
Mul,
Div,
Mod,
Eq,
Ne,
Gt,
Lt,
Gte,
Lte
}
impl From<Op> for BinOp {
fn from(op: Op) -> BinOp {
match op {
Op::Add => BinOp::Add,
... |
#[derive(Debug)]
struct Rectangle {
width: u32,
height: u32,
}
impl Rectangle {
fn new(width: u32, height: u32) -> Rectangle {
Rectangle { width, height }
}
fn area(&self) -> u32 {
self.width * self.height
}
fn can_hold(&self, other: &Rectangle) -> bool {
... |
use game::Game;
use text_io::read;
extern crate text_io;
mod game;
fn main() {
let mut game = Game::default();
loop {
println!("Multiplayer or Ai(M/A): ");
match read!() {
'M' | 'm' => game.run_game(),
'A' | 'a' => game.run_game_vs_ai(),
_ => {}
}
... |
#![doc = "generated by AutoRust 0.1.0"]
#![allow(non_camel_case_types)]
#![allow(unused_imports)]
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Resource {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(d... |
// avro.rs
//
// Avro Codec for primitive types
// and Avro arrays (as vectors) and Avro maps
// (as HashMap<String, T>)
// (c) 2016 James Crooks
use std::iter::Iterator;
use std::collections::HashMap;
use std::mem;
pub type ByteStream = Iterator<Item = u8>;
pub trait AvroCodec: Sized {
fn encode(&self) -> Vec<u... |
use argh::FromArgs;
#[derive(FromArgs)]
/// dd writer goes drrrrrrrr
pub struct AppArgs {
/// the file to read
#[argh(option)]
pub input: String,
/// the file to write
#[argh(option)]
pub output: String,
/// set the blocksize, default is 1MiB
#[argh(option)]
pub blocksize: Option<... |
use rand::{seq::SliceRandom, thread_rng, Rng};
use vek::Rgb;
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Body {
pub race: Race,
pub body_type: BodyType,
pub chest: Chest,
pub belt: Belt,
pub pants: Pants,
pub hand: Hand,
pub foot: Foot,
pub shou... |
struct Point <T,U>{
x:T,
y:U,
}
impl <T,U> Point <T,U>{
fn mixup <V,W> (self,other: Point<V,W>) -> Point<T,W>{
Point {
x:self.x,
y:other.y,
}
}
}
fn main() {
let p1 = Point {x:6,y:7.0};
let p2 = Point {x:"Areeb",y:'c'};
let p3 = p1.mixup... |
use crate::arch::interrupt::TrapFrame;
use bcm2837::interrupt::Controller;
use spin::RwLock;
pub use bcm2837::interrupt::Interrupt;
lazy_static! {
static ref IRQ_HANDLERS: RwLock<[Option<fn()>; 64]> = RwLock::new([None; 64]);
}
pub fn is_timer_irq() -> bool {
super::timer::is_pending()
}
pub fn handle_irq(_... |
use crate::*;
#[derive(Debug, Clone, Copy, Default)]
pub struct BodyJson<T>(pub T);
#[async_trait]
impl<T, B> FromRequest<B> for BodyJson<T>
where
T: serde::de::DeserializeOwned,
B: http_body::Body + Send,
B::Data: Send,
B::Error: Into<tower::BoxError>,
{
type Rejection = JsonRejection;
asyn... |
extern crate askama;
use askama::Template;
use actix_files as fs;
use actix_web::{http, web, App, HttpRequest, HttpResponse, HttpServer, Responder, Result};
use listenfd::ListenFd;
use http::StatusCode;
use std::clone::Clone;
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
use std:... |
extern crate num_cpus;
extern crate pretty_env_logger;
use std::os::raw::c_void;
use std::sync::{Arc, Mutex};
use cfile;
use log::Level::Debug;
use ffi;
use common::memory::SOCKET_ID_ANY;
use eal::{self, ProcType};
use launch;
use lcore;
use mbuf;
use memory::AsMutRef;
use mempool::{self, MemoryPool, MemoryPoolFlag... |
//! Multi Media eXtensions (MMX)
use mem::transmute;
use sealed::*;
use simd::*;
/// Instantiate zero-initialized vector
///
/// # Instruction
///
/// This intrinsic maps to different instructions depending on how the vector is
/// used:
///
/// * [`pxor mm, mm`](http://www.felixcloutier.com/x86/PXOR.html)
/// * [`xo... |
//! Module contains a list of backends for pretty print tables.
pub mod compact;
#[cfg(feature = "std")]
pub mod iterable;
#[cfg(feature = "std")]
pub mod peekable;
|
use std::sync::mpsc::SyncSender;
use std::thread;
use crate::mechatronics::commands::RobotCommand;
/// The controller module contains the `RobotController` struct.
/// The `RobotController` struct owns instances of the `DriveTrain` and the `MaterialHandler`.
pub mod controller;
pub mod commands;
/// The drive_train... |
pub use crate::core::{
clients::{AsStorageClient, StorageAccountClient, StorageClient},
shared_access_signature::{
account_sas::{
AccountSasPermissions, AccountSasResource, AccountSasResourceType,
ClientAccountSharedAccessSignature, SasExpirySupport, SasPermissionsSupport,
... |
use std::fmt;
use std::time::Duration;
/// Represents parameters of "gameover" command.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum GameOverKind {
Win,
Lose,
Draw,
}
impl fmt::Display for GameOverKind {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
... |
use json::{JsonValue};
use v2::V2;
pub struct MyV2(pub V2);
use gamestate::{GameState, Player, Pickup, PickupType};
impl<'a> From<&'a PickupType> for JsonValue {
fn from(v : &'a PickupType) -> JsonValue {
format!("{:?}", v).into()
}
}
impl<'a> From<&'a MyV2> for JsonValue {
fn from(v : &'a MyV2) ... |
use super::lock::spin::SpinMutex;
use super::memory::{Page, PAGE_SIZE};
use alloc::alloc::{GlobalAlloc, Layout};
use core::ptr::NonNull;
use utils::prelude::*;
use linked_list_allocator::Heap;
pub struct KernelHeap {
heap: SpinMutex<Heap>,
}
unsafe impl GlobalAlloc for KernelHeap {
unsafe fn alloc(&self, layou... |
use std::collections::HashMap;
/*
There is a mathematical solution to this -- it's very similar to an older
problem I've seen, which wanted people to solve for the values at the corner
of this spiral square.
But to make this a better Rust problem, I'm gonna try a state-machiney thing.
*/
#[derive(Hash, Eq, Partial... |
extern crate futures;
extern crate tokio_core;
extern crate tokio_timer;
extern crate env_logger;
#[macro_use]
extern crate serde_derive;
extern crate serde;
extern crate serde_json;
pub mod codec;
pub mod message;
use codec::TplinkSmartHomeCodec;
use message::*;
use std::io;
use std::time::Duration;
use std::ne... |
pub mod encode;
pub mod decode;
pub mod endian;
pub mod buffer;
|
pub fn solve_n_queens(n: i32) -> Vec<Vec<String>> {
if n < 4 {
if n == 1 {
return vec![vec!["Q".to_string()]]
}
return vec![]
}
let n = n as usize;
let mut result = vec![];
fn core(index: usize, v: &mut Vec<usize>, r: &mut Vec<Vec<usize>>, push_two: bool) {
... |
// if let
//
// 变量赋值时把`if`作为一个表达式。
//
// 表达式的值是任何被选择的分支的最后一个表达式的值。
//
fn main() {
sample1();
no_else();
}
fn sample1() {
// 普通的if in let表达式
let x = if true { 1 } else { 0 };
assert_eq!(x, 1);
// 不会执行的分支内加上宏定义, 没有返回值, 也能编译通过.
let x = if true { 1 } else { unreachable!() };
assert_eq!(x, ... |
use std::collections::HashSet;
use std::fs;
use std::path::Path;
fn main() {
let data = read_file("./input/input.txt").unwrap();
// data.sort();
println!("{:?}", data);
println!("{:?}", part1(data.clone()));
println!("{:?}", part2(data.clone()));
}
fn part1(data: Vec<i64>) -> std::result::Result<... |
// MESSAGES FROM HANDLERS TO THE APPLICATION
use actix::prelude::*;
use crate::game_folder::game::Game;
/// Check if a game exists
/// ```
/// #[rtype(bool)]
/// pub struct DoesGameExist {
/// pub game_id: String,
/// }
/// ```
#[derive(Message)]
#[rtype(bool)]
pub struct DoesGameExist {
pub game_id: String,
... |
#![deny(unsafe_op_in_unsafe_fn)]
use parking_lot::Mutex;
use pymemprofile_api::memorytracking::LineNumberInfo::LineNumber;
use pymemprofile_api::memorytracking::{
AllocationTracker, CallSiteId, Callstack, FunctionId, IdentityCleaner, VecFunctionLocations,
PARENT_PROCESS,
};
use pymemprofile_api::oom::{InfiniteM... |
use std::io::Write;
use std::path::Path;
use super::btmeister::{BuildToolDef, BuildToolDefs};
use super::cli::Format;
use super::BuildTool;
pub trait Formatter {
fn print(&self, out: &mut Box<dyn Write>, base: &Path, vector: Vec<BuildTool>) -> i32 {
self.print_header(out, base);
vector
... |
struct MinStack {
values: Vec<i32>,
min_values: Vec<i32>,
}
impl MinStack {
fn new() -> Self {
Self {
values: vec![],
min_values: vec![],
}
}
fn push(&mut self, val: i32) {
self.values.push(val);
if self.min_values.len() == 0 {
s... |
//
// Copyright 2020 The Project Oak Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law o... |
use cpu::Core;
/// Execute the opcode and return the number of cycles.
pub fn execute(cpu: &mut Core, opcode: u8) -> usize {
match opcode {
0x4c => jump_abs(cpu),
0x6c => jump_indr(cpu),
_ => 0,
}
}
/// Jump to absolute address (JMP).
///
/// Flags affected: None
fn jump_abs(cpu: &mut ... |
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Duration;
pub struct MavlinkCameraInformation {
system_id: u8,
component_id: u8,
// This is necessary since mavlink does not provide a way to have nonblock communication
// So we need the main mavlink loop live while changing the stream uri
... |
extern crate glium;
extern crate imgui;
extern crate imgui_glium_renderer;
mod support;
const CLEAR_COLOR: [f32; 4] = [0.2, 0.2, 0.2, 1.0];
fn main() {
support::run("test_window.rs".to_owned(), CLEAR_COLOR, |ui| {
let mut open = true;
ui.show_test_window(&mut open);
open
});
}
|
#![allow(dead_code)]
use hashbrown::HashSet;
use valis_hir::{HirStorage, Identifier};
use valis_source::SourceStorage;
use valis_syntax::SyntaxStorage;
use valis_type::{
binding::{Binder, DebruijnIndex},
FuncTyData, LatticeOpTyData, LatticeOpType, ParamTy, PlaceholderTy, Polarity, RecordTyData, Ty,
TyData,... |
use std::fs;
use regex::Regex;
fn find(a: usize, seat: &str, start: usize, end: usize,
lower: usize, upper: usize,
upper_char: char, lower_char: char) -> usize {
match seat.chars().nth(a) {
Some(c) => {
if c == lower_char {
if a == end - 1 {
return lower;
}
return find(a+1, seat, start, end,
... |
mod processor;
pub use processor::ProxyProcessor;
use crate::CoreLayer;
use crate::CoreProcessor;
use common::{async_trait::async_trait, tokio};
use std::{
any::Any,
sync::{Arc, Weak},
};
use crate::SipManager;
use models::transport::TransportMsg;
pub struct Proxy<P: CoreProcessor> {
inner: Arc<Inner<P>>... |
use crossterm::cursor::MoveToColumn;
#[cfg(feature = "sync")]
use crossterm::event::{poll, read, Event};
#[cfg(feature = "async-tokio")]
use crossterm::event::{Event, EventStream};
#[cfg(any(feature = "sync", feature = "async-tokio"))]
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use crossterm::execute;
#[c... |
pub mod header_component;
pub mod homepage_component;
pub mod item_wrapper_component;
pub mod todo_item_component;
pub mod add_item_component;
|
use crate::{
gui::{BuildContext, Ui, UiMessage, UiNode},
scene::EditorScene,
settings::{
debugging::{DebuggingSection, DebuggingSettings},
graphics::{GraphicsSection, GraphicsSettings},
move_mode::{MoveInteractionModeSettings, MoveModeSection},
},
GameEngine, Message, CONFIG_... |
/// Transform a traditional `for` loop into a parallel `for_each`
///
/// ```rust,ignore
/// for item in expr { /* body */ }
/// ```
///
/// becomes roughly:
///
/// ```rust,ignore
/// expr.into_par_iter().for_each(|item| { /* body */ });
/// ```
#[proc_macro_hack::proc_macro_hack]
pub use rayon_macro_hack::parallel;
... |
use crate::api::models::bridgechain::Bridgechain;
use crate::api::Result;
use crate::http::client::Client;
use std::borrow::Borrow;
use std::collections::HashMap;
pub struct Bridgechains {
client: Client,
}
impl Bridgechains {
pub fn new(client: Client) -> Bridgechains {
Bridgechains { client }
}
... |
// q0102_binary_tree_level_order_traversal
struct Solution;
use crate::util::TreeNode;
use std::cell::RefCell;
use std::rc::Rc;
impl Solution {
pub fn level_order(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<Vec<i32>> {
if let Some(rrc_root) = root {
let mut ret = vec![];
let mut l... |
pub(crate) use std::fs::Metadata;
use std::{ffi::OsStr, io, path::Path};
pub(crate) use fs_err::*;
/// Removes a file from the filesystem **if exists**.
pub(crate) fn remove_file(path: impl AsRef<Path>) -> io::Result<()> {
match fs_err::remove_file(path.as_ref()) {
Err(e) if e.kind() == io::ErrorKind::Not... |
use std::{
collections::{hash_map, HashMap},
fmt::Debug,
marker::PhantomData,
net::SocketAddr,
ops::Deref,
path::{Path, PathBuf},
sync::{
atomic::{AtomicU32, AtomicUsize, Ordering},
Arc,
},
time::Duration,
};
use async_trait::async_trait;
use bonsaidb_core::{
adm... |
#![allow(non_snake_case)]
extern crate sfml;
use crate::cpu::{Z80, Flags, UNPREFIXED_INSTRUCTION_TABLE, PREFIXED_INSTRUCTION_TABLE};
use sfml::{
graphics::{
Text, RenderTarget, RenderWindow, Color, Font, Transformable
},
};
const CHAR_SIZE: u32 = 14;
pub fn showRam(c: &Z80, startIndex: u16, nRows: u16... |
// cargo-deps: chrono
extern crate chrono;
fn main() {
println!("--output--");
println!("Hello");
} |
use std::path::Path;
extern crate sdl2;
use sdl2::pixels::Color;
use sdl2::rect::Rect;
use sdl2::render::Canvas;
use sdl2::render::TextureQuery;
use sdl2::ttf::{Font, Sdl2TtfContext};
use sdl2::video::Window;
use sdl2::Sdl;
const PADDING: u32 = 64;
pub struct Screen<'a> {
pub canvas: Canvas<Window>,
font: Fo... |
use crate::{
error::SendDuccError,
util::{
get_time_ms,
JsEngine,
},
Nonce,
};
use url::Url;
#[derive(Debug)]
pub enum QuizError {
Ducc(SendDuccError),
QuizAnswer(QuizAnswerError),
}
impl From<ducc::Error> for QuizError {
fn from(e: ducc::Error) -> Self {
Self::Ducc... |
pub mod entry;
pub mod file;
pub mod item;
pub use entry::{Entry, Status};
pub use file::Dotfile;
pub use item::Item;
|
#[macro_use]
extern crate serde_derive;
use azure_storage::table::{Batch, CloudTable, TableClient};
use std::error::Error;
use std::mem;
#[derive(Debug, Serialize, Deserialize)]
struct MyEntity {
data: String,
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
// First we retrieve the account n... |
use std::io;
use aoc2020;
fn main() {
aoc2020::run(25);
loop {
println!("Enter input: ");
let mut input = String::new();
io::stdin().read_line(&mut input).expect("Failed to read input");
let input : Vec<&str> = input.split_ascii_whitespace().collect();
if input.len() == ... |
//! Common IO primitives.
//!
//! These primitives are closely mirroring the definitions in
//! [`tokio-io`](https://docs.rs/tokio-io). A big difference is that these definitions are not tied
//! to `std::io::Error`, but instead allow for custom error types, and also don't require
//! allocation.
use core::fmt;
use c... |
use super::responses::RemoveNeighborsResponse;
use crate::Result;
use reqwest::Client;
/// Removes a list of neighbors to your node.
/// This is only temporary, and if you have your neighbors
/// added via the command line, they will be retained after
/// you restart your node.
pub async fn remove_neighbors(
client... |
#[macro_use]
extern crate criterion;
use criterion::{BatchSize, Criterion};
use hacspec_aes::*;
use hacspec_dev::rand::random_byte_vec;
use hacspec_lib::prelude::*;
fn benchmark(c: &mut Criterion) {
c.bench_function("AES 128 encrypt", |b| {
b.iter_batched(
|| {
let key = Key128... |
use frame::Frame;
use texture::{Pixel, Texture};
pub use self::skyline_packer::SkylinePacker;
mod skyline_packer;
pub trait Packer {
type Pixel: Pixel;
fn pack(
&mut self,
key: String,
texture: &Texture<Pixel = Self::Pixel>,
) -> Option<Frame>;
fn can_pack(&self, texture: &Te... |
use std::path::{Component, Path};
use quick_error::ResultExt;
pub use rodio::{queue::SourcesQueueOutput, Decoder, Device, Sample, Sink, Source, SpatialSink};
use serde::Deserialize;
use crate::{cache::download, error::Result, types::Chatsound, Chatsounds};
#[derive(Deserialize)]
pub struct GitHubApiFileEntry {
p... |
fn main() {
let mut v = std::vec::Vec::<Body>::new();
v.push(Body {
pos: [-3,15,-11],
vel: [0,0,0],
});
v.push(Body {
pos: [3,13,-19],
vel: [0,0,0],
});
v.push(Body {
pos: [-13,18,-2],
vel: [0,0,0],
});
v.push(Body {
pos: [6,0,-1],... |
use relalg::{Datum, ScalarExpr};
// Can copy-paste the examples from the tests in here to actually run them.
fn main() {
let __values_2 = vec![
vec![
ScalarExpr::Literal(Datum::Int(1i64)).eval(&Vec::new()),
ScalarExpr::Literal(Datum::Int(2i64)).eval(&Vec::new()),
Scalar... |
fn main(){
newfunction(23);
}
fn newfunction(x: i32){
println!("Hello {}",x);
} |
use crate::frame_counter::FrameCounter;
use std::cell::RefCell;
pub struct GraphicsState {
pub window: winit::window::Window,
pub(super) surface: wgpu::Surface,
pub(super) device: wgpu::Device,
pub(super) queue: wgpu::Queue,
pub(super) swap_chain_descriptor: wgpu::SwapChainDescriptor,
pub(supe... |
pub mod nuke;
pub mod package;
pub mod repo;
pub(crate) mod fbs {
fbs_build::include_fbs!("index");
}
pub trait Request {
type Error;
type Partial;
fn new_from_user_input(partial: Self::Partial) -> Result<Self, Self::Error>
where
Self: Sized;
}
pub fn make_lang_tag_map(value: String) -> ... |
use brotli::CompressorWriter;
use bytes::BufMut;
use std::io::{Read, Write};
use bytes::Buf;
use std::ffi::{CStr, CString};
pub fn brotli_compress_rs(buf: &Vec<u8>) -> Vec<u8> {
// (false, buf.clone())
let compressed_buf = Vec::with_capacity(buf.len());
let mut w = compressed_buf.writer();
let mut c =... |
#[derive(PartialOrd, PartialEq, Ord, Eq, Copy, Clone, Debug)]
pub enum Dir {
North,
East,
South,
West,
}
#[derive(PartialOrd, PartialEq, Ord, Eq, Copy, Clone, Debug)]
pub struct CoordinateSystem {
dx_east: i64,
dy_south: i64,
}
pub fn step(dir: Dir, coords: CoordinateSystem) -> (i64, i64) {
... |
fn main() {
tonic_build::compile_protos("proto/pahkat.proto").unwrap();
let gen_path = std::path::Path::new(&std::env::var("OUT_DIR").unwrap()).join("pahkat.rs");
let data = std::fs::read_to_string(&gen_path).unwrap();
let data = data.replace(
"::prost::Message)",
"::prost::Message, ::s... |
// Copyright 2019, 2020 Wingchain
//
// 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... |
#[derive(Debug)]
pub struct Rating {
pub value: i64,
}
|
use super::BlockId;
use crate::arena::resource::ResourceId;
use crate::libs::select_list::SelectList;
#[derive(Clone)]
pub struct Drawing {
drawing_texture_id: BlockId,
drawed_texture_id: BlockId,
}
impl Drawing {
pub fn new(drawing_texture_id: BlockId, drawed_texture_id: BlockId) -> Self {
Self {... |
struct Solution {}
impl Solution {
pub fn mirror_reflection(mut p: i32, mut q: i32) -> i32 {
while p%2 == 0 && q%2 == 0 {
p/=2;
q/=2;
}
1 - p%2 + q%2
}
}
fn main() {
println!("Hello, world!");
}
|
use std::borrow::Borrow;
use std::collections::HashMap;
use fluent_bundle::concurrent::FluentBundle;
use fluent_bundle::{FluentResource, FluentValue};
pub use unic_langid::{langid, langids, LanguageIdentifier};
pub fn lookup_single_language<T: AsRef<str>, R: Borrow<FluentResource>>(
bundles: &HashMap<LanguageIde... |
use super::{new_block_assembler_config, type_lock_script_code_hash};
use crate::utils::wait_until;
use crate::{Net, Node, Spec, DEFAULT_TX_PROPOSAL_WINDOW};
use ckb_app_config::CKBAppConfig;
use ckb_crypto::secp::{Generator, Privkey};
use ckb_hash::{blake2b_256, new_blake2b};
use ckb_types::{
bytes::Bytes,
core... |
use crate::{
arch::{self, KERNEL_STACK_SIZE, USER_STACK_TOP},
ctypes::*,
fs::{
devfs::SERIAL_TTY,
mount::RootFs,
opened_file::{Fd, OpenFlags, OpenOptions, OpenedFile, OpenedFileTable, PathComponent},
path::Path,
},
mm::vm::{Vm, VmAreaType},
prelude::*,
process... |
#[doc = "Register `CR2` reader"]
pub type R = crate::R<CR2_SPEC>;
#[doc = "Register `CR2` writer"]
pub type W = crate::W<CR2_SPEC>;
#[doc = "Field `ADON` reader - A/D Converter ON / OFF"]
pub type ADON_R = crate::BitReader<ADON_A>;
#[doc = "A/D Converter ON / OFF\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, Part... |
use crate::extensions::NodeExt as _;
use gdnative::prelude::*;
#[derive(NativeClass)]
#[inherit(CanvasLayer)]
#[user_data(user_data::ArcData<HUD>)]
#[register_with(Self::register_hud)]
/// Game state struct.
pub struct HUD;
#[methods]
impl HUD {
/// Create a new HUD.
pub fn new(_owner: &CanvasLayer) -> Self {
... |
use radix::node::Node;
use std::cmp::Ordering;
use std::mem;
pub type Tree<T> = Option<Box<Node<T>>>;
pub fn insert<T>(tree: &mut Tree<T>, mut key: &[u8], value: T) -> Option<T> {
let node = tree.as_mut().expect("Expected non-empty tree.");
let split_index = node.key
.iter()
.zip(key.iter())
... |
/*!
## Auxiliar functions to manipulate arrays
*/
use ndarray::prelude::*;
use ndarray_linalg::generate::random;
use log::info;
use std::time::Instant;
use std::cmp::Ordering;
use approx::relative_eq;
/// Generate a random highly diagonal symmetric matrix
pub fn generate_diagonal_dominant(dim: usize, sparsity: f6... |
use std::collections::HashSet;
use aoc_runner_derive::{aoc, aoc_generator};
#[aoc_generator(day1)]
pub fn input_generator(input: &str) -> Vec<i32> {
input.lines().map(|l| l.parse().unwrap()).collect()
}
#[aoc(day1, part1)]
pub fn solve_part1(input: &[i32]) -> i32 {
input.iter().sum()
}
#[aoc(day1, part2)]
p... |
use lopdf::Dictionary;
pub fn get_object_rect(field: &Dictionary) -> Result<(f64, f64, f64, f64), lopdf::Error> {
let rect = field
.get(b"Rect")?
.as_array()?
.iter()
.map(|object| {
object
.as_f64()
.unwrap_or(object.as_i64().unwrap_or(0)... |
//! **uvm_install_graph** is a helper library to visualize and traverse a unity installation manifest.
use petgraph::visit::NodeIndexable;
pub use daggy::petgraph;
use daggy::petgraph::graph::DefaultIx;
use daggy::petgraph::visit::Topo;
use daggy::Dag;
use daggy::NodeIndex;
pub use daggy::Walker;
use itertools::Itertoo... |
pub mod listener;
mod stream;
pub use stream::Stream;
pub enum SocketAddr {
Tcp(std::net::SocketAddr),
Unix(tokio::net::unix::SocketAddr),
}
|
#[doc = "Register `APB2RSTR` reader"]
pub type R = crate::R<APB2RSTR_SPEC>;
#[doc = "Register `APB2RSTR` writer"]
pub type W = crate::W<APB2RSTR_SPEC>;
#[doc = "Field `SYSCFGRST` reader - System configuration (SYSCFG) reset"]
pub type SYSCFGRST_R = crate::BitReader<SYSCFGRST_A>;
#[doc = "System configuration (SYSCFG) r... |
use ducc::Ducc;
use std::time::{
SystemTime,
UNIX_EPOCH,
};
const BROWSER_ENV_SHIM: &str = include_str!("./browser_env_shim.js");
pub struct JsEngine {
vm: Ducc,
}
impl JsEngine {
pub fn new() -> Result<Self, ducc::Error> {
let vm = Ducc::new();
vm.exec(BROWSER_ENV_SHIM, None, Default... |
use super::{
Expr,
Type,
ExprValue,
IfExpr,
BinOp,
UnaryOp
};
use crate::parser::token::Token;
use std::borrow::Borrow;
#[derive(Debug)]
pub struct TypedExpr<'a> {
token: Token<'a>,
/// Not actually a kind, but avoids having to call it r#type
kind: Type,
value: ExprValue<Typed... |
extern crate dmbc;
extern crate exonum;
extern crate exonum_testkit;
extern crate hyper;
extern crate iron;
extern crate iron_test;
extern crate mount;
extern crate serde_json;
pub mod dmbc_testkit;
use dmbc_testkit::{DmbcTestApiBuilder, DmbcTestKitApi};
use exonum::crypto;
use exonum::messages::Message;
use hyper::s... |
// Generated by `scripts/generate.js`
pub type VkTransformMatrix = super::super::khr::VkTransformMatrix;
#[doc(hidden)]
pub type RawVkTransformMatrix = super::super::khr::RawVkTransformMatrix; |
pub mod pathfinder;
|
mod abi;
mod crypto;
mod primitives;
|
//! Models for password reset
use std::fmt;
use std::time::SystemTime;
use base64::encode;
use uuid::Uuid;
use validator::Validate;
use stq_static_resources::TokenType;
use models::user::User;
use schema::reset_tokens;
#[derive(Serialize, Deserialize, Queryable, Insertable, Debug)]
#[table_name = "reset_tokens"]
pu... |
#![feature(generators, try_trait)]
extern crate aoc_runner;
extern crate pest;
#[macro_use] extern crate pest_derive;
#[macro_use] extern crate failure;
#[macro_use] extern crate aoc_runner_derive;
extern crate gen_iter;
extern crate num_integer;
pub mod common;
pub mod day1;
pub mod day2;
pub mod day3;
pub mod day... |
#[doc = "Register `FDCAN_TTTMK` reader"]
pub type R = crate::R<FDCAN_TTTMK_SPEC>;
#[doc = "Register `FDCAN_TTTMK` writer"]
pub type W = crate::W<FDCAN_TTTMK_SPEC>;
#[doc = "Field `TM` reader - Time Mark"]
pub type TM_R = crate::FieldReader<u16>;
#[doc = "Field `TM` writer - Time Mark"]
pub type TM_W<'a, REG, const O: u... |
// Generated by the capnpc-rust plugin to the Cap'n Proto schema compiler.
// DO NOT EDIT.
// source: protos/src/service.capnp
pub mod person {
#![allow(unused_imports)]
use capnp::capability::{FromClientHook, FromTypelessPipeline};
use capnp::{text, data, Result};
use capnp::private::layout;
use capnp::tra... |
use std::io::{BufReader, BufferedReader, Buffer, File, EndOfFile};
use std::comm::{channel, Sender, Receiver};
use std::vec::Vec;
use std::char;
use token::Token;
use token;
pub fn tokenize_str(code : &str) -> Vec<Token> {
let reader = BufReader::new(code.as_bytes());
let buf_reader = BufferedReader::new(read... |
use lazy_static::*;
use regex::Regex;
use std::collections::HashMap;
use crate::common::str_to_numbers;
pub fn get_rule_set(input: &str) -> HashMap<Vec<u8>, u8> {
lazy_static! {
static ref PARSING_EXPR: Regex =
Regex::new(r"^(?P<input>[#.]{5}) => (?P<output>[#.])").unwrap();
}
let mut... |
// q0002_add_two_numbers
use crate::util::ListNode;
struct Solution;
impl Solution {
pub fn add_two_numbers(
l1: Option<Box<ListNode>>,
l2: Option<Box<ListNode>>,
) -> Option<Box<ListNode>> {
let mut ret = vec![];
let mut flag = 0;
let mut l1 = l1;
let mut l2 =... |
use std::path::Path;
use anyhow::Result;
#[allow(dead_code)]
#[allow(unused_variables)]
pub fn parse_args(in_graph: &Path, rank_cutoff: Option<&f64>) -> Result<()> {
error!("Not implemented yet");
Ok(())
}
|
// q0164_maximum_gap
struct Solution;
impl Solution {
pub fn maximum_gap(mut nums: Vec<i32>) -> i32 {
if nums.len() < 2 {
return 0;
}
let build_buf = || {
let mut r = Vec::with_capacity(10);
for _ in 0..10 {
r.push(vec![]);
}
... |
use std::fs::File;
use resol_vbus::{DataSet, RecordingWriter};
use tokio::{net::TcpStream, prelude::*};
use tokio_resol_vbus::{Error, LiveDataStream, TcpClientHandshake};
fn main() {
// Create an recording file and hand it to a `RecordingWriter`
let file = File::create("test.vbus").expect("Unable to create o... |
use regex::Regex;
use std::fs::File;
use std::io::Read;
#[derive(Clone, Copy, PartialEq, Debug)]
pub enum Action {
MoveNorth,
MoveSouth,
MoveEast,
MoveWest,
TurnRight,
TurnLeft,
MoveForward,
}
#[derive(Debug)]
pub struct BoatPart1 {
angle: i32,
orientation_y: i32,
orientation_x... |
mod util;
use std::collections::HashMap;
use std::collections::HashSet;
use std::collections::VecDeque;
use std::io::BufRead;
use util::*;
struct Node {
children: HashSet<String>,
parent: HashSet<String>,
}
impl Node {
fn new() -> Node {
Node { children: HashSet::new(), parent: HashSet::new() }
... |
use core::f64::consts::*;
use crate::coord_plane::CartPoint;
use crate::coord_plane::PolarPoint;
use crate::projections::projection_types::ProjectionParams;
pub fn simple_equidistant_conic(params: ProjectionParams) -> Vec<CartPoint> {
match params {
ProjectionParams::PointsTwoStandardPar(points, phi_1, ph... |
use bytes::BufMut;
use futures::future::{self, Future};
use futures::sync::oneshot;
use futures::task;
use std::collections::{HashMap, VecDeque};
use std::iter;
use std::sync::{Arc, Mutex};
use super::{QuicError, QuicResult};
use codec::{BufLen, Codec};
use frame::{Frame, StreamFrame, StreamIdBlockedFrame};
use type... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.