blob_id stringlengths 40 40 | language stringclasses 1
value | repo_name stringlengths 5 140 | path stringlengths 5 183 | src_encoding stringclasses 6
values | length_bytes int64 12 5.32M | score float64 2.52 4.94 | int_score int64 3 5 | detected_licenses listlengths 0 47 | license_type stringclasses 2
values | text stringlengths 12 5.32M | download_success bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|
8cf226a74ffbca65f5a569afe8d5f2076a6a98e4 | Rust | tower-rs/tower | /tower-layer/src/identity.rs | UTF-8 | 892 | 3.140625 | 3 | [
"MIT"
] | permissive | use super::Layer;
use std::fmt;
/// A no-op middleware.
///
/// When wrapping a [`Service`], the [`Identity`] layer returns the provided
/// service without modifying it.
///
/// [`Service`]: https://docs.rs/tower-service/latest/tower_service/trait.Service.html
#[derive(Default, Clone)]
pub struct Identity {
_p: (... | true |
43333da1e9a2a7fd31fad673b7e3865844019f1f | Rust | pitpo/AdventOfCode2018 | /tests/day4.rs | UTF-8 | 1,525 | 2.8125 | 3 | [] | no_license | extern crate day4;
extern crate utils;
use utils::Day;
#[test]
fn day4_a() {
let solver = day4::Day4::new(String::from(
"[1518-11-01 00:00] Guard #10 begins shift
[1518-11-01 00:05] falls asleep
[1518-11-01 00:25] wakes up
[1518-11-05 00:03] Guard #99 begins shift
[1518-11-01 00:30] falls asleep
[1518-11-... | true |
c9f519d5bc926ac8d3dace1bbb5d127b655ca782 | Rust | fitzgen/mcmc-maze-solver | /src/maze.rs | UTF-8 | 6,124 | 3.171875 | 3 | [] | no_license | use crate::{Move, Path};
use rand::prelude::*;
use std::collections::HashSet;
use std::iter;
#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
pub struct Cell {
pub row: u32,
pub col: u32,
}
pub struct Maze {
edges: Vec<Vec<u32>>,
rows: u32,
cols: u32,
}
impl Maze {
pub fn new(rng: &mut dyn ... | true |
dfce0edeb331ed124d777a5a9d6340735a26da01 | Rust | romainbou/markdown-splitter | /src/bin.rs | UTF-8 | 608 | 2.734375 | 3 | [
"Apache-2.0"
] | permissive | use markdown_splitter::*;
use structopt::StructOpt;
#[derive(StructOpt)]
struct Cli {
/// The path to the markdown file to read
#[structopt(parse(from_os_str))]
path: std::path::PathBuf,
/// Output filename (default: `export.md`)
#[structopt(short = "o", long = "output", default_value = "export.md... | true |
17d292dee26d9b6cdd7c6e2472567c3952df20e4 | Rust | alex-norton/advent-of-code-2020 | /src/bin/day22-2.rs | UTF-8 | 1,805 | 3.4375 | 3 | [
"MIT"
] | permissive | use std::collections::HashSet;
use std::collections::VecDeque;
use std::fs::read_to_string;
type Deck = VecDeque<usize>;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let file = read_to_string("data/day22input")?;
let mut lines = file.lines();
lines.next();
let mut p1 = Deck::new();
while ... | true |
d00e98c0849d0b40deab3865a5b5a51d6eac2f53 | Rust | MysterionRise/octo-render | /src/main.rs | UTF-8 | 1,485 | 2.78125 | 3 | [
"MIT"
] | permissive | use image::{ImageBuffer, Rgb, RgbImage};
use image::imageops::{flip_vertical_in_place};
use renderer::{draw_line, read_waveform_obj_file};
fn main() {
let (vertices, faces) = read_waveform_obj_file("resources/teapot.obj");
let tga_red = Rgb([255, 0, 0]);
let tga_green = Rgb([0, 255, 0]);
let tga_white... | true |
ebecce785801359683d4d78b8130f980e118adf4 | Rust | johnfercher/motion_detection | /src/camera_reader/mod.rs | UTF-8 | 2,316 | 2.53125 | 3 | [
"MIT"
] | permissive | extern crate opencv;
use std::thread;
use self::opencv::core::{Mat, absdiff, bitwise_and, Size, Point, Scalar};
use self::opencv::highgui::{VideoCapture, imshow, wait_key};
use self::opencv::imgproc::{threshold, CV_THRESH_BINARY, cvt_color, CV_RGB2GRAY, MORPH_RECT, get_structuring_element, erode};
pub struct CameraR... | true |
af4ef7453e54f91c0466b95592c2d75bc2de6fbe | Rust | steadylearner/Rust-Full-Stack | /actix/actix_examples/async_ex1/src/main.rs | UTF-8 | 3,362 | 2.953125 | 3 | [
"Apache-2.0",
"MIT"
] | permissive | // This is a contrived example intended to illustrate actix-web features.
// *Imagine* that you have a process that involves 3 steps. The steps here
// are dumb in that they do nothing other than call an
// httpbin endpoint that returns the json that was posted to it. The intent
// here is to illustrate how to chain ... | true |
af125c755b6819dd3da1021c4be99d1b1b45284e | Rust | jasonpeacock/advent-of-code-2019-rust | /src/day4.rs | UTF-8 | 3,215 | 3.8125 | 4 | [
"MIT"
] | permissive | /*
* Notes:
*
* Part 1:
* - The double may be at the end of the string, need to handle that last-digit edge case.
*
* Part 2:
* - Instructions are confusing. Basically, it's OK for there to be larger groups of
* duplicates as long as there is at least 1 group of only 2 dupes.
* - There may be a valid dupli... | true |
eed065aecdeab5be43fbb8c29126b1811472884f | Rust | sashinexists/advent-of-code-2020-rust | /src/day5part2.rs | UTF-8 | 4,570 | 3.265625 | 3 | [] | no_license | use aocf::Aoc;
pub fn run() {
let boarding_passes: Vec<BoardingPass> = process_input(&read_input());
println!(
"My seat is {}. Hello there.",
find_my_seat(&boarding_passes)
);
}
struct BoardingPass {
row_instructions: [bool; 7],
column_instructions: [bool; 3],
}
impl BoardingPass ... | true |
9f2f5dcdf2ca3356baa94cd228717b6fee26cf1f | Rust | tafia/quick-xml | /tests/fuzzing.rs | UTF-8 | 1,858 | 2.78125 | 3 | [
"MIT"
] | permissive | //! Cases that was found by fuzzing
use quick_xml::events::Event;
use quick_xml::reader::Reader;
use quick_xml::Error;
#[test]
fn fuzz_53() {
let data: &[u8] = b"\xe9\x00\x00\x00\x00\x00\x00\x00\x00\
\x00\x00\x00\x00\n(\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\
\x00<>\x00\x08\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0... | true |
52f0da9dc9632241e6e43c18eee8addb47d67ef9 | Rust | sunguru98/escrow-solana | /program/src/instruction.rs | UTF-8 | 2,924 | 3.15625 | 3 | [] | no_license | use std::convert::TryInto;
use solana_program::program_error::ProgramError;
// inside instruction.rs
pub enum EscrowInstruction {
/// Starts the trade by creating a PDA and populating an escrow account and transferring ownership of the given temp token account to the PDA
///
///
/// Accounts expected:... | true |
ca318278c8114a5116e88e55ff701afaf1484ecd | Rust | ima9rd/carballrs | /src/rattletrap/check_version.rs | UTF-8 | 2,131 | 2.859375 | 3 | [
"MIT"
] | permissive | use ::glob::glob;
use ::version_compare::{Version, VersionCompare};
const URL: &str = "https://api.github.com/repos/tfausak/rattletrap/releases/latest";
const RATTLETRAP_PATH: &str = "src/rattletrap/";
fn fetch_url(url: &str) -> Result<String, reqwest::Error> {
let res = reqwest::get(url)?.text()?;
Ok(res)
}
... | true |
7633fa630734b679f4a3fdbe875a203755474442 | Rust | shanlashari/vector | /lib/tracing-limit/benches/limit.rs | UTF-8 | 3,098 | 2.515625 | 3 | [
"Apache-2.0",
"OpenSSL"
] | permissive | #[macro_use]
extern crate tracing;
#[macro_use]
extern crate criterion;
use criterion::{black_box, Criterion};
use std::{
fmt,
sync::{Mutex, MutexGuard},
};
use tracing::{field, span, Event, Id, Metadata};
use tracing_limit::Limit;
use tracing_subscriber::layer::SubscriberExt;
const INPUTS: &'static [usize] ... | true |
e63cea4bb21feeab41eebce2e26cbc415d0a4499 | Rust | IThawk/rust-project | /rust-master/src/test/ui/hrtb/issue-46989.rs | UTF-8 | 1,123 | 3.34375 | 3 | [
"Apache-2.0",
"MIT",
"LicenseRef-scancode-other-permissive",
"BSD-3-Clause",
"BSD-2-Clause",
"NCSA"
] | permissive | // Regression test for #46989:
//
// In the move to universes, this test started passing.
// It is not necessarily WRONG to do so, but it was a bit
// surprising. The reason that it passed is that when we were
// asked to prove that
//
// for<'a> fn(&'a i32): Foo
//
// we were able to use the impl below to prove
//... | true |
ac7620d748fdcbbd740a7f5c14ce50f5dca5e764 | Rust | raygon-renderer/ply-rs | /examples/write_ply.rs | UTF-8 | 2,359 | 3.328125 | 3 | [
"MIT"
] | permissive | extern crate ply_rs;
use ply_rs::ply::{Addable, DefaultElement, ElementDef, Encoding, Ply, Property, PropertyDef, PropertyType, ScalarType};
use ply_rs::writer::Writer;
/// Demonstrates simplest use case for reading from a file.
fn main() {
// set up a target, could also be a file
let mut buf = Vec::<u8>::new(... | true |
c210dd2ba4700262a82d8d227e23c424498b1773 | Rust | MoBlaa/bot-rs-core | /src/auth.rs | UTF-8 | 7,680 | 3.375 | 3 | [] | no_license | use std::convert::TryFrom;
use std::fmt;
#[derive(PartialEq, Eq, Debug, Hash, Clone, Serialize, Deserialize)]
pub enum Platform {
Twitch,
}
#[derive(Debug, Clone, Eq, PartialEq)]
pub enum InvalidIrcMessageError<'a> {
MissingTags(&'a irc_rust::Message),
MissingUserId(&'a irc_rust::Message),
MissingPref... | true |
17ea1d5477588ff9598ae1cf33a59510635a2f52 | Rust | andrewcharlton/advent-of-code | /2021/day08/src/main.rs | UTF-8 | 3,222 | 3.703125 | 4 | [
"MIT"
] | permissive | use std::collections::HashMap;
use std::fs;
fn main() {
println!("Part one: {}", unique_segments("input.txt"));
println!("Part two: {}", sum("input.txt"));
}
fn unique_segments(filename: &str) -> usize {
fs::read_to_string(filename)
.expect("couldn't open file")
.lines()
.map(|line... | true |
72bb27510e1d7902130802145d393c2e37067f29 | Rust | iFaceless/beanstalkc-rust | /src/job.rs | UTF-8 | 5,619 | 3.28125 | 3 | [
"MIT"
] | permissive | use std::collections::HashMap;
use std::fmt;
use std::time::Duration;
use crate::config::DEFAULT_JOB_DELAY;
use crate::config::DEFAULT_JOB_PRIORITY;
use crate::error::BeanstalkcResult;
use crate::Beanstalkc;
/// `Job` is a simple abstraction about beanstalkd job.
#[derive(Debug)]
pub struct Job<'a> {
conn: &'a mu... | true |
1281ab5ea3b7099e52ebd1c0ed71a22983d4fada | Rust | martingallagher/minibot-rust | /crates/common/src/future/pipe.rs | UTF-8 | 8,310 | 2.765625 | 3 | [] | no_license | mod cloner;
mod safe_sender;
use futures::channel::{mpsc, oneshot};
use futures::prelude::*;
use futures::stream::BoxStream;
use super::pipe as run_pipe;
#[derive(Copy, Clone, Debug)]
pub enum Either<A, B> {
Left(A),
Right(B),
}
#[derive(Clone)]
pub struct PipeStart<T>(mpsc::Sender<T>);
impl<T> PipeStart<T... | true |
b70ecde2c5d231600956d01e1fab57756a8e96ea | Rust | SKYLARMIC25/mercury | /core/storage/src/lib.rs | UTF-8 | 4,958 | 2.65625 | 3 | [
"MIT"
] | permissive | use common::derive_more::Display;
use common::{anyhow::Result, MercuryError};
pub use ckb_indexer::store::{
Batch, Error as StoreError, IteratorDirection, IteratorItem, RocksdbStore, Store,
};
use ckb_types::bytes::Bytes;
use std::sync::{Arc, RwLock};
#[derive(Clone, Debug, Display)]
enum StorageError {
#[di... | true |
5f9da41231b3821a2d425b000e9daeb8855c582c | Rust | nikomatsakis/graph-compress | /src/test_macro.rs | UTF-8 | 1,171 | 2.609375 | 3 | [
"MIT",
"Apache-2.0"
] | permissive | macro_rules! graph {
($( $source:ident -> $target:ident, )*) => {
{
use $crate::rustc_data_structures::graph::{Graph, NodeIndex};
use $crate::rustc_data_structures::fx::FxHashMap;
let mut graph = Graph::new();
let mut nodes: FxHashMap<&'static str, NodeIndex>... | true |
8cd572468bd6a1f772ad568025be61c5e04889c4 | Rust | conorpp/lpc55-host | /src/bootloader/protocol.rs | UTF-8 | 19,425 | 2.828125 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | // https://www.nxp.com/docs/en/reference-manual/MCUBOOTRM.pdf
//
// - all fields in packets are little-endian
// - each command sent from host is replied to with response
// - optional data phase, either command or response (not both!)
// RM uses "incoming" (host->MCU) and "outgoing" (host<-MCU) terminology
//
//
// ... | true |
3b4296aa68880cf085fa8be331bcd4c16264892e | Rust | JP-Ellis/coding-problems | /src/daily_coding_problem/p043.rs | UTF-8 | 874 | 2.96875 | 3 | [] | no_license | use crate::{Error, Problem};
use std::io::prelude::*;
pub struct P;
const STATEMENT: &str = r#"Implement a stack that has the following methods:
- push(val), which pushes an element onto the stack
- pop(), which pops off and returns the topmost element of the stack. If there
are no elements in the stack, then it s... | true |
a4584de4e2ce36043a3a69feaf0d079f2a1b1b91 | Rust | kessl/advent_of_code_2020 | /day_16/src/ticket_validator.rs | UTF-8 | 4,639 | 3.046875 | 3 | [] | no_license | use std::collections::HashMap;
use std::ops::RangeInclusive;
type Error = &'static str;
type Range = RangeInclusive<u32>;
type Rules = HashMap<String, (Range, Range)>;
type Ticket = Vec<u32>;
#[derive(Debug)]
pub struct TicketValidator {
rules: Rules,
ticket: Ticket,
nearby_tickets: Vec<Ticket>,
field... | true |
ed72ced110fea18e850a261d1d86cd481e238b81 | Rust | ltriess/advent-of-code-2020 | /src/bin/12_rain-risk_part1.rs | UTF-8 | 1,883 | 3.515625 | 4 | [
"MIT"
] | permissive | use std::fs::File;
use std::io::{self, BufRead, BufReader};
fn turn_right(direction: char) -> char {
return match direction {
'N' => 'E',
'E' => 'S',
'S' => 'W',
'W' => 'N',
_ => direction,
};
}
fn turn_left(direction: char) -> char {
return match direction {
... | true |
9575c095de7002594c7637605fe6edca71e8fffe | Rust | diesel-rs/diesel | /diesel/src/expression_methods/text_expression_methods.rs | UTF-8 | 4,919 | 3.578125 | 4 | [
"Apache-2.0",
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | use self::private::TextOrNullableText;
use crate::dsl;
use crate::expression::grouped::Grouped;
use crate::expression::operators::{Concat, Like, NotLike};
use crate::expression::{AsExpression, Expression};
use crate::sql_types::SqlType;
/// Methods present on text expressions
pub trait TextExpressionMethods: Expressio... | true |
0c9c4879ead8689d86844f7949e98c477b50b254 | Rust | PyO3/maturin | /src/upload.rs | UTF-8 | 23,733 | 2.84375 | 3 | [
"MIT",
"Apache-2.0"
] | permissive | //! The uploading logic was mostly reverse engineered; I wrote it down as
//! documentation at https://warehouse.readthedocs.io/api-reference/legacy/#upload-api
use crate::build_context::hash_file;
use anyhow::{bail, Context, Result};
use base64::engine::general_purpose::STANDARD;
use base64::Engine;
use bytesize::Byt... | true |
e2f161defdce4fbdc8332311e9f1ed50cc2da569 | Rust | ayberkt/rs-natural | /src/classifier.rs | UTF-8 | 2,225 | 3.15625 | 3 | [
"LicenseRef-scancode-warranty-disclaimer",
"MIT"
] | permissive | extern crate stem;
use tokenize::tokenize;
use stem::get;
use std::collections::HashMap;
use std::collections::hash_map::{Occupied, Vacant};
use std::num::Float;
pub struct NaiveBayesClassifier {
documents: HashMap<String, HashMap<String, uint>>,
total_document_count: uint
}
impl NaiveBayesClassifier {
pub fn ... | true |
ecba661d4b2abcfc90f8f0c8a4b87e12933c3bfd | Rust | isgasho/em-refactor | /em-refactor-lib/src/refactorings/close_over_variables/expr_use_visit.rs | UTF-8 | 5,086 | 2.546875 | 3 | [
"Apache-2.0"
] | permissive | use rustc_hir::{BodyId, Node, hir_id::HirId};
use rustc_infer::infer::{TyCtxtInferExt};
use rustc_middle::ty::{self, TyCtxt, print::with_crate_prefix};
use rustc_typeck::expr_use_visitor::{ConsumeMode, Delegate, ExprUseVisitor, Place, PlaceBase};
use rustc_span::Span;
use crate::refactorings::visitors::hir::ExpressionU... | true |
5fe31413c719d0541187fdd30e11c346171bf45a | Rust | slog-rs/term | /src/lib.rs | UTF-8 | 46,015 | 2.890625 | 3 | [
"Apache-2.0",
"MIT",
"MPL-2.0"
] | permissive | // {{{ Module docs
//! `slog-rs`'s `Drain` for terminal output
//!
//! This crate implements output formatting targeting logging to
//! terminal/console/shell or similar text-based IO.
//!
//! **Warning**: `slog-term` (like `slog-rs` itself) is fast, modular and
//! extensible. It comes with a price: a lot of details ... | true |
3e28d914d41fb6c530269fce99e047cd2bd580dc | Rust | Cryptjar/random-branch | /src/lib.rs | UTF-8 | 6,909 | 3.59375 | 4 | [
"Apache-2.0",
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | #![no_std]
// Enable annotating features requirements in docs
#![cfg_attr(feature = "doc_cfg", feature(doc_cfg))]
// This crate is entirely safe, actually it's just macros
#![forbid(unsafe_code)]
// Ensures that `pub` means published in the public API.
// This property is useful for reasoning about breaking API chan... | true |
72d3fffaa25ea74ef2d500ec2e134751b8f148bc | Rust | AaronM04/rp | /src/main.rs | UTF-8 | 520 | 3.125 | 3 | [] | no_license | extern crate rand;
use rand::Rng;
use std::env;
use std::str::FromStr;
use std::process;
fn main() {
let args: Vec<String> = env::args().collect();
if args.len() != 2 {
println!("Usage: {} <highest_page_number>", args[0]);
println!("Prints a random page number from a book with specified number... | true |
b8273c18f065076f84bf1c25ca5e317ad5827e2c | Rust | zaphar/ucg | /src/build/scope.rs | UTF-8 | 7,183 | 3 | 3 | [
"Apache-2.0"
] | permissive | use std::clone::Clone;
use std::collections::HashMap;
use std::convert::AsRef;
use std::convert::Into;
use std::error::Error;
use std::rc::Rc;
use crate::ast::Position;
use crate::ast::PositionedItem;
use crate::build::ir::Val;
use crate::error;
pub fn find_in_fieldlist(target: &str, fs: &Vec<(String, Rc<Val>)>) -> O... | true |
17cc33c2f6191e7303af7889ec6463adb92e82b8 | Rust | galenelias/AdventOfCode_2017 | /src/Day24/mod.rs | UTF-8 | 1,383 | 3.0625 | 3 | [] | no_license | use std::io::{self, BufRead};
fn tuple_other(tup : &(u32, u32), val : u32) -> u32
{
if tup.0 == val { tup.1 } else { tup.0 }
}
fn build_bridge(adapter : u32, value : u32, pieces : &[(u32,u32)]) -> u32
{
pieces.iter().enumerate().filter_map(|(i,p)| {
if p.0 == adapter || p.1 == adapter {
let mut leftovers = pie... | true |
e25989182f6525a05ae6ca2da649a51875e662c9 | Rust | ReginaF2012/rust_strings | /src/main.rs | UTF-8 | 2,646 | 4.21875 | 4 | [] | no_license | fn main() {
// create a new empty String
let mut s = String::new();
// another way to create a String
let s2 = "initial contents".to_string();
// another...
let s3 = String::from("initial contents");
// Remember that strings are UTF-8 encoded, so we can include any properly encoded data i... | true |
dc702e0e543e76f9f101e1005a6cbd1680e141aa | Rust | jaredly/rusty-automata | /src/colors.rs | UTF-8 | 1,751 | 3.28125 | 3 | [
"Apache-2.0"
] | permissive | use sdl2::pixels::Color;
use utils;
use utils::{Team};
#[derive(Debug, Copy, Clone)]
pub enum Theme {
Light,
Dark,
Orange
}
pub fn colorize(theme: &Theme, val: u8) -> Color {
match theme {
&Theme::Light => light(val),
&Theme::Dark => dark(val),
&Theme::Orange => orange(val)
}
}
pub fn nextThem... | true |
2d0dbf0ac2e1a9a4a55b29e99425072ca2a3d6a9 | Rust | xymostech/XymosTeX | /src/parser/expand.rs | UTF-8 | 7,581 | 3.515625 | 4 | [
"MIT"
] | permissive | use crate::parser::Parser;
use crate::token::Token;
impl<'a> Parser<'a> {
pub fn lex_expanded_token(&mut self) -> Option<Token> {
if self.is_conditional_head() {
// Handle conditionals, like \ifnum
self.expand_conditional();
return self.lex_expanded_token();
} el... | true |
d7f337553cdaa98b9753c15f4ba71e4220b0fb7c | Rust | cwboden/.dotfiles | /games/dcg_render/src/card/components/description.rs | UTF-8 | 1,337 | 2.546875 | 3 | [
"MIT"
] | permissive | use crate::card::components::{RenderError, Surfaced};
use sdl2::pixels::Color;
use sdl2::rect::Rect;
use sdl2::surface::Surface;
use sdl2::ttf::Font;
use std::rc::Rc;
struct Description<'ttf_module, 'rwops> {
description: String,
font: Rc<Font<'ttf_module, 'rwops>>,
}
#[allow(dead_code)]
impl<'ttf_module, 'rw... | true |
11303fc7fd70e5a624eed99ec1a2c41a4d799580 | Rust | RangerStation/alexandrie-run | /.cargo/registry/src/github.com-1ecc6299db9ec823/diesel-1.4.4/src/type_impls/integers.rs | UTF-8 | 3,275 | 2.6875 | 3 | [
"MIT",
"Apache-2.0"
] | permissive | use byteorder::{ReadBytesExt, WriteBytesExt};
use std::error::Error;
use std::io::prelude::*;
use backend::Backend;
use deserialize::{self, FromSql};
use serialize::{self, IsNull, Output, ToSql};
use sql_types;
impl<DB: Backend<RawValue = [u8]>> FromSql<sql_types::SmallInt, DB> for i16 {
fn from_sql(bytes: Option... | true |
923fbfb74fda0c296e726e0852ffacdf3c74ef6c | Rust | JulianKnodt/mireba | /src/unit_tests/triangle.rs | UTF-8 | 630 | 2.65625 | 3 | [] | no_license | use crate::triangle::Triangle;
use crate::vec::{Ray, Vec2, Vec3};
use quickcheck::TestResult;
quickcheck! {
fn barycentric_identity(t: Triangle<Vec3<f32>>) -> bool {
let Triangle(Vec3(v0, v1, v2)) = t;
assert_eq!(Vec2(1., 0.), t.as_ref().barycentric(&v0));
assert_eq!(Vec2(0., 1.), t.as_ref().barycentric(&... | true |
39c4a95a50ab7c959e50586581b6a4ae88fe1849 | Rust | adumbidiot/piston | /src/input/src/cursor.rs | UTF-8 | 1,409 | 3.203125 | 3 | [
"MIT"
] | permissive | use {Event, Input};
/// When window gets or loses cursor.
pub trait CursorEvent: Sized {
/// Creates a cursor event.
///
/// Preserves time stamp from original input event, if any.
fn from_cursor(cursor: bool, old_event: &Self) -> Option<Self>;
/// Calls closure if this is a cursor event.
fn cu... | true |
c53f4887d5d6c704f3595496332e5d8c411adb70 | Rust | google/note-maps | /rust/notemaps_text/src/table.rs | UTF-8 | 20,545 | 3.046875 | 3 | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla"
] | permissive | // Copyright 2021-2022 Google LLC
//
// 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to i... | true |
4195982fe106c2c34f2a201e74391f7d9c3f6baa | Rust | whizsid/ineedtext | /src/parsers/css.rs | UTF-8 | 1,367 | 2.515625 | 3 | [] | no_license | use crate::parser::{LangItem, Language, Matcher, Parser, UniId};
use onig::Regex;
#[derive(Clone)]
pub struct CSSParser;
#[derive(Clone)]
pub struct Scope;
impl LangItem for Scope {
fn start(&self) -> Matcher {
Matcher::new(Some(1), Regex::new("{").unwrap())
}
fn end(&self) -> Matcher {
M... | true |
377b342bc5f674c484add127119dfc54ad8de105 | Rust | wendajiang/leetcode | /rust/src/leetcode/918.maximum-sum-circular-subarray.rs | UTF-8 | 2,305 | 2.96875 | 3 | [] | no_license | /*
* @lc app=leetcode id=918 lang=rust
*
* [918] Maximum Sum Circular Subarray
*
* https://leetcode.com/problems/maximum-sum-circular-subarray/description/
*
* algorithms
* Medium (35.68%)
* Likes: 2363
* Dislikes: 99
* Total Accepted: 89.9K
* Total Submissions: 251.7K
* Testcase Example: '[1,-2,3,-... | true |
7192a282c0da0f2df3e5bb3302686b40394602e0 | Rust | erlandsona/tree-calculus-1 | /trees/src/lib.rs | UTF-8 | 8,411 | 2.9375 | 3 | [
"MIT"
] | permissive | /**********************************************************************/
/* Copyright 2020 Barry Jay */
/* */
/* Permission is hereby granted, free of charge, to any person */
/* obtaining a copy of thi... | true |
99242d7058e9fa2fd217ddc095f3142233834cd9 | Rust | gleicon/sled_demo | /src/main.rs | UTF-8 | 3,082 | 3.15625 | 3 | [] | no_license | use sled::{Config, Result};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::fs;
use serde::{Serialize, Deserialize};
#[derive(Serialize, Deserialize, PartialEq, Debug)]
struct Envelope {
body: Vec<u8>,
}
struct PersistenceManager <'a> {
root_path: String,
path: &'a Path,
datab... | true |
b2fc6264c2ab241c9dd52a11dbd84ccf16c8acd6 | Rust | Cytosine2020/authernet | /src/athernet/rtaudio.rs | UTF-8 | 2,215 | 2.703125 | 3 | [] | no_license | use std::{ffi::c_void, ops::Deref};
#[derive(std::fmt::Debug)]
pub enum StreamError {
UnknownError,
}
impl std::fmt::Display for StreamError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("RTAudio stream error!")
}
}
impl std::error::Error for StreamError {}
... | true |
f4c5b93ff5a120dab54119f42433df9da6c07697 | Rust | DmitrySamoylov/libv4l-rs | /src/buffers/userptr.rs | UTF-8 | 1,835 | 3.125 | 3 | [
"MIT"
] | permissive | use crate::buffer;
/// Buffer allocated in userspace (by the application)
///
/// Devices supporting user pointer mode will directly transfer image memory to the buffer
/// "for free" by using direct memory access (DMA).
pub struct UserBuffer<'a> {
view: &'a [u8],
metadata: buffer::Metadata,
}
impl<'a> UserBu... | true |
925eeedc482a54a41d88d71c4415d474148cb281 | Rust | ducharmemp/distrust | /src/types.rs | UTF-8 | 1,700 | 3.296875 | 3 | [] | no_license | use std::collections::{VecDeque, BTreeMap};
use std::sync::{Arc, Mutex};
#[derive(Debug, Clone)]
pub enum RedisType {
Integer(i64),
String(String),
List(VecDeque<RedisType>),
Nil
}
impl RedisType {
pub fn respond(&self) -> String {
match self {
Self::Integer(val) => format!(":{}\r\n", val.... | true |
d1c7fe41cf7d71abebcdc4ec0972f64b802af67e | Rust | charlesvdv/cirrus | /backend/src/users.rs | UTF-8 | 3,955 | 2.734375 | 3 | [] | permissive | use std::str::FromStr;
use anyhow::{bail, Result};
use argon2::{
password_hash::{rand_core::OsRng, PasswordHasher, SaltString},
Argon2, PasswordVerifier,
};
use super::role::Role;
use serde::{Deserialize, Serialize};
#[derive(thiserror::Error, Debug)]
pub enum UserError {
#[error("User name is empty")]
... | true |
beb20f82227bea3ab226cced3988b575c1b44b2d | Rust | stm32-rs/stm32f3xx-hal | /src/signature.rs | UTF-8 | 2,761 | 3.234375 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT",
"Apache-2.0"
] | permissive | //! Device electronic signature
//!
//! (stored in flash memory)
use core::fmt;
use core::str;
use core::convert::TryInto;
macro_rules! define_ptr_type {
($name: ident, $ptr: expr) => {
impl $name {
fn ptr() -> *const Self {
$ptr as *const _
}
/// Retur... | true |
4c774a89c3fc04af4c77b6424c44c54cc7028323 | Rust | Fahien/exrust | /the-book/advanced-features/src/functions.rs | UTF-8 | 724 | 4.125 | 4 | [
"MIT"
] | permissive | // The type of functions is fn, not to be confused with the Fn closure trait.
fn add_one(x: i32) -> i32 {
x + 1
}
fn do_twice(f: fn(i32) -> i32, arg: i32) -> i32 {
f(arg) + f(arg)
}
pub fn functions() {
let answer = do_twice(add_one, 5);
println!("The answer is {}", answer);
let numbers = vec![1,... | true |
a43bbbd1fb78b05649bd5a0cafa5619316006f61 | Rust | ParthDesai/snowball | /src/traits/query.rs | UTF-8 | 1,715 | 2.953125 | 3 | [
"Apache-2.0"
] | permissive | use crate::traits::signable::Signable;
use serde::de::DeserializeOwned;
use serde::Serialize;
/// Context of the query, used to store additional data
/// that recipient node can use to figure out query's response
pub trait QueryContext: Serialize + DeserializeOwned {
type Key: Serialize + DeserializeOwned + Ord;
... | true |
bb711a893ef969388fcf2b4d7764f4acdb9e053f | Rust | sithumonline/website-wasm | /src/pages/project_details.rs | UTF-8 | 1,561 | 2.546875 | 3 | [] | no_license | use yew::prelude::*;
use super::PageTemplate;
use crate::components::{MenuStrip, ProjectHeader};
use crate::data::{AppRoute, AppRouteAnchor, Project};
#[derive(Clone, Debug, Properties)]
pub struct Props {
pub project: &'static Project,
}
#[derive(Clone, Debug)]
pub struct ProjectDetails {
props: Props,
... | true |
56b8c7045cc5fca7948076a60134fba5f75af507 | Rust | LinuX-lab/20180208-Rust | /p01-basics/src/bin/04_obiekty.rs | UTF-8 | 1,354 | 3.796875 | 4 | [] | no_license | use std::fmt::{Error, Formatter};
// Prosta struktura
pub struct Osoba {
imie: String,
nazwisko: String,
wiek: u8,
}
impl Osoba {
// P.O. konstruktora w Ruście
fn new(i: &str, n: &str, w: u8) -> Self {
Osoba {
imie: String::from(i),
nazwisko: String::from(n),
... | true |
6e8b4839fe891e8977d67f96ce3ff6f78b7b31fc | Rust | RCasatta/authenticated_tree | /src/main.rs | UTF-8 | 9,196 | 3.125 | 3 | [] | no_license |
extern crate integer_encoding;
extern crate crypto;
extern crate data_encoding;
extern crate rand;
use std::collections::HashMap;
use std::mem;
use std::borrow::BorrowMut;
use integer_encoding::VarInt;
use crypto::sha2::Sha256;
use crypto::digest::Digest;
#[derive(Debug, Clone)]
struct Sha256Hash ([u8;32]); // for ... | true |
314dab242a437b86a004d9f372b5edb9b3e35d19 | Rust | WanzenBug/aoc-2019 | /p15/src/main.rs | UTF-8 | 1,018 | 3.15625 | 3 | [] | no_license | use std::{
error::Error,
};
const INPUT: &'static [u8] = include_bytes!("../INPUT");
struct Layer<'a> {
pixels: &'a [u8],
}
impl<'a> Layer<'a> {
fn new(data: &'a [u8]) -> Self {
Layer { pixels: data }
}
fn width() -> usize {
25
}
fn height() -> usize {
6
}
... | true |
fc07e4d71f587d75e7d3103719e7696ae300c11a | Rust | cdumay/rust-serde-value-flatten | /src/ser.rs | UTF-8 | 3,109 | 2.625 | 3 | [
"BSD-3-Clause"
] | permissive | // Copyright 2019-present, OVH SAS
// All rights reserved.
//
// This OVH Software is licensed to you under the MIT license <LICENSE-MIT
// https://opensource.org/licenses/MIT> or the Modified BSD license <LICENSE-BSD
// https://opensource.org/licenses/BSD-3-Clause>, at your option. This file may not be copied,
// modi... | true |
3faf01d60963b5b752ec4a961a8dd63e6a2779d7 | Rust | phoniks/bs | /src/fs.rs | UTF-8 | 10,643 | 2.53125 | 3 | [
"Apache-2.0"
] | permissive | use indicatif::{ProgressBar, ProgressStyle};
use num_cpus;
use rayon;
use sha2::{Sha512Trunc256, Digest};
use std::collections::{BinaryHeap, BTreeSet};
use std::cmp::Ordering;
use std::fs::File;
use std::io::{BufReader, BufRead};
use std::path::PathBuf;
use std::sync::mpsc::{self, Sender, SyncSender, Receiver};
#[deri... | true |
74cd583627fd897b4efc5d365583c0656ab0f7a4 | Rust | intgr/ego | /src/cli.rs | UTF-8 | 2,800 | 2.859375 | 3 | [
"MIT"
] | permissive | use clap::{command, Arg, ArgAction, ArgGroup, Command, ValueHint};
use log::Level;
use std::ffi::OsString;
#[derive(Debug, PartialEq, Eq)]
pub enum Method {
Sudo,
Machinectl,
MachinectlBare,
}
/// Data type for parsed settings
pub struct Args {
pub user: String,
pub command: Vec<String>,
pub l... | true |
859f1022881e81b21a5f9c9c16f4b9c2338950ee | Rust | Mvdboon/ScalingUpStayingSecure | /Model/src/agent/netstation.rs | UTF-8 | 6,170 | 2.625 | 3 | [
"MIT"
] | permissive | use std::fmt::{Debug, Display};
use apache_avro::AvroSchema;
use serde::{Deserialize, Serialize};
use crate::agent::{AgentKind, AgentList, AgentTrait};
#[allow(unused_imports)]
use crate::agent::{Area, Household};
use crate::grid::{Boundaries, BoundaryAgentTrait, Grid, GridState, GridWarning, InfectionState, Infectio... | true |
e9311b0154030c4b6e2e85f3bc62395f2e0e0f0a | Rust | rezural/mesh-ripper | /src/app/resources/mesh_aabb_estimator.rs | UTF-8 | 1,115 | 2.609375 | 3 | [
"CC0-1.0"
] | permissive | use bevy::prelude::*;
use parry3d::{bounding_volume::AABB, math::*};
pub struct MeshAABBEstimator {}
impl MeshAABBEstimator {
pub fn aabb(mesh: &Mesh) -> Option<AABB> {
let vertices = mesh.attribute("Vertex_Position");
if let Some(vertices) = vertices {
if let Some(vertices) = match ve... | true |
db4cb2d3de89a1750f77e06df07a3b80d1422c45 | Rust | fortitudepub/R2 | /graph/src/lib.rs | UTF-8 | 12,117 | 2.953125 | 3 | [
"MIT"
] | permissive | use counters::flavors::{Counter, CounterType};
use counters::Counters;
use crossbeam_queue::ArrayQueue;
use log::Logger;
use packet::BoxPkt;
use packet::PacketPool;
use perf::Perf;
use std::collections::HashMap;
use std::collections::VecDeque;
use std::sync::Arc;
// We preallocate space for these many graph nodes, of ... | true |
2401bc72d4ed6bf2bb98e33215b60d071ef55c56 | Rust | jsolon-ncp/agnes | /examples/gdp_life_local.rs | UTF-8 | 3,008 | 2.59375 | 3 | [
"MIT"
] | permissive | #[macro_use]
extern crate agnes;
use std::fmt::Debug;
use std::path::Path;
use agnes::join::{Equal, Join};
use agnes::source::csv::{CsvReader, CsvSource, IntoCsvSrcSchema};
use agnes::value::Value;
fn load_csv_file<Schema>(filename: &str, schema: Schema) -> CsvReader<Schema::CsvSrcSchema>
where
Schema: IntoCsvSr... | true |
6480e63b18592c4b2ae178a7f46f1e2ebe190eda | Rust | LoungeCPP/pir-8-emu | /tests/rw/read_write_marker.rs | UTF-8 | 1,464 | 2.890625 | 3 | [
"MIT"
] | permissive | use pir_8_emu::ReadWriteMarker;
#[test]
fn new() {
let marker = ReadWriteMarker::new();
assert_eq!(marker.was_read(), false);
assert_eq!(marker.was_written(), false);
}
#[test]
fn read() {
let marker = ReadWriteMarker::new();
marker.read();
assert_eq!(marker.was_read(), true);
assert_eq!... | true |
51ac5a4df38b0ae0dbf81008d78b8c9239e4bef5 | Rust | yjh0502/sse | /src/client.rs | UTF-8 | 4,287 | 2.5625 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | use super::*;
use hyper::client::connect::Connect;
#[derive(Default, PartialEq, Eq, Debug)]
pub struct Event {
pub id: Option<String>,
pub event: String,
pub data: String,
}
struct SSEBodyStream {
body: hyper::Body,
events: Vec<Event>,
buf: Vec<u8>,
}
impl SSEBodyStream {
fn new(body: hyp... | true |
9083433c42c05ff66a3845629b151b7aade9a9ea | Rust | claudiavmbrito/opendp | /rust/opendp/src/error.rs | UTF-8 | 2,011 | 2.96875 | 3 | [] | no_license | use std::fmt;
use backtrace::Backtrace as _Backtrace;
#[macro_export]
macro_rules! fallible {
($variant:ident) => (Err(err!($variant)));
($variant:ident, $($inner:expr),+) => (Err(err!($variant, $($inner),+)));
}
// "error" is shadowed, and breaks intellij macro resolution
#[macro_export]
macro_rules! err {
... | true |
f311c3c35160d4378b29ab31ae0dbc1c5b97c335 | Rust | scifi6546/Sukakpak | /summit_surveyor_v2/src/gui/text.rs | UTF-8 | 6,293 | 2.734375 | 3 | [] | no_license | use super::super::prelude::{AssetHandle, AssetManager};
use epaint::{
text::{FontDefinitions, Fonts, TextStyle},
TessellationOptions, Tessellator,
};
use std::collections::HashMap;
use sukakpak::{image::RgbaImage, nalgebra::Vector2, Context, MeshAsset, Texture};
struct Dimensions {
width: u32,
height: u... | true |
e8fbd25c3dd7e43d8ae388dd827f03d74d4538aa | Rust | leejw51crypto/chain | /chain-tx-enclave-next/enclave-ra/ra-common/src/quote/report_body.rs | UTF-8 | 2,925 | 2.78125 | 3 | [
"Apache-2.0",
"MIT"
] | permissive | use std::{convert::TryInto, fmt};
use super::Measurement;
const REPORT_BODY_LEN: usize = 384;
/// Report body in a quote
pub struct ReportBody {
/// Security version number of host system's CPU
pub cpu_svn: [u8; 16],
/// Attributes of the enclave, for example, whether the enclave is running in debug mode... | true |
fe072f60dd4c4bb2c44d093373b3e8688eb44fe5 | Rust | safrannn/leetcode_rust | /src/_1736_latest_time_by_replacing_hidden_digits.rs | UTF-8 | 1,450 | 3.421875 | 3 | [] | no_license | struct Solution;
impl Solution {
pub fn maximum_time(time: String) -> String {
let time = time.as_bytes();
let mut first = time[0].clone();
let mut second = time[1].clone();
let mut third = time[3].clone();
let mut fourth = time[4].clone();
if first == '?' as u8 && ... | true |
255aa658a5812f1e412a3d76b8eff3ea25290a4e | Rust | jbradaric/aoc-2020 | /day-06/src/main.rs | UTF-8 | 879 | 3.21875 | 3 | [] | no_license | use std::collections::HashSet;
const INPUT: &str = include_str!("../input");
fn count_answers(s: &str) -> usize {
let mut set = HashSet::new();
for line in s.lines() {
for c in line.chars() {
set.insert(c);
}
}
set.len()
}
fn count_answers_part2(s: &str) -> usize {
let... | true |
7525dca1a2196bf36124dd6e49eda8721f56502d | Rust | MaulingMonkey/jreflection | /src/src.rs | UTF-8 | 8,562 | 3.078125 | 3 | [
"Apache-2.0",
"MIT",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | //! Sources of JVM metadata such as .jars, jimage files, etc.
use crate::Class;
use zip::ZipArchive;
use std::cell::RefCell;
use std::default::Default;
use std::fs::File;
use std::ffi::*;
use std::io::{BufReader, Cursor, Error, ErrorKind, Result};
use std::iter::Extend;
use std::path::*;
enum SourceInt {
Jar(Jar)... | true |
89afcddee585c0bf1d465092498f356475c2f061 | Rust | theodoreleebrant/graphs-in-rust | /src/bfs.rs | UTF-8 | 5,571 | 2.953125 | 3 | [] | no_license | //! Will return parent array for a BFS traversal from a source vertex
//!
//! This BFS implementation makes use of the Direction-Optimizing approach \[1\].
//! It uses the alpha and beta parameters to determine whether to switch search
//! directions. For representing the frontier, it uses a SlidingQueue for the
//! to... | true |
cb15c31c053a4044dcbbc4a9a918c2d9285c80c5 | Rust | rustwasm/wasm-bindgen | /tests/wasm/optional_primitives.rs | UTF-8 | 8,215 | 2.515625 | 3 | [
"Apache-2.0",
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | use wasm_bindgen::prelude::*;
use wasm_bindgen_test::*;
#[wasm_bindgen(module = "tests/wasm/optional_primitives.js")]
extern "C" {
fn optional_i32_js_identity(a: Option<i32>) -> Option<i32>;
fn optional_u32_js_identity(a: Option<u32>) -> Option<u32>;
fn optional_isize_js_identity(a: Option<isize>) -> Optio... | true |
362bd28ef6137be05954f53791da13a412674962 | Rust | tempbottle/rust-psutil | /src/system.rs | UTF-8 | 9,127 | 3.015625 | 3 | [
"MIT"
] | permissive | //! Read information about the operating system from `/proc`.
use std::str::FromStr;
use std::path::Path;
use std::collections::HashMap;
use std::io::{Result, ErrorKind, Error};
use PID;
use utils::read_file;
#[derive(Debug)]
pub struct VirtualMemory {
/// Amount of total memory
pub total: u64,
/// Am... | true |
510c449e72594cbbe3906fe473f1ccc682d9709d | Rust | L-F-Stack-Exchange/lockwars | /src/player.rs | UTF-8 | 2,068 | 3.671875 | 4 | [
"MIT"
] | permissive | //! The players.
use crate::{Cooldown, Object};
use std::fmt;
/// A player.
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub enum Player {
/// The left player.
Left,
/// The right player.
Right,
}
impl Player {
/// Returns the opposite player.
pub fn toggle(self) -> Pla... | true |
1b694a06c78c8980eddec43e95bb5d4df044bf7c | Rust | ytulf/ecc | /src/curves.rs | UTF-8 | 21,251 | 2.984375 | 3 | [
"MIT"
] | permissive | use std::fmt;
use std::default::Default;
use std::num::FromStrRadix;
use num::{BigUint, Zero, One};
use num::bigint::ToBigUint;
use fields::{Field, FieldElem, P192, R192, P256, R256, P521, R521};
#[allow(non_snake_case)]
// Weierstrass curve with large characteristic field.
pub trait Curve<F: Field, G: Field>: Clone ... | true |
d5db5f97020732d6cb552e97dec52f8e14d009a5 | Rust | CharlesLiu-TOPNetwork/rustvm | /src/interface.rs | UTF-8 | 6,231 | 2.5625 | 3 | [] | no_license | use std::ffi::CStr;
use std::fs::File;
use std::io::Read;
use std::os::raw::c_char;
use crate::wasm_backend::compile;
#[no_mangle]
pub extern "C" fn validator_wasm_with_path(s: *const c_char) {
let path;
unsafe {
path = CStr::from_ptr(s).to_str().unwrap();
println!("here is wasm file path: {:?... | true |
40226c54e086abf068138fe84c328029230ce022 | Rust | book-resources/rustlernen | /09-Zeichenketten/programmtext-098.rs | UTF-8 | 108 | 3.046875 | 3 | [] | no_license | fn main() {
let mut s1 = String::from("Hallo");
s1.push_str(", Welt!");
println!("s1 = {}", s1);
} | true |
5ace3a42c12f4bd249645050d6c2b2f8081e82c9 | Rust | peterwmwong/aoc2019 | /d14/src/main.rs | UTF-8 | 8,384 | 3.40625 | 3 | [] | no_license | use std::cmp::Ordering::{Equal, Greater, Less};
use std::collections::HashMap;
type ConversionReqs = HashMap<String, usize>;
type ConversionsTable = HashMap<String, (usize, ConversionReqs)>;
fn parse(s: &str) -> ConversionsTable {
s.trim()
.lines()
.map(str::trim)
.map(|s| {
le... | true |
0bcf14d5b8061a623f63fdf02061e77a493c213c | Rust | sammyne/signatures | /ed25519/src/lib.rs | UTF-8 | 4,914 | 2.921875 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | //! Ed25519 signatures.
//!
//! Edwards Digital Signature Algorithm (EdDSA) over Curve25519 as specified in
//! RFC 8032: <https://tools.ietf.org/html/rfc8032>
//!
//! This crate doesn't contain an implementation of Ed25519, but instead
//! contains an [`ed25519::Signature`] type which other crates can use in
//! conju... | true |
9cac6a76e9461cbe2277c7dde32306456e28f145 | Rust | lpil/exercism | /rust/nth-prime/src/lib.rs | UTF-8 | 385 | 3.328125 | 3 | [] | no_license | pub fn nth(n: usize) -> Result<usize, ()> {
if n == 0 {
return Err(());
}
let mut primes: Vec<usize> = vec![2];
let mut candidate = 3;
while primes.len() < n {
let is_prime = primes.iter().all(|prime| candidate % prime != 0);
if is_prime {
primes.push(candidate);... | true |
c1ef684348d39bea1c2325e349c35573c32c0b97 | Rust | au-z/rs-raytrace | /src/rt/camera.rs | UTF-8 | 1,664 | 2.984375 | 3 | [] | no_license | use cgmath::prelude::*;
use cgmath::Vector3;
use rand::prelude::*;
use crate::rt::{Ray};
fn rand_in_unit_disk() -> Vector3<f32> {
let mut vec: Vector3::<f32>;
let mut rng = rand::thread_rng();
loop {
vec = 2.0 * Vector3::<f32>::new(rng.gen(), rng.gen(), 0.0) - Vector3::<f32>::new(1.0, 1.0, 0.0);
... | true |
043881690de040866e82d1be17ff74ff0f67bd5d | Rust | heartyhardy/learnin-rust | /src/strings.rs | UTF-8 | 1,464 | 4.40625 | 4 | [] | no_license | pub fn run(){
// Primitive string
let _greet = "Hello";
// Growable
let greet = String::from("Hello");
println!("{} there! How are you?", greet );
// Length of the string
println!("Length: {}", greet.len() );
// Capacity of the string
println!("Capacity: {}", greet.capacity());
... | true |
4ffe44c344408136a6815e27f0c8157dcd9ef21e | Rust | JamesShoaf/AlgorithmPractice | /arraysMatricesStrings/arrays/maximum_product_subarray/src/lib.rs | UTF-8 | 1,145 | 3.46875 | 3 | [] | no_license | /*
Given an integer array nums, find the contiguous subarray within an array (containing at least
one number) which has the largest product.
*/
fn max_product(nums: Vec<i32>) -> i32 {
if nums.len() == 0 { return 0; }
use std::{ cmp, mem };
let (mut max, mut min, mut best) = (1, 1, i32::MIN);
for num i... | true |
6b74d76bbb51fe98fe18dc5e7c328e4278dc9af2 | Rust | isgasho/dfrs | /src/theme.rs | UTF-8 | 1,862 | 2.875 | 3 | [
"MIT"
] | permissive | use colored::*;
pub struct Theme {
pub char_bar_filled: char,
pub char_bar_empty: char,
pub char_bar_open: String,
pub char_bar_close: String,
pub threshold_usage_medium: f32,
pub threshold_usage_high: f32,
pub color_heading: Option<Color>,
pub color_usage_low: Option<Color>,
pub co... | true |
b96abe762db25cf564f9590d5130e7f6d1d1c958 | Rust | munckymagik/rust_kb | /standard/tests/compile_time_helper_functions.rs | UTF-8 | 1,814 | 3.015625 | 3 | [] | no_license | #[test]
fn compile_time_conversion_checking() {
fn is_convertable<T: Into<i64>>(_n: T) {}
is_convertable(1);
is_convertable(1i8);
is_convertable(1i16);
is_convertable(1i32);
is_convertable(1i64);
is_convertable(1u8);
is_convertable(1u16);
is_convertable(1u32);
// Won't compile
... | true |
3741839f3aacc15595f0960afd5f17eea744e97f | Rust | kumusan/twitter_auth | /src/token.rs | UTF-8 | 800 | 2.796875 | 3 | [] | no_license | use serde::Deserialize;
use reqwest::header::{Headers, Authorization, ContentType};
use base64;
#[derive(Deserialize, Debug)]
pub struct Token {
pub access_token: String,
pub token_type: String,
}
pub fn get_token() -> Token {
let consumer_key = "";
let consumer_secret = "";
let auth = base64::enc... | true |
e7f762a4a952263f4bc8e44407410702b9d9f61d | Rust | lu-zero/av-scenechange | /src/lib.rs | UTF-8 | 11,934 | 2.96875 | 3 | [
"MIT"
] | permissive | mod pixel;
mod y4m;
use self::pixel::*;
use ::y4m::{Colorspace, Decoder};
use std::cmp;
use std::collections::{BTreeMap, BTreeSet};
use std::io::Read;
/// Options determining how to run scene change detection.
pub struct DetectionOptions {
/// Whether or not to analyze the chroma planes.
/// Enabling this is ... | true |
f96075d9b48ff8184c272304ac5137be31f526ef | Rust | mantono/food | /src/qty.rs | UTF-8 | 16,489 | 3.59375 | 4 | [
"MIT"
] | permissive | use std::fmt;
#[derive(Eq, PartialEq, Hash, Debug, Clone)]
pub enum Quantity {
Pieces(u32),
Weight(Weight),
Volume(Volume),
Custom(u32, String),
}
trait StdUnit {
fn in_std_unit() -> u32;
}
impl std::ops::Add for Quantity {
type Output = Quantity;
fn add(self, other: Quantity) -> Quantit... | true |
aac9df15585fb551656d960a6992e31e5f4c7b76 | Rust | synecdoche/pelikan | /src/rust/metrics/src/lib.rs | UTF-8 | 2,278 | 2.578125 | 3 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | // Copyright 2021 Twitter, Inc.
// Licensed under the Apache License, Version 2.0
// http://www.apache.org/licenses/LICENSE-2.0
//! A wrapper library for metrics which contains helper functions and macros to
//! make it easier to use metrics within Pelikan.
pub use common::metrics::{metric, Counter, Gauge, Heatmap, R... | true |
66807875907833de3286ce4f27fe1ffa1a9a0e9c | Rust | HadrienG2/smallmatrix-tests | /tests/iter.rs | UTF-8 | 3,846 | 2.875 | 3 | [] | no_license | //! Iterator-related tests
//!
//! Split out from other tests to increase build parallelism
mod common;
use self::common::*;
use paste::paste;
use quickcheck_macros::quickcheck;
use smallmatrix_tests::{Matrix, Scalar};
fn test_from_col_major_elems<const ROWS: usize, const COLS: usize>(elems: Vec<Scalar>) {
if el... | true |
91a063670978a088a7636d1cd38fd8218736b374 | Rust | kennetpostigo/zero-to-production | /src/routes/subscriptions.rs | UTF-8 | 6,066 | 2.78125 | 3 | [] | no_license | use crate::domain::{NewSubscriber, SubscriberEmail, SubscriberName};
use crate::email_client::EmailClient;
use crate::startup::ApplicationBaseUrl;
use actix_web::http::StatusCode;
use actix_web::{web, HttpResponse, ResponseError};
use anyhow::Context;
use chrono::Utc;
use rand::distributions::Alphanumeric;
use rand::{t... | true |
f2353ae15f177f1199ffcf36854f8c52d0fdb118 | Rust | felixniemeyer/repeer-simulation-B | /src/main.rs | UTF-8 | 8,701 | 2.671875 | 3 | [] | no_license | use rand::rngs::ThreadRng;
use rand::Rng;
use core::fmt;
use std::collections::HashMap;
struct GameParams {
borrower_defect_payout: f64,
borrower_coop_payout: f64,
lender_defect_payout: f64,
lender_coop_payout: f64
}
const GP: GameParams = GameParams {
borrower_defect_payout: 6., // steals the... | true |
b4615716a35ff8ea20031996eca07c5eb2a2228b | Rust | jacksonludwig/Rust-General | /modules_1/src/use_as_keywords.rs | UTF-8 | 799 | 2.75 | 3 | [] | no_license | use std::collections::HashMap;
// -------------------------------
mod front_of_house {
pub mod hosting {
pub fn add_to_waitlist() {}
}
}
use crate::front_of_house::hosting;
pub fn eat_at_restaurant() {
hosting::add_to_waitlist();
hosting::add_to_waitlist();
hosting::add_to_waitlist();
}
/... | true |
47720dc74bef744879f06cf6e631b1ac4426e028 | Rust | uazu/stakker | /src/lib.rs | UTF-8 | 24,496 | 3.1875 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | //! [![license:MIT/Apache-2.0][1]](https://github.com/uazu/stakker)
//! [![github:uazu/stakker][2]](https://github.com/uazu/stakker)
//! [![crates.io:stakker][3]](https://crates.io/crates/stakker)
//! [![docs.rs:stakker][4]](https://docs.rs/stakker)
//! [![uazu.github.io:stakker][5]](https://uaz... | true |
8ff004bc1f6d8658fb87772380b3bb60dc0ff2c8 | Rust | ejmahler/RustFFT | /src/sse/sse_vector.rs | UTF-8 | 11,215 | 3.171875 | 3 | [
"MIT",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | use core::arch::x86_64::*;
use num_complex::Complex;
use std::ops::{Deref, DerefMut};
use crate::array_utils::DoubleBuf;
// Read these indexes from an SseArray and build an array of simd vectors.
// Takes a name of a vector to read from, and a list of indexes to read.
// This statement:
// ```
// let values = read_co... | true |
85cd8b024208bf16689a1e513e62ffba3f29b710 | Rust | devforfu/rust | /traits/src/complex.rs | UTF-8 | 1,344 | 4 | 4 | [] | no_license | use std::ops::{Add, Sub};
pub struct Complex<T> {
pub re: T,
pub im: T,
}
impl<T> Complex<T> {
pub fn new(re: T, im: T) -> Self { Complex { re, im } }
}
impl<T> Add for Complex<T>
where
T: Add<Output = T>
{
type Output = Self;
fn add(self, rhs: Self) -> Self::Output {
Complex... | true |
4657563fe3924d4edd7c7bd5f5240b8c3dadd632 | Rust | emrecelikten/adventofcode2020 | /d16/src/main.rs | UTF-8 | 4,949 | 3.109375 | 3 | [] | no_license | use std::collections::HashMap;
use std::ops::RangeInclusive;
use regex::Regex;
fn load_data(filename: &str) -> String {
std::fs::read_to_string(filename).unwrap()
}
type RuleMap = HashMap<String, (RangeInclusive<usize>, RangeInclusive<usize>)>;
fn parse_data(data: &str) -> (RuleMap, Vec<Vec<usize>>) {
let m... | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.