text stringlengths 8 4.13M |
|---|
// Copyright 2021 The Simlin Authors. All rights reserved.
// Use of this source code is governed by the Apache License,
// Version 2.0, that can be found in the LICENSE file.
use std::collections::hash_map::Entry;
use std::collections::HashMap;
use std::result::Result as StdResult;
use float_cmp::approx_eq;
use cra... |
//! Definition of `Endpoint`.
use {
crate::{
error::Error,
future::TryFuture,
generic::{Func, Tuple},
},
futures01::IntoFuture,
std::marker::PhantomData,
};
/// A trait representing the process to be performed when a route matches.
pub trait Endpoint<T> {
type Output;
t... |
pub use {EventFlags, EventLoop, RetValue, EventBuffer, now_micro};
use std::fmt;
use std::cell::Cell;
use std::cmp::{Ord, Ordering};
use std::hash::{self, Hash};
use std::any::Any;
use std::io::Result;
use psocket::{TcpSocket, SOCKET};
extern crate time;
pub type CellAny = Cell<Option<Box<dyn Any>>>;
pub type Accept... |
use anyhow::{anyhow, Context, Error};
use crypto::Crypto;
use crypto::UncryptedVaultFile;
use key::Pem;
use key::PrivateKey;
use key::PublicKey;
use proto::VaultFile;
use std::collections::{HashMap, HashSet};
use std::fs;
use std::fs::{File, FileType};
use std::io::Read;
use std::path::Path;
use globset::Glob;
use toml... |
#![feature(proc_macro_hygiene, type_ascription)]
use linux::{
syscall, lmem,
kty::{CAP_LAST_CAP, k_ulong, __user_cap_data_struct, __u32, c_int},
util::io::{Write as X},
};
use std::{
mem,
io::{Write},
};
use linux::time::clock::{REAL, MONO};
fn set(caps: &[__user_cap_data_struct; 2], cap: c_int) -... |
mod reader;
mod writer;
mod message;
use std::net::SocketAddr;
use std::{io, fmt, mem, time};
use std::net::TcpStream;
use chrono::{DateTime, Utc};
pub use self::message::Message;
use self::reader::Reader;
use self::writer::Writer;
use socket::Socket;
use torrent::{Torrent, Bitfield};
use throttle::Throttle;
use con... |
#[doc = "Register `CCIPR2` reader"]
pub type R = crate::R<CCIPR2_SPEC>;
#[doc = "Register `CCIPR2` writer"]
pub type W = crate::W<CCIPR2_SPEC>;
#[doc = "Field `USART11SEL` reader - USART11 kernel clock source selection Set and reset by software. others: reserved, the kernel clock is disabled"]
pub type USART11SEL_R = c... |
use std::{cmp::max, usize};
use cgmath::Vector3;
use crate::geom::*;
const SAMPLE_DENSITY: f32 = 1.0;
#[derive(Clone, Copy, Debug)]
pub struct Contact<T: Copy> {
pub a: T,
pub b: T,
pub mtv: Vec3,
}
pub fn restitute_dyn_stat<S1: Shape, S2: Shape>(
ashapes: &mut [S1],
avels: &mut [Vec3],
bsh... |
// Copyright 2014 The Gfx-rs Developers.
//
// 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 ag... |
use std::collections::HashMap;
use crate::Opa;
impl Opa {
/// Health Check
pub async fn health(&self) {
let resp = reqwest::get(format!("{}/health", self.ip())).await.unwrap();
// .json()
// .await
// .unwrap();
println!("{:#?}", resp);
}
}
#[cfg(test)]
mod tests ... |
use std::{fmt::Write, sync::Arc};
use eyre::Report;
use rosu_v2::prelude::{GameMode, GameMods, OsuError, Score};
use twilight_model::{
application::interaction::{
application_command::{CommandDataOption, CommandOptionValue},
ApplicationCommand,
},
id::{marker::UserMarker, Id},
};
use crate... |
use game_state;
use std::str;
pub fn get_bishop_moves(state: &game_state::GameState, piece_coord: Vec<u8>) -> Vec<String> {
let mut can_move_here = true;
let mut allowed_bishop_moves: Vec<String> = Vec::new();
//down right
let down_right = (1i8,1i8);
//up right
let up_right = (1i8,-1i8);
... |
#[doc = "Register `APB1SMENR1` reader"]
pub type R = crate::R<APB1SMENR1_SPEC>;
#[doc = "Register `APB1SMENR1` writer"]
pub type W = crate::W<APB1SMENR1_SPEC>;
#[doc = "Field `TIM2SMEN` reader - TIM2 timer clocks enable during CPU1 Sleep mode"]
pub type TIM2SMEN_R = crate::BitReader;
#[doc = "Field `TIM2SMEN` writer - ... |
use crate::build_options::CargoOptions;
use crate::target::Arch;
use crate::BuildOptions;
use crate::PlatformTag;
use crate::PythonInterpreter;
use crate::Target;
use anyhow::{anyhow, bail, Context, Result};
use pep508_rs::{MarkerExpression, MarkerOperator, MarkerTree, MarkerValue};
use std::path::Path;
use std::path::... |
use alloc::boxed::Box;
use alloc::collections::BTreeMap;
use alloc::string::String;
use spin::{Once, RwLock, RwLockReadGuard, RwLockWriteGuard};
mod device;
pub use self::device::Device;
pub static DEVICE_MAP: Once<RwLock<BTreeMap<String, Box<device::Device>>>> = Once::new();
pub fn devices() -> RwLockReadGuard<'st... |
use colored::*;
use std::fmt;
use anyhow::Result;
use serde::de;
use serde::de::{MapAccess, Unexpected, Visitor};
use serde::export::Formatter;
use serde::ser::SerializeMap;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::str::FromStr;
use strum;
use strum::EnumProperty;
use strum::IntoEnumIte... |
#[doc = "Reader of register DDRCTRL_DFIUPD1"]
pub type R = crate::R<u32, super::DDRCTRL_DFIUPD1>;
#[doc = "Writer for register DDRCTRL_DFIUPD1"]
pub type W = crate::W<u32, super::DDRCTRL_DFIUPD1>;
#[doc = "Register DDRCTRL_DFIUPD1 `reset()`'s with value 0x0001_0001"]
impl crate::ResetValue for super::DDRCTRL_DFIUPD1 {
... |
pub mod complex {
use std::ops::{Add, AddAssign, Mul};
#[derive(Copy, Clone)]
pub struct Complex {
pub imaginary: f64,
pub real: f64,
}
impl Complex {
pub fn new(real: f64, imaginary: f64) -> Complex {
Complex {
real,
imaginary,
}
}
pub fn square(&mut self) {
let squared_real = self.r... |
use crate::{errors::Error, Filter, Pipeline};
use std::collections::HashMap;
pub fn parse_pipeline(
filter_registry: &HashMap<String, Box<dyn Filter>>,
query: String,
) -> Result<Pipeline, Error> {
let mut lexer = Lexer::new(query);
let tokens = lexer.tokenize()?;
if tokens.is_empty() {
re... |
use chrono::{prelude::*};
use std::collections::HashSet;
use std::convert::TryFrom;
use url::Url;
use crate::block::*;
use crate::transaction::*;
pub struct Blockchain{
pub chain: Vec<Block>,
pub transactions: Vec<Transaction>,
pub nodes: HashSet<String>,
me: String,
mining_fee: u64,
node_addr... |
// pub struct TraitObject {
// pub data: *mut (),
// pub vtable: *mut (),
// }
// struct FooVtable {
// destructor: fn(*mut ()),
// size: usize,
// align: usize,
// method: fn(*const ()) -> String,
// }
// http://doc.rust-lang.org/book/static-and-dynamic-dispatch.html#representation
fn main... |
pub struct PascalsTriangle {
row_count: u32,
}
impl PascalsTriangle {
pub fn new(row_count: u32) -> Self {
PascalsTriangle { row_count }
}
pub fn rows(&self) -> Vec<Vec<u32>> {
let mut triangle = vec![];
for row in 0..self.row_count {
triangle.push(PascalsTriangle::... |
fn main() {
go1();
}
// main 関数で panic する
fn go1() {
panic!("このプログラムは動きません");
}
// 引数の有無で panic する
fn go2() {
let args = std::env::args().collect::<Vec<String>>();
if args.len() <= 1 {
panic!("パラメータは必須です");
} else {
for (i,s) in args.iter().enumerate() {
println!("{}: ... |
extern crate octocrab;
use chrono::{DateTime, Utc};
use octocrab::models::User;
use reqwest::Url;
use serde::{Deserialize, Serialize};
use crate::*;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct PullRequest {
pub number: u64,
pub created_at: DateTime<Utc>,
pub up... |
extern crate bindgen;
use std::env;
use std::path::{Path, PathBuf};
fn main() {
let dir = env::var("CARGO_MANIFEST_DIR").unwrap();
let helpers = Path::new(&dir).join("./helpers");
// compile helpers lib
cc::Build::new()
.file(helpers.join("helpers.c"))
.flag("-Werror")
.flag("... |
use amethyst::{
core::{Time, Transform},
ecs::prelude::{Join, Read, ReadStorage, System, WriteStorage},
input::{InputHandler, StringBindings},
};
use crate::components::map::Pannable;
use crate::utilities::Clampable;
pub struct PanningSystem;
impl PanningSystem {}
impl<'s> System<'s> for PanningSystem {... |
use log::debug;
use log::warn;
use std::collections::HashMap;
use std::fmt;
use std::io::{self, BufWriter, Write};
use std::ops::Deref;
use std::path::{Path, PathBuf};
use std::sync::{Arc, RwLock};
use ownedbytes::OwnedBytes;
use stable_deref_trait::StableDeref;
use super::{AntiCallToken, Directory, TerminatingWrite,... |
//use id::{MsgPackId};
use read::value::{Value};
use read::reader::{MsgPackReader};
use std::io::{Read};
//use std::iter::{IntoIterator};
/*
enum MsgPackIteratorState
{
Free,
Map(usize),
Array(usize)
}
* */
/*
enum MsgPackValueHandle
{
Int...
}
*/
//bytes readed
pub struct MsgPackIterator<'a, T: 'a>
where T:... |
pub mod chart_type;
pub mod traffic_chart;
|
use std::collections::HashMap;
use std::sync::{Condvar, Mutex, MutexGuard};
use std::thread::ThreadId;
use std::vec::IntoIter;
use super::interning;
use svm_types::Type;
use lazy_static::lazy_static;
lazy_static! {
/// Stores for each interned type its number of live instances.
/// In case a value is negati... |
use reqwest::blocking::RequestBuilder;
use serde::Serialize;
use crate::framework::auth::Credentials;
use crate::framework::reqwest_adaptors::match_reqwest_method;
use crate::framework::{
apiclient::ApiClient, auth, auth::AuthClient, endpoint, response, response::map_api_response,
Environment, HttpApiClient, H... |
// ctl_error.rs
#[derive(Debug, Fail)]
pub enum SysctlError {
#[fail(display = "no such sysctl: {}", _0)]
NotFound(String),
#[fail(display = "no matching type for value")]
#[cfg(not(target_os = "macos"))]
UnknownType,
#[fail(display = "Error extracting value")]
ExtractionError,
#[fai... |
use crate::comp::{Comp, HtmlCtx};
use crate::query::Query;
use crate::view;
pub struct DataTable {
pub query: Query,
}
impl Comp for DataTable {
fn html(&self, mut c: HtmlCtx) {
// This render function could maybe be closure with a flexible type?
// (would possibly like to return Result here?)... |
// Copyright 2021 Parity Technologies (UK) Ltd.
// This file is part of Cumulus.
// Cumulus 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 your option) any later ... |
pub mod client;
pub mod error;
pub mod response;
pub use client::{EsClient, EsCmd, EsResult};
pub use error::{Error, Result};
pub use response::{
BulkResponse, CatIndicesResponse, Hit, HitsWrapper, ItemError, ScrollResponse, SearchResponse,
Shards,
};
#[cfg(not(feature = "v5"))]
pub use response::HitsTotal;
|
#![no_std]
#![no_main]
use cortex_m::asm::delay;
use cortex_m_rt::entry;
#[cfg(feature = "enable-debug")]
use cortex_m_semihosting::hprintln;
use panic_semihosting as _;
// As we don't use `PAC` and `HAL` in this example, and we didn't touch the `Clock` and
// `Interrupt` yet. That's why we use a dumb version `dela... |
use super::super::{components, resources};
use specs::{Read, ReadStorage, System, WriteStorage};
pub struct Visibility;
const THETA_BUCKET_COUNT: i32 = 1000;
const THETA_BUCKET_SIZE: f32 = 2. * std::f32::consts::PI / (THETA_BUCKET_COUNT as f32);
impl<'a> System<'a> for Visibility {
type SystemData = (
sp... |
extern crate stdweb;
#[macro_use]
extern crate webcomponent_rs;
use stdweb::{ web::{ HtmlElement, INode, Node, IElement, IEventTarget, event::{ ClickEvent }} };
use webcomponent_rs::*;
#[derive(Default)]
struct TestComponent {
}
fn construct_dom(element: HtmlElement) {
element.append_child(&Node::from_html("<div>... |
// Copyright 2021 Red Hat, Inc.
//
// 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 i... |
use crate::{Alphabet, TestSpace, TestSpaceTextFile};
use std::fs;
use std::io::{BufRead, BufReader, BufWriter, Read, Write};
use std::path;
impl TestSpaceTextFile {
pub fn new(path_to_file: path::PathBuf, alphabet: Alphabet) -> TestSpaceTextFile {
TestSpaceTextFile {
alphabet,
lines... |
//! Abstracts architecture details.
//!
//! The job of this module is to have submodules for each architecture and to
//! provide interfaces to them.
use core::time::Duration;
use memory::address_space::AddressSpace;
use memory::{MemoryArea, PageFlags, PhysicalAddress, VirtualAddress};
use multitasking::stack::StackTy... |
use std::thread;
use std::sync::{Arc};
fn main() {
let a = Arc::new(vec![1, 2, 3]);
{
let a = Arc::clone(&a);
thread::spawn(move || {
a[1];
});
}
{
let a = Arc::clone(&a);
thread::spawn(move || {
a[1];
});
}
}
|
use log::*;
use serde_json::Value;
use tantivy::tokenizer::NgramTokenizer;
#[derive(Clone)]
pub struct NgramTokenizerFactory {}
impl NgramTokenizerFactory {
pub fn new() -> Self {
NgramTokenizerFactory {}
}
pub fn create(self, json: &str) -> NgramTokenizer {
let v: Value = match serde_jso... |
use super::aggregation::Aggregator;
use super::statement::Statement;
use chrono::{TimeZone, Utc};
use serde_derive::{Deserialize, Serialize};
use std::convert::TryFrom;
use std::str::FromStr;
#[derive(Deserialize, Serialize, Debug)]
pub struct StatementExpr {
pub from: String,
pub group_by: String,
pub agg... |
#![allow(dead_code)]
#![allow(unused_must_use)]
#![allow(unused_imports)]
extern crate rustc_serialize;
extern crate mio;
#[macro_use]
extern crate log;
mod rtps;
pub mod rmw;
struct Entity;
struct QosPolicy;
struct Listener;
struct StatusKind;
trait EntityTrait {
fn set_qos(qos_list:&[QosPolicy]) -> ReturnCo... |
mod tasks;
pub async fn run_task() -> Result<(), String> {
Ok(())
}
|
use std::collections::hash_map::Entry::*;
use rustc_hash::FxHashMap;
use crate::util::clear::Clear;
pub struct HalfJoinStateFold<K, A> {
pub table: FxHashMap<K, A>,
}
impl<K, A> Default for HalfJoinStateFold<K, A> {
fn default() -> Self {
Self {
table: Default::default(),
}
}... |
use std::time::Instant;
use colored::*;
mod error;
mod fasta;
mod matrices;
mod options;
mod result;
mod spmeasure;
//mod weighting;
fn main()
{
println!( "\nCalculating conservation score a site in a MSA using Sum-of-pairs measure.\n" );
println!( "Karlin, Samuel, and Luciano Brocchieri. \"Evolutionary conservati... |
use cgmath::{Matrix4, Point3, Vector2};
use cgmath::prelude::*;
use graphics;
use math::{matrices, Aabb, Rot};
use math::raw::ToRawMath;
#[derive(Copy, Clone)]
pub struct Camera {
pub pos: Vector2<f32>,
pub viewport_height: f32,
pub aspect_ratio: f32,
pub roll: Rot,
pub near: f32,
pub far: f32... |
use crate::field::Field;
use crate::mode::AccessMode;
use crate::utils;
use serde::{Deserialize, Serialize};
use svd_parser::svd::{
registerinfo::RegisterInfoBuilder, Register as SvdRegister, RegisterCluster,
};
#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct RegisterCsv {
#[serde(rename = "偏移地址")]
... |
lazy_static! {
static ref BLOCK_ELEMENTS: Vec<&'static str> = vec![
"_root_",
"address",
"article",
"aside",
"blockquote",
"canvas",
"dd",
"div",
"dl",
"dt",
"fieldset",
"figcaption",
"figure",
"footer",
... |
pub fn problem_002() -> usize {
let n = 4000000;
let mut fib: Vec<usize> = vec![1, 1];
loop {
let f_2 = fib[fib.len() - 2];
let f_1 = fib[fib.len() - 1];
if f_1 + f_2 > n {
break;
}
fib.push(f_2 + f_1);
}
let mut sum = 0;
for x in fib {
... |
#[doc = "Register `CR2` reader"]
pub type R = crate::R<CR2_SPEC>;
#[doc = "Register `CR2` writer"]
pub type W = crate::W<CR2_SPEC>;
#[doc = "Field `ADD` reader - Address of the USART node"]
pub type ADD_R = crate::FieldReader;
#[doc = "Field `ADD` writer - Address of the USART node"]
pub type ADD_W<'a, REG, const O: u8... |
use super::ChannelStream;
use std::net::Shutdown;
use tokio::io::AsyncRead;
use tokio::io::AsyncWrite;
use tokio::net::TcpStream;
struct DirectChannelStream {
pub conn: TcpStream,
}
impl DirectChannelStream {
pub fn new(s: TcpStream) -> Self {
Self { conn: s }
}
}
impl ChannelStream for DirectCh... |
use std::fmt::{
self,
Display
};
use num_derive::FromPrimitive;
use num_traits::FromPrimitive;
use super::{
BytePattern,
Width,
Offset
};
#[derive(Debug, Clone, Copy, FromPrimitive)]
pub enum Opcode
{
Add = 0b_00000,
Sub = 0b_00001,
Mul = 0b_00010,
Div = 0b_000... |
use necsim_core::{
cogs::{
ActiveLineageSampler, DispersalSampler, EmigrationExit, EmptyActiveLineageSamplerError,
Habitat, PeekableActiveLineageSampler, PrimeableRng, SpeciationProbability, TurnoverRate,
},
landscape::IndexedLocation,
lineage::{GlobalLineageReference, Lineage},
simu... |
use octocrab::models::issues::*;
use reqwest::Url;
type DateTime = chrono::DateTime<chrono::Utc>;
use serde::Serialize;
use crate::*;
#[derive(Serialize, Debug)]
pub struct IssueRec {
pub id: i64,
pub node_id: String,
pub url: Url,
pub repository_url: Url,
pub labels_url: Url,
pub comments_ur... |
extern crate rand;
use rand::{Rng, random};
use std::time;
use std::time::{UNIX_EPOCH, SystemTime};
use std::i32;
fn bin_search(v: &Vec<i32>, elem: i32) -> Option<usize> {
let mut start: usize = 0;
let mut end = v.len();
while start != end {
let mid = start / 2 + end / 2;
if elem == v[mid... |
use rand::Rng;
use std::collections::VecDeque;
use tetra::audio::Sound;
use tetra::graphics::{self, Color, DrawParams, Texture};
use tetra::input::{self, Key};
use tetra::math::Vec2;
use tetra::{Context, ContextBuilder, State};
const FRAMES_PER_SECOND: f64 = 15.0;
const SPRITE_SIZE: i32 = 20;
const SCREEN_SIZE: i32 = ... |
//
// 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 std::{env, error::Error};
use lambda_runtime::{error::HandlerError, lambda, Context};
use log::LevelFilter;
use log::{self, error};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use simple_error::bail;
use simple_logger::SimpleLogger;
use rusoto_core::Region;
use rusoto_dynamodb::{DynamoDb, DynamoDb... |
pub mod stir {
pub mod intid {
pub fn get() -> u32 {
unsafe {
core::ptr::read_volatile(0xE000EF00u32 as *const u32) & 0x1FF
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0xE000EF00u32 as *const ... |
use super::*;
use std::mem;
pub trait MemoryUsage {
fn get_memory_usage(&self) -> usize;
}
impl MemoryUsage for RsDict {
fn get_memory_usage(&self) -> usize {
mem::size_of::<u64>() // len
+ mem::size_of::<u64>() // num_ones
+ mem::size_of::<u64>() // num_zeros
+ sel... |
fn main() {
println!("funk-db!");
}
|
// Definition for a binary tree node.
#[derive(Debug, PartialEq, Eq)]
pub struct TreeNode {
pub val: i32,
pub left: Option<Rc<RefCell<TreeNode>>>,
pub right: Option<Rc<RefCell<TreeNode>>>,
}
impl TreeNode {
#[inline]
pub fn new(val: i32) -> Self {
TreeNode {
val,
lef... |
fn sort(s: String) -> String {
let mut chars: Vec<_> = s.chars().collect();
chars.sort_by(|a, b| b.cmp(a));
String::from_iter(chars)
}
fn is_anagram(s: String, t: String) -> bool {
// sort(s) == sort(t)
use std::collections::HashMap;
let mut hm = HashMap::new();
s.chars().for_each(|c| *h... |
use codec::{Decode, Encode};
use frame_support::Parameter;
use sp_runtime::traits::{AtLeast32Bit, Member};
use std::fmt::Debug;
use substrate_subxt::{balances::*, module, system::*, Call, Store};
#[module]
pub trait DexPallet: System + Balances {
type AssetId: Parameter + Member + AtLeast32Bit + Default + Copy;
}
... |
// Vicfred
// https://atcoder.jp/contests/abc167/tasks/abc167_a
// implementation
use std::io;
fn main() {
let mut s = String::new();
io::stdin()
.read_line(&mut s)
.unwrap();
let s = s.trim();
let mut t = String::new();
io::stdin()
.read_line(&mut t)
.unwrap();
... |
use std::fs;
use std::io::prelude::*;
use std::net::TcpStream;
use std::net::Shutdown;
pub struct Request {
path: String,
status: RequestStatus,
stream: TcpStream,
}
impl Request {
pub fn new(stream: TcpStream, root: &String)->Request{
Request {
path: String::from(root),
... |
/*
chapter 4
syntax and semantics
*/
trait Foo {
fn foo(&self);
}
trait FooBar : Foo {
fn foobar(&self);
}
fn main() {}
// output should be:
/*
*/
|
use core::fmt::{Write, Error};
pub trait Writer {
fn write_byte(&mut self, byte: u8);
fn write_bytes(&mut self, bytes: &[u8]) {
for &byte in bytes { self.write_byte(byte) }
}
}
pub trait TextWriter: Writer {
fn print(&mut self, string: &str) {
self.write_bytes(string.as_bytes());
... |
use std::{borrow::Cow, collections::HashSet, hash::Hash, sync::Arc};
use async_trait::async_trait;
use bonsaidb_core::schema::{view, CollectionName, Key, Schema, ViewName};
use bonsaidb_jobs::{Job, Keyed};
use nebari::{
io::fs::StdFile,
tree::{KeyEvaluation, Root, UnversionedTreeRoot, VersionedTreeRoot},
T... |
//! The game state is represented by a relational model.
//! Tables are generic collections that store game data split by [shape] components.
//!
pub mod btree_table;
pub mod flag_table;
pub mod handle_table;
pub mod hex_grid;
pub mod iterators;
pub mod morton_hierarchy;
pub mod morton_table;
pub mod page_table;
pub mo... |
use std::collections::HashMap;
use nm_dbus::NmApi;
use crate::{
nm::checkpoint::nm_checkpoint_timeout_extend,
nm::connection::iface_to_nm_connection, nm::error::nm_error_to_nmstate,
nm::profile::delete_exist_profiles, InterfaceType, NetworkState,
NmstateError,
};
// We only adjust timeout for every 2... |
#![allow(clippy::needless_update)]
use std::io::{self, Write};
use std::sync::atomic;
use typos_cli::report::{Context, Message, Report, Typo};
#[derive(Copy, Clone, Debug)]
pub struct Palette {
error: yansi::Style,
warn: yansi::Style,
info: yansi::Style,
strong: yansi::Style,
}
impl Palette {
pu... |
use super::schema::{duel, moves};
#[derive(Insertable)]
#[table_name = "duel"]
pub struct NewDuel {
pub(crate) suspect_id: i32,
pub(crate) victim_id: i32,
pub(crate) suspect_side: bool,
pub(crate) winner: Option<bool>,
}
#[derive(Queryable, Serialize)]
pub struct Duel {
pub(crate) id: i32,
pu... |
use iron::prelude::*;
use iron::status;
use iron::middleware::Handler;
use handlers::HealthHandler;
impl Handler for HealthHandler {
fn handle(&self, _: &mut Request) -> IronResult<Response> {
Ok(Response::with(status::Ok))
}
}
|
use std::io::Error;
use std::fs::File;
use std::io::prelude::*;
use std::collections::HashMap;
use std::collections::HashSet;
#[macro_use] extern crate lazy_static;
extern crate regex;
use regex::Regex;
fn read_input(filename: &str) -> Result<String, Error> {
let mut input = String::new();
File::open(filename)?.... |
use minigrep;
use minigrep::Config;
use std::collections::HashMap;
use std::env;
use std::process;
fn main() {
// let query = &args[1];
// let filename = &args[2];
// let args: Vec<String> = env::args().collect();
let envVars: HashMap<String, String> = env::vars().collect();
let config = Config::n... |
use twang::{gen::Saw, mono::Mono64, Audio, Hz};
mod wav;
fn main() {
let mut saw = Saw::new(Hz(220.0)); // A4
let mut out = Audio::<Mono64>::with_silence(48_000, 48_000 * 5);
out.generate(&mut saw);
wav::write(out, "saw.wav").expect("Failed to write WAV file");
}
|
extern crate irc;
extern crate nanomsg;
extern crate rustc_serialize;
extern crate clap;
extern crate bender; // interface to plugins
use bender::*;
use std::default::Default;
use std::path::{Path, PathBuf};
use irc::client::prelude as client;
use irc::client::server::Server;
use irc::client::server::utils::ServerE... |
use anyhow::{anyhow, Result};
use crate::Challenge;
pub struct DayXX;
impl Challenge for DayXX {
const DAY_NUMBER: u32 = XX;
type InputType = ();
type OutputType = ();
fn part1(input: &Self::InputType) -> Result<Self::OutputType> {
unimplemented!()
}
fn part2(input: &Self::InputTyp... |
#![warn(rust_2018_idioms)]
#![warn(clippy::pedantic)]
#![warn(clippy::cargo)]
#![warn(clippy::nursery)]
use std::{fs, mem};
use numeral::Cardinal;
macro_rules! test_call_on_min_max {
($fn_name:ident, $numtype:ty) => {
#[test]
fn $fn_name() {
<$numtype>::MAX.cardinal();
<$n... |
use super::super::cpu::ioregister::CPU_FREQUENCY_HZ;
use blip_buf::BlipBuf;
use sdl2::audio::AudioSpecDesired;
use std::fmt;
use std::fmt::Debug;
const IO_START: u16 = 0xFF10;
const IO_END: u16 = 0xFF3F;
// PulseAVoice registers
pub const NR10_REGISTER_ADDR: u16 = 0xFF10;
pub const NR11_REGISTER_ADDR: u16 = 0xFF11;
p... |
//parse entire file and extract labelling triples
//substitute entities with lables where possible
//
use std::fs::File;
use std::io::{prelude::*, BufReader};
use serde_json::{Value};
use std::collections::HashMap;
pub fn substitute(v : &Value, e2l : &HashMap<String, String>) -> Value {
//substitute is only call... |
use super::ValueStoreApi;
use crate::{Result, Value};
use serde_json::Value as JsonValue;
pub struct ValueStore {
value: JsonValue,
}
impl Default for ValueStore {
fn default() -> Self {
Self {
value: JsonValue::default(),
}
}
}
impl ValueStoreApi for ValueStore {
fn load(... |
use std::{
collections::{HashMap, VecDeque},
convert::TryFrom,
};
const INPUT: &str = include_str!("../inputs/day_15_input");
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
struct Position {
pub x: usize,
pub y: usize,
}
impl Position {
fn from_tuple((x, y): (usize, usize)) -> Self {
... |
use super::FpCategory;
use crate::consts::DecimalProps;
use crate::*;
#[test]
fn it_works() {
// //bid128_from_string 2 -9.9999999999999999999999999999999995 [afffed09bead87c0378d8e63ffffffff] 20
// use crate::d32;
// let expected = d32::from_bits(0x6018967f);
// let unpacked: crate::Unpack... |
//! The `generators` module contains API for producing a
//! set of generators for a rangeproof.
#![allow(non_snake_case)]
#![deny(missing_docs)]
extern crate alloc;
use alloc::vec::Vec;
use curve25519_dalek::constants::RISTRETTO_BASEPOINT_COMPRESSED;
use curve25519_dalek::constants::RISTRETTO_BASEPOINT_POINT;
use c... |
use std::fmt;
#[derive(Debug)]
/// Bit vector of arbitrary length (actually the length is limited to _[1, 2^64)_).
///
/// ```text
/// When fist_byte_offset = 2, last_byte_len = 2:
///
/// 10101010 00000000 11111111
/// | effective bits |
/// ```
pub struct RawBitVector<'s> {
byte_slice: &'s [u8],
first_byt... |
// Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use crate::server::Service;
use failure_ext::Result;
use serde::{Deserialize, Serialize};
// Implementation of the decl service.
#[deriv... |
mod builder;
mod file_source_stream;
mod srt_source_stream;
pub use builder::SourceStreamBuilder;
pub use file_source_stream::FileSourceStream;
pub use srt_source_stream::SrtSourceStream;
use crate::Result;
use bytes::Bytes;
use std::time::Instant;
pub trait SourceStream {
fn receive(&mut self) -> Option<(Instant,... |
#![feature(test, generator_trait, exhaustive_patterns)]
extern crate test;
use std::ops::{Generator, GeneratorState};
use std::pin::Pin;
use std::{env, fs};
use test::Bencher;
use lochnes::nes::ppu::PpuStep;
use lochnes::nes::NesStep;
use lochnes::{input, nes, rom, video};
#[bench]
fn bench_frames(b: &mut Bencher) ... |
extern crate getopts;
use std::io::prelude::*;
use std::net::TcpListener;
use std::net::TcpStream;
use std::process::Command;
use getopts::Options;
use std::env;
fn main() {
let args: Vec<String> = env::args().collect();
let program = args[0].clone();
let mut opts = Options::new();
opts.optopt("p", "... |
use azure_core::prelude::IfMatchCondition;
use http::response::Response;
/// A document's attributes
#[derive(Default, Serialize, Deserialize, Debug, Clone, PartialEq)]
pub struct DocumentAttributes {
#[serde(rename = "_rid")]
rid: String,
#[serde(rename = "_ts")]
ts: u64,
_self: String,
#[serd... |
use std::{fmt, iter::Zip, mem, ops::{Index, IndexMut}};
/// Dynamically allocated 2d array
#[derive(Clone, PartialEq, Eq)]
pub struct Grid<T> {
cols: usize,
rows: usize,
data: Box<[T]>,
}
impl<T> Grid<T> {
/// Allocates a new grid with default values for each cell
pub fn new(cols: usize, rows: usi... |
use clap::{App, Arg};
use pop_ci::{
cache::Cache,
git::{GitBranch, GitCommit, GitRemote, GitRepo},
repo::{Arch, Package, Pocket, RepoInfo, Suite, SuiteDistro},
util::{check_output, check_status},
};
use std::{
collections::{BTreeMap, BTreeSet},
env,
fmt::Write,
fs,
io,
path::{Pat... |
pub fn main() {
let mut number: u32;
let mut highest: u32 = 0;
for x in 100..1000 {
for y in 100..1000 {
number = x * y;
if is_palindrome(number.to_string()) {
if number > highest {
highest = number;
}
}
... |
enum Message{
Quit,
ChangeColor(i32,i32,i32),
Move {x : i32,y : i32},
Write(String),
}
enum _Message {
ChangeColor(i32,i32),
Move{x : i32},
}
fn main() {
let x : Message = Message::Move{x : 3,y : 3};
let y : _Message = _Message::Move{x : 3};
let m = Message::Write("Hello,world".to... |
use crate::protocol::Protocol;
use crate::protocol::ProtocolSet;
use crate::name_server::NameServer;
use crate::name_server::ROOT_V4_SERVERS;
use crate::name_server::ROOT_V6_SERVERS;
#[derive(Debug, PartialEq, Eq, Hash, Clone, Copy)]
pub struct ResolvOptions {
pub use_ipv4: bool,
pub use_ipv6: bool,
pub ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.