text stringlengths 8 4.13M |
|---|
#[doc = "Reader of register CH9_DBG_CTDREQ"]
pub type R = crate::R<u32, super::CH9_DBG_CTDREQ>;
#[doc = "Reader of field `CH9_DBG_CTDREQ`"]
pub type CH9_DBG_CTDREQ_R = crate::R<u8, u8>;
impl R {
#[doc = "Bits 0:5"]
#[inline(always)]
pub fn ch9_dbg_ctdreq(&self) -> CH9_DBG_CTDREQ_R {
CH9_DBG_CTDREQ_R... |
#[doc = "Reader of register WL_ENABLE"]
pub type R = crate::R<u32, super::WL_ENABLE>;
#[doc = "Writer for register WL_ENABLE"]
pub type W = crate::W<u32, super::WL_ENABLE>;
#[doc = "Register WL_ENABLE `reset()`'s with value 0"]
impl crate::ResetValue for super::WL_ENABLE {
type Type = u32;
#[inline(always)]
... |
#[derive(Debug)]
pub struct Stack <T>
{
stack: Vec<T>,
}
impl <T> Stack<T>
{
pub fn new (head: T) -> Self
{
Stack { stack: vec![ head ] }
}
pub fn head (&mut self) -> &mut T
{
self.stack.last_mut().expect("stack_empty")
}
pub fn push (&mut self, head: T)
{
self.stack.push(head);
}
pub fn pop (&mut... |
use walkdir::WalkDir;
use std::{collections::HashMap, hash::Hasher, io, path::{Path, PathBuf}};
use std::fs::File;
use twox_hash::XxHash64;
use gumdrop::Options;
use std::fs;
#[derive(Debug, Options)]
struct MyOptions {
#[options(help = "Root directory to scan")]
root: String,
#[options(help = "Enable ... |
use cocoa::base::{class, id};
use objc::runtime::BOOL;
use MTLCompareFunction;
pub trait MTLDepthStencilDescriptor {
unsafe fn new(_: Self) -> id {
msg_send![class("MTLDepthStencilDescriptor"), new]
}
unsafe fn depthCompareFunction(self) -> MTLCompareFunction;
unsafe fn setDepthCompareFunction... |
// include!("lib.rs");
fn main() {
// let tweet = Tweet{
// username: String::from("twttr"),
// content: String::from("first tweet ever")
// };
//
// println!("Summarize tweet: {}", tweet.summarize());
}
fn add(a: i32, b:i32) -> i32{
a+b
}
#[cfg(test)]
mod tests {
use super::*... |
use std::borrow::Cow;
use scroll::{ctx::TryFromCtx, Endian, Pread};
use crate::common::*;
use crate::msf::Stream;
/// Magic bytes identifying the string name table.
///
/// This value is declared as `NMT::verHdr` in `nmt.h`.
const PDB_NMT_HDR: u32 = 0xEFFE_EFFE;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum Str... |
#[cfg(unix)]
mod fuzzer;
#[cfg(unix)]
pub fn main() {
fuzzer::main();
}
#[cfg(not(unix))]
pub fn main() {
todo!("Frida not yet supported on this OS.");
}
|
use crate::name_resolution::TopLevelContext;
use crate::rustspec::*;
use core::iter::IntoIterator;
use core::slice::Iter;
use heck::TitleCase;
use itertools::Itertools;
use pretty::RcDoc;
use rustc_session::Session;
use rustc_span::DUMMY_SP;
use std::fs::File;
use std::io::Write;
use std::path;
use rustc_ast::node_id:... |
//! 一覧詳細情報取得APIのデータモデル
//!
//! 技術基準適合証明等を受けた機器の検索Web-APIのリクエスト条件一覧(Ver.1.1.1)
//!
//! https://www.tele.soumu.go.jp/resource/j/giteki/webapi/gk_req_conditions.pdf
use serde::{Deserialize, Serialize};
use serde_aux::field_attributes::deserialize_number_from_string;
/// 一覧詳細情報取得APIのリクエストパラメータ
#[derive(Serialize)]
pub st... |
extern crate time;
#[macro_use]
extern crate clap;
use clap::App;
use std::fs;
use std::path::Path;
use std::time::Duration;
use std::thread;
const SEC_PER_MIN: u64 = 60;
const MINUETS_PER_DAY: i32 = 1440;
const DEFAULT_DIRECTORY: &str = "/usr/share/tod_wallpaper/";
/// Calculate the curent image index and the del... |
#[doc = "Reader of register GPIO_CTRL"]
pub type R = crate::R<u32, super::GPIO_CTRL>;
#[doc = "Writer for register GPIO_CTRL"]
pub type W = crate::W<u32, super::GPIO_CTRL>;
#[doc = "Register GPIO_CTRL `reset()`'s with value 0x1f"]
impl crate::ResetValue for super::GPIO_CTRL {
type Type = u32;
#[inline(always)]
... |
//! # howto
//!
//! Instant coding answers with Google and StackOverflow.
//! Inspired by [gleitz/howdoi](https://github.com/gleitz/howdoi).
//!
//! ## Usage
//!
//! ```
//! # use futures::prelude::*;
//! # async move {
//! let mut answers = howto::howto("file io rust").await;
//!
//! while let Some(answer) = answers.n... |
extern crate serde_codegen;
extern crate syntex;
use std::env::var_os;
use std::fs::File;
use std::io::copy;
use std::path::Path;
use std::process::Command;
use serde_codegen::register;
use syntex::Registry;
fn main() {
let out_dir = var_os("OUT_DIR").expect("OUT_DIR not specified");
let out_path = Path::new... |
use std::sync::Arc;
use crate::bxdf::TransportMode;
use crate::primitive::Primitive;
use crate::interaction::SurfaceInteraction;
use crate::light::Light;
use crate::material::Material;
mod bvh;
pub use self::bvh::{ BvhAccel, SplitMethod };
pub trait Aggregate: Primitive { }
default impl<T> Primitive for T where T: A... |
use std::env;
fn move_(disk:i32, from : i32 , to : i32 , via :i32 ,n : i32 )
{ // let mut i :i32=n;
if disk == n
{
println!("this is a thing")
}
if disk >0
{
move_ (disk -1 , from , to, via,n );
//println!("Move disk from pole {} to pole {}", from, to);
move_ (... |
//! Contains post processing logic for solution.
use crate::construction::heuristics::InsertionContext;
mod advance_departure;
pub use self::advance_departure::AdvanceDeparture;
/// A trait which specifies the logic to apply post processing to solution.
pub trait PostProcessing {
/// Applies post processing to g... |
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
use simple_socket::{PostServing, SocketClient, SocketServer};
use podo_core_driver::AliveFlag;
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize)]
enum Request {
Hello(String),
Goodbye(String),
}
#[derive(Debug, Serialize, Deserialize)]... |
// ---------------------------------------------------------------------
// ZkConfig
// ---------------------------------------------------------------------
// Copyright (C) 2007-2021 The NOC Project
// See LICENSE for details
// ---------------------------------------------------------------------
use crate::collect... |
use ethers::{
abi::{Function, ParamType, Token, Tokenizable},
types::{Address, Bytes, U256},
};
use proptest::prelude::*;
pub fn fuzz_calldata(func: &Function) -> impl Strategy<Value = Bytes> + '_ {
// We need to compose all the strategies generated for each parameter in all
// possible combinations
... |
use crate::{keypair::PublicKey, result::Result};
use helium_crypto::{ecc_compact, ed25519, KeyType};
use io::{Read, Write};
use std::{convert::TryFrom, io};
pub trait ReadWrite {
fn read(reader: &mut dyn Read) -> Result<Self>
where
Self: std::marker::Sized;
fn write(&self, writer: &mut dyn Write) -... |
use crate::domain::model::{IPostRepository, NewPost, Post, User};
use diesel::pg::PgConnection;
use diesel::prelude::*;
use std::sync::{Arc, Mutex};
#[derive(Clone)]
pub struct PostRepository {
conn: Arc<Mutex<PgConnection>>,
}
impl PostRepository {
pub fn new(conn: Arc<Mutex<PgConnection>>) -> Self {
... |
use buttplug::{
client::{ButtplugClient, ButtplugClientDevice, VibrateCommand},
server::ButtplugServerOptions,
util::async_manager,
};
use futures::StreamExt;
use futures_timer::Delay;
use std::{sync::Arc, time::Duration};
fn main() {
println!("start...");
async_manager::block_on(async {
c... |
use std::fs;
use std::ops::Deref;
use std::path::PathBuf;
use regex::Regex;
#[derive(Debug, Clone)]
pub struct Tokenizer {
token_data: Option<TokenData>,
tokens: Vec<String>,
idx: usize,
}
impl Tokenizer {
pub fn new(pb: &PathBuf) -> Self {
let jack = fs::read_to_string(pb).unwrap();
l... |
extern crate proc_macro;
use {
codespan_reporting::{
files::SimpleFiles,
term::{self, termcolor::NoColor, Config},
},
proc_macro::TokenStream,
rewryte_generator::{Format, FormatType},
rewryte_parser::parser::{parse, Context},
std::{
fs,
io::{BufWriter, ErrorKind}... |
use crate::core;
use crate::core::{Error, Service, User, UserKey, UserToken};
use crate::driver;
// TODO(feature): Warning logs for bad requests.
/// User authentication using email address and password.
pub fn login(
driver: &driver::Driver,
service: &Service,
email: &str,
password: &str,
token_e... |
use crate::memory::phys_to_virt;
/// Mask all external interrupt except serial.
pub unsafe fn init_external_interrupt() {
// By default:
// riscv-pk (bbl) enables all S-Mode IRQs (ref: machine/minit.c)
// OpenSBI v0.3 disables all IRQs (ref: platform/common/irqchip/plic.c)
const HART0_S_MODE_INTERRUPT... |
extern crate adventofcode;
use adventofcode::d4::Filter;
use std::io;
fn main() -> io::Result<()> {
println!("{}", (240_298..784_956).filter(|&n| Filter::validate_p1(n)).count());
println!("{}", (240_298..784_956).filter(|&n| Filter::validate_p2(n)).count());
Ok(())
}
|
use std::marker::PhantomData;
use esp_idf_bindgen::*;
#[derive(Debug)]
pub struct Heap {
_marker: PhantomData<()>,
}
impl Heap {
#[cfg(target_device = "esp32")]
pub fn total_size() -> usize {
unsafe { heap_caps_get_total_size(MALLOC_CAP_32BIT) as usize }
}
pub fn free_size() -> usize {
unsafe { he... |
use date_tuple::DateTuple;
use month_tuple::MonthTuple;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use time_tuple::TimeTuple;
const UNIX_EPOCH_START_YEAR: u16 = 1970;
const SECONDS_IN_A_YEAR: u64 = 31557600;
const SECONDS_IN_A_MONTH: u64 = 2629800;
const SECONDS_IN_A_DAY: u64 = 86400;
/// Takes a year as a u... |
use crate::mock::{new_test_ext, Header, MockStorage, PosTable};
use crate::{
ChainConstants, DigestError, HashOf, HeaderExt, HeaderImporter, ImportError, NextDigestItems,
NumberOf, Storage, StorageBound,
};
use frame_support::{assert_err, assert_ok};
use futures::executor::block_on;
use rand::rngs::StdRng;
use ... |
pub mod load;
|
#![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 operations {
use crate::models::*;
use reqwest::StatusCode;
use snafu::{ResultExt, Snafu};
pub async f... |
use crate::ebr::{Arc, AtomicArc, Barrier, Ptr, Tag};
use std::sync::atomic::Ordering::{self, Relaxed, Release};
/// [`LinkedList`] is a wait-free self-referential singly linked list.
pub trait LinkedList: 'static + Sized {
/// Returns a reference to the forward link.
///
/// The pointer value may be tagge... |
// Copyright (c) The Starcoin Core Contributors
// SPDX-License-Identifier: Apache-2.0
use futures03::{stream::unfold, FutureExt, Stream, StreamExt};
use futures_timer::Delay;
use std::time::Duration;
pub fn interval(duration: Duration) -> impl Stream<Item = ()> + Unpin {
unfold((), move |_| Delay::new(duration).... |
#[cfg(all(unix, not(target_env = "musl")))]
#[global_allocator]
static GLOBAL: mimalloc::MiMalloc = mimalloc::MiMalloc;
use fnd::cli;
fn main() -> cli::Result<()> {
cli::run()
}
|
extern crate libc;
use libc::{c_int, c_uchar, c_char, c_void, timeval};
use std::ptr;
use std::ffi::CStr;
use std::collections::HashMap;
use std::slice;
pub mod codes;
// Define the structs used by the ldap c library.
#[repr(C)]
struct LDAP;
#[repr(C)]
struct LDAPMessage;
#[repr(C)]
struct LDAPControl;
#[repr(C)]
str... |
struct Solution;
impl Solution {
pub fn combine(n: i32, k: i32) -> Vec<Vec<i32>> {
let mut ans = Vec::new();
Self::helper(n, k, 1, &mut Vec::with_capacity(k as usize), &mut ans);
ans
}
fn helper(n: i32, k: i32, next: i32, tmp: &mut Vec<i32>, ans: &mut Vec<Vec<i32>>) {
if k =... |
use super::SocketAddr;
use super::Stream;
use std::io::Error;
use std::io::ErrorKind;
use tokio::net::{TcpListener, UnixListener};
pub enum Listener {
Unix(UnixListener),
Tcp(TcpListener),
}
impl Listener {
pub async fn bind(protocol: &str, addr: &str) -> std::io::Result<Self> {
match protocol {... |
#[doc = "Register `TX_SINGLE_COLLISION_GOOD_PACKETS` reader"]
pub type R = crate::R<TX_SINGLE_COLLISION_GOOD_PACKETS_SPEC>;
#[doc = "Field `TXSNGLCOLG` reader - Tx Single Collision Good Packets This field indicates the number of successfully transmitted packets after a single collision in the Half-duplex mode."]
pub ty... |
extern crate ws;
use std::path::Path;
use std::thread;
use std::io::{Read, Write, self};
use std::net::TcpStream;
use std::sync::mpsc::Sender;
use std::sync::mpsc::Receiver;
use std::ops::Deref;
use std::collections::HashSet;
use std::sync::{RwLock, Arc, Mutex};
use std::collections::HashMap;
use encoding::{Encoding, E... |
use std::collections::HashMap;
struct Game {
round: u32,
history: HashMap<u32, u32>,
last: u32,
}
impl Game {
fn new(start: &[u32]) -> Game {
// Insert all except last, last will be inserted when stepping.
let mut history = HashMap::new();
for (r, &n) in start.iter().take(start... |
use tic_tac_toe::{GameState, Player};
use std::collections::HashMap;
use sdl2::event::Event;
use sdl2::gfx::primitives::DrawRenderer;
use sdl2::keyboard::Keycode;
use sdl2::pixels::Color;
use sdl2::rect::{Point, Rect};
use sdl2::render;
use nalgebra as na;
// Base constants
const MARGIN: u32 = 10;
const CELL_SIZE: ... |
use std::env;
use std::fs::File;
use std::io::prelude::*;
use std::io::Read;
use std::io::SeekFrom;
use crate::gb;
pub struct Memory {
pub rom_bank0: Vec<u8>,
pub rom_bank1: Vec<u8>,
pub vram: Vec<u8>,
pub eram: Vec<u8>,
pub wram: Vec<u8>,
pub oam: Vec<u8>,
pub io: Vec<u8>,
pub hram: V... |
#[doc = "Reader of register IC_ENABLE_STATUS"]
pub type R = crate::R<u32, super::IC_ENABLE_STATUS>;
#[doc = "Slave Received Data Lost. This bit indicates if a Slave-Receiver operation has been aborted with at least one data byte received from an I2C transfer due to the setting bit 0 of IC_ENABLE from 1 to 0. When read ... |
use super::{Graph,Element,ElementType,SimResult};
use super::linalg::{Matrix,Vector,gaussian_elimination};
pub fn solve(gr: &Graph) -> SimResult
{
let (a,b) = build_eqns(gr);
// Solve Ax = b
let x = gaussian_elimination(&a, &b);
// Save results
let n = count_nets(gr);
let (v,i) = x.data.spli... |
#[doc = "Reader of register RANGE_INTR_SET"]
pub type R = crate::R<u32, super::RANGE_INTR_SET>;
#[doc = "Writer for register RANGE_INTR_SET"]
pub type W = crate::W<u32, super::RANGE_INTR_SET>;
#[doc = "Register RANGE_INTR_SET `reset()`'s with value 0"]
impl crate::ResetValue for super::RANGE_INTR_SET {
type Type = ... |
use logos::{Logos, Lexer as LLexer};
#[derive(Logos, Clone, Debug, PartialEq)]
pub enum ObjectT {
#[token("'", priority = 5)]
Quote,
#[token("`", priority = 5)]
QuasiQuote,
#[token(",", priority = 5)]
Unquote,
#[token(",@", priority = 5)]
UnquoteSplice,
#[token("#t", pri... |
/// An enum to represent all characters in the Lydian block.
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
pub enum Lydian {
/// \u{10920}: '𐤠'
LetterA,
/// \u{10921}: '𐤡'
LetterB,
/// \u{10922}: '𐤢'
LetterG,
/// \u{10923}: '𐤣'
LetterD,
/// \u{10924}: '𐤤'
LetterE,
... |
use syn::parse::{Parse, ParseStream, Result};
mod glsl;
use glsl::{Glsl, GlslLine};
mod yasl_block;
mod yasl_expr;
mod yasl_file;
mod yasl_ident;
mod yasl_item;
mod yasl_stmt;
mod yasl_type;
use yasl_file::YaslFile;
pub struct Shader {
pub glsl: String,
pub sourcemap: Vec<GlslLine>,
}
impl Parse for Shader... |
fn main() {
println!("Hello, world!");
let x: i64 = 257;
println!("{}!", x);
another_function(x as i8);
let x = 127;
let y = 3.0;
second_fn(x, y);
let sum: i32 = {
let x: i32 = 5;
let y: i32 = 7;
x + y
};
println!("The sum is: {}!", sum);
let x: i6... |
use std::slice;
use libc::c_uint;
use std::borrow::Cow;
use ::ffi;
use ::ffi::*;
use traits::{Named, FromRaw};
use mesh::*;
use ::scene::*;
pub struct Node<'a> {
raw: &'a ffi::AiNode
}
impl<'a> Named<'a> for Node<'a> {
#[inline]
fn name(&self) -> Cow<'a, str> {
self.raw.name.to_string_lossy()
... |
use lexer_lib as lexer;
use parser_lib as parser;
use gen_lib as gen;
use lib::Pprint;
use std::env;
use std::io::{stdin, stdout, Write};
use std::process::Command;
use std::os::unix::process::CommandExt;
fn get_args() -> (String, String) {
let mut path = String::new();
let mut args = env::args_os();
if args.len()... |
// Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the root directory of this source tree.
use crate::{
field::{FieldElement, StarkField},
utils::log2,
};
use utils::{collections::Vec, iterators::*, rayon, uninit_vector};... |
// Copyright (c) The Starcoin Core Contributors
// SPDX-License-Identifier: Apache-2.0
use anyhow::Result;
use starcoin_crypto::HashValue;
use starcoin_state_api::{ChainState, ChainStateReader};
use starcoin_types::{
account_address::AccountAddress,
block::{Block, BlockHeader, BlockInfo, BlockNumber, BlockStat... |
use amethyst::{
ecs::prelude::{Entities, Entity, Join, ReadExpect, ReadStorage, System, WriteStorage},
renderer::SpriteRender,
};
use crate::{
components::{Sprite, Sprites},
resources::SpriteResource,
};
pub struct SpriteSystem;
impl<'s> System<'s> for SpriteSystem {
type SystemData = (
E... |
extern crate crossbeam_channel;
use crossbeam_channel::{Sender, Receiver};
#[derive(Debug, Clone)]
pub struct Phone<S, R> {
sender: Sender<S>,
receiver: Receiver<R>,
}
impl<S, R> Phone<S, R> {
pub fn send(&self, msg: S) {
self.sender.send(msg)
}
pub fn recv(&self) -> Option<R> {
... |
pub(crate) const USAGE_MSG: &str = "usage: visudo [-chqsV] [[-f] sudoers ]";
const DESCRIPTOR: &str = "visudo - safely edit the sudoers file";
const HELP_MSG: &str = "Options:
-c, --check check-only mode
-f, --file=sudoers specify sudoers file location
-h, --help display help me... |
use crate::{error::ValueError, eval::Expr, EvalError};
use gc::{Finalize, Gc, Trace};
use std::{
collections::HashMap,
fmt::{Debug, Display},
};
#[derive(Clone, Trace, Finalize)]
pub enum NixValue {
Map(HashMap<String, Gc<Expr>>),
#[allow(dead_code)] // TODO: implement parsing for strings
Str(Strin... |
pub fn is_interleave(s1: String, s2: String, s3: String) -> bool {
let s1: Vec<char> = s1.chars().collect();
let s2: Vec<char> = s2.chars().collect();
let s3: Vec<char> = s3.chars().collect();
let n1 = s1.len();
let n2 = s2.len();
if n1 + n2 != s3.len() {
return false
}
let mut... |
extern crate ndarray;
pub mod levenshtein;
|
mod assets;
mod map;
pub use assets::MapAssetsListener;
pub use map::{MapEvents, MapEventsListener};
|
//! The simple python packaging tool ✨
#![deny(unsafe_code)]
#![deny(missing_docs)]
#![feature(format_args_nl)]
pub(crate) mod log;
mod errors;
mod init;
mod package;
pub use errors::{Error, Result};
pub use package::{Package, PackageId};
use sqlx::SqlitePool;
use std::{env, process};
const DEFAULT_LOCKFILE: &str... |
use battleship::*;
use iota_sc_utils::*;
use wasmlib::*;
use crate::consts::*;
use crate::helpers::*;
use crate::structures::*;
pub fn create_game(ctx: &ScFuncContext) {
ctx.log("create_game");
// Reads argument called "createGameRequestKey" and tries to deserialize it to the CreateGameRequest structure
... |
pub mod intcode;
pub mod sif;
pub mod intcode_old; |
use chrono::NaiveDateTime;
use schema::horus_pastes;
#[derive(AsChangeset, Identifiable, Serialize, Insertable, Queryable, Deserialize)]
#[table_name = "horus_pastes"]
pub struct HPaste
{
pub id: String,
pub title: Option<String>,
pub paste_data: String,
pub owner: i32,
pub date_added: NaiveDateTi... |
#[doc = "Register `MACL3A30R` reader"]
pub type R = crate::R<MACL3A30R_SPEC>;
#[doc = "Register `MACL3A30R` writer"]
pub type W = crate::W<MACL3A30R_SPEC>;
#[doc = "Field `L3A30` reader - Layer 3 Address 3 Field When the L3PEN0 and L3SAM0 bits are set in the L3 and L4 control 0 register (ETH_MACL3L4C0R), this field con... |
use crate::prelude::*;
use polars::prelude::*;
pub fn link_work_genders() -> Result<()> {
require_working_dir("goodreads")?;
let gender = LazyFrame::scan_parquet("../book-links/cluster-genders.parquet", default())?;
let books = LazyFrame::scan_parquet("gr-book-link.parquet", default())?;
let merged =... |
use crate::*;
use crate::primitives::*;
use ndarray::prelude::*;
use rand::prelude::ThreadRng;
use std::convert::TryFrom;
use crate::primitives;
macro_rules! assert_num_args {
($name:expr, $args:expr, $len:expr) => {
if $args.len() != $len {
panic!("{} requires {} arguments but got {}", $name,... |
//! This is more of a philosophy than a library
pub trait Dependee {
fn revision(&self) -> Revision;
}
#[derive(Debug)]
pub struct Current(Revision);
impl Current {
pub fn new() -> Self {
Self(Revision::INITIAL_CURRENT)
}
}
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub ... |
pub struct Complex {
pub real: f64,
pub imaginary: f64,
}
|
mod client;
pub mod models;
mod utils;
pub use client::VGMClient;
#[derive(Debug, thiserror::Error)]
pub enum VGMError {
#[error(transparent)]
RequestError(#[from] reqwest::Error),
#[error("no album found from search")]
NoAlbumFound,
#[error("invalid date format")]
InvalidDate,
}
pub(crate)... |
use utils;
pub fn problem_048() -> u64 {
let n = 1000;
let mut last_ten_digits = vec![0];
for i in 1..(n+1){
let digits = utils::as_digit_array(i);
let product = utils::power_digit_array_truncated(&digits, i as u32, 10);
last_ten_digits = utils::add_digit_array(&last_ten_digits, ... |
use libc;
use std::ffi::CString;
use td_rlua::{self, lua_State, Lua, LuaPush, LuaRead, LuaStruct, NewStruct};
use {NetMsg, ProtocolMgr};
impl NewStruct for NetMsg {
fn new() -> NetMsg {
NetMsg::new()
}
fn name() -> &'static str {
"NetMsg"
}
}
impl<'a> LuaRead for &'a mut NetMsg {
... |
// https://www.codewars.com/kata/array-dot-diff
fn array_diff<T: PartialEq>(a: Vec<T>, b: Vec<T>) -> Vec<T> {
a.into_iter()
.filter(|x| !b.contains(&x))
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_array_diff() {
assert_eq!(array_diff(vec![1,2], vec![1]), vec![2]);
assert... |
use sdl2::{keyboard::Keycode};
use std::collections::HashMap;
pub enum GameInput {
Move(f64, f64),
Jump,
Up,
Down,
Other(Keycode),
None,
}
pub struct InputManager {
inputs: Vec<GameInput>,
pub keyboard_states: HashMap<Keycode, bool>,
}
impl InputManager {
pub fn new() -> Self {
... |
#[cfg(not(feature = "loom"))]
mod loom {
pub use std::thread;
pub use std::sync;
pub fn model<F>(f: F)
where
F: Fn() + Sync + Send + 'static
{
f()
}
}
use std::num::NonZeroUsize;
use loom::sync::Arc;
use loom::thread;
use wfqueue::queue::{ WfQueue, EnqueueCtx, DequeueCtx };
... |
use crate::{Job, JobRequest};
use anyhow::Error;
use log::*;
use std::sync::Arc;
use tokio_postgres::{Client, NoTls, Row};
#[derive(Clone)]
pub struct DbHandle {
client: Arc<Client>,
}
impl DbHandle {
pub(crate) async fn new(url: &str) -> Result<Self, Error> {
let (client, connection) = tokio_postgres... |
#[doc = "Register `PTPPPSCR` reader"]
pub type R = crate::R<PTPPPSCR_SPEC>;
#[doc = "Field `TSSO` reader - TSSO"]
pub type TSSO_R = crate::BitReader;
#[doc = "Field `TSTTR` reader - TSTTR"]
pub type TSTTR_R = crate::BitReader;
impl R {
#[doc = "Bit 0 - TSSO"]
#[inline(always)]
pub fn tsso(&self) -> TSSO_R {... |
#[cfg(test)]
extern crate tempfile;
extern crate termion;
#[macro_use]
extern crate lazy_static;
#[cfg(test)]
mod tests;
use std::env;
use std::fs;
use std::io::{self, BufRead, BufReader, BufWriter, Write};
use std::ops::Range;
use termion::{
raw::IntoRawMode,
input::TermRead,
};
type Line = String;
type Buffer... |
use env_logger::init as log_init;
use failure::Error;
use std::fs;
use std::sync::Arc;
use super::configuration::configuration as read_configuration;
use super::server::{server, Context};
use super::store::redis::new_redis_store;
pub fn run_app() -> Result<(), Error> {
log_init();
let config = read_configura... |
// 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<TreeNode>>>,
}
impl TreeNode {
#[inline]
pub fn new(val: i32) -> Self {
TreeNode {
val,
lef... |
pub mod exp;
pub mod module;
pub mod stm;
pub mod util;
|
// Convenience functions for creating mappings for
// US keyboards
// vim: shiftwidth=2
use crate::keys::{KeyCode, Mapping, Repeat};
use std::collections::HashMap;
use KeyCode::*;
use lazy_static::lazy_static;
use std::default::Default;
pub struct USKeyboardLayout {
pub tilde: char,
pub tilde_shift: char,
pu... |
mod mongoclient;
use mongoclient::MongoClient;
#[tokio::main]
async fn main() -> std::io::Result<()> {
// let my_mongo_client = MongoClient::from_environment().await;
// let collection = MongoClient::collection_wrap(of: "something");
let coll = MongoClient::proxy_for("db", "collection").await;
coll.sim... |
pub mod prelude {
pub use super::HttpStatus;
}
pub enum HttpStatus {
Ok,
NotFound,
}
impl HttpStatus {
pub fn code(&self) -> u32 {
match self {
HttpStatus::Ok => 200,
HttpStatus::NotFound => 404,
}
}
pub fn msg(&self) -> &str {
match self {
... |
const WHITE_XYZ: [f64; 3] = [0.95047, 1.0, 1.08883];
const CIELAB_D: f64 = 6.0 / 29.0;
const CIELAB_M: f64 = (29.0 / 6.0) * (29.0 / 6.0) / 3.0;
const CIELAB_C: f64 = 4.0 / 29.0;
const CIELAB_A: f64 = 3.0;
const CIELAB_MATRIX: [[f64; 3]; 3] = [
[ 0.0 , 1.16, 0.0 ],
[ 5.0 , -5.0 , 0.0 ],
[ 0.0 , 2.0 , -2.... |
#![doc = "generated by AutoRust 0.1.0"]
#![allow(unused_mut)]
#![allow(unused_variables)]
#![allow(unused_imports)]
use super::{models, API_VERSION};
#[non_exhaustive]
#[derive(Debug, thiserror :: Error)]
#[allow(non_camel_case_types)]
pub enum Error {
#[error(transparent)]
VaultCertificates_Create(#[from] vaul... |
/*
MIT License
Copyright (c) 2021 Philipp Schuster
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 rights
to use, copy, modify, merge, publis... |
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under both the MIT license found in the
* LICENSE-MIT file in the root directory of this source tree and the Apache
* License, Version 2.0 found in the LICENSE-APACHE file in the root directory
* of this source tree.
*/
use p... |
// Underlying typed representation of task fields, shared across other parts of the code base
use std::ops::RangeInclusive;
#[derive(PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Annotation;
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Context<'a>(&'a str);
#[derive(PartialEq, Eq, PartialOrd,... |
#![allow(clippy::missing_safety_doc)]
use libc::*;
use std::ffi::CString;
use std::slice;
// types
pub enum CSymbolTable {}
pub enum CExpression {}
pub enum CParser {}
pub enum CppString {}
// simple types used for communications with C++
#[repr(C)]
pub struct Pair<T, U>(pub T, pub U);
pub type CStrList = Pair<si... |
// Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the root directory of this source tree.
use core::cmp;
use math::FieldElement;
use utils::collections::Vec;
// CONSTANTS
// =====================================================... |
mod util;
mod scanner;
mod parser;
mod resolver;
mod bash_backend;
mod rust_backend;
use std::env;
use std::process;
use std::fs;
fn usage(cmd: &str) {
eprintln!("Usage: {} {{-t|--target bash|rust}} <source.rss>", cmd);
process::exit(1);
}
fn main() {
let args: Vec<String> = env::args().collect();
i... |
// Copyright (C) 2020 Sebastian Dröge <sebastian@centricular.com>
//
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
use super::*;
/// `CSeq` header ([RFC 7826 section 18.20](https://tools.ietf.org/html/rfc7826#section-18.20)).
#[derive(Debug, Clone, Copy, PartialEq, Eq... |
use std::{io::{Read, Result, Write}, net::{TcpListener, TcpStream}};
use std::time::Duration;
use std::thread;
fn handle_connection(mut stream: TcpStream, wait_time: u64) -> Result<()> {
let mut buf = [0; 1024];
// 服务端需要接受用户输入, 但是为了而防止恶意输入, 不能无限等待用户, 需要设置一定的缓冲区
// 客户端可以通过\n表示返回信息结束
loop {
let b... |
#![feature(box_syntax, box_patterns)]
use core::fmt::Debug;
use std::collections::VecDeque;
use std::collections::HashMap;
#[derive(Debug, Clone)]
enum Term {
Literal(String),
Int(i64),
LogicVariable(String),
Pair(Box<Term>, Box<Term>),
Three(Box<Term>, Box<Term>, Box<Term>)
}
impl Into<Term> fo... |
use std::f32;
use types::Point2;
#[derive(Clone, Copy, Debug)]
pub struct BoundingBox {
pub topleft: Point2,
pub bottomright: Point2,
}
impl BoundingBox {
pub fn new(l: f32, r: f32, t: f32, b: f32) -> BoundingBox {
BoundingBox {
topleft: Point2::new(l, t),
bottomright: Poi... |
use std::sync::Arc;
use async_trait::async_trait;
use axum::{
extract::{rejection::JsonRejection, Extension, FromRequest},
routing::{get, post, Router},
};
use svc_utils::middleware::{CorsLayer, LogLayer, MeteredRoute};
use super::api::v1::class::{
commit_edition, create_timestamp, read, read_by_scope, re... |
// Copyright 2019, 2020 Wingchain
//
// 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... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.