text stringlengths 8 4.13M |
|---|
use std::{collections::HashMap, path::PathBuf, sync::Arc, time::Duration};
use futures::TryStreamExt;
use semver::Version;
use tokio::sync::{mpsc, RwLock};
use crate::{
bson::{doc, Document},
client::options::ClientOptions,
concern::{Acknowledgment, WriteConcern},
gridfs::GridFsBucket,
options::{
... |
use std::fs;
use std::process::Command;
use std::sync::Once;
pub fn setup() {
static BUILD: Once = Once::new();
BUILD.call_once(|| {
let status = Command::new("cargo")
.arg("build")
.status()
.expect("failed to build");
assert!(status.success());
});
}
p... |
use anyhow;
use k8s_openapi::apiextensions_apiserver::pkg::apis::apiextensions::v1::CustomResourceDefinition;
use kube_derive::CustomResource;
use rweb::openapi::Entity;
use rweb::openapi::Schema;
use rweb::Schema;
use serde::{Deserialize, Serialize};
#[derive(CustomResource, Serialize, Deserialize, Clone, Debug, Sche... |
use std::collections::HashMap;
use std::convert::TryFrom;
use std::ops::{Deref, DerefMut};
use crate::Element;
/// Maps to `HashMap<String, Element>`
#[derive(Debug)]
pub struct Struct(pub HashMap<String, Element>);
impl From<Struct> for Element {
fn from(s: Struct) -> Self {
Element::Struct(s.0)
}
... |
#[cfg(test)]
#[path = "../../tests/unit/validation/vehicles_test.rs"]
mod vehicles_test;
use super::*;
use crate::parse_time;
use crate::utils::combine_error_results;
use crate::validation::common::get_time_windows;
use hashbrown::HashSet;
use std::cmp::Ordering;
use std::ops::Deref;
use vrp_core::models::common::Time... |
use serde::{Deserialize, Serialize};
use structopt::StructOpt;
use persist_core::error::Error;
use persist_core::protocol::PruneRequest;
use crate::daemon;
use crate::format;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, StructOpt)]
pub struct Opts {
/// Also prune file of stopped, but still managed,... |
//! The RFC 2389 Options (`OPTS`) command
//
// The OPTS (options) command allows a user-PI to specify the desired
// behavior of a server-FTP process when another FTP command (the target
// command) is later issued. The exact behavior, and syntax, will vary
// with the target command indicated, and will be specified ... |
extern crate stava;
#[macro_use]
extern crate clap;
#[macro_use]
extern crate include_dir;
use clap::{Arg, Command};
use include_dir::Dir;
use stava::{Stava, StavaResult};
use std::collections::HashMap;
use std::ffi::OsStr;
use std::fs;
use std::path::Path;
use std::process::exit;
const OPT_NAME_WORD: &str = "WORD";... |
//! RPC wrapper for `/status` endpoint
use crate::{jsonrpc, node_info::NodeInfo};
use serde::{de::Error as DeError, Deserialize, Deserializer, Serialize, Serializer};
/// Request the status of the node
#[derive(Default)]
pub struct Status;
impl jsonrpc::Request for Status {
type Response = StatusResponse;
f... |
#![cfg_attr(not(feature = "force_macros11_mode"),
feature(rustc_attrs, rustc_private,
rustc_macro_internals, plugin))]
#![cfg_attr(not(feature = "force_macros11_mode"),
plugin(namedarg_hack))]
#![feature(rustc_macro, rustc_macro_lib)]
// for testing: #![feature(rustc_macro_internals, rustc_private)]
ex... |
//
// All datetimes in chore are implicitly durations over the provided resolution.
// For example, "2001-02-03" describes 2001-02-03T00:00:00 to 2001-02-03T23:59:59.
//
use chrono::{Datelike, Timelike};
#[derive(Clone, Debug, PartialEq)]
pub struct Date {
start: chrono::NaiveDateTime,
duration: self::Duratio... |
use std::path::Path;
use ignore::{self, DirEntry};
use log;
/// A configuration for describing how subjects should be built.
#[derive(Clone, Debug)]
struct Config {
strip_dot_prefix: bool,
}
impl Default for Config {
fn default() -> Config {
Config {
strip_dot_prefix: false,
}
... |
use std::collections::HashMap;
#[derive(Clone, Debug)]
pub struct Bounds {
bd: HashMap<usize, (usize, usize)>,
}
impl Bounds {
pub fn new(y: usize, (lb, hb): (usize, usize)) -> Self {
let mut bd = HashMap::new();
bd.insert(y, (lb, hb));
Self { bd }
}
pub fn lower_bound(&self,... |
#![cfg_attr(test, deny(warnings))]
//#![deny(missing_docs)]
//! # httpparse
//!
//! A chunks-based, asynchronous HTTP parser.
//!
extern crate hyper;
use std::default::Default;
use hyper::header::Headers;
use hyper::status::StatusCode as Status;
use self::Next::{Continue, Break};
pub enum Next { Continue, Break }... |
use std::io::{BufReader, Read};
use thiserror::Error;
use super::{lookup::LookupRef, value::Value};
pub trait CelesteIo: Sized {
type Error;
fn read<R: Read>(
reader: &mut BufReader<R>,
lookup: Option<LookupRef<'_>>,
) -> Result<Self, Self::Error>;
}
impl CelesteIo for bool {
type E... |
#[doc = "Register `DBG_CR` reader"]
pub type R = crate::R<DBG_CR_SPEC>;
#[doc = "Register `DBG_CR` writer"]
pub type W = crate::W<DBG_CR_SPEC>;
#[doc = "Field `DBG_STOP` reader - Debug Stop mode"]
pub type DBG_STOP_R = crate::BitReader;
#[doc = "Field `DBG_STOP` writer - Debug Stop mode"]
pub type DBG_STOP_W<'a, REG, c... |
#[doc = "Register `FIR0` reader"]
pub type R = crate::R<FIR0_SPEC>;
#[doc = "Register `FIR0` writer"]
pub type W = crate::W<FIR0_SPEC>;
#[doc = "Field `FAE0` reader - Force acknowledge error 0"]
pub type FAE0_R = crate::BitReader;
#[doc = "Field `FAE0` writer - Force acknowledge error 0"]
pub type FAE0_W<'a, REG, const... |
mod helpers;
use jsonprima;
// t
test!(test_1, "t", vec![("E104", 0, 1)]);
test!(test_2, " t", vec![("E104", 1, 2)]);
test!(test_3, "t ", vec![("E105", 0, 2)]);
test!(test_4, " t ", vec![("E105", 1, 3)]);
test!(test_5, " t😋", vec![("E105", 1, 3)]);
// tr
test!(test_6, "tr", vec![("E104", 0, 2)]);
test!(test_7, " tr... |
use libc;
use nix;
pub fn all() -> Result<Vec<String>, nix::Error> {
nix::net::if_::if_nametoindex
nix::sys::ioctl!();
} |
/// Error Correction Code
pub fn hamming_parity(mut x: i64) -> i64 {
x = x ^ (x >> 1);
x = x ^ (x >> 2);
x = x ^ (x >> 4);
x = x ^ (x >> 8);
x = x ^ (x >> 16);
return x & 1;
}
/* Computes the six parity check bits for the
"information" bits given in the 32-bit word u. The
check bits are p[5:0].... |
use core::position::{Size, Pos, HasSize, HasPosition};
use core::cellbuffer::CellAccessor;
use std::boxed::Box;
use std::collections::HashMap;
use ui::core::{
Layout,
Alignable,
HorizontalAlign,
VerticalAlign,
Widget,
Frame,
Button,
Painter,
ButtonResult
};
/// Hold buttons a... |
use std::error::Error;
use std::fs::File;
use std::io::BufReader;
use std::io::prelude::*;
use std::path::Path;
fn main() {
//Day 1 Input
//let lines: Vec<String> = get_input("./src/input1.txt");
//Day 1, Q1
//fuel_tally(&lines);
//Day 1, Q2
//fuel_fuel_tally(&lines)
//Day 2 Input
... |
use crate::errors::*;
use std::fs;
/// A trait for mutable stores. This is abstracted away so that users can implement a non-filesystem mutable store, which is useful
/// for read-only filesystem environments, as on many modern hosting providers. See the book for further details on this subject.
#[async_trait::async_t... |
#[macro_use]
extern crate iron;
extern crate router;
extern crate mount;
extern crate params;
extern crate iron_sessionstorage;
extern crate iron_json_response as ijr;
#[macro_use]
extern crate serde_derive;
#[macro_use]
extern crate diesel;
#[macro_use]
extern crate diesel_codegen;
extern crate r2d2;
extern crate r2d2... |
#[derive(Debug)]
struct Person {
name: String,
age: i32,
}
fn main1() {
// 変数xを用意する
let x: &Person;
// ブロックを開始する
{
// 変数aにメモリ領域を割り当てる
let a = Person {
name: String::from("masuda"),
age: 50,
};
// 変数xに参照させる
x = &a ;
// ブロックを... |
use crate::{R, FontError};
use nom::{
number::complete::{be_u16, be_u32},
};
use svg_dom::{Svg, Item};
use std::collections::HashMap;
use std::sync::Arc;
use std::fmt;
#[derive(Clone)]
pub struct SvgGlyph {
pub svg: Arc<Svg>,
pub item: Arc<Item>,
}
impl fmt::Debug for SvgGlyph {
fn fmt(&self, f: &mut f... |
use crate::main;
pub mod frame_allocator;
#[macro_use]
pub mod interrupts;
pub mod intrinsics;
pub mod gdt;
pub mod multiboot;
pub mod paging;
pub mod pic;
pub mod stacks;
pub mod syscall;
pub mod tss;
pub const KERNEL_BASE: usize = 0xffffffff80000000;
use self::multiboot::MultibootTags;
use self::frame_allocator::{... |
use std::{fs::File, io::Read};
use crate::code::*;
use crate::symbol_table::SymbolTable;
#[derive(Debug)]
pub struct CCommand {
dest: Option<String>,
comp: String,
jump: Option<String>,
}
impl CCommand {
fn new(s: &str) -> Self {
let mut ccommand = CCommand{dest: None, comp: "NOP".to_string(),... |
pub mod component;
|
use std::path::PathBuf;
use structopt::StructOpt;
#[derive(Debug, StructOpt)]
#[structopt(about = "GUI viewer for `nix store --query --tree` output.")]
pub struct Opts {
/// PATH in /nix/store to view references of
#[structopt(name = "PATH", parse(from_os_str))]
pub nix_store_path: PathBuf,
}
impl Opts {
... |
use std::str;
static TABLE: [uint, ..10] = [
0b1110111,
0b0100100,
0b1011101,
0b1101101,
0b0101110,
0b1101011,
0b1111011,
0b0100101,
0b1111111,
0b1101111
];
static H_SYM: &'static str = "-";
static V_SYM: &'static str = "|";
static S_SYM: &'static str = " ";
struct LCD {
numbers: ~[uint],
... |
extern crate core;
extern crate rk3399_tools;
pub struct PerilpM0 { }
pub trait M0 {
fn setup(&mut self, pmusgrf: &rk3399_tools::PMUSGRF,
pmucru: &rk3399_tools::PMUCRU, start: u32);
fn on(&mut self, pmucru: &rk3399_tools::PMUCRU);
}
// WMSK_BIT(x) => BIT(x + 16) => 1 << (x + 16)
// BI... |
use clumsy::fs::inmem::InMemFileSystem;
use clumsy::fs::mac::MacOSFileSystem;
use clumsy::fs::FileSystem;
use clumsy::object::GitObject;
use clumsy::*;
use std::io;
use libflate::zlib::{Decoder, Encoder};
use std::fs::File;
use std::io::prelude::*;
fn main() -> io::Result<()> {
let args: Vec<String> = std::env::a... |
//! testing closure with a linear offset
use anyhow::Result;
use approx::assert_abs_diff_eq;
use ndarray::{array, Array1, Array2};
use ndarray_glm::{Linear, ModelBuilder};
#[test]
/// Check that the result is the same in linear regression when subtracting
/// offsets from the y values as it is when adding linear offs... |
use serde::{Deserialize, Serialize};
//;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
// RDF
//;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
//
#[derive(Debug,Serialize, Deserialize,Clone,Hash)]
pub struct RDFList {
//#[serde(rename = "rdf:type")]
//pub rdf_type: Option<Vec<... |
pub struct Sporangium {}
pub struct Spore {}
struct Cell {}
pub fn produce_spore(factory: &mut Sporangium) -> Spore {
Spore
}
fn recombine(parent: &mut Cell) {} |
use advent_libs::input_helpers;
fn main() {
println!("Advent of Code 2020 - Day 3");
println!("---------------------------");
// Read in puzzle input
let mut input = input_helpers::read_puzzle_input_to_string(3);
// Strip out the carriage returns (on Windows)
input.retain(|c| c != '\r');
/... |
#[doc = "Register `DOUTR18` reader"]
pub type R = crate::R<DOUTR18_SPEC>;
#[doc = "Register `DOUTR18` writer"]
pub type W = crate::W<DOUTR18_SPEC>;
#[doc = "Field `DOUT18` reader - Output data sent to MDIO Master during read frames"]
pub type DOUT18_R = crate::FieldReader<u16>;
#[doc = "Field `DOUT18` writer - Output d... |
use super::Transition;
use super::super::Frame;
use super::StateData;
pub trait State: Send + StateClone {
fn draw(&self, _frame: &mut Frame, _state_data: &StateData) {
}
fn shadow_draw(&self, _frame: &mut Frame, _state_data: &StateData) {
}
fn update(&mut self, _state_data:... |
use crate::{reflector::ObjectRef, watcher::Error};
use core::{
pin::Pin,
task::{Context, Poll},
};
use futures::{ready, Stream};
use kube_client::Resource;
use pin_project::pin_project;
use std::{collections::HashMap, hash::Hash};
#[allow(clippy::pedantic)]
#[pin_project]
/// Stream returned by the [`predicate... |
use futures::sync::mpsc::{unbounded, UnboundedSender};
use futures::Stream;
use netlink_packet_core::NetlinkMessage;
use std::fmt::Debug;
use crate::errors::{Error, ErrorKind};
use crate::Request;
use netlink_sys::SocketAddr;
/// A handle to pass requests to a [`Connection`](struct.Connection.html).
#[derive(Clone, D... |
use std::cell::RefCell;
use std::collections::HashMap;
use std::rc::Rc;
use crate::execute::{VMError, VMResult};
use crate::value::Value;
#[derive(Debug, Clone)]
pub struct Environment {
enclosing: Option<Rc<RefCell<Environment>>>,
bindings: HashMap<String, Value>,
}
impl Environment {
pub fn new() -> Se... |
#![allow(dead_code)]
use iced_wgpu::{wgpu, wgpu::vertex_attr_array};
use rand::{rngs::SmallRng, Rng, SeedableRng};
#[repr(C)]
#[derive(Copy, Clone, Debug, Default)]
pub struct ParticleAttributes {
position: glam::Vec3,
radius: f32,
color: glam::Vec4,
}
pub struct ParticleSystem {
particle_count: usiz... |
use std::{
io,
borrow::Cow,
os::unix::ffi::{OsStrExt, OsStringExt},
path::Path,
pin::Pin,
task::{Context, Poll},
ffi::{OsStr, OsString},
};
use lazy_static::lazy_static;
use derive_more::From;
use thiserror::Error;
use serde::de::DeserializeOwned;
use regex::bytes::Regex;
use futures::AsyncReadExt;
pub us... |
// This file is part of Substrate.
// Copyright (C) 2019-2020 Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// ht... |
pub mod graph_fns;
pub mod validate_fns;
pub use self::graph_fns::*;
|
// https://www.codewars.com/kata/52761ee4cffbc69732000738
fn good_vs_evil(good: &str, evil: &str) -> String {
let good_points : Vec<u32> = vec![1,2,3,3,4,10];
let evil_points : Vec<u32> = vec![1,2,2,2,3,5,10];
let good_wins : String = String::from("Battle Result: Good triumphs over Evil");
let evil_wi... |
use super::{Body, Frame};
#[derive(Debug, Eq, PartialEq)]
pub struct Cancel {}
pub struct CancelBuilder {
stream_id: u32,
flag: u16,
}
impl CancelBuilder {
pub fn build(self) -> Frame {
Frame::new(self.stream_id, Body::Cancel(), self.flag)
}
}
impl Cancel {
pub fn builder(stream_id: u32,... |
// This file is part of rdma-core. It is subject to the license terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/rdma-core/master/COPYRIGHT. No part of rdma-core, including this file, may be copied, modified, propagated, or distributed ... |
// Copyright 2019 The Grin Develope;
//
// 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... |
use specs::Join;
pub struct HelpSystem;
impl<'a> ::specs::System<'a> for HelpSystem {
type SystemData = (
::specs::ReadStorage<'a, ::component::Attracted>,
::specs::ReadStorage<'a, ::component::Avoider>,
::specs::ReadStorage<'a, ::component::Bouncer>,
::specs::ReadStorage<'a, ::com... |
use std::string::String;
use std::io;
use std::io::{Read,Write};
use customer::{CustomerList,CustomerId};
use util::{Creatable,UrlEncodable};
use card::CardList;
use decoder::{StripeDecoder,StripeDecoderError};
use url::{Url,form_urlencoded};
use hyper::client::Request;
use hyper::net::{Fresh,Streaming};
use hyper::met... |
use clap::{Arg, App, AppSettings};
use image::FilterType;
use job::{Format, Job, JobBuilder, ResizeType};
use std::env;
use std::path::PathBuf;
const SUPPORTED_IMAGES: [&str; 7] = ["jpg", "png", "jpeg", "gif", "bmp", "tif", "tiff"];
const SUPPORTED_SAVES: [&str; 2] = ["jpg", "png"];
const FILTERS: [&str; 5] = ["nn", "... |
use crate::sys;
use piet::{Error, RoundInto};
pub struct Text(pub(crate) sys::dwrite::Factory);
impl piet::Text for Text {
type Font = Font;
type FontBuilder = FontBuilder;
type TextLayout = TextLayout;
type TextLayoutBuilder = TextLayoutBuilder;
fn new_font_by_name(
&mut self,
n... |
#[doc = "Reader of register DDRCTRL_DFIMISC"]
pub type R = crate::R<u32, super::DDRCTRL_DFIMISC>;
#[doc = "Writer for register DDRCTRL_DFIMISC"]
pub type W = crate::W<u32, super::DDRCTRL_DFIMISC>;
#[doc = "Register DDRCTRL_DFIMISC `reset()`'s with value 0x01"]
impl crate::ResetValue for super::DDRCTRL_DFIMISC {
typ... |
/*
* The default huffman tables are taken from
* section K.3 Typical Huffman tables for 8-bit precision luminance and chrominance
*/
#[derive(Copy, Clone, Debug)]
pub enum CodingClass {
Dc = 0,
Ac = 1,
}
static DEFAULT_LUMA_DC_CODE_LENGTHS: [u8; 16] = [
0x00, 0x01, 0x05, 0x01, 0x01, 0x01, 0x01, 0x01,
... |
use std::{ops::Deref, time::Duration};
use futures::{future::BoxFuture, stream::StreamExt, FutureExt};
use serde::{
de::{self, Deserializer},
Deserialize,
};
use crate::{
bson::{Bson, Deserializer as BsonDeserializer, Document},
bson_util,
error::Result,
options::{FindOptions, Hint, InsertMany... |
#[doc = "Reader of register BUFF_CPU_SHOULD_HANDLE"]
pub type R = crate::R<u32, super::BUFF_CPU_SHOULD_HANDLE>;
#[doc = "Reader of field `EP15_OUT`"]
pub type EP15_OUT_R = crate::R<bool, bool>;
#[doc = "Reader of field `EP15_IN`"]
pub type EP15_IN_R = crate::R<bool, bool>;
#[doc = "Reader of field `EP14_OUT`"]
pub type... |
#![allow(dead_code)]
pub fn area(w: i32, h: i32) -> i32 {
w * h
}
|
// unihernandez22
// https://codeforces.com/problemset/problem/401/C
// simulation
use std::io;
fn main() {
let mut line = String::new();
io::stdin()
.read_line(&mut line)
.unwrap();
let words: Vec<i64> =
line
.split_whitespace()
.map(|x| x.parse().unwrap())
... |
use crate::analytics::create_directory;
use crate::maze::maze_genotype::MazeGenome;
use crate::mcc::agent::mcc_agent::MCCAgent;
use crate::neatns::agent::Agent;
use crate::simulator::{simulate_single_mcc, simulate_single_neatns};
use crate::visualization::maze::visualize_maze;
use crate::visualization::simulation::visu... |
#[macro_export]
macro_rules! version_deps {
(
let $version:ident = 0;
$(let $v:ident = $e:expr;)+
) => {
$(let $v = $e;)*
let $version = storm::version_tag::combine(&[$(storm::Tag::tag(&$v),)*]);
};
}
|
use std::collections::HashMap;
use bson::Array;
use mongocrypt::ctx::KmsProvider;
use serde::Deserialize;
use crate::{
bson::{Bson, Document},
client::options::TlsOptions,
error::{Error, Result},
Namespace,
};
/// Options related to automatic encryption.
///
/// Automatic encryption is an enterprise ... |
/**
* This example shows how you can use the mid-level wrapper directly as opposed to the
* high-level wrapper. You may want to do this if you prefer a near to 1:1 mapping
* to the GLFW API (the high level bindings alter it considerably).
*/
extern mod GLFW (name = "glfw");
use glfw = GLFW::ml; // use mid-level... |
mod base64_ciphers;
fn main() {
let v = "abcd";
let en = base64_ciphers::encode(&v);
println!("{}", en);
let de = base64_ciphers::decode(&en).unwrap();
println!("{}", de);
}
|
// TLE
pub fn find_substring_1(s: String, words: Vec<String>) -> Vec<i32> {
use std::collections::HashSet;
let n = words.len();
let m = words[0].len();
let ns = s.len();
if n == 0 || m == 0 {
return vec![]
}
if ns < n * m {
return vec![]
}
fn perm(n: usize) -> Vec<... |
#[doc = "Reader of register STATUS"]
pub type R = crate::R<u32, super::STATUS>;
#[doc = "Reader of field `EC_BUSY`"]
pub type EC_BUSY_R = crate::R<bool, bool>;
impl R {
#[doc = "Bit 0 - Inidicates whether the externally clocked logic is potentially accessing the EZ memory (this is only possible in EZ mode). This bi... |
#[ link(name = "randgen",
vers = "0.1.2",
author = "smadhueagle") ];
#[pkg(id = "randgen", vers = "0.1.2")];
// Additional metadata attributes
#[ desc = "A simple random num generator example in rust"];
#[ license = "MIT" ];
#[crate_type = "bin"];
extern mod rustils;
use rustils::ioutils;
use std::io::... |
use std::path::{Path, PathBuf};
use std::ffi::OsString;
pub fn get_obj_path<TP: AsRef<Path>, BP: AsRef<Path>, FP: AsRef<Path>>(target: TP, base: BP, file: FP) -> PathBuf {
let mut base = base.as_ref();
let mut parents = 0;
loop {
if let Ok(stripped) = file.as_ref().strip_prefix(base) {
... |
use std::fs::File;
use std::io::prelude::*;
use std::path::Path;
use crate::game::game::*;
pub fn export_to_file(game: &Game) {
let b = game.b * game.max_values.y;
let m = (game.m * game.max_values.y) / game.max_values.x;
let output = format!("m,b\n{:.10},{:.10}", m, b);
let path = Path::new("output/s... |
use ::{Value, AresResult, AresError};
use super::util::expect_arity;
pub fn some(args: &[Value]) -> AresResult<Value> {
try!(expect_arity(args, |l| l == 1, "exactly 1"));
let first = args[0].clone();
Ok(Value::Option(Some(Box::new(first))))
}
pub fn none(args: &[Value]) -> AresResult<Value> {
try!(exp... |
//! Day 3.
//!
//! Counting valid triangles based on the length of each side. A
//! triangle is considered 'valid' if all sides are shorter than the
//! sum of the other two sides.
/// Counts the valid triangles in a list of sides.
fn count_valid_triangles(numbers: Vec<i32>) -> usize {
numbers.chunks(3)
.f... |
use crate::{
bson::Document,
event::{
cmap::{CmapEvent, ConnectionCheckoutFailedReason, ConnectionClosedReason},
command::CommandEvent,
},
test::{Event, SdamEvent},
ServerType,
};
use serde::Deserialize;
#[derive(Debug, Deserialize)]
#[serde(untagged, deny_unknown_fields, rename_all... |
use std::cell::Cell;
trait Arg {
fn run(&self) -> i32;
}
impl Arg for i32 {
fn run(&self) -> i32 { *self }
}
struct B<'a> {
k: &'a Cell<i32>,
x1: &'a Arg,
x2: &'a Arg,
x3: &'a Arg,
x4: &'a Arg,
}
impl<'a> Arg for B<'a> {
fn run(&self) -> i32 {
self.k.set(self.k.get() - 1)... |
use nom::{types::CompleteStr, *};
use crate::ir::{FnSig, Type};
#[derive(Clone, Debug, PartialEq)]
pub struct Define<'a> {
pub name: &'a str,
pub sig: FnSig<'a>,
pub stmts: Vec<Stmt<'a>>,
}
#[derive(Clone, Debug, PartialEq)]
pub enum Stmt<'a> {
// ` call void asm sideeffect "cpsid i"`
Asm(&'a st... |
use crate::value::Value;
/// Error returned by `ocaml-rs` functions
#[derive(Debug)]
pub enum Error {
/// An index is out of bounds
OutOfBounds,
/// A value cannot be called using callback functions
NotCallable,
/// An OCaml exception
Exception(Value),
/// Array is not a double array
... |
use std::collections::HashMap;
use std::hash::Hash;
pub struct Env<N, V>(HashMap<N, V>);
impl<N, V> Env<N, V>
where
N: Clone + Hash + Eq,
{
pub fn new() -> Env<N, V> {
Env(HashMap::new())
}
pub fn get_mut(&mut self, name: &N) -> Option<&mut V> {
self.0.get_mut(name)
}
pub fn ... |
use crate::c_component::CModel;
use yew::prelude::*;
use yew::Properties;
use yew_router::component;
use yew_router::components::router_button::RouterButton;
use yew_router::route;
use yew_router::FromCaptures;
use yew_router::{Route, Router};
pub struct AModel {}
#[derive(PartialEq, Properties, FromCaptures)]
pub st... |
struct Circle {
x: f64,
y: f64,
radius: f64,
}
trait HasArea {
fn area(&self) -> f64;
}
impl HasArea for Circle {
fn area(&self) -> f64{
std::f64::consts::PI * (self.radius * self.radius)
}
}
fn print_area<T: HasArea>(shape: &T)
{
println!("shape have the area {}",shape.area())... |
use std::collections::HashMap;
fn main() {
let mut scores = HashMap::new();
scores.insert(String::from("Blue"), 10);
scores.insert(String::from("Yellow"), 50);
println!("scores: {:?}", scores);
let teams = vec![String::from("Blue"), String::from("Yellow")];
let initial_scores = vec![10, 50];... |
use crate::util::bit_op;
use std::fmt;
#[derive(Clone)]
pub(crate) struct Registers {
af: AF,
bc: BC,
de: DE,
hl: HL,
sp: u16,
pc: u16,
}
impl fmt::Debug for Registers {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"{{af: {:?}, bc: {... |
use ndarray::{arr2, Array2};
use std::convert::Into;
pub struct ModelMatrix {
model_matrix: Array2<f32>,
}
impl ModelMatrix {
pub fn new() -> Self {
Self {
model_matrix: arr2(&[
[1.0, 0.0, 0.0, 0.0],
[0.0, 1.0, 0.0, 0.0],
[0.0, 0.0, 1.0, 0.0]... |
pub run() {
} |
use super::scenario::Scenario;
use crate::agents::Agents;
use crate::navmesh::{Navmesh, NavmeshBuilder};
use crate::vec2::Vec2;
use serde::Deserialize;
#[derive(Clone, Copy, Debug, PartialEq, Deserialize)]
pub struct EmptyScenario {}
impl EmptyScenario {
pub fn new() -> Self {
EmptyScenario {}
}
}
impl Defau... |
//! A Rubble BLE driver for the nRF51/nRF52-series radios.
#![no_std]
#![warn(rust_2018_idioms)]
pub mod radio;
pub mod timer;
pub mod utils;
|
use
{
thespis :: { * } ,
thespis_impl :: { * } ,
async_executors :: { * } ,
futures::executor :: { block_on } ,
};
#[ derive( Actor ) ] struct Sum( u64 );
struct Add (u64);
struct Show ;
impl Message for Add { type Return = () ; }
impl Message for Show { type Return = ... |
#[macro_export]
macro_rules! bench_func {
($name: ident, $desc: expr, op => $func: ident, from => $from: expr) => {
pub(crate) fn $name(c: &mut Criterion) {
const SIZE: usize = 1 << 13;
let mut rng = support::PCG32::default();
let inputs =
criterion::black... |
use {
data::semantics::{
properties::{CuiProperty, Property},
Semantics, Value,
},
proc_macro2::TokenStream,
quote::quote,
};
impl Semantics {
fn static_render_all(&self, group_id: usize) -> TokenStream {
let elements = self.static_render_elements(group_id);
let classes = self.static_render_classes(group_... |
use glow::HasContext;
use std::convert::TryInto;
use std::ops::Deref;
use luminance::shader::program::Program;
use crate::{
VertexSemantics,
pipeline::{
ShaderInterface,
shader::IsShader,
texture::Texture,
},
};
pub trait IsMaterial {
fn upload_fields(&self, gl: &glow::Context... |
use crate::html::Element;
pub struct ElementMockOption {
pub name: String,
pub id: String,
pub class: String,
}
impl ElementMockOption {
pub fn new() -> ElementMockOption {
ElementMockOption {
name: String::from(""),
id: String::from(""),
class: String::from... |
use byteorder::*;
use fs2::FileExt;
use memmap::{Mmap, Protection};
use std::fs::{OpenOptions, File};
use std::io::{Seek, SeekFrom};
use std::path::Path;
use types::*;
/// A mapping from a message's sequence number to its byte offset in the log file.
///
/// A `MsgOffsets` index is always backed by a file. The file is... |
use std::collections::HashMap;
pub struct codon<'a> {
names: HashMap<&'a str, &'a str>
}
pub fn parse<'a>(pairs: Vec<(&'a str, &'a str)>) -> codon<'a> {
codon { names: pairs.iter().cloned().collect::<HashMap<_,_>>() }
}
impl <'a>codon<'a> {
pub fn name_for(&self, s: &'a str) -> Result<&'a str, &'static s... |
// Copyright (c) The Starcoin Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::MyWorld;
use cucumber::{Steps, StepsBuilder};
use scmd::{CmdContext, Command};
use serde_json::Value;
use starcoin_cmd::dev::GetCoinCommand;
use starcoin_cmd::node::{InfoCommand, PeersCommand};
use starcoin_cmd::view::{Acc... |
#![doc = "generated by AutoRust 0.1.0"]
#![allow(unused_mut)]
#![allow(unused_variables)]
#![allow(unused_imports)]
use crate::models::*;
use reqwest::StatusCode;
use snafu::{ResultExt, Snafu};
pub mod database_instances {
use crate::models::*;
use reqwest::StatusCode;
use snafu::{ResultExt, Snafu};
pub... |
/*
Mine simulator .. the mine is represented by an array
... a really poor one :D
*/
use rand::{thread_rng, Rng};
use std::io;
enum MineralType {
MITHRIL,
GOLD,
SILVER,
DIAMOND,
IRON,
CUPPER,
ROCK
}
struct MineSpot {
mineral: MineralType
}
fn init_gold_and_stuff() -> Option<MineSpot>... |
use x86_64::VirtAddr;
use x86_64::structures::tss::TaskStateSegment;
use lazy_static::lazy_static;
// create a static GDT that includes a segment for TSS static:
use x86_64::structures::gdt::{GlobalDescriptorTable,Descriptor,SegmentSelector};
struct Selectors {
code_selector:SegmentSelector,
tss_selector:Segme... |
pub mod agents;
pub mod login;
pub mod permission_membership;
pub mod permissions;
pub mod routers;
pub mod tunnels;
pub mod users;
|
use std::{
io::{Read, Write},
net::{IpAddr, Ipv4Addr, SocketAddr, SocketAddrV4, TcpStream, UdpSocket},
time::{Duration, SystemTime},
};
use argh::FromArgs;
use color_eyre::eyre::WrapErr;
use polling::{Event, Poller};
use flatbuffers_structs::net_protocol::{ConfigArgs, Endpoint, HandshakeArgs};
use protoco... |
use super::service::NewService;
use crate::{frame::*, server::tcp_server::TcpServer};
use futures::future;
use std::{future::Future, io::Error, net::SocketAddr};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Server {
socket_addr: SocketAddr,
threads: Option<usize>,
}
impl Server {
/// Set the addres... |
use eos::types::*;
use std::str::FromStr;
use stdweb::web::error::SecurityError;
use stdweb::web::Location;
use types::*;
#[derive(Clone, PartialEq)]
pub enum Route {
Home(Option<ChainIdPrefix>),
Profile(ChainIdPrefix, AccountName),
PollVoting(ChainIdPrefix, PollId),
PollResults(ChainIdPrefix, PollId),... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.