text stringlengths 8 4.13M |
|---|
#![allow(non_upper_case_globals)]
use libc::c_void;
#[repr(C, packed)]
pub struct DatTable {
pub data: *mut c_void,
pub entry_size: u32,
pub entries: u32,
}
whack_vars!(init_vars, 0x00400000,
0x00513C30 => units_dat: [DatTable; 0x35];
0x005136E0 => upgrades_dat: [DatTable; 0xb];
0x005137D8 =>... |
use std::error::Error;
use reqwest::blocking::multipart;
const URL: &'static str = "http://esummarizer.com/main/getsummary";
pub fn summarize_text(text: &str) -> Result<String, Box<dyn Error>> {
let form = multipart::Form::new()
.text("text", text.to_string())
.text("nbsentences", "5");
let cl... |
use std::fmt::{Display, Formatter, Result};
use itertools::Itertools;
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum PermissionLevel {
User,
Superuser
}
#[derive(Debug)]
pub struct Command {
pub name: &'static str,
pub args: &'static [&'static str],
pub message: &'static str,
pub pe... |
pub use bson::Bson;
pub use mongodb::{Client, ThreadedClient};
pub use mongodb::db::ThreadedDatabase;
pub fn testone() -> String {
let client = Client::connect("localhost", 27017)
.expect("Failed to initialize standalone client.");
let coll = client.db("test").collection("movies");
let doc = doc! ... |
// vim: tw=80
//! A library of [`Futures`]-aware locking primitives. These locks can safely
//! be used in asynchronous environments like [`Tokio`]. When they block,
//! they'll only block a single task, not the entire reactor.
//!
//! These primitives generally work much like their counterparts from the
//! st... |
/// An enum to represent all characters in the SupplementalSymbolsandPictographs block.
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
pub enum SupplementalSymbolsandPictographs {
/// \u{1f900}: '๐ค'
CircledCrossFormeeWithFourDots,
/// \u{1f901}: '๐ค'
CircledCrossFormeeWithTwoDots,
/// \u{1f902... |
//use propagators::network::{ Network };
//#[test]
//fn test_network_f64_add() {
//let mut network : Network<f64> = Network::new();
//let a = network.make_cell();
//let b = network.make_cell();
//let c = network.make_cell();
//network.write_cell(a, 1.);
//network.write_cell(b, 2.);
//net... |
extern crate roaring;
use roaring::RoaringBitmap;
#[test]
fn array_not() {
let sup: RoaringBitmap<u32> = (0..2000u32).collect();
let sub: RoaringBitmap<u32> = (1000..3000u32).collect();
assert_eq!(sub.is_subset(&sup), false);
assert_eq!(sub.is_subset_opt(&sup), false);
}
#[test]
fn array() {
let s... |
use std::ffi::CStr;
use std::fmt;
use std::os::raw::{c_char, c_int, c_void};
use crate::error::{Error, Result};
use crate::panic;
/// The result of a successful name-info lookup.
#[derive(Clone, Copy, Debug)]
pub struct NameInfoResult<'a> {
node: Option<&'a c_char>,
service: Option<&'a c_char>,
}
impl<'a> Na... |
use std::time::Duration;
use hal::prelude::*;
use rppal::hal::Timer;
use rppal::pwm::{Channel, Error, Polarity, Pwm};
const EPSILON: Duration = Duration::from_micros(4);
fn sleep(delay: Duration) {
let mut timer = Timer::new();
timer.start(delay - EPSILON);
block!(timer.wait()).unwrap();
}
fn space(p... |
pub mod classical;
pub mod independent;
|
use crate::aoc_utils::read_input;
pub fn run(input_filename: &str) {
let input = read_input(input_filename);
let mut line_number: i32 = 0;
let mut instructions: Vec<Instruction> = vec![];
for line_str in input.lines() {
instructions.push(read_operation(line_number, line_str));
line_num... |
#[doc = "Reader of register FDCAN_TXBRP"]
pub type R = crate::R<u32, super::FDCAN_TXBRP>;
#[doc = "TRP\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u32)]
pub enum TRP_A {
#[doc = "0: No transmission request\r\n pending"]
B_0X0 = 0,
#[doc = "1: Transmission request\... |
//! Types for PCD metadata.
use std::{iter::FromIterator, ops::Index};
/// The struct keep meta data of PCD file.
#[derive(Debug, Clone, PartialEq)]
pub struct PcdMeta {
pub version: String,
pub width: u64,
pub height: u64,
pub viewpoint: ViewPoint,
pub num_points: u64,
pub data: DataKind,
... |
pub mod project;
use self::project::*;
use assert_cmd::prelude::*;
use predicates::prelude::*;
use std::fs;
use std::path::Path;
use std::process::Command;
fn cargo_fuzz() -> Command {
Command::cargo_bin("cargo-fuzz").unwrap()
}
#[test]
fn help() {
cargo_fuzz().arg("help").assert().success();
}
#[test]
fn i... |
use serde::{Deserialize, Serialize};
use std::{collections::HashMap, error::Error, fmt::Display, fmt, fs::OpenOptions, io::{Read, Write}, path::Path};
#[derive(Debug)]
pub enum SettingsError {
ParseError(String),
WriteParseError(String),
WriteError,
ReadError,
}
impl Error for SettingsError {}
impl ... |
use std::path::Path;
use crate::{NodeJsEngineBuildpack, NodeJsEngineBuildpackError};
use libcnb::additional_buildpack_binary_path;
use libcnb::build::BuildContext;
use libcnb::data::layer_content_metadata::LayerTypes;
use libcnb::generic::GenericMetadata;
use libcnb::layer::{Layer, LayerResult, LayerResultBuilder};
/... |
#[doc = "Register `CWD` reader"]
pub type R = crate::R<CWD_SPEC>;
#[doc = "Register `CWD` writer"]
pub type W = crate::W<CWD_SPEC>;
#[doc = "Field `WDC` reader - WDC"]
pub type WDC_R = crate::FieldReader<u16>;
#[doc = "Field `WDC` writer - WDC"]
pub type WDC_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 16, O, ... |
use std::borrow::Cow;
use std::fs;
use std::io;
use std::path::{Path, PathBuf};
use std::result::Result as ResultOf;
use structopt::StructOpt;
type Error = Cow<'static, str>;
type Result<T = (), E = Error> = ResultOf<T, E>;
#[derive(Debug, StructOpt)]
#[structopt(name = "bfc")]
struct Args {
/// Input .bf file
... |
use ffsvm::{Attribute, Header, ModelFile, SupportVector};
use rand::Rng;
pub fn random_dense<'b>(svm_type: &'b str, kernel_type: &'b str, total_sv: u32, attr: u32) -> ModelFile<'b> {
let mut rng = rand::thread_rng();
ModelFile {
header: Header {
svm_type,
kernel_type,
... |
fn main() {
// dependencies
println!("cargo:rustc-link-search=../kjsl_c_lib/cmake-build-debug/");
println!("cargo:rustc-link-lib=static=kjsl_c_lib");
}
|
#![no_std]
#![no_main]
#![feature(custom_test_frameworks)]
#![test_runner(glade::test_runner)]
#![reexport_test_harness_main = "test_main"]
use core::panic::PanicInfo;
use glade::{print, println, sprint, sprintln};
#[no_mangle]
pub extern "C" fn _start() -> ! {
test_main();
glade::hlt_loop();
}
#[panic_handl... |
extern crate foodep;
fn main() {
println!("Hello, world!");
foodep::foo();
}
|
fn insertion_sort<T: std::cmp::Ord>(arr: &mut [T]) {
for i in 1..arr.len() {
let mut j = i;
while j > 0 && arr[j] < arr[j-1] {
arr.swap(j, j-1);
j = j-1;
}
}
}
fn main() {} |
use crate::candidate::{CandidatePairState, CandidateType};
use crate::agent::agent_internal::AgentInternal;
use crate::network_type::NetworkType;
use std::sync::atomic::Ordering;
use tokio::time::Instant;
/// Contains ICE candidate pair statistics.
pub struct CandidatePairStats {
/// The timestamp associated with... |
use crate::initial_load::initial_load;
use crate::page_data::page_data;
use crate::translations::translations;
use actix_files::{Files, NamedFile};
use actix_web::{web, HttpRequest};
use perseus::{
get_render_cfg,
html_shell::prep_html_shell,
path_prefix::get_path_prefix_server,
stores::{ImmutableStore,... |
use crate::net::TcpStream;
use std::future::Future;
use std::io;
use std::pin::Pin;
use std::task::{Context, Poll};
/// A future completing when a stream is ready to use (or failed).
#[must_use = "futures do nothing unless you `.await` or poll them"]
#[derive(Debug)]
pub struct TcpConnectFuture {
stream: Option<TcpSt... |
// This file is part of rdma-core. It is subject to the license terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/rdma-core/master/COPYRIGHT. No part of rdma-core, including this file, may be copied, modified, propagated, or distributed ... |
//! Utilities for manipulating the data devices
//!
//! The data device is wayland's abstraction to represent both selection (copy/paste) and
//! drag'n'drop actions. This module provides logic to handle this part of the protocol.
//! Selection and drag'n'drop are per-seat notions.
//!
//! This module provides 2 main f... |
use cocoa::base::id;
use cocoa::foundation::{NSInteger, NSRange, NSUInteger};
use libc::{uint32_t, c_void};
use types::{MTLScissorRect, MTLViewport};
pub trait MTLRenderCommandEncoder {
unsafe fn setBlendColorRed_green_blue_alpha(self, red: f32, green: f32, blue: f32, alpha: f32);
unsafe fn setCullMode(self, c... |
use proc_macro;
use proc_macro::TokenStream;
use quote::{format_ident, quote};
#[proc_macro]
pub fn build_test_renderer(input: TokenStream) -> TokenStream {
let renderer_name = format_ident!("{}", input.to_string());
let exp = quote! {
let mut character_sizes = std::collections::HashMap::new();
... |
#[doc = "Register `SYSCFG_ITLINE5` reader"]
pub type R = crate::R<SYSCFG_ITLINE5_SPEC>;
#[doc = "Field `EXTI0` reader - EXTI line 0 interrupt request pending"]
pub type EXTI0_R = crate::BitReader;
#[doc = "Field `EXTI1` reader - EXTI line 1 interrupt request pending"]
pub type EXTI1_R = crate::BitReader;
impl R {
#... |
#[doc = "Reader of register CMP0_SW_CLEAR"]
pub type R = crate::R<u32, super::CMP0_SW_CLEAR>;
#[doc = "Writer for register CMP0_SW_CLEAR"]
pub type W = crate::W<u32, super::CMP0_SW_CLEAR>;
#[doc = "Register CMP0_SW_CLEAR `reset()`'s with value 0"]
impl crate::ResetValue for super::CMP0_SW_CLEAR {
type Type = u32;
... |
use std::cmp;
use std::env;
use std::fs;
use std::path::Path;
#[derive(Copy, Clone, Debug)]
enum GameObjectClass {
Player = 1,
Enemy = 2,
}
#[derive(PartialEq, Copy, Clone, Debug)]
enum ItemCategory {
Weapon = 1,
Armor = 2,
Misc = 3,
}
#[derive(PartialEq, Copy, Clone, Debug)]
enum ItemClass {
... |
use std::collections::HashMap;
use hyper::http::Request;
use svc_authn::jose::ConfigMap;
use tower::ServiceExt;
use super::*;
use crate::app::http;
use crate::test_helpers::prelude::*;
#[tokio::test]
async fn test_healthz() {
let state = TestState::new(TestAuthz::new()).await;
let state = Arc::new(state) as ... |
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use uuid::Uuid;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TodoItem {
pub id: Uuid,
pub name: String,
pub completed: bool,
#[serde(with = "my_date_format")]
pub created_date: DateTime<Utc>,
#[serde(with = "my_date... |
use std::sync::Arc;
use crate::config::VolumeCtrl;
pub mod mappings;
use self::mappings::MappedCtrl;
pub struct NoOpVolume;
pub trait Mixer: Send + Sync {
fn open(config: MixerConfig) -> Self
where
Self: Sized;
fn set_volume(&self, volume: u16);
fn volume(&self) -> u16;
fn get_soft_vol... |
use crate::testing::*;
#[test]
fn test_bad_attributes() {
assert_parse_error! {
r#"fn main() { #[foo] #[bar] hello }"#,
span, AttributesNotSupported => {
assert_eq!(span, Span::new(12, 25));
}
};
}
|
extern crate num_traits;
use std::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign};
pub trait Sqrt {
type Output;
fn sqrt(self) -> Self::Output;
}
impl Sqrt for f32 {
type Output = f32;
fn sqrt(self) -> Self::Output {
self.sqrt()
}
}
impl Sqrt for f64 {
type Output = f64;
... |
use super::*;
use graph::{EdgeT, Graph, NodeT};
#[pymethods]
impl EnsmallenGraph {
#[staticmethod]
#[args(py_kwargs = "**")]
#[text_signature = "(edge_path, directed, *, directed_edge_list, sources_column_number, sources_column, destinations_column_number, destinations_column, edge_types_column_number, edg... |
use sdl2::rect::{Point, Rect};
use sdl2::render::Texture;
use std::rc::Rc;
use crate::app::application::WindowCanvas;
use crate::app::{UpdateResult as UR, UpdateResult};
use crate::renderer::managers::*;
use rider_config::*;
pub mod buttons;
pub mod caret;
pub mod file;
pub mod file_editor;
pub mod filesystem;
pub m... |
use std::fs::File;
use std::io::BufReader;
use std::io::prelude::*;
use std::collections::HashSet;
// Doing it a low level way that's closer to how I'll do it
// in stee.
fn main() -> std::io::Result<()> {
let f = File::open("src/bin/day01.txt")?;
let mut reader = BufReader::new(f);
let mut input_buf = v... |
use crate::parsing::basic_parsers::char_that;
use crate::parsing::combinators::repeat_1_or_more;
use basic_parsers::{any_char, char, eof, tag, whitespace};
use combinators::{all, any, followed, map, not, opt, peek, repeat_0_or_more};
type Result<'a, T> = std::result::Result<T, ParseError<'a>>;
type ParseResult<'a, T>... |
#![deny(warnings)]
use hyper::service::{make_service_fn, service_fn};
use hyper::{Body, Client, Request, Response, Server};
use std::{convert::Infallible, net::SocketAddr};
async fn hello(mut req: Request<Body>) -> Result<Response<Body>, hyper::Error> {
println!("--- {:?}", req.headers());
// let body_buf = h... |
use std::fs::File;
use std::io::{self, BufRead};
use std::path::Path;
use std::collections::{HashSet, HashMap};
use itertools::Itertools;
use std::convert::TryInto;
fn read_lines<P>(filename: P) -> io::Result<io::Lines<io::BufReader<File>>>
where P: AsRef<Path>, {
let file = File::open(filename)?;
Ok(io::BufRe... |
use std::thread;
use std::time::Duration;
use std::sync::{Mutex, Arc};
fn main() {
let a = 1;
let b = 2;
let m1 = Arc::new(Mutex::new(a));
let m2 = Arc::new(Mutex::new(b));
let am1 = Arc::clone(&m1);
let am2 = Arc::clone(&m1);
let bm1 = Arc::clone(&m2);
let bm2 = Arc::clone(&m2);
... |
use std::fs::File;
use std::io::{self, prelude::*, BufReader, SeekFrom};
use std::path::Path;
use bzip2::read::BzDecoder;
type BZipReader = BufReader<BzDecoder<BufReader<File>>>;
/// Create a bzip2 BufReader from a File handle.
pub fn to_decode_buffer(file: File) -> BZipReader {
let buf = BufReader::with_capacit... |
fn gen_next_seq(seq:Vec<usize>, steps:i32) ->Vec<usize>{
if steps <= 0 {
return seq.clone();
}
let mut next:Vec<usize> = Vec::new();
let mut i = 0;
while i < seq.len() {
let mut n:usize = 1;
for j in i..seq.len()-1{
if seq[j] == seq[j+1]{
n+... |
extern crate mio;
use mio::*;
use mio::tcp::*;
use mio::util::Slab;
use std::net::SocketAddr;
use std::str::FromStr;
use std::mem;
struct Server {
socket: TcpListener,
connections: Slab<Connection>,
}
impl Server {
fn new(socket: TcpListener) -> Server {
Server {
socket: socket,
... |
#[doc = "Register `PRIVCFGR1` reader"]
pub type R = crate::R<PRIVCFGR1_SPEC>;
#[doc = "Register `PRIVCFGR1` writer"]
pub type W = crate::W<PRIVCFGR1_SPEC>;
#[doc = "Field `AESPRIV` reader - AESPRIV"]
pub type AESPRIV_R = crate::BitReader;
#[doc = "Field `AESPRIV` writer - AESPRIV"]
pub type AESPRIV_W<'a, REG, const O: ... |
#[doc = "Reader of register EP_TYPE"]
pub type R = crate::R<u32, super::EP_TYPE>;
#[doc = "Writer for register EP_TYPE"]
pub type W = crate::W<u32, super::EP_TYPE>;
#[doc = "Register EP_TYPE `reset()`'s with value 0"]
impl crate::ResetValue for super::EP_TYPE {
type Type = u32;
#[inline(always)]
fn reset_va... |
#[cfg(test)]
mod cli {
// use std::io::Write;
use std::process::Command;
use assert_cmd::prelude::*;
// use tempfile;
#[test]
fn should_invert_match_when_v_flag_is_specified() {
let mut cmd = Command::main_binary().unwrap();
cmd.arg("-v").arg(r#"{"name":"jeff goldblum"}"#);
... |
#![doc = "generated by AutoRust 0.1.0"]
#[cfg(feature = "package-webservices-2017-01")]
mod package_webservices_2017_01;
#[cfg(feature = "package-webservices-2017-01")]
pub use package_webservices_2017_01::{models, operations, API_VERSION};
#[cfg(feature = "package-commitmentPlans-2016-05-preview")]
mod package_commitm... |
fn abs(x: i32) -> i32 {
if x > 0 {
x
} else {
-x
}
}
fn main() {
let nbr = -2;
println!("abs of nbr is {}", abs(nbr));
}
|
#[doc = "Register `CSR` reader"]
pub type R = crate::R<CSR_SPEC>;
#[doc = "Register `CSR` writer"]
pub type W = crate::W<CSR_SPEC>;
#[doc = "Field `LSION` reader - Internal low-speed oscillator enable"]
pub type LSION_R = crate::BitReader<LSION_A>;
#[doc = "Internal low-speed oscillator enable\n\nValue on reset: 0"]
#[... |
#[path = "support/macros.rs"]
#[macro_use]
mod macros;
mod support;
use criterion::{criterion_group, criterion_main, Criterion};
use std::ops::Mul;
use support::*;
bench_binop!(
mat2_mul_vec2,
"mat2 mul vec2",
op => mul,
from1 => random_mat2,
from2 => random_vec2
);
bench_unop!(
mat2_transpos... |
use std::ops::{
Index,
IndexMut,
Deref,
DerefMut,
};
pub struct Palette<T> {
pub map: [T; 256],
pub size: usize,
pub transparent: Option<u8>,
}
impl<T: Copy> Palette<T> {
pub fn new<C: Into<Option<u8>>>(def: T, c: C) -> Self {
Self {
map: [def; 256],
siz... |
use util::*;
const LEN: usize = 'z' as usize - 'a' as usize + 1;
fn main() {
let timer = Timer::new();
let count: usize = input::vec::<String>(&std::env::args().nth(1).unwrap(), "\n\n")
.iter()
.map(|s| {
let answers: Vec<[bool; LEN]> = s
.split('\n')
... |
// Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution.
//
// 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>,... |
use std::rc::Rc;
use std::thread;
use std::sync::{Arc, Mutex};
extern crate easydb;
use self::easydb::Column;
use self::easydb::Table;
use self::easydb::DbPool;
use std::collections::BTreeMap;
extern crate rustc_serialize;
use self::rustc_serialize::json::Json;
use self::rustc_serialize::json::ToJson;
... |
use cortex_m::{
iprintln,
peripheral::{
ITM,
TPIU,
},
interrupt,
};
use log::{
Log,
Level,
Metadata,
Record,
SetLoggerError
};
const STIM_PORT_NUMBER: usize = 0;
#[derive(Debug, PartialEq, Clone, Copy)]
pub enum Error {
ImpossibleBaudRate,
}
///Updates the tpiu... |
use chrono::{DateTime, Utc};
use hyper::body::HttpBody;
use hyper::client::connect::dns::GaiResolver;
use hyper::client::HttpConnector;
use hyper::{header, Body, Method, Request, Response, Uri};
use hyper_tls::HttpsConnector;
use percent_encoding::{utf8_percent_encode, AsciiSet, CONTROLS};
use serde::{Deserialize, Seri... |
#![allow(clippy::too_many_arguments)]
use crate::sys;
use std::ptr::NonNull;
pub use sys::SIMCONNECT_OBJECT_ID_USER;
pub use msfs_derive::sim_connect_data_definition as data_definition;
/// A trait implemented by the `data_definition` attribute.
pub trait DataDefinition {
#[doc(hidden)]
const DEFINITIONS: &... |
#[doc = "Register `DDRPERFM_STATUS` reader"]
pub type R = crate::R<DDRPERFM_STATUS_SPEC>;
#[doc = "Field `COVF` reader - COVF"]
pub type COVF_R = crate::FieldReader;
#[doc = "Field `BUSY` reader - BUSY"]
pub type BUSY_R = crate::BitReader;
#[doc = "Field `TOVF` reader - TOVF"]
pub type TOVF_R = crate::BitReader;
impl R... |
fn main() {
let string = "main";
let mut char_string = string.chars();
println!("{:?}",char_string.next());
}
|
#[doc = "Register `IFCR` writer"]
pub type W = crate::W<IFCR_SPEC>;
#[doc = "Field `CGIF1` writer - global interrupt flag clear for channel 1"]
pub type CGIF1_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `CTCIF1` writer - transfer complete flag clear for channel 1"]
pub type CTCIF1_W<'a, REG, ... |
use chrono::{DateTime, Utc};
pub type Measurement = u16;
#[derive(Debug)]
pub struct MoistureEvent {
pub time: DateTime<Utc>,
pub name: String,
pub value: Measurement
}
impl super::ToInfluxDB for MoistureEvent {
fn to_line(&self) -> String {
format!("moisture,name={} value={} {}",
self.name,
self.value,
... |
use crate::utils::wait_until;
use crate::{Net, Spec, TestProtocol};
use ckb_sync::{NetworkProtocol, MAX_LOCATOR_SIZE};
use ckb_types::{
h256,
packed::{Byte32, GetHeaders, SyncMessage},
prelude::*,
H256,
};
use log::info;
pub struct InvalidLocatorSize;
impl Spec for InvalidLocatorSize {
crate::name... |
use crate::engine::{element::Element, *};
pub struct SpriteRenderer {
path: String, // Idk how to store the sprite, now I am using a cache :/
}
impl SpriteRenderer {
pub fn new(path: String) -> Box<dyn Component> {
Box::new(SpriteRenderer { path: path })
}
}
impl Component for SpriteRenderer {
... |
use std::{collections::HashSet, time::Duration};
use pretty_assertions::assert_eq;
use super::{LookupHosts, SrvPollingMonitor};
use crate::{
error::Result,
options::{ClientOptions, ServerAddress},
runtime,
sdam::Topology,
test::{log_uncaptured, CLIENT_OPTIONS},
};
fn localhost_test_build_10gen(po... |
mod test_notifier;
mod test_verifier;
|
enum IpAddrKind {
V4,
V6,
}
struct Ipv4Addr {
address: (u8, u8, u8, u8)
}
struct Ipv6Addr {
address: String
}
enum IpAddr {
V4(Ipv4Addr),
V6(Ipv6Addr),
}
fn main() {
let v4_addr = Ipv4Addr { address: (127, 0, 0, 1) };
let home = IpAddr::V4(v4_addr);
let v6_addr = Ipv6Addr { addr... |
fn read<T: std::str::FromStr>() -> T {
let mut s = String::new();
std::io::stdin().read_line(&mut s).ok();
s.trim().parse().ok().unwrap()
}
fn read_vec<T: std::str::FromStr>() -> Vec<T> {
read::<String>()
.split_whitespace()
.map(|e| e.parse().ok().unwrap())
.collect()
}
fn rea... |
use std::{
collections::BTreeMap,
path::{Path, PathBuf},
fmt,
error::Error,
};
use regex::Regex;
use yaml_rust::{Yaml, YamlLoader, ScanError};
use crate::{
ContextHandle, Polarity, DotId, Content, PartialContent, ContentFormat,
content::{PolyForContent, MonoForContent},
};
#[derive(Clone, Debug... |
use crate::{ import::*, error::* };
/// This type can be used when you need a concrete type as Address<M>. Eg,
/// you can store this as BoxAny and then use down_cast from std::any::Any.
//
pub struct Receiver<M: Message>
{
rec: Pin<BoxAddress<M, ThesErr>>
}
impl<M: Message> Receiver<M>
{
/// Create a new Receive... |
use ::std::*;
/**
--- Part Two ---
The air conditioner comes online! Its cold air feels good for a while, but then the TEST alarms start to go off. Since the air conditioner can't vent its heat anywhere but back into the spacecraft, it's actually making the air inside the ship warmer.
Instead, you'll need ... |
use crate::error::{Error, UnderlyingError};
use crate::hash::Hash;
use crate::snapshots::{FileMetadata, Snapshot};
use crate::storage::stream::{ReadEggExt, WriteEggExt};
use ahash;
use byteorder::LittleEndian;
use byteorder::{ReadBytesExt, WriteBytesExt};
use smallvec::SmallVec;
use std::collections::HashMap;
use std::... |
use std::collections::HashSet;
use std::fs::File;
use std::io::{BufRead, BufReader};
fn main() {
let file = File::open("input").expect("Failed to open file");
let reader = BufReader::new(file);
let mut counts: HashSet<i64> = HashSet::new();
let mut current = 0;
counts.insert(current);
let mut... |
extern crate rustc_hex;
extern crate wasmi;
#[macro_use]
extern crate clap;
use std::time::{Duration, Instant};
use rustc_hex::FromHex;
use serde::{Deserialize, Serialize};
use std::env;
use std::fs::File;
use wasmi::memory_units::Pages;
use wasmi::{
Error as InterpreterError, Externals, FuncInstance, FuncRef, Im... |
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use std::collections::BTreeSet;
use std::collections::HashMap;
use std::collections::HashSet;
use std::fmt::Debug;
use std::hash:... |
//! [Rc<T>], the Reference Counted Smart Pointer
//!
//! [rc<t>]: https://doc.rust-lang.org/book/ch15-04-rc.html
use std::rc::Rc;
use the_book::ch15::sec04::List::{Cons, Nil};
fn main() {
let a = Rc::new(Cons(5, Rc::new(Cons(10, Rc::new(Nil)))));
println!("a's strong count={} in the beginning", Rc::strong_cou... |
// Copyright 2020 ChainSafe Systems
// SPDX-License-Identifier: Apache-2.0, MIT
use super::{Error, TipIndex, TipsetMetadata};
use actor::{power::State as PowerState, STORAGE_POWER_ACTOR_ADDR};
use blocks::{Block, BlockHeader, FullTipset, Tipset, TipsetKeys, TxMeta};
use cid::Cid;
use encoding::{de::DeserializeOwned, f... |
//! Asynchronous engine for running THavalon games
use std::collections::{HashMap, HashSet};
use serde::{Deserialize, Serialize};
use thiserror::Error;
use super::role::{PriorityTarget, RoleDetails, Team};
use super::{Card, MissionNumber};
// Game-related messages
/// Something the player tries to do
#[derive(Debu... |
use serenity::client::CACHE;
use serenity::model::*;
use serenity::voice;
use serenity::Result as SerenityResult;
command!(deafen(ctx, msg) {
let guild_id = match CACHE.read().unwrap().guild_channel(msg.channel_id) {
Some(channel) => channel.read().unwrap().guild_id,
None => {
check_msg... |
use std::process;
use syslog::{BasicLogger, Facility, Formatter3164};
pub fn setup(name: &str, level: log::Level, syslog: bool) -> Result<(), String> {
if syslog {
let formatter = Formatter3164 {
facility: Facility::LOG_USER,
hostname: None,
process: name.to_string(),
... |
#[derive(Clone)]
struct EmptyClient {
public_key: (),
period: time::Duration,
genesis_time: time::SystemTime,
hash: Vec<u8>,
}
impl From<EmptyClient> for ClientInfo {
fn from(val: EmptyClient) -> Self {
ClientInfo {
public_key: val.public_key,
period: val.period,
... |
use model::*;
use utils::*;
use std::fmt::Write;
use std::vec::Vec;
use std::str;
use reqwest::header::Headers;
use reqwest::unstable::async::Client as AsyncReqClient;
use reqwest::Method;
use tokio_core::reactor::Handle;
use futures::future::Future;
use futures::{Stream, IntoFuture};
use {API_V1, WAPI_V3, API_V3};... |
#[doc = "Register `TX_MULTIPLE_COLLISION_GOOD_PACKETS` reader"]
pub type R = crate::R<TX_MULTIPLE_COLLISION_GOOD_PACKETS_SPEC>;
#[doc = "Field `TXMULTCOLG` reader - Tx Multiple Collision Good Packets"]
pub type TXMULTCOLG_R = crate::FieldReader<u32>;
impl R {
#[doc = "Bits 0:31 - Tx Multiple Collision Good Packets"... |
pub const OPENING_TAG: u8 = b'<';
pub const END_OF_TAG: &[u8] = b"</";
pub const SELF_CLOSING: &[u8] = b"/>";
pub const COMMENT: &[u8] = b"--";
pub const ID_ATTR: &[u8] = b"id";
pub const CLASS_ATTR: &[u8] = b"class";
pub const VOID_TAGS: &[&[u8]] = &[
b"area", b"base", b"br", b"col", b"embed", b"hr", b"img", b"inp... |
use crate::{
api::{
extractors::{
auth::Auth,
multer::Multer,
config::{
default_json_config,
default_path_config,
default_query_config,
avatar_multer_config,
},
},
errors::{ApiErro... |
use std::error::Error;
use serde::Deserialize;
#[derive(Deserialize)]
pub enum AssociationType {
#[serde(alias = "bind")]
Bind,
#[serde(alias = "connect")]
Connect,
}
impl Default for AssociationType {
fn default() -> Self {
AssociationType::Bind
}
}
#[derive(Default, Deserialize)]
pu... |
/*!
The build script has two primary jobs:
1. Do code generation. Currently, this consists of turning `data/winver.json` into an appropriate `enum`.
2. Tell Cargo to link against Clang.
*/
extern crate itertools;
extern crate serde;
use std::env;
use std::fs;
use std::io;
use std::io::prelude::*;
use std::path::{Pa... |
use libra_types::account_address::AccountAddress;
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, Eq, PartialEq, Hash, Ord, PartialOrd, Serialize, Deserialize)]
pub struct Type(pub String);
/// A vertex.
///
/// Vertices are how you would represent nouns in the datastore. An example
/// might be a user, o... |
use std::time::SystemTime;
use actix::prelude::*;
use diesel::{self, prelude::*};
use crate::common::error::ServerError;
use crate::models::{
executor::DatabaseExecutor as DbExecutor,
paste::{NewPaste, Paste},
};
pub struct CreatePasteMsg {
pub title: String,
pub body: String,
pub created_at: Sys... |
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Debug, PartialEq)]
pub struct LinkAsset {
url: String,
#[serde(rename = "urlfb")]
fallback_url: Option<String>,
#[serde(rename = "trkr")]
third_party_tracker_url: Vec<String>,
ext: Option<LinkAssetExt>,
}
#[derive(Seriali... |
extern crate cgmath;
extern crate image;
extern crate rand;
use cgmath::{dot, prelude::*, vec3, Vector3};
struct Ray {
origin: Vector3<f64>,
direction: Vector3<f64>,
}
struct Intersection {
pos: Vector3<f64>,
distance: f64,
color: Vector3<f64>,
}
struct Sphere {
center: Vector3<f64>,
rad... |
use std::collections::{HashMap, HashSet, VecDeque};
use std::error::Error;
use std::fs::{read_to_string};
use itertools::Itertools;
type Cell = (usize, usize);
type Maze = HashMap<Cell, char>;
type Path = Vec<Cell>;
fn main() -> Result<(), Box<dyn Error>> {
let contents = read_to_string("maze.txt")?;
let line... |
use quote::quote_spanned;
use super::{
FlowProperties, FlowPropertyVal, OperatorCategory, OperatorConstraints, OperatorWriteOutput,
WriteContextArgs, RANGE_0, RANGE_1,
};
use crate::graph::OperatorInstance;
/// > 0 input streams, 1 output stream
///
/// > Arguments: An iterable Rust object.
/// Takes the iter... |
use std::str::FromStr;
use std::num::ParseIntError;
pub mod part1;
pub mod part2;
pub fn default_input() -> &'static str {
include_str!("input")
}
pub fn run() {
part1::run();
part2::run();
}
pub fn parse_input(input : &str) -> Vec<Row> {
input.lines().map(|l| {Row::from_str(l).unwrap()}).collect()
... |
use std::collections::HashMap;
fn main() {
let mut book_reviews: HashMap<String, String> = HashMap::new();
book_reviews.insert(
"Adventures of Huckleberry Finn".to_string(),
"My favorite book.".to_string(),
);
book_reviews.insert(
"Grimms' Fairy Tales".to_string(),
"Mas... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.