text stringlengths 8 4.13M |
|---|
use argh::FromArgs;
use fshare::{Client, Disconnected, ServerBuilder};
/// send or receive files between hosts
#[derive(FromArgs, PartialEq, Debug)]
struct Args {
#[argh(subcommand)]
subcommand: SubCommand,
}
#[derive(FromArgs, PartialEq, Debug)]
#[argh(subcommand)]
enum SubCommand {
Client(ClientArgs),
... |
#[allow(dead_code)]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum Platform {
Portable,
#[cfg(feature = "asm")]
Asm,
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
Sha,
}
#[derive(Clone, Copy, Debug)]
pub struct Implementation(Platform);
impl Implementation {
pub fn detect() -> Se... |
use core::sync::atomic::{AtomicU8, Ordering};
use core::task::Poll;
use embassy::interrupt::{Interrupt, InterruptExt};
use embassy::util::AtomicWaker;
use futures::future::poll_fn;
use super::*;
use crate::interrupt;
use crate::pac;
use crate::pac::dma::{regs, vals};
const DMAS: [pac::dma::Dma; 2] = [pac::DMA1, pac::... |
use std::path::PathBuf;
use crate::prelude::*;
use futures::channel::oneshot;
#[derive(Clone)]
pub struct Gl(std::rc::Rc<glow::Context>);
impl Gl {
pub(crate) fn new(gl: glow::Context) -> Self {
Gl(std::rc::Rc::new(gl))
}
}
impl std::ops::Deref for Gl {
type Target = glow::Context;
fn deref(... |
fn destroy_box(c: Box<i32>) {
println!("Destorying a box that contains {}", c);
}
fn main() {
let x = 5u32;
let y = x;
println!("x is {}, and y is {}", x, y);
let a = Box::new(5i32);
println!("a contains: {}", a);
let b = a;
// println!("a contains: {}", a);
destroy_box(b);
... |
use std::fmt::Debug;
#[derive(Copy, Clone)]
pub struct NonNegativeFloat(f32);
impl Debug for NonNegativeFloat {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "|{}|", self.0)
}
}
pub struct NegativeFloatError;
impl NonNegativeFloat {
pub fn new(x: f32) -> Result<S... |
#![allow(non_upper_case_globals)]
#![allow(non_camel_case_types)]
#![allow(non_snake_case)]
#![allow(dead_code)]
mod bindings;
use std::ffi::CStr;
use bindings::*;
fn main() {
unsafe {
let ctx = X_NewContext();
let text_str = "Rafael\0";
let text = CStr::from_bytes_with_nul(text_str.as_by... |
#[derive(Default)]
struct Foo {
a: u8,
b: u32,
c: bool,
}
enum Bar {
X(u32),
Y(bool, u64),
}
impl Default for Bar {
fn default() -> Bar {
Bar::X(123)
}
}
struct Unit;
fn main() {
let v1 = vec![1, 2, 3];
println!("v1.len: {}", v1.len());
for v in &v1 {
printl... |
use serde::{Deserialize, Serialize};
use std::{
borrow::Cow,
iter::FromIterator,
sync::mpsc::{Receiver, SyncSender},
};
use eframe::egui::{
self, epaint::text, Button, Color32, CtxRef, FontDefinitions, FontFamily, Hyperlink, Label,
Layout, Separator, TopBottomPanel, Window,
};
pub const PADDING: f... |
use std::{str::FromStr, sync::Arc};
use eyre::Report;
use rosu_v2::prelude::{BeatmapsetCompact, GameMode, OsuError};
use tokio::{
fs::{remove_file, File},
io::AsyncWriteExt,
};
use crate::{
util::{
constants::{
common_literals::{MANIA, OSU},
GENERAL_ISSUE, OSU_API_ISSUE, OS... |
#![allow(dead_code)]
use crate::Result;
use anyhow::anyhow;
use std::iter::IntoIterator;
#[derive(Clone, Debug, PartialEq)]
/// Represents a dependency in distribution agnostic way, used for a recipe.
pub struct Dependency {
/// fallback global name
name: Option<String>,
/// each value corresponds to (ima... |
// Generated from swizzle_impl.rs.tera template. Edit the template, not the generated file.
#![allow(clippy::useless_conversion)]
use crate::{Vec2, Vec3A, Vec3Swizzles, Vec4};
#[cfg(target_arch = "x86")]
use core::arch::x86::*;
#[cfg(target_arch = "x86_64")]
use core::arch::x86_64::*;
impl Vec3Swizzles for Vec3A {
... |
fn main() {
loop {
let mut num = String::new();
std::io::stdin().read_line(&mut num).unwrap();
let num = num.trim().chars().collect::<Vec<char>>();
if num.len() == 1 && num[0] == '0' {
break;
}
let mut sum: u32 = 0;
for digit in num {
... |
#[derive(Clone, Copy)]
enum RomanDigit {
I,
IV,
V,
IX,
X,
XL,
L,
XC,
C,
CD,
D,
CM,
M,
}
impl RomanDigit {
fn largest_fit(num: u16) -> Option<RomanDigit> {
match num {
n if n >= RomanDigit::M.into() => Some(RomanDigit::M),
n if n >= ... |
fn main() {
// Bind a value to the name
let x = 5; // x: i32
println!("The value of x is: {}", x);
// Pattern
let (a,b) = (1,2);
println!("The value of a is: {}", a);
println!("The value of b is: {}", b);
// Type annotations
// y is a binding with the type i32 and the value 5
/... |
//! Low-Level reader for FDB files
//!
//! This module provides a struct which can be used to access
//! a FDB file in any order the user desires.
pub mod builder;
use std::io::{self, BufRead, Read, Seek, SeekFrom};
use super::{
file::{
lists::{FDBBucketHeaderList, FDBColumnHeaderList, FDBFieldDataList, ... |
/*!
A simple, streaming, partially-validating XML writer that writes XML data into an internal buffer.
## Features
- A simple, bare-minimum, panic-based API.
- Non-allocating API. All methods are accepting either `fmt::Display` or `fmt::Arguments`.
- Nodes auto-closing.
## Example
```rust
use xmlwriter::*;
let opt... |
//! Frodobuf library
//!
//! This crate provides code generation and runtime support for fordobuf messages
//! used by [wasmcloud](https://wasmcloud.dev) actors and capability providers.
//!
mod common;
pub use common::{
client, context, deserialize, serialize, Message, MessageDispatch, RpcError, Transport,
Wa... |
fn fun_test(value: i32, f: &Fn(i32) -> i32) -> i32 {
println!("{}", f(value));
value
}
fn times2(value: i32) -> i32 {
2 * value
}
fn main() {
fun_test(5, ×2);
}
// extern crate gnuplot;
// use gnuplot::{Figure, Caption, Color};
// fn main() {
// let x = [0u32, 1, 2];
// let y = [3u32, 4... |
// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... |
impl Solution {
pub fn spiral(matrix: &Vec<Vec<i32>>) -> Vec<i32> {
fn shape(m: &Vec<Vec<i32>>) -> (usize, usize) {
if m.len() == 0 {
(0, 0)
}
else {
(m.len(), m[0].len())
}
}
let (row, col) = shape(matrix);
... |
//! Parameters are kept as the single "source of truth" for the long-term state of the plugin. As
//! used by the VST API, the parameter bank is accessible by both the audio processing thread and
//! the UI thread, and updated using thread-safe interior mutability. However, to avoid costly
//! synchronization overhead,... |
mod maybe_result;
use color_eyre::{eyre::eyre, Report};
use maybe_result::MaybeResult;
use std::{
future::Future,
pin::Pin,
task::{Context, Poll},
time::Duration,
};
#[tokio::main]
async fn main() {
println!("Ok we're off!");
let tup = try_join_correct(do_more_stuff(), do_stuff()).await;
p... |
pub mod byzan;
pub mod byzan_grpc;
|
pub mod rush;
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn alias_test() {
let mut shell = rush::Shell::new() ;
shell.prompt("$").flush();
let mut line = vec!["alias", "l=ls"].into_iter().map(|x| x.to_string()).collect::<Vec<String>>();
shell.exec(line).finish();
... |
use std::time::Duration;
use circulate::Relay;
use tokio::time::sleep;
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let relay = Relay::default();
let subscriber = relay.create_subscriber().await;
// Subscribe for messages sent to the topic "pong"
subscriber.subscribe_to("pong").await;
... |
pub struct LVar(pub usize);
pub enum LError {
Contradiction
}
pub trait Unifiable<E=LError> {
fn unify(&self,&Self) -> Result<Self,E>;
}
pub trait LMap {
type Target;
fn bump(&mut self,usize);
fn fresh(&mut self) -> LVar;
fn unify(&mut self,(LVar,Self::Target));
}
|
extern crate upload_images;
#[cfg(test)]
mod dataset;
use rocket::http::{ContentType, Status};
use rocket::local::Client;
use upload_images::rocket;
#[test]
fn test_valid_json_png_base64() {
let client = Client::new(rocket()).unwrap();
let mut response = client
.post("/api/v1/images/upload")
.header(Con... |
/// Attachment a generic attachment
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct Attachment {
pub browser_download_url: Option<String>,
pub created_at: Option<String>,
pub download_count: Option<i64>,
pub id: Option<i64>,
pub name: Option<String>,
pub size: Option<i64>,
... |
use std::collections::HashMap;
pub const DEFAULT_ALPHABET: &str = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_";
pub struct Convertor {
pub input_map: HashMap<char, u32>,
pub output_vec: Vec<char>,
}
impl Convertor {
pub fn new(input_alphabet: &str, output_alphabet: &str) -> Convertor {
... |
use ansi_term::Color;
use std::process::Command;
use chrono::Local;
use super::{Context, Module};
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
const TIME_SYMBOL: &str = "🕒 ";
const DEFAULT_FORMAT: &str = "%Y/%m/%d %H:%M:%S";
let mut module = context.new_module("datetime")?;
let f... |
// q0132_palindrome_partitioning_ii
struct Solution;
use std::collections::HashSet;
impl Solution {
pub fn min_cut(s: String) -> i32 {
if Solution::is_plalindrome(&s) {
return 0;
}
let ss = s.as_str();
let mut times = 0;
let mut start_indexs = HashSet::new();
... |
use serde::{Deserialize, Serialize};
use std::convert::TryFrom;
use crate::prelude::*;
pub fn default_user_config() -> UserConfig {
// Colors: https://lospec.com/palette-list/vinik24
UserConfig {
post_scanlines: false,
post_burnin: Some("#8d6268".into()),
default_fg: "#c5ccb8".into()... |
mod namevaluepair;
pub use self::namevaluepair::NameValuePair;
mod xmlparser;
pub use self::xmlparser::XMLParser;
pub use self::xmlparser::XMLEntry;
mod logger;
pub use self::logger::Logger;
pub use self::logger::LogLevel;
|
use pixels::{
wgpu::{PowerPreference, RequestAdapterOptions},
Pixels, PixelsBuilder, SurfaceTexture,
};
use sdl2::event::Event;
use sdl2::video::Window;
use sdl2::EventPump;
use std::time::Instant;
use crate::font::Font;
use crate::State;
pub struct Game {
pixels: Pixels<Window>,
event_pump: EventPump... |
use super::new::*;
use super::parser2::*;
use std::time::Instant;
pub fn run_new() {
let now = Instant::now();
let mut program = Program::new();
// Need to set this non-manually
// program.clause_indexes = vec![Clause{left: 14, right: 18}, Clause{left: 21, right: 25},];
let main = &mut program.m... |
extern crate ghost;
use ghost::board;
use ghost::game;
fn main() {
let mut g = game::Game::new(19);
g.make_move(board::Stone::Black, board::Coords{ x: 15, y: 3 });
g.make_move(board::Stone::White, board::Coords{ x: 3, y: 15 });
g.make_move(board::Stone::Black, board::Coords{ x: 15, y: 16 });
g.mak... |
use kube::api::{Patch, PatchParams, Resource};
use kube::Api;
use serde_json::{json, Value};
#[derive(
Clone, Debug, kube::CustomResource, schemars::JsonSchema, serde::Deserialize, serde::Serialize,
)]
#[kube(
kind = "TorHiddenService",
group = "tor-operator.agabani",
version = "v1",
namespaced,
... |
use super::{Cartridge, Mirror};
#[derive(serde::Serialize, serde::Deserialize)]
pub enum MapperData {
Nrom(NromData),
Mmc1(Mmc1Data),
Uxrom(UxromData),
Cnrom(CnromData),
Mmc3(Mmc3Data),
}
#[derive(serde::Serialize, serde::Deserialize)]
pub struct NromData {
pub cart: Cartridge,
pub chr_ra... |
mod chip8;
use chip8::Chip8;
fn main() {
setup_graphics();
setup_input();
let mut my_chip8 = Chip8::initialize();
my_chip8.load_game("pong");
loop {
my_chip8.emulate_cycle();
if my_chip8.drawflag {
draw_graphics();
}
my_chip8.set_keys();
}
}
fn s... |
pub mod clustering;
pub mod codon_usage;
pub mod construct;
pub mod extract;
pub mod merge;
pub mod query;
|
#[doc = "Register `C7BR2` reader"]
pub type R = crate::R<C7BR2_SPEC>;
#[doc = "Register `C7BR2` writer"]
pub type W = crate::W<C7BR2_SPEC>;
#[doc = "Field `BRSAO` reader - Block repeated source address offset For a channel with 2D addressing capability, this field is used to update (by addition or subtraction depending... |
pub struct UrlEncodeQueryValue<'a> {
data: &'a [u8],
}
fn must_escape(byte: u8) -> bool {
match byte {
b'#' => true,
b'%' => true,
b'&' => true,
b'=' => true,
_ => byte > 127,
}
}
impl std::fmt::Display for UrlEncodeQueryValue<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
let... |
use crate::{BoxFuture, Ctx, Result};
use async_cell_lock::QueueRwLockReadGuard;
pub trait AsRefAsync<T> {
fn as_ref_async(&self) -> BoxFuture<'_, Result<&'_ T>>;
}
impl<T, U> AsRefAsync<T> for QueueRwLockReadGuard<'_, U>
where
U: AsRefAsync<T>,
{
fn as_ref_async(&self) -> BoxFuture<'_, Result<&'_ T>> {
... |
extern crate futures;
extern crate tokio;
extern crate inotify;
use std::time::{Duration, Instant};
use futures::future::lazy;
use futures::prelude::*;
use futures::stream::Stream;
use inotify::{Inotify, WatchMask};
use tokio::timer::Interval;
fn main() {
// inotify testing
// we do the directory. if you do ... |
use ntex_mqtt::{v3, v5};
#[derive(Debug)]
pub enum ServerError {
InternalError(String),
UnsupportedOperation,
AuthenticationFailed,
NotAuthorized,
}
impl std::convert::TryFrom<ServerError> for v5::PublishAck {
type Error = ServerError;
fn try_from(err: ServerError) -> Result<Self, Self::Error... |
use super::sacak;
use proptest::prelude::*;
macro_rules! bytes {
($range:expr) => {
prop::collection::vec(any::<u8>(), $range)
};
}
proptest! {
#[test]
fn sacak_correctness(s in bytes!(0..8192_usize)) {
prop_assert!(check(&s[..]));
}
}
fn check(s: &[u8]) -> bool {
let mut sa =... |
use serde::de::{self, Deserialize, Deserializer};
use serde::ser::Serializer;
use std::fmt::Display;
use std::str::FromStr;
pub(crate) fn from_str<'de, T, D>(deserializer: D) -> Result<T, D::Error>
where
T: FromStr,
T::Err: Display,
D: Deserializer<'de>,
{
let s = String::deserialize(deserializer)?;
... |
extern crate utils;
fn main() {
let limit = match utils::read_int() {
Ok(value) => value,
Err(msg) => {
println!("{}", msg);
return;
}
};
utils::time(|| -> u64 {
largest_prime_factor_nosieve(limit, 2, 1)
}, limit.to_string());
}
fn largest_prime... |
#![feature(proc_macro_hygiene, decl_macro)]
#[macro_use] extern crate rocket;
use rocket::http::RawStr;
#[get("/user/<id>")]
fn user(id: usize) -> String {
format!("you called user() with: {}", id)
}
#[get("/user/<id>", rank = 2)]
fn user_int(id: isize) -> String {
format!("you called user_int() with: {}", ... |
/// This module contains optional APIs for implementing QUIC TLS.
use crate::client::{ClientConfig, ClientSession, ClientSessionImpl};
use crate::msgs::enums::{ContentType, ProtocolVersion, AlertDescription};
use crate::msgs::handshake::{ClientExtension, ServerExtension};
use crate::msgs::message::{Message, MessagePayl... |
struct Reindeer {
speed: u32,
time: u32,
rest: u32,
}
impl std::str::FromStr for Reindeer {
type Err = ();
fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut parts = s.split(' ');
parts.next();
parts.next();
parts.next();
let speed = parts.next().unwr... |
use std::{f64::consts::PI, time::Instant};
use veccentric::Fecc;
mod engine;
use engine::{Buffer, Color, HEIGHT, WIDTH};
struct State {
seconds: Fecc,
minutes: Fecc,
hours: Fecc,
start: Instant,
}
fn main() -> Result<(), pixels::Error> {
// Set up state.
let original_s = (0.0, -25.0).into()... |
fn main() {
let nums1 = vec![34, 50, 25, 100, 65];
let nums2 = vec![102.0, 34.1, 6000.2, 89.111, 54.3];
fn largest<T: PartialOrd>(list: &[T]) -> &T {
let mut largest = &list[0];
for item in list {
if item > largest {
largest = &item
}
}
... |
use std::io;
fn main() {
let mut r = String::new();
// io::stdin().read_line(&mut r).expect("Failed to read line");
io::stdin().read_line(&mut r).ok();
let r: u32 = r.trim().parse().unwrap();
println!("{}", r*r);
}
|
//
use std::time::Instant;
fn main() {
let now = Instant::now();
println!("e:{:?}, {:?} seconds", e(), now.elapsed());
}
fn e() -> usize {
let v = get_triangle_nums_up_to(20);
let file = include_str!("./p042_words.txt") // nifty lil macro
.chars()
.filter(|&x| x != '\"' && x != '\n' && ... |
use ast::{Ast};
#[allow(unused_imports)]
use nom::*;
mod operators;
mod expressions;
use self::expressions::sexpr;
mod identifier;
mod literal;
mod utilities;
mod assignment;
use self::assignment::*;
mod type_signature;
mod function;
use self::function::*;
mod body;
mod control_flow;
use self::control_flow:... |
use std::fs::File;
use std::io::Read;
use regex::Regex;
mod aoclib;
use aoclib::modular;
struct Disc {
positions: i32,
start: i32,
}
fn parse_input(text: &str) -> Vec<Disc> {
let re = Regex::new(r"has (\d+) positions.*is at position (\d+)").unwrap();
text.lines()
.into_iter()
.filter(|... |
#![warn(rust_2018_idioms)]
use std::fs;
use anyhow::Result;
use clap::{crate_authors, crate_description, crate_name, crate_version, App as ClapApp, Arg};
use md_designer::app::App;
fn main() -> Result<()> {
// setup clap
let clap = ClapApp::new(crate_name!())
.author(crate_authors!())
.versi... |
use clap::{App, Arg};
use kvs::KvStore;
use kvs::{KvsError, Result};
use std::process::exit;
use std::env::current_dir;
fn main() -> Result<()> {
let matches = App::new(env!("CARGO_PKG_NAME"))
.version(env!("CARGO_PKG_VERSION"))
.author(env!("CARGO_PKG_AUTHORS"))
.about(env!("CARGO_PKG_DESC... |
use crate::rcc_clock_settings::{clock_source_selecting, RCC_CR};
use core::ptr;
#[cfg(feature = "enable-debug")]
use cortex_m_semihosting::hprintln;
// ------ RCC PLL configuration register (RCC_PLLCFGR) ---------
pub const RCC_PLLCFGR: u32 = RCC_CR + 0x04; // page 226
// bit0 ~ bit5
pub const RCC_PLLCFGR_PLL_M_STAR... |
use std::io::Read;
use encoding::DecoderTrap::Replace;
use encoding::Encoding;
use encoding::all::WINDOWS_31J;
use if_let_return::if_let_some;
use crate::dictionary::DictionaryWriter;
use crate::errors::{AppError, AppResultU};
use crate::loader::Loader;
use crate::parser::eijiro::parse_line;
use crate::str_utils::{s... |
//! # "Normal" aligned versions of the FDB structures
use crate::generic;
/// The header at the start of the file
pub type Header = generic::Header<u32, u32>;
/// The entry in the table array
pub type TableHeader = generic::Table<u32>;
/// The definition of the data
pub type TableDefHeader = generic::TableDef<u32, u3... |
use chom_ir::Namespace;
pub struct Scope<T: Namespace + ?Sized> {
/// Current module.
module: u32,
/// Loop label.
label: Option<T::Label>,
/// `self` variable.
this: Option<T::Var>,
/// Function marker.
function_marker: Option<chom_ir::function::Marker>
}
impl<T: Namespace + ?Sized> Clone for Scope<T> {
... |
//! Soft server to handle soft client
mod connection;
pub mod users;
use APP_INFO;
use app_dirs::{AppDataType, app_dir};
use error::*;
use self::connection::SoftConnection;
use self::users::Users;
use std::io::{Read, Write};
use std::sync::mpsc;
use std::sync::Arc;
use std::thread;
use std::time::Duration;
/// Soft s... |
use std::env;
use std::fs::File;
use std::io::BufRead;
use std::io::BufReader;
/**
* 自作catコマンド
* rsgrepを参考に作成する。
* rsgrepはfileを開き、バッファに入れ、それをパターンマッチした結果を返していた。
* そのため、パターンマッチをせず、そのまま標準出力する。
*/
// 使い方
fn usage() {
println!("usage : cat FILENAME");
}
fn main() {
// envモジュールのargs関数で、引数を取得
let filename = ... |
use crate::PeerId;
use serde::{
de::{self, Deserializer, Visitor},
ser::Serializer,
};
use std::fmt;
use std::str::FromStr;
struct PeerIdVisitor;
impl<'de> Visitor<'de> for PeerIdVisitor {
type Value = String;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
write!(formatt... |
#![feature(allow_internal_unstable)]
#![feature(core_intrinsics)]
#![feature(const_fn)]
#![feature(asm)]
#![feature(global_asm)]
#![feature(decl_macro)]
#![feature(never_type)]
#![feature(extern_prelude)]
#![feature(optin_builtin_traits)]
#![feature(nll)]
#![feature(allocator_api)]
#![feature(alloc)]
#![feature(raw_vec... |
#[doc = "Register `RX_PAYSZR` reader"]
pub type R = crate::R<RX_PAYSZR_SPEC>;
#[doc = "Field `RXPAYSZ` reader - Rx payload size received This bitfield contains the number of bytes of a payload (including header but excluding CRC) received: each time a new data byte is received in the UCPD_RXDR register, the bitfield va... |
extern crate clap;
extern crate time;
use clap::{Arg, App, SubCommand};
use facteur::Facteur;
mod task;
mod facteur;
fn main() {
let directory_arg = Arg::with_name("DIRECTORY")
.help("The directory of your web app")
.required(true)
.index(1);
let git_arg = Arg::with_name("GIT_REPOSIT... |
use crate::{Result, Error};
use std::path::PathBuf;
pub fn get_name(path: &PathBuf) -> Result<String> {
let result = path
.components()
.last()
.ok_or(Error::LastComponentInvalid(
String::from(path.to_str().unwrap_or(""))
))?
.as_os_str()
.to_str()
... |
pub
fn str_methods() {
println!("{}", "ONE".to_lowercase());
println!("{}", "peanut".contains("nut"));
println!("{}", "ಠ_ಠ".replace("ಠ", "■"));
println!("{}", " clean\n".trim());
assert!("ONE".to_lowercase() == "one");
assert!("peanut".contains("nut"));
assert_eq!("ಠ_ಠ".replace("ಠ", ... |
extern crate hound;
use std::iter::Iterator;
use std::collections::VecDeque;
/// An iterator that maps the values of an `Iterator` using a `VecDeque` as a
/// buffer.
///
/// Usage: `Iterator.buf_map(window_size, function)`
/// Example: `(1..).buf_map(3, |buf| buf[0] + buf[1] + buf[2])`
pub struct BufMap<F, I>
wh... |
use amethyst::{
core::timing::Time,
core::transform::Transform,
ecs::prelude::{Entities, Join, Read, ReadStorage, System, WriteStorage},
};
use crate::components::Velocity;
pub struct MovementSystem;
impl<'s> System<'s> for MovementSystem {
type SystemData = (
Entities<'s>,
ReadStorag... |
extern crate core;
use std::io::Error;
use std::io::{Read, Write};
use std::{panic, process};
use std::process::{Command, Stdio};
use signal_hook::iterator::Signals;
pub const SIGINT: i32 = 2;
pub const SIGTERM: i32 = 15;
fn main() -> Result<(), Error>{
// ls_test();
// out_test();
// terminate_abort();
... |
use std::io::{self, prelude::*};
use std::error::Error;
fn pogo_jump(mut x: i32, mut y: i32) -> String {
assert_ne!((x, y), (0, 0));
dbg!(x, y);
let mut res = String::new();
while (x, y) != (0, 0) {
let px = x.abs() % 2; // parity
let py = y.abs() % 2;
if px == py {
... |
use std::cell::RefCell;
mod board;
mod board_info;
mod board_parser;
mod board_solver;
mod cell;
mod coordinate;
mod number;
mod region;
pub const BOARD_WIDTH: u8 = 9;
pub fn solve(sudoku_content: String, context: &mut SolveContext) {
let mut board = Board::parse(sudoku_content);
board_solver::solve(&mut bo... |
//! This module contains all the models
//! every model has multiple versions of it
//!
//! InputModel -> Model from the GraphQL API
//! NewModel -> InputModel with timestamp, consumed by diesel
//! UpdateModel -> Similar to InputModel but with Option<T> only
//! Model -> Model with all data
use diesel::PgConnection;
... |
#[repr(C)]
#[derive(Default)]
pub struct Color {
pub r: f32,
pub g: f32,
pub b: f32,
pub a: f32,
}
#[rust_saber::hook(0x12DC59C)]
pub unsafe fn get_color(orig: GetColorFn, this: *mut std::ffi::c_void) -> Color {
let orig_color = orig(this);
Color {
r: 1.0,
g: orig_color.g,
... |
use arkecosystem_client::api::models::fee::FeeStatistics;
use arkecosystem_client::api::models::transaction::TransactionFeesCore;
use serde_json::Value;
use std::str::FromStr;
pub fn assert_configuration_fees(actual: &TransactionFeesCore, expected: &Value) {
assert_eq!(actual.transfer, expected["transfer"].as_u64(... |
#[macro_use]
extern crate derive_builder;
#[macro_use]
extern crate error_chain;
#[macro_use]
extern crate serde_derive;
extern crate serde;
extern crate serde_json;
extern crate chrono;
pub mod errors;
pub mod protocol;
pub mod widgets;
use errors::*;
use std::fmt;
use std::thread::sleep;
use std::time::Duration;
p... |
/*
---String Letter Counting---
Take an input string and return a string that is made up of the number of occurences of each
english letter in the input followed by that letter, sorted alphabetically. The output string
shouldn't contain chars missing from input (chars with 0 occurence); leave them out.
An empty string... |
//! Contains endpoints for accessing accounts and related information.
use error::Result;
use std::str::FromStr;
use stellar_resources::Account;
use stellar_resources::Transaction;
use super::{Body, EndPoint, Order, Records};
use http::{Request, Uri};
/// An endpoint that accesses a single accounts details.
#[derive(D... |
#[allow(unused_imports)]
use nom::*;
use ast::Ast;
use operator::Operator;
use s_expression::SExpression;
use parser::operators::*;
use parser::utilities::no_keyword_token_group;
use parser::identifier::identifier;
named!(pub sexpr<Ast>,
alt_complete!(
do_parse!(
lhs: no_keyword_token_group >... |
use crate::io::*;
use crate::layers::loss_layer::*;
use crate::layers::*;
use crate::model::rnn::*;
use crate::optimizer::{NewSGD, SGD};
use crate::trainer::RnnlmTrainer;
use crate::trainer::Trainer;
use crate::util::*;
use std::collections::HashMap;
pub fn train() {
const WORDVEC_SIZE: usize = 100;
const HIDD... |
// delete before releasing !!
#![allow(unused_imports, unused_variables, unused_mut, unused_parens)]
#![allow(dead_code)]
#![warn(rust_2018_compatibility)]
#![warn(rust_2018_idioms)]
// Enable before releasing!
// #![deny(missing_docs, warnings)]
// TODO: Errorhandling! Seperate error module?
// TODO: Reduce file ope... |
// Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
use std::time::Instant;
fn main() {
let now = Instant::now();
println!("result: {:?}, time: {:?}", e6(), now.elapsed());
}
fn e6() -> usize {
let sum_of_squares: usize = (1..101).fold(... |
use std::collections::HashMap;
use std::fs::File;
use std::io;
use std::io::Read;
use std::str::FromStr;
use lazy_static::lazy_static;
use regex::Regex;
use crate::solution::ProblemSolution;
pub struct Solution {}
impl ProblemSolution for Solution {
fn name(&self) -> &'static str {
return "problem_04";
... |
//! # Metrics
//!
//! `metrics` provides various evaluation metrics.
extern crate ndarray;
extern crate ndarray_linalg;
use ndarray::{ArrayBase, Data, Ix1, NdFloat};
/// Calculate the mean squared error (L2 loss) between two arrays.
pub fn mean_squared_error<T, S1, S2>(
truth: &ArrayBase<S1, Ix1>,
... |
use std::error::Error;
use ndarray::prelude::*;
use rust_ml::neuron::{
activations::{leaky_relu, linear},
layers::Layer,
losses::cce,
networks::Network,
optimizers::{Optimizer, SGD},
transfers::dense,
};
const MNIST_TRAIN_PATH: &str = "/home/tom/Documents/Datasets/MNIST/mnist_train.csv";
cons... |
/*!
```rudra-poc
[target]
crate = "alg_ds"
version = "0.3.1"
[test]
cargo_flags = ["--release"]
[report]
issue_url = "https://gitlab.com/dvshapkin/alg-ds/-/issues/1"
issue_date = 2020-08-25
rustsec_url = "https://github.com/RustSec/advisory-db/pull/362"
rustsec_id = "RUSTSEC-2020-0033"
[[bugs]]
analyzer = "Manual"
g... |
#![doc = "generated by AutoRust 0.1.0"]
#![allow(unused_mut)]
#![allow(unused_variables)]
#![allow(unused_imports)]
use crate::models::*;
use reqwest::StatusCode;
use snafu::{ResultExt, Snafu};
pub mod location {
use crate::models::*;
use reqwest::StatusCode;
use snafu::{ResultExt, Snafu};
pub async fn ... |
use perceptron::couche::*;
use perceptron::neurone::*;
use perceptron::learning::*;
use rand::{Rng};
use rand;
pub fn perceptron(neurone_nb : i32, couche_nb: i32, neurones_output: i32){
let mut cstart = Couche::new();
let mut cinter = Couche::new();
let mut cend = Couche::new();
for _i in 0..neurone_... |
#![doc = "generated by AutoRust 0.1.0"]
#![allow(non_camel_case_types)]
#![allow(unused_imports)]
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct StsTokenResponseMessage {
#[serde(rename = "AccessToken")]
pub access_token: String,
}
|
/*
Copyright 2016 Robert Lathrop
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, softwar... |
//! This module contains a [`Concat`] primitive which can be in order to combine 2 [`Table`]s into 1.
//!
//! # Example
//!
//! ```
//! use tabled::{Table, settings::Concat};
//! let table1 = Table::new([0, 1, 2, 3]);
//! let table2 = Table::new(["A", "B", "C", "D"]);
//!
//! let mut table3 = table1;
//! table3.with(Co... |
use crate::BLOCK_SIZE;
// Super Block
#[allow(non_camel_case_types)]
#[derive(Debug, Copy, Clone)]
#[repr(C)]
pub struct superblock {
pub magic: u32, // Must be FSMAGIC
pub size: u32, // Size of file system image (blocks)
nblocks: u32, // Number of data blocks
pub ninodes: u32, // ... |
// Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#![feature(async_await)]
use failure::{Error, ResultExt};
use fuchsia_async as fasync;
use fuchsia_framebuffer::{Config, Frame, FrameBuffer, PixelFormat, ... |
use hyper::client::HttpConnector;
use hyper::header::{HeaderName, HeaderValue};
use hyper::{Body, Client, Request, Response};
use hyper_tls::HttpsConnector;
use std::collections::HashMap;
use std::sync::Arc;
type Resp<T> = Result<T, Box<dyn std::error::Error + Send + Sync>>;
pub type HyperClient = Arc<Client<HttpsCo... |
fn main(){
let mut num = 600851475143i64;
let mut i = 2;
while num != 1{
if num % i == 0 {
num /= i
} else { i += 1}
}
println!("Euler Problem #3");
println!("Problem:\n\tWhat is the largest prime factor of the number 600851475143 ?")
println!("Solution:\n\t{}", ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.