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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
bb6ca81c055f30b04fbec89a70733a31936a634f | Rust | RicoGit/rust-alg | /src/leetcode/last_stone_weight.rs | UTF-8 | 459 | 3.125 | 3 | [] | no_license | //! 1046. Last Stone Weight
impl Solution {
pub fn last_stone_weight(stones: Vec<i32>) -> i32 {
use std::collections::BinaryHeap;
let mut heap = stones.into_iter().collect::<BinaryHeap<_>>();
while heap.len() > 1 {
let diff = heap.pop().unwrap() - heap.pop().unwrap();
... | true |
6b7212f4e0fa8e206eec95229dbcfe5ea1a83da3 | Rust | kirhgoff/rust-db-pump | /src/lib.rs | UTF-8 | 2,608 | 3.03125 | 3 | [] | no_license | extern crate postgres;
use std::env;
use postgres::{Connection, TlsMode};
pub const SOURCE_DATABASE_URL: &str = "SOURCE_DATABASE_URL";
pub const TARGET_DATABASE_URL: &str = "TARGET_DATABASE_URL";
pub fn create_connection(env_connection_name: &str) -> Connection {
let database_url = env::var(env_connection_name)
... | true |
f7469025bcbd5b27d0a3f2d3d847a14686796fb0 | Rust | boa-dev/boa | /boa_engine/src/builtins/string/mod.rs | UTF-8 | 113,323 | 2.859375 | 3 | [
"MIT",
"Unlicense"
] | permissive | //! Boa's implementation of ECMAScript's global `String` object.
//!
//! The `String` global object is a constructor for strings or a sequence of characters.
//!
//! More information:
//! - [ECMAScript reference][spec]
//! - [MDN documentation][mdn]
//!
//! [spec]: https://tc39.es/ecma262/#sec-string-object
//! [mdn]... | true |
5a9f2c3f48d3c61bf164632d8fcf03c2b2e0ef9c | Rust | aizigao/keepTraining | /rust_learn/enumerate/src/main.rs | UTF-8 | 707 | 3.671875 | 4 | [] | no_license | #![allow(unused_variables)]
fn main() {
#[derive(Debug)]
enum UsState {
Alabama,
Alaska,
}
enum Coin {
Penny,
Nickel,
Dime,
Quarter(UsState),
}
fn value_in_cents(coin: Coin) -> u32 {
match coin {
Coin::Penny=>{
... | true |
f23493de5acaef8493e17ab135e251cc9bacced4 | Rust | paritytech/parity-common | /kvdb-rocksdb/src/iter.rs | UTF-8 | 3,378 | 2.703125 | 3 | [
"MIT",
"Apache-2.0"
] | permissive | // Copyright 2020 Parity Technologies
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except accor... | true |
5fd74141a1a9b8af56f2fd2444a14e19da13c8c8 | Rust | BookOwl/rhesus | /src/main.rs | UTF-8 | 1,472 | 2.78125 | 3 | [] | no_license | use std::io;
use std::io::prelude::*;
use rhesus;
use rhesus::eval::EvalError;
fn main() -> io::Result<()> {
let mut stdout = io::stdout();
let stdin = io::stdin();
let mut buf = String::with_capacity(256);
let mut out = String::with_capacity(256);
let mut interp = rhesus::eval::Interpreter::new(... | true |
e4ef64e576a8072d9f7a3fd459ecdd04691f8cd4 | Rust | sugyan/leetcode | /problems/0048-rotate-image/lib.rs | UTF-8 | 1,093 | 3.65625 | 4 | [] | no_license | pub struct Solution {}
impl Solution {
pub fn rotate(matrix: &mut Vec<Vec<i32>>) {
matrix.reverse();
for i in 0..matrix.len() {
let (a, b) = matrix.split_at_mut(i);
for (j, c) in (0..).zip(a.iter_mut()) {
std::mem::swap(&mut c[i], &mut b[0][j]);
}... | true |
1e338d6e3c37b00de94a5fb604392f3d0202487d | Rust | PeterDing/aget-rs | /src/app/receive/m3u8_receiver.rs | UTF-8 | 3,376 | 2.609375 | 3 | [
"MIT",
"Apache-2.0"
] | permissive | use std::{io::SeekFrom, path::Path, time::Duration};
use futures::{channel::mpsc::Receiver, pin_mut, select, StreamExt};
use crate::{
app::{
record::{bytearray_recorder::ByteArrayRecorder, common::RECORDER_FILE_SUFFIX},
show::m3u8_show::M3u8Shower,
status::rate_status::RateStatus,
},
... | true |
ac630430a1d65a45de502499351c542cca454f1a | Rust | davidsullins/AdventOfCodeRust | /src/bin/advent16.rs | UTF-8 | 2,789 | 3.234375 | 3 | [
"MIT"
] | permissive | // advent16.rs
// find Aunt Sue
extern crate pcre;
use std::io;
fn main() {
loop {
let mut input = String::new();
let result = io::stdin().read_line(&mut input);
match result {
Ok(byte_count) => if byte_count == 0 { break; },
Err(_) => {
println!("e... | true |
9e912a6668dd4df7b9d6590d37b09136e0e8f70f | Rust | gaotianyu1350/rCore_audio | /crate/thread/src/thread_pool.rs | UTF-8 | 7,220 | 3.09375 | 3 | [
"MIT",
"Apache-2.0"
] | permissive | use crate::scheduler::Scheduler;
use crate::timer::Timer;
use alloc::boxed::Box;
use alloc::vec::Vec;
use log::*;
use spin::{Mutex, MutexGuard};
struct Thread {
status: Status,
status_after_stop: Status,
waiter: Option<Tid>,
context: Option<Box<Context>>,
}
pub type Tid = usize;
type ExitCode = usize;... | true |
91de710719f8aaf3f3db7f051046516b9d65eb10 | Rust | Ongy/dhcp-rs | /src/frame/udp.rs | UTF-8 | 1,751 | 2.578125 | 3 | [] | no_license | extern crate byteorder;
extern crate pnet;
use self::byteorder::{WriteBytesExt, NetworkEndian, ByteOrder};
//TODO: use self::pnet::util::checksum;
use std::marker::PhantomData;
use std::vec::Vec;
use serialize::{Serializeable, HasCode};
#[derive(Debug)]
pub struct UDP<P, S> {
pub remote: u16,
pub payload: P,
... | true |
45407414b278b4140ff53945e2455b2a6c978d69 | Rust | liyuntao/adventofcode2018 | /examples/day05_2.rs | UTF-8 | 1,438 | 3.46875 | 3 | [] | no_license | use std::collections::VecDeque;
use std::fs::File;
use std::io::Read;
fn react(input: &str) -> usize {
let mut stack: VecDeque<char> = VecDeque::with_capacity(input.len());
input.chars().for_each(|c| match stack.back() {
Some(&last_c) => {
if (last_c.clone().to_ascii_lowercase() == c.clone(... | true |
5db7de5c062dc66f24bcaee3b7fdf9fad19b647b | Rust | benzyx/Elric | /src/orderbook.rs | UTF-8 | 10,206 | 2.90625 | 3 | [] | no_license | use crate::event::*;
use crate::types::*;
use chrono::Local;
use std::collections::hash_map::HashMap;
use std::collections::BTreeMap;
// Really, a resting order on the book.
#[allow(dead_code)]
#[derive(Clone, PartialEq)]
pub struct Order {
pub side: Side,
pub price: Price,
pub qty: Qty,
pub order_id: ... | true |
da7e37c5e24af115848e113cc0abd4197dd9e93f | Rust | stefanfrei/sa117 | /src/geom/bodies/cube.rs | UTF-8 | 279 | 3.359375 | 3 | [
"MIT"
] | permissive | struct Cube {
a: f64,
b: f64,
c: f64
}
impl Cube {
fn vol(&self) -> f64 {
self.a * self.b * self.c
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_vol() {
assert_eq!(Cube{a: 1.0, b: 1.0, c: 1.0}.vol(), 1.0);
}
}
| true |
12bc65b6b3aa2ff859413322836024ee41387f08 | Rust | shepmaster/pattern-3 | /src/strings/char.rs | UTF-8 | 4,723 | 3.015625 | 3 | [] | no_license | use pattern::*;
use haystack::Span;
use memchr::{memchr, memrchr};
use std::ops::Range;
#[derive(Debug, Clone)]
pub struct CharSearcher {
// safety invariant: `utf8_size` must be less than 5
utf8_size: usize,
/// A utf8 encoded copy of the `needle`
utf8_encoded: [u8; 4],
}
#[derive(Debug, Clone)]
pub... | true |
26bde11d9de657a5fc5c4351af916e99b5bd04a3 | Rust | Axect/PL2020 | /03_math/game/src/engine/util.rs | UTF-8 | 97 | 2.625 | 3 | [] | no_license | pub fn damage_calc(dam: usize, def: usize) -> usize {
if dam > def { dam - def } else { 0 }
} | true |
b783cea0774165e914a103e0e204752fef10827b | Rust | rosenjcb/term-browse | /src/selection.rs | UTF-8 | 1,042 | 2.734375 | 3 | [] | no_license | use crossterm::{Terminal, terminal, TerminalCursor, cursor, Color};
use crate::screen::Screen;
use crate::coord::Coord;
pub struct Selection {
cursor: TerminalCursor,
content: String,
clipboard: String,
}
impl Selection {
pub fn new() -> Self {
let cursor = cursor();
let (content, clip... | true |
1b21539fe3d125f04c960cc80ba648e0adb35719 | Rust | fossabot/stronghold.rs | /engine/vault/src/vault/chain.rs | UTF-8 | 3,158 | 2.6875 | 3 | [
"Apache-2.0"
] | permissive | // Copyright 2020-2021 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0
use crate::types::{
transactions::{Transaction, TransactionType},
utils::{TransactionId, Val},
};
pub struct Chain {
garbage: Vec<TransactionId>,
subchain: Vec<TransactionId>,
init: Option<TransactionId>,
data: Option<... | true |
2b5487d22cfde8f4c0b8b09a36e98243244c7626 | Rust | ProgrammerAndHacker/fantoccini | /src/lib.rs | UTF-8 | 50,450 | 3.484375 | 3 | [
"Apache-2.0",
"MIT"
] | permissive | //! A high-level API for programmatically interacting with web pages through WebDriver.
//!
//! This crate uses the [WebDriver protocol] to drive a conforming (potentially headless) browser
//! through relatively high-level operations such as "click this element", "submit this form", etc.
//!
//! Most interactions are ... | true |
3adbd308813ce3d43a72e3b5e77702de4f762798 | Rust | FujiiNoritsugu/try_rust | /src/bin/main.rs | UTF-8 | 1,057 | 2.625 | 3 | [] | no_license | use try_rust::binary_tree::*;
fn main() {
let mut first = insert(Box::new(None),7);
first = insert(first, 2);
first = insert(first, 1);
first = insert(first, 5);
first = insert(first, 4);
first = insert(first, 15);
first = insert(first, 10);
first = insert(first, 8);
//first = inser... | true |
0123faceb541ba0fb64eb0c60dda6f52ce26af2e | Rust | heartleth/east | /src/assemble.rs | UTF-8 | 2,065 | 2.71875 | 3 | [] | no_license | use std::collections::HashMap;
use super::parser::SyntaxTree;
use handlebars::Handlebars;
pub fn assemble(ast :&SyntaxTree, lang :&json::JsonValue, renderer :&mut Handlebars, rule_type :&str, lf_reg :&mut HashMap<String, bool>)->std::result::Result<String, &'static str> {
let type_id_raw = format!("{}-{}", &ast.ru... | true |
fb0e2884fe01f864959f7c2e5ee97435190c49ad | Rust | okready/scratchpad | /src/traits.rs | UTF-8 | 41,192 | 3.078125 | 3 | [
"Apache-2.0",
"MIT"
] | permissive | // Copyright 2018 Theodore Cipicchio
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except accord... | true |
5c325d0681cea6a930698e3bfefaaab6426adce3 | Rust | redox-os/rs-nes | /src/cpu/debugger/mod.rs | UTF-8 | 7,398 | 2.703125 | 3 | [
"MIT"
] | permissive | mod debugger_command;
mod http_handlers;
mod breakpoint_map;
mod cpu_snapshot;
use byte_utils::from_lo_hi;
use chan::{self, Receiver, Sender};
use cpu::{Cpu, Interrupt};
use cpu::debugger::breakpoint_map::BreakpointMap;
use cpu::debugger::cpu_snapshot::{CpuSnapshot, MemorySnapshot};
use cpu::debugger::debugger_command... | true |
ee007faf4a6036a6540d17a365f48c8675919cea | Rust | agemor/sage | /src/tensor/init.rs | UTF-8 | 1,229 | 2.734375 | 3 | [
"Apache-2.0"
] | permissive | use rand_distr::{Normal, Uniform};
use crate::tensor::shape::ToShape;
use crate::tensor::Tensor;
pub fn kaiming_uniform<S>(shape: S, gain: f32) -> Tensor
where
S: ToShape,
{
let shape = shape.to_shape(0);
let (fan_in, _) = fan_in_and_out(&shape);
let std = gain * (1.0 / fan_in as f32).sqrt();
let... | true |
7f8050af7ff1460ed5a1ae67bd73e1b541a19c14 | Rust | mitrid-labs/bezier | /src/io/network/transport/client.rs | UTF-8 | 1,979 | 2.578125 | 3 | [
"Apache-2.0"
] | permissive | use mitrid_core::base::Result;
use mitrid_core::base::Checkable;
use mitrid_core::io::network::ClientTransport as BasicClientTransport;
use std::net::{TcpStream, Shutdown};
use std::io::{Write, Read};
use std::mem;
pub const BUFFER_SIZE: usize = 2048;
use io::network::Address;
pub struct ClientTransport(pub TcpStre... | true |
edb98fa9c86e3b3ad46adcf4358f54db248a2ee0 | Rust | jvff/ioc-test | /src/async_server/active_server.rs | UTF-8 | 4,811 | 2.671875 | 3 | [] | no_license | use std::fmt::Display;
use std::hash::Hash;
use std::mem;
use futures::{Async, AsyncSink, Future, Poll, Sink, StartSend, Stream};
use futures::stream::FuturesUnordered;
use super::errors::Error;
use super::finite_service::FiniteService;
use super::status::Status;
pub struct ActiveServer<T, S>
where
T: Stream + S... | true |
fdc8b3facae7642e28a52cd946b03a7e9c62eacb | Rust | benkay86/nom-tutorial | /src/lib.rs | UTF-8 | 15,075 | 3.40625 | 3 | [] | no_license | //! Example crate demonstrating how to use nom to parse `/proc/mounts`. Browse crates.io for sys-mount, proc-mounts, and libmount for more stable, usable crates.
// Needed to use traits associated with std::io::BufReader.
use std::io::BufRead;
use std::io::Read;
/// Type-erased errors.
pub type BoxError = std::boxed... | true |
8bb4ceb2372b79efb70948a8b33f51b0697e6dbe | Rust | Liby99/saemanga-rust | /src/app/session.rs | UTF-8 | 5,148 | 2.875 | 3 | [] | no_license | use chrono::Utc;
use mongodb::oid::ObjectId;
use mongodb::{bson, doc};
use rocket::http::{Cookie, Cookies};
use time::{self, Duration};
use super::user::User;
use crate::util::Collection;
use crate::util::Database;
use crate::util::Error;
#[collection("session")]
#[derive(Serialize, Deserialize)]
pub struct Session {... | true |
2f3a572d3a4f64a348701df2b1348b2c15d7faf4 | Rust | adamtrilling/trilogy-leaderboard | /src/lib.rs | UTF-8 | 1,638 | 2.625 | 3 | [] | no_license | #[macro_use]
extern crate seed;
pub mod model;
use futures::Future;
use futures::future::join_all;
use seed::prelude::*;
use seed::{fetch, Request};
use model::Leaderboard;
// Model
struct Model {
leaderboards: Vec<Leaderboard>
}
impl Default for Model {
fn default() -> Self {
Self {
... | true |
1ef0788d8e9faaa40e306046b621b43b0d2095a2 | Rust | dimforge/nalgebra | /tests/core/matrix.rs | UTF-8 | 37,989 | 2.734375 | 3 | [
"Apache-2.0"
] | permissive | use num::{One, Zero};
use std::cmp::Ordering;
use na::dimension::{U15, U8};
use na::{
self, Const, DMatrix, DVector, Matrix2, Matrix2x3, Matrix2x4, Matrix3, Matrix3x2, Matrix3x4,
Matrix4, Matrix4x3, Matrix4x5, Matrix5, Matrix6, OMatrix, RowVector3, RowVector4, RowVector5,
Vector1, Vector2, Vector3, Vector4... | true |
f3c92fa67d698d7dccbd85d81ed2763ada8f5d41 | Rust | lucasig11/jlox | /src/lib/interpreter/class.rs | UTF-8 | 3,689 | 2.9375 | 3 | [] | no_license | use crate::lib::{
error::{InnerError, LoxError, LoxResult},
interpreter::{values::LoxCallable, Environment, LoxValue},
parser::Expr,
token::Token,
};
use std::{
cell::RefCell,
collections::HashMap,
fmt::{Display, Formatter},
rc::Rc,
};
use super::LoxFunction;
#[derive(Clone, Debug)]
pu... | true |
aad9b93fc9b5c541bfc44560ea6838a43cf3692e | Rust | iolivia/fizzbuzz | /fizzbuzz.rs | UTF-8 | 243 | 2.953125 | 3 | [
"MIT"
] | permissive | fn main() {
for x in 1..=100 {
match (x % 3, x % 5) {
(0, 0) => println!("FizzBuzz"),
(0, _) => println!("Fizz"),
(_, 0) => println!("Buzz"),
_ => println!("{}", x),
}
}
} | true |
146d9568693000ca12879d531958b8d6d88c747f | Rust | emirayka/nia_interpreter_core | /src/interpreter/library/root/set_root_variable.rs | UTF-8 | 2,175 | 3.375 | 3 | [
"MIT"
] | permissive | use crate::interpreter::error::Error;
use crate::interpreter::interpreter::Interpreter;
use crate::interpreter::value::Value;
pub fn set_root_variable(
interpreter: &mut Interpreter,
name: &str,
value: Value,
) -> Result<(), Error> {
let root_environment = interpreter.get_root_environment_id();
let... | true |
b4b2e27c5b4fd887345770d3663b11e1f3fd2b65 | Rust | maxmcd/tinykaboom | /src/main.rs | UTF-8 | 4,696 | 2.90625 | 3 | [] | no_license | use rayon::prelude::*;
use std::cmp::max;
use std::cmp::min;
use std::f32::consts::PI;
use std::fs::File;
use std::io::BufWriter;
use std::io::Write;
use std::ops::{Add, Mul, Sub};
use std::time::SystemTime;
const SPHERE_RADIUS: f32 = 1.2;
const NOISE_AMPLITUDE: f32 = 0.2;
const WIDTH: usize = 640;
const HEIGHT: usize... | true |
4c59e04489e42b4c36aae77019fac654bef36696 | Rust | EVaillant/entity-system-rs | /src/system_manager.rs | UTF-8 | 5,051 | 3.34375 | 3 | [
"BSL-1.0"
] | permissive | use crate::event_dispatcher::EventDispatcher;
use std::cell::RefCell;
use std::cmp::{max, Ord, Ordering};
use std::collections::HashMap;
use std::rc::Rc;
use std::time::Instant;
///
/// Definie the system execution period.
#[derive(Clone, Copy, Eq, PartialEq)]
pub enum RefreshPeriod {
///
/// Each time.
Ev... | true |
9fb72591a9a01fab1280285d48804d59a765e9cf | Rust | rust-lang/rust | /tests/ui/lint/lint-unconditional-drop-recursion.rs | UTF-8 | 989 | 2.546875 | 3 | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"BSD-2-Clause",
"LicenseRef-scancode-unicode",
"MIT",
"LicenseRef-scancode-other-permissive"
] | permissive | // Because drop recursion can only be detected after drop elaboration which
// happens for codegen:
// build-fail
#![deny(unconditional_recursion)]
#![allow(dead_code)]
pub struct RecursiveDrop;
impl Drop for RecursiveDrop {
fn drop(&mut self) { //~ ERROR function cannot return without recursing
let _ = ... | true |
70d70bec93a54209d446b4d2fabfa7de3633d69d | Rust | droundy/lists | /src/sheets.rs | UTF-8 | 14,261 | 2.609375 | 3 | [] | no_license | use crate::atomicfile;
use display_as::{display, with_template, DisplayAs, HTML, UTF8};
use futures::{FutureExt, StreamExt};
use serde::{Deserialize, Serialize};
use tokio::sync::{mpsc, RwLock};
use warp::reply::Reply;
use warp::{path, Filter};
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
struct Char... | true |
b6e294df1b2c081da29e9c9b0ed9c861f07df9a1 | Rust | makepad/makepad | /draw/vector/src/internal_iter/into_internal_iterator.rs | UTF-8 | 710 | 3.390625 | 3 | [
"MIT"
] | permissive | use crate::internal_iter::InternalIterator;
/// A trait for conversion into an internal iterator.
///
/// This trait is commonly implemented for collections. It is useful when you want to write a
/// function that can take either a collection or an internal iterator as input.
pub trait IntoInternalIterator {
type ... | true |
5355780c07ced3e69d25c5ecdc0b4a58e3e3985c | Rust | sharkAndshark/geoengine | /datatypes/src/util/helpers.rs | UTF-8 | 1,657 | 3.421875 | 3 | [] | no_license | /// This macro allows specifying a JSON Map inplace for convenience.
///
/// The code is taken and modified from maplit (https://github.com/bluss/maplit/blob/master/src/lib.rs).
///
/// # Examples
///
/// ```
/// use serde_json::{Map, Value};
/// use geoengine_datatypes::json_map;
///
/// let mut map: Map<String, Value... | true |
39f003fdc592bfa0bde0affaefe9e0b0c41711b5 | Rust | quilt/lighthouse | /shard_node/shard_store/src/memory_store.rs | UTF-8 | 1,910 | 3.25 | 3 | [
"Apache-2.0"
] | permissive | use super::{Error, Store};
use parking_lot::RwLock;
use std::collections::HashMap;
use std::sync::Arc;
type DBHashMap = HashMap<Vec<u8>, Vec<u8>>;
/// A thread-safe `HashMap` wrapper.
#[derive(Clone)]
pub struct MemoryStore {
// Note: this `Arc` is only included because of an artificial constraint by gRPC. Hopefu... | true |
5c5a758d72045060862803f41d8f09bfdacb478b | Rust | SpaceEraser/chess | /src/square.rs | UTF-8 | 14,562 | 3.828125 | 4 | [
"MIT"
] | permissive | use crate::color::Color;
use crate::file::File;
use crate::rank::Rank;
use std::fmt;
/// Represent a square on the chess board
#[derive(PartialEq, Ord, Eq, PartialOrd, Copy, Clone, Debug, Hash)]
pub struct Square(u8);
/// How many squares are there?
pub const NUM_SQUARES: usize = 64;
impl Default for Square {
//... | true |
92beef211bf432c1f7b09fccdaaca4bf8f302206 | Rust | remexre/neuroflap | /neat/src/network.rs | UTF-8 | 2,553 | 3.328125 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | use std::cmp::max;
use activation::Activation;
use genome::Genome;
/// The representation of a neural network.
#[derive(Debug)]
pub struct Network {
activation: Activation,
neurons: Vec<Neuron>,
}
impl Genome {
/// Builds a network from the genome, using the given activation function.
pub fn build_ne... | true |
4643886358d2aa9088920d2594fa7715bfe208c2 | Rust | starblue/advent_of_code | /a2015/src/bin/a201512.rs | UTF-8 | 1,157 | 3.15625 | 3 | [] | no_license | use std::io;
use std::io::Read;
use json::JsonValue;
fn number_sum1(json: &JsonValue) -> f64 {
if json.is_number() {
json.as_f64().unwrap()
} else if json.is_object() {
json.entries().map(|(_, v)| number_sum1(v)).sum()
} else if json.is_array() {
json.members().map(number_sum1).sum... | true |
680dd8c5d4ab61e86ddf6f7e2c9432046e3e5a66 | Rust | sigoden/iredismodule | /src/context/cluster.rs | UTF-8 | 5,593 | 2.671875 | 3 | [
"MIT"
] | permissive | use super::Context;
use crate::cluster::{ClusterNodeInfo, MsgType};
use crate::error::Error;
use crate::handle_status;
use crate::raw;
use std::ffi::CString;
use std::os::raw::{c_char, c_int, c_uchar};
impl Context {
/// Return an list cluster node id.
///
/// However if this function is called by a module... | true |
24925d64c90449d32d337b9fa50d51ba79818626 | Rust | eigenein/my-iot-rs | /src/core/value/from.rs | UTF-8 | 514 | 3.390625 | 3 | [
"MIT"
] | permissive | //! Convenience functions to construct a `Value`.
use crate::prelude::*;
impl From<bool> for Value {
fn from(value: bool) -> Self {
Self::Boolean(value)
}
}
impl Value {
/// Builds a `Value` instance from [kilowatt-hours](https://en.wikipedia.org/wiki/Kilowatt-hour).
#[inline(always)]
pub... | true |
92a0faa37568deb632085c4e8a506aedda6a1aba | Rust | filecoin-project/rust-fil-proofs | /storage-proofs-core/src/multi_proof.rs | UTF-8 | 2,151 | 2.578125 | 3 | [
"Apache-2.0",
"MIT"
] | permissive | use std::io::{Read, Write};
use anyhow::{ensure, Context};
use bellperson::groth16::{self, PreparedVerifyingKey};
use blstrs::Bls12;
use crate::error::Result;
pub struct MultiProof<'a> {
pub circuit_proofs: Vec<groth16::Proof<Bls12>>,
pub verifying_key: &'a PreparedVerifyingKey<Bls12>,
}
const GROTH_PROOF_S... | true |
eb72ad39ff42b5137d37ac49798c7c4d5f351f44 | Rust | m00p1ng/kattis-problem | /LV1/1.4/cetvrta/cetvrta.rs | UTF-8 | 800 | 3.46875 | 3 | [] | no_license | use std::io::{self, BufRead};
fn get_number(s: String) -> Vec<i32> {
return s.split_whitespace().map(|n| n.parse().unwrap()).collect();
}
fn main() {
let stdin = io::stdin();
let mut buff = stdin.lock().lines().map(|l| l.unwrap());
let num1: Vec<i32> = get_number(buff.next().unwrap());
let num2: ... | true |
b9492f43555c8fac884d0d3e1bacadb3f1c27563 | Rust | dmah42/mrdo | /src/compiler/program_parser.rs | UTF-8 | 2,564 | 3.125 | 3 | [] | no_license | use nom::combinator::map_res;
use nom::multi::many1;
use nom::IResult;
use crate::compiler::expression_parsers::expression;
use crate::compiler::tokens::Token;
pub fn program(i: &str) -> IResult<&str, Token> {
map_res(
many1(expression),
|expressions| -> Result<Token, nom::error::Error<&str>> {
... | true |
5e668a6d57ea3a5ab31c8649a82b0974f658ec82 | Rust | wzekin/json_parse | /src/parse.rs | UTF-8 | 8,835 | 3.09375 | 3 | [] | no_license | //
// parse.rs
// Copyright (C) 2019 zekin <zekin@DESKTOP-78TBROT>
// Distributed under terms of the MIT license.
//
use super::err::JsonParseError;
use super::token::{TokenType, Tokenizer};
use std::collections::{HashMap, VecDeque};
use std::mem::replace;
#[derive(Debug)]
pub enum Value {
NULL,
BOOLEAN(bool)... | true |
bd243be07a29f8a027ddb7c41c842998fb8c5ee2 | Rust | futurepaul/hash-cop | /src/manifest_parser.rs | UTF-8 | 1,438 | 2.6875 | 3 | [
"MIT"
] | permissive | use std::collections::HashMap;
use anyhow::Result;
pub fn parse_manifest(manifest: String, is_asc: bool) -> Result<HashMap<String, String>> {
let mut filename_hash_pairs = HashMap::<String, String>::new();
let lines = manifest.lines();
for line in lines {
match line {
"" => {
... | true |
a08ea71e69c1e13cca2f7d51247d211a1a78f612 | Rust | dixe/Game-in-rust | /executable/src/text_render/free_type_wrapper.rs | UTF-8 | 414 | 2.703125 | 3 | [] | no_license | use freetype::Library;
pub struct FreeTypeWrapper {
pub lib: freetype::Library,
pub face: freetype::face::Face
}
pub fn load_free_type() -> FreeTypeWrapper {
let lib = Library::init().unwrap();
let path = "C:/Windows/Fonts/arial.ttf";
let face = lib.new_face(path, 0).unwrap();
face.set_c... | true |
469237389c9ef21e25a341da8163d6f767ec217d | Rust | mesalock-linux/crates-io | /vendor/rocket/tests/uri-percent-encoding-issue-808.rs | UTF-8 | 1,708 | 3.03125 | 3 | [
"Apache-2.0",
"Unlicense",
"BSD-3-Clause",
"0BSD",
"MIT"
] | permissive | #![feature(proc_macro_hygiene)]
#[macro_use] extern crate rocket;
use rocket::response::Redirect;
use rocket::http::uri::Uri;
const NAME: &str = "John[]|\\%@^";
#[get("/hello/<name>")]
fn hello(name: String) -> String {
format!("Hello, {}!", name)
}
#[get("/raw")]
fn raw_redirect() -> Redirect {
Redirect::... | true |
315e5af0589206b6f5643436e9e48a47bcd83f9c | Rust | singaraiona/Streams | /src/iter/stream.rs | UTF-8 | 435 | 3.078125 | 3 | [] | no_license | // Streams inspired by Iterators.
#[derive(Debug)]
pub enum Async<T> {
Ready(T),
NotReady,
}
impl<T> Async<T> {
#[inline]
pub fn unwrap(self) -> T {
match self {
Async::Ready(val) => val,
Async::NotReady => panic!("called `Async::unwrap()` on a `NotReady` value"),
... | true |
733083f8a6368927bb74addfb41178ce5a050474 | Rust | frankegoesdown/LeetCode-in-Go | /Algorithms/0514.freedom-trail/freedom-trail.go | UTF-8 | 1,610 | 3.1875 | 3 | [
"MIT"
] | permissive | package problem0514
func findRotateSteps(ring string, key string) int {
// m 中记录了每个字符所有出现过的位置
m := make(map[rune][]int, 26)
for i, r := range ring {
m[r] = append(m[r], i)
}
// ss 记录了到达同一个字符的各个位置的最佳状态
// 0123456789
// 例如, ring = "acbcccccbd",
// key = "ab" 时,0 → 2 是最优解
// key = "abd" 时,0 → ... | true |
cbfeb242f5ef6e5e53e4b49e312162b79e213654 | Rust | wycats/language-reporting | /crates/render-tree/src/debug.rs | UTF-8 | 4,151 | 3.015625 | 3 | [] | no_license | use crate::stylesheet::WriteStyle;
use crate::Document;
use crate::{Node, PadItem};
use crate::{Style, Stylesheet};
use std::{fmt, io};
use termcolor::WriteColor;
struct DebugDocument<'a, C: WriteColor + 'a> {
document: &'a Document,
writer: &'a mut C,
stylesheet: &'a Stylesheet,
line_start: bool,
... | true |
59bc77229938fddcf94a7e09397fc57b8e31c504 | Rust | tk-nguyen/packets | /src/main.rs | UTF-8 | 447 | 2.765625 | 3 | [] | no_license | use clap::Clap;
mod ping;
use ping::*;
#[derive(Clap, Debug)]
#[clap(
name = "packets",
version = "0.1.0",
author = "Thai Nguyen",
about = "A program to interact with packets on the wire"
)]
struct PacketOpt {
/// The destination IP address
#[clap(long, short, value_name = "IP ADDRESS")]
p... | true |
6d755b67f0c2931b07e0fa4404c33037e2cac285 | Rust | benbrunton/brush | /src/main.rs | UTF-8 | 4,250 | 2.796875 | 3 | [] | no_license | use termion;
use termion::input::TermRead;
use termion::raw::IntoRawMode;
use termion::cursor::DetectCursorPos;
use std::{io, thread, time};
use std::io::{stdin, stdout, Write};
use std::process::{Command, Stdio};
use std::path::Path;
use std::env;
const CD_DEFAULT: &str = "~";
fn main() {
println!("Brush - the \... | true |
92e7d2bf89115933d3b2c642b162ebdbc5e30bd1 | Rust | ein-lang/ein | /lib/app/src/common/file_path.rs | UTF-8 | 3,950 | 3.703125 | 4 | [
"Apache-2.0"
] | permissive | use std::{fmt::Display, ops::Deref, str::FromStr};
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct FilePath {
components: Vec<String>,
}
impl FilePath {
pub fn new<I: IntoIterator<Item = impl AsRef<str>>>(components: I) -> Self {
Self {
components: components
... | true |
b64ee900103384244f7784a005704cfe671116d6 | Rust | wbprice/the-marriage-of-ferris | /models/src/dietary_restrictions.rs | UTF-8 | 194 | 2.515625 | 3 | [
"MIT"
] | permissive | use serde_derive::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize)]
pub enum DietaryRestrictions {
Vegetarian,
Vegan,
Pescatarian,
GlutenFree,
DairyFree,
}
| true |
c0d0376c8a43c86c443f8f5843a9ad7e70973a3b | Rust | akitsu-sanae/ysd | /src/layout.rs | UTF-8 | 2,620 | 3.09375 | 3 | [
"BSL-1.0"
] | permissive | use buffer::BufferId;
use cursor::Cursor;
use frame::Frame;
use util::{clamp, Direction};
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
pub struct PanelName(pub String);
impl PanelName {
pub fn new(name: &str) -> Self {
PanelName(name.to_string())
}
}
use std::fmt;
impl fmt::Display for PanelName {
... | true |
c2b8ea96e0da3d58ac64d94cd24e93b03bf5bbb0 | Rust | jsmnbom/prompts-rs | /examples/series_of_prompts.rs | UTF-8 | 1,334 | 3.640625 | 4 | [
"MIT",
"Apache-2.0"
] | permissive | use prompt::{select::SelectPrompt, text::TextPrompt, Prompt};
#[tokio::main]
async fn main() {
// Prompt for first name and store it in var
let mut first_name_prompt = TextPrompt::new("What is your first name?");
let first_name = match first_name_prompt.run().await {
Ok(Some(first_name)) => first_n... | true |
5015a3530800269a2ffb91ce50052a816b3b390b | Rust | maidsafe/crdt_tree | /src/state.rs | UTF-8 | 9,076 | 2.640625 | 3 | [
"BSD-3-Clause"
] | permissive | // Copyright (c) 2022, MaidSafe.
// All rights reserved.
//
// This SAFE Network Software is licensed under the BSD-3-Clause license.
// Please see the LICENSE file for more details.
use serde::{Deserialize, Serialize};
use std::cmp::{Eq, Ordering, PartialEq};
use super::{Clock, LogOpMove, OpMove, Tree, TreeId, TreeM... | true |
2005e90057930d5e61e93363cd80d6ca261ab164 | Rust | ahenshaw/colo | /src/show_color.rs | UTF-8 | 2,164 | 3.0625 | 3 | [
"MIT"
] | permissive | use anyhow::Result;
use color_space::ToRgb;
use crossterm::style::{self, Print, ResetColor, SetForegroundColor};
use crossterm::{queue, tty::IsTty};
use std::io::{stdout, Write};
use crate::color::{hex, html, json, space, Color, ColorSpace};
pub fn show(color: Color, out: ColorSpace) -> Result<()> {
let rgb = col... | true |
f5efec2bc8af04bc55d52bc0685d648a513f8fde | Rust | mwallenfang/dicey | /src/main.rs | UTF-8 | 190 | 2.78125 | 3 | [] | no_license | use dicey::Dice;
fn main() {
println!("{}", "2d6 +4 +3d20".parse::<Dice>().unwrap());
let d20 = "d20".parse::<Dice>().unwrap();
println!("{} results in {}", d20, d20.roll());
}
| true |
4f6359d200566531c59605622bfa57b049bd6bbb | Rust | z1queue/incubator-teaclave | /rpc/src/protocol.rs | UTF-8 | 4,155 | 2.5625 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT",
"BSD-3-Clause",
"Apache-2.0"
] | permissive | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may... | true |
c12871fcf3829e16960145af4e2681559e0dfc20 | Rust | Tzrlk/myth | /src/core/fate/result.rs | UTF-8 | 1,348 | 3.828125 | 4 | [] | no_license | //!
use std::fmt::{ Display, Formatter, Error };
pub struct CalcResult {
pub yes_result: bool,
pub exceptional: bool,
pub random_event: bool
}
impl Display for CalcResult {
fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
let message = &[
if self.exceptional { "Exceptional " } else { "" },
i... | true |
735fb1394109853a9da8a631b97d8e901f77a6b4 | Rust | marijnhurkens/rust-raytracer | /src/bsdf/helpers/fresnel.rs | UTF-8 | 1,835 | 3.421875 | 3 | [
"MIT"
] | permissive | #[derive(Debug, Clone, Copy)]
pub enum Fresnel {
Noop(FresnelNoop),
Dielectric(FresnelDielectric),
}
pub trait FresnelTrait {
fn evaluate(&self, cos_i: f64) -> f64;
}
impl FresnelTrait for Fresnel {
fn evaluate(&self, cos_i: f64) -> f64 {
match self {
Fresnel::Noop(x) => x.evaluate... | true |
6e1f95be2c9516ac56b636a0467660f9f40bd353 | Rust | tomohiko38/rust_projects | /chapter10/trait_sample01/src/main.rs | UTF-8 | 1,677 | 3.34375 | 3 | [] | no_license | use trait_sample01::Tweet;
use trait_sample01::Summary;
use trait_sample01::NewsArticle;
use std::fmt::Display;
fn main() {
let tweet = Tweet {
username: String::from("horse_ebooks"),
content: String::from("of course, as you probably already know, people"),
reply: false,
retweet: fa... | true |
d8c6ee457ebaa23506d8339bdf83819a3d9a8635 | Rust | mrDIMAS/tbc | /src/lib.rs | UTF-8 | 2,015 | 2.703125 | 3 | [
"MIT"
] | permissive | //! Texture Block Compression
//!
//! Pure Rust implementation of BCn texture compression algorithm implementations.
//!
//! Supported formats:
//! - BC1 (DXT1)
//! - BC3 (DTX5)
//! - BC4 (Both R8 and RG8)
//!
//! References:
//!
//! https://docs.microsoft.com/en-us/windows/win32/direct3d10/d3d10-graphics-programming-g... | true |
b9d1af18ec9cb87e1a3328ad98e273b9ad6d9e06 | Rust | risboo6909/aoc2020 | /problems/src/problem10/mod.rs | UTF-8 | 3,548 | 2.953125 | 3 | [
"MIT"
] | permissive | use std::cmp::max;
use std::collections::{HashMap, HashSet};
use itertools::sorted;
use failure::{format_err, Error};
use utils::{result, split_by_lines, RetTypes};
fn first_star_rec(
input: &mut HashSet<usize>,
cur_joltage: usize,
one_jolt_cnt: usize,
three_jolt_cnt: usize,
) -> usize {
if input... | true |
8b731eb7a9ea439c515b786966adf39b3332e96e | Rust | olback/atsamd | /hal/src/common/thumbv7em/sercom/v2/spi.rs | UTF-8 | 73,086 | 3.453125 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0",
"MIT"
] | permissive | //! Use the SERCOM peripheral for SPI transactions
//!
//! Configuring the SPI peripheral occurs in three steps. First, you must create
//! a set of [`Pads`] for use by the peripheral. Next, you assemble pieces into
//! a [`Config`] struct. After configuring the peripheral, you then [`enable`]
//! it, yielding a functi... | true |
34a18362322ed1f7a1d5bb148f7e0c83a7aa97da | Rust | taiki-e/miri | /ui_test/src/rustc_stderr.rs | UTF-8 | 4,975 | 2.78125 | 3 | [
"Apache-2.0",
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | use std::{
fmt::Write,
path::{Path, PathBuf},
};
use color_eyre::eyre::{eyre, Error};
use regex::Regex;
#[derive(serde::Deserialize, Debug)]
struct RustcMessage {
rendered: Option<String>,
spans: Vec<Span>,
level: String,
message: String,
children: Vec<RustcMessage>,
}
#[derive(Copy, Clon... | true |
11a460fca3aa915e3a20c2bbb796233b5660444a | Rust | pacman82/rtiow | /src/random_scenes.rs | UTF-8 | 3,515 | 2.5625 | 3 | [] | no_license | use crate::{
persistence::{CameraBuilder, HittableBuilder, SceneBuilder, ShapeBuilder, SurfaceBuilder},
vec3::{Color, Point, Vec3},
};
use rand::Rng;
pub fn spheres(rng: &mut impl Rng, aspect_ratio: f64) -> SceneBuilder {
let mut world = Vec::new();
let ground_material = SurfaceBuilder::Checkered(
... | true |
55f0d7bbac76f214144e29b9ba2f9cfa8a271709 | Rust | bombadil7/rust | /iter/src/main.rs | UTF-8 | 1,215 | 3.703125 | 4 | [] | no_license | //struct Empty;
//
//impl Iterator for Empty {
// type Item = u32;
//
// fn next(&mut self) -> Option<<Self>::Item> {
// None
// }
//}
//struct TheAnswer;
//
//impl Iterator for TheAnswer {
// type Item = u32;
//
// fn next(&mut self) -> Option<u32> {
// Some(42)
// }
//}
//
struct OneT... | true |
db7a33f3e48f8e96cb1c84038f164aa824abda3d | Rust | 38/d4-format | /d4/examples/find_de_novo.rs | UTF-8 | 3,581 | 2.6875 | 3 | [
"MIT"
] | permissive | use d4::{
task::{Mean, Task, TaskPartition},
D4MatrixReader, D4TrackReader, MultiTrackReader,
};
use std::{collections::HashMap, marker::PhantomData};
fn compute_chrom_mean_depth(
reader: &mut D4TrackReader,
) -> Result<HashMap<String, (u32, f64)>, Box<dyn std::error::Error>> {
let regions: Vec<_> = re... | true |
397cc72407d33384773f828a597b9c41e89fdd53 | Rust | 0nkery/congenial-lamp | /src/apis/weatherbit.rs | UTF-8 | 2,344 | 3.03125 | 3 | [
"MIT"
] | permissive | use std::env;
use chrono::{TimeZone, Utc};
use failure::Error;
use reqwest::Url;
use apis::{WeatherAPI, WeatherData, WeatherDataVec, WeatherQuery};
/// https://www.weatherbit.io/api/weather-forecast-16-day
pub struct WeatherBit {
key: String,
}
impl WeatherBit {
pub fn new() -> Result<Self, Error> {
... | true |
76fb75d9f364ae868e1a23231ec5fff95775d802 | Rust | Noah2610/deathframe | /deathframe_core/src/custom_game_data/data.rs | UTF-8 | 2,265 | 2.828125 | 3 | [
"MIT"
] | permissive | use std::collections::HashMap;
use std::fmt::Debug;
use std::hash::Hash;
use amethyst::core::SystemBundle;
use amethyst::ecs::Dispatcher;
use amethyst::prelude::*;
use amethyst::DataDispose;
use super::internal_helpers::*;
use super::CustomGameDataBuilder;
pub struct CustomGameData<'a, 'b, D, C = ()>
where
D: Ha... | true |
0af7874cb382ac688c883eda7d4af2e6719aa4d3 | Rust | likewhatevs/rust-socketio | /src/engineio/transport.rs | UTF-8 | 23,611 | 2.609375 | 3 | [
"MIT"
] | permissive | use crate::engineio::packet::{decode_payload, encode_payload, Packet, PacketId};
use crate::error::{Error, Result};
use adler32::adler32;
use bytes::{BufMut, Bytes, BytesMut};
use reqwest::{blocking::Client, Url};
use serde::{Deserialize, Serialize};
use std::{borrow::Cow, time::SystemTime};
use std::{fmt::Debug, sync:... | true |
ce73c9763f9e9d8d04254f10956ed4ba9e5ba192 | Rust | JosephLenton/burgundy | /src/native_client/string_stream.rs | UTF-8 | 1,002 | 3.4375 | 3 | [
"MIT"
] | permissive | use crate::error;
use futures;
use hyper;
/// This is a fake future stream.
/// It wraps the `String` given, and when it is polled it just gets
/// returned.
///
/// Second, third, and other future polls, all return `Option::None`.
pub(crate) struct StringStream {
content: Option<String>,
}
impl StringStream {
... | true |
d9bf3887150f04d4ae778f2aad030a6c45a237b4 | Rust | linkerd/linkerd2-proxy | /linkerd/proxy/balance/src/discover/from_resolve.rs | UTF-8 | 8,085 | 2.5625 | 3 | [
"Apache-2.0"
] | permissive | use futures::{prelude::*, ready};
use indexmap::{map::Entry, IndexMap};
use linkerd_proxy_core::resolve::Update;
use pin_project::pin_project;
use std::{
collections::VecDeque,
net::SocketAddr,
pin::Pin,
task::{Context, Poll},
};
use tower::discover::Change;
use tracing::{debug, trace};
/// Observes an... | true |
ceedb883c4c15f56b1f22d05ad88ef934464491a | Rust | avbhandaru/csvql | /src/query/postgres.rs | UTF-8 | 6,484 | 2.921875 | 3 | [
"MIT"
] | permissive | use crate::querier::QuerierTrait;
use crate::table;
use crate::types;
use async_trait::async_trait;
use tokio_postgres::error::Error;
use tokio_postgres::{connect, Client, NoTls, Row};
#[derive(Debug)]
pub struct Querier {
pub name: String,
pub url: String,
pub client: Client,
}
impl Querier {
pub async fn ne... | true |
77b0080617509b529d5ef72ebafcd6808d5aeef6 | Rust | Roba1993/Heima-legacy | /core/src/zwave.rs | UTF-8 | 7,116 | 2.78125 | 3 | [
"MIT"
] | permissive | use serde_json::Value as JValue;
use serde_json::map::Map;
use error::Error;
use std::time::Duration;
use std::thread;
//use std::time::SystemTime;
use rzw::driver::serial::SerialDriver;
use rzw::basic::Controller;
use rzw::cmds::CommandClass;
use rzw;
use std::sync::mpsc::Sender;
use core::Reactor;
use model::{Event, ... | true |
ddf5294292251dea91bd0aaeb98ecb3824fdd6d4 | Rust | nestordemeure/gambit | /gambit/src/result/mod.rs | UTF-8 | 692 | 2.578125 | 3 | [
"Apache-2.0"
] | permissive | pub mod single;
pub mod pareto;
pub mod display;
pub mod option;
use crate::grammar::{Grammar, Formula};
pub use single::Single;
pub use pareto::ParetoFront;
pub use display::DisplayProgress;
pub use option::Optional;
/// represents a result of the algorithm
pub trait Result<State>: std::fmt::Display
where State: ... | true |
b258ce0765015039ef1845e0b39e9ff04f4c1836 | Rust | jonasbb/advent-of-code-2018 | /src/day02.rs | UTF-8 | 2,076 | 3.5625 | 4 | [] | no_license | use hashbrown::HashMap;
#[aoc(day2, part1)]
pub fn solve_part1(input: &str) -> u32 {
let contains_iter = input.lines().map(|l| {
// count how often each char exists
let mut char_count = HashMap::new();
for c in l.trim().chars() {
char_count.entry(c).and_modify(|e| *e += 1).or_in... | true |
cf1b50eab4cfa6497ea9e94a36c63e27fe053966 | Rust | second-state/wasm-learning | /faas/image-brighten/src/lib.rs | UTF-8 | 865 | 2.90625 | 3 | [] | no_license | use wasm_bindgen::prelude::*;
use image::{ImageOutputFormat, GenericImageView, ImageFormat};
#[wasm_bindgen]
pub fn brighten(img_buf: &[u8]) -> Vec<u8> {
println!("image size is {}", img_buf.len());
let img = image::load_from_memory(img_buf).unwrap();
let (w,h) = img.dimensions();
println!("Image size ... | true |
eb9f858e964415551c6e5e5248512394e050ea9f | Rust | DataDog/glommio | /glommio/src/task/state.rs | UTF-8 | 2,141 | 2.90625 | 3 | [
"MIT",
"Apache-2.0"
] | permissive | // Unless explicitly stated otherwise all files in this repository are licensed
// under the MIT/Apache-2.0 License, at your convenience
//
// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2020 Datadog, Inc.
//
/// Set if the task is scheduled for running.
///
/// A task is... | true |
91488ea767b3f66e35cbe418f7c8c558e72563ff | Rust | ghaerdi/rust-algorithms | /src/collections/linked_list.rs | UTF-8 | 917 | 3.953125 | 4 | [] | no_license | #[derive(Debug)]
struct Node<T> {
value: T,
next: Option<Box<Node<T>>>,
}
impl<T> Node<T> {
fn new(value: T) -> Self {
Node {
value: value,
next: None,
}
}
}
#[derive(Debug)]
pub struct LinkedList<T> {
head: Option<Box<Node<T>>>,
len: usize,
}
impl<T> LinkedList<T> {
pub fn new() ->... | true |
456e6bf241787f94c15e5ae3c21f84a189db793f | Rust | riku179/mac-notify | /src/redis_client.rs | UTF-8 | 3,112 | 2.875 | 3 | [] | no_license | use mac_cap::MacAddr;
use r2d2;
use r2d2_redis::RedisConnectionManager;
use redis::cmd;
use redis::{Commands, RedisResult, Connection, Client};
use chrono;
use chrono::prelude::*;
use chrono::{DateTime, Local};
// ref) https://rocket.rs/guide/state/#managed-pool
pub fn new_redis_pool(url: &str) -> Result<r2d2::Pool<Re... | true |
f62326b9c590a12b23fd39d9a0696e6fa299dee8 | Rust | tomhoule/try-parcel | /src/rpc/server.rs | UTF-8 | 6,926 | 2.640625 | 3 | [] | no_license | use config;
use diesel;
use r2d2;
use diesel::prelude::*;
use configure::Configure;
use rpc::yacchauyo::{FragmentsQuery, Schema, Text, Texts, TextsQuery};
use models;
use models::texts::Text as TextModel;
use error::Error;
use utils::*;
use uuid::Uuid;
#[derive(Clone)]
pub struct Server {
pool: r2d2::Pool<diesel::... | true |
203c25b11c3d12bddc29e1034b50c31ebb4d6e14 | Rust | kashifsoofi/exercism | /rust/grade-school/src/lib.rs | UTF-8 | 1,096 | 3.578125 | 4 | [] | no_license | use std::collections::HashMap;
struct Grade {
grade: u32,
students: Vec<String>,
}
pub struct School {
grade_students: HashMap<u32, Vec<String>>,
}
impl School {
pub fn new() -> School {
School {
grade_students: HashMap::new(),
}
}
pub fn add(&mut self, grade: u32... | true |
bc806d638cb7b1f82a9d6a33825d52b1eb3a20a8 | Rust | vercel/next.js | /packages/next-swc/crates/next-core/src/next_image/source_asset.rs | UTF-8 | 4,698 | 2.546875 | 3 | [
"MIT"
] | permissive | use std::io::Write;
use anyhow::{bail, Result};
use turbo_tasks::Vc;
use turbopack_binding::{
turbo::tasks_fs::{rope::RopeBuilder, FileContent},
turbopack::{
core::{
asset::{Asset, AssetContent},
ident::AssetIdent,
source::Source,
},
ecmascript::utils... | true |
a4b6fa3703f110fd5fffa44726776d5d22b3df04 | Rust | Kreedzt/LearningRust | /16.2.message-passing/src/main.rs | UTF-8 | 1,481 | 3.78125 | 4 | [] | no_license | use std::sync::mpsc;
use std::thread;
use std::time::Duration;
fn main() {
// mspc::channel 多个生产者, 单个消费者(multiple producer, single consumer) 的缩写.
// tx: 发送者 transmitter, rx: 接收者 receiver
let (tx, rx) = mpsc::channel();
// 使用 move 转移所有权
// thread::spawn(move || {
// let val = String::from("... | true |
3bae201b56de41d972497a27b9796eb5c9dfacdb | Rust | alexcarol/exercism-rust | /diffie-hellman/src/lib.rs | UTF-8 | 395 | 3 | 3 | [] | no_license | pub fn private_key(p: u64) -> u64 {
p - 1
}
pub fn public_key(p: u64, g: u64, a: u64) -> u64 {
module_exponential(g, a, p)
}
pub fn secret(p: u64, b_pub: u64, a: u64) -> u64 {
module_exponential(b_pub, a, p)
}
fn module_exponential(base: u64, exp: u64, module: u64) -> u64 {
let mut power = 1;
for... | true |
c099ba248d0ecd80c922f573a53cb88b5de48e60 | Rust | magj2006/my-redis | /examples/select.rs | UTF-8 | 1,000 | 2.921875 | 3 | [] | no_license | use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
use tokio::sync::oneshot;
struct MySelect {
rx1: oneshot::Receiver<&'static str>,
rx2: oneshot::Receiver<&'static str>,
}
impl Future for MySelect {
type Output = ();
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) ->... | true |
ee3c064e96891459aba4387344f8c8bca0e60727 | Rust | osklunds/Distributed-SWMR-register | /application/src/terminal_output.rs | UTF-8 | 309 | 2.734375 | 3 | [
"BSD-3-Clause"
] | permissive | use colored::Colorize;
use crate::settings::SETTINGS;
// Prints a string with the color assigned to this node.
pub fn printlnu(string: String) {
let output_string =
format!("[Node {}] {}", SETTINGS.node_id(), string);
println!("{}", output_string.color(SETTINGS.terminal_color()).bold());
}
| true |
31f9d93a910da36ccb2578b07574bea3e0a43788 | Rust | barakplasma/frawk | /src/codegen/clif.rs | UTF-8 | 62,264 | 3.125 | 3 | [
"Apache-2.0",
"MIT"
] | permissive | //! Cranelift code generation for frawk programs.
//!
//! A few notes on how frawk typed IR is translated into CLIF (from which cranelift can JIT machine
//! code):
//! * Integers are I64s
//! * Floats are F64s
//! * Strings are I128s
//! * Maps are I64s (pointers, in actuality, but we have no need for cranelift's spec... | true |
9fc4e8382671439a1bba0f2ea9d526666d64743f | Rust | onesk/aoc2019 | /src/bin/2.rs | UTF-8 | 2,846 | 3.359375 | 3 | [] | no_license | #[allow(unused_imports)]
use std::convert::TryInto;
use itertools::{join, iproduct};
use boolinator::Boolinator;
const INPUT: &'static str = include_str!("inputs/2.txt");
type Memory = Vec<usize>;
fn parse_line(s: &str) -> Option<Memory> {
s.trim().split(",").map(|l| l.parse().ok()).collect()
}
struct State {
... | true |
80342e119b59554b175b02027114b10124adce73 | Rust | teloxide/teloxide | /crates/teloxide/tests/redis.rs | UTF-8 | 2,508 | 2.625 | 3 | [
"MIT"
] | permissive | use std::{
fmt::{Debug, Display},
sync::Arc,
};
use teloxide::{
dispatching::dialogue::{RedisStorage, RedisStorageError, Serializer, Storage},
types::ChatId,
};
#[tokio::test]
#[cfg_attr(not(CI_REDIS), ignore)]
async fn test_redis_json() {
let storage = RedisStorage::open(
"redis://127.0.0.... | true |
1dcb8bb08b69a1839256ad6a64fd317698407c7a | Rust | isgasho/tanks | /src/physics/inertia.rs | UTF-8 | 665 | 2.59375 | 3 | [] | no_license | use super::{Delta, Position, Velocity};
use cgmath::prelude::*;
use specs;
#[derive(Debug)]
pub struct InertiaSystem;
impl InertiaSystem {
pub fn new() -> InertiaSystem {
InertiaSystem {}
}
}
impl specs::System<Delta> for InertiaSystem {
fn run(&mut self, arg: specs::RunArg, time: Delta) {
... | true |
0a441a55e45dccc4f78a1bc41999056ad2f632cf | Rust | ianzhang1988/RustOneFileExample | /src/bin/tcp_server_ext.rs | UTF-8 | 4,024 | 3.046875 | 3 | [] | no_license | use std::thread;
use std::net::{TcpListener, TcpStream, Shutdown};
use std::io::{Read};
use std::convert::TryInto;
use std::str::from_utf8;
fn read_le_u32_simple(input: &[u8]) -> u32 {
let (int_bytes, _rest) = input.split_at(std::mem::size_of::<u32>());
u32::from_le_bytes(int_bytes.try_into().unwrap())
}
#[al... | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.