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
da6c2685d91f6fc86c990a947643efad2341c557
Rust
batmanwgd/advent-of-code-rust
/src/day1.rs
UTF-8
1,107
3.21875
3
[]
no_license
#[aoc(day1, part1)] pub fn part1(input: &str) -> Option<i32> { let mut my_ints = input.lines().map(|x| x.parse::<i32>().unwrap() ).collect::<Vec<i32>>(); my_ints.sort_unstable(); for x in &my_ints { if 2020 - x > 0 && my_ints.iter().any(|&y| y == 2020 - x ){ return Some(x * (...
true
0bb8777af5591e57a2cb17c8f3f4f6d628fe622a
Rust
dbrgn/acmed
/acmed/build.rs
UTF-8
3,590
2.640625
3
[ "FSFAP", "MIT", "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
extern crate serde; extern crate toml; use serde::Deserialize; use std::env; use std::fs::File; use std::io::prelude::*; use std::io::BufReader; use std::path::PathBuf; macro_rules! set_rustc_env_var { ($name: expr, $value: expr) => {{ println!("cargo:rustc-env={}={}", $name, $value); }}; } #[derive(...
true
88d6032adcd29af4d650442f90d669d19ea726b5
Rust
mr-beerkiss/samples
/books/the-rust-programming-language/19-Advanced-Features/advanced-functions-and-closures/src/lib.rs
UTF-8
892
3.90625
4
[]
no_license
fn add_one(x: i32) -> i32 { x + 1 } fn do_twice(f: fn(i32) -> i32, arg: i32) -> i32 { f(arg) + f(arg) } #[cfg(test)] mod tests { use super::*; #[test] fn it_does_add_one_twice() { assert_eq!(do_twice(add_one, 5), 12); } #[test] fn it_uses_closure_to_convert_vec_int_to_str() {...
true
207f6c28cf4783f13fc249751db5244b44eea4bf
Rust
Pajn/server-manager
/src/services/ssh.rs
UTF-8
1,130
3.078125
3
[]
no_license
use std::process::Command; use config::SshConfiguration; impl SshConfiguration { fn as_command<'a>(&self) -> Command { let connection_string = if let Some(ref user) = self.user { format!("{}@{}", user, self.host) } else { self.host.to_owned() }; let mut comm...
true
b82429dea1c17fa453d5e04e9aaf1187544ae45e
Rust
althonos/uniprot.rs
/src/uniprot/model/comment/conflict.rs
UTF-8
4,552
2.765625
3
[ "MIT" ]
permissive
use std::io::BufRead; use std::str::FromStr; use quick_xml::events::BytesStart; use quick_xml::Reader; use crate::error::Error; use crate::error::InvalidValue; use crate::parser::utils::attributes_to_hashmap; use crate::parser::utils::decode_attribute; use crate::parser::utils::extract_attribute; use crate::parser::F...
true
040890a2be1554bbd83a25428288a92724987b38
Rust
haryu703/cash-tx-builder
/src/types/uint256.rs
UTF-8
3,382
3.015625
3
[ "MIT" ]
permissive
use std::str::FromStr; use hex; use super::error::{Error, Result}; #[cfg(feature = "serde")] use serde::{Serializer, Serialize, Deserializer, Deserialize, de}; /// 256 bit unsigned value #[allow(non_camel_case_types)] #[derive(Copy, Clone, Debug, Default, PartialEq, Eq)] pub struct uint256(pub [u8; 32]); // TODO: u...
true
eec77d0dd1ab07b6503f0f1fb77b6a5f08797e00
Rust
someoneonearthwholovestg/el_monitorro
/src/sync/reader/atom.rs
UTF-8
3,765
3.046875
3
[ "MIT" ]
permissive
use crate::db; use crate::sync::reader; use crate::sync::reader::{FeedReaderError, FetchedFeed, FetchedFeedItem, ReadFeed}; use atom_syndication::Feed as AtomFeed; use chrono::{DateTime, FixedOffset, Utc}; pub struct AtomReader { pub url: String, } impl ReadFeed for AtomReader { fn read(&self) -> Result<Fetch...
true
5b1ec402035676a8b9b7bec297a3683b0ad0e88c
Rust
slavapeshkin/reactive-rs
/src/stream.rs
UTF-8
25,486
3.5
4
[ "MIT" ]
permissive
use std::borrow::Borrow; use std::cell::RefCell; use std::iter::Iterator; use std::rc::Rc; #[cfg(any(test, feature = "slice-deque"))] use slice_deque::SliceDeque; /// A stream of context/value pairs that can be subscribed to. /// /// Note: in order to use stream trait methods, this trait /// must imported into the cu...
true
7eb749267c41571e062bb937c42db7cea0f418a1
Rust
g-jackson/rust-learning
/structs/src/main.rs
UTF-8
1,867
3.75
4
[ "MIT" ]
permissive
fn main() { let mut user1 = User { email: String::from("someone@example.com"), username: String::from("someusername123"), active: true, sign_in_count: 2, }; println!("user1: {}", user1.username); user1.email = String::from("someone@changedemail.com"); println!("{}", u...
true
d0a7ddb65b5eda5aa043974b1b76a23561dba574
Rust
kogai/oxford-dictionary-api-rs
/src/models/thesaurus_lexical_entry.rs
UTF-8
3,316
2.59375
3
[]
no_license
/* * * * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) * * OpenAPI spec version: 1.11.0 * * Generated by: https://github.com/swagger-api/swagger-codegen.git */ /// ThesaurusLexicalEntry : Description of an entry for a particular part of speech #[allow...
true
2e629c2eab39e9ecab882d151f08aa556a177844
Rust
leetie/rust-connect4
/src/game.rs
UTF-8
2,334
3.375
3
[]
no_license
// Module for game functions pub mod board { use crate::player::*; use colored::*; use std::{thread, time}; pub fn new() -> Vec<Vec<ColoredString>> { vec![vec!["O".black().on_green(); 7]; 5] } fn print_board(board: &Vec<Vec<ColoredString>>) { for row in board.iter() { for cell in row.iter() ...
true
2989fa275eafd226388869612ce38c7d65302687
Rust
DarinM223/ctci-rs
/src/chapter8/recursive_multiply.rs
UTF-8
1,322
3.296875
3
[]
no_license
pub fn min_product(a: i32, b: i32) -> i32 { let (bigger, smaller) = if a < b { (b, a) } else { (a, b) }; min_product_helper(smaller, bigger) } fn min_product_helper(smaller: i32, bigger: i32) -> i32 { if smaller == 0 { return 0; } else if smaller == 1 { return bigger; } let s ...
true
e8434ad5fc60d98166c5901d50d9bdbbc1f9d75f
Rust
truchi/lay
/src/layer/canvas/layer.rs
UTF-8
2,444
2.90625
3
[]
no_license
use crate::*; use std::{ iter::{Copied, Flatten}, slice::{Iter, IterMut}, }; pub type CanvasRow<'a> = Copied<Iter<'a, Cell>>; pub type CanvasRowMut<'a> = IterMut<'a, Cell>; pub type CanvasCells<'a> = Flatten<CanvasRows<'a>>; pub type CanvasCellsMut<'a> = Flatten<CanvasRowsMut<'a>>; impl LayerSize for Canvas {...
true
9a52d3f0c0e1f9997d3e6572ad8dba3c25424897
Rust
importcjj/async-tungstenite
/examples/split-client.rs
UTF-8
3,067
3.203125
3
[ "MIT" ]
permissive
//! A simple example of hooking up stdin/stdout to a WebSocket stream. //! //! This example will connect to a server specified in the argument list and //! then forward all data read on stdin to the server, printing out all data //! received on stdout. //! //! Note that this is not currently optimized for performance, ...
true
015f022932f33224c9e0803f3509cbe5ff639972
Rust
andrewcsmith/vox_box.rs
/src/polynomial.rs
UTF-8
14,873
3.046875
3
[]
no_license
extern crate num; use std::ops::Neg; use std::iter::*; use error::*; use num::{Float, Zero, One, FromPrimitive, Complex}; pub trait Polynomial<'a, T> { fn degree(&self) -> usize; fn off_low(&self) -> usize; fn laguerre(&self, z: Complex<T>) -> Complex<T>; fn find_roots_work_size(&self) -> usize; ...
true
70943d2c07cd14df866c51248746615ea0814865
Rust
ntgraff/infinite-tic-tac-toe
/src/main.rs
UTF-8
897
3.234375
3
[]
no_license
mod board; mod game; use board::Board; use game::Game; use std::env; macro_rules! USAGE_FMT { () => { r#" Usage: {exe_path} [DEPTH] DEPTH must be a natural number, and is 0 by default "#; } } fn main() { let mut args = env::args(); let exe_path = args.next().unwrap(); let depth = if let Some(...
true
a15a3413b1476a8d054d10da3b8805f8bbc36e76
Rust
spacemeshos/svm
/crates/wasm/sdk-std/src/vec.rs
UTF-8
8,183
3.46875
3
[ "LicenseRef-scancode-free-unknown", "MIT" ]
permissive
/// This file implements a `Vec` of a fixed-size. /// In order to use it, the maximum number of elements should be known before calling `Vec#with_capacity. /// The underlying allocated memory won't resize (grow or shrink) nor will it move. /// /// The API of the fixed-sized `Vec` is a subset of `std::vec::Vec`. /// So ...
true
5b3f98861eff58f90cd7972a1d3089d65b9c34a0
Rust
cesindo/pandemia
/src/city_dao.rs
UTF-8
2,695
2.9375
3
[ "MIT" ]
permissive
//! Dao implementation for City //! use chrono::prelude::*; use diesel::prelude::*; use diesel::sql_types; use crate::{models::City, result::Result, schema::cities, sqlutil::lower, types::EntriesResult, ID}; #[derive(Insertable)] #[table_name = "cities"] struct NewCity<'a> { pub name: &'a str, pub province: ...
true
b744aeda773fe8b382ac9d7e117bbc7088ee1c4d
Rust
foxfriends/root
/src/handler/client_command.rs
UTF-8
1,363
3.171875
3
[]
no_license
use super::{CommandError, Socket}; use crate::models::GameConfig; #[derive(Debug, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub enum ClientCommand { SetName(String), JoinGame(String), CreateGame(GameConfig), LeaveGame, Perform(String), } impl ClientCommand { ///...
true
12751ffd7852f21c28c111e8d644d9c82476c102
Rust
icefoxen/games-rustdragon
/src/bounded_number.rs
UTF-8
1,639
3.78125
4
[ "MIT" ]
permissive
use std::cmp; use std::fmt; use std::ops::{Add, Sub, AddAssign, SubAssign}; /// Represents a u32 that is fixed to be between 0 and some max value. #[derive(Copy, Clone, Debug, PartialEq)] pub struct BoundedNumber { pub val: u32, pub max: u32, } impl BoundedNumber { pub fn new(max: u32) -> BoundedNumber {...
true
20c7d7d983c8407f2d31debdc793b5609dd99d63
Rust
ConnyOnny/simple_parallel
/src/pool.rs
UTF-8
22,387
3.21875
3
[ "MIT", "Apache-2.0" ]
permissive
use std::collections::BinaryHeap; use std::iter::IntoIterator; use std::{marker, mem}; use std::sync::{mpsc, atomic, Mutex, Arc}; use std::thread; use fnbox::FnBox; use crossbeam::{self, Scope}; type JobInner<'b> = Box<for<'a> FnBox<&'a [mpsc::Sender<Work>]> + Send + 'b>; struct Job { func: JobInner<'static>, } ...
true
e166a15bcecb4a04e8c1705abdd2879a1d85bff6
Rust
devops-vn/shortcut-cli
/src/macro_hub.rs
UTF-8
3,869
2.921875
3
[ "BSD-3-Clause", "BSD-2-Clause-Views" ]
permissive
use slog::Logger; use std::collections::HashMap; use yaml_rust::YamlLoader; use crate::error::EasyErrorHandling; use crate::kvs::KVS; use regex::Regex; use colored::*; #[derive(Debug)] pub struct MacroHub<'a> { logger: &'a Logger, config: &'a HashMap<String, String>, hub_list_uri: &'a str, macros_hu...
true
71adb4941609f3822c1c4018a25f2a63ac6bf61e
Rust
nooberfsh/service-registry
/src/heartbeat/server.rs
UTF-8
4,526
2.609375
3
[]
no_license
use std::io; use std::sync::Arc; use std::sync::mpsc; use std::net::{SocketAddr, SocketAddrV4}; use std::thread::{self, JoinHandle}; use bytes::BytesMut; use tokio_core::reactor::{Core, Handle}; use tokio_core::net::TcpListener; use tokio_io::codec::length_delimited::Framed; use tokio_io::AsyncWrite; use futures::sync...
true
85e004a9f34a614f50c5eca9327175a3273b9241
Rust
Dakuaxd/tic_tac_toe
/tic_tac_toe/src/main.rs
UTF-8
16,063
3.140625
3
[]
no_license
use std::io; fn main() { let mut grid: [[usize; 3]; 3] = [[0; 3]; 3]; let mut is_pX_turn: bool = true; let game_over_state: usize; let bot_difficulty: usize; // indexing like this: grid[1][2] let (is_two_player, bot_difficulty, is_go_first): (bool, usize, bool) = intro(); if !is_two_playe...
true
70bf6bf99bae99bb209949c1cdbe28aba468a54e
Rust
Einstrasse/rust-web-server
/src/main.rs
UTF-8
1,128
2.90625
3
[]
no_license
use std::net::{TcpListener, TcpStream}; use std::io::{Write}; use std::io::prelude::*; fn handle_client(mut stream: TcpStream) { //get request and dump let mut request = [0; 1024]; stream.read(&mut request).unwrap(); println!("Received HTTP Request...\n{}", String::from_utf8_lossy(&request[..])); l...
true
1746fbb22a53bbdfc81222ba73be09c05e09f314
Rust
mardiros/cabot
/src/asynctls.rs
UTF-8
6,496
2.6875
3
[ "BSD-3-Clause" ]
permissive
//! decrypt TLS data using rustls on a async-std TcpStream use std::io::{Error as IoError, ErrorKind as IoErrorKind, Read as SyncRead, Write as SyncWrite}; use std::pin::Pin; use std::sync::Arc; use std::vec::Vec; use async_std::io::{Read, Result as IoResult, Write}; use async_std::net::TcpStream; use async_std::prel...
true
823b978b41d9aa9538e79e723625f3dd972ab5f0
Rust
EvanMerlock/sports_record
/record_client/src/client/web/web_handler.rs
UTF-8
3,182
2.65625
3
[ "MIT" ]
permissive
use std::sync::mpsc::{channel, Sender}; use std::io; use std::net::{TcpStream, SocketAddr}; use std::sync::{Arc, Mutex}; use std::thread; use websocket::server::sync::{Server}; use websocket::client::sync::{Client}; use websocket::Message; use client::web::body_writer; use base64; use iron::prelude::*; use iron::Li...
true
bd27f8ea0b7609174b600f7be660eeb7965fc7c1
Rust
mactsouk/introRustLC
/day1/S3/palindromes.rs
UTF-8
788
3.5
4
[]
no_license
use std::env; pub fn check_palindrome(input: &str) -> bool { if input.len() == 0 { return true; } let mut last = input.len() - 1; let mut first = 0; let my_vec = input.as_bytes().to_owned(); while first < last { if my_vec[first] != my_vec[last] { return fal...
true
2822584e36c7d0c59b07745297b3e0c0bb9b4852
Rust
ashutoshlamba/ECE421-GroupProject1
/connect4/connect4-server/src/jwthelper.rs
UTF-8
2,510
2.953125
3
[]
no_license
// from https://github.com/Keats/jsonwebtoken/blob/master/examples/validation.rs pub static JWT_KEY: &str = env!("JWT_KEY"); //use jsonwebtoken::errors::ErrorKind; use connect4_coms::types::{ClaimPayload, Claims}; use jsonwebtoken::{decode, encode, DecodingKey, EncodingKey, Header, Validation}; use std::time::{System...
true
ddf83ddee0ee829337b1f6c4cc3e3f3d21c944fa
Rust
hakatashi/nine-grids-shogi-analyzer
/tests/BoardMap.rs
UTF-8
6,993
2.65625
3
[ "MIT" ]
permissive
#![feature(non_ascii_idents)] extern crate nine_grids_shogi_analyzer; use nine_grids_shogi_analyzer::Board::{Board}; use nine_grids_shogi_analyzer::BoardMap::{BoardMap}; use nine_grids_shogi_analyzer::Piece::{Piece}; use nine_grids_shogi_analyzer::Grid::{Grid}; #[test] fn board_map_from_pieces_test() { let board...
true
1dfcf30d21c3cb29717f682a5383f6cf1533ee8c
Rust
jlgerber/rustclass
/exe1/work/levelspec/src/lib.rs
UTF-8
3,711
3.84375
4
[]
no_license
//! LevelSpec - creates a levelspec duh? pub mod error; pub use error::LevelSpecError; use std::env; use std::str::FromStr; #[derive(Debug, PartialEq, Eq, PartialOrd, Ord)] pub enum LevelSpec { Show { show: String, }, Sequence { show: String, sequence: String, }, Shot { ...
true
7625a326f8a86187464d112165f9fb5e51f61fb4
Rust
bkaestner/pipeviewer
/src/main.rs
UTF-8
1,482
2.6875
3
[]
no_license
use anyhow::Result; use indicatif::{ProgressBar, ProgressStyle}; use std::fs::File; use std::io::{self, ErrorKind, Read}; use std::path::PathBuf; use structopt::StructOpt; #[derive(Debug, StructOpt)] #[structopt(name = "pipeviewer", about = "A pipe inspecting application.")] struct Opt { // TODO: Handle more input...
true
7c0549c2db9fd693600d5e23800ed1cc0aa3f334
Rust
bodgergely/wargames
/tutorials/lang-tut/rust/haha/src/main.rs
UTF-8
135
2.828125
3
[]
no_license
fn main() { println!("Hello, world!"); goal(); } fn goal() { let s = "Hello Marcika"; println!("{hello}", hello=s); }
true
b89757c0c3dd67c1ee3c6a1a609730ac8be2aa72
Rust
bouzuya/rust-atcoder
/cargo-atcoder/contests/math-and-algorithm/src/bin/048.rs
UTF-8
897
2.765625
3
[]
no_license
use proconio::input; fn dijkstra(n: usize, inf: u64, e: &[Vec<(usize, u64)>], s: usize) -> Vec<u64> { use std::{cmp::Reverse, collections::BinaryHeap}; let mut d = vec![inf; n]; let mut pq = BinaryHeap::new(); d[s] = 0; pq.push(Reverse((0, s))); while let Some(Reverse((w_u, u))) = pq.pop() { ...
true
e9a8d23e79747bcece4c9bcbd2cb8c4119b70b40
Rust
MattiasBuelens/rust-countdown-game
/src/solve.rs
UTF-8
5,452
3.671875
4
[]
no_license
use std::rc::Rc; use std::fmt; use std::ops::Deref; use std::collections::VecDeque; #[derive(Debug, Clone)] enum Operator { Add, Subtract, Multiply, Divide } const NUM_OPERATORS: usize = 4; impl fmt::Display for Operator { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self ...
true
7fd1366e45020b03e99f69291866df3e17316409
Rust
tlverwijst/snips-nlu-utils
/src/language.rs
UTF-8
1,287
3.28125
3
[ "Apache-2.0" ]
permissive
use std::str::FromStr; use failure; use failure::format_err; const PUNCTUATION: &str = "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"; const SPACE: &str = " "; macro_rules! language_enum { ([$($language:ident),*]) => { /// Enumerates all language supported #[allow(non_camel_case_types)] #[derive(Cop...
true
29b6ff02ebb97e3d632e585b006761917c09c1d6
Rust
dobrite/flexbox-rs
/src/cursor.rs
UTF-8
3,019
3.390625
3
[]
no_license
use std::default::Default; use offset; use rgb; use style; #[derive(Clone, Copy, Debug, Default)] pub struct Cursor { pub x: u32, pub y: u32, pub offset_x: i32, pub offset_y: i32, pub root_width: u32, pub root_height: u32, pub width: u32, pub height: u32, pub fg: rgb::RGB<u8>, ...
true
83e2554a09aa73dbeac24f087fe6a2ad5b4069bb
Rust
davidk81/rust-actix-hello
/src/extractor.rs
UTF-8
294
2.609375
3
[]
no_license
use actix_web::{web, post, Result}; use serde::{Deserialize, Serialize}; #[derive(Deserialize, Serialize)] pub struct Event { username: String, } #[post("/extractor")] pub async fn post( body: web::Json<Event> ) -> Result<String> { Ok(format!("hello, {}\n", body.username)) }
true
73854aa64b3150b0b8e22e3d9f7efc71fe80cc30
Rust
scalar438/sysinfo
/src/apple/utils.rs
UTF-8
713
2.859375
3
[ "MIT" ]
permissive
// Take a look at the license at the top of the repository in the LICENSE file. use libc::c_char; pub(crate) fn cstr_to_rust(c: *const c_char) -> Option<String> { cstr_to_rust_with_size(c, None) } pub(crate) fn cstr_to_rust_with_size(c: *const c_char, size: Option<usize>) -> Option<String> { if c.is_null() {...
true
7d4f8ea1814ecb633af458433982311da2ba57f9
Rust
michimani/Project-Euler-Solutions
/rust/src/solutions/s0001.rs
UTF-8
695
3.03125
3
[ "MIT" ]
permissive
use proconio::input; use std::time::Instant; /// Solution for Project Euler problem 1 /// /// Copyright michimani All rights reserved. /// /// https://projecteuler.net/problem=1 pub fn solve() { let org = 1000; println!("(original: {})", org); input! { limit: usize, } let start = Instant::no...
true
ee41bc2822d116bac98ab9427770d7f14761d3b4
Rust
jdanford/tern
/src/vm.rs
UTF-8
13,431
3.03125
3
[ "ISC" ]
permissive
use libc::{malloc, free}; use std::mem::transmute; use ternary; use types::*; use opcodes::Opcode; use registers::{Register, REGISTER_COUNT}; use syscalls::Syscall; pub const PROGRAM_MAGIC_NUMBER: isize = 47330224520; // 1TTTTT1TTTTT1TTTTT1TTTTT pub struct VM { pub registers: [Word; REGISTER_COUNT], pub memo...
true
f964cf7b82e614b3459730632e70cf49e896ea43
Rust
orogene/orogene
/crates/oro-package-spec/src/lib.rs
UTF-8
4,703
2.921875
3
[ "Apache-2.0", "ISC" ]
permissive
//! NPM package specifier parser. This is the stuff that takes something like //! `foo@^1.2.3` and turns it into something meaningful. use std::fmt; use std::path::PathBuf; use std::str::FromStr; use node_semver::{Range, Version}; use nom::combinator::all_consuming; use nom::Err; pub use crate::error::{PackageSpecEr...
true
7cde7b22cb9c8b65e840c0f593cb2c3ff118614e
Rust
WhyNotHugo/malc
/src/main.rs
UTF-8
1,857
2.875
3
[ "ISC", "LicenseRef-scancode-unknown-license-reference" ]
permissive
extern crate env_logger; #[macro_use] extern crate lazy_static; #[macro_use] extern crate log; extern crate regex; use std::fs::File; use std::io::Read; use std::io::Write; use std::thread::sleep; use std::time::Duration; use regex::Regex; fn read_ambient_light() -> u8 { let path = "/sys/devices/platform/applesm...
true
0f994b62e3aed782ac30e2b49d75bdfb5f49eb8e
Rust
miquels/nntp-rs
/src/util/de.rs
UTF-8
3,480
3.375
3
[ "MIT" ]
permissive
use serde::{self, Deserialize, Deserializer}; use std::io; use std::time::Duration; /// Parse size in B, K, KB, KiB, M, MB, MiB, G, GB, GiB. pub fn parse_size(s: &str) -> io::Result<u64> { let mut s = s.to_string(); s.make_ascii_lowercase(); let (num, mul) = match s.find(|c: char| c.is_alphabetic()) { ...
true
0a6324d50b47ad6611f9caaf3cd11d1f7ce63819
Rust
rupansh/gb
/src/frontend.rs
UTF-8
2,258
3.09375
3
[]
no_license
use crate::consts::*; use crate::{ cpu::Cpu, mem::Mem, input::{KeyCode, Input}, }; use sdl2::{ event::Event, EventPump, keyboard::Keycode, rect::Rect, render::Canvas, }; pub struct FrontEnd { canvas: Canvas<sdl2::video::Window>, event_pump: EventPump } impl Default for FrontEnd...
true
60b0b24306aae0a59db6a976cacf4a19953adf0a
Rust
gitter-badger/jolimail
/server/src/model/template/create.rs
UTF-8
1,382
2.90625
3
[]
no_license
use crate::error::ServerError; use deadpool_postgres::Client; use serde::{Deserialize, Serialize}; use slug::slugify; use super::Template; use super::COLUMNS; lazy_static! { pub static ref QUERY_INSERT: String = format!( "INSERT INTO templates (title, slug, description) VALUES ($1, $2, $3) RETURNING {}", ...
true
2c6cb1204185e97721291ca309a2cc0afd785454
Rust
bashi8128/rip
/src/parse_args.rs
UTF-8
1,023
2.828125
3
[]
no_license
//! Author: Masahiro Itabashi <itabasi.lm@gmail.com> //! Last modified: Mon, 11 Jan 2021 21:35:22 +0900 use std::env; use docopt::Docopt; use serde::Deserialize; #[derive(Debug, Deserialize)] pub struct Args { arg_file: String, flag_p: Option<i32>, flag_s: Option<String>, flag_u: bool, flag_r: Opt...
true
53cb02fba91db530cf159345f23318d855e12ae0
Rust
RohanArepally/tt
/src/main.rs
UTF-8
2,848
3.03125
3
[]
no_license
extern crate clap; extern crate chrono; extern crate ansi_term; extern crate term_grid; use clap::{Arg, App, ArgMatches, SubCommand, AppSettings}; use clap::crate_version; use std::time::{SystemTime, UNIX_EPOCH}; use chrono::{DateTime, Utc, TimeZone, Duration, Local}; use std::str::FromStr; use ansi_term::Colour::{Red...
true
a4f67a8c92b0c5a7831cbc2dba6cd01d7e1cc941
Rust
ssnover/pkmn_tools
/pkmn_utils/src/lib.rs
UTF-8
319
3
3
[ "Apache-2.0", "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
use num_derive::{FromPrimitive, ToPrimitive}; #[repr(u16)] #[derive(Debug, FromPrimitive, PartialEq, ToPrimitive)] pub enum Species { Squirtle = 7, Pidgey = 16, } impl std::fmt::Display for Species { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "{:?}", self) } }
true
c3bb5f89cddfbcbeef7493e6cb0b38be7874e66b
Rust
alexcrichton/futures-spsc
/tests/channel.rs
UTF-8
2,237
2.609375
3
[ "Apache-2.0", "MIT", "LicenseRef-scancode-other-permissive", "LicenseRef-scancode-unknown-license-reference" ]
permissive
extern crate futures; extern crate futures_spsc as spsc; use std::sync::Arc; use std::sync::atomic::*; use futures::{Future, Async, Stream, Sink}; use futures::future::done; use futures::executor; mod support; use support::*; #[test] fn sequence() { let (tx, mut rx) = spsc::channel(); sassert_empty(&mut rx...
true
6fc18edfd6f3136c1086c5cf3e9109ef8f42b130
Rust
BurtonMatthew/aoc-2019
/src/day17.rs
UTF-8
7,350
3.03125
3
[]
no_license
use intcode::Program; use vec2::Vec2; use itertools::Itertools; pub fn main(file_data: &str) { part2(file_data, &part1(file_data)); } pub fn part1(file_data: &str) -> Vec2<char> { let mut program : Program = file_data.parse().unwrap(); program.extend_tape(10000); let prog_output = program.map(|i|...
true
a49e53290839dc9f19c938b5baf37d3a769b2dc2
Rust
rust-lang/rust
/tests/ui/typeck/assign-non-lval-needs-deref.rs
UTF-8
412
2.890625
3
[ "Apache-2.0", "LLVM-exception", "NCSA", "BSD-2-Clause", "LicenseRef-scancode-unicode", "MIT", "LicenseRef-scancode-other-permissive" ]
permissive
// issue #101376 use std::ops::AddAssign; struct Foo; impl AddAssign<()> for Foo { fn add_assign(&mut self, _: ()) {} } impl AddAssign<()> for &mut Foo { fn add_assign(&mut self, _: ()) {} } fn main() { (&mut Foo) += (); //~^ ERROR invalid left-hand side of assignment //~| NOTE cannot assign to ...
true
05376f953bf9ae230b6ca9c4a206bab96c5aa684
Rust
shutarou-iijima/github_actions_rust_sample
/src/main.rs
UTF-8
236
3.359375
3
[]
no_license
fn main() { println!("{}", add(1, 2)); } fn add(a: i32, b: i32) -> i32 { a + b } #[cfg(test)] mod tests { use super::*; #[test] fn test_add() { let value = add(1, 2); assert_eq!(3, value); } }
true
979d07ff40ecf349b72154c5709115f0d400378a
Rust
s1th-lord/rust-facedetect
/src/window.rs
UTF-8
650
2.515625
3
[ "MIT" ]
permissive
use opencv::{highgui, prelude::*}; type Result<T> = opencv::Result<T>; pub(crate) struct Window { name: String, } impl Window { pub fn create(name: &'_ str, width: i32, height: i32) -> Result<Self> { highgui::named_window(name, highgui::WINDOW_GUI_NORMAL | highgui::WINDOW_KEEPRATIO)?; highgui...
true
926bd1daa258b047e4eec2a63f8c59e5028d050d
Rust
danieleorler/advent_of_code
/2019/src/bin/03.rs
UTF-8
2,653
3.109375
3
[]
no_license
use std::io; use std::io::prelude::*; use aoc2019::geometry::{Point, Line, manhattan_distance}; fn main() { let stdin = io::stdin(); let mut a = String::new(); stdin.lock().read_line(&mut a).unwrap(); let first = to_lines(to_points(to_instructions(String::from(a.trim())))); let mut b = String::new...
true
c2a0aa6fbd2586c74910825175817fd3fb3c6ab4
Rust
IThawk/rust-project
/rust-master/src/test/ui/const-generics/uninferred-consts-during-codegen-2.rs
UTF-8
446
2.96875
3
[ "MIT", "LicenseRef-scancode-other-permissive", "Apache-2.0", "BSD-3-Clause", "BSD-2-Clause", "NCSA" ]
permissive
// run-pass #![feature(const_generics)] //~^ WARN the feature `const_generics` is incomplete and may cause the compiler to crash use std::fmt; struct Array<T>(T); impl<T: fmt::Debug, const N: usize> fmt::Debug for Array<[T; N]> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_list().entr...
true
4ef599633b89e993ffbe49d9601fe97a1fda2ace
Rust
spiricn/rserv
/src/thread_pool/thread_pool.rs
UTF-8
1,870
3.640625
4
[]
no_license
use super::worker::Message; use super::worker::Worker; use std::sync::Arc; use std::sync::Mutex; /// Thread pool pub struct ThreadPool { /// List of worker threads workers: Vec<Worker>, /// Channel used to send messages to one of the threads sender: std::sync::mpsc::Sender<Message>, } impl ThreadPool...
true
309ad2201ae280bf5d53516511fcc3f84f0022cb
Rust
ApproachingApathy/rust-lang
/variables/src/main.rs
UTF-8
227
3.171875
3
[]
no_license
// You can use underscores in numbers to improve readability! // const MAX_POINTS: u32 = 100_000; fn main() { let mut x = 5; println!("The value of x is: {}", x); x = 6; println!("The value of x is: {}", x); }
true
8b25d9e59c6232f23234c549594c6d722f99310f
Rust
yiwang/goban-screenhack
/src/goban.rs
UTF-8
4,205
3.421875
3
[ "BSD-3-Clause" ]
permissive
use std::collections::{HashMap, HashSet, VecDeque}; pub struct Goban { pub size: (u8, u8), pub stones: HashMap<(u8, u8), StoneColor>, pub move_number: u64, pub black_captures: u64, pub white_captures: u64, } impl Goban { pub fn new(board_size: (u8, u8)) -> Goban { Goban { s...
true
010379ec7e19375d8bd61412ce7e0c06e8743c82
Rust
magurotuna/leetcode-rust
/src/bin/1376.rs
UTF-8
1,778
3.375
3
[]
no_license
struct Solution; impl Solution { pub fn num_of_minutes(n: i32, head_id: i32, manager: Vec<i32>, inform_time: Vec<i32>) -> i32 { let mut subs = vec![vec![]; n as usize]; for i in 0..(n as usize) { if manager[i] != -1 { subs[manager[i] as usize].push(i as i32); ...
true
8bc166a8680ec547ae3bac4b4c80f473721b6d98
Rust
txie/playground
/rust/basic/src/address.rs
UTF-8
1,152
3.625
4
[]
no_license
use std::mem; use std::ptr; pub fn run() { println!("======== address ======"); let var: i8 = 1; println!("address of var: {:p}", &var); // get the memory address of a variable let address: usize = 0x7ffc8f303130; unsafe { let val = *(address as *const usize); println!("value a...
true
ce13357322664a2a1105b7dd99e037b3e448c9c2
Rust
ryanwcyin/rust_practice
/src/7_matrix_elements_sum.rs
UTF-8
896
3.328125
3
[]
no_license
/* Given matrix, a rectangular matrix of integers, where each value represents the cost of the room, your task is to return the total sum of all rooms that are suitable for the CodeBots (ie: add up all the values that don't appear below a 0). */ fn matrix_elements_sum(matrix: Vec<Vec<i32>>) -> i32 { let mut ans...
true
4457089d3ec280128758c833e921846642d63683
Rust
diesel-rs/diesel
/diesel_tests/tests/connection.rs
UTF-8
5,890
2.875
3
[ "Apache-2.0", "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
use crate::schema::*; use diesel::connection::BoxableConnection; use diesel::*; #[test] #[cfg(any(feature = "postgres", feature = "sqlite"))] fn managing_updated_at_for_table() { use crate::schema_dsl::*; use chrono::NaiveDateTime; use std::{thread, time::Duration}; table! { #[sql_name = "auto...
true
d73780809529c9be125979325c889f0d567b5773
Rust
rbatis/rbatis
/rbatis-codegen/src/codegen/func.rs
UTF-8
14,015
2.734375
3
[ "Apache-2.0" ]
permissive
use proc_macro2::{Ident, Span}; use quote::quote; use quote::ToTokens; use syn; use syn::{BinOp, Expr, Lit, Member}; fn token_steam_string(arg: proc_macro2::TokenStream) -> String { arg.to_token_stream().to_string().trim().to_string() } fn convert_to_arg_access(context: &str, arg: Expr, ignore: &[String]) -> Expr...
true
3ad350488705d5bab706441715abde992327ff28
Rust
aeyakovenko/loom-1
/src/wallet.rs
UTF-8
6,991
2.59375
3
[ "Apache-2.0" ]
permissive
//! wallet library use std::slice::from_raw_parts; use std::fs::File; use std::mem::transmute; use std::mem::size_of; use std::io::Read; use std::io::Write; use crypto::ed25519; use rand::Rng; use rand::os::OsRng; use data; use result::Result; use result::Error; use serde_json; use aes; type Keypair = ([u64; 8], [u6...
true
90266f9b37d8a66510a76a91fc1348492a2f5b83
Rust
rike422/rustbook
/ch05/ex05/examples/ch05_11_result.rs
UTF-8
1,320
3.90625
4
[ "BSD-3-Clause", "Apache-2.0", "MIT" ]
permissive
fn main() { // str::parse()は文字列を指定した型(ここではi32型)に変換する assert_eq!("10".parse::<i32>(), Ok(10)); // 変換できたらOK(値)が返される let res0 = "a".parse::<i32>(); // 変換できなかったら`Err(エラーを表す値)`が返される assert!(res0.is_err()); println!("{:?}", res0); // → Err(ParseIntError { kind: InvalidDigit }) // 複数のR...
true
9d41fbd9c96a369350c4572df5c456f1a83f5ac3
Rust
ecafkoob/ockam
/examples/rust/get_started/examples/09-streams-initiator.rs
UTF-8
1,474
2.859375
3
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
/// This example uses the stream service to send messages between two /// clients. A stream is a buffered message sending channel, which /// means that you can run `initiator` and `responder` in any order /// you like. use ockam::{route, stream::Stream, Context, Result, TcpTransport, TCP}; #[ockam::node] async fn mai...
true
f5ca66ff1ad0c7db0205ba1d18ddf1d652d596ef
Rust
tnyjhnsn/rust-roguelike
/client/src/list.rs
UTF-8
1,023
2.671875
3
[ "MIT", "Apache-2.0" ]
permissive
use yew::prelude::*; use super::list_item::*; pub struct List { props: Props, } #[derive(Clone, PartialEq, Properties)] pub struct Props { pub list: Vec<(i32, i32)>, } impl Component for List { type Message = (); type Properties = Props; fn create(props: Self::Properties, _: ComponentLink<Self>)...
true
b857c85085b1ff080adada5ef19b1aad22257e78
Rust
rust-datetime/datetime
/tests/simple_arithmetic.rs
UTF-8
250
2.875
3
[ "MIT" ]
permissive
extern crate datetime; use datetime::{Instant, Duration}; #[test] fn addition() { assert_eq!(Instant::at(10), Instant::at(3) + Duration::of(7)) } #[test] fn subtraction() { assert_eq!(Instant::at(20), Instant::at(50) - Duration::of(30)) }
true
170d2e2df4da6167bb74d517f2c171ea66f74e3d
Rust
andom9/chull
/src/lib.rs
UTF-8
1,115
2.84375
3
[ "MIT", "Apache-2.0" ]
permissive
//! Convex hull approximation based on [Quick hull](http://citeseerx.ist.psu.edu/viewdoc/summary;jsessionid=C57E2269B0D64504B97E8469F6A1315D?doi=10.1.1.117.405). //! Available in 3-D or 2-D for now. //! ## Examples //! ```rust //! use chull::{ConvexHull,ConvexHullWrapper}; //! let p1 = vec![1.0, 1.0, 1.0]; //! let p2 =...
true
c927201255df6b3acdced40c8a0041cc9ba91fec
Rust
neon64/rust_workshop_materials
/rust-examples/src/main.rs
UTF-8
547
2.90625
3
[]
no_license
//! Some examples of various features/concepts in Rust! //! //! Please see each module for examples. // Each of these modules are essentially a bunch of 'tests'. // they are structured this way so that in VS Code you can // hit "run test" and see each example run individually #[cfg(test)] mod fizzbuzz; #[cfg(test)] m...
true
07fb06e09ffbd59d7966aec31a9596b85466874f
Rust
bvssvni/ld31
/src/player.rs
UTF-8
3,230
2.90625
3
[ "MIT" ]
permissive
#![allow(dead_code)] bitflags! { flags KeyState: u8 { const LEFT = 0b1, const RIGHT = 0b10, const UP = 0b100, const DOWN = 0b1000, } } impl KeyState { pub fn acceleration(&self, d: f64) -> [f64; 2] { let mut acc = [0.0; 2]; if self.contains(LEFT) { ...
true
67fdbbce680c2fbb68874cebcdffee7712d53f69
Rust
Lyndon-Mackay/ecology
/src/bin/main.rs
UTF-8
897
2.828125
3
[]
no_license
use ecology::simulate; use clap::{App, Arg, SubCommand}; use std::env; fn main() { let matches = App::new("My Super Program") .version("1.0") .author("lyndon Mackay") .about("SImulated Forest") .arg( Arg::with_name("Size") .help("The size of the forest an...
true
b6c6831b57e5a6d14d52131805ddc414cdebb1af
Rust
einars/explore-table-postgres
/src/main.rs
UTF-8
7,608
2.890625
3
[]
no_license
use postgres::{Connection, TlsMode, Error}; use clap::{Arg, App}; fn printable(c: Option<String>) -> String { let cutoff = 70; match c { None => "null".to_string(), Some(s) => { let t = s.trim().replace("\n", "\\n"); if t.len() > cutoff { let out: String...
true
26a36cab9668227340983558ce1fae56b5417c23
Rust
stadust/dash-rs
/src/serde/thunk.rs
UTF-8
7,817
3.046875
3
[ "MIT" ]
permissive
use base64::{DecodeError, URL_SAFE}; use percent_encoding::{percent_decode_str, utf8_percent_encode, AsciiSet, CONTROLS}; use serde::{ser::Error as _, Deserialize, Serialize, Serializer}; use std::{ borrow::Cow, fmt::{Display, Formatter}, mem, num::ParseIntError, str::Utf8Error, string::FromUtf8...
true
404af3f906c56e7885a14ad12565abebf272c9c6
Rust
nymtech/nym
/examples/cli/commands/verify-signature/src/main.rs
UTF-8
2,963
2.84375
3
[ "CC0-1.0", "Apache-2.0" ]
permissive
use nym_cli_commands::validator::signature::helpers::secp256k1_verify_with_public_key_json; fn main() { println!("\nNym signature verification example\n\n"); // the public key in JSON format (because Cosmos supports secp256k1 and ed25519 - NB: the helper only supports secp256k1) let public_key_as_json = r...
true
1f8126aeed900c737b77b91ba2c84a708527564d
Rust
ultrasaurus/rust-clib
/mylib/src/tcp.rs
UTF-8
1,684
2.96875
3
[ "MIT" ]
permissive
use std::ffi::c_void; use tokio::runtime::Runtime; use tokio::net::TcpStream; // use std::time::Duration; pub struct TcpConnection { runtime: Runtime, conn: Option<TcpStream>, callback: TcpStatusCallback, user_data: * mut c_void, } pub type TcpStatusCallback = extern "C" fn(code: i32, user_data: * mut c_void)...
true
1a546cf3ab1509eae96f11063fd1dd4d9fab276f
Rust
Flux-Audio/fft_freeze
/src/compute.rs
UTF-8
599
2.59375
3
[ "MIT" ]
permissive
use rustfft::num_complex::Complex; use rand_xoshiro::rand_core::RngCore; use rand_xoshiro::rand_core::SeedableRng; use rand_xoshiro::Xoshiro256Plus; /// hann window function /// - x: input /// - i: index /// - l_div: reciprocal of window length pub fn win_hann(x: Complex<f32>, i: usize, l_div: f32) -> Complex<f32> { ...
true
dfab425afaa355443f34b6ee94f82cb8fefde707
Rust
norcalli/ksway
/src/client.rs
UTF-8
5,609
2.765625
3
[]
no_license
use std::io::Read; use std::os::unix::net::UnixStream; use std::path::{Path, PathBuf}; use std::time::Duration; use byteorder::{NativeEndian, ReadBytesExt}; use crossbeam_channel as chan; use num_traits::FromPrimitive; use crate::ipc_command; use crate::{guess_sway_socket_path, Error, IpcCommand, IpcEvent, Result}; ...
true
ce2bf7a271294837d94973d8d7cefd6633e6b0ff
Rust
monoid/junk
/arm64express/src/codegen.rs
UTF-8
1,563
2.71875
3
[]
no_license
use dynasmrt::aarch64::Assembler; use dynasmrt::{DynasmApi, ExecutableBuffer}; pub struct Function { _func: ExecutableBuffer, entry: unsafe extern "C" fn(a: i32, b: i32) -> i32, } impl Function { pub fn new() -> Function { let mut ops = Assembler::new().unwrap(); let start = ops.offset();...
true
8a17fd80a8b3250d4db93d27793c5fd6b30aaf2f
Rust
cuiy0006/Algorithms
/leetcode/14. Longest Common Prefix.rs
UTF-8
619
2.875
3
[]
no_license
impl Solution { pub fn longest_common_prefix(strs: Vec<String>) -> String { let v: Vec<Vec<char>> = strs.into_iter().map(|s| { return s.chars().collect(); }).collect(); let mut res = "".to_string(); for i in (0..v[0].len()) { let mut c = v[0]...
true
925aad57a0e07963dd06b9e3a749afa4f4156f70
Rust
jiangshide/android-system
/security/keystore2/src/operation.rs
UTF-8
39,140
2.90625
3
[ "Apache-2.0" ]
permissive
// Copyright 2020, The Android Open Source Project // // 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...
true
c96658613c0870f064995620153a08d79994bd48
Rust
cesbo/textcode
/build/gb2312.rs
UTF-8
3,850
3.125
3
[]
no_license
//! GB2312 Parser //! //! 1. Build generator: rustc parser.rs //! 2. Launch: ./parser >../../src/charset/data/gb2312.rs use { std::{ fs::File, io::{ self, BufReader, BufRead, }, path::Path, }, super::push_unicode, }; fn read_file<P: As...
true
d2fdbb606ebd1a7c1c8f5f6a241ab7d46a28447d
Rust
Pzixel/CsRustInterop
/rust/src/lib.rs
UTF-8
827
3.0625
3
[ "MIT" ]
permissive
#[repr(C)] pub struct ArrayRef<T> { bytes: *const T, length: usize } #[no_mangle] pub extern fn println(array: *const ArrayRef<u8>, count: usize) -> i32 { let array_slice = unsafe { std::slice::from_raw_parts(array, count) }; for str in array_slice { let slice = unsafe { std::slice::from_raw_pa...
true
7c72f1e44964294f460566a751a596a7f21a4734
Rust
kolemannix/hello_redis
/src/main.rs
UTF-8
565
2.671875
3
[]
no_license
use hello_redis::*; fn main() -> Result<()> { // let mut redis = RedisClient::connect("127.0.0.1:6379"); let mut redis = RedisClient::connect("127.0.0.1:6379")?; println!("Sending PING..."); let pong = redis.ping()?; assert_eq!((), pong); println!("Got PONG!"); println!("Sending SET..."); ...
true
214729b7459bca4e744294c707ee2c3e23e29da9
Rust
quilt/lighthouse
/beacon_node/store/src/impls/beacon_state.rs
UTF-8
2,528
2.84375
3
[ "Apache-2.0" ]
permissive
use crate::*; use ssz::{Decode, DecodeError, Encode}; use ssz_derive::{Decode, Encode}; use std::convert::TryInto; use types::beacon_state::{CommitteeCache, PeriodCommitteeCache, CACHED_EPOCHS, CACHED_PERIODS}; /// A container for storing `BeaconState` components. #[derive(Encode, Decode)] struct StorageContainer { ...
true
3f4e036a6491f8025e59c3f7e85142c179605d57
Rust
Amelia10007/cui_gaming
/src/layer.rs
UTF-8
510
3.0625
3
[]
no_license
/// キャンバスに描画する物体の優先順位を表す. /// キャンバス内の同じ位置に複数の物体を描画した場合,コンソール上に表示されるのはそのうちもっとも描画優先度が高いものだけとなる. /// 描画優先度が等しい複数の物体を同じ位置に描画した場合,表示されるのは最後に描画した物体のみとなる. pub trait Layer: Copy + Ord {} // Auto trait implementation impl<T: Copy + Ord> Layer for T {}
true
4256696e88ee54469240c8147e1f8ed958e102a8
Rust
little-dude/juniper
/src/integrations/iron_handlers.rs
UTF-8
16,846
2.609375
3
[ "BSD-2-Clause" ]
permissive
//! Optional handlers for the Iron framework. Requires the `iron-handlers` feature enabled. use iron::prelude::*; use iron::middleware::Handler; use iron::mime::Mime; use iron::status; use iron::method; use urlencoded::{UrlEncodedQuery, UrlDecodingError}; use std::io::Read; use std::io::Error as IoError; use std::io::...
true
91a844f7ce34f70675df4a6406f038c4517ea8f0
Rust
andywarduk/aoc2020
/day21-2/src/main.rs
UTF-8
4,794
3.203125
3
[]
no_license
use std::fs; use std::io::{self, BufRead}; use std::collections::HashMap; use std::cmp::PartialOrd; struct Ingredient { lang: String, english: Option<String> } #[derive(Default)] struct Allergen { lang: Option<String>, foods: Vec<usize> } type Ingredients = Vec<Ingredient>; type Foods = Vec<Ingredien...
true
71f829edb2e221c407c984306f5c069f35a1d50a
Rust
czyczk/LeetCode
/rust/lc-1319/src/solution.rs
UTF-8
1,734
3.421875
3
[]
no_license
pub struct Solution {} impl Solution { pub fn make_connected(n: i32, connections: Vec<Vec<i32>>) -> i32 { let mut uf = UnionFind::with_capacity(n as usize); let mut remaining = 0; for c in connections.iter() { let is_accepted = uf.union(c[0] as usize, c[1] as usize); ...
true
ad9d2c78208bfdb467cf261bda1f3199e09cf3f9
Rust
averycrespi/yolk
/src/parser/tests.rs
UTF-8
4,180
3
3
[ "Apache-2.0", "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
use num_traits::identities::Zero; use yolol_number::YololNumber; use crate::ast::{YolkExpr, YolkProgram, YolkStmt}; use crate::error::YolkError; use std::str::FromStr; #[test] fn test_import() -> Result<(), YolkError> { let parsed: YolkProgram = "import number".parse()?; let expected: YolkProgram = vec![Yolk...
true
a50c489d488678f1710014abf361721b3abaccff
Rust
ralvescosta/rust_exercism
/armstrong-numbers/src/lib.rs
UTF-8
280
3.15625
3
[]
no_license
pub fn is_armstrong_number(num: u32) -> bool { let to_string = num.to_string(); let amount = to_string.len() as u32; let sum: u32 = to_string .chars() .map(|i| i.to_string().parse::<u32>().unwrap().pow(amount)) .sum(); return sum == num; }
true
ca51f33904cf20b764ad7ce2d6352c0ff38a33ed
Rust
nicklasmoeller/theia
/src/scenery/sphere.rs
UTF-8
1,708
2.921875
3
[]
no_license
use ::materials::{Scatterable}; use ::utils::vec3::Vec3; use ::utils::ray::Ray; use super::hitable::{HitRecord, Hitable}; pub struct Sphere { center: Vec3, radius: f32, material: Box<dyn Scatterable> } impl Sphere { pub fn new<T: Scatterable + 'static>(center: Vec3, radius: f32, material: T) -> Spher...
true
8a893653b999d7d76a1dd0a04229ba800becedec
Rust
tickbh/td_proto_rust
/tests/test.rs
UTF-8
8,583
2.796875
3
[ "Apache-2.0", "MIT" ]
permissive
extern crate td_proto_rust as td_rp; use td_rp::{Value, Config, Buffer}; use std::io::prelude::*; use std::mem; use std::collections::{HashMap}; fn test_head_field(buffer : &mut Buffer, index : u16, t : u16) { // first index bytes let data: &mut [u8; 2] = &mut [0, 0]; let size = buffer.read(data).unwrap()...
true
c6a8d85ddfd201f78194c03e869ff93a607c4eb7
Rust
pierremarc/apply
/apply/src/source/geojson_source.rs
UTF-8
1,787
2.78125
3
[]
no_license
use geojson::{Feature, FeatureCollection, GeoJson}; use parser::ast::Num; use proj::Proj; use std::fs::read_to_string; use std::rc::Rc; use crate::error::{ApplyError, ApplyResult}; use super::{Resolver, SourceT}; #[derive(Clone)] pub struct GeoJSON { pub data: Rc<FeatureCollection>, pub source_srid: i64, ...
true
ba4df7264db1b9836a7ffc666c2e04c80122698a
Rust
justinrlle/spa-server
/src/cache.rs
UTF-8
3,171
3.078125
3
[]
no_license
use std::{ env, fs, io, path::{Path, PathBuf}, }; use anyhow::{Context, Result}; use rouille::url::percent_encoding::{percent_encode, USERINFO_ENCODE_SET}; #[derive(Debug)] pub struct Cache { cache_folder: PathBuf, } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum CacheKind { Archive, Http,...
true
d57fbf9eca5e7c179247f16509eb344301596eb8
Rust
WhoisDavid/advent2020
/src/day7.rs
UTF-8
3,332
3.328125
3
[]
no_license
use aoc_runner_derive::{aoc, aoc_generator}; use std::collections::{HashMap, HashSet}; use recap::Recap; use serde::Deserialize; #[derive(Debug, Recap, Deserialize)] #[recap(regex = r"^(?P<n>\d+) (?P<color>.*) bags?\.?$")] pub struct Bag { color: String, n: usize, } type OuterToInners = HashMap<String, Vec<Ba...
true
be0b773022131120ba693adac607f793667ea578
Rust
andogq/opengl_rust
/src/engine.rs
UTF-8
1,783
2.828125
3
[]
no_license
pub mod traits; mod vertex_array; mod shader; mod camera; mod renderer; pub mod models; use traits::*; pub use vertex_array::{ VertexArray, Layout }; pub use shader::Shader; pub use camera::Camera; use renderer::Renderer; pub struct Engine<'a, T> { global_state: T, objects: Vec<Box<dyn Renderable>>, light...
true
106de8c7740f63846ed4c40a1bf4de2fcb350e1e
Rust
mdowell12/advent-of-code-2020
/solutions_fer/day16/src/main.rs
UTF-8
3,722
3.28125
3
[]
no_license
use std::collections::HashMap; use std::io::{self, BufRead}; use std::ops::RangeInclusive; extern crate regex; use regex::Regex; struct Rule { name: String, first_range: RangeInclusive<usize>, second_range: RangeInclusive<usize>, } impl Rule { pub fn passes(&self, num: &usize) -> bool { self.f...
true
3d321796a5f0c775d2f99e6bcfc759f8af67f290
Rust
luke-biel/CommonDataLayer
/crates/command-service/src/output/victoria_metrics/mod.rs
UTF-8
10,296
2.625
3
[ "Apache-2.0" ]
permissive
use crate::communication::resolution::Resolution; use crate::output::OutputPlugin; use cdl_dto::ingestion::BorrowedInsertMessage; use fnv::FnvHashMap; use metrics_utils::{self as metrics, counter}; use reqwest::Url; use reqwest::{Client, StatusCode}; use serde::{Deserialize, Serialize}; use serde_json::value::RawValue;...
true