text stringlengths 8 4.13M |
|---|
use core::mem::replace;
use crate::drivers::fe310_g002::UartDriver;
pub struct Peripherals {
pub uart_0: Option<UartDriver>,
}
impl Peripherals {
pub fn take_uart_0(&mut self) -> UartDriver {
let p = replace(&mut self.uart_0, None);
p.unwrap()
}
}
|
pub fn clamp(x: f64, min: f64, max: f64) -> f64 {
if x < min {
min
} else if x > max {
max
} else {
x
}
}
pub fn random() -> f64 {
rand::random()
}
pub fn degrees_to_radians(degrees: f64) -> f64 {
degrees * std::f64::consts::PI / 180.0
}
|
#![allow(dead_code)]
use std::ops::{Add, Sub, Neg, Mul, Div};
use std::cmp::{PartialEq, PartialOrd, Ordering};
pub use num::{Zero, One, Num};
use num;
use super::float::Float;
use super::Vec3;
use super::unit::{ToRad, Rad};
use std::fmt;
use clamp::Clamp;
use std::iter::IntoIterator;
/// Vec2 is a generic two-compone... |
use termion::raw::IntoRawMode;
use std::io::{Read, Write, stdout};
use termion::async_stdin;
use rand::Rng;
use std::{thread, time};
enum Directions {
Left,
Right,
Up,
Down,
None,
}
const ROWS: usize = 20;
const COLS: usize = 20;
fn main() {
let interval = time::Duration::from_millis(100);
... |
use quick_xml::{XmlReader, XmlWriter, Element, Event};
use quick_xml::error::Error as XmlError;
use fromxml::FromXml;
use toxml::ToXml;
use error::Error;
/// A representation of the `<guid>` element.
#[derive(Debug, Clone, PartialEq)]
pub struct Guid {
/// The value of the GUID.
pub value: String,
/// Ind... |
#![no_std]
extern crate alloc;
#[macro_use]
extern crate arrayref;
#[cfg(feature = "bpf")]
extern crate solana_sdk_bpf_no_std;
#[cfg(feature = "wasm")]
extern crate wasm_bindgen;
mod clock;
mod collection;
mod command;
mod poll;
mod tally;
pub use clock::*;
pub use collection::*;
pub use command::*;
pub use poll::*;... |
use memory_rs::process::process_wrapper::Process;
use std::env;
use std::ffi::CString;
use std::mem;
use std::process;
use std::ptr;
use winapi::shared::basetsd::DWORD_PTR;
use winapi::shared::minwindef::LPVOID;
use winapi::um::errhandlingapi::GetLastError;
use winapi::um::libloaderapi::{FreeLibrary, GetModuleHandleA, ... |
//! 2. 两数相加
//! https://leetcode-cn.com/problems/add-two-numbers/
// Definition for singly-linked list.
#[derive(PartialEq, Eq, Clone, Debug)]
pub struct ListNode {
pub val: i32,
pub next: Option<Box<ListNode>>,
}
impl ListNode {
#[inline]
fn new(val: i32) -> Self {
ListNode { next: None, val ... |
// Copyright (c) The Starcoin Core Contributors
// SPDX-License-Identifier: Apache-2.0
mod keypair_wallet;
mod mem_wallet_store;
mod mock_wallet_service;
pub use keypair_wallet::KeyPairWallet;
pub use mem_wallet_store::MemWalletStore;
pub use mock_wallet_service::MockWalletService;
|
/*
The following matches commands formatted as
Letter (possible space or comma) number (possible space or comma) number
*/
pub static SVG_COMMAND_GROUPING: &str = r"[a-zA-Z]([ ,]*[\-0-9]*[\.0-9]*[ ,]*)*";
/*
Used for splitting on either a comma or a space
TODO: As per the specification, a 0.5.... |
use crate::shapes;
use serde::Deserialize;
#[derive(Debug, Deserialize)]
pub struct Group {
#[serde(rename = "mn")]
pub match_name: String,
#[serde(rename = "nm")]
pub name: String,
#[serde(rename = "np")]
pub number_of_properties: i64,
#[serde(rename = "it")]
pub items: Vec<shapes::Any... |
use std::collections::HashMap;
pub mod item;
use super::product;
#[derive(Debug)]
pub struct Cart<'a, 'b: 'a, 's: 'b> {
pub id: u32,
items: &'a mut HashMap<u32, &'b mut item::Item<'b, 's>>,
}
impl<'a, 'b, 's>Cart<'a, 'b, 's> {
pub fn new(id: u32, items: &'a mut HashMap<u32, &'b mut item::Item<'b, 's>>) ->... |
#[derive(Debug)]
struct Vector {
x: f64,
y: f64,
z: f64,
}
impl Vector {
fn new(x: f64, y: f64, z: f64) -> Self {
Vector {
x: x,
y: y,
z: z,
}
}
fn dot_product(&self, other: &Vector) -> f64 {
(self.x * other.x) + (self.y * other.y) ... |
#![feature(proc_macro_hygiene, decl_macro)]
use crate::get::Movie;
#[macro_use]
extern crate rocket;
mod get;
mod db;
mod update;
fn main() {
// first insert the new movie
update::update_data(Movie {
title: "Parasite".to_string(),
year: "2020".to_string(),
plot: "me bumble me".to_string(),
... |
#[doc = "Register `FMC_CSQCFGR1` reader"]
pub type R = crate::R<FMC_CSQCFGR1_SPEC>;
#[doc = "Register `FMC_CSQCFGR1` writer"]
pub type W = crate::W<FMC_CSQCFGR1_SPEC>;
#[doc = "Field `CMD2EN` reader - CMD2EN"]
pub type CMD2EN_R = crate::BitReader;
#[doc = "Field `CMD2EN` writer - CMD2EN"]
pub type CMD2EN_W<'a, REG, con... |
use std::num::NonZeroU64;
use crate::exchange::{Exchange, types::{Event, EventBody}};
use crate::history::parser::EventProcessor;
use crate::lags::interface::NanoSecondGenerator;
use crate::trader::Trader;
use crate::types::{DateTime, SeedableRng, StdRng};
pub struct VoidNanoSecGen;
impl NanoSecondGenerator for Void... |
use std::alloc::Layout;
use std::cell::Cell;
use std::marker::PhantomData;
use std::ops::Deref;
use std::ptr::NonNull;
pub struct MyRc<T: ?Sized> {
inner: NonNull<RcInner<T>>,
_phantom: PhantomData<T>,
}
pub struct MyWeak<T: ?Sized> {
inner: NonNull<RcInner<T>>,
_phantom: PhantomData<T>,
}
struct RcI... |
//! This example demonstrates how [`Tables`](Table) can be comprised of other tables.
//!
//! * This first nested [`Table`] example showcases the [`Builder`] approach.
//!
//! * Note how a great deal of manual customizations have been applied to create a
//! highly unique display.
//!
//! * 🎉 Inspired by https://githu... |
#![macro_use]
use ast;
use name::*;
use span::*;
use ivar::Ivar;
use std::cell::RefCell;
use std::collections::HashMap;
use std::cmp::{Ord, Ordering};
use std::{fmt, hash, ops};
pub use self::Impled::*;
pub use self::Accessibility::*;
// In this file, the variable name prefix 'fq_' abbreviates fully_qualified_
// ... |
pub mod exercise01;
pub mod exercise02;
|
use itertools::Itertools;
use unicode_segmentation::UnicodeSegmentation;
pub trait Sorted {
fn sorted(&self) -> String;
}
impl Sorted for String {
fn sorted(&self) -> Self {
UnicodeSegmentation::graphemes(self.as_str(), true)
.sorted()
.collect::<String>()
}
}
|
use crate::types::InflightBlocks;
use crate::BLOCK_DOWNLOAD_TIMEOUT;
use ckb_types::prelude::*;
use ckb_types::{h256, H256};
use std::collections::HashSet;
use std::iter::FromIterator;
#[test]
fn inflight_blocks_count() {
let mut inflight_blocks = InflightBlocks::default();
// allow 2 peer for one block
a... |
#[allow(unused_imports)]
use log::{debug, info, warn};
use crate::{AsAttachment, AsBindTarget, BindTarget};
use js_sys::{Error, Float32Array, Object, Uint16Array, Uint8Array};
use serde::Serialize;
use std::marker::PhantomData;
use web_sys::{WebGl2RenderingContext as Context, WebGlTexture, WebglCompressedTextureS3tcSr... |
use nalgebra::na;
use ncollide::math::{N, LV, AV};
#[deriving(Eq, ToStr, Clone)]
pub struct VelocityConstraint {
normal: LV,
weighted_normal1: LV,
weighted_normal2: LV,
rot_axis1: AV,
weighted_rot_axis1: AV,
rot_axis2: AV,
weighted_rot_axis2: AV,
in... |
use std::ops::Range;
use std::fs;
use std::fmt;
use std::collections::HashMap;
use itertools::iproduct;
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum State {
Active,
Inactive,
}
impl State {
pub fn parse(c: char) -> State {
match c {
'#' => State::Active,
'.' => Sta... |
use crate::components::terrain::{Chunk, VoxelData};
use amethyst::{
assets::{AssetLoaderSystemData, Handle},
core::math::*,
core::{SystemDesc, Transform},
derive::SystemDesc,
ecs::prelude::*,
renderer::{types::Mesh, visibility::BoundingSphere, Material},
};
// generates meshes for chunks
#[der... |
use std::fmt;
#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct Transaction {
pub sender: String,
pub recipient: String,
pub amount: i64
}
// impl Display, get to_string for free
impl fmt::Display for Transaction {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "(... |
pub mod config;
pub mod constant;
pub mod error;
|
fn main(){
let s = "stressed";
let s: String = s.chars().rev().collect();
println!("{}", s);
}
|
#[doc = "Register `EXTI_EXTICR4` reader"]
pub type R = crate::R<EXTI_EXTICR4_SPEC>;
#[doc = "Register `EXTI_EXTICR4` writer"]
pub type W = crate::W<EXTI_EXTICR4_SPEC>;
#[doc = "Field `EXTI12` reader - EXTI12"]
pub type EXTI12_R = crate::FieldReader;
#[doc = "Field `EXTI12` writer - EXTI12"]
pub type EXTI12_W<'a, REG, c... |
use ggez::{Context, GameResult};
use ggez::graphics::{self, Mesh, DrawParam, DrawMode, Rect};
use na::{Vector2, Point2, Rotation2};
use std::f32::consts::PI;
const TWO_PI: f32 = PI * 2.0;
const CAR_DIMS: (f32, f32) = (20.0, 30.0); // (width, height)
const MAX_TURN_RATE: f32 = PI/2.0;
const MAX_WHEEL_ANGULAR_ACC: f32... |
use bodymovin::Bodymovin;
use std::path::Path;
#[test]
fn test_shapes() {
let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/shapes.json");
let loaded = Bodymovin::load(path).unwrap();
insta::assert_debug_snapshot!(loaded);
}
|
use crate::hal_prelude::*;
use glsl_to_spirv::ShaderType;
use std::error::Error;
use std::fmt;
use std::fs::{self, File};
use std::io::Read;
use std::path::Path;
type ShaderModule<B> = <B as gfx_hal::Backend>::ShaderModule;
#[derive(Debug)]
pub enum ShaderHandleError {
LoadFail(std::io::Error),
ShaderFail(gfx... |
#[doc = "Register `GCOMP` reader"]
pub type R = crate::R<GCOMP_SPEC>;
#[doc = "Register `GCOMP` writer"]
pub type W = crate::W<GCOMP_SPEC>;
#[doc = "Field `GCOMPCOEFF` reader - Gain compensation coefficient"]
pub type GCOMPCOEFF_R = crate::FieldReader<u16>;
#[doc = "Field `GCOMPCOEFF` writer - Gain compensation coeffic... |
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT license.
*/
#![allow(dead_code)] // Todo: Remove this when the disk index query code is complete.
use std::mem;
use std::vec::Vec;
use hashbrown::HashSet;
use crate::{
common::{ANNResult, AlignedBoxWithSlice},
model::{N... |
use super::prelude::*;
#[derive(Debug, Clone, PartialEq)]
pub struct Let {
pub name: Identifier,
pub value: Expr,
}
impl Display for Let {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
let out = format!("{} {} = {};", self.name, self.name, self.value);
write!(f, "{}", out)
}
}... |
use collections::string::String;
use system::error::Result;
pub mod ahci;
pub mod ide;
pub trait Disk {
fn name(&self) -> String;
fn on_irq(&mut self, irq: u8);
fn size(&self) -> u64;
fn read(&mut self, block: u64, buffer: &mut [u8]) -> Result<usize>;
fn write(&mut self, block: u64, buffer: &[u8]... |
use alloc::string::String;
use alloc::vec::Vec;
use serde::{Deserialize, Serialize};
pub type Result<T> = core::result::Result<T, self::Error>;
#[derive(Debug)]
pub enum Error {
EosError{
eos_err: ErrorResponse,
},
#[cfg(feature = "use-hyper")]
HttpRequestError {
request_err: hyper::Er... |
#![allow(unused_variables)]
///!
///! Implement the `Numeric` trait for arrays.
///!
use crate::prelude::*;
#[macro_export]
#[doc(hidden)]
macro_rules! _implement_numeric_unsigned_public {
($name:ident) => {
impl PartialOrd for $name {
#[cfg_attr(feature = "use_attributes", in_hacspec)]
... |
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - Control register"]
pub cr: CR,
#[doc = "0x04 - Interrupt mask register"]
pub imr: IMR,
#[doc = "0x08 - Status register"]
pub sr: SR,
#[doc = "0x0c - Interrupt Flag Clear register"]
pub ifcr: IFCR,
_reser... |
use std::io;
mod types;
mod consts;
mod cert;
pub use consts::*;
pub use types::CommonAddr;
pub use cert::{load_certs, load_keys, generate_cert_key};
#[cfg(target_os = "linux")]
pub use consts::PIPE_BUF_SIZE;
pub fn new_io_err(e: &str) -> io::Error {
io::Error::new(io::ErrorKind::Other, e)
}
#[allow(clippy::mut_... |
pub fn compute() -> String {
(::euler_library::math_library::square(::euler_library::math_library::sum_natural(100)) - ::euler_library::math_library::sum_natural_squares(100)).to_string()
}
|
fn main() {
let _: i8 = 127;
let _: i16 = 32_767;
let _: i32 = 2_147_483_647;
let _: i64 = 9_223_372_036_854_775_807;
let _: isize = 100; // the maximum value depends on the target architecture
let _: u8 = 255;
let _: u16 = 65_535;
let _: u32 = 4_294_967_295;
let _: u64 = 18_446_744_... |
#[doc = "Reader of register CH_CTRL_TRIG"]
pub type R = crate::R<u32, super::CH_CTRL_TRIG>;
#[doc = "Writer for register CH_CTRL_TRIG"]
pub type W = crate::W<u32, super::CH_CTRL_TRIG>;
#[doc = "Register CH_CTRL_TRIG `reset()`'s with value 0"]
impl crate::ResetValue for super::CH_CTRL_TRIG {
type Type = u32;
#[i... |
#[doc = "Reader of register FDCAN_TXBAR"]
pub type R = crate::R<u32, super::FDCAN_TXBAR>;
#[doc = "Writer for register FDCAN_TXBAR"]
pub type W = crate::W<u32, super::FDCAN_TXBAR>;
#[doc = "Register FDCAN_TXBAR `reset()`'s with value 0"]
impl crate::ResetValue for super::FDCAN_TXBAR {
type Type = u32;
#[inline(... |
// This solution could have been a lot shorter if I used raw &str instead of making a bunch of types
use std::collections::HashMap;
use std::str::FromStr;
use std::{error, result};
type BoxedError = Box<dyn error::Error>;
type Result<T> = result::Result<T, BoxedError>;
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)... |
use std::sync::{Arc, RwLock, RwLockReadGuard};
use super::super::nix_query_tree::exec_nix_store::{
ExecNixStoreRes, NixStoreRes,
};
use super::builder;
use super::prelude::*;
/// Sort order for the tree of nix store paths.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[repr(i32)]
pub enum SortOrder {
NixStore... |
use sqlx::SqlitePool;
#[derive(sqlx::FromRow, Debug)]
pub struct AccessUser {
pub id: i64,
pub user_id: i64,
pub file_id: i64,
pub access_id: i64,
}
impl AccessUser {
pub async fn new(user_id: i64, file_id: i64, access_id: i64) -> anyhow::Result<AccessUser> {
Ok(AccessUser {
id:... |
extern crate utils;
use std::env;
use std::io::{self, BufReader};
use std::io::prelude::*;
use std::fs::File;
use utils::*;
type Input = Vec<u32>;
#[derive(Eq, PartialEq, Copy, Clone, Debug)]
struct Spoken {
last_t: u32,
turns_apart: u32
}
fn solve(input: &Input) -> (usize, usize) {
const NEVER: Spoken ... |
// q0048_rotate_image
struct Solution;
impl Solution {
pub fn rotate(matrix: &mut Vec<Vec<i32>>) {
let mut ele_picked = vec![];
let n = matrix.len();
let mut start = 0;
let mut end = n - 1;
for i in 0..n / 2 {
for j in start..end {
ele_picked.pus... |
#![cfg(target_os="android")]
#![allow(non_snake_case)]
#[macro_use]
extern crate log;
extern crate android_logger;
use log::Level;
use log::{info, trace, warn};
use android_logger::{Config as LoggerConfig,FilterBuilder};
mod models;
mod oauth2client;
pub use models::{Options, Credentials, Config};
pub use oauth2clie... |
use rayon::prelude::*;
use std::thread;
use std::time::Duration;
pub fn have_a_try() {
let mut arr = [0, 7, 2, 1];
arr.par_iter_mut().for_each(|n| {
println!("1");
thread::sleep(Duration::from_millis(5000));
*n += 1
});
println!("{:?}", arr);
assert!(arr.par_iter().all(|n| ... |
#![feature(const_option, type_changing_struct_update)]
mod commands;
mod ss58;
mod utils;
use bytesize::ByteSize;
use clap::{Parser, ValueHint};
use ss58::parse_ss58_reward_address;
use std::fs;
use std::num::NonZeroU8;
use std::path::PathBuf;
use std::str::FromStr;
use subspace_core_primitives::PublicKey;
use subspa... |
use hyper::server::conn::AddrStream;
use hyper::service::{make_service_fn, service_fn};
use hyper::StatusCode;
use hyper::{Body, Response, Server};
use std::convert::Infallible;
use std::net::SocketAddr;
use std::sync::{Arc, Mutex};
//Internal modules
pub mod worker;
use worker::Worker;
pub mod id_generator;
use id_g... |
use image::EncodableLayout;
use super::reqrep::{Reply, Request};
use crate::serial::{deserialize, serialize};
use crate::Result;
use async_executor::Executor;
use async_std::sync::Arc;
use async_zmq;
use futures::FutureExt;
pub struct GatewayService;
enum NetEvent {
RECEIVE(async_zmq::Multipart),
SEND(async... |
use nu_test_support::{nu, pipeline};
#[test]
fn better_empty_redirection() {
let actual = nu!(
cwd: "tests/fixtures/formats", pipeline(
r#"
ls | each { |it| nu --testbin cococo $it.name }
"#
));
eprintln!("out: {}", actual.out);
assert!(!actual.out.contains('2'));
... |
pub mod custom_hkdf;
pub mod custom_pbkdf2;
#[cfg(feature = "safe_api")]
pub mod other_argon2i;
pub mod other_hkdf;
#[cfg(feature = "safe_api")]
pub mod pynacl_argon2i;
#[cfg(feature = "safe_api")]
pub mod ref_argon2i;
pub mod wycheproof_hkdf;
use orion::hazardous::{kdf::hkdf::*, mac::hmac};
pub fn hkdf_test_runner(
... |
fn print_grid(grid: &mut HashMap<Point,char>) {
let min_x = (*grid.iter().min_by_key(|&(pt, _)| pt.x).unwrap().0).x;
let max_x = (*grid.iter().max_by_key(|&(pt, _)| pt.x).unwrap().0).x;
let min_y = (*grid.iter().min_by_key(|&(pt, _)| pt.y).unwrap().0).y;
let max_y = (*grid.iter().max_by_key(|&(pt, _)| p... |
use std::io;
pub trait Day {
fn tag(&self) -> &str;
fn part1(&self, _input: &dyn Fn() -> Box<dyn io::Read>) {}
fn part2(&self, _input: &dyn Fn() -> Box<dyn io::Read>) {}
} |
use kompact::prelude::*;
use kompact::config_keys::system::LABEL;
use kompact::config_keys::system::THREADS;
use kompact::executors::crossbeam_workstealing_pool;
use omnipaxos::leader_election::ballot_leader_election::messages::BLEMessage;
use omnipaxos::leader_election::ballot_leader_election::messages::HeartbeatMsg... |
//! The Cargo "compile" operation.
//!
//! This module contains the entry point for starting the compilation process
//! for commands like `build`, `test`, `doc`, `rustc`, etc.
//!
//! The `compile` function will do all the work to compile a workspace. A
//! rough outline is:
//!
//! - Resolve the dependency graph (see... |
use std::fmt;
use std::ops::Not;
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum Player {
White,
Black
}
impl Not for Player {
type Output = Player;
fn not(self) -> Player {
match self {
Player::White => Player::Black,
Player::Black => Player::White
}
}
}
#[derive(Copy, Clone, Debug, PartialEq... |
#[macro_use]
extern crate lazy_static;
extern crate regex;
use regex::Captures;
use regex::Regex;
use std::thread;
const NUMBER_OF_ITERATIONS: i32 = 300000;
const THREADS_NUMBER: i32 = 4;
fn main() {
let start = std::time::SystemTime::now();
let text = "[subject]Czym jest Lorem Ipsum?[/subject]
[body]Lorem ... |
//! This example demonstrates the fundemental qualities of the [crate](https://crates.io/crates/tabled) [`tabled`].
//!
//! * [`tabled`] is powered by convenient [procedural macros](https://doc.rust-lang.org/reference/procedural-macros.html#procedural-macros)
//! like [`Tabled`]; a deriveable trait that allows your cus... |
use crate::entities::point::StoragePoint;
use crate::entities::point::{NewPoint, Point, QueryOptions};
use crate::entities::series::{NewSeries, Series};
use bincode::{deserialize, serialize};
use rocksdb::{Direction, IteratorMode, WriteBatch, DB};
use std::fmt;
use std::path::Path;
use std::str;
#[derive(PartialEq, De... |
use super::Result;
use crate::model::Source;
pub trait SourceService: Send + Sync {
fn get_source_by_id(&self, id: &str) -> Result<Source>;
}
|
use rand::Rng;
use serde_derive::{Deserialize, Serialize};
use crate::types::ItemMap;
#[derive(Debug, Serialize, Deserialize)]
pub struct Enemy {
hp: i32,
xp: u32,
damage: u32,
name: String,
desc: String,
inspection: String,
is_angry: bool,
loot: ItemMap,
}
impl Enemy {
pub fn xp... |
use std::fmt::Debug;
use std::process::exit;
use botan::base64_decode;
use crate::Response;
pub static SERVER_PRIVATE: &'static str = include_str!("/code/server/server.pem");
pub static USER_PUBLIC : &'static str = include_str!("/code/keys/keeper_pub.pem");
#[inline(always)]
pub fn get_private() -> botan::Privkey {
... |
macro_rules! create_impl {
($field:ident, $ty:ty) => {
#[macro_export]
macro_rules! $field {
($shape:ident) => {
impl<'s> $shape<'s> {
pub fn $field(mut self, $field: $ty) -> Self {
self.$field = $field;
... |
// Copyright (c) 2021, Roel Schut. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
use crate::*;
use crate::utils::singleton::SingletonInstance;
pub const ON_INSTANCE_NODE: &str = "_on_instance_node";
#[derive(NativeClass)]
#[inherit(Node)]... |
//! Extractors for parsing message body.
use {
super::Extractor,
crate::{
error::Error,
future::{Poll, TryFuture},
input::{
body::{ReadAll, RequestBody},
header::ContentType,
localmap::LocalData,
Input,
},
},
bytes::Bytes,
... |
use carmen_core::gridstore::{coalesce, stack_and_coalesce, stackable};
use carmen_core::gridstore::{
CoalesceContext, GridEntry, GridKey, GridStore, GridStoreBuilder, MatchKey, MatchKeyWithId,
MatchOpts, PhrasematchSubquery,
};
use failure::Error;
use neon::declare_types;
use neon::prelude::*;
use neon_serde::... |
/// Test a call to this lib
/// # Example
///
/// ```
/// // You can have rust code between fences inside the comments
/// // If you pass --test to `rustdoc`, it will even test it for you!
/// use code_timer as timer;
/// pub fn main(){
/// timer::test_call();
/// println!("main called");
/// }
/// ```
pu... |
use crate::BalanceOf;
use super::{Config, Module, LiquidityRewards};
use pallet_staking::EraPayout;
use pallet_staking_reward_fn::compute_inflation;
use sp_runtime::traits::{Zero, Saturating};
use sp_runtime::{Perbill, RuntimeDebug};
use codec::{Encode, Decode};
use sp_std::{prelude::*};
use frame_support::{StorageValu... |
extern crate dmbc;
extern crate exonum;
extern crate exonum_testkit;
extern crate hyper;
extern crate iron;
extern crate iron_test;
extern crate serde_json;
extern crate mount;
pub mod dmbc_testkit;
use hyper::status::StatusCode;
use exonum::messages::Message;
use exonum::crypto;
use dmbc_testkit::{DmbcTestApiBuilder... |
use crate::io::request::Request;
#[cfg(feature = "libcouchbase")]
mod lcb;
#[cfg(feature = "libcouchbase")]
use crate::io::lcb::IoCore;
pub mod request;
pub struct Core {
io_core: IoCore,
}
impl Core {
pub fn new(connection_string: String, username: String, password: String) -> Self {
Self {
... |
/// An enum to represent all characters in the PhaistosDisc block.
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
pub enum PhaistosDisc {
/// \u{101d0}: '𐇐'
SignPedestrian,
/// \u{101d1}: '𐇑'
SignPlumedHead,
/// \u{101d2}: '𐇒'
SignTattooedHead,
/// \u{101d3}: '𐇓'
SignCaptive,
... |
#[doc = "Register `KR` writer"]
pub type W = crate::W<KR_SPEC>;
#[doc = "Key value\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u16)]
pub enum KEY_AW {
#[doc = "21845: Enable access to PR, RLR and WINR registers (0x5555)"]
Enable = 21845,
#[doc = "43690: Reset the watchdog valu... |
#![feature(mpsc_select)]
extern crate rand;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
pub struct HostResolver {
next_host_id: Arc<AtomicUsize>,
hosts: Vec<String>
}
impl HostResolver {
pub fn new(hosts: Vec<String>) -> HostResolver {
info!("All available hosts: {:?}", h... |
use actix_web::client::{ClientRequest, ClientResponse};
use actix_web::{HttpRequest, HttpResponse};
use chrono::prelude::*;
use inflector::Inflector;
use yansi::Paint;
pub fn log_incoming_request(req: &HttpRequest, verbose: bool) -> String {
let conn_info = req.connection_info();
let local_time = Local::now();... |
#[derive(PartialEq, Debug)]
pub enum Token<'a> {
// Basic Syntax Blocks
Assign, // Assignment "="
Comma, // Separator ","
Semicolon, // End of statement ";"
LParen, // Left Parenthesis "("
RParen, // Right Parenthesis ")"
LBrace, // Left Brace "{"
RBrace, // Right Brac... |
use crate::components;
use crate::indices::{EntityId, UserId};
use crate::scripting_api::OperationResult;
use crate::storage::views::View;
use serde::{Deserialize, Serialize};
use tracing::{debug, trace};
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct MineIntent {
pub bot: EntityId,
pub re... |
use std::{cmp::Ordering, fmt::Display, iter};
fn main() {
let mut f = Field::new(1000);
for line in input().filter(|line| line.col1 == line.col2 || line.row1 == line.row2) {
f.apply(line);
}
println!("First solution: {}", f.overlaps());
let mut f = Field::new(1000);
for line in input()... |
use crate::sidebar::make_section;
use crate::{
gui::{BuildContext, Ui, UiMessage, UiNode},
physics::{Joint, RigidBody},
scene::commands::{physics::SetJointConnectedBodyCommand, SceneCommand},
send_sync_message,
sidebar::{
make_text_mark,
physics::joint::{
ball::BallJointS... |
use anyhow::Result;
use regex::Regex;
/// Attempt to validate password policy.
fn validate_sled_policy(min_times: usize, max_times: usize, c: char, line: &str) -> bool {
let count = line.chars().filter(|a| *a == c).count();
count >= min_times && count <= max_times
}
pub fn day2() -> Result<()> {
let passw... |
extern crate bincode;
extern crate serde;
use crypto::sha2::Sha256;
use base64::
{
encode_config,
};
use base64::
{
decode_config,
DecodeError,
};
use crypto::digest::Digest;
use std::hash::{Hash, Hasher};
use serde::{Serialize, Deserialize};
use crate::system::
{
System,
ReadWriteError,
};
use st... |
use crate::ast;
use crate::{Parse, ParseError, ParseErrorKind, Parser, Spanned, ToTokens};
/// A literal value
#[derive(Debug, Clone, ToTokens, Spanned)]
pub enum Lit {
/// A unit literal
Unit(ast::LitUnit),
/// A boolean literal
Bool(ast::LitBool),
/// A byte literal
Byte(ast::LitByte),
//... |
#[macro_use]
extern crate lazy_static;
use actix_web::{HttpServer, App};
use actix_web::middleware::Logger;
use crate::mysql::spawn_queue;
use crate::collector::spawn_collector;
mod appdata;
mod endpoints;
mod mysql;
mod common;
mod collector;
#[actix_web::main]
pub async fn main() -> std::io::Result<()> {
print... |
use crate::fetch_path;
use color_eyre::eyre::{eyre, Result, WrapErr};
use futures::future::try_join_all;
use lazy_static::lazy_static;
use regex::Regex;
use std::fmt;
use std::fs::File;
use std::io::Write;
use std::path::PathBuf;
pub struct ErrnoFile<'a>(&'a Vec<Errno>);
impl<'a> fmt::Display for ErrnoFile<'a> {
... |
#[doc = "Register `CCIPR2` reader"]
pub type R = crate::R<CCIPR2_SPEC>;
#[doc = "Register `CCIPR2` writer"]
pub type W = crate::W<CCIPR2_SPEC>;
#[doc = "Field `LPTIM1SEL` reader - LPTIM1 kernel clock source selection others: reserved, the kernel clock is disabled"]
pub type LPTIM1SEL_R = crate::FieldReader;
#[doc = "Fi... |
pub mod world{
pub use SmolCommon::WorldCommon;
pub use SmolHBSECS::world::World;
}
pub mod entity{
pub use SmolCommon::entity::EntityCommon;
pub use SmolHBSECS::{Entity, EntityStorage};
}
pub mod component{
pub use SmolCommon::component::{Component, ComponentStorage};
pub use SmolHBSECS::com... |
use matrices::Matrix4;
use shapes::Shape;
use tuples::Tuple;
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum PatternKind {
Stripe(Tuple, Tuple),
Gradient(Tuple, Tuple),
Ring(Tuple, Tuple),
Checkers(Tuple, Tuple),
TestPattern,
}
impl Default for PatternKind {
fn default() -> PatternKind {
... |
use super::*;
#[test]
fn create_1() {
assert_eq!(
Table::create()
.table(Glyph::Table)
.col(
ColumnDef::new(Glyph::Id)
.integer_len(11)
.not_null()
.auto_increment()
.primary_key()
... |
use clap::{App, ArgMatches, SubCommand};
use std::path::Path;
use database::DB;
use utils::get_bookmarks_from_html;
pub fn make_subcommand<'a, 'b>() -> App<'a, 'b> {
SubCommand::with_name("import")
.about("Import bookmark")
.arg_from_usage("<FILE> 'Import bookmarks from html file'")
}
pub fn exec... |
use std::fs::read_to_string;
use regex::{Regex};
use std::collections::{HashSet, HashMap};
use itertools::Itertools;
const INPUT_FILE: &str = "data/day_19.txt";
const TEST_REPLACEMENTS: &str = r#"H => HO
H => OH
O => HH"#;
fn parse_replacements(s: &str) -> Vec<(String, String)> {
s.lines().map(|l| {
let ... |
mod message;
fn main() {
match message::recv() {
Ok(()) => {},
Err(err) => println!("Error: {:?}", err),
}
}
|
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT license.
*/
#![warn(missing_debug_implementations, missing_docs)]
//! Aligned allocator
extern crate cblas;
extern crate openblas_src;
use cblas::{sgemm, snrm2, Layout, Transpose};
use rayon::prelude::*;
use std::{
cmp::{m... |
use wasm_bindgen::JsCast;
pub fn html_image_element() -> web_sys::HtmlImageElement {
web_sys::window()
.unwrap()
.document()
.unwrap()
.create_element("img")
.unwrap()
.dyn_into::<web_sys::HtmlImageElement>()
.unwrap()
}
pub fn html_canvas_element() -> web_s... |
fn insertion_sort(array_A: &mut [int, ..6]) {
// Implementation of the traditional insertion sort algorithm in Rust
// The idea is to both learn the language and re visit classic (and not so much)
// algorithms.
// This algorithm source has been extracted from "Introduction to Algorithms" - Cormen
let mut i: int;... |
use core;
use crust;
use memory::LinkedList;
use mantle;
use mantle::KError;
use kobject::*;
use mantle::kernel;
pub struct UntypedAllocator {
small_pages: LinkedList<Untyped>,
large_pages: LinkedList<Untyped>,
stashed: LinkedList<UntypedSet>,
}
impl UntypedAllocator {
pub fn add_oversize_block(&mut s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.