text stringlengths 8 4.13M |
|---|
use std::collections::HashMap;
use nimiq_primitives::policy::Policy;
use nimiq_utils::math::log2;
use serde::{Deserialize, Serialize};
use crate::MacroBlock;
// Block inclusion proofs proof that a block is part of the blockchain.
// The proof consists of an interlink chain from the current election head down to the ... |
use std::collections::{HashMap, HashSet};
#[cfg(feature = "metrics")]
use std::sync::Arc;
use nimiq_account::ReservedBalance;
use nimiq_blockchain::Blockchain;
use nimiq_hash::{Blake2bHash, Hash};
use nimiq_keys::Address;
use nimiq_primitives::account::AccountType;
use nimiq_transaction::Transaction;
#[cfg(feature = ... |
use std::io;
use std::io::{BufReader,BufRead};
use std::fs::File;
use byteorder::{LittleEndian,ReadBytesExt};
fn main() -> io::Result<()> {
let file = File::open("foo.txt")?;
let mut reader = BufReader::new(file);
// read 3 integers i32, but doesn't work with Vec
let mut array = [0; 3];
loop {
... |
use crate::config::{MulletNodeConfig, MulletService};
use crate::service::kv::KeyValueService;
use crate::service::manager::ManagerService;
use crate::service::query::QueryService;
use crate::service::Service;
use crate::state::SharedMulletState;
use slog::debug;
use slog::o;
use slog::Logger;
pub struct Node {
co... |
//! 構文解析の状態管理
use super::*;
use std::rc::Rc;
type TokenIndex = usize;
type TokenList = Rc<[TokenData]>;
pub(crate) struct ParseContext {
tokens: TokenList,
index: TokenIndex,
}
impl ParseContext {
pub(crate) fn new(tokens: TokenList) -> Self {
ParseContext { tokens, index: 0 }
}
pub(cr... |
// Long and nested future chains can quickly result in large generic types.
#![type_length_limit = "16777216"]
extern crate arete;
extern crate env_logger;
extern crate uuid;
use arete::queue::Queue;
#[test]
fn it_publish() {
env_logger::init();
let mq = arete::queue::rabbitmq::Config::default().open().unwra... |
use tiny_skia::*;
fn main() {
let mut paint1 = Paint::default();
paint1.set_color_rgba8(50, 127, 150, 200);
paint1.anti_alias = true;
let mut paint2 = Paint::default();
paint2.set_color_rgba8(220, 140, 75, 180);
paint2.anti_alias = false;
let path1 = {
let mut pb = PathBuilder::ne... |
use std::fmt::Debug;
use async_trait::async_trait;
use crate::opt::Opt;
use crate::error::Result;
use crate::set::Set;
/// Callback will be used by `option` type such as [`BoolOpt`](crate::opt::bool::BoolOpt)
#[async_trait(?Send)]
pub trait ValueCallback: Debug {
#[cfg(not(feature="async"))]
fn call(&mut self... |
use std::path::{PathBuf};
use std::fs::{File};
use crate::assets::{AssetLoadError};
use std::collections::HashMap;
use std::sync::{RwLock};
pub trait Source: Send + Sync + 'static {
fn load(&self, path: &str) -> Result<Vec<u8>, AssetLoadError>;
fn set_loc(&mut self,path:&str);
fn loc(&self) -> String;
}
#[... |
pub mod board;
pub mod position;
pub mod rules;
pub use aga::board::Board19x19;
pub use aga::position::Position19x19;
pub use aga::rules::{Action, GamePhase};
|
use actix::prelude::*;
use rand::prelude::*;
use std::collections::{HashMap, HashSet};
use std::time::{Duration, Instant};
use uuid::Uuid;
use crate::db;
use crate::game_room::{self, GameRoom};
use shared::game;
use shared::message::{self, AdminAction};
macro_rules! catch {
($($code:tt)+) => {
(|| Some({ ... |
#![allow(unused)]
extern crate quick_xml;
use quick_xml::events::Event;
use quick_xml::Reader;
use std::io::Read;
struct Resource {
etag: String,
calendar_data: String,
}
struct Prop {
namespace: String,
local_name: String,
value: String,
}
impl Prop {
fn new() -> Prop {
Prop {
... |
// Copyright 2016 Google Inc. All Rights Reserved.
//
// Licensed under the MIT License, <LICENSE or http://opensource.org/licenses/MIT>.
// This file may not be copied, modified, or distributed except according to those terms.
#![feature(plugin, use_extern_macros, proc_macro_path_invoc)]
#![plugin(tarpc_plugins)]
ex... |
extern crate amqp;
extern crate fallible_iterator;
extern crate postgres;
extern crate r2d2;
extern crate r2d2_postgres;
extern crate uuid;
#[macro_use]
extern crate log;
use amqp::{protocol, AMQPError, Basic, Channel, Session, Table};
use fallible_iterator::FallibleIterator;
use r2d2::{Pool, PooledConnection};
use r2... |
mod common;
use common::*;
use nm::*;
fn main() {
let client = Client::new(Cancellable::NONE).unwrap();
let all_devices = client.devices();
let all_connections: Vec<_> = client
.connections()
.into_iter()
.map(|c| c.upcast::<Connection>())
.collect();
for device in a... |
use std::{
collections::HashMap,
env, fmt,
io::{self, Read},
path::PathBuf,
};
use dirs::home_dir;
use log::{debug, info, trace, warn};
use serde::Deserialize;
use crate::{
consul,
prompt::{prompt_default, prompt_password},
rancher_metadata, service, vault, FetchOpts,
};
pub trait Client ... |
// Copyright (C) 2014-2015 Mickaël Salaün
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, version 3 of the License.
//
// This program is distributed in the hope that it will be use... |
use config::Region;
use color::RGB8;
use dxgcap::{ DXGIManager, CaptureError, BGRA8 };
use std::mem;
/// Representation of an image as a vector of BGRA8 pixels, coupled with image dimensions
#[derive(Clone)]
pub struct Image {
width: usize, height: usize,
pixels: Vec<BGRA8>,
}
impl Image {
/// Construct a new, emp... |
#![allow(dead_code)]
use cargo_snippet::snippet;
#[snippet]
fn next_permutation<T: Ord>(v: &mut [T]) -> bool {
let len = v.len();
if len <= 1 {
return false;
}
let mut i = len - 1;
loop {
let i1 = i;
i -= 1;
if v[i] < v[i1] {
let mut i2 = len - 1;
... |
#[derive(Debug,PartialEq)]
pub struct RibonucleicAcid(String);
#[derive(Debug)]
pub struct DeoxyribonucleicAcid(String);
impl RibonucleicAcid {
pub fn new(s: &str) -> RibonucleicAcid {
RibonucleicAcid(String::from(s))
}
}
impl DeoxyribonucleicAcid {
pub fn new(s: &str) -> DeoxyribonucleicAcid ... |
use std::string::ToString;
use std::time::Duration;
use actix_cors::Cors;
use actix_http::ContentEncoding;
use actix_web::dev::Server;
use actix_web::error::ErrorBadRequest;
use actix_web::http::header::{
AcceptEncoding, ContentType, Encoding as HeaderEnc, HeaderValue, Preference, CACHE_CONTROL,
CONTENT_ENCODI... |
use ux::*;
use crate::clone_into_array;
use crate::error_check::*;
use super::{Ipv4Frame, Ipv6Frame};
pub struct TcpFrame<'a> {
pseudo_header_sum: u16,
header: &'a [u8],
opts: Option<&'a [u8]>,
payload: &'a [u8],
}
impl<'a> TcpFrame<'a> {
pub fn raw_header(&self) -> &'a [u8] {
self.heade... |
extern crate rand;
extern crate chrono;
use flare_utils::ValueType;
use flare_utils::timeseries::*;
use chrono::Local;
use rand::Rng;
fn main() {
let mut tsfile = TimeSeriesFileReader::new("tsfile-test1").unwrap();
let info = tsfile.get_header_info();
println!("tsfile header: {:?}", info);
... |
use rand::Rng;
fn should_crossover(crossover_rate: f32) -> bool {
if crossover_rate <= rand::thread_rng().gen_range(0.0, 1.0) {
return true;
} else {
return false;
}
}
fn choose_exchange_point(max: u32) -> u32 {
return rand::thread_rng().gen_range(1,max);
}
fn exchange_chromosomes(ind... |
use serde::Deserialize;
use std::fs;
use std::net::SocketAddr;
/// Configuration used for initializing the `ConnectionManager`
#[derive(Debug, Deserialize)]
pub struct NodeConfig {
pub peer_addresses: Vec<SocketAddr>,
pub server_address: SocketAddr,
pub capacity: usize,
pub mining: bool,
pub conne... |
#[doc = "Register `INTCAP` reader"]
pub struct R(crate::R<INTCAP_SPEC>);
impl core::ops::Deref for R {
type Target = crate::R<INTCAP_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<crate::R<INTCAP_SPEC>> for R {
#[inline(always)]
fn from(reader: crate::R... |
use std::fs::File;
use std::io::prelude::*;
fn main() -> std::io::Result<()> {
let mut file = File::create("output.txt")?;
file.write(b"Hello, world!\n")?;
Ok(())
}
|
// Copyright 2020 WHTCORPS INC Project Authors. Licensed Under Apache-2.0
use std::path::Path;
use std::sync::*;
use futures::executor::block_on;
use futures::{future, TryStreamExt};
use grpcio::{Error, RpcStatusCode};
use ekvproto::interlock::*;
use ekvproto::kvrpc_timeshare::*;
use ekvproto::violetabft_server_times... |
use std::io::IoResult;
pub struct CustomStream<R, W> {
reader: R,
writer: W,
}
impl<R: Reader, W: Writer> CustomStream<R, W> {
pub fn new(reader: R, writer: W) -> CustomStream<R, W> {
CustomStream {
reader: reader,
writer: writer,
}
}
}
impl<R: Reader, W> Reade... |
use std::{hint::unreachable_unchecked, io, iter};
// O(1)
fn calc_fft(i: usize, j: usize) -> Option<i32> {
match j / i {
e if e % 2 == 0 => None,
e if e % 4 == 1 => Some(1),
e if e % 4 == 3 => Some(-1),
_ => unsafe { unreachable_unchecked() },
}
}
// O(j - i)
fn calc_2_fft(i: u... |
use std::time::Duration;
use std::marker::PhantomData;
use actix::*;
use actix_web::*;
use actix_web::http::Method;
use serde_json;
use regex::Regex;
use context::ChannelItem;
use protocol::{Frame, CloseCode};
use utils::SockjsHeaders;
use session::Session;
use manager::{Broadcast, Record, SessionManager};
use super... |
type TestType = u32;
#[test]
fn f32_vec_mat_mul() {
use vector::*;
use matrix::*;
let a: Vector<f32> = Vector::from_vec(vec![1.0, 2.0, 3.0, 4.0]);
let b: Vector<f32> = Vector::from_vec(vec![5.0, 4.0, 9.0]);
let m: Matrix<f32> = Matrix::from_vec(vec![
1.0, 0.0, 0.0,
0.0, 2.0, 0.0,... |
use std::cmp::Ordering;
use std::collections::{BTreeMap, HashMap};
use std::convert::TryInto;
use std::io::Cursor;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::SystemTime;
use std::time::{Duration, Instant};
use async_trait::async_trait;
use bazel_protos::gen::build::bazel::remote::execution::v2 as remex... |
use crate::mm_error::{MmError, NotMmError};
use common::SerializationError;
use ser_error::SerializeErrorType;
use serde::{Deserialize, Serialize};
use serde_json::{self as json, Error as JsonError, Value as Json};
use std::fmt;
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct MmJsonError(Json);
impl fmt::D... |
//! A library to help you convert your sync functions into non-blocking thread futures.
//!
//! Futurify uses `futures 0.3` by default.
//!
//! # Examples
//!
//! A simple `actix-web` server serving async endpoints:
//!
//! ```rust,no_run
//! use actix_web_2::{web, App, HttpServer, Responder};
//! use std::time::Durati... |
extern crate flate2;
extern crate hyper;
extern crate time;
extern crate url;
use std::error::Error;
use std::io::{Read, Write};
use std::thread;
use self::hyper::Client;
use self::hyper::header::{Authorization, ContentEncoding, Encoding, Headers};
pub struct SplunkBuffer {
index: String,
sourcetype: String,... |
// Copyright 2020 Yevhenii Reizner
//
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#[cfg(all(not(feature = "std"), feature = "no-std-float"))]
use crate::NoStdFloat;
// Right now, there are no visible benefits of using SIMD for f32x2. So we don't.
/// A pair ... |
// Copyright 2016 The Gfx-rs Developers.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or ag... |
use crate::COUNTER;
use proc_macro::TokenStream;
pub fn generate_dummy_part_checker(input: TokenStream) -> TokenStream {
if !input.is_empty() {
return syn::Error::new(proc_macro2::Span::call_site(), "No arguments expected")
.to_compile_error()
.into()
}
let count = COUNTER.with(|counter| counter.borrow_mut... |
use structopt::StructOpt;
use aoc2019::intcode::{execute_program, read_program_from_file, read_program_from_string};
use aoc2019::StandardOptions;
fn part1(program: Vec<i64>) -> i64 {
let input: Vec<i64> = vec![1];
let (_mem, output) = execute_program(&program, &input);
println!("Program output: {:?}", ou... |
//! Projection expression plan.
use timely::dataflow::Scope;
use timely::dataflow::scopes::child::Iterative;
use plan::Implementable;
use Relation;
use {QueryMap, RelationMap, SimpleRelation, Var};
/// A plan stage projecting its source to only the specified sequence
/// of symbols. Throws on unbound symbols. Fronte... |
use std::borrow::Cow;
#[derive(Clone, Debug)]
pub enum StringBuilder<'a> {
Empty,
String(Cow<'a, str>),
Vec(Vec<StringBuilder<'a>>),
}
impl<'a> StringBuilder<'a> {
pub fn new() -> StringBuilder<'a> {
StringBuilder::Vec(Vec::new())
}
pub fn with_capacity(capacity: usize) -> StringBuild... |
/*
* 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::fs;
use std::io::ErrorKind;
use std::path::Path;
use std::path::PathBuf;
use std::process::Command;
use tracing::debug;... |
pub struct Solution {}
impl Solution {
pub fn subsets_with_dup(nums: Vec<i32>) -> Vec<Vec<i32>> {
let mut nums = nums;
nums.sort_unstable();
let mut results = vec![vec![]];
let mut status = Vec::with_capacity(nums.len());
Self::backtrack(&mut status, &nums, &mut results);
... |
use std::fmt::{Display, Formatter};
#[derive(Debug)]
pub enum InterpError {
MemLeak,
UsingUninitializedMemory,
NoLastLabel,
NoMainFunction,
UnequalPhiNode, // Unequal number of args and labels
DuplicateFunction,
NonEmptyRetForfunc(String),
CannotAllocSize(i64),
IllegalFree(usize, i64), // (ba... |
use crate::tls::{ChannelBinding, TlsStream};
use std::io;
use std::pin::Pin;
use std::task::{Context, Poll};
use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};
pub enum MaybeTlsStream<S, T> {
Raw(S),
Tls(T),
}
impl<S, T> AsyncRead for MaybeTlsStream<S, T>
where
S: AsyncRead + Unpin,
T: AsyncRead + Unpin... |
use std::time::UNIX_EPOCH;
pub fn current_time_millis() -> u64 {
UNIX_EPOCH.elapsed().unwrap_or_default().as_millis() as u64
}
|
extern crate fern;
#[macro_use]
extern crate fern_macros;
fn main() {
println!("Hello, world!");
info!("Program ran.");
}
|
use int::Int;
/// Sets the least significant bit of `x`.
///
/// If there is no zero bit in `x`, it returns `x`.
///
/// # Assembly Instructions
///
/// - [`BLCS`](http://support.amd.com/TechDocs/24594.pdf):
/// - Description: Set lowest clear bit.
/// - Architecture: x86.
/// - Instruction set: TBM.
/// - Reg... |
// Copyright (c) Starcoin
// SPDX-License-Identifier: Apache-2.0
use crate::pick_slice_idxs;
use proptest::sample::Index;
use std::iter;
/// An efficient representation of a vector with repeated elements inserted.
///
/// Internally, this data structure stores one copy of each inserted element, along with data about
... |
// (c) Copyright 2018 Palantir Technologies Inc. All rights reserved.
//
// 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 req... |
use std::{
cmp,
future::{self, Future},
mem,
panic::{self, AssertUnwindSafe},
pin::pin,
sync::{Arc, Mutex, OnceLock},
task, thread,
time::Duration,
};
type Error = Box<dyn std::error::Error + Send + Sync + 'static>;
pub fn bounded<T>(max_capacity: usize) -> (Sender<T>, Receiver<T>) {
... |
use std::fmt::Debug;
use itertools::Itertools;
use std::collections::{VecDeque, HashSet, HashMap, BinaryHeap};
use std::cmp::Ordering;
use std::array::IntoIter;
const RAW_INPUT_STR: &str = include_str!("../../inputs/day18.txt");
pub fn day18() -> impl Debug {
let maze = parse_input(RAW_INPUT_STR);
(part1(&ma... |
use crate::models::Reply;
use dirs;
use serde_json;
use std::fs;
use std::io;
use std::path::Path;
use zip;
const GAMES_DIR: &str = ".sinix/games";
const TEMP_DIR: &str = ".sinix/games/.tmp_game";
fn rename() {
let home_dir = dirs::home_dir().unwrap();
let tmp_dir = Path::new(&home_dir)
.join(TEMP_DIR)
.t... |
mod all_storages;
mod entities;
mod unique_view;
mod unique_view_mut;
mod view;
mod view_mut;
pub use all_storages::{AllStoragesView, AllStoragesViewMut};
pub use entities::{EntitiesView, EntitiesViewMut};
pub use unique_view::UniqueView;
pub use unique_view_mut::UniqueViewMut;
pub use view::View;
pub use view_mut::Vi... |
use std::cmp::PartialOrd;
pub fn sort<T: PartialOrd>(arr: &mut [T]) {
if arr.len() > 0 {
slow_sort(0, arr.len() - 1, arr);
}
}
fn slow_sort<T: PartialOrd>(i: usize, j: usize, arr: &mut [T]) {
if i >= j {
return;
}
let m = (i + j) / 2;
slow_sort(i, m, arr);
slow_sort(m + 1,... |
use bevy::prelude::*;
use bevy::render::camera::Camera;
use rand::Rng;
// const WIDTH: f32 = 40.0;
// const HEIGHT: f32 = 40.0;
const BOARD_SIZE: usize = 10;
fn main() {
App::build()
.add_resource(WindowDescriptor {
title: "Mine Sweeper".to_string(),
width: 600,
height: ... |
// This is pretty basic cron-based scheduler.
//
// The scheduler will attempt to push tasks to the queue at
// regular interval / times (any cron expression is supported)
// without guarantee that the tasks are executed at these times.
// If your worker pool has capacity at that time it should be close
// enough for m... |
use error_chain::error_chain;
use ::ate::prelude::*;
use crate::request::*;
error_chain! {
types {
GroupRemoveError, GroupRemoveErrorKind, ResultExt, Result;
}
links {
QueryError(super::QueryError, super::QueryErrorKind);
AteError(::ate::error::AteError, ::ate::error::AteErrorKind)... |
//!
//! # Fluvio SC - Describe Topic Processing
//!
//! Communicates with Fluvio Streaming Controller to retrieve desired Topic
//!
use std::net::SocketAddr;
use std::io::Error as IoError;
use std::io::ErrorKind;
use serde::Serialize;
use prettytable::Row;
use prettytable::cell;
use prettytable::row;
use crate::erro... |
pub fn factors(n: u64) -> Vec<u64> {
let mut primes: Vec<u64> = Vec::new();
let mut num = n;
let mut idx = 2;
loop {
if num % idx == 0 {
primes.push(idx);
num = num/idx;
} else {
idx += 1;
}
if num == 1 {
break;
}
... |
use colored::Colorize;
#[derive(Clone, Debug)]
pub struct Point {
pub level: u32,
pub x: usize,
pub y: usize,
}
impl Point {
pub fn find_neighbors(&self, grid: &Vec<Vec<u32>>) -> Vec<Point> {
let mut neighbors = Vec::new();
if self.y > 0 {
neighbors.push(Point {
... |
use crate::{Cell, Instruction};
pub enum Token<T: Cell> {
Instruction(Instruction<T>),
LoopBlock(Vec<Token<T>>)
}
impl<T: Cell> Token<T> {
pub fn can_join(&self, other: &Token<T>) -> bool {
match (self, other) {
(Token::Instruction(x), Token::Instruction(y))
=> x.can_join(y... |
#![deny(rust_2018_compatibility)]
#![deny(rust_2018_idioms)]
#![deny(warnings)]
// TODO split most modules into library
pub mod cm;
pub mod codegen;
mod fmt;
pub mod ir;
pub mod opt;
mod translate;
mod verify;
use std::{fs, path::Path};
fn main() -> Result<(), anyhow::Error> {
gen_cm(Path::new("../../shared/cm/... |
use crate::db::schema::{zhl_settings, vpm_settings, general_settings};
use serde::{Deserialize, Serialize};
use crate::simplified::{SimplifiedZHLSettings, SimplifiedGeneralSettings};
#[derive(Queryable, Identifiable, Serialize, Deserialize)]
#[table_name = "zhl_settings"]
pub struct ZHLSettings {
pub id: i32,
... |
use crate::{
render_object::RenderObject,
light::{Light, LightType},
player::Player,
camera::Camera,
resources::Resources,
material::Material,
math::{Vector3f, Mat4f},
transform::Transform,
};
pub struct Scene {
pub objects: Vec::<RenderObject>,
pub lights: Vec::<Light>
}
impl ... |
use std::{env, fmt};
use ansi_term::{Color, Style};
use log::{level_filters::LevelFilter, Event, Level, Subscriber};
use time::format_description::well_known::Iso8601;
use tracing_log::NormalizeEvent;
use tracing_subscriber::{
filter::Targets,
fmt::{
format::Writer,
time::{FormatTime, UtcTime},... |
/// Simple hash function.
/// reference: https://www.cnblogs.com/zhoug2020/p/6984177.html
pub fn simple_hasher(key:&[u8], step: usize) -> usize{
let p = 16777619;
let mut hash = 2166136261usize;
for &b in key{
hash = (hash ^ b as usize).wrapping_mul(p);
}
hash = hash.wrapping_add(hash.rot... |
//Anything related to DELETE requests for collaborators and it's properties goes here.
use super::{Collaborator, TeamCollaborator};
use crate::framework::endpoint::{HerokuEndpoint, Method};
/// Collaborator Delete
///
/// Delete an existing collaborator.
///
/// [See Heroku documentation for more information about th... |
use std::fmt::{self, Display, Formatter};
#[derive(Debug)]
pub enum Error {
Reqwest(reqwest::Error),
Io(std::io::Error),
UrlParse(url::ParseError),
Server,
}
impl From<reqwest::Error> for Error {
fn from(e: reqwest::Error) -> Self {
Error::Reqwest(e)
}
}
impl From<std::io::Error> for ... |
#[allow(unused_imports)]
use serde_json::Value;
#[derive(Debug, Serialize, Deserialize)]
pub struct FsaResultExtended {
/// True if the result is pinned to prevent automatic removal.
#[serde(rename = "pinned")]
pub pinned: bool,
/// Unix Epoch time of start of results collection job.
#[serde(rename... |
extern crate rust_htslib;
extern crate csv;
use std::convert;
use std::io;
use std::num;
use std::str;
use std::string;
use seq_loc;
#[derive(Debug)]
pub enum MyErr {
IO(io::Error),
Utf8(str::Utf8Error),
Str(String),
ParseInt(num::ParseIntError),
ParseFloat(num::ParseFloatError),
BamRead(rust... |
use glium::glutin::{self, Event, WindowEvent};
use glium::{Display, Surface};
use imgui::{Context, FontConfig, FontGlyphRanges, FontSource, Ui};
use imgui_glium_renderer::Renderer;
use imgui_winit_support::{HiDpiMode, WinitPlatform};
use std::time::Instant;
mod clipboard;
// TODO: Consider visibility of System struct... |
impl Solution {
pub fn is_palindrome(x: i32) -> bool {
match x {
0 => return true,
1 => return true,
2 => return true,
3 => return true,
4 => return true,
5 => return true,
6 => return true,
7 => return true,
... |
ApBegin(RS,CLSID_BIG2)
WndBegin(BIG2_WND_MAIN_OPTIONMENU)
WdgBegin(CLSID_VTMOPTIONMENU, VtmOptionMenu)
VtmCreateOptionMenuRC({WDG_MENU_ITEM_TYPE_TEXT, 2})
VtmCreateOptionMenuDataRC(2, {
{{MENUMODEL_ITEM_VISABLE, {SK_SELECT, SK_SELECT, SK_BACK}, BIG2_OPTION_MENU_ITEM... |
pub fn add_two(a: i32) -> i32 {
a + 2
// 아래 코드를 돌릴시에는
// it_adds_two에서 FAILED가 뜸
// a + 3
}
// greeting_contains_name 성공 ver
pub fn greeting(name: &str) -> String {
format!("Hello {}!", name)
}
// greeting_contains_name 실패 ver
pub fn greeting2(name: &str) -> String {
String::from("Hello!")
}
... |
use minnie::prelude::*;
use sylphie::core::InitEvent;
use sylphie::database::config::*;
use sylphie::prelude::*;
/// A module that can be added to a Sylphie bot to add Discord support.
#[derive(Module)]
pub struct ModDiscord {
#[module_info] info: ModuleInfo,
}
#[module_impl]
impl ModDiscord {
#[config]
p... |
#[doc = "Register `CIDR3` reader"]
pub struct R(crate::R<CIDR3_SPEC>);
impl core::ops::Deref for R {
type Target = crate::R<CIDR3_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<crate::R<CIDR3_SPEC>> for R {
#[inline(always)]
fn from(reader: crate::R<CID... |
use std::fs::File;
use std::io::prelude::*;
use std::path::Path;
use log::*;
use simplelog::*;
use toml;
use librogue::ability::*;
use librogue::utility::SerializableUuid;
fn main() {
TermLogger::init(LevelFilter::Trace, Config::default(), TerminalMode::Mixed).unwrap();
info!("Starting abilities example");
... |
//! # Adder
//!
//! 测试做为包的注释,包含有一些小组件
use std::ops::Add;
/// 定义一个泛型加法
///
/// # Example
///
/// 例子,一般是测试用例
/// ```
/// assert_eq!(5, adder::adder(3,2));
/// assert_eq!(9.8, adder::adder(3.3, 6.5));
/// ```
/// # Panics
///
/// 可能Panic的场景
///
/// # Errors
/// 如果返回Result时,这里写明Error返回的场景,以及返回的Error值
///
/// # Safety
///... |
use std::{
error::Error,
io::{Seek, Write},
};
use parquet_format::{CompressionCodec, RowGroup};
use crate::{
error::{ParquetError, Result},
metadata::ColumnDescriptor,
read::CompressedPage,
};
use super::{column_chunk::write_column_chunk, DynIter};
fn same_elements<T: PartialEq + Copy>(arr: &[T... |
use chrono::{NaiveDate};
use std::collections::HashMap;
#[derive(Clone, Debug, Hash)]
pub struct Team {
pub name : String,
pub link : String,
pub players : Vec<String>,
}
impl PartialEq for Team {
fn eq(&self, rhs : &Self) -> bool {
self.link == rhs.link
}
}
impl Eq for Team {}
#[derive... |
/*
* Copyright 2019 Fluence Labs Limited
*
* 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 a... |
use super::{Mysql, MysqlTypeMetadata};
use crate::backend::BinaryRawValue;
/// Raw mysql value as received from the database
#[derive(Copy, Clone, Debug)]
pub struct MysqlValue<'a> {
raw: &'a [u8],
tpe: MysqlTypeMetadata,
}
impl<'a> MysqlValue<'a> {
pub(crate) fn new(raw: &'a [u8], tpe: MysqlTypeMetadata)... |
// Copyright (c) 2015 Alcatel-Lucent, (c) 2016 Nokia
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
// * Redistributions of source code must retain the above copyright
// notice,... |
// Copyright 2020 Contributors to the Parsec project.
// SPDX-License-Identifier: Apache-2.0
use crate::tss2_esys::{TPM2_PCR_SELECT_MAX, TPMS_PCR_SELECT};
use crate::{Error, Result, WrapperErrorKind};
use enumflags2::BitFlags;
use enumflags2::_internal::RawBitFlags;
use log::error;
use num_derive::{FromPrimitive, ToPri... |
use crate::menu::widget::Widget;
use std::collections::HashMap;
use sfml::{
graphics::{
Color,
RenderTarget,
RenderWindow,
},
window::{
mouse,
Event,
},
system::{
Vector2i,
},
};
pub struct Menu<'a, T> where T: Clone {
widgets: Vec<Widget<'a... |
//! Unit tests for the ciphersuites.
use crate::ciphersuite::*;
use crate::config::Config;
// Spot test to make sure hpke seal/open work.
#[test]
fn test_hpke_seal_open() {
// Test through ciphersuites.
for ciphersuite in Config::supported_ciphersuites() {
println!("Test {:?}", ciphersuite.name());
... |
use std::{
fmt,
mem::{self, MaybeUninit},
ops::{Add, Div, Index, IndexMut, Mul, MulAssign, Neg, Sub},
ptr,
};
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct Matrix<T> {
data: Box<[T]>,
n: usize,
m: usize,
}
impl<T> Matrix<T> {
pub fn repeat(n: usize, m: usize, x: T) -> Self
where
... |
use wasm_bindgen::prelude::*;
extern crate quenya;
#[wasm_bindgen]
pub fn annotate(text: &str) -> String {
String::from(quenya::annotate(text))
}
|
#[doc = "Register `MAC_ADDR2H` reader"]
pub struct R(crate::R<MAC_ADDR2H_SPEC>);
impl core::ops::Deref for R {
type Target = crate::R<MAC_ADDR2H_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<crate::R<MAC_ADDR2H_SPEC>> for R {
#[inline(always)]
fn from(... |
use super::{Account, Estimation};
use crate::providers::ethereum::types::Bytes;
use crate::providers::ethereum::{to_string_result, Call, CallOptions, EthereumProvider};
use serde::{Deserialize, Serialize};
use anyhow::Result;
use ethabi_contract::use_contract;
use ethereum_types::{Address, H256, U256};
#[derive(Seria... |
use itertools::join;
use super::aggregator::{
agg_sql_string_pass_1,
agg_sql_string_pass_2,
agg_sql_string_select_mea,
};
use super::cuts::cut_sql_string;
use super::{
TableSql,
CutSql,
DrilldownSql,
MeasureSql,
HiddenDrilldownSql,
dim_subquery,
};
/// Error checking is done befor... |
use anyhow::Error;
use futures::future::try_join_all;
use log::{debug, error};
use reqwest::{Client, Url};
use select::{
document::Document,
predicate::{Class, Name},
};
use serde::Deserialize;
use stack_string::{format_sstr, StackString};
use std::{fmt, fmt::Write};
use time::{
macros::{date, format_descri... |
use std::mem;
use std::io;
use std::io::prelude::*;
use std::net::{self, SocketAddr};
use std::sync::{Arc, Mutex};
use std::convert::AsMut;
use bytes::{BufMut, Bytes, BytesMut};
use nom::IError;
use rotor::{EventSet, PollOpt, Void};
use rotor::mio::tcp::{TcpListener, TcpStream};
use rotor::{Machine, Response, EarlyS... |
#[doc = "Register `CTL2` reader"]
pub struct R(crate::R<CTL2_SPEC>);
impl core::ops::Deref for R {
type Target = crate::R<CTL2_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<crate::R<CTL2_SPEC>> for R {
#[inline(always)]
fn from(reader: crate::R<CTL2_SP... |
use serde_derive::{Deserialize, Serialize};
// TODO move this to a better place? Does this belong in query_ir?
// Median is the one that postgres and mysql don't support
// That means that the actual string generation happens
// inside each db's sql implementation
//
// For custom calculations,
// the col is referred ... |
use crate::{
datastructure::generic::Vec2i,
opengl::{
rect::RectRenderer,
text::TextRenderer,
types::{RGBAColor, RGBColor},
},
};
use super::{boundingbox::BoundingBox, coordinate::Size};
use crate::textbuffer::metadata::{Column, Line};
#[derive(Debug)]
pub enum StatusBarContent<'a>... |
use crate::command;
use command::Command;
use crate::entity;
use entity::Entity;
use crate::game;
use game::Game;
/// The scheduler.
#[derive(Clone, Copy, Debug)]
pub struct Scheduler {
}
/// The scheduler.
impl Scheduler {
/// Constructor.
pub fn new() -> Self {
Scheduler {
}
}
/// ... |
use machine::state::State;
use machine::state::mem::WydeAt;
/// store wyde immediate
pub fn stwi(state: &mut State, x: u8, y: u8, z: u8) {
// Load first operand
let op1: u64 = state.gpr[y].into();
// Execute
let a = op1.wrapping_add(z as u64);
// Load x
let res: i64 = state.gpr[x].into();
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.