text stringlengths 8 4.13M |
|---|
fn get_char() -> char {
b'!' as char
}
fn main() {
let c: u8 = get_char() as u8;
println!("{}", c);
}
|
// TODO: Remove this when announces are implemented
#![allow(unused)]
use bip_bencode::{Bencode, BencodeConvert, Dictionary};
use bip_util::bt::{NodeId, InfoHash};
use message;
use message::request::{self, RequestValidate};
use error::DhtResult;
const PORT_KEY: &'static str = "port";
const IMPLIED_PORT_KEY: &'static... |
#![cfg_attr(feature="clippy", feature(plugin))]
#![feature(lang_items)]
#![feature(const_fn)]
#![feature(unique)]
#![feature(asm)]
#![feature(abi_x86_interrupt)]
#![feature(const_unsafe_cell_new)]
#![feature(const_unique_new)]
#![no_std]
extern crate rlibc;
extern crate volatile;
extern crate spin;
extern crate multib... |
pub use time::{get_time, Timespec, Duration};
pub use self::ticker::{Ticker, Tick, Stop};
mod ticker;
use std::io::{Write, Read, Error, ErrorKind};
use util::binary_io::{BinaryWrite, BinaryRead, BinaryError};
use util::json::{FromJson, JsonError, Json};
impl BinaryWrite for Timespec {
fn binary_write(&self, writ... |
pub(crate) fn prompt() -> crate::Result<u8> {
print!("{}", crate::prompt(std::env::var("status").map_err(|_| ()).and_then(|v| v.parse().map_err(|_| ())).unwrap_or(0) != 0));
Err(crate::Error::NoStatusChange)
}
|
//! Legends of Runeterra deck encoder and decoder.
//!
//! # Usage
//!
//! The encoding and decoding can be done by directly calling the static functions found on [`Encoder`].
//!
//! [`Encoder`]: encoder/struct.Encoder.html
//!
//! # Examples
//!
//! Obtain a deck from the provided code:
//!
//! ```
//! use lordeckcod... |
use super::{Ty, TyKind, Substitution, Type};
use std::collections::HashSet;
use crate::util::Counter;
use std::fmt::{self, Formatter, Display};
#[derive(PartialEq, Debug, Clone)]
pub(crate) struct TyScheme {
ty: Ty,
forall: HashSet<u64>,
}
impl TyScheme {
pub fn new(ty: Ty, forall: HashSet<u64>) -> Self {... |
use crate::inner_prelude::*;
#[derive(Copy, Clone)]
pub struct Bot {
pos: Vec2<i32>,
num: usize,
}
pub fn handle_bench_inner(scene: &mut bot::BotScene<Bot>, height: usize) -> f64 {
let instant = Instant::now();
let bots = &mut scene.bots;
let prop = &scene.bot_prop;
let mut bb = bbox_helper::... |
struct Solution;
impl Solution {
pub fn remove_kdigits(num: String, k: i32) -> String {
if num.is_empty() {
return String::from("0");
}
let mut cs = num.chars().collect::<Vec<char>>();
let mut count = 0;
while count < k {
let len = cs.len();
... |
use nalgebra::Vector3;
use num_traits::Zero;
use crate::bsdf::helpers::fresnel::FresnelDielectric;
use crate::bsdf::helpers::microfacet_distribution::{
MicrofacetDistribution, TrowbridgeReitzDistribution,
};
use crate::bsdf::lambertian::Lambertian;
use crate::bsdf::microfacet_reflection::MicrofacetReflection;
use ... |
const MAX: u64 = 4000000000;
fn main() {
let mut a: u64 = 1;
let mut b: u64 = 1;
let mut sum: u64 = 0;
loop {
if b % 2 == 0 { sum += b }
let n = a + b;
if n >= MAX { break; }
a = b;
b = n;
}
println!("{}", sum);
}
|
use crate::player::{ConnectStream, PlaybackMode, PlayerInternal, Song, State};
use crate::prelude::*;
use crate::settings;
use crate::spotify_id::SpotifyId;
use crate::utils;
use crate::Uri;
use anyhow::Result;
use std::sync::Arc;
use tokio::sync::RwLock;
/// Future associated with driving audio playback.
pub(super) s... |
use rand::prelude::*;
use std::thread::sleep;
use std::{thread, time};
#[macro_use] extern crate text_io;
pub struct Player {
head: bool,
body: bool,
left_arm: bool,
right_arm: bool,
left_leg: bool,
right_leg: bool,
}
impl Player {
pub fn new() -> Player {
Player {head : false, bod... |
use graphics::text::Text;
use graphics::{DrawState, Transformed};
use opengl_graphics::GlyphCache;
use opengl_graphics::{GlGraphics, TextureSettings};
use piston::input::{Button, Event, Input, Key, RenderArgs, UpdateArgs};
use piston::{ButtonArgs, ButtonState, Loop};
use piston_window::PistonWindow as Window;
use rand:... |
use crate::lib_surface::*;
use crate::lib_2d::*;
use sdl2::pixels::Color;
#[derive(Copy, Clone)]
pub struct Matrix3D(pub [[f64;4];4]);
#[derive(Copy, Clone)]
pub struct Point3D([f64;4]);
#[derive(Copy, Clone)]
pub struct Triangle3D(pub Point3D, pub Point3D, pub Point3D);
pub struct Plan3D{//a*x+b*y+c*z=d
pub a: f... |
use std::collections::HashMap;
extern crate time;
const RES_BEFORE: i32 = 2;
fn fuzzy_hour(time: time::Tm) -> String {
let translate: HashMap<i32, &str> = [
(1, "Eins"),
(2, "Zwei"),
(3, "Drei"),
(4, "Vier"),
(5, "Fünf"),
(6, "Sechs"),
(7, "Sieben"),
... |
use crate::imp::structs::linked_m::{LinkedMap, LinkedMapUnsafeIter};
use crate::imp::structs::rust_list::MutItem;
use std::marker::PhantomData;
use crate::imp::structs::list_def_obj::ListDefObj;
use crate::imp::structs::root_obj::RootObject;
use crate::imp::intf::mitem::MItemPtr;
///&mut LinkedMapからしか使えない。
/// &Linked... |
#![feature(stmt_expr_attributes, proc_macro_hygiene)]
extern crate emit;
fn main() {
tracing_subscriber::fmt().init();
emit::info!("something went wrong ({#[emit::as_display] err: 42})");
}
|
use syntax::ext::base::{ExtCtxt, MacResult, MacEager};
use syntax::parse::token;
use syntax::util::small_vector::SmallVector;
use syntax::ext::quote::rt::ExtParseUtils;
use utils::*;
pub fn build_simple_enum(cx: &mut ExtCtxt,
name: token::InternedString,
ty: FieldType... |
extern crate gstreamer as gst;
use gst::prelude::*;
extern crate gstreamer_video as gst_video;
extern crate gstreamer_app as gst_app;
extern crate glib;
extern crate failure;
use failure::Error;
use std::env;
use std::error::Error as StdError;
#[macro_use]
extern crate failure_derive;
#[derive(Debug, Fail)]
#[fail... |
pub mod config;
pub mod sensor_data;
pub mod sensor_type;
|
use crate::aoc::read_input;
use std::collections::HashMap;
use std::collections::hash_map::RandomState;
use chrono::{NaiveDateTime, Timelike};
use regex::Regex;
use lazy_static::*;
use std::cmp;
#[derive(Debug)]
enum Action {
BeginsShift(u32),
FallsAsleep(u32),
WakesUp(u32)
}
#[derive(Debug)]
struct Reco... |
struct Solution;
impl Solution {
fn total_hamming_distance(nums: Vec<i32>) -> i32 {
let mut res = 0;
let n = nums.len();
for i in 0..32 {
let mut count = 0;
for &x in &nums {
if x & 1 << i != 0 {
count += 1;
}
... |
//! This file is for small helpers & utilities that aren't exported by the library.
use acl_sys::acl_free;
use std::ffi::CString;
use std::io;
use std::os::raw::c_void;
use std::os::unix::ffi::OsStrExt;
use std::path::Path;
/// NB! Unix-only
pub(crate) fn path_to_cstring(path: &Path) -> CString {
CString::new(path... |
use crate::prelude::*;
#[system]
#[read_component(Point)]
#[read_component(Name)]
#[read_component(FieldOfView)]
#[read_component(Player)]
pub fn pathtip(
ecs: &SubWorld,
#[resource] map: &Map,
#[resource] mouse_pos: &Point,
#[resource] camera: &Camera
) {
let mut fov = <&FieldOfView>::query().filt... |
use url::{Url};
/**
*
* @date 2020/12/2
*/
fn main() {
let full = "http://llever.com/rust-cookbook-zh/web/url.zh.html?a=123";
let parsed = Url::parse(full).unwrap();
println!("{:?}", parsed.scheme());
println!("{:?}", parsed.host());
println!("{:?}", parsed.path());
println!("{:?}", parsed.path_... |
extern crate js_sys;
//extern crate cfg_if;
extern crate wasm_bindgen;
use js_sys::Math;
mod utils;
use std::fmt;
use wasm_bindgen::prelude::*;
extern crate web_sys;
use web_sys::console;
pub struct Timer<'a> {
name: &'a str,
}
impl<'a> Timer<'a> {
pub fn new(name: &'a str) -> Timer<'a> {
console::ti... |
fn is_valid(s: String) -> bool {
let mut stack = Vec::new();
for c in s.chars() {
match c {
'(' | '[' | '{' => stack.push(c),
')' => if stack.pop() != Some('(') { return false; },
']' => if stack.pop() != Some('[') { return false; },
'}' => if stack.pop()... |
use std::ops::*;
use std::fmt;
use num;
use super::super::pbrt::Float;
use super::Vector2;
use super::Point3;
pub type Point2f = Point2<Float>;
pub type Point2i = Point2<i32>;
/// A 2D Point.
#[derive(Debug, Default, Copy, Clone, PartialEq, PartialOrd)]
#[repr(C)]
pub struct Point2<T> {
pub x: T,
pub y: T
}
... |
use aoc::*;
#[allow(dead_code)]
pub fn day3(input : &String) -> () {
let parsed = to_char_vec(input);
println!("Part1: {}", day3_1(&parsed));
println!("Part2: {}", day3_2(&parsed));
}
pub fn day3_1(input : &Vec<Vec<char>>) -> u32 {
let line_len = input[0].len();
let mut gamma : u32 = 0;
let mut epsilon : u32 = ... |
#[test]
fn arity() {
let sum = |a: i32, b: i32| a + b;
let result = sum(1, 2);
assert_eq!(result, 3);
}
|
#[cfg(not(any(target_os = "redox", target_os = "wasi")))]
#[test]
fn test_utimensat() {
use rustix::fs::{openat, statat, utimensat, AtFlags, Mode, OFlags, Timespec, Timestamps, CWD};
let tmp = tempfile::tempdir().unwrap();
let dir = openat(
CWD,
tmp.path(),
OFlags::RDONLY | OFlags::... |
use std::str::FromStr;
use crate::issues::jira_issue::JiraIssue;
#[derive(Deserialize, Debug, Clone)]
pub struct JiraIssues {
pub issues: Vec<JiraIssue>,
pub total: u16,
}
impl FromStr for JiraIssues {
type Err = failure::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let output = ... |
use vizia::*;
fn main() {
Application::new(|cx|{
VStack::new(cx, |cx| {
Label::new(cx, "Label 1")
.width(Pixels(100.0))
.height(Pixels(30.0))
.background_color(Color::blue());
Label::new(cx, "Label 2")
.width(Pixels(... |
use linked_hash_map::LinkedHashMap;
use std::{
collections::HashSet,
fmt::{Display, Error, Formatter},
str::FromStr,
};
pub const OTHER_KEY: &str = "Value";
/// The header of the VCF file
#[derive(Debug)]
pub struct Header {
/// The VCF version. Captures the string that comes right after "##fileformat... |
//!Representation of the B2C Api
//!
//! This API enables Business to Customer (B2C) transactions between a company and customers who are the end users of
//! its products or services. Use of this API requires a valid and verified B2C M-Pesa Short code.
//!
//! testing url: POST https://sandbox.safaricom.co.ke/mpesa/b... |
extern crate util;
fn move_point(x: i32, y: i32, value: i32, dir: i32) -> (i32, i32) {
return match dir {
270 => (x, y + value), // North
90 => (x, y - value), // South
0 => (x + value, y), // East
180 => (x - value, y), // West
_ => (x, y)
}
}
fn get_direction(c: char)... |
use std::fs::File;
use log::info;
use crate::network::{geo, GraphBuilder, StreetType};
mod pbf {
pub use osmpbfreader::reader::OsmPbfReader as Reader;
pub use osmpbfreader::OsmObj;
}
//------------------------------------------------------------------------------------------------//
pub struct Parser;
impl... |
// Copyright 2021 The BMW Developers
//
// 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... |
use num_enum::TryFromPrimitive;
use crate::tools::un_pack_tool::{parse_long_int, parse_string, parse_byte, parse_short_int, unpack_var_int};
use crate::tools::pack_tool::{pack_long_int, pack_string, pack_byte, pack_short_int, pack_var_int};
pub mod reason_code;
pub mod un_pack_property;
pub mod pack_property;
#[deriv... |
use crate::common::*;
pub(crate) struct TestEnvBuilder {
args: Vec<OsString>,
current_dir: Option<PathBuf>,
err_style: bool,
input: Option<Box<dyn InputStream>>,
out_is_term: bool,
tempdir: Option<TempDir>,
use_color: bool,
}
impl TestEnvBuilder {
pub(crate) fn new() -> TestEnvBuilder {
TestEnvBui... |
use url::percent_encoding::percent_decode;
use iron::prelude::*;
use iron::status;
use iron::Url;
use iron::headers::ContentType;
use iron::middleware::Handler;
use iron::modifiers::Header;
use iron::modifiers::Redirect;
use mount;
use url;
use urlencoded::UrlEncodedQuery;
use pulldown_cmark::{html, Parser};
use std... |
use crate::{
device::{Device, FeedCallback, MixContext, NativeSample},
error::SoundError,
};
use coreaudio_sys::*;
use std::{ffi::c_void, mem::size_of};
pub struct CoreaudioSoundDevice {
/// Give fixed memory location
inner: Box<Inner>,
}
unsafe impl Send for CoreaudioSoundDevice {}
struct Inner {
... |
//@compile-flags: -Zmiri-tree-borrows
// copy_nonoverlapping works regardless of the order in which we construct
// the arguments.
pub fn main() {
test_to_from();
test_from_to();
}
fn test_to_from() {
unsafe {
let data = &mut [0u64, 1];
let to = data.as_mut_ptr().add(1);
let from =... |
use crate::config::*;
use std::collections::{BTreeMap, BTreeSet};
use std::sync::{Arc, RwLockWriteGuard, RwLockReadGuard};
use crate::translation::{Translation, VirtualReg, register_map_policy};
use dynasmrt::AssemblyOffset;
use std::sync::Mutex;
use crate::error::{self, ExecError};
use bit_field::BitField;
use crate::... |
// Copyright 2015-2019 Parity Technologies (UK) Ltd.
// This file is part of Parity Ethereum.
// Parity Ethereum is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at yo... |
use std::thread;
use std::time::Duration;
async fn foo(id: i32) {
for i in 0..10 {
println!("thread #{} count {}.", id, i);
thread::sleep(Duration::from_millis(1000));
}
}
async fn sub() {
foo(10).await;
foo(20).await;
foo(30).await;
}
/*
fn main() {
println!("program start")... |
//! Typestates to express ownership and thread safety of Godot types.
/// Marker that indicates that a value currently only has a
/// single unique reference.
///
/// Using this marker causes the type to be `!Sync`.
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Default)]
pub struct Unique(std::mar... |
use std::collections::BTreeSet;
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
use std::fmt;
pub use self::Thing::*;
pub fn solve(){
const INPUT : &str = include_str!("../../inputs/2016/11");
println!("WARNING! this is kind of very slow :(");
let floors : Vec<BTreeSet<Thin... |
use crate::hook;
use proc_macro2::TokenStream;
use syn::{parse::Parse, punctuated::Punctuated, token::Comma, Expr, Ident};
pub struct Args;
impl Parse for Args {
fn parse(_: syn::parse::ParseStream) -> syn::Result<Self> {
Ok(Args)
}
}
pub struct RenameHookTokens {
pub args: TokenStream,
pub e... |
mod codeblock;
mod context;
mod markdown;
mod shortcode;
mod table_of_contents;
use errors::Result;
pub use context::RenderContext;
use markdown::markdown_to_html;
pub use shortcode::render_shortcodes;
pub use table_of_contents::Heading;
pub fn render_content(content: &str, context: &RenderContext) -> Result<markdow... |
pub struct QuadTree<'a, T> {
capacity: u32,
depth: u32,
max_depth: u32,
bounds: Bounds,
elements: Vec<T>,
children: Option<[Box<QuadTree<'a, T>>; 4]>,
}
/// A bounded area represented by x, y, width, and height.
#[derive(PartialEq, Eq, Debug)]
pub struct Bounds {
/// x coordinate
pub x:... |
use std::{
error::Error,
io::{stdout, Write},
time::Duration,
};
use crossterm::{
self,
cursor::{Hide, MoveTo, MoveToColumn, MoveToNextLine, RestorePosition, SavePosition, Show},
event::{self, Event, KeyCode, KeyEvent, KeyModifiers},
execute,
style::Print,
terminal::{self, Clear, Cl... |
//extern crate termion;
// todo: handle sigwinch https://crates.io/crates/signal-hook
use std::convert::TryFrom;
use std::io::{stdin, stdout, Stdout, Write};
use termion::color;
use termion::event::Key;
use termion::input::TermRead;
use termion::raw::{IntoRawMode, RawTerminal};
use std::fs::File;
use std::io::prelud... |
use clap::{App, Arg, ArgMatches};
use serde_json::Value;
use solana_clap_utils::{
input_parsers::value_of,
input_validators::{is_hash, is_pubkey_sig},
offline::{BLOCKHASH_ARG, SIGNER_ARG, SIGN_ONLY_ARG},
};
use solana_client::rpc_client::RpcClient;
use solana_sdk::{fee_calculator::FeeCalculator, hash::Hash,... |
use crate::consts::WG_GENL_NAME;
use libc::{IFLA_INFO_KIND, IFLA_LINKINFO};
use neli::consts::{Arphrd, Ifla, NlmF, Rtm};
use neli::err::SerError;
use neli::nl::Nlmsghdr;
use neli::nlattr::Nlattr;
use neli::rtnl::Ifinfomsg;
use neli::rtnl::Rtattr;
use neli::Nl;
use neli::StreamWriteBuffer;
const RTATTR_HEADER_LEN: libc... |
use fp_core::foldable::*;
/*
// Check out foldable.rs in fp-core
pub trait Foldable<A, B>: HKT<A, B> {
fn reduce<F>(b: B, ba: F) -> <Self as HKT<A, B>>::Target
where
F: FnOnce(B, A) -> (B, B);
}
*/
#[test]
fn foldable_example() {
let k = vec![1, 2, 3];
let result = k.reduce(0, |i, acc| i + acc... |
#[macro_export]
macro_rules! merge_modules {
(mod $ident:ident { $($module:path;)* }) => {
fn $ident<T>() -> $crate::module::Module<T> {
let mut module = $crate::module::Module::new();
$(
module.merge_module($module());
)*
module
}
... |
// Copyright (c) Starcoin
// SPDX-License-Identifier: Apache-2.0
use criterion::{measurement::Measurement, BatchSize, Bencher};
use proptest::{
collection::vec,
strategy::{Strategy, ValueTree},
test_runner::TestRunner,
};
use starcoin_crypto::HashValue;
use starcoin_language_e2e_tests::account::AccountDat... |
extern crate libc;
use libc::c_int;
use std::ffi::CString;
const BOARDW: i32 = 1307;
// 875 + 75 (75 for buttons) = 950
const BOARDH: i32 = 950;
static mut XPAD: i32 = 0;
static mut YPAD: i32 = 0;
#[no_mangle]
pub extern "C" fn get_countryliststr() -> CString {
let countrystrings = PARSED_COUNTRIES.iter()
... |
#[derive(PartialEq, Debug)]
pub enum Direction {
North,
East,
South,
West,
}
pub struct Robot {
position: (i32, i32),
direction: Direction,
}
impl Robot {
pub fn new(x: i32, y: i32, direction: Direction) -> Self {
Self {
position: (x, y),
direction,
... |
// #![deny(missing_docs)]
pub mod brb_membership;
pub use crate::brb_membership::{Ballot, Generation, Reconfig, State, Vote, VoteMsg};
pub mod error;
pub use crate::error::Error;
pub mod actor;
pub use actor::{Actor, Sig, SigningActor};
pub use signature;
|
use pix_engine::prelude::*;
struct HelloWorld;
impl PixEngine for HelloWorld {
// Set up any state or resources before starting main event loop.
fn on_start(&mut self, s: &mut PixState) -> PixResult<()> {
s.background(220);
Ok(())
}
// Main render loop. Called as often as possible, or... |
// b^e % m
#[allow(dead_code)]
pub fn mod_ex(b: u128, e: u128, m: u128) -> u128 {
if e == 0 {
return 1;
}
if b == 0 || b == 1 {
return b;
}
let mut c = mod_ex(b, e / 2, m);
c = (c * c) % m;
if e % 2 == 1 {
c = (c * b) % m;
}
return c;
}
#[cfg(test)]
mod tests... |
uucore_procs::main!(uu_base64); // spell-checker:ignore procs uucore
|
use std::collections::HashMap;
use std::convert::TryFrom;
use rusqlite::{Connection, Error, NO_PARAMS, Result as SR};
use rusqlite::types::ToSql;
use serde_json::Value;
use crate::datastructures::{Credential, CryptographicKeys, Schema, SchemaValueType};
pub trait ConnectionRestMapping {
type Target;
// SQLi... |
/*
* MIT License
*
* Copyright (c) 2017 Robert Swain <robert.swain@gmail.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rig... |
use super::{z_coin_errors::*, CheckPointBlockInfo, ZcoinConsensusParams};
use crate::utxo::rpc_clients::{NativeClient, UtxoRpcClientOps, NO_TX_ERROR_CODE};
use async_trait::async_trait;
use common::executor::{spawn_abortable, AbortOnDropHandle, Timer};
use common::log::{debug, error, info, LogOnError};
use common::{asy... |
#[allow(unused_imports)]
use serde_json::Value;
#[derive(Debug, Serialize, Deserialize)]
pub struct DiagnosticsGatherSettingsExtended {
/// Use ESRS for upload of gather.
#[serde(rename = "esrs")]
pub esrs: Option<bool>,
#[serde(rename = "ftp_upload")]
pub ftp_upload: Option<bool>,
/// Alternat... |
#[doc = "Register `SCK` reader"]
pub struct R(crate::R<SCK_SPEC>);
impl core::ops::Deref for R {
type Target = crate::R<SCK_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<crate::R<SCK_SPEC>> for R {
#[inline(always)]
fn from(reader: crate::R<SCK_SPEC>) ... |
use utils::bignum::{Int512, Uint512, Uint256, Zero, One};
use std::ops::{Add, Mul};
use std::fmt;
/// Elliptic curve over finite field.
pub struct EllipticCurve<'a> {
/// The modulo that defines finite field.
modulo: Uint256,
/// The `a` and `b` curve parameters.
params: (Uint256, Uint256),
/// Generation point... |
use std::io::Cursor;
use std::result::Result as StdResult;
use failure::{Error as FailureError, Fail};
use rocket::{
http::{ContentType, Status},
response::Responder,
Request, Response,
};
use rocket_contrib::{
json::{Json, JsonValue},
templates::Template,
};
pub type Result<T> = StdResult<T, Fail... |
// Copyright (c) The Libra Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::write_set::WriteSet;
use canonical_serialization::{
CanonicalDeserializer, CanonicalSerializer, SimpleDeserializer, SimpleSerializer,
};
use proptest::prelude::*;
use proto_conv::test_helper::assert_protobuf_encode_decod... |
// Copyright 2019 Peter Williams <pwil3058@gmail.com> <pwil3058@bigpond.net.au>
///! This module provides floating point types that represent angles (in radians) restricted to the
///! confines of a circle (i.e. their value is guaranteed to be in the range -PI to +PI).
use std::{
cmp::{Ordering, PartialEq, PartialO... |
#![cfg(windows)]
use bytes::{Buf, BufMut};
use futures::{Async, Future, Poll};
use hyper::client::connect::{Connect, Connected, Destination};
use mio::Ready;
use mio_named_pipes::NamedPipe;
use tokio_io::{AsyncRead, AsyncWrite};
use tokio_reactor::PollEvented;
use winapi::um::winbase::*;
use std::fmt;
use std::fs::Op... |
pub fn run() {
let bytes = include_bytes!("input.txt");
let mut polymer = Vec::new();
polymer.extend_from_slice(&bytes[..]);
polymer.pop(); // remove trailing '\n'
let tables = CaseTables::new();
let best = (b'a' ..= b'z').into_iter().map(|problem| {
let better_poly: Vec<u8> = polymer.clone().into_i... |
use proc_macro2::{Ident, Span, TokenStream};
use quote::quote;
use syn::{Error, Field, Fields, Result};
use super::{attr, Var, VarId};
use attr::{has_storage_attr, StructAttr};
use crate::{PrimType, Struct, Type};
pub fn expand(strukt: &Struct, attrs: &[StructAttr], must_mock: bool) -> Result<TokenStream> {
deb... |
// This file is part of Substrate.
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// 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.a... |
use std::cmp;
impl Solution {
pub fn partition_disjoint(nums: Vec<i32>) -> i32 {
let N = nums.len();
let mut max_arr = vec![i32::MIN; N];
let mut min_arr = vec![i32::MAX; N];
for i in 0..N {
if i == 0 {
max_arr[0] = nums[0];
}
... |
// This file is part of Substrate.
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// 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.a... |
use std::{cmp::Ordering, io};
use parser::PacketData;
mod parser;
mod scanner;
impl Ord for PacketData {
fn cmp(&self, other: &Self) -> Ordering {
match (self, other) {
(PacketData::Int(v1), PacketData::Int(v2)) => v1.cmp(v2),
(PacketData::List(items1), PacketData::List(items2)) =... |
//!
//! Add Two Numbers
//!
//! https://leetcode.com/problems/add-two-numbers/
//!
//! You are given two non-empty linked lists representing two non-negative integers.
//!
//! The digits are stored in reverse order and each of their nodes contain a single digit.
//!
//! Add the two numbers and return it as a linked l... |
#[macro_export]
macro_rules! c_try {
($expr:expr) => {{
let res: Result<_, _> = $expr;
match res {
Ok(val) => val,
Err(err) => {
crate::error::update_last_error(err);
return None;
}
}
}};
($expr:expr, $e:expr) => {{
... |
use std::collections::HashMap;
use std::cmp::Ordering;
use std::ops::Deref;
use std::ops::DerefMut;
#[derive(Debug)]
pub struct Table {
pub table: Vec<Row>,
}
#[derive(Debug)]
pub struct Row {
pub row: Vec<Cell>,
}
#[derive(Debug)]
#[derive(Eq)]
pub struct Cell {
pub name: String,
pub column_type: Ty... |
use zen_memory::Handle;
#[derive(Default)]
pub struct GameExternals<'a> {
pub insert_npc: Option<&'a dyn Fn(Handle, &str)>,
pub post_insert_npc: Option<&'a dyn Fn(Handle)>,
pub remove_npc: Option<&'a dyn Fn(Handle)>,
pub insert_item: Option<&'a dyn Fn(Handle)>,
pub create_inv_item: Option<&'a dyn Fn... |
#![deny(unused_extern_crates)]
#![warn(
missing_debug_implementations,
missing_docs,
rust_2018_idioms,
unreachable_pub
)]
//! Crypto used by Iota
#[macro_use]
extern crate crunchy;
#[macro_use]
extern crate failure;
use std::fmt;
pub use self::curl::*;
pub use self::iss::*;
pub use self::kerl::*;
m... |
use crate::input::get_lines;
pub fn run() {
let lines = get_lines("day17");
println!("part1: {}", combinations(&lines, 150));
println!("part2: {}", ways_to_use_min_containers(&lines, 150));
}
fn combinations(lines: &[String], volume: i32) -> usize {
let containers = get_containers(lines);
find_... |
//! This module includes some implementations related to top menu.
use cursive::{event::Key, menu, views::Dialog, CursiveRunnable};
/// `init_menu` adds a top menu to the given cursive instance.
pub fn init_menu(siv: &mut CursiveRunnable) {
siv.menubar()
.add_subtree(
"Operation",
... |
#![allow(unused)]
use crate::{
block_data_manager::BlockExecutionResult,
message::NetworkContext,
sync::{
error::{Error, ErrorKind},
message::{
msgid, Context, SnapshotManifestRequest, SnapshotManifestResponse,
},
state::storage::SnapshotSyncCandidate,
sy... |
use client_api;
use town;
use messages;
extern crate ws;
use itertools::Itertools;
use protobuf::Message;
use serde_json;
use std::net::{SocketAddr, UdpSocket};
use std::rc::Rc;
use std::sync::mpsc;
pub struct TownController {
arduino_socket: UdpSocket,
arduino_addr: SocketAddr,
town: Rc<town::Town>,
... |
/**
* [200] Number of Islands
*
* Given an m x n 2D binary grid grid which represents a map of '1's (land) and '0's (water), return the number of islands.
An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surround... |
//! # amethyst_locale
//!
//! Localisation binding a `Fluent` file to an Asset<Locale> via the use of amethyst_assets.
#![warn(missing_docs)]
extern crate amethyst_assets;
extern crate amethyst_core;
extern crate fluent;
#[macro_use]
#[cfg(feature = "profiler")]
extern crate thread_profiler;
#[cfg(feature = "profile... |
use std::env;
use std::fs::File;
use std::io::Read;
use std::io::Error;
use yaml_rust::yaml;
pub fn port() -> String {
env::var("PORT").unwrap_or("3000".to_string())
}
pub fn language(lang: String) -> Result<yaml::Yaml, Error> {
let mut f = File::open(["config/",lang.as_str(),".yml"].join("")).unwrap();
l... |
use cs::lang;
use lazy_static::lazy_static;
use serde_derive::{Deserialize, Serialize};
use std::collections::HashMap;
use uuid;
lazy_static! {
pub static ref QUICK_START_GUIDE_WINDOW_ID: lang::ID =
uuid::Uuid::parse_str("8d12c907-3129-40b2-af67-a6f727a1e888").unwrap();
pub static ref CHAT_TEST_WINDOW_... |
extern crate ncurses;
use ncurses::*;
fn main() {
let mut board = ['0', '1', '2', '3', '4', '5', '6', '7', '8'];
let mut x_turn = true;
let mut won;
let mut num_turns = 0;
initscr();
noecho();
printw("Tic-Tac-Toe \n");
print_board(&mut board);
loop{
printw("\n Next move... |
//! The stl-loader reads binary and ASCII STL files and converts them into `Faces`.
use std::str;
use std::vec::Vec;
use scanner_rust::Scanner;
mod errors;
pub use errors::ObjError;
mod helpers;
use helpers::{ObjVertex, ObjNormal, ObjParam, ObjFace, from_homogenous};
pub use geometry::{Face, Vec3};
/// Read in a... |
extern crate argparse;
extern crate zmq;
extern crate yaml_rust;
mod command_socket;
use argparse::{ArgumentParser, StoreTrue};
use command_socket::CommandSocket;
use yaml_rust::yaml;
use std::io::Read;
use std::fs::File;
struct Options {
status: bool,
version: bool,
version_value: String,
server_loc... |
/// Module that contains all the functions related to sessions.
use crate::db::session::add_session;
use crate::models::ServerError;
use crate::{config, err_server};
use actix_http::cookie::{Cookie, SameSite};
use actix_web::HttpMessage;
use chrono::{Duration, Utc};
use log::warn;
use time::Duration as Dur;
/// Creat... |
pub mod account;
pub mod general;
pub mod market;
pub mod rest_model;
|
#[doc = "Reader of register CNTR%s"]
pub type R = crate::R<u32, super::CNTR>;
#[doc = "Reader of field `CTN1`"]
pub type CTN1_R = crate::R<u16, u16>;
#[doc = "Reader of field `CTN`"]
pub type CTN_R = crate::R<u16, u16>;
impl R {
#[doc = "Bits 0:15 - TouchSensing Channel n-1 16-bit counter value"]
#[inline(alway... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.