text stringlengths 8 4.13M |
|---|
use crate::models::{
schema::{pageviews, stats, websites},
AuthUser, Browser, DeviceCategory, OperatingSystem, Page, Pageview,
Referrer, Stat, Stats, SystemStats, Website,
};
use crate::utils::{get_days, get_months, Db, DAILY_FORMAT, MONTHLY_FORMAT};
use actix_web::{error::Error as ActixError, web, HttpResp... |
// Copyright 2017 pdb Developers
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or distributed except according to tho... |
use std::collections::HashMap;
use std::fmt::{Debug, Formatter};
use std::fs;
#[macro_use]
extern crate lazy_static;
lazy_static! {
static ref ROLL_FREQUENCY: HashMap<usize, usize> =
HashMap::from([(3, 1), (4, 3), (5, 6), (6, 7), (7, 6), (8, 3), (9, 1)]);
static ref POSSIBLE_DICE_ROLLS: Vec<(usize, us... |
use std::fs::File;
use std::io::Read;
fn main(){
let mut file = File::open("input.txt").expect("opening file");
let mut text = String::new();
file.read_to_string(&mut text).expect("reading file");
const MAX: usize = 1000;
let mut patches = vec![vec![0u8; MAX]; MAX];
for line in text.lines(){ ... |
pub mod header;
pub mod proposer;
pub mod transaction;
pub mod voter;
use crate::crypto::hash::{Hashable, H256};
use crate::experiment::performance_counter::PayloadSize;
/// A block in the Prism blockchain.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Block {
/// The header of the block.
pub head... |
#![deny(
anonymous_parameters,
bad_style,
missing_copy_implementations,
missing_debug_implementations,
unused_extern_crates,
unused_import_braces,
unused_results,
unused_qualifications,
)]
// This file is an adaptation of https://github.com/PyO3/pyo3-built
// pyo3-built seems not releas... |
fn main() {
{
let tup = (500, 3.0, 'a'); // 推导类型
let (aa, bb, cc) = tup;
println!("{:?}", aa);
println!("{:?}", bb);
println!("{:?}", cc);
}
{
let tup: (i32, f32, char) = (500, 3.0, 'a'); // 指定类型
let (aa, bb, cc) = tup;
println!("{:?}", aa);
... |
#![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 connected_cluster {
use crate::models::*;
use reqwest::StatusCode;
use snafu::{ResultExt, Snafu};
pub ... |
extern crate steel;
extern crate steel_derive;
extern crate steel_repl;
use steel::steel_vm::{engine::Engine, register_fn::RegisterAsyncFn};
use steel_repl::repl::repl_base;
use std::env::args;
use std::fs;
use std::process;
// use env_logger::Builder;
// use log::LevelFilter;
fn main() {
// env_logger::init();... |
impl Solution {
pub fn max_length(arr: Vec<String>) -> i32 {
let (mut ans,n) = (0,arr.len());
for i in 0..(1 << n){
let mut st = vec![0;26];
let mut flag = false;
for j in 0..n{
if (i >> j) & 1 == 1 {
for ch in arr[j].chars(){
... |
extern crate r2d2;
extern crate r2d2_mongodb;
use actix::prelude::*;
use crate::model::users::UserRecord;
use crate::model::users::UserReturned;
use actix_web::Error;
use bson::from_bson;
use crate::model::users::User;
use actix_web::{http, web, App, HttpRequest, HttpResponse, HttpServer};
use actix_web::http::{Sta... |
use core::fmt;
use std::collections::HashMap;
use syn::parse::{Parse, ParseStream};
use syn::{Meta, NestedMeta, Token};
use crate::error::Error;
use crate::parser::{parse_enable_disable, parse_shorthand};
use crate::utils::PathExt;
#[derive(Clone, PartialEq, Eq)]
pub struct Forward {
default_state: bool,
fie... |
pub mod image_generator {
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::Duration;
use async_std::task;
use crate::image::image::{Image, Pixel};
use crate::image_dimensions::image_dimensions::ImageDimensions;
use crate::mandelbrot_pixel_calculation::mandelbrot_pixel_calculat... |
use std::rc::Rc;
enum RcList<T> {
Cons(T, Rc<RcList<T>>),
Nil,
}
pub fn list_main() {
let a = Rc::new(RcList::Cons(
5,
Rc::new(RcList::Cons(10, Rc::new(RcList::<i32>::Nil))),
));
println!("A count: {}", Rc::strong_count(&a));
let b = RcList::Cons(3, Rc::clone(&a));
print... |
use crate::utils::{AsyncJoinOnDrop, CollectionBatcher, Handler, HandlerFn, PeerAddress};
use async_trait::async_trait;
use event_listener_primitives::HandlerId;
use fs2::FileExt;
use futures::future::Fuse;
use futures::FutureExt;
use libp2p::multiaddr::Protocol;
use libp2p::{Multiaddr, PeerId};
use lru::LruCache;
use m... |
// q0011_container_with_most_water
struct Solution;
impl Solution {
pub fn max_area(height: Vec<i32>) -> i32 {
let mut max_area = 0;
for i in 0..height.len() {
let mut j = i + 1;
while j < height.len() {
let area = (j - i) as i32 * height[i].min(height[j]);
... |
/// Client for Genshin API
use std::{cell::Cell, collections::HashMap, future, iter::once, rc::Rc};
use anyhow::{anyhow, Context};
use chrono::{Local, TimeZone};
use futures::stream::{self, StreamExt, TryStreamExt};
use indicatif::{MultiProgress, ProgressBar};
use reqwest::{
header::{HeaderMap, HeaderValue, ACCEPT... |
use crate::{
grid::config::{ColoredConfig, SpannedConfig},
grid::records::{ExactRecords, Records, RecordsMut, Resizable},
settings::TableOption,
};
/// A horizontal/column span from 0 to a count rows.
#[derive(Debug)]
pub struct HorizontalPanel<S> {
text: S,
row: usize,
}
impl<S> HorizontalPanel<S... |
use rbtree::RBTree;
use rbtree::RBNode;
use std::ptr;
use apqueue::APQueue;
use apqueue::APNode;
use globe;
use std::f64::consts::PI;
use std::f64::consts::FRAC_PI_2;
const ZERO: f64 = 0.0f64;
const ONE: f64 = 1.0f64;
const TWO: f64 = 1.0f64;
const TWO_PI: f64 = PI * 2.0f64;
const HALF: f64 = 0.5f64;
pub struct Arc... |
use std::fmt;
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub enum Instruction {
Adc,
And,
Asl,
Bcc,
Bcs,
Beq,
Bit,
Bmi,
Bne,
Bpl,
Brk,
Bvc,
Bvs,
Clc,
Cld,
Cli,
Clv,
Cmp,
Cpx,
Cpy,
Dec,
Dex,
Dey,
Eor,
Inc... |
extern crate clipboard;
use clipboard::ClipboardProvider;
use clipboard::ClipboardContext;
fn example() {
let mut ctx: ClipboardContext = ClipboardProvider::new().unwrap();
println!("{:?}", ctx.get_contents());
ctx.set_contents("some string".to_owned()).unwrap();
}
fn main() {
example();
// print... |
// Copyright (c) 2017 oic developers
//
// 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>, at your
// option. All files in the project carrying such notice may not be copied,
// mo... |
extern crate videocore;
use videocore::bcm_host;
use videocore::dispmanx;
fn main() {
// first thing to do is initialize the broadcom host (when doing any graphics on RPi)
bcm_host::init();
// open the display
let display = dispmanx::display_open(0);
// get update handle
let update = dispman... |
use crate::cell::CellValue;
use crate::{Board, Cell};
use itertools::Itertools;
/// Simple syntax for creating an entire constraint group.
#[macro_export]
macro_rules! constraints {
($([$($size:expr, $value:expr $(,)?);* $(;)?])*) => {
vec![$(
vec![$(
$crate::ConstraintEntry { v... |
use riddle_common::Color;
use riddle_image::{packer::ImagePackerSizePolicy, Image, ImagePacker};
use riddle_math::vec2;
use riddle_math::{Rect, SpacialNumericConversion, Vector2};
use std::collections::{HashMap, HashSet};
use crate::rusttype_ext::*;
use crate::*;
/// Represents an image font, which is an Image contai... |
use crate::enums::{Align, CallbackTrigger, Color, Damage, Event, Font, FrameType, LabelType};
use crate::image::Image;
use crate::prelude::*;
use crate::utils::FlString;
use fltk_sys::input::*;
use std::{
ffi::{CStr, CString},
mem,
os::raw,
};
/// Creates an input widget
#[derive(WidgetBase, WidgetExt, Inp... |
use std::fmt;
use std::io;
use term::{stdout, color, Attr};
use std::str::Str;
use std::path::PathBuf;
use std::iter::IntoIterator;
use itertools::Itertools;
fn connected<'a, S, I>(s: I) -> String //'
where S: Str,
I: IntoIterator<Item=&'a S> //'
{
s.into_iter().map(|s| s.as_slice()).intersperse(" "... |
use async_trait::async_trait;
use mockall::predicate::*;
use mockall::*;
#[automock]
#[async_trait]
pub trait Sick {
async fn cough(&self) -> String;
}
pub async fn hospital(patient: &impl Sick) -> String {
patient.cough().await
}
#[cfg(test)]
mod test {
use super::*;
#[tokio::test]
async fn tes... |
use crate::{
chunk_map::ChunkMap,
filesystem,
items::{
BlockGroupItem, ChunkItem, CsumItem, DevExtent, DevItem, DevStatsItem, DirItem, ExtentItem,
FileExtentItem, InodeItem, InodeRef, RootItem, RootRef, UuidItem,
},
superblock::{ChecksumType, Superblock},
Checksum, DiskKey, DiskK... |
use std::io::{self, Read};
mod aes_ctr;
pub use self::aes_ctr::AesCtr;
pub trait Encryption {
fn encrypt(&mut self, data: &[u8], buf: &mut [u8]);
fn decrypt(&mut self, data: &[u8], buf: &mut [u8]);
}
pub struct Decryptor<'a> {
encryption: &'a mut Encryption,
stream: &'a mut Read,
}
impl<'a> Decrypt... |
use std::collections::HashMap;
use std::str::FromStr;
use regex::Regex;
#[derive(Debug)]
struct Grid {
tiles: Vec<Option<Point>>,
specials: Vec<Point>,
length: usize,
breadth: usize,
}
impl Grid {
#[allow(dead_code)]
fn new(input: &str) -> Grid {
let specials: Vec<Point> = input.lines... |
//! Contains environment specific logic.
use crate::utils::{DefaultRandom, Random, ThreadPool};
use std::sync::Arc;
/// Keeps track of environment specific information which influences algorithm behavior.
#[derive(Clone)]
pub struct Environment {
/// A wrapper on random generator.
pub random: Arc<dyn Random +... |
// Copyright 2020 The VectorDB Authors.
//
// Code is licensed under Apache License, Version 2.0.
use crate::planners::Planner;
#[derive(Debug)]
pub struct ScalarExpressionPlanner {
pub op: String,
pub arguments: Vec<Planner>,
}
impl ScalarExpressionPlanner {
pub fn new(op: String, arguments: Vec<Planner... |
//! list subcomAmand - List leetcode problems
//!
//! ```sh
//! leetcode-list
//! List problems
//!
//! USAGE:
//! leetcode list [FLAGS] [OPTIONS] [keyword]
//!
//! FLAGS:
//! -h, --help Prints help information
//! -s, --stat Show statistics of listed problems
//! -V, --version Prints ver... |
extern crate cifra;
use std::collections::HashSet;
use std::convert::TryFrom;
use std::env::args;
use std::fmt::{Display, Formatter};
use std::fs::{read_to_string, write};
use std::path::PathBuf;
use std::str::FromStr;
use clap::{App, AppSettings, Arg, ArgMatches};
use error_chain::bail;
use strum::IntoEnumIterator;
... |
use crate::{Replacer, Result, Source};
use structopt::StructOpt;
#[derive(Debug, StructOpt)]
#[structopt(
// hide author from help
author = "",
about = "",
raw(setting = "structopt::clap::AppSettings::ColoredHelp"),
raw(setting = "structopt::clap::AppSettings::NextLineHelp"),
raw(setting = "str... |
use std::{fmt::Display, vec};
pub struct Index<'a>(&'a str);
impl<'a> From<&'a str> for Index<'a> {
fn from(s: &'a str) -> Self {
Self(s)
}
}
struct Capitalize<'a>(&'a str);
impl<'a> Display for Capitalize<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let (in... |
use std::{io::ErrorKind, iter, sync::Arc, time::Duration};
use anyhow::{anyhow, bail, Context, Result};
use async_std::{
io::BufReader, net::TcpStream, os::unix::net::UnixStream, prelude::*, task,
};
use futures::{
channel::{
mpsc,
mpsc::{UnboundedReceiver as Receiver, UnboundedSender as Sender... |
use std::borrow::Cow;
use wasm_bindgen::JsValue;
pub type Result<T> = std::result::Result<T, Error>;
#[derive(Debug)]
pub struct Error {
kind: ErrorKind,
}
#[derive(Debug)]
enum ErrorKind {
CaughtFromJS(JsValue),
Custom(Cow<'static, str>),
}
impl Error {
pub fn caught_from_js(payload: JsValue) -> Se... |
use crate::error::NiaServerError;
use crate::error::NiaServerResult;
use crate::protocol::NiaKeyChord;
use crate::protocol::NiaMapping;
use crate::protocol::Serializable;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NiaRemoveMappingRequest {
key_chords: Vec<NiaKeyChord>,
}
impl NiaRemoveMappingRequest {
... |
use std::collections::BTreeMap;
use sentry_core::protocol::{self, Event, TraceContext, Value};
use sentry_core::{Breadcrumb, Level};
use tracing_core::{
field::{Field, Visit},
span, Subscriber,
};
use tracing_subscriber::layer::Context;
use tracing_subscriber::registry::LookupSpan;
use crate::Trace;
/// Conv... |
pub mod imagemagick;
pub mod image_tools;
mod util;
|
pub use libra_crypto::{
ed25519::{Ed25519PublicKey, Ed25519Signature},
hash::CryptoHash,
};
use anyhow::{ensure, Result};
use libra_crypto::ed25519::Ed25519PrivateKey;
use libra_crypto::test_utils::KeyPair;
use libra_crypto::PrivateKey;
use libra_wallet::{
key_factory::{ChildNumber, KeyFactory, Seed},
... |
#![allow(dead_code)]
extern crate nom;
extern crate nom_locate;
extern crate pretty_assertions;
#[macro_use]
extern crate lazy_static;
#[allow(dead_code)]
pub mod ast;
pub mod compile;
pub mod datastructures;
#[allow(dead_code)]
pub mod eval;
#[allow(dead_code)]
pub mod lex;
pub mod lua_stdlib;
pub mod macros;
pub mo... |
use crate::protogen::protos::mock::mock_service_client::MockServiceClient;
use crate::protogen::protos::mock::MockRequest;
mod protogen;
#[tokio::main]
async fn main() {
let mut client = MockServiceClient::connect("tcp://127.0.0.1:50052")
.await
.unwrap();
let mut stream = client
.mock(MockRequest {
... |
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
extern crate accel_mma84;
extern crate tessel;
use accel_mma84::Accelerometer;
use tessel::Tessel;
use std::thread::sleep;
use std::time::Duration;
fn main() {
// Acquire port A.
let (port_a, _) = Tessel::ports().unwrap();
// Create the accelerometer object and connect to the sensor.
let mut acc = Ac... |
use std::collections::HashMap;
#[derive(Serialize, Deserialize, Debug)]
pub struct Image {
#[serde(rename = "Id")]
id: String,
#[serde(rename = "ParentId")]
parent_id: String,
#[serde(rename = "RepoTags")]
repo_tags: Vec<String>,
#[serde(rename = "RepoDigests")]
repo_digests: Option<... |
use sp_runtime::traits::{GetNodeBlockType, Block as BlockT};
use substrate_test_runtime_client::runtime::Block;
/// The declaration of the `Runtime` type and the implementation of the `GetNodeBlockType`
/// trait are done by the `construct_runtime!` macro in a real runtime.
struct Runtime {}
impl GetNodeBlockType for ... |
//! History API types.
use super::object::Object;
/// Timetoken type used in history API.
pub type Timetoken = u64;
/// A history item.
#[derive(Debug, Clone, PartialEq)]
pub struct Item {
/// The message payload.
pub message: Object,
/// Message timetoken.
pub timetoken: Timetoken,
/// The mes... |
//! Repo Companies table.
use diesel;
use diesel::connection::AnsiTransactionManager;
use diesel::dsl::sql;
use diesel::pg::Pg;
use diesel::prelude::*;
use diesel::query_dsl::RunQueryDsl;
use diesel::sql_types::VarChar;
use diesel::Connection;
use errors::Error;
use failure::Error as FailureError;
use stq_types::{Al... |
use std::iter::Peekable;
pub struct PeekWhile<'a, I, F>
where
I: Iterator + 'a,
{
iter: &'a mut Peekable<I>,
f: F,
}
impl<'a, I, F> Iterator for PeekWhile<'a, I, F>
where
I: Iterator + 'a,
F: for<'b> FnMut(&'b <I as Iterator>::Item) -> bool,
{
type Item = <I as Iterator>::Item;
fn next(&m... |
#![feature(proc_macro_hygiene, decl_macro)]
#[macro_use]
extern crate rocket;
#[macro_use]
extern crate diesel;
#[macro_use]
extern crate diesel_migrations;
use rocket::{fairing::AdHoc, Rocket};
use rocket_contrib::serve::StaticFiles;
mod config;
use config::CONFIG;
mod cors;
mod jwks;
mod connection;
use connecti... |
use super::*;
use std::io::Read;
use byteorder::{LittleEndian, ReadBytesExt};
pub struct OpIterator<'a> {
pub iter: &'a [u8],
nesting: usize
}
#[derive(Debug, Clone)]
pub struct BrTable<'a> {
pub count: u32,
raw: &'a [u8],
pub default: u32,
}
#[derive(Debug, Clone)]
pub struct BrTableArmIterator<... |
use crate::prelude::*;
/// This is a mirror of the system that can reflect the current state of the system.
#[derive(Debug)]
pub(crate) struct SystemMirror {
inner_system: RwLock<System>,
inner_snapshot: RwLock<SystemSnapshot>,
}
impl SystemMirror {
pub(crate) async fn refresh_all(&self) -> SystemSnapshot... |
extern crate cpal;
use cpal::traits::{DeviceTrait,EventLoopTrait, HostTrait};
use cpal::{StreamData,UnknownTypeOutputBuffer};
use std::sync;
use std::sync::mpsc;
use std::thread;
enum PlayerCommand {
Stop {},
}
fn setup_stream(song: sync::Arc<mod_player::Song>) -> mpsc::Sender<PlayerCommand> {
let host = cpal... |
use crate::*;
use axum::http::Uri;
use uuid::Uuid;
#[derive(Debug, Deserialize)]
pub(crate) struct TwitchOauthRequest {
pub code: String,
pub scope: String,
pub state: Option<String>,
}
#[derive(Serialize)]
pub(crate) struct TwitchCodeExchangeRequest {
pub client_id: String,
pub client_secret: St... |
/*
MIT License
Copyright (c) 2017 Frederik Delaere
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... |
use super::car::*;
use super::msg;
use rosrust::api::raii::Publisher;
pub struct IbeoPublisher {
ibeo_vehicle_pub: Publisher<msg::ibeo_msgs::ObjectListEcu>,
protagonist_tf_pub: Publisher<msg::tf2_msgs::TFMessage>,
}
impl IbeoPublisher {
pub fn try_new() -> Option<IbeoPublisher> {
let ros_not_avai... |
#[doc = "Register `VMCR` reader"]
pub type R = crate::R<VMCR_SPEC>;
#[doc = "Register `VMCR` writer"]
pub type W = crate::W<VMCR_SPEC>;
#[doc = "Field `PVDE` reader - PVD enable"]
pub type PVDE_R = crate::BitReader;
#[doc = "Field `PVDE` writer - PVD enable"]
pub type PVDE_W<'a, REG, const O: u8> = crate::BitWriter<'a,... |
/// A voice note.
#[derive(Debug,Deserialize)]
pub struct Voice {
/// A unique identifier for the file.
pub file_id: String,
/// The duration of the audio in seconds.
pub duration: i32,
/// The MIME type of the file.
pub mime_type: Option<String>,
/// The size of the file.
pub file_size:... |
#[derive(PartialEq, Debug, Clone, Copy)]
pub struct Mat<const ROWS: usize, const COLS: usize> {
// Indexing - data[row][col]
data: [[f64; COLS]; ROWS]
}
impl <const ROWS: usize, const COLS: usize> Mat<ROWS, COLS> {
pub fn new(data: [[f64; COLS]; ROWS]) -> Mat<ROWS, COLS> {
Mat { data: data }
}
... |
use std::fmt;
use std::iter::FromIterator;
use std::rc::Rc;
pub enum SExpr {
Nil,
Bool(bool),
Integer(i32),
Float(f32),
Symbol(String),
List(Vec<SExpr>),
BinaryOp(Rc<dyn Fn(&SExpr, &SExpr) -> SExpr>),
UnaryOp(Rc<dyn Fn(&SExpr) -> SExpr>),
BuiltinOp(Rc<dyn Fn(&SExpr) -> SExpr>),
... |
/*
Copyright ⓒ 2016 rust-custom-derive contributors.
Licensed under the MIT license (see LICENSE or <http://opensource.org
/licenses/MIT>) or the Apache License, Version 2.0 (see LICENSE of
<http://www.apache.org/licenses/LICENSE-2.0>), at your option. All
files in the project carrying such notice may not be copied, m... |
pub use super::ctypes::convertion::{
ToRustBoolConvertion , ToWindowTextConvertion
};
pub use super::ctypes::win32::{
CCINT , UINT , BOOL , WNDPROC , WORD , DWORD , ATOM , WCHAR ,
LPCWSTR , LPCTSTR , PVOID , LPVOID , HANDLE , HWND , HINSTANCE ,
HMENU , HICON , HCURSOR , HBRUSH , HMODULE , UINT_PTR , L... |
#[cfg(feature = "serde")]
use serde::{Deserialize, Deserializer, Serialize, Serializer};
macro_rules! fixed_point_impl {
($name:ident, $int_bits:expr, $frac_bits:expr, $epsilons_type:ty, $value_type:ty) => {
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub struct $name {
... |
use bevy::{prelude::*, reflect::TypeUuid};
use serde::{Deserialize, Serialize};
use crate::prelude::{PrefabAppBuilder, PrefabData};
use super::PbrPrimitiveBundle;
///////////////////////////////////////////////////////////////////////////////
#[derive(Debug)]
pub struct Primitives {
default_material: Handle<Sta... |
use alloc::vec::Vec;
use util::Hash;
use super::{Blake, IV224};
pub struct Blake224(Blake<u32>);
impl Blake224 {
#[rustfmt::skip]
pub const fn new(salt: [u32; 4]) -> Self {
Self(Blake::<u32>::new(IV224, salt, 14))
}
}
impl Default for Blake224 {
#[rustfmt::skip]
fn default() -> Self {
... |
use z80::Z80;
pub fn ret(z80: &mut Z80, op: u8) {
z80.set_register_clock(1);
match op {
0xD8 => if z80.r.get_carry() != 1 { return ; },
0xD0 => if z80.r.get_carry() != 0 { return ; },
0xC0 => if z80.r.get_zero() != 0 { return ; },
0xC8 => if z80.r.get_zero() != 1 { r... |
use menu::anilist::AniListPagination;
use once_cell::sync::Lazy;
use regex::Regex;
use serenity::model::prelude::Message;
use serenity::prelude::Context;
static RE: Lazy<Regex> = Lazy::new(|| {
Regex::new(r"https://anilist\.co/(character|activity|studio|staff)/([0-9]+)?/?([^/]+)?/?")
.unwrap()
});
fn shou... |
use std::collections::{HashMap, HashSet};
pub type TypeName = String;
pub type TypeAttributeKey = String;
pub type TypeAtrributeValue = String;
pub type TypeAttributes = HashMap<TypeAttributeKey, TypeAtrributeValue>;
pub type TypeCollection = HashMap<TypeName, Type>;
pub type Types = HashSet<TypeName>;
pub type EnumV... |
#[doc = "Register `SPDIFRX_CR` reader"]
pub type R = crate::R<SPDIFRX_CR_SPEC>;
#[doc = "Register `SPDIFRX_CR` writer"]
pub type W = crate::W<SPDIFRX_CR_SPEC>;
#[doc = "Field `SPDIFRXEN` reader - SPDIFRXEN"]
pub type SPDIFRXEN_R = crate::FieldReader;
#[doc = "Field `SPDIFRXEN` writer - SPDIFRXEN"]
pub type SPDIFRXEN_W<... |
pub fn longest_increasing_path(matrix: Vec<Vec<i32>>) -> i32 {
use std::cmp::*;
let n = matrix.len();
if n == 0 {
return 0;
}
let m = matrix[0].len();
if m == 0 {
return 0;
}
let mut table = vec![vec![None; m]; n];
fn core(i: usize, j: usize, n: usize, m: usize, matr... |
use {
crate::{error::GraphQLParseError, Schema},
futures::Future,
http::{Method, Response, StatusCode},
juniper::{DefaultScalarValue, InputValue, ScalarRefValue, ScalarValue},
percent_encoding::percent_decode,
serde::Deserialize,
tsukuyomi::{
error::Error,
extractor::Extracto... |
use anyhow::{format_err, Error};
use async_trait::async_trait;
use log::error;
use rand::{thread_rng, RngCore};
use stack_string::{format_sstr, StackString};
use std::{collections::HashMap, fs::create_dir_all, path::Path};
use stdout_channel::StdoutChannel;
use tokio::{fs::remove_file, process::Command};
use url::Url;
... |
#![doc = "generated by AutoRust 0.1.0"]
#![allow(non_camel_case_types)]
#![allow(unused_imports)]
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct NetworkInterfaceListResult {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<Networ... |
use amethyst::renderer::rendy::mesh::Position;
use amethyst::ecs::{Component, DenseVecStorage};
struct Location {
pub current_position: Position
}
impl Location {
pub fn move_to(&mut self, pos: Position){
self.current_position = pos;
}
}
impl Component for Location {
type Storage = DenseVecSt... |
#[cfg(any(feature = "country-info", feature = "language-info"))]
pub mod geonames;
pub mod country;
pub mod language;
|
use bindgen::Builder;
use clap::Parser;
use pkg_config::Config;
use regex::Regex;
use semver::Version;
use std::fs;
use std::io;
use std::path::{Path, PathBuf};
use std::process::{exit, Command};
const MINIMUM_GEOS_VERSION: &str = "3.6.0";
struct GEOSConfig {
header: String,
version: Version,
}
/// standardi... |
#[doc = "Register `I3C_GETCAPR` reader"]
pub type R = crate::R<I3C_GETCAPR_SPEC>;
#[doc = "Register `I3C_GETCAPR` writer"]
pub type W = crate::W<I3C_GETCAPR_SPEC>;
#[doc = "Field `CAPPEND` reader - IBI MDB support for pending read notification This bit is written by software during bus initialization (i.e. I3C_CFGR.EN=... |
#![allow(dead_code, unused_imports, unused_variables)]
extern crate regex;
use std::collections::{HashMap,HashSet};
use regex::Regex;
const DATA: &'static str = include_str!("../../../data/03");
#[derive(Copy, Clone, Debug)]
struct Claim {
id: usize,
left: usize,
right: usize,
width: usize,
heig... |
#[doc = "Reader of register CTRL"]
pub type R = crate::R<u32, super::CTRL>;
#[doc = "Writer for register CTRL"]
pub type W = crate::W<u32, super::CTRL>;
#[doc = "Register CTRL `reset()`'s with value 0x0aa0"]
impl crate::ResetValue for super::CTRL {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self... |
use svg::Document;
use svg::node::element::Path;
use svg::node::element::path::Data;
pub struct Shape {
pub depth: i32,
pub infill: f32,
pub shapeData: Data,
pub color: String
}
pub trait ShapeContract {
fn make(width: u32, height: u32, x: i32, y: i32) -> Self;
fn make_with_infill... |
#![allow(dead_code, unused_imports, unused_variables)]
use std::collections::{HashMap,HashSet,BTreeSet};
const DATA: &'static str = include_str!("../../../data/07");
type Input = HashMap<char, Vec<char>>;
fn main() {
let input = read_input();
println!("Part 01: {}", part1(&input));
println!("Part 02: {... |
//! Module for a sorted list using multiple lists of varying length.
//!
//! Copied from Grant Jenks' sorted containers.
// TODO:
// make sure the index is never truly empty (should be [0] if empty).
//
// other invariants?
#[cfg(test)]
mod tests;
use super::sorted_utils;
use std::default::Default;
use std::iter::Fr... |
use std::num::Wrapping;
pub struct MemoryBase<T> {
base: Wrapping<T>,
}
impl<T> MemoryBase<T>
where
T: Copy,
Wrapping<T>: std::ops::Sub<Output = Wrapping<T>> + std::ops::Add<Output = Wrapping<T>>,
{
pub fn new(documented: T, leaked: T) -> Self {
Self {
base: Wrapping(leaked) - Wrapping(documented),
}
}
... |
use serde::{Deserialize, Serialize};
use std::default::Default;
use std::convert::TryFrom;
use log::{error};
use redis::{FromRedisValue, ToRedisArgs, RedisResult, Value};
use super::redis_connection::{RedisConnection};
use super::InfocomError;
#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
pub enum Version {
... |
#[macro_use]
extern crate json;
extern crate winreg;
use std::io::prelude::*;
use std::fs::File;
use winreg::RegKey;
use winreg::enums::*;
use std::error::Error;
use std::env;
use std::path::Path;
use std::fs::OpenOptions;
use std::io::SeekFrom;
/// Finds the path where Steam is installed. Uses the Registry key locat... |
pub fn is_same_tree(p: Option<Rc<RefCell<TreeNode>>>, q: Option<Rc<RefCell<TreeNode>>>) -> bool {
fn core(p: Option<&Rc<RefCell<TreeNode>>>, q: Option<&Rc<RefCell<TreeNode>>>) -> bool {
if let Some(p_rc) = p {
if let Some(q_rc) = q {
p_rc.borrow().val == q_rc.borrow().val
... |
use crate::error::*;
use crate::config::MsgConfig;
use std::{collections::VecDeque, time::Instant};
pub struct RateLimiter {
buf: VecDeque<(Instant, String)>,
cfg: MsgConfig,
}
impl RateLimiter {
pub fn new(cfg: MsgConfig) -> RateLimiter {
RateLimiter {
buf: VecDeque::with_capacity(cf... |
use ggez::event::*;
use ggez::graphics;
use ggez::mint::Point2;
use ggez::timer;
use ggez::{Context, GameResult};
use game::Game;
use resources::Resources;
use super::main_state::MainState;
use super::GameWrapper;
use ggez::graphics::DrawParam;
pub struct VictoryState {
pub resources: Resources,
pub move_on:... |
//! Represent values.
use types;
fn mask(bits: usize) -> usize {
2_usize.pow(bits as u32) - 1
}
/// A field value.
pub enum FieldValue {
/// A boolean value, corresponding to `Field::Boolean`
Boolean(bool),
/// An integer value, corresponding to `Field::Integer`
Integer(usize),
/// An enumera... |
use super::GsnNode;
use crate::diagnostics::Diagnostics;
use std::collections::{BTreeMap, BTreeSet};
///
/// Entry function to all checks.
///
///
pub fn check_nodes(
diag: &mut Diagnostics,
nodes: &BTreeMap<String, GsnNode>,
excluded_modules: &[&str],
) {
check_node_references(diag, nodes, excluded_mo... |
use codespan::{CodeMap, Span};
use codespan_reporting::termcolor::StandardStream;
use codespan_reporting::{emit, ColorArg, Diagnostic, Label, Severity};
use std::fmt;
use std::str::FromStr;
use crate::parser::ExprParser;
use crate::semantics::Env;
/// SPARC expression executor.
pub struct Executor {
parser: ExprP... |
use std::env;
use std::path::PathBuf;
const LIBRARY_DIR_VARIABLE: &str = "VAPOURSYNTH_LIB_DIR";
fn main() {
// Make sure the build script is re-run if our env variable is changed.
println!("cargo:rerun-if-env-changed={}", LIBRARY_DIR_VARIABLE);
let windows = env::var("TARGET").unwrap().contains("windows"... |
#![allow(unused_parens)]
#![allow(unused_imports)]
use frame_support::{traits::Get, weights::Weight};
use sp_std::marker::PhantomData;
/// Weight functions for pallet_utility.
pub struct WeightInfo<T>(PhantomData<T>);
impl<T: frame_system::Config> pallet_utility::WeightInfo for WeightInfo<T> {
fn batch(c: u32) -> We... |
#![allow(non_upper_case_globals)]
#[repr(packed)]
pub struct DtPointer {
_size: u16,
_table: &'static [u64; 3]
}
pub static gdt: [u64; 3] = [
// All GDTs must start with a null entry
0,
// The code segment (readable + executable + is a data or code segment + present + is a 64-bit code segment)
... |
/*
* 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.
*/
//! F... |
extern crate rand;
mod philosopher;
mod table;
use philosopher::Philosopher;
use std::sync::{Arc, Mutex};
use std::thread;
use table::Table;
fn main() {
let table = Arc::new(Table {
forks: vec![
Mutex::new(()),
Mutex::new(()),
Mutex::new(()),
Mutex::new(())... |
// 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.