text stringlengths 8 4.13M |
|---|
pub mod process_epoch;
|
extern crate glutin_window;
extern crate graphics;
extern crate opengl_graphics;
extern crate piston;
use glutin_window::GlutinWindow as Window;
use opengl_graphics::{GlGraphics, OpenGL};
use piston::event_loop::{EventSettings, Events};
use piston::input::{RenderArgs, RenderEvent, UpdateArgs, UpdateEvent};
use piston:... |
use crate::{bikes::BicycleDomain, error::Error};
pub trait BicycleRepoInterface {
fn create(&self, bike: BicycleDomain) -> Result<BicycleDomain, Error>;
fn update(&self, bike: BicycleDomain) -> Result<BicycleDomain, Error>;
fn delete(&self, id: i32) -> Result<bool, Error>;
fn find_all(&self) -> Result<... |
use aubio_rs::{OnsetMode, Tempo};
use nannou::prelude::*;
use nannou::ui::prelude::*;
use nannou_audio as audio;
use ringbuf::{Consumer, Producer, RingBuffer};
fn main() {
nannou::app(model).update(update).simple_window(view).run();
}
widget_ids! {
struct Ids {
startstop,
threshold,
si... |
use mygrep::*;
#[test]
fn query_casesensitive() {
let query = "duct";
let contents = "\
Rust:
safe, fast, productive.
rusty.
Duct tape.";
assert_eq!(vec!["safe, fast, productive."], search(query, contents));
}
#[test]
fn query_caseinsensitive() {
let query = "RuSt";
let contents = "\
Rust:
safe, ... |
use num_format::{Locale, ToFormattedString};
use std::io::{stdout, Write};
use std::iter::repeat;
use std::time::Instant;
use unicode_segmentation::UnicodeSegmentation;
use crate::hash_file_process::{FileProcessEntry, FileProgress};
use crate::speed::get_speed;
use crate::tty::terminal_size;
const OUTPUT_REFRESH_IN_M... |
fn main() {
let number1;
print!("{}", number1);
number1 = 12;
}
|
pub mod add;
pub mod cp;
pub mod ld;
pub mod misc;
pub mod adc;
pub mod xor;
pub mod bit;
pub mod jump;
pub mod call;
pub mod rotate;
pub mod ret;
pub mod sbc;
pub mod sub;
pub mod and;
pub mod res;
|
pub mod manifest;
pub use manifest::*; |
fn lower_bound<T: PartialOrd>(list: &Vec<T>, value: &T) -> usize {
if list.is_empty() {
return 0;
}
let mut lower = 0usize;
let mut upper = list.len();
while lower != upper {
let middle = lower + upper >> 1;
if list[middle] < *value {
lower = middle + 1;
}... |
#![recursion_limit = "1024"]
mod subscribers;
mod types;
mod web_socket_session;
use subscribers::Subscribers;
pub use types::RawMeasurement;
use jsonrpc_core::MetaIoHandler;
use jsonrpc_core::{futures as futuresOne, Params, Value};
use jsonrpc_pubsub::typed::{Sink, Subscriber};
use jsonrpc_pubsub::{PubSubHandler, S... |
pub mod api;
pub mod configuration;
pub mod database;
pub mod database_structures;
pub mod server;
pub mod database_errors;
pub mod emailer;
pub mod oauth;
pub mod authorizer; |
extern crate arkecosystem_crypto;
extern crate serde;
extern crate serde_json;
use serde_json::{from_str, Value};
use std::fs::File;
use std::io::prelude::*;
pub mod transactions;
pub fn json_transaction(transaction_type: &str, name: &str) -> Value {
let path = read_fixture(&format!("transactions/{}/{}", transac... |
use super::service::Service;
use crate::{
await_test_server,
db::builders::UserBuilder,
tests::{self, setup_env, RequestJwtAuthExt as _},
};
use actix_web::{
http::{Method, StatusCode},
test::{call_service, read_body, TestRequest},
};
use bigdecimal::BigDecimal;
use serde_json::{json, Value};
#[act... |
#[macro_use]
extern crate service_core_derive;
#[allow(non_camel_case_types)]
#[mock_service(name = "database", version = "0.1.0")]
pub struct database {}
|
// -*- mode:rust;mode:rust-playground -*-
// snippet of code @ 2017-04-18 11:36:23
// === Rust Playground ===
// Execute the snippet with Ctl-Return
// Remove the snippet completely with its dir and all files M-x `rust-playground-rm`
struct Point<T> {
x: T,
y: T,
}
impl<T> Point<T> {
fn x(&self) -> &T {
... |
// https://www.codewars.com/kata/grasshopper-terminal-game-combat-function-1
fn combat(health: f32, damage: f32) -> f32 {
if health - damage < 0.0 {
0.0
} else {
health - damage
}
}
#[test]
fn example_tests() {
assert_eq!(combat(100.0, 5.0), 95.0);
assert_eq!(combat(92.0, 8.0), 84.... |
use crate::{BalanceOf, Config, Pallet, Relayers};
use frame_support::traits::ExistenceRequirement::AllowDeath;
use frame_support::traits::{Currency, ExistenceRequirement, WithdrawReasons};
use frame_support::PalletId;
use sp_messenger::messages::FeeModel;
use sp_runtime::traits::{AccountIdConversion, CheckedDiv, Checke... |
#![deny(clippy::all, clippy::pedantic)]
#[allow(clippy::needless_pass_by_value)]
pub fn find<V, T>(array: V, key: T) -> Option<usize>
where
T: std::cmp::Ord,
V: AsRef<[T]>,
{
let array = array.as_ref();
let mut range = 0..array.len();
while range.start < range.end {
let idx = range.start +... |
use serde::{Deserialize, Serialize};
use common::event::EventPublisher;
use common::result::Result;
use crate::domain::author::{AuthorId, AuthorRepository};
use crate::domain::category::{CategoryId, CategoryRepository};
use crate::domain::publication::{
Header, Image, Name, Publication, PublicationRepository, Syn... |
use crate::day2;
pub(crate) fn way_down_we_go() {
let input: Vec<String> = day2::fetch_input();
let trees = count_trees(3, 1, input.clone());
let trees1 = count_trees(1, 1, input.clone());
let trees2 = count_trees(5, 1, input.clone());
let trees3 = count_trees(7, 1, input.clone());
let trees4 =... |
use parallel::*;
fn main() {
println!("Parallel: start");
show_cpus();
monte_carlo::pi::main();
println!("Parallel: done");
}
fn show_cpus() {
println!("cores = {}", num_cpus::get_physical());
println!("cpus = {}", num_cpus::get());
} |
use crate::emitter::emitter::Emitter;
use crate::emitter::environment::{Value, Variable};
use crate::parser::node::expression::unary::primary::PrimaryNode;
#[derive(Debug, PartialEq, Clone)]
pub struct PrefixNode {
pub op: String,
pub val: PrimaryNode,
}
impl PrefixNode {
pub fn emit(self, emitter: &mut Em... |
use std::fmt;
use std::fmt::{Display, Formatter};
use std::fs;
use std::io;
use std::path::PathBuf;
use chrono::Utc;
use semver::Version;
use crate::release::Release;
#[derive(Debug)]
pub struct Error(io::Error);
impl Display for Error {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
self.0.fmt(f... |
use crate::{
ast::ty::{Type, TypeData},
wasm::{
frame::frame::{Frame, FrameType, Frame_},
il::{
module::{ModuleList, Module_},
stm::StmList,
},
},
};
use super::entry_map::EntryMap;
pub struct SemanticParam {
pub venv: EntryMap,
pub tenv: EntryMap,
... |
// FIPS-180-1 compliant SHA-1 implementation
//
// The SHA-1 standard was published by NIST in 1993.
// https://csrc.nist.gov/csrc/media/publications/fips/180/2/archive/2002-08-01/documents/fips180-2.pdf
//
// ❗️ SHA1算法在2005年后被证实存在弱点,可以被加以破解。
// ‼️ SHA1算法在2017年被证实无法防止碰撞攻击,因此不适用于安全性认证。
use core::convert::TryFrom;
// NO... |
// q0094_binary_tree_inorder_traversal
struct Solution;
use crate::util::TreeNode;
use std::cell::RefCell;
use std::rc::Rc;
impl Solution {
pub fn inorder_traversal(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<i32> {
match root {
Some(head) => {
let mut ret = vec![];
... |
#[doc = "Reader of register MUX_SWITCH_SQ_CTRL"]
pub type R = crate::R<u32, super::MUX_SWITCH_SQ_CTRL>;
#[doc = "Writer for register MUX_SWITCH_SQ_CTRL"]
pub type W = crate::W<u32, super::MUX_SWITCH_SQ_CTRL>;
#[doc = "Register MUX_SWITCH_SQ_CTRL `reset()`'s with value 0"]
impl crate::ResetValue for super::MUX_SWITCH_SQ... |
//! A parser for the arith language.
//!
//! t :=
//! true
//! false
//! if t then t else t
//! 0
//! succ t
//! pred t
//! iszero t
use std::error;
use std::fmt;
use Term;
/// Errors that may occur during parsing.
#[derive(PartialEq, Debug, Clone)]
pub enum Error {
/// An if t... |
/*!
Bytecode `io` helpers.
*/
use std::io;
use std::mem;
use byteorder::{ self, LittleEndian, ReadBytesExt, WriteBytesExt };
/// Bytecode representation.
pub trait Bytecode {
}
/// Serialize and deserialize a structure from `io`.
pub trait Serializer {
/// Write contents to io `writer`, returns bytes writte... |
// By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
//
// What is the 10 001st prime number?
extern crate project_euler;
fn main() {
let mut primes = project_euler::primes::primes();
// note that nth_prime is 0-indexed, but the problem is 1-indexed.
assert_eq... |
//! This module handles connections to Content Manager Server
//! First you connect into the ip using a tcp socket
//! Then reads/writes into it
//!
//! Packets are sent at the following format: packet_len + packet_magic + data
//! packet length: u32
//! packet magic: VT01
//!
//! Apparently, bytes received are in litt... |
// Implement basic function to split some generic computational work between threads
// Split should occur only on some threshold
// If computational work is shorter that this threshold
// No splitting should occur and no threads should be created
// You get as input:
// 1. Vec<T>
// 2. Function f(t: T) -> R
//... |
mod cli;
mod ndjson;
use std::fs;
use std::io;
fn main() {
let opts = cli::parse_opts();
let uniq_opts = ndjson::Opts {
group: opts.group,
count: opts.count,
};
if opts.file == "-" {
let reader = io::BufReader::new(io::stdin());
ndjson::uniq(reader, &opts.key, io::std... |
#[macro_use]
pub mod register;
pub mod authentication;
use actix_identity::Identity;
use actix_web::error::{ErrorBadRequest, ErrorUnauthorized};
use actix_web::{dev, FromRequest, HttpRequest};
use actix_web::{web, Error, Result};
use chrono::Duration;
use csrf_token::CsrfTokenGenerator;
use futures_util::future::{err,... |
use spair::prelude::*;
impl spair::Render<crate::App> for &spair::FetchError {
fn render(self, nodes: spair::Nodes<crate::App>) {
nodes.div(|d| {
d.nodes()
.span(|s| s.nodes().render(&self.to_string()).done());
});
}
}
|
use crate::error::{Error, Result, RuntimeError};
use crate::parsing::{parse_sexpr, ParseErrorKind, Span};
use crate::scm::Scm;
use std::cell::RefCell;
use std::fs::File;
use std::io::{stderr, stdin, stdout, BufRead, BufReader, BufWriter, Write};
use std::mem::size_of;
pub struct SchemePort {
port: RefCell<PortStat... |
use crate::ast::expressions;
use crate::ast::stack;
use crate::interpreter;
#[derive(Debug)]
pub struct Label(pub Box<dyn expressions::Expression>);
impl interpreter::Eval for Label {}
impl expressions::Expression for Label {}
impl Label {
pub fn new(stack: &mut stack::Stack) {
let (_, name, _) = stack_u... |
use log::error;
use rand::Rng;
use std::{
ffi::CString,
ops::{Add, Div, Mul, Sub},
path::Path,
time::Duration,
};
pub fn to_vec32(vecin: Vec<u8>) -> Vec<u32> { unsafe { vecin.align_to::<u32>().1.to_vec() } }
pub fn load_file(file: &Path) -> Option<Vec<u8>> {
let contents = std::fs::read(file);
... |
fn main() {
let rect = Rectange {
width: 10.0,
height: 20.0,
};
let tri = Triangle {
base: 10.0,
height: 20.0,
};
let cir = Circle {
radius: 10.0
};
println!("rect area is {}", rect.calc_area());
println!("tri area is {}", tri.calc_area());
pr... |
use proconio::input;
// ABC180のE問題に提出してACしたコードです。
// 巡回セールスマン問題を解くものです。
fn main() {
input! {
number_of_cities:usize,
xyz:[(isize,isize,isize);number_of_cities],
}
// distance
let mut distance: Vec<Vec<usize>> = vec![vec![0; number_of_cities]; number_of_cities];
for city_from in 0.... |
use crate::types::{keyword_type::KeywordType, validation_error::ValidationError};
use failure::Fail;
use loader_rs::LoaderError;
use url::{ParseError, Url};
#[derive(Debug, Fail)]
pub(in crate) enum SchemaError {
#[fail(display = "Unknown error")]
Unknown,
#[fail(display = "Malformed Schema: path={}, detai... |
#[doc = "Reader of register RCC_MP_APB3LPENSETR"]
pub type R = crate::R<u32, super::RCC_MP_APB3LPENSETR>;
#[doc = "Writer for register RCC_MP_APB3LPENSETR"]
pub type W = crate::W<u32, super::RCC_MP_APB3LPENSETR>;
#[doc = "Register RCC_MP_APB3LPENSETR `reset()`'s with value 0x0003_290f"]
impl crate::ResetValue for super... |
use super::*;
impl<T: FromPacketBytes> FromPacketBytes for Option<T> {
type Output = Option<T::Output>;
fn from_packet(reader: &mut PacketReader) -> Result<Self::Output, Box<PacketFormatError>> {
if reader.is_empty() {
Ok(None)
} else {
T::from_packet(reader).map(Some)
... |
use llvm_sys::{core::*, execution_engine::*, prelude::*, support::*, target::*, *};
use super::{to_ptr, Type, LLVMTypeCache};
use std::ptr;
pub struct LLVMCompiler {
pub context: LLVMContextRef,
pub module: LLVMModuleRef,
pub builder: LLVMBuilderRef,
pub types: LLVMTypeCache,
}
impl LLVMCompiler {
... |
use common::BitSet;
use std::borrow::Borrow;
use std::borrow::BorrowMut;
use std::cmp::Ordering;
use DocId;
/// Expresses the outcome of a call to `DocSet`'s `.skip_next(...)`.
#[derive(PartialEq, Eq, Debug)]
pub enum SkipResult {
/// target was in the docset
Reached,
/// target was not in the docset, skip... |
use std::fs::{create_dir_all, write as write_file, File};
use std::io::Read;
use std::path::PathBuf;
use sodiumoxide::crypto::sign;
use sodiumoxide::crypto::sign::ed25519::PublicKey;
use sodiumoxide::crypto::sign::ed25519::SecretKey;
pub struct Keyring {
pub public_key: PublicKey,
pub secret_key: SecretKey,
}
im... |
use crate::custom_var::CustomVar;
use crate::function::Function;
use crate::name::Name;
use crate::name_map::NameMap;
use crate::operator::Operator;
use crate::runtime::Runtime;
use crate::std_type::Type;
use crate::string_var::StringVar;
use crate::variable::{FnResult, Variable};
use std::fmt::Debug;
use std::rc::Rc;
... |
#![no_main]
#![no_std]
extern crate cortex_m_rt;
extern crate panic_halt;
use cortex_m_rt::{entry, exception, ExceptionFrame};
#[entry]
fn foo() -> ! {
loop {}
}
#[exception]
unsafe fn HardFault(_ef: &ExceptionFrame) -> ! {
loop {}
}
pub mod reachable {
use cortex_m_rt::{exception, ExceptionFrame};
... |
use chrono;
use lazy_static::lazy_static;
use regex::Regex;
use serde_json::Value;
use crate::validator::{scope::ScopedSchema, state::ValidationState, types::validate_as_string};
lazy_static! {
// ajv v6.7.0 compatible
// https://github.com/epoberezkin/ajv/blob/v6.7.0/lib/compile/formats.js#L90
static ref... |
use heck::*;
use proc_macro2::Span;
use quote::{quote, ToTokens};
use syn::parse::{Parse, ParseStream, Result};
use syn::punctuated::Punctuated;
use syn::{braced, parenthesized, parse_macro_input, token, Ident, Lifetime, Path, PathArguments, PathSegment, Token, TraitBound, TraitBoundModifier, Type, TypeParamBound,... |
use puck_core::Vec3f;
use cgmath::Zero;
use alto;
use std::fs;
use std::path::{PathBuf, Path};
pub mod engine;
pub mod load;
pub mod context;
pub mod source;
pub mod worker;
pub use self::engine::*;
pub use self::worker::*;
pub type SoundName = String;
pub type SoundEventId = u64;
pub type Gain = f32;
pub type ... |
use async_graphql::*;
use futures::{Stream, StreamExt};
#[async_std::test]
pub async fn test_subscription() {
struct QueryRoot;
#[SimpleObject]
struct Event {
#[field]
a: i32,
#[field]
b: i32,
}
#[Object]
impl QueryRoot {}
struct SubscriptionRoot;
#[... |
use std::cmp::{min, max};
use std::fs;
fn find_crossing_points(map: &Vec<Vec<char>>, a: (i32, i32), b: (i32, i32)) -> Vec<(i32, i32)> {
let mut points = vec!();
let ((x1, y1), (x2, y2)) = (a, b);
let ab_dist_sq = ((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1)) as f32;
for x in min(x1, x2)..=max(x1, x2)... |
fn main() {
for _i in 1.. {
println!("Hello, world!");
}
}
|
use crate::{
node::{Node, Tickable},
status::Status,
};
/// A node that will repeat its child a specific number of times, possibly
/// infinite.
///
/// A repeat node will report that it is running until its child node has been
/// run to completion the specified number of times, upon which it will be
/// cons... |
use alloc::string::String;
use core::str::FromStr;
use crate::Client;
use chain::names::{AccountName, ActionName, ParseNameError};
use rpc_codegen::Fetch;
use serde::{Deserialize, Serialize};
#[derive(Fetch, Clone, Debug, Deserialize, Serialize)]
#[api(path="v1/chain/abi_json_to_bin", http_method="POST", returns="Get... |
use std::cell::RefCell;
use std::cmp::*;
use std::rc::Rc;
use crate::treenode::TreeNode;
type ONode = Option<Rc<RefCell<TreeNode>>>;
type RNode = Rc<RefCell<TreeNode>>;
pub fn rob(root: ONode) -> i32 {
fn search(root: RNode) -> (i32, i32) {
let val = root.borrow().val;
let left_max = root.borrow(... |
// 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... |
extern crate hyper;
extern crate futures;
extern crate tokio_core;
use std::str;
use futures::{Future, Stream};
use hyper::Client;
use tokio_core::reactor::Handle;
pub fn get_mta_status(handle: &Handle) -> Box<Future<Item = String, Error = hyper::Error>> {
// This is not a txt file, but actually a URL which retur... |
pub mod publisher;
|
use crate::{error::ProcessingError, fuzzers};
use globset::{Glob, GlobMatcher};
use std::{
fs::{read_dir, DirEntry},
path::Path,
};
pub(crate) fn read_runs(
directory: &Path,
fuzzers: &[fuzzers::Fuzzer],
targets: &[String],
indices: &[String],
) -> Result<Vec<DirEntry>, ProcessingError> {
l... |
use wasm_bindgen::prelude::*;
#[wasm_bindgen(raw_module = "../src/js_zip/js_zip.js")]
extern "C" {
pub type JSZip;
#[wasm_bindgen(constructor)]
pub fn new() -> JSZip;
#[wasm_bindgen(method, js_name = "loadAsync")]
pub fn load_async(this: &JSZip, data: &JsValue) -> js_sys::Promise;
#[wasm_bin... |
use std::vec::Vec;
pub fn factors(number: u64) -> Vec<u64> {
(1..=number).filter(|&value| number % value == 0).collect()
}
pub fn prime_factors(number: u64) -> Vec<u64> {
let mut val = number;
let mut to_ret = Vec::new();
while val > 1 {
if val % 2 == 0 {
to_ret.push(2);
... |
use bw;
use save::{LoadError, SaveError};
use sprites;
use units;
pub trait SaveEntityPointer {
type Pointer;
fn pointer_to_id(&self, pointer: *mut Self::Pointer) -> Result<u32, SaveError>;
}
pub trait LoadEntityPointer {
type Pointer;
fn id_to_pointer(&self, id: u32) -> Result<*mut Self::Pointer, Loa... |
use parser::*;
use std::io::{Write, Error};
pub struct Generator {
prelude: Option<String>,
attrs: Vec<String>,
typemap: Box<Fn(&SpecFieldType) -> String>,
ser: Box<Fn(&SpecFieldType) -> String>,
de: Box<Fn(&SpecFieldType) -> String>,
namemap: Box<Fn(&str) -> String>
}
impl Generator {
const DEFAULT_SER: &'st... |
use crate::blob::blob::generate_blob_uri;
use crate::blob::blob::responses::CopyBlobResponse;
use crate::core::prelude::*;
use crate::{RehydratePriority, RehydratePriorityOption, RehydratePrioritySupport};
use azure_core::errors::AzureError;
use azure_core::lease::LeaseId;
use azure_core::prelude::*;
use azure_core::{N... |
struct Fib {
first: u32,
second: u32,
}
fn fib() -> Fib {
Fib {
first: 0,
second: 1,
}
}
impl Iterator for Fib {
type Item = u32;
fn next(&mut self) -> Option<Self::Item> {
let origin_first = self.first;
let origin_second = self.second;
match origin_fir... |
// use failure;
use failure_derive::Fail;
/// Error type for kvs
#[derive(Debug, Fail)]
pub enum KvsError {
/// caused by IO error
#[fail(display = "{}", _0)]
IoError(#[cause] std::io::Error),
/// caused by serde error
#[fail(display = "{}", _0)]
SerdeError(#[cause] serde_json::error::Error),
... |
//! A library to read binary protobuf files
//!
//! This reader is developed similarly to a pull reader
#![deny(missing_docs)]
#![allow(dead_code)]
extern crate byteorder;
extern crate failure;
extern crate failure_derive;
pub mod errors;
pub mod message;
pub mod reader;
pub mod sizeofs;
pub mod writer;
pub use err... |
//! Some general utility functions.
use std::{iter, str::from_utf8};
use strip_ansi_escapes::strip;
fn ansi_len(s: &str) -> usize {
from_utf8(&strip(s.as_bytes()).unwrap())
.unwrap()
.chars()
.count()
}
pub fn adjust_to_size(s: &str, rows: usize, columns: usize) -> String {
s.lines()... |
mod term_query;
mod term_weight;
mod term_scorer;
pub use self::term_query::TermQuery;
pub use self::term_weight::TermWeight;
pub use self::term_scorer::TermScorer;
#[cfg(test)]
mod tests {
use docset::DocSet;
use postings::SegmentPostings;
use query::{Query, Scorer};
use query::term_query::TermScore... |
//! Test helpers
/// parse the output of `ps aux`
pub fn parse_ps_aux(ps_aux: &str) -> Vec<PsAuxEntry> {
let mut entries = vec![];
for line in ps_aux.lines().skip(1 /* header */) {
let columns = line.split_ascii_whitespace().collect::<Vec<_>>();
let entry = PsAuxEntry {
command: co... |
use ra_db::FileId;
use ra_syntax::ast;
use crate::db::RootDatabase;
pub fn goto_defenition(db: &RootDatabase, position: FilePosition,
) -> Cancelable<Option<Vec<NavigationTarget>>> {
let file = db.source_file(position.file_id);
let syntax = file.syntax();
if let Some(name_ref) = find_node_at_offset::<ast:... |
use criterion::{criterion_group, criterion_main};
use criterion::{BenchmarkId, Criterion};
#[cfg(unix)]
use pprof::criterion::{Output, PProfProfiler};
use ppp::v1;
use std::net::{Ipv4Addr, Ipv6Addr};
fn benchmarks(c: &mut Criterion) {
let mut group = c.benchmark_group("PPP Text");
let inputs = [
("U... |
Version {
minor: 44,
patch: 1,
channel: Stable,
}
|
use std::time::Duration;
use frp_gaming_lib::drawer::{Drawer, DrawerCommand};
use frp_gaming_lib::glium::glutin::event::Event;
use frp_gaming_lib::glium::{Frame, Surface};
use frp_gaming_lib::sodium_rust::Stream;
use frp_gaming_lib::timer::Timer;
pub fn create_drawer_command<CustomEvent>(
_event: &Stream<Event<'s... |
pub mod named_field;
pub mod tuple_like;
pub mod unit_like;
|
/*
* Datadog API V1 Collection
*
* Collection of all Datadog Public endpoints.
*
* The version of the OpenAPI document: 1.0
* Contact: support@datadoghq.com
* Generated by: https://openapi-generator.tech
*/
/// SyntheticsDeviceId : The device ID.
/// The device ID.
#[derive(Clone, Copy, Debug, Eq, PartialEq, ... |
use flate2::write::GzEncoder;
use flate2::Compression;
use iron::headers::{AcceptEncoding, ContentEncoding, ContentType, Encoding};
use iron::prelude::*;
use iron::AfterMiddleware;
use iron_staticfile_middleware::helpers;
pub struct GzipMiddleware;
impl AfterMiddleware for GzipMiddleware {
fn after(&self, req: &m... |
#[doc = "Reader of register SR"]
pub type R = crate::R<u32, super::SR>;
#[doc = "Reader of field `DCOL`"]
pub type DCOL_R = crate::R<bool, bool>;
#[doc = "Reader of field `TXE`"]
pub type TXE_R = crate::R<bool, bool>;
#[doc = "Reader of field `RFF`"]
pub type RFF_R = crate::R<bool, bool>;
#[doc = "Reader of field `RFNE... |
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#![crate_type = "proc-macro"]
use quote::quote;
use syn::parse_macro_input;
use syn::DeriveInput;
extern crate proc_macro;
use ... |
mod first_line;
mod second_line;
use std::fmt::{Display, Error, Formatter};
use zellij_tile::prelude::*;
use first_line::{ctrl_keys, superkey};
use second_line::keybinds;
pub mod colors {
use ansi_term::Colour::{self, Fixed};
pub const WHITE: Colour = Fixed(255);
pub const BLACK: Colour = Fixed(16);
... |
use std::fs::File;
use std::io::prelude::*;
fn read_data(filepath: &str) -> std::io::Result<String> {
let mut file = File::open(filepath)?;
let mut contents: String = String::new();
file.read_to_string(&mut contents)?;
Ok(contents.trim().to_string())
}
/// # Errors
///
/// Returns () as error for lack... |
pub mod lexer;
pub mod parser;
pub mod runner;
pub mod helpers;
pub mod builtins;
|
// Takes a list of entities with bodies, then spits out their transformations.
pub struct PhysicsEngine;
impl PhysicsEngine {
pub fn new() -> Self {
PhysicsEngine
}
pub fn step(&mut self) {}
} |
use crate::errors::Errcode;
use crate::ipc::{send_boolean, receive_boolean};
use std::os::unix::io::RawFd;
use nix::sched::{unshare, CloneFlags};
use nix::unistd::{Gid, Uid, setgroups, setresuid, setresgid};
pub fn userns(fd: RawFd, uid: u32) -> Result<(), Errcode> {
log::debug!("Setting up user namespace with U... |
// Copyright (C) 2015-2021 Swift Navigation Inc.
// Contact: https://support.swiftnav.com
//
// This source is subject to the license found in the file 'LICENSE' which must
// be be distributed together with this source. All other rights reserved.
//
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ... |
use std;
#[derive(Eq,PartialEq)]
pub enum RespValue {
Int(i64),
NilBulk,
NilArray,
Bulk(Vec<u8>),
Array(Vec<RespValue>),
Error(Vec<u8>),
}
impl std::fmt::Debug for RespValue {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
RespValue::N... |
use std::borrow::Cow;
use std::collections::BTreeMap;
use std::fmt::Debug;
use std::fs;
use camino::Utf8Path;
use chrono::{NaiveDate, NaiveDateTime, NaiveTime};
use eyre::{eyre, Result};
use itemref_derive::ItemRef;
use lazy_static::lazy_static;
use rayon::iter::{IntoParallelRefIterator, ParallelIterator};
use regex::... |
#![allow(unused_variables)]
#![allow(unused_mut)]
#![allow(unused_imports)]
#![allow(dead_code)]
use std::fs::File;
use std::io::prelude::*;
use std::env;
use std::rc::Rc;
pub use crate::configuration::Configuration;
pub use crate::globalstate::GlobalState;
pub use crate::instructions::Instruction;
pub use crate::ins... |
use date_time::{date_tuple::DateTuple, time_tuple::TimeTuple};
use log::error;
use serenity::{
framework::standard::{macros::command, CommandResult},
model::channel::Message,
prelude::*,
};
#[command]
#[description = "Display the date in format: `14:47 | 28 May 2020`."]
fn date(ctx: &mut Context, msg: &Mes... |
use maat_graphics::math;
use maat_graphics::cgmath::{Vector2, Vector3};
use maat_graphics::cgmath::InnerSpace;
use maat_graphics::cgmath::Zero;
use crate::modules::Boid;
pub fn boid_collision(boids: &mut Vec<Boid>, delta_time: f32) {
let clone_boids = boids.clone();
for i in 0..boids.len() {
boid_math(i, b... |
// Copyright (c) The Starcoin Core Contributors
// SPDX-License-Identifier: Apache-2.0
use anyhow::{ensure, format_err, Result};
use config::NodeConfig;
use crypto::{hash::PlainCryptoHash, HashValue};
use logger::prelude::*;
use starcoin_accumulator::{
node::AccumulatorStoreType, Accumulator, AccumulatorTreeStore,... |
use crate::Server;
use log::info;
use notify_rust;
use notify_rust::{Notification, NotificationHandle};
use std::{error::Error, io};
pub struct Importer {
pub state: State,
pub config: Config,
}
pub mod config;
mod link;
mod sync;
use config::Config;
pub mod state;
use state::State;
impl Importer {
pu... |
pub struct PseudorandomFloatGenerator {
state: u32,
}
/// Generates floats (f64) between 0.0 (inclusive) and 1.0 (exclusive).
///
/// Uses [Xorshift](https://en.wikipedia.org/wiki/Xorshift)
impl PseudorandomFloatGenerator {
pub fn new(seed: u32) -> PseudorandomFloatGenerator {
PseudorandomFloatGenerato... |
#[derive(Debug)]
enum Ipaddress {
Ipaddrv4(i32,i32,i32,i32),
Ipaddrv6(String)
}
#[derive(Debug)]
enum Option<T>{
Some(T),
None
}
fn main() {
let v4 = Ipaddress::Ipaddrv4(0,0,0,0);
let v6 = Ipaddress::Ipaddrv6(String::from("::!"));
println!("{:?}", v4);
println!("This address:: {}", whi... |
use std::process::Command;
fn main(){
let output = if cfg!(target_os = "windows") {
Command::new("cmd")
.args(&["/C", "echo hello"])
.output()
.expect("failed to execute process")
} else {
Command::new("ls")
// .arg("-c")
... |
extern crate iref;
use std::convert::TryInto;
use iref::{Iri, IriRef, IriRefBuf};
fn main() -> Result<(), iref::Error> {
let mut iri_ref = IriRefBuf::default(); // an IRI reference can be empty.
// An IRI reference with a scheme is a valid IRI.
iri_ref.set_scheme(Some("https".try_into()?));
let iri: Iri = iri_re... |
//! Based on http://www.gc-forever.com/yagcd/chap14.html#sec14.1
use encoding_rs::{UTF_8, SHIFT_JIS};
use failure::{err_msg, Error};
const COLUMNS: usize = 24;
const ROWS: usize = 8;
const PIXELS_PER_COLUMN: usize = 4;
const PIXELS_PER_ROW: usize = 4;
const WIDTH: usize = 96;
const HEIGHT: usize = 32;
const UNCOMPRES... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.