text stringlengths 8 4.13M |
|---|
#![allow(dead_code)]
use std::collections::HashMap;
use std::cmp::max;
use crate::prime::{Primes};
// 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
// What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
fn prob... |
// 2019-02-16
// Cours sur les traits. On va suivre tranquillement parce que je comprends pas.
// Suivons le cours et réalisons des structs de texte : un article,
// Voir lib.rs pour la définition du trait et des structs
use definition_traits::{NewsArticle, Summary, Tweet, notify, notifier};
fn main() {
// Créo... |
use protocol::error::SerError as Error;
use protocol::serde_am::*;
pub type SerResult = Result<(), SerError>;
pub mod textbig {
use protocol::field::*;
pub fn serialize(val: &str, ser: &mut Serializer) -> SerResult {
let bytes = val.as_bytes();
if bytes.len() > 0xFFFF {
return Err(Error::ArrayLengthTooBig)... |
impl Solution {
pub fn profitable_schemes(n: i32, min_profit: i32, group: Vec<i32>, profit: Vec<i32>) -> i32 {
let (min_profit,n) = (min_profit as usize,n as usize);
let MOD = 1e9 as i32 + 7;
let mut dp = vec![vec![0;min_profit + 1];n + 1];
for i in 0..=n{
dp[i][0] = 1;
... |
#[cfg(all(feature = "compress", feature = "decompress"))]
#[test]
fn test_compress_decompress() {
use relox::{elf32_relocate, Elf32Relocs};
const REL1: [u8; 192] = [
0x00, 0x08, 0x00, 0x40, 0x02, 0x65, 0x00, 0x00, 0x10, 0x08, 0x00, 0x40, 0x02, 0x29, 0x00,
0x00, 0x18, 0x08, 0x00, 0x40, 0x02, 0x6... |
pub fn simulate_rolls(){
let mut game = new_game();
roll(&mut game);
println!("{:?}", game);
println!("Scoring Roll...");
println!("{:?}", score_roll(&game.roll));
const ROLLS: usize = 100000;
println!("Simulating rolls for {} rolls", ROLLS);
let now = Instant::now();
le... |
// Copyright 2014 Pierre Talbot (IRCAM)
// 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... |
use common::*;
use standard;
/// A Future that produces a random `u8` after a delay of 1 second
pub struct Producer {
inner: standard::instant::Producer,
sleeper: standard::sleeper::Sleeper,
}
impl Producer {
pub fn new() -> Producer {
Producer {
inner: standard::instant::Producer::new(),
sl... |
//Defines what Intcode instructions look like~
enum IntcodeInstruction {
Add { lhs: u32, rhs: u32, dest: u32 },
Mul { lhs: u32, rhs: u32, dest: u32 },
Halt,
}
impl IntcodeInstruction {
//Instructions are built from a slice (of which 1 element is read, and perhaps 3 more)
// We also keep track of the... |
/*
* 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
*/
/// SyntheticsBrowserTestResultFull : Object returned describing a browser test result.
#[derive(Clon... |
#![feature(plugin)]
#![plugin(rocket_codegen)]
extern crate c_vec;
extern crate rocket;
extern crate rocket_contrib;
extern crate sdl2;
extern crate url;
mod url_open;
/*
* #![recursion_limit = "1024"]
*
* #[macro_use]
* extern crate error_chain;
*
* mod errors {
* error_chain!{}
* }
*
* use er... |
use crate::utils::get_fl_name;
use proc_macro::TokenStream;
use quote::*;
use syn::*;
pub fn impl_group_trait(ast: &DeriveInput) -> TokenStream {
let name = &ast.ident;
let name_str = get_fl_name(name.to_string());
let begin = Ident::new(format!("{}_{}", name_str, "begin").as_str(), name.span());
let ... |
#![feature(allocator_api)]
pub mod arena;
pub mod linear;
pub mod scope_stack;
|
use crate::mesh::{Mesh, Vertex};
use descartes::{P2, N, LinePath, PrimitiveArea, Band};
use lyon_tessellation::math::point as lyon_point;
use lyon_tessellation::path::iterator::PathIter;
use lyon_tessellation::path::PathEvent;
use lyon_tessellation::{FillOptions, FillTessellator};
use std::rc::Rc;
pub struct SculptLin... |
#[doc = "Register `WPCR2` reader"]
pub type R = crate::R<WPCR2_SPEC>;
#[doc = "Register `WPCR2` writer"]
pub type W = crate::W<WPCR2_SPEC>;
#[doc = "Field `HSTXDCL` reader - High-Speed Transmission Delay on Clock Lane"]
pub type HSTXDCL_R = crate::FieldReader;
#[doc = "Field `HSTXDCL` writer - High-Speed Transmission D... |
#![warn(unused_extern_crates)]
mod chain_spec;
#[macro_use]
mod service;
mod cli;
mod command;
#[cfg(feature = "parachain")]
const DEFAULT_PARACHAIN_ID: u32 = 9123;
fn main() -> sc_cli::Result<()> {
command::run()
}
|
#[doc = "Reader of register CLK_SYS_CTRL"]
pub type R = crate::R<u32, super::CLK_SYS_CTRL>;
#[doc = "Writer for register CLK_SYS_CTRL"]
pub type W = crate::W<u32, super::CLK_SYS_CTRL>;
#[doc = "Register CLK_SYS_CTRL `reset()`'s with value 0"]
impl crate::ResetValue for super::CLK_SYS_CTRL {
type Type = u32;
#[i... |
use shorthand::ShortHand;
#[derive(ShortHand)]
#[shorthand(verify(fn))]
struct Example {
field: usize,
}
fn main() {}
|
use std::fs;
fn main() {
read_file();
}
fn read_file() {
let text = fs::read_to_string("resource/sample.txt").unwrap();
println!("{}", text);
println!("{}", text.chars().rev().collect::<String>());
} |
use crate::debug_logger::{DebugLogger, FromEnvList};
lazy_static! {
pub static ref CPU_LOGGER: CpuDebug = CpuDebug::env("CPU_DEBUG").build();
}
#[derive(Default)]
pub struct CpuDebug {
current_instruction: bool,
current_register_values: bool,
alu: bool,
bitwise: bool,
control: bool,
ld: bo... |
#[derive(Debug)]
pub enum Error {
MismatchedBrackets,
IOError(std::io::Error),
EOF,
}
impl From<std::io::Error> for Error {
fn from(err: std::io::Error) -> Error {
Error::IOError(err)
}
}
type CellContent = u8;
struct Tape {
contents: [CellContent; 30000],
}
impl Tape {
pub fn ge... |
/*!
```rudra-poc
[target]
crate = "parallel-event-emitter"
version = "0.2.4"
[report]
issue_url = "https://github.com/novacrazy/parallel-event-emitter/issues/2"
issue_date = 2021-03-02
[[bugs]]
analyzer = "SendSyncVariance"
bug_class = "SendSyncVariance"
rudra_report_locations = ["src/lib.rs:237:5: 237:50"]
```
!*/
#... |
struct Point {
x: i32,
y: i32,
}
fn destructuring_structs () {
let p = Point { x: 0, y: 7 };
let Point { x: a, y: b } = p; // source first - [source]: [destination]
println!("a = {}, b = {}", a, b);
let Point { x, y } = p; // compact syntax
println!("x = {}, y = {}", x, y);
}
fn destructur... |
use crate::logger;
use age::{
armor::{ArmoredReader, ArmoredWriter, Format},
x25519, Decryptor, Encryptor, Identity, Recipient,
};
use anyhow::{anyhow, bail, Context, Error, Result};
use bastion::prelude::*;
use edn_rs::Edn;
use secrecy::{ExposeSecret, Secret};
use std::{
collections::HashSet,
fmt::Disp... |
pub mod board;
pub mod hands;
mod impl_game;
pub use crate::game::board::Board;
pub use crate::game::hands::{Hand, HandOf2, HandOf4, HandOf5};
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Game {
TexasHoldem(Board, Vec<HandOf2>),
OmahaHoldem(Board, Vec<HandOf4>),
FiveCardDraw(Vec<HandOf5>),
}
|
#[cfg(test)]
mod candidate_pair_test;
#[cfg(test)]
mod candidate_relay_test;
#[cfg(test)]
mod candidate_server_reflexive_test;
#[cfg(test)]
mod candidate_test;
pub mod candidate_base;
pub mod candidate_host;
pub mod candidate_peer_reflexive;
pub mod candidate_relay;
pub mod candidate_server_reflexive;
use crate::netw... |
// Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0.
pub use crocksdb_ffi::{self, DBFileSystemInspectorInstance};
use libc::{c_char, c_void, size_t, strdup};
// Inspect global IO flow. No per-file inspection for now.
pub trait FileSystemInspector: Sync + Send {
fn read(&self, len: usize) -> Result<... |
#[derive(Copy, Debug, Clone)]
pub struct Disk<'a> {
pub file: &'a str,
pub reads: u32,
pub writes: u32,
}
impl<'a> Disk<'a> {
pub fn new(file_name: &str) -> Disk {
Disk {
file: file_name,
reads: 0,
writes: 0,
}
}
pub fn read(self) -> Disk<'a> ... |
use futures::future::{self, Future, IntoFuture};
use crate::server::{Code, UserInfo};
use futures_locks::RwLock;
use std::time::Instant;
use quick_error::quick_error;
#[derive(Debug)]
pub struct StorageError {
inner: Box<dyn std::error::Error>
}
impl std::fmt::Display for StorageError {
fn fmt(&se... |
use crate::helpers::algorithms::gsom::{create_test_network, Data};
use crate::utils::{DefaultRandom, Random};
#[test]
fn can_train_network() {
let mut network = create_test_network();
let samples = vec![Data::new(1.0, 0.0, 0.0), Data::new(0.0, 1.0, 0.0), Data::new(0.0, 0.0, 1.0)];
// train
let random ... |
/// This is an exercise to test Trait, Generic Types.
mod shapes;
use shapes::shapes::{
Triangle, Rectangle, Round
};
use shapes::calculable::AreaCalculable;
/// The main function will print 3 shapes' area one by one, which are all AreaCalculable.
fn main() {
let shape_1 = Triangle { bot_edge: 4.0, height: 3... |
use pongo::ui::{Drawable,Ui};
use sdl2::pixels::Color;
use sdl2::rect::Rect;
pub struct Net {
pub color: Color,
pub x: f32, // x pixel coordinate of top left corner
pub dot_width: f32,
pub dot_height: f32,
pub num_dots: i32
}
impl Net {
pub fn new(color: Color, x: f32, do... |
use pest::iterators::{Pair, Pairs};
use pest::Parser as ParserTrait;
use pest_derive::Parser;
use bear_vm::vm;
pub mod ast;
#[derive(Parser)]
#[grammar = "bearasm.pest"] // relative to src
pub struct G;
#[derive(Debug)]
pub struct Error {
pub message: String,
pub position: Option<Position>,
}
impl Error {
... |
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use std::env;
fn main() {
let hermes_build = env::var("HERMES_BUILD")
.expect("HERMES_BUILD must point to a Hermes CMa... |
use dns::{MandatedLength, WireError};
use dns_transport::Error as TransportError;
pub fn error_message(error: TransportError) -> String {
match error {
TransportError::WireError(e) => wire_error_message(e),
TransportError::TruncatedResponse => "Truncated response".into(),
TransportError::Ne... |
use crate::lbvrf::LBVRF;
use crate::param::Param;
use crate::serde::Serdes;
use crate::VRF;
#[test]
fn test_param() {
let mut rng = rand::thread_rng();
let _param = Param::init(&mut rng);
}
#[test]
fn test_serdes_param() {
let seed = [0u8; 32];
// let mut rng = rand::thread_rng();
// let param = P... |
use x86_64::VirtAddr;
use x86_64::structures::tss::TaskStateSegment;
use x86_64::structures::gdt::SegmentSelector;
use x86_64::structures::gdt::{GlobalDescriptorTable, Descriptor};
use lazy_static::lazy_static;
use crate::{serial_println};
/// Define a stack to use as the double fault stack (any stack works)
///
///... |
pub fn group_by<I, F, K, T>(xs: I, mut key_fn: F) -> Vec<(K, Vec<T>)>
where
I: IntoIterator<Item = T>,
F: FnMut(&T) -> K,
K: Eq,
{
let mut groups = Vec::<(K, Vec<T>)>::new();
for item in xs {
let key = key_fn(&item);
let last = groups.last_mut();
if let Some((_, group)) = las... |
use std::fs::File;
use std::io::Read;
use std::path::Path;
use thiserror::Error;
use url::Url;
/// Attachment error
#[derive(Error, Debug)]
pub enum AttachmentError {
/// Error from [`std::io`]
#[error("IO error: {0}")]
IO(#[from] std::io::Error),
/// Error from [`reqwest`] crate
#[error("reqwest e... |
use std::io; // use the standard library, kinda like c++ huh
use std::cmp::Ordering;
use rand::Rng; //use the random librabry
fn /*Declare a function*/ main() /*Parameters here kinda like c++*/ {
println!("Guessing Game By Decode!"); // this is how we prints in Rust
let secret_number = rand::thread_rng().gen_... |
use aoc2020::aoc::load_data;
use nom::{
bits::complete::*, branch::*, bytes::complete::*, character::complete::*, combinator::*,
multi::*, sequence::*, IResult,
};
use regex::Regex;
use std::collections::HashMap;
use std::collections::HashSet;
use std::fmt::Debug;
use std::hash::Hash;
use std::io::BufRead;
fn ... |
//! The snake game.
//!
//! This is not a properly designed game! Mainly game loop, input events
//! handling, UI separation, ... The main purpose of this example is to
//! test the `crossterm` crate and demonstrate some of the capabilities.
use std::convert::TryFrom;
use std::io::{stdout, Write};
use std::iter::Iterat... |
// Copyright (c) The Starcoin Core Contributors
// SPDX-License-Identifier: Apache-2.0
//! This module defines error types used by sgstorage.
use thiserror::Error;
/// This enum defines errors commonly used among SgStorage APIs.
#[derive(Debug, Error)]
pub enum SgStorageError {
/// A requested item is not found.... |
use std::io;
use std::io::BufRead;
use std::process;
fn main() {
let first_arg = std::env::args().nth(1).unwrap_or_else(|| String::from("0"));
if first_arg == "--help" || first_arg == "-h" {
println!("nth - Select the nth line(s) from STDIN");
println!();
println!("Usage:");
pr... |
use std::convert::TryInto;
use crate::vm::code::get_op;
use crate::common::{ Closure, Opcode, Value };
use crate::parser::ast::{
Node, Stmt, Expr, UnOp, BinOp
};
#[derive(Clone, Debug)]
pub struct VarInfo {
pub name: String,
pub pos: u8,
pub captured: bool
}
impl VarInfo {
pub fn new(name: String, pos: u8)... |
extern crate futures;
extern crate hyper;
extern crate tokio_core;
use futures::{future,Future,Stream};
use hyper::{Client, Error, Chunk, Body};
use tokio_core::reactor::Core;
#[derive(Debug)]
enum Meta {
PNG(u32,u32),
Unknown,
}
fn main() {
let url = "http://www.freepngimg.com/download/light/1-2-light-p... |
use std::time::Duration;
use futures::{future::Either, StreamExt, TryStreamExt};
use serde::{Deserialize, Serialize};
use crate::{
bson::doc,
options::{CreateCollectionOptions, CursorType, FindOptions},
runtime,
test::{log_uncaptured, util::EventClient, TestClient, SERVERLESS},
};
#[cfg_attr(feature ... |
//! Rendering simulation input structure.
use crate::{input::Settings, parts::Attributes};
use arctk::{
geom::{Mesh, Tree},
ord::Set,
};
use palette::{Gradient, LinSrgba};
/// Rendering main input structure.
pub struct Scene<'a, T: Ord> {
/// Adaptive tree.
pub tree: &'a Tree<'a, &'a T>,
/// Engin... |
//! This module defines the [`BufPolicy`](trait.BufPolicy.html) trait,
//! which configures how the internal buffer of the parsers should grow upon
//! encountering large sequences that don't fit into the buffer.
//!
//! The standard policy ([`DoubleUntil`](struct.DoubleUntil.html))
//! causes the initial buffer to dou... |
#[doc = "Reader of register HOST_CTL0"]
pub type R = crate::R<u32, super::HOST_CTL0>;
#[doc = "Writer for register HOST_CTL0"]
pub type W = crate::W<u32, super::HOST_CTL0>;
#[doc = "Register HOST_CTL0 `reset()`'s with value 0"]
impl crate::ResetValue for super::HOST_CTL0 {
type Type = u32;
#[inline(always)]
... |
use crate::{
binding::{Binder, DebruijnIndex},
error::TyError,
polarity::Polarity,
scope::TyScope,
FuncTy, LatticeOpTy, RecordTy, Ty, TyDatabase, TyTables,
};
use core::fmt;
use hashbrown::HashSet;
use valis_ds::{DebugWith, FmtWith, Intern, Untern};
use valis_ds_macros::DebugWith;
use valis_hir::{
... |
use criterion::{black_box, criterion_group, criterion_main, Criterion};
use std::io::Cursor;
use fmlrc::bv_bwt::BitVectorBWT;
use fmlrc::bwt_converter::convert_to_vec;
use fmlrc::read_correction::bridge_kmers;
use fmlrc::ropebwt2_util::create_bwt_from_strings;
use fmlrc::stats_util::*;
use fmlrc::string_util::*;
fn ... |
use std::fs::File;
use std::io::prelude::*;
use std::env;
use std::process;
pub mod convert_types;
pub mod crypt;
pub mod subkey_gen;
pub mod whiten;
#[cfg(test)]
mod test;
const NUM_EXPECTED_ARGS: usize = 2;
/// Displays a message telling the user how to properly run the program
/// Invoked when a command line par... |
use std::{
env,
path::{Path, PathBuf},
};
use anyhow::{bail, Result};
use pico_args::Arguments;
use xshell::{cmd, pushd, pushenv};
fn main() -> Result<()> {
let _d = pushd(project_root());
let mut args = Arguments::from_env();
let subcommand = args.subcommand()?.unwrap_or_default();
match su... |
#[derive(Debug)]
struct Person {
name: String,
age: u32,
}
#[derive(Debug)]
enum Event {
Quit,
KeyDown(u8),
MouseDown {x: i32, y: i32}
}
fn func(code: i32) -> Result<i32, String> {
println!("code: {}", code);
Ok(100)
}
fn error_handling(result: Result<i32, String>) -> Result<i32, String> ... |
pub mod math;
pub mod music;
pub mod reply;
#[macro_export]
macro_rules! mk_group {
($name: ident , $($coms: ident),*) => {
#[group]
#[commands($($coms,)*)]
struct $name;
};
}
#[macro_export]
macro_rules! cmd_ctx_msg {
($name: ident,$ctx: ident, $msg: ident , $args: ident , $($line... |
use std::env;
use crate::{data::OauthClient, error::AppError};
use actix_session::Session;
use actix_web::{http::header, web, HttpResponse};
use oauth2::{reqwest::async_http_client, AsyncCodeTokenRequest, AuthorizationCode, TokenResponse};
use serde::Deserialize;
#[derive(Debug, Deserialize)]
pub struct AuthRequest {... |
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - LPTIM interrupt and status register"]
pub lptim_isr: LPTIM_ISR,
#[doc = "0x04 - LPTIM interrupt clear register"]
pub lptim_icr: LPTIM_ICR,
#[doc = "0x08 - LPTIM interrupt enable register"]
pub lptim_ier: LPTIM_IER,
... |
use butterfly_extractor::{Client, WebpageParser};
use env_logger::Builder;
use log::LevelFilter;
extern crate clap;
use clap::{App, Arg};
use log::info;
fn main() {
Builder::from_default_env()
.filter_level(LevelFilter::Info)
.default_format_module_path(false)
.default_format_timestamp(fal... |
use crate::models::user::SlimUser;
use crate::utils::jwt::decode_token;
use actix_web::{dev, http::header, Error, FromRequest, HttpRequest};
use futures::future::{ok, Ready};
pub type LoggedUser = SlimUser;
impl FromRequest for LoggedUser {
type Error = Error;
type Future = Ready<Result<Self, Self::Error>>;
... |
#[doc = "Reader of register CH_AL2_CTRL"]
pub type R = crate::R<u32, super::CH_AL2_CTRL>;
impl R {}
|
use by_blocks::prelude::*;
use fast_tracer::svg;
use rayon::prelude::*;
use std::collections::LinkedList;
fn main() {
svg("deadline.svg", || {
let start = std::time::Instant::now();
let s = (0..100_000_000u32)
.into_par_iter()
.map(|e| e % 2 + e % 3)
.deadline(st... |
#![allow(dead_code)]
#![allow(unused_variables)]
// enums
// -----
#[derive(Debug)]
enum IpAddrKind {
V4,
V6,
}
#[derive(Debug)]
struct IpAddrStruct {
kind: IpAddrKind,
address: String,
}
#[derive(Debug)]
enum IpAddr {
V4(u8, u8, u8, u8),
V6(String),
}
enum Message {
Quit,
Move { x:... |
extern crate base64;
use std::str;
pub fn to_base64(hex: &str) -> String {
base64::encode(&to_bytes(hex))
}
pub fn to_bytes(hex: &str) -> Vec<u8> {
assert!(
hex.len() % 2 == 0,
"Hex strings must have an even number of characters."
);
hex.as_bytes()
.chunks(2) // each char repr... |
use std::rc::Rc;
use std::any::Any;
use subscriber::*;
use observable::*;
use unsub_ref::UnsubRef;
use std::sync::atomic::AtomicBool;
use std::sync::Arc;
use std::sync::atomic::Ordering;
pub struct TakeUntilState
{
notified: Arc<AtomicBool>
}
pub struct TakeUntilOp<VNoti, Src>
{
source : Src,
noti: Arc<O... |
// Copyright 2017 pdb Developers
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or distributed except according to tho... |
//! Shared domain worker functions.
use crate::utils::{to_number_primitive, BlockInfo, OperatorSlotInfo};
use futures::channel::mpsc;
use futures::{SinkExt, Stream, StreamExt};
use sc_client_api::{BlockBackend, BlockImportNotification, BlockchainEvents};
use sp_api::{ApiError, BlockT, ProvideRuntimeApi};
use sp_blockc... |
pub use self::engine_runner::EngineRunner;
pub use self::silly::SillyRun;
pub mod engine_runner;
pub mod silly;
|
use super::*;
use hashing::hash;
use int_to_bytes::int_to_bytes32;
use std::ops::Range;
pub mod btree_overlay;
pub mod impls;
pub mod resize;
pub use btree_overlay::BTreeOverlay;
#[derive(Debug, PartialEq, Clone)]
pub enum Error {
ShouldNotProduceBTreeOverlay,
NoFirstNode,
NoBytesForRoot,
UnableToObt... |
use rustenger_shared::codec::ClientCodec;
use std::{
iter,
net::{Ipv4Addr, SocketAddr, TcpStream},
};
mod framed;
use framed::Framed;
const DEFAULT_ADDR: Ipv4Addr = Ipv4Addr::LOCALHOST;
const DEFAULT_PORT: u16 = 4732;
fn main() {
let matches = clap::App::new("Rustenger console client")
.version("... |
use HashMap;
use HashSet;
use chain::{Block, Chain, Event, Hash};
use log;
use message::{Action, Message};
use node::{self, Node};
use params::Params;
use prefix::{Name, Prefix};
use random;
use std::collections::hash_map::{self, Entry};
use std::fmt;
use std::mem;
use std::u8;
pub struct Section {
prefix: Prefix,... |
//! Inspired by https://github.com/jacktasia/dumb-jump/blob/master/dumb-jump.el.
//!
//! This module requires the executable rg with `--json` and `--pcre2` is installed in the system.
use std::collections::HashMap;
use std::path::PathBuf;
use anyhow::Result;
use rayon::prelude::*;
use structopt::StructOpt;
use crate... |
#![cfg_attr(feature = "clippy", feature(plugin))]
#![cfg_attr(feature = "clippy", plugin(clippy))]
#![feature(alloc)]
#![feature(ptr_offset_from)]
#![feature(raw_vec_internals)]
#[macro_use]
pub mod maptable;
pub mod db;
pub mod env;
pub mod util;
#[cfg(test)]
mod tests {
#[test]
fn it_works() {
ass... |
use serde_derive::Deserialize;
#[derive(Deserialize, Debug, PartialEq)]
struct NewType<T>(T);
#[test]
fn deserialize_newtype_i32() {
let result = vec![("field".to_owned(), NewType(11))];
assert_eq!(serde_urlencoded::from_str("field=11"), Ok(result));
}
#[test]
fn deserialize_bytes() {
let result = vec![... |
// Copyright 2015 Felix S. Klock II
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except accordi... |
use crate::metrics::utils::graphemes;
use std::cmp;
pub struct JaroSimilarityResult {
pub value: f64,
pub max_prefix_length: i64,
}
pub fn similarity(a: &str, b: &str, ignore_case: bool) -> JaroSimilarityResult {
if ignore_case {
return similarity_impl(&graphemes(&a.to_lowercase()), &graphemes(&b.... |
use super::{
Compiler, DispError, DispResult, FunctionMap, GenericResult, Token, Type, UnparsedFunction,
};
use inference::{Constraint, TypeResolver, TypeVar, Unresolved};
use std::{collections::HashMap, rc::Rc};
mod scope;
mod types;
pub use self::scope::AnnotatorScope;
pub use self::types::{to_type, TypecheckType... |
//! Source implementation for SQL Server.
mod errors;
mod typesystem;
pub use self::errors::MsSQLSourceError;
pub use self::typesystem::{FloatN, IntN, MsSQLTypeSystem};
use crate::constants::DB_BUFFER_SIZE;
use crate::{
data_order::DataOrder,
errors::ConnectorXError,
sources::{PartitionParser, Produce, So... |
use crate::search::CharStream;
use std::collections::{btree_map::Iter as MapIter, BTreeMap};
use std::fmt;
#[derive(Debug, PartialEq, Eq)]
pub struct Tag {
pub name: String,
pub value: Option<String>,
}
impl Tag {
pub fn new(name: String, value: Option<String>) -> Self {
Tag { name, value }
}
... |
mod stats;
pub use self::stats::*;
mod stats_queue;
pub use self::stats_queue::*;
mod stats_basic;
pub use self::stats_basic::*;
use std::mem::size_of;
use crate::{
nla::{DefaultNla, Nla, NlaBuffer, NlasIterator},
traits::{Emitable, Parseable},
utils::{parse_string, parse_u8},
DecodeError,
};
pub c... |
/// This File takes a string of 'a' characters and performs a 2-tag
/// collatz reduction on it
// Import necessary libraries
use std::io;
use std::collections::HashMap;
fn main() {
println!("Enter a string of n a's where n is the number you want to start from");
// Create a holder for the raw input
let... |
use clap::{App, Arg, SubCommand};
use testanything::tap_writer::TapWriter;
fn main() {
let matches = App::new("tapper")
.about(env!("CARGO_PKG_DESCRIPTION"))
.author(env!("CARGO_PKG_AUTHORS"))
.version(env!("CARGO_PKG_VERSION"))
.subcommand(
SubCommand::with_name("plan")... |
extern crate regex;
use std::fs::File;
use std::io::Read;
use regex::RegexSet;
fn main() {
let mut file = File::open("d04-input").expect("file not found");
let mut input = String::new();
file.read_to_string(&mut input).expect("something went wrong reading file");
let mut valid = 0u32;
let data: Vec<String> = inp... |
use std::f64::consts::PI;
fn main() {
part1();
println!("----------");
part2();
}
fn part1() {
let circle = Circle {
x: 10.,
y: 10.,
radius: 10.,
};
println!("Circle: {:?}\nArea: {}", circle, circle.area());
let right_triangle = RTriangle {
leg_1: 10.,
... |
use crate::codegen::AatbeModule;
use parser::ast::{AtomKind, Expression, FloatSize, FunctionType, IntSize, PrimitiveType};
pub trait NameMangler {
fn mangle(&self, module: &AatbeModule) -> String;
}
impl NameMangler for Expression {
fn mangle(&self, module: &AatbeModule) -> String {
match self {
... |
use std::fmt::Write;
use hashbrown::HashMap;
use rosu_pp::{
Beatmap as Map, BeatmapExt, CatchPP, DifficultyAttributes, GameMode as Mode, ManiaPP, OsuPP,
PerformanceAttributes, TaikoPP,
};
use rosu_v2::prelude::{GameMode, Grade, Score, User};
use crate::{
core::Context,
embeds::{osu, Author, Footer},
... |
fn main() {
println!("Ce programme est avant tout un moyen d'apprendre à rédiger des tests.");
println!("Aller lire le fichier lib.rs, ou éxécuter 'cargo test'");
}
|
#![cfg(target_arch = "wasm32")]
use day06::*;
use wasm_bindgen_test::*;
wasm_bindgen_test_configure!(run_in_browser);
static INPUT: &str = include_str!("../input.txt");
#[wasm_bindgen_test]
fn day06_part1() {
assert_eq!(part1("COM)B\nB)C\nC)D\nD)E\nE)F\nB)G\nG)H\nD)I\nE)J\nJ)K\nK)L\n"), Ok(42));
assert_eq!... |
use log::trace;
use nu_engine::eval_block;
use nu_parser::{escape_quote_string, lex, parse, unescape_unquote_string, Token, TokenContents};
use nu_protocol::engine::StateWorkingSet;
use nu_protocol::CliError;
use nu_protocol::{
engine::{EngineState, Stack},
PipelineData, ShellError, Span, Value,
};
#[cfg(window... |
//! Contains main morphing routines.
use rand::{weak_rng, Rng};
use pad::*;
use objects::*;
use parsing::{parse_objects, parse_target_size};
use distribution::{sample_html_size, sample_object_count, sample_object_sizes};
const PAGE_SAMPLE_LIMIT: u8 = 10;
/// Do ALPaCA's morphing.
///
/// If the input object is an HT... |
use crate::block::BlockId;
use std::ops::{Deref, DerefMut};
pub enum Contextmenu {
Default,
Character(BlockId),
Tablemask(BlockId),
Area(BlockId),
Boxblock(BlockId),
}
pub struct State {
grobal_position: [f64; 2],
canvas_position: [f64; 2],
payload: Contextmenu,
}
impl State {
pub... |
#[doc = "Register `PRIVCFGR1` reader"]
pub type R = crate::R<PRIVCFGR1_SPEC>;
#[doc = "Register `PRIVCFGR1` writer"]
pub type W = crate::W<PRIVCFGR1_SPEC>;
#[doc = "Field `TIM2PRIV` reader - TIM2PRIV"]
pub type TIM2PRIV_R = crate::BitReader;
#[doc = "Field `TIM2PRIV` writer - TIM2PRIV"]
pub type TIM2PRIV_W<'a, REG, con... |
use crate::builtins;
use crate::helpers::{Fd, Shell};
use crate::parser::{Cmd, Simple};
use os_pipe::{pipe, PipeReader, PipeWriter};
use std::process::Command;
use std::rc::Rc;
use std::cell::RefCell;
use std::io::Read;
// This is useful to keep track of what each command does with its STDs
#[derive(Debug)]
struct Cmd... |
//
// sprocketnes/speex.rs
//
// Author: Patrick Walton
//
use std::cast::transmute;
use std::libc::{c_int, c_void};
use std::ptr::null;
type SpeexResamplerState = c_void;
#[link_args="-lspeexdsp"]
extern {
fn speex_resampler_init(nb_channels: u32,
in_rate: u32,
... |
// MIT License
//
// Copyright (c) 2018-2021 Hans-Martin Will
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, cop... |
use hydroflow::util::collect_ready;
use hydroflow::{assert_graphvis_snapshots, hydroflow_syntax};
use multiplatform_test::multiplatform_test;
#[multiplatform_test]
pub fn test_forwardref_basic_forward() {
let (out_send, mut out_recv) = hydroflow::util::unbounded_channel::<usize>();
let mut df = hydroflow_synt... |
use std::path::Path;
use tracing::info;
use crate::errors::DspMetaError;
use crate::load_model;
/// Read projects definition from .toml
pub fn validate<P: AsRef<Path>>(project_path: &P) -> Result<(), DspMetaError> {
info!("Hello from validate!");
let _ = load_model(project_path)?;
Ok(())
}
#[cfg(test)]
... |
#![cfg_attr(not(feature = "std"), no_std)]
use ink_lang as ink;
#[ink::contract]
mod nebula {
use ink_storage::{
collections::{hashmap::Entry, HashMap},
traits::{PackedLayout, SpreadLayout},
};
use ibport::IBport;
use gravity::Gravity;
use std::mem::transmute;
use web3::types::... |
//! Helper actors
pub mod signal;
#[cfg(unix)]
pub mod dns;
|
//! FBX tree viewer.
#![warn(missing_docs)]
use gtk::prelude::*;
use gtk::ScrolledWindow;
use gtk::{AccelFlags, AccelGroup, WidgetExt};
use gtk::{FileChooserAction, FileChooserDialog, FileFilter};
use gtk::{Menu, MenuBar, MenuItem};
use gtk::{Orientation, Paned, Window, WindowType};
use self::{
fbx::load_fbx_bina... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.