text stringlengths 8 4.13M |
|---|
use biscuit::jwa::*;
use biscuit::jwk::*;
use biscuit::*;
use once_cell::sync::OnceCell;
use serde::{Deserialize, Serialize};
use thiserror::Error;
use tonic::{Request, Status};
#[derive(Debug, Serialize, Deserialize)]
struct Claims {
exp: usize,
}
pub async fn validate_token<T>(request: &Request<T>) -> Result<()... |
#[doc = "Register `APBSMENR1` reader"]
pub type R = crate::R<APBSMENR1_SPEC>;
#[doc = "Register `APBSMENR1` writer"]
pub type W = crate::W<APBSMENR1_SPEC>;
#[doc = "Field `TIM3SMEN` reader - TIM3 timer clock enable during Sleep mode Set and cleared by software."]
pub type TIM3SMEN_R = crate::BitReader;
#[doc = "Field `... |
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - GICC control register"]
pub gicc_ctlr: GICC_CTLR,
#[doc = "0x04 - GICC input priority mask register"]
pub gicc_pmr: GICC_PMR,
#[doc = "0x08 - GICC binary point register"]
pub gicc_bpr: GICC_BPR,
#[doc = "0x0c - ... |
use crate::error::{FundError, FundErrorCode};
use arrayref::{array_mut_ref, array_ref};
use solana_client_gen::solana_sdk::account_info::AccountInfo;
use solana_client_gen::solana_sdk::pubkey::Pubkey;
/// Whitelist maintaining the list of program-derived-addresses the Locked
/// SRM program is allowed to delegate fund... |
/// An enum to represent all characters in the BoxDrawing block.
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
pub enum BoxDrawing {
/// \u{2500}: '─'
LightHorizontal,
/// \u{2501}: '━'
HeavyHorizontal,
/// \u{2502}: '│'
LightVertical,
/// \u{2503}: '┃'
HeavyVertical,
/// \u{25... |
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
use syn::parse::Parse;
use syn::parse::ParseStream;
use syn::punctuated::Punctuated;
use syn::Error;
use syn::Ident;
use syn::Result;
use syn::Token;
#[derive(Copy, Clone, Debug, Default)]
pub struct Attributes {
pub is_unstable: bool,
pub ... |
//! History.
use super::util::{build_uri, handle_json_response, json_as_array, json_as_object};
use super::{error, Hyper};
use crate::core::data::{request, response};
use crate::core::json;
use crate::core::TransportService;
use async_trait::async_trait;
use http::{Method, Request};
use hyper::{Body, Response};
use pu... |
pub enum ScopeLevel {
Global,
File,
Scope, // .SCOPE / .PROC
HasData, // last scope that has data (originally equal to scope scope)
Struct, // .STRUCT / .UNION
Enum,
Undef,
}
impl ScopeLevel {
pub fn u8_from(&self) -> u8 {
match self {
ScopeLevel::Global => 0,
ScopeLevel::File => 1,
... |
use std::marker::PhantomData;
use std::{fmt,hash,slice};
use super::QName;
use super::raw;
pub struct Storage<'d> {
storage: &'d raw::Storage,
}
impl<'d> Storage<'d> {
pub fn new(storage: &raw::Storage) -> Storage {
Storage {
storage: storage,
}
}
pub fn create_element<'n... |
use std::collections::HashMap;
fn main() {
let n: u32 = {
let mut line = String::new();
std::io::stdin().read_line(&mut line).unwrap();
line.trim_end().parse().unwrap()
};
for o in run(n) {
println!("{}", o);
}
}
fn run(n: u32) -> Vec<String> {
let prime_numbers: Ve... |
//! # Tendermock
//!
//! A builder API to build and run Tendermock node.
//!
//! ```no_run
//! use tendermock::Tendermock;
//!
//! let jrpc_addr = format!("127.0.0.1:{}", 5000).parse().unwrap();
//! let grpc_addr = format!("127.0.0.1:{}", 6000).parse().unwrap();
//!
//! Tendermock::default()
//! .growth_rate(10)
//... |
use quote::Tokens;
use syn::{Attribute, Field, Lit::Str, Meta, Meta::*, MetaList, MetaNameValue, NestedMeta::*};
fn walk_attrs(attrs: &[Attribute], callback: &mut FnMut(Meta)) {
use Meta::*;
use NestedMeta::*;
let valid_tokens = attrs
.iter()
.filter_map(|attr| {
let path = &at... |
use crate::utils::get_fl_name;
use proc_macro::TokenStream;
use quote::*;
use syn::*;
pub fn impl_window_trait(ast: &DeriveInput) -> TokenStream {
let name = &ast.ident;
let name_str = get_fl_name(name.to_string());
let make_modal = Ident::new(
format!("{}_{}", name_str, "make_modal").as_str(),
... |
use std::collections::HashMap;
fn main() {
let vector = vec![2, 1, 3, 7, 4, 2, 0, 6, 9, 1, 9, 3, 9, 1, 9, 4, 5];
println!("Average = {}", avg(&vector));
println!("Median = {}", median(&vector));
println!("Mode = {}", mode(&vector));
}
fn avg(arr: &[i32]) -> f64 {
let mut total = 0;
let leng... |
#![allow(non_snake_case)]
mod Command;
mod Helper;
use crate::Command::command;
use crate::Helper::helpers;
use std;
use std::env;
use std::path::Path;
use std::process::exit;
use colored::*;
fn main() {
let args = env::args().collect::<Vec<String>>();
if (&args).len() > 1 {
process_cli_args(args);
... |
#![allow(dead_code)]
use std::mem;
pub fn array_test() {
let a:[i32;5] = [0,1,2,3,4];
let b:[i32;5] = [10,11,12,13,14];
println!("a.length = {} head={}", a.len(), a[0]);
println!("a full array = {:?}", a);
if a != b {
println!("a != b -> same array length")
}
println!("\n .. auto... |
/*
* Copyright (C) 2019-2021 TON Labs. All Rights Reserved.
*
* Licensed under the SOFTWARE EVALUATION License (the "License"); you may not use
* this file except in compliance with the License.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an ... |
//! 145. 二叉树的后序遍历
// https://leetcode.cn/problems/binary-tree-postorder-traversal/
use std::rc::Rc;
use std::cell::RefCell;
// Definition for a binary tree node.
#[derive(Debug, PartialEq, Eq)]
pub struct TreeNode {
pub val: i32,
pub left: Option<Rc<RefCell<TreeNode>>>,
pub right: Option<Rc<RefCell<T... |
#[doc = "Register `GICD_IPRIORITYR47` reader"]
pub type R = crate::R<GICD_IPRIORITYR47_SPEC>;
#[doc = "Register `GICD_IPRIORITYR47` writer"]
pub type W = crate::W<GICD_IPRIORITYR47_SPEC>;
#[doc = "Field `PRIORITY0` reader - PRIORITY0"]
pub type PRIORITY0_R = crate::FieldReader;
#[doc = "Field `PRIORITY0` writer - PRIOR... |
use chrono::{DateTime, Utc};
use octocrab::models::repos::Asset;
use reqwest::Url;
use serde::*;
use crate::*;
// use octocrab::models::repos::Release;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct Release {
pub url: Url,
pub html_url: Url,
pub a... |
use std::collections::BTreeMap;
use std::fmt;
use std::fs::{File, OpenOptions};
use std::io;
use std::io::prelude::*;
use std::path::Path;
use transaction::*;
pub trait TransactionLog {
type Error: fmt::Debug;
fn create(
&mut self,
data: TransactionData,
time: Option<TransactionTime>,... |
extern crate rooms_server;
fn main() {
rooms_server::hello();
} |
use clap::{App, ArgMatches, SubCommand};
use bookmark::Bookmark;
use database::DB;
use utils::get_title_from_url;
pub fn make_subcommand<'a, 'b>() -> App<'a, 'b> {
SubCommand::with_name("update")
.about("Update bookmark")
.arg_from_usage("<ID> 'Update bookmark matching the specified id'")
... |
//! Bounding Volume Heirarchies.
//!
//! These allow us to more effeciently compute what a ray might be able to hit
//! without having to construct a bunch of `HitRecord` structs and do a bunch of
//! calculations up front.
use crate::{
aabb::AABB,
hittable::{HitRecord, Hittable},
ray::Ray,
};
/// A bound... |
use crate::types::{Face, Vertex};
use crate::{cone, cylinder};
/// Ratios are cylinder / cone
pub fn arrow(thickness_ratio: f32, length_ratio: f32) -> (Vec<Vertex>, Vec<Face>) {
let (mut cyv, mut cyi) = cylinder(10, 1);
let (mut cov, mut coi) = cone(10);
cov.iter_mut()
.for_each(|v| v.position[1] =... |
use color_eyre::{Help, Report};
use libspideog::{data::tree::Tree, errors::SpideogError};
use tracing::instrument;
use crate::{
cli::subcommands::{CombineTrees, Runner},
io::{newick::write_newick, report::ParseKrakenReport, Output},
};
type VecResultTrees = Vec<Result<Tree, SpideogError>>;
impl Runner for Co... |
#![feature(test)]
use std::collections::HashMap;
use std::fmt::Display;
use md5::compute;
extern crate test;
pub trait Hash {
fn hash(&self, weight: i32) -> u128;
}
impl Hash for String {
fn hash(&self, weight: i32) -> u128 {
let hash_string = format!("{}-{}", self, weight);
let digest = com... |
use crate::datetime::{to_ordinal, Time};
use crate::iter::easter::easter;
use crate::iter::monthinfo::{rebuild_month, MonthInfo};
use crate::iter::yearinfo::{rebuild_year, YearInfo};
use crate::options::{Frequenzy, ParsedOptions};
use chrono::prelude::*;
pub struct IterInfo<'a> {
pub yearinfo: Option<YearInfo>,
... |
#[cfg(test)]
mod tests {
use kingslayer::Cli;
#[test]
fn readme_example() {
let cli = Cli::from_json_file("data/world.json");
println!("{}", cli.ask("l"));
loop {
let s = cli.ask(&String::new());
println!("{}", s);
if s.contains("You died.") {
... |
use actix_web::{guard, web, App, HttpRequest, HttpResponse, HttpServer, Result};
use async_graphql::http::{playground_source, GraphQLPlaygroundConfig};
use async_graphql::{Context, Data, EmptyMutation, Object, Schema, Subscription};
use async_graphql_actix_web::{Request, Response, WSSubscription};
use futures::{stream,... |
//! The basic authentication method, using a reddit username and password.
use crate::{auth::Auth, client::route::Route, error::Error, model::misc::Params};
use async_trait::async_trait;
use reqwest::{Client as HttpClient, Response};
use std::sync::{Arc, RwLock};
use std::time::{Duration, SystemTime};
/// The basic a... |
#![allow(dead_code)]
use crate::*;
use std::collections::{HashMap, VecDeque};
use std::cmp::Ordering;
const DAY: usize = 14;
pub struct Chemical {
name: String,
num: usize
}
impl FromStr for Chemical {
type Err = AocErr;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let p = s.find(' ')
... |
pub fn reverse(x: i32) -> i32 {
if x == 0 {
return 0;
}
let pos = x > 0;
let mut y = if pos { x } else { -x };
let mut ry = 0;
while y > 0 {
let ry64 = ry as i64 * 10 + (y % 10) as i64;
if ry64 > (1 << 31) - 1 {
return 0;
}
ry = ry64 as i32;
... |
pub mod gfx;
pub mod math;
use std::collections::HashMap;
use ash::vk;
use spirq::{SpirvBinary};
use crate::gfx::{Context, Device, ShaderModule, Buffer, BufferConfig,
MemoryUsage, VertexHead, FragmentHead, AttributeBinding, DeviceProc,
Transaction, BindPoint, AttachmentReference, ShaderArray,
GraphicsPipel... |
#![allow(non_upper_case_globals, dead_code)]
pub mod netvars {
use memlib::memory::Address;
pub static cs_gamerules_data: Address = 0x0;
pub static m_ArmorValue: Address = 0xB378;
pub static m_Collision: Address = 0x320;
pub static m_CollisionGroup: Address = 0x474;
pub static m_Local: Address... |
use crate::config::cache;
use crate::lib::dist;
use crate::lib::error::{DfxError, DfxResult};
use anyhow::bail;
use semver::{Version, VersionReq};
use std::fmt;
use std::fmt::Formatter;
use std::path::{Path, PathBuf};
use std::str::FromStr;
const TOOLCHAINS_ROOT: &str = ".dfinity/toolchains/";
const DEFAULT_PATH: &st... |
fn print_typename<T>(_: T) {
println!("{}", std::any::type_name::<T>());
}
fn main() {
let mut s = String::new();
std::io::stdin().read_line(&mut s).unwrap();
let v = s
.split_whitespace()
.map(|w| w.parse().unwrap())
.collect::<Vec<f64>>();
let (a, b, x) = (v[0], v[1], v[2]... |
/*
* Datadog API V1 Collection
*
* Collection of all Datadog Public endpoints.
*
* The version of the OpenAPI document: 1.0
* Contact: support@datadoghq.com
* Generated by: https://openapi-generator.tech
*/
/// SloCorrectionListResponse : A list of SLO correction objects
#[derive(Clone, Debug, PartialEq, S... |
use super::{spawner, Position, Rect, Viewport, Viewshed};
use rltk::{Algorithm2D, BaseMap, Point, RandomNumberGenerator, Rltk, RGB};
use specs::prelude::*;
// ------------------------------------------------------------------------------------------------------------------ //
#[derive(PartialEq, Copy, Clone)]
pub enum... |
mod name;
mod repository;
pub use name::*;
pub use repository::*;
use common::event::Event;
use common::model::{AggregateRoot, StringId};
use common::result::Result;
pub type CategoryId = StringId;
#[derive(Debug, Clone)]
pub struct Category {
base: AggregateRoot<CategoryId, Event>,
name: Name,
}
impl Categ... |
// Copyright (c) The diem-devtools Contributors
// SPDX-License-Identifier: MIT OR Apache-2.0
use crate::serialize::serialize_report;
use chrono::{DateTime, FixedOffset};
use indexmap::map::IndexMap;
use std::{borrow::Cow, io, iter, time::Duration};
/// The root element of a JUnit report.
#[derive(Clone, Debug)]
pub ... |
//! Expressions
//!
//! See: [6.4 Expressions](http://erlang.org/doc/apps/erts/absform.html#id87350)
use ast;
use ast::clause;
use ast::common;
use ast::literal;
use ast::pat;
pub type LocalCall = common::LocalCall<Expression>;
pub type RemoteCall = common::RemoteCall<Expression>;
pub type Match = common::Match<pat::P... |
use std::{
env,
ffi::OsString,
fs, io,
path::{Path, PathBuf},
};
use crate::common::resolve::{is_valid_executable, resolve_current_user};
use crate::common::{error::Error, Environment};
use crate::exec::RunOptions;
use crate::log::user_warn;
use crate::system::{Group, Process, User};
use super::cli::S... |
use serde::de::Visitor;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::convert::{From, TryFrom, TryInto};
use crate::be_bytes::BeBytes;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct EthereumType<const N: usize, const H: bool>([u8; N]);
impl<const N: usize, const H: bool> Seri... |
mod error;
pub mod progress;
pub use error::*;
use crate::controller::base::ProcessOutcome;
use async_trait::async_trait;
use core::fmt::{Debug, Formatter};
pub enum ReconcileState<I, C, D> {
Ignore(I),
Construct(C),
Deconstruct(D),
}
impl<I, C, D> Debug for ReconcileState<I, C, D> {
fn fmt(&self, f... |
#[doc = "Register `FDCAN_PSR` reader"]
pub type R = crate::R<FDCAN_PSR_SPEC>;
#[doc = "Register `FDCAN_PSR` writer"]
pub type W = crate::W<FDCAN_PSR_SPEC>;
#[doc = "Field `LEC` reader - Last Error Code"]
pub type LEC_R = crate::FieldReader;
#[doc = "Field `LEC` writer - Last Error Code"]
pub type LEC_W<'a, REG, const O... |
use std::ffi::c_void;
use std::ops::{Deref, DerefMut};
use svm_runtime::Runtime;
use svm_types::Type;
/// A Smart-Pointer for a [`Runtime`] implementation.
///
/// Its main usage will be FFI related code.
#[repr(transparent)]
pub struct RuntimeRef {
inner: Box<dyn Runtime>,
}
static RUNTIME_REF_TYPE: Type = Type... |
use std::net::{SocketAddr, TcpStream, TcpListener, ToSocketAddrs};
use std::io::{Write, BufReader};
use serde::{Serialize, Deserialize};
//
// Client to Daemon packets
//
#[derive(Serialize, Deserialize, Debug)]
pub enum DaemonPktType
{
ClientRegistration(ClientRegistrationPkt),
MutexCreation(MutexCreationPk... |
pub fn main() {
let data = Sample { d: 11111, ..Sample::default() };
println!("{:?}", data);
}
#[derive(Debug)]
struct Sample {
a: u32,
b: u32,
c: u32,
d: u32,
e: u32,
f: u32,
}
impl Default for Sample {
fn default() -> Self {
Sample { a: 1, b: 2, c: 3, d: 4, e: 5, f: 6 }
... |
use std::fs::File;
use std::io::Read;
use std::io::Write;
// Read as string
pub fn run2() {
let mut data = String::new();
let mut f = File::open("/etc/hosts").expect("Unable to open file");
f.read_to_string(&mut data).expect("Unable to read string");
println!("{}", data);
}
// Read as vec
pub fn run3... |
use std::collections::HashMap;
use std::ops::Index;
pub struct Image {
width: usize,
height: usize,
layers: Vec<Layer>,
}
impl Image {
pub fn new(width: usize, height: usize, data: &[u8]) -> Self {
Image {
width,
height,
layers: data.chunks(width * height).m... |
use crate::html::{BaseComponent, Scope};
/// A Yew Server-side Renderer.
#[cfg_attr(documenting, doc(cfg(feature = "ssr")))]
#[derive(Debug)]
pub struct ServerRenderer<COMP>
where
COMP: BaseComponent,
{
props: COMP::Properties,
hydratable: bool,
}
impl<COMP> Default for ServerRenderer<COMP>
where
COMP... |
//! IPC stuff for starting to split things into a client and server model.
use serde::{Deserialize, Serialize};
use std::collections::HashSet;
type SessionId = u64;
#[derive(PartialEq, Eq, Serialize, Deserialize, Hash)]
pub struct Session {
// Unique ID for this session
id: SessionId,
// Identifier for t... |
// stm32f3-liar-test src/main.rs
//
// A test harnesss for the 'liar' crate, which tests running it in no_std
// environment, specifically, on an STM32F3 Discovery development board.
//
// Copyright © 2017 Sean Bolton
//
// Licensed under the MIT/X11 license, see the included file 'LICENSE' for
// details.
// This use... |
fn largest<T: PartialOrd + Copy>(list: &[T]) -> T {
let mut largest = list[0];
for &item in list {
if item > largest {
largest = item;
}
}
largest
}
fn largest_ref<T: PartialOrd + Copy>(list: &[T]) -> &T {
let mut largest = &list[0];
for item in list {
if *it... |
const K_FACTOR: f32 = 32_f32;
pub enum GameResult {
Win,
Draw,
Loss,
Score(f32),
}
impl GameResult {
fn get_val(&self) -> &f32 {
match self {
GameResult::Win => &1_f32,
GameResult::Draw => &0.5,
GameResult::Loss => &0_f32,
GameResult::Score(i... |
pub struct HealthcareParameters {}
impl HealthcareParameters {
pub fn new() -> HealthcareParameters {
HealthcareParameters {}
}
}
impl Default for HealthcareParameters {
fn default() -> Self {
HealthcareParameters::new()
}
}
|
#[cfg(feature = "gen")]
extern crate cc;
#[cfg(feature = "module")]
extern crate fnv;
#[cfg(feature = "module")]
extern crate syn;
#[cfg(feature = "gen")]
pub mod gen;
#[cfg(feature = "module")]
pub mod module;
use std::env;
use std::path::{Path, PathBuf};
use std::process::Command;
fn check_verilator_bin(path: &Pat... |
use {
hyper::{
service::{make_service_fn, service_fn},
Body,
StatusCode,
Request,
Response,
Result,
Server,
},
std::net::SocketAddr,
std::io::{Read, BufRead},
std::time::{Duration, Instant},
std::fs,
structopt::StructOpt,
tokio::st... |
use crate::eval::prelude::*;
impl Eval<&ast::ExprLet> for ConstCompiler<'_> {
fn eval(
&mut self,
expr_let: &ast::ExprLet,
used: Used,
) -> Result<Option<ConstValue>, crate::CompileError> {
match &expr_let.pat {
ast::Pat::PatPath(path) => {
if let Som... |
#[doc = "Register `MACPMTCSR` reader"]
pub type R = crate::R<MACPMTCSR_SPEC>;
#[doc = "Register `MACPMTCSR` writer"]
pub type W = crate::W<MACPMTCSR_SPEC>;
#[doc = "Field `PD` reader - Power down"]
pub type PD_R = crate::BitReader<PD_A>;
#[doc = "Power down\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq,... |
//
// Copyright (c) 2017, 2020 ADLINK Technology Inc.
//
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License 2.0 which is available at
// http://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0
// which is available at https://www.apache.or... |
//! Implementations of insecure block-cryptographic algorithms.
use std::collections::HashMap;
use rand;
use rand::Rng;
use utils::block::{BlockCipher, Algorithms, OperationModes, PaddingSchemes};
use utils::data::Data;
/// Encrypts data under a random choice of ECB or CBC.
///
/// A black box which encrypts some i... |
use std::fmt::Write;
use rosu_v2::prelude::{GameMode, Score, User};
use crate::{
embeds::{osu, Author, Footer},
util::{
constants::OSU_BASE,
datetime::how_long_ago_dynamic,
numbers::{with_comma_float, with_comma_int},
ScoreExt,
},
};
pub struct TopIfEmbed {
author: Aut... |
// Copyright 2017 PingCAP, Inc.
//
// 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 i... |
use std::collections::HashMap;
use std::fs;
fn main() -> Result<(), String> {
let input = fs::read_to_string("input/data.txt").map_err(|e| e.to_string())?;
let (map, creatures) = parse(&input);
Ok(())
}
fn evaluate_round(cave: &Cave, creatures: &Creatures) {
// determine turn order
//
}
enum S... |
mod benchmark;
mod fingerprint;
mod help;
mod upload;
mod util;
fn main() {}
|
use std::io;
fn main() {
let unit = get_unit();
let temperature = get_temp();
let (temperature, unit) = convertor(temperature, unit);
println!("\n👉🏻 Result: {} °{}", temperature, unit);
}
fn get_unit() -> char {
println!("Enter the temperature unit you want to convert from ('C' for celsius, 'F'... |
use ws;
use std::collections::HashMap;
pub struct Connections {
connections: HashMap<u64, ws::Sender>,
next_connection_id : u64,
}
impl Connections {
pub fn new() -> Self {
Self {
connections: HashMap::new(),
next_connection_id: 1
}
}
pub fn add(&mut self,... |
use std::cmp::{Eq, Ord, Ordering, PartialEq, PartialOrd};
use std::f64;
use std::hash::{Hash, Hasher};
use std::mem;
use std::ops;
pub fn number_of_digits(num: f64) -> f64 {
f64::floor(f64::log10(num) + 1.0)
}
pub fn digit_at_index(index: u32, num: u32) -> u8 {
let mask = u32::pow(10, index);
((num / mask... |
use rand::{distributions::Alphanumeric, prelude::*};
#[allow(unused)]
pub fn print_type_of<T>(_: &T) {
println!("{}", std::any::type_name::<T>())
}
#[allow(unused)]
pub fn gen_rand_string(digits: usize) -> String {
rand::thread_rng()
.sample_iter(&Alphanumeric)
.take(digits)
.map(char:... |
use std::fs;
use intcode::{Computer, InterpretStep};
fn main() {
let input: Vec<i64> = fs::read_to_string("input")
.unwrap()
.split(',')
.map(|n| n.trim().parse().unwrap())
.collect();
let cpu = Computer::from(&input[..]);
part1(cpu.clone());
part2(cpu.clone());
}
fn... |
use super::ApiError;
use futures_util::SinkExt;
use serde::{Deserialize, Serialize};
use tokio::net::TcpStream;
use tokio_stream::StreamExt;
use tokio_tungstenite::{MaybeTlsStream, WebSocketStream};
use uuid::Uuid;
/* Documentation for SSO integration:
* https://github.com/Nexus-Mods/sso-integration-demo */
pub stru... |
mod dummy_system;
mod shadow_dummy_system;
pub mod ingame;
pub mod serialization;
//pub use self::{dummy_system::DummySystem, shadow_dummy_system::ShadowDummySystem};
|
#[doc = "Reader of register ENC_CONFIG"]
pub type R = crate::R<u32, super::ENC_CONFIG>;
#[doc = "Writer for register ENC_CONFIG"]
pub type W = crate::W<u32, super::ENC_CONFIG>;
#[doc = "Register ENC_CONFIG `reset()`'s with value 0"]
impl crate::ResetValue for super::ENC_CONFIG {
type Type = u32;
#[inline(always... |
use actix_web::{
web::{Data, Json, Path},
Responder,
};
use tracing::info;
use tracing::instrument;
use htsget_http::{post, Endpoint, PostRequest};
use htsget_search::htsget::HtsGet;
use crate::AppState;
use super::handle_response;
/// POST request reads endpoint
#[instrument(skip(app_state))]
pub async fn read... |
use std::error::Error;
use std::fmt::{self, Display};
use gfx_hal::{
adapter::MemoryTypeId,
buffer,
memory::{Properties},
Backend, Device, MemoryType,
};
#[derive(Debug)]
pub enum BufferError {
AllocationError(gfx_hal::device::AllocationError),
BindError(gfx_hal::device::BindError),
Creat... |
extern crate libc;
use self::libc::c_char;
#[link(name = "pcap")]
extern "C" {
// Opening a capture handle for reading
pub fn pcap_lookupdev(errbuf: *mut c_char) -> *mut c_char;
// Getting library version information
pub fn pcap_lib_version() -> *const c_char;
}
|
pub use {
windows_dll_codegen::dll,
once_cell,
};
use winapi::{
shared::{
minwindef::{WORD, FARPROC},
},
um::winnt::{LPCSTR, LPCWSTR},
};
#[inline]
pub unsafe fn load_dll_proc_ordinal(name: &'static str, proc: Proc, name_lpcwstr: LPCWSTR, proc_ordinal: WORD) -> Result<FARPROC, Error> {
... |
//! The trap module contains exceptions and interrupts.
#![allow(dead_code)]
use crate::cpu::*;
/// All kinds of exceptions, an unusual condition occurring at run
/// time associated with an instruction in the current hardware thread.
#[derive(Debug)]
pub enum Exception {
InstructionAddressMisaligned,
Instru... |
use async_std::io;
use async_std::net::{
IpAddr, Ipv4Addr, Shutdown, SocketAddr, TcpListener, TcpStream, ToSocketAddrs,
};
use async_std::prelude::*;
use async_std::task;
use std::str;
const SOCKS5_VERSION: u8 = 0x05;
const SOCKS5_AUTH_METHOD_NONE: u8 = 0x00;
const SOCKS5_CMD_TCP_CONNECT: u8 = 0x01;
const SOCKS5_RSV... |
use super::*;
/// A link.
///
/// # Semantics
///
/// This is either a link to an internal element or an external website or file.
///
/// # Syntax
///
/// There a 4 formats of links:
///
/// - radio link: `PRE1 RADIO POST1`
/// - angle link: `<PROTOCOL:PATH>`
/// - plain link: `PRE2 PROTOCOL:PATH2 POST2`
/// - bracke... |
#[doc = "Reader of register DSI_GVCIDR"]
pub type R = crate::R<u32, super::DSI_GVCIDR>;
#[doc = "Reader of field `VCID`"]
pub type VCID_R = crate::R<u8, u8>;
impl R {
#[doc = "Bits 0:1 - VCID"]
#[inline(always)]
pub fn vcid(&self) -> VCID_R {
VCID_R::new((self.bits & 0x03) as u8)
}
}
|
//! This test case demonstrates correct use of the `#[codec(crate = path)]` attribute.
use parity_scale_codec::{self as codec, Encode, MaxEncodedLen};
#[derive(Encode, MaxEncodedLen)]
#[codec(crate = codec)]
struct Example;
fn main() {
let _ = Example::max_encoded_len();
}
|
use Point;
use Circle;
use Path;
use std::f32;
use std::i32;
use std::cmp::*;
// use stf::fmt::*;
static LEN: usize = 66_049;
pub fn point_to_idx(point: &Point::Point, size: usize, width: u32) -> Option<usize> {
if point.x < 0 || point.y < 0 || point.x >= width as i32 || point.y > size as i32 / width as i32 {
... |
//! Define types which validate their inputs for use throughout the app.
use serde_derive::Deserialize;
#[derive(Debug, PartialEq, Deserialize)]
pub struct Url(String);
impl Url {
/// Get a URL. `Err` if the item passed in is not a spec-conformant URL.
pub fn new(unvalidated_url: &str) -> Result<Url, String>... |
use serde_piecewise_default::*;
use serde::{Deserialize, Deserializer};
extern crate serde;
extern crate serde_json;
extern crate serde_piecewise_default;
#[derive(DeserializePiecewiseDefault)] //~ ERROR the trait bound `Example: std::default::Default` is not satisfied [E0277]
struct Example {
datum: bool,
}
fn ... |
fn main() {
println!("This is here just for dockerfile build");
} |
use nu_engine::{eval_block, CallExt};
use nu_protocol::ast::Call;
use nu_protocol::engine::{CaptureBlock, Command, EngineState, Stack};
use nu_protocol::{
Category, Example, IntoInterruptiblePipelineData, IntoPipelineData, PipelineData, ShellError,
Signature, Span, SyntaxShape, Value,
};
#[derive(Clone)]
pub s... |
pub fn fighter_name(name: &str) -> String {
match name {
"Captain" => String::from("Captain Falcon"),
"Dedede" => String::from("King Dedede"),
"Diddy" => String::from("Diddy Kong"),
"Donkey" => String::from("Donkey Kong"),
"Falco" => S... |
#[cfg(all(target_vendor = "apple", not(feature = "getrandom")))]
pub use darwin::entropy_from_system;
#[cfg(all(
any(target_os = "linux", target_os = "android"),
not(feature = "getrandom")
))]
pub use linux::entropy_from_system;
#[cfg(all(windows, not(target_vendor = "uwp"), not(feature = "getrandom")))]
pub use wind... |
#[doc = "Register `WRP2R_PRG` reader"]
pub type R = crate::R<WRP2R_PRG_SPEC>;
#[doc = "Register `WRP2R_PRG` writer"]
pub type W = crate::W<WRP2R_PRG_SPEC>;
#[doc = "Field `WRPSG2` reader - Bank 2 sector group protection option status byte Setting WRPSGn2 bits to 0 write protects the corresponding group of four consecut... |
//! Async-graphql integration with Tide
//!
//! # Examples
//! *[Full Example](<https://github.com/async-graphql/examples/blob/master/tide/starwars/src/main.rs>)*
#![warn(missing_docs)]
#![allow(clippy::type_complexity)]
#![allow(clippy::needless_doctest_main)]
#![forbid(unsafe_code)]
use async_graphql::http::Multipa... |
let odds_squared: Vec<_> = (1..100)
.filter(|x| x % 2 != 0)
.map(|x| x * x)
.collect();
|
#![feature(panic_implementation)]
#![feature(abi_x86_interrupt)]
#![feature(asm)]
#![no_std]
#![cfg_attr(test, allow(dead_code, unused_macros, unused_imports))]
#[cfg(test)]
extern crate std;
#[macro_use]
extern crate lazy_static;
extern crate bootloader;
extern crate spin;
extern crate volatile;
extern crate uart_16... |
use std::str::Chars;
use std::collections::BTreeMap;
use std::collections::btree_map::Entry::{Occupied, Vacant};
use std::str::FromStr;
use std::slice::Iter;
use lexer::{Lexeme, Cursor};
pub enum ParameterValue {
String{line:usize, value:String},
List(List),
Map(Map),
}
impl ParameterValue {
pub fn... |
#[doc = "Register `AXIMC_COMP_ID_3` reader"]
pub type R = crate::R<AXIMC_COMP_ID_3_SPEC>;
#[doc = "Field `PREAMBLE` reader - PREAMBLE"]
pub type PREAMBLE_R = crate::FieldReader;
impl R {
#[doc = "Bits 0:7 - PREAMBLE"]
#[inline(always)]
pub fn preamble(&self) -> PREAMBLE_R {
PREAMBLE_R::new((self.bit... |
pub fn sum_of_multiples(limit: u32, factors: &[u32]) -> u32 {
let mut multiples: Vec<u32> = vec![];
for factor in factors.iter() {
multiples.extend(
(1..)
.take_while(|x| factor * x < limit)
.map(|x| factor * x)
);
}
multiples.sort();
multi... |
fn main() {
let raw = include_str!("input.txt");
println!("Answer #1: {}", sum(raw));
println!("Answer #2: {}", sum_mid(raw));
}
fn sum(input: &str) -> u32 {
let mut total: u32 = 0;
let mut s = input.char_indices().peekable();
while let Some((_, ch)) = s.next() {
match s.peek() {
... |
use serde::{Deserialize, Serialize};
use typesense::document::Document as DocumentTrait;
use typesense::Document;
#[test]
fn derived_document_generates_schema() {
let schema = Company::collection_schema();
let expected = serde_json::json!(
{
"name": "companies",
"fields": [
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.