text stringlengths 8 4.13M |
|---|
#[allow(unused_imports)]
use serde_json::Value;
#[derive(Debug, Serialize, Deserialize)]
pub struct SettingsKrb5Domains {
#[serde(rename = "domain")]
pub domain: Option<Vec <crate::models::SettingsKrb5DomainsDomainItem>>,
}
|
pub fn char_to_b6(c : char) -> Option<u8>{
fn sub(l : char, r : char) -> u8{
return l as u8 - r as u8;
}
return match c {
'A'..='Z' => Some(sub(c,'A')),
'a'..='z' => Some(sub(c, 'a') + 26),
'0'..='9' => Some(sub( c, '0') + 52),
'-' => Some(62),
'_' => Some(6... |
use crossterm_utils::TerminalOutput;
use std::fmt::Display;
use std::io::{self, Write};
use std::sync::Arc;
/// This type offers a easy way to use functionalities like `cursor, terminal, color, input, styling`.
///
/// To get a cursor instance to perform cursor related actions, you can do the following:
///
/// ```ru... |
use crate::day12::part1::*;
use crate::io::*;
#[test]
fn test1() {
let input = read_file("day12/input_test_part1_test1").unwrap();
assert_eq!(solve(&input, 20), 325);
}
|
/*
* Copyright 2018-2019 TON DEV SOLUTIONS LTD.
*
* Licensed under the SOFTWARE EVALUATION License (the "License"); you may not use
* this file except in compliance with the License. You may obtain a copy of the
* License at: https://ton.dev/licenses
*
* Unless required by applicable law or agreed to in writing, softw... |
extern crate nalgebra;
use nalgebra::Vector3;
use rand::distributions::{Distribution, Normal};
use specs::{Builder, World, VecStorage, System, Component, DispatcherBuilder, ReadStorage, WriteStorage};
use std::time::Instant;
#[derive(Copy, Clone)]
pub struct ComponentA {
x: f64,
y: f64,
z: f64
}
impl Defau... |
use cargo_snippet::snippet;
use crate::number::{modinv, modpow};
use crate::garner::garner;
/// mod pの下でFTTのようなことをする。
/// 計算量: O(N logN)
#[test]
fn test_ntt() {
let a = vec![1,2];
let b = vec![1,2,3];
let c = ntt_multiply(&a, &b, 1_000_000_007);
assert_eq!(c, vec![1,4,7,6]);
}
#[snippet("NTT")]
struc... |
#![feature(decl_macro)]
#![feature(proc_macro_hygiene)]
#[macro_use] extern crate rocket;
#[macro_use] extern crate serde_derive;
#[macro_use] extern crate rocket_contrib;
#[macro_use] extern crate lazy_static; //this will store values on run time
extern crate rocket_cors;
use std::sync::{Arc,Mutex}; //for global vari... |
#![cfg_attr(rustfmt, rustfmt::skip)]
use super::*;
#[derive_ReprC(dyn)]
pub
trait DropGlue {}
/// We need to use a new type to avoid the trait-coherence issues of
/// an otherwise too blanket-y impl.
#[derive(Debug)]
#[repr(transparent)]
pub
struct ImplDropGlue<T>(pub T);
impl<T> DropGlue for ImplDropGlue<T> {}
im... |
mod local_graph;
pub use local_graph::*;
|
extern crate pnet;
extern crate ipnetwork;
extern crate rips;
use ipnetwork::Ipv4Network;
use pnet::packet::{MutablePacket, Packet};
use pnet::packet::arp::{ArpPacket, MutableArpPacket, ArpOperations};
use pnet::packet::ethernet::{EtherTypes, EthernetPacket, MutableEthernetPacket};
use pnet::util::MacAddr;
use rips:... |
mod borrow_info;
#[cfg(feature = "thread_local")]
mod non_send;
#[cfg(feature = "thread_local")]
mod non_send_sync;
#[cfg(feature = "thread_local")]
mod non_sync;
mod world_borrow;
pub use borrow_info::BorrowInfo;
#[cfg(feature = "thread_local")]
pub use non_send::NonSend;
#[cfg(feature = "thread_local")]
pub use non_... |
// Require use of WinMain entrypoint so cmd doesn't flash open
// See RFC 1665 for additional details
#![windows_subsystem = "windows"]
#[cfg(windows)]
#[path = "windows.rs"]
mod platform;
#[cfg(target_os = "macos")]
#[path = "macos.rs"]
mod platform;
#[cfg(not(any(windows, target_os = "macos")))]
#[path = "unsuppor... |
use std::num::NonZeroU32;
use crate::cgu_reuse_tracker::CguReuse;
use rustc_errors::{
fluent, DiagnosticBuilder, ErrorGuaranteed, Handler, IntoDiagnostic, MultiSpan,
};
use rustc_macros::Diagnostic;
use rustc_span::{Span, Symbol};
use rustc_target::abi::TargetDataLayoutErrors;
use rustc_target::spec::{SplitDebugin... |
ApBegin(QvgaP,CLSID_CALCULATORAPP)
WndBegin(CALCULATOR_WND_MAIN)
WndSetTitleVisiableRC(FALSE)
WndSetAllSoftkeyRC({SK_PLUSMINUS, SK_NONE, SK_CLOSE})
WndSetBgColorRC((RGBColor_t)DEF_THM_CALCULATORAPP_BACKGROUND)
WndSetBgPosRC(WDG_BG_POS_WHOLE)
/*----- Start of common widgets --... |
use bitflags::bitflags;
use chrono::offset::TimeZone;
use chrono::{Date, Utc};
use enum_primitive::{enum_from_primitive, enum_from_primitive_impl, enum_from_primitive_impl_ty};
use std::os::raw::{c_char, c_void};
use std::time::Duration;
/// Original API implementation
#[cfg_attr(
all(not(target_os = "macos"), tar... |
use actix_web::get;
use actix_web::{App, HttpResponse, HttpServer, Responder};
fn main() {
HttpServer::new(|| App::new().service(index))
.bind("0.0.0.0:8080")
.unwrap()
.run()
.unwrap();
}
#[get("/")]
fn index() -> impl Responder {
HttpResponse::Ok().body("Hello")
}
|
use shrev::{EventChannel,ReaderId,EventIterator};
mod update_limiter;
mod timing;
mod game;
mod module_bundle;
pub use update_limiter::{UpdateLimiter,LimitSetting};
pub use timing::{Stopwatch,Time};
pub use module_bundle::{IModuleBundle};
pub use game::{IGame};
#[derive(Copy,Clone)]
pub enum AppControlFlow {
None... |
use super::builtins;
use super::env;
use super::function;
use super::http_client;
use super::http_request;
use super::lang;
use super::result::Result;
use super::structs;
use crate::builtins::{
get_ok_type_from_result_type, none_option_value, ok_result_value, some_option_value,
};
use crate::code_generation;
use h... |
use std::ops::Index;
const THREE_HOURS_IN_SECOND:u32 = 60 * 60 * 3;
fn main() {
println!("{}", THREE_HOURS_IN_SECOND);
// const I_WILL_NOT_DISCUSS:i32 = 1*2;
let b = "😍";
println!("{}", b);
// 使用Debug 模式的时候会对 overflow 做 panic
// Release 模式的时候是不会的,overflow 的时候只会环绕
let r_array = [1... |
uucore_procs::main!(uu_mv); // spell-checker:ignore procs uucore
|
#![no_std]
#[panic_handler]
fn panic(_: &core::panic::PanicInfo) -> ! {
semidap::abort()
}
|
use macroquad::{
prelude::{collections::storage, Texture2D},
rand::{gen_range, ChooseRandom},
};
use crate::{
actor::{Actor, Anchor},
collide_actor::CollideActor,
gravity_actor::GravityActor,
orb::RcOrb,
player::Player,
resources::Resources,
};
use crate::{bolt::Bolt, game_playback::pla... |
// 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::{mem::swap, rc::Rc};
use crate::{
inflate_helpers::adjust_parameters_trailing_whitespace,
nodes::{
traits::{In... |
// Copyright 2020 Conflux Foundation. All rights reserved.
// Conflux is free software and distributed under GNU General Public License.
// See http://www.gnu.org/licenses/
pub fn new_cancellable_task_channel<T: CancelByKey>(
) -> (CancelableTaskSender<T>, CancelableTaskReceiver<T>) {
let (sender, receiver) = mpsc... |
use crate::common::*;
pub(crate) struct Release {
pub(crate) version: Option<String>,
pub(crate) time: DateTime<Utc>,
pub(crate) entries: Vec<Entry>,
}
impl Release {
#[throws]
pub(crate) fn render(&self, lines: &mut Vec<String>, book: bool) {
let time = self.time.format("%Y-%m-%d");
let header = m... |
use gui::directory_list::DirectoryList;
use orbtk::prelude::*;
mod gui;
mod core;
fn main() {
Application::new()
.window(|context| {
Window::create()
.title("Twin Commander")
.position((100.0, 100.0))
.size(1920.0 * 0.75, 1080.0 * 0.75)
... |
use common::sha1::Sha1Hash;
use std::path::PathBuf;
use std::time::Instant;
#[derive(Default)]
pub struct FileStorage {
piece_len: usize,
}
impl FileStorage {
pub fn new() -> Self {
Self::default()
}
pub fn is_valid(&self) -> bool {
self.piece_len > 0
}
}
pub struct FileEntry {
... |
extern crate ndarray;
use std::ops::Mul;
use ndarray::{arr2, Array, Array2, ArrayBase, Ix, OwnedRepr};
use ndarray::Ix2;
use ndarray_rand::rand_distr::Uniform;
use ndarray_rand::RandomExt;
use ndarray_stats::QuantileExt;
struct NeuralNetwork {
W1: Array2<f64>,
W2: Array2<f64>,
y_hat: Array2<f64>,
Z2:... |
use crate::ident::Ident;
use std::fmt;
use std::rc::Rc;
use crate::lit::TyLit;
#[derive(Clone, Debug, Eq, Hash, PartialEq, Ord, PartialOrd)]
pub enum Ty {
Void,
Bool,
Int,
Float,
Bvec2,
Bvec3,
Bvec4,
Ivec2,
Ivec3,
Ivec4,
Vec2,
Vec3,
Vec4,
Mat2,
Mat3,
Mat4... |
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
pub async fn upload(
base_url: String,
file: web_sys::File,
chunk_size: f64,
parallel: usize,
) -> Result<JsValue, JsValue> {
match chua::upload(&base_url, file, chunk_size as u64, parallel).await {
Ok(uuid) => Ok(JsValue::from_str(&uuid.to_stri... |
use crate::{util::le_f32, util::le_i32, Encoding, Utf8Encoding, Windows1252Encoding};
/// Trait customizing decoding values from binary data
pub trait BinaryFlavor: Sized + Encoding {
/// Decode a f32 from 4 bytes of data
fn visit_f32_1(&self, data: &[u8]) -> f32;
/// Decode a f32 from 8 bytes of data
... |
#[macro_use]
extern crate fstrings;
#[macro_use]
mod logging;
use std::fs::File;
use std::io::Read;
use anyhow::{bail, Result};
use clap::{App, Arg};
use glob::glob;
use file::OutputDirectory;
use svd_expander::DeviceSpec;
mod file;
mod generators;
mod system;
fn main() {
match run() {
Ok(()) => {}
Err(e... |
// Lumol, an extensible molecular simulation engine
// Copyright (C) Lumol's contributors — BSD license
//! Multi-dimensional arrays based on ndarray
use num_traits::Zero;
use std::ops::{Deref, DerefMut, Index, IndexMut};
/// Two dimensional tensors, based on ndarray.
///
/// Most of the methods are simply forwarded... |
pub enum Vertical {
Up,
Down,
}
pub enum Horizontal {
Left,
Right,
}
pub fn match_nested(v: Vertical, h: Horizontal) -> usize {
match v {
Vertical::Up => match h {
Horizontal::Left => 0,
Horizontal::Right => 1,
},
Vertical::Down => match h {
... |
use super::thread::sgx_thread_get_self;
use super::untrusted_event::{set_event, wait_event};
/// A wait/wakeup mechanism that connects wait4 and exit system calls.
use crate::prelude::*;
#[derive(Debug)]
pub struct Waiter<D, R>
where
D: Sized + Copy,
R: Sized + Copy,
{
inner: Arc<SgxMutex<WaiterInner<D, R>... |
use std::hash::Hash;
#[derive(Debug)]
pub struct Mutator<M: Mutable>(super::Shared<std::collections::HashMap<M::Name, Result<M::Output, M::Failure>>>);
pub struct MutatorRef<'a, M: Mutable, S: super::WorldRenderer> {
client: &'a super::ServerConnection<S>,
creator: &'a Mutator<M>,
}
pub trait Mutable {
const OPE... |
pub fn is_armstrong_number(num: u32) -> bool {
is_armstrong_number_for_base(num, 10)
}
pub fn is_armstrong_number_for_base(num: u32, base: u32) -> bool {
let mut numstring = match base {
2 => format!("{:b}", num),
8 => format!("{:o}", num),
10 => format!("{}", num),
16 => forma... |
use std::fmt::Debug;
use std::rc::Rc;
// Graph, ClassicPure, Qisikit, ClassicDensityなどの実装
pub trait QBackend {}
#[derive(Debug)]
// 測定結果
pub enum QBasis {
Zero,
One,
}
// グラフに関する操作
pub trait QPublicGraph<T>: Debug
where
T: QBackend,
{
// 単一Qubitの測定を行う
fn measure(&self) -> QBasis;
}
pub trait QIn... |
// vim: set ai et ts=4 sts=4 sw=4:
use crate::util;
use crate::intcode::{CPU};
use std::collections::VecDeque;
use std::ops::Range;
struct IncrementalBeamRange<'a> {
// returns the range of affected X coordinates over incremental values of Y
program: &'a Vec<i64>,
next_y: usize,
prev_left_x: usize,
... |
use crate::sauce::error::SauceError;
use serde::{Deserialize, Serialize};
pub use std::str::FromStr;
#[derive(Deserialize, Serialize)]
pub enum DataType {
Character,
Bitmap,
Vector,
Audio,
BinaryText,
XBin,
Archive,
Executable,
}
impl std::fmt::Display for DataType {
fn fmt(&self, ... |
pub mod mem;
pub mod pg;
use crate::prelude::*;
use common_failures::prelude::*;
use std::collections::BTreeMap;
use std::str::FromStr;
pub trait DataStore {
fn wipe_to_height(&mut self, height: u64) -> Result<()>;
/// Get the height of the stored chainhead
fn get_head_height(&mut self) -> Result<Option<... |
use crate::{constants::HISTORY_CONTENT_VALUE, Peertest};
use ethportal_api::types::content_key::HistoryContentKey;
use ethportal_api::types::content_value::{HistoryContentValue, PossibleHistoryContentValue};
use ethportal_api::types::node_id::NodeId;
use ethportal_api::types::portal::TraceContentInfo;
use ethportal_api... |
use crate::day17::part2::*;
use crate::io::*;
//#[test]
//fn test1() {
// let input = read_file("day17/input_test_part2_test1").unwrap();
//// assert_eq!(solve(&input), );
//}
|
use crate::{
database::{last_activity_timestamp, Object},
error::Error,
};
use sqlx::PgPool;
use uuid::Uuid;
/// Get follow activities addressed to the user
pub async fn followers(
conn_pool: &PgPool,
user_id: Uuid,
last_activity_id: Option<Uuid>,
limit: i64,
) -> Result<Vec<Object>, Error> {
... |
pub trait ArrayVec: Sized {
fn neg(&mut self) -> &mut Self;
fn scalar_mult(&mut self, scalar: f32) -> &mut Self;
fn pointwise_exp(&mut self) -> &mut Self;
fn powi_mean(&self, pow: i32) -> f32;
fn powf_mean(&self, pow: f32) -> f32;
fn pointwise_add(&mut self, other: &Self) -> &mut Self;
fn po... |
use std::cell::RefCell;
use std::net::TcpListener;
use std::sync::mpsc;
use std::thread;
use nix::errno::Errno;
use xyio::io::Context;
use xyio::io::net::ip::tcp::TcpStream;
#[test]
fn connect() {
let (tx, rx) = mpsc::channel();
let thread = thread::spawn(move || {
let acceptor = TcpListener::bind((... |
#[derive(Copy)]
#[repr(C)]
pub enum BodMode {
Active,
Inactive
}
#[derive(Copy)]
#[repr(C)]
pub enum Em4Oscillator {
Ulfrco = 0x0, // 0x0u64,
Lfxo = 0x2, // 0x2u64,
Lfrco = 0x1, // 0x1u64
}
#[derive(Copy)]
#[repr(C)]
pub struct Em4Init{
lock_config: bool,
oscillator: Em4Oscill... |
/// Macro to implement and run a parser iterator, it provides the ability to add an extra state
/// variable into it and also provide a size_hint as well as a pre- and on-next hooks.
macro_rules! run_iter {
(
input: $input:expr,
parser: $parser:expr,
state: $data_ty:ty : $data:ex... |
/*
* Copyright 2018 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... |
#![allow(unused_macros)]
macro_rules! bf_op {
($cells:ident, $ptr:ident, $sout:ident, $sin:ident, >) => {
$ptr = $ptr.wrapping_add(1);
};
($cells:ident, $ptr:ident, $sout:ident, $sin:ident, <) => {
$ptr = $ptr.wrapping_sub(1);
};
($cells:ident, $ptr:ident, $sout:ident, $sin:ident, +)... |
use std::cmp::Ordering;
use std::fs::File;
use std::io::{BufRead, BufReader, Result};
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
use std::str::FromStr;
use std::sync::Arc;
use std::time::Duration;
use async_std::net::UdpSocket;
use async_std::prelude::*;
use async_std::task;
use clap::Clap;
use trust_dns_server::au... |
// Copyright 2022 Datafuse Labs.
//
// 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 ... |
mod user_message;
mod process_loop;
pub use self::{
process_loop::{
telegram_receive_updates_loop
}
}; |
use std::io::{self, Read, Write};
use std::string::FromUtf8Error;
use std::error::Error;
use std::fmt;
use std::convert::From;
use byteorder;
use control::{FixedHeader, PacketType, ControlType};
use control::variable_header::PacketIdentifier;
use packet::{Packet, PacketError};
use {Encodable, Decodable};
use encodabl... |
#[macro_use]
extern crate cluLog;
extern crate cluLogKmsg;
use cluLogKmsg::default_open_kmsg;
use cluLog::log_addition::union::LogUnionConst;
pub fn main() {
//Attempt to open file /dev/kmsg
//In case of an error the program will be interrupted!
cluLog::set_logger({
let kmsg = default_o... |
extern crate r2d2;
use std::default::Default;
use std::sync::atomic::{AtomicBool, ATOMIC_BOOL_INIT, Ordering};
use std::sync::mpsc::{self, SyncSender, Receiver};
use std::sync::{Mutex, Arc};
use std::time::Duration;
use std::thread;
mod config;
#[derive(Debug, PartialEq)]
struct FakeConnection(bool);
struct OkManag... |
mod keystore;
mod crypto;
mod command;
mod wallet;
mod pkcs8;
mod networks;
use sp_core::crypto::{Ss58AddressFormat, set_default_ss58_version};
use std::path::Path;
use std::fs;
use keystore::Keystore;
use crypto::*;
use wallet::*;
fn main() {
let mut app = command::get_app();
let matches = app.clone().get_matches... |
use std::collections::HashMap;
use std::collections::HashSet;
use std::env;
use std::fs;
struct AdapterSet {
numbers: HashSet<usize>,
cached_combinations: HashMap<(usize,usize),usize>
}
impl AdapterSet {
fn count_combinations(&mut self, from: usize, to: usize) -> usize {
match self.cached_combinat... |
use crate::mm2::{lp_ordermatch::lp_bot::simple_market_maker_bot::vwap,
lp_ordermatch::lp_bot::SimpleCoinMarketMakerCfg,
lp_swap::{MakerSavedSwap, SavedSwap}};
use common::{block_on, log::UnifiedLoggerBuilder};
use mm2_number::MmNumber;
fn generate_swaps_from_values(swaps_value: Vec<(M... |
#[macro_export]
macro_rules! shape {
( ) => {{
use $crate::primitives::Shape;
Shape::scalar_shape()
}};
( $dim0: expr ) => {{
use $crate::primitives::Shape;
Shape::vector_shape($dim0.into())
}};
( $dim0: expr, $dim1: expr ) => {{
use $crate::primitives::Shape... |
#[derive(Clone, Debug)]
pub struct Palette {
h0: f32,
hscale: f32,
}
impl Palette {
pub fn default() -> Self {
Palette {
h0: 0.0,
hscale: 1.0,
}
}
pub fn cycle(&mut self) {
if self.h0 * self.hscale > 1.0 {
self.hscale = -self.hscale;
... |
#[doc = "Reader of register WF10"]
pub type R = crate::R<u8, super::WF10>;
#[doc = "Writer for register WF10"]
pub type W = crate::W<u8, super::WF10>;
#[doc = "Register WF10 `reset()`'s with value 0"]
impl crate::ResetValue for super::WF10 {
type Type = u8;
#[inline(always)]
fn reset_value() -> Self::Type {... |
pub struct ValueEntry {
// Max size of data is 2^32
pub data_size: u32,
pub data: Vec<u8>
}
impl ValueEntry {
pub fn with_data(data_size: u32, data: Vec<u8>) -> Self {
return ValueEntry {
data_size,
data
}
}
} |
use crate::error::SourceLoc;
#[derive(Debug, PartialEq, Eq)]
pub struct MetaToken<'a> {
pub token: Token<'a>,
pub span: Span<'a>,
pub loc: SourceLoc,
}
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct Span<'a>(pub usize, pub &'a str);
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum Token<'a>... |
pub fn add_to_waitlist() {
// println!("this has been printed from /front_of_house/hosting.rs")
} |
extern crate serde;
extern crate serde_json;
#[macro_use]
extern crate serde_derive;
pub mod errors;
pub mod status;
use errors::{VmctlControllerError, VmctlControllerErrorCause};
use status::Status;
use std::process::Command;
use std::str;
fn vm_id(name: &str) -> Result<u64, VmctlControllerError> {
let status = ... |
use crate::{
crypto::{
ciphersuite::CipherSuite,
dh::{DhPrivateKey, DhPublicKey},
hkdf,
},
error::Error,
ratchet_tree::{NodeSecret, PathSecret},
};
/// Unwraps an enum into an expected variant. Panics if the supplied value is not of the expected
/// variant. This macro is used t... |
use crate::mm2::lp_dispatcher::{dispatch_lp_event, DispatcherContext};
use crate::mm2::lp_ordermatch::lp_bot::{RunningState, StoppedState, StoppingState, TradingBotStarted,
TradingBotStopped, TradingBotStopping, VolumeSettings};
use crate::mm2::lp_ordermatch::{cancel_all_orders, ... |
#[derive(Debug, Clone, Serialize)]
pub struct Template {}
impl super::Template for Template {}
|
#![no_main]
mod mmio_device;
mod mmio_plugin;
mod uart;
type ThisDeviceType = uart::Uart;
|
use scraper::Html;
use super::form::FormInfo;
use super::{KeycloakError, KeycloakErrorKind};
pub fn get_totp_form(document: &str) -> Result<FormInfo, KeycloakError> {
let doc = Html::parse_document(document);
let form = match FormInfo::from_html(&doc, "form#kc-totp-login-form") {
Some(f) => f,
... |
use serde::{Deserialize, Serialize};
use std::path::PathBuf;
use crossterm::event::{Event, KeyCode, KeyEvent, KeyModifiers};
use irust_api::Command;
use once_cell::sync::Lazy;
static SCRIPT_PATH: Lazy<PathBuf> = Lazy::new(|| std::env::temp_dir().join("irust_input_event"));
fn main() {
if !SCRIPT_PATH.exists() {
... |
#[derive(Clone, PartialEq, Debug)]
pub enum NodeKind {
Minimizer,
Maximizer,
}
|
use std::{
cmp::Ordering,
collections::HashSet,
error::Error,
fmt::{self, Debug, Display, Formatter},
fs::File,
io::{self, BufRead, BufReader},
ops::{Index, IndexMut},
};
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum HeightmapParseError {
NarrowRow { expected: usize, actual: usize }... |
use diesel::data_types::PgNumeric;
#[derive(Debug)]
pub enum SLPError {
NotSLPSafe, // SLP ops must be bigger than 0x00 and less than 0x4f
TooFewPushops(usize), // SLP output must have at least 6 pushops
TooManyAmounts(usize), // SLP output must have at most 19 outputs
InvalidSLPType(String),
In... |
use serde::{Serialize, Deserialize};
#[derive(Serialize, Deserialize, Clone, Debug, Eq, PartialEq)]
pub enum DerustError {
UnknownError,
HttpError,
NoPermissions,
InvalidToken,
}
|
use crate::ctx::RCtx;
use fluix_syntax::{Decl, Expr, Type, BinaryOp};
use std::collections::BTreeSet;
#[derive(PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Equals(pub Type, pub Type);
pub struct Constraints {
pub set: BTreeSet<Equals>,
pub ctx: RCtx,
}
impl Constraints {
pub fn new(ctx: RCtx) -> Con... |
mod pipeline;
use pipeline::ObjectPipeline;
mod model;
use model::Drawable;
use foreach::ForEach;
use std::sync::{Arc, Mutex};
//----------------------------------------
fn main() {
use camera_controllers::{FirstPerson, FirstPersonSettings};
use piston_window::*;
let opengl = OpenGL::V3_2;
let mut... |
extern crate futures_glib;
extern crate futures;
extern crate tokio_io;
use std::io::{Read, Write};
use std::net::TcpListener;
use std::thread;
use futures::Future;
use futures_glib::net::TcpStream;
use futures_glib::{MainContext, MainLoop, Executor};
use tokio_io::io::{read, write_all, read_to_end};
#[test]
fn smok... |
/// Capabilities for Chrome.
pub mod chrome;
/// Capabilities for Chromium.
pub mod chromium;
/// Generic capabilities methods.
pub mod desiredcapabilities;
/// Capabilities for Microsoft Edge.
pub mod edge;
/// Capabilities for Firefox.
pub mod firefox;
/// Capabilities for Internet Explorer.
pub mod ie;
/... |
pub mod clear;
pub mod spawn;
pub mod gravity;
pub mod pos_update;
pub mod translation;
pub mod timing;
pub mod key_update;
pub mod rotation; |
extern crate actix;
extern crate futures;
use std::io;
use actix::prelude::*;
use futures::Future;
struct Ping;
impl Message for Ping {
type Result = Result<bool,io::Error>;
}
struct MyActor;
impl Actor for MyActor {
type Context = Context<Self>;
fn started(&mut self, _ctx: &mut Context<Self>) {
p... |
use std::fs::read_to_string;
use rust_cnc::process_bmp;
const DATA_PATH: &str = "tests/data/bmp/";
#[test]
fn bmp_test() {
test_bmp("test.bmp", "test.nc", 200);
}
fn test_bmp(bmp_file: &str, nc_file: &str, dpi: u16) {
let bmp = std::fs::read(DATA_PATH.to_owned() + bmp_file).unwrap();
let gcode = read_to_... |
use smart_default::SmartDefault;
/// ConditionalEdge stores the conditional edges
#[derive(Debug, Serialize, Deserialize, SmartDefault, Clone)]
#[serde(default)]
pub struct ConditionalEdge {
#[serde(skip_serializing)]
pub edge_regex: ConditionalUpdateEdge,
pub edges: Vec<ConditionalUpdateEdge>,
pub ris... |
//! Computes running medians of a sequence.
//!
//! It is worth noting that running median is different from "moving median" or "rolling median"
//! (medians within a sliding window).
//!
#![feature(conservative_impl_trait)]
#[cfg(test)]
#[macro_use]
extern crate quickcheck;
mod rev_ord;
use std::collections::Binar... |
//! The config module owns the definition and loading process for our configuration sources.
use chrono::Duration;
use parse_datetime::parse_offset;
use serde::{Deserialize, Deserializer};
use snafu::ResultExt;
use std::collections::{HashMap, VecDeque};
use std::convert::TryFrom;
use std::fs;
use std::path::{Path, Pat... |
extern crate lmqueue;
extern crate tempdir;
extern crate env_logger;
#[test]
fn can_produce_none() {
env_logger::init().unwrap_or(());
let dir = tempdir::TempDir::new("store").expect("store-dir");
let mut cons = lmqueue::Consumer::new(dir.path().to_str().expect("path string"), "default").expect("consumer")... |
#![allow(unused_imports)]
use std::f64::consts::PI;
use libm::sin;
use proconio::{fastout, input, marker::*};
use num::abs;
#[fastout]
fn main() {
input! {
a: usize,
b: usize,
c: usize
};
let a = a as f64;
let b = b as f64;
let c = c as f64;
let mut d = 1.0;
let ... |
// Result and Some error handling
fn test() -> Option<u32>
{
if false {
Some(32)
} else {
None
}
}
fn something() -> Result<u32, String>
{
if false
{
Ok(32)
}
else
{
Err(String::from("not good"))
}
}
|
// * Daily Coding Problem November 20 2020
// * [Easy] -- Twitter
// * A permutation can be specified by an array P, where P[i] represents the location
// * of the element at i in the permutation. For example, [2, 1, 0] represents the
// * permutation where elements at the index 0 and 2 are swapped.
// * Given an ar... |
#[doc = "Reader of register WF42"]
pub type R = crate::R<u8, super::WF42>;
#[doc = "Writer for register WF42"]
pub type W = crate::W<u8, super::WF42>;
#[doc = "Register WF42 `reset()`'s with value 0"]
impl crate::ResetValue for super::WF42 {
type Type = u8;
#[inline(always)]
fn reset_value() -> Self::Type {... |
extern crate walkdir;
use walkdir::{WalkDir};
use std::fs;
use std::path::{PathBuf};
use std::process::{Command};
fn main() {
println!("cargo:rerun-if-changed=build.rs");
for entry in WalkDir::new("../sysroot") {
let entry = entry.unwrap();
println!("cargo:rerun-if-changed={}", entry.path().display());
... |
use std::fmt;
use super::{
de::{Deserialize, Reader},
rt::{Runtime, SizeCache},
ser::Serialize,
state::State,
steit_derive,
};
#[macro_export]
macro_rules! test_case {
($name:ident : $assert:expr ; $($args:expr),+) => {
#[test]
fn $name() {
$assert($($args),+);
... |
/**
* [5] Longest Palindromic Substring
*
* Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example 1:
Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Example 2:
Input: "cbbd"
Output: "bb"
* How can we reuse a previously compu... |
// Copyright (c) The Starcoin Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::pool::AccountSeqNumberClient;
use crate::TxStatus;
use anyhow::Result;
use network_api::messages::{PeerTransactionsMessage, TransactionsMessage};
use network_api::PeerId;
use parking_lot::RwLock;
use starcoin_config::{Met... |
//! `SignedPacket` message content. The message may be linked to any other message
//! in the channel. It contains both plain and masked payloads. The message can only
//! be signed and published by channel owner. Channel owner must firstly publish
//! corresponding public key certificate in either `Announce` or `Chang... |
pub fn collatz(n: u64) -> Option<u64> {
let mut count: u64 = 0;
if n < 1 {
return None;
} else if n > 1 {
if n % 2 == 0 {
// even
count = collatz(n / 2).unwrap() + 1;
} else {
// odd
count = collatz(3 * n + 1).unwrap() + 1;
}
... |
use std::collections::{HashMap, HashSet};
use std::convert::TryFrom;
use std::str::FromStr;
use std::sync::Arc;
use async_trait::async_trait;
use bit_vec::BitVec;
use futures::executor::block_on;
use futures::lock::Mutex;
use overlord::types::{AggregatedSignature, AggregatedVote, Node, SignedVote, Vote, VoteType};
use... |
#![recursion_limit="128"]
#[macro_use]
extern crate stdweb;
use gif::{Repeat, SetParameter};
use stdweb::unstable::TryInto;
use stdweb::web::ArrayBuffer;
//生成gif
fn create(total: usize, width: u16, height: u16, fps: u16){
//创建gif编码器
let mut file = vec![];
{
let mut encoder = gif::Encoder::new(&mut... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.