text stringlengths 8 4.13M |
|---|
//extern crate regex;
//use regex::Regex;
use std::fs;
fn main() {
let contents = fs::read_to_string("data.txt").expect("Error reading input");
/*
let re = Regex::new("[0-9]+").unwrap();
for n in re.captures_iter(&contents) {
input.push((&n[0]).parse().unwrap());
} */
let mut ... |
mod colors;
mod k_means_solver;
mod pixels;
use crate::colors::{ColorCieLab, ColorRgb, ColorXyz};
use crate::k_means_solver::KMeansSuperPixelSolver;
use crate::pixels::PixelCieLab;
use image::{DynamicImage, GenericImage, GenericImageView, Rgb, RgbImage};
use rand::Rng;
fn pixel_from_rgb(x: u32, y: u32, rgb: &Rgb<u8>)... |
// Copyright 2019 Conflux Foundation. All rights reserved.
// Conflux is free software and distributed under GNU General Public License.
// See http://www.gnu.org/licenses/
use hibitset::BitSet;
use malloc_size_of::{MallocSizeOf, MallocSizeOfOps};
use std::collections::{HashMap, HashSet};
const MAX_PASTSET_CACHE_CAP:... |
#![no_std]
//! Embed git information in your code at compile-time.
//!
//! ```
//! use git_version::git_version;
//! const GIT_VERSION: &str = git_version!();
//! ```
//!
//! The version number will have a `-modified` suffix if your git worktree had
//! untracked or changed files.
//!
//! These macros do not depend on... |
use std::fs::read_dir;
fn main() {
let directory = if let Some(dir) = std::env::args().nth(1) {
dir
} else {
eprintln!("Expected Argument");
std::process::exit(0);
};
let files: Vec<std::fs::DirEntry> = read_dir(".")
.into_iter()
.next()
.unwrap()
... |
use anyhow::{bail, Context, Result};
use chrono::{DateTime, Local, TimeZone};
use reqwest::blocking::{multipart::Form, Client};
use serde::Deserialize;
use serde_json::json;
use std::time::Duration;
pub struct Requests {
client: Client,
}
pub enum DroptimeData {
Available(DateTime<Local>),
Unavailable(Str... |
pub mod setup;
pub mod test_runner;
pub mod tls;
pub mod test_meta;
const VERSION: &str = include_str!("../../../../VERSION");
|
use crate::{LayoutBlock, TextObject};
use serde::{Serialize, Deserialize};
use serde_json::Value;
use std::collections::HashMap;
#[derive(Serialize, Deserialize, Default, Debug)]
#[serde(default)]
pub struct View {
r#type: ViewType,
pub title: TextObject,
pub blocks: Vec<LayoutBlock>,
#[serde(skip_seri... |
use lettre::transport::smtp::authentication::Credentials;
use lettre::{Message, SmtpTransport, Transport};
use rusqlite::Result;
use std::collections::HashMap;
pub struct Mailer {
mailer: SmtpTransport,
from: String,
to: String,
}
pub fn init_mailer(
username: &str,
password: &str,
server: &st... |
extern crate rand;
use rand::Rng;
use vec3::Vec3;
use ray::Ray;
use hitable::HitRecord;
pub struct ScatterRecord {
pub attenuation: Vec3,
pub scattered: Ray
}
/*************************************************************************************************/
pub trait Material {
fn scatter(&self, r_in: ... |
use bank_ofx;
bank_ofx!("vanguard", Vanguard, {
fn url(&self) -> &str {
"https://vesnc.vanguard.com/us/OfxDirectConnectServlet"
}
fn fid(&self) -> &str {
"15103"
}
fn fid_org(&self) -> &str {
"Vanguard"
}
fn broker_id(&self) -> &str {
"vanguard.com"
}
... |
mod execute;
mod plan;
pub use execute::AggregateTopKExec;
pub use plan::materialize_topk;
pub use plan::plan_topk;
use crate::queryplanner::planning::Snapshots;
use arrow::compute::SortOptions;
use datafusion::logical_plan::{DFSchemaRef, Expr, LogicalPlan, UserDefinedLogicalNode};
use itertools::Itertools;
use serde... |
//! テスト用DSLで用いる `Io`-traitの実装 を提供するモジュール
//! 以下の点に留意されたい:
//! * これ以外の`Io`-traitの実装を妨げるものではない
use crate::election::{Ballot, Role};
use crate::log::{Log, LogIndex, LogPrefix, LogSuffix};
use crate::message::Message;
use crate::node::NodeId;
use crate::{Error, ErrorKind, Io, Result};
use futures::{Async, Future, Poll};
u... |
extern crate dirs;
extern crate os_type;
extern crate reqwest;
extern crate serde;
extern crate serde_json;
#[macro_use]
extern crate serde_derive;
#[macro_use]
extern crate log;
extern crate fern;
use std::path::PathBuf;
pub mod installer;
use installer::*;
fn main() {
fern::Dispatch::new()
.level(log:... |
// This file is part of Substrate.
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Softwa... |
pub fn reply(sentence: &str) -> &str {
match sentence {
_ if sentence.ends_with('?') => "Sure.",
_ if sentence.find(char::is_lowercase) != None => "Whatever.",
"" => "Fine. Be that way!",
_ => "Whoa, chill out!"
}
} |
#[allow(unused_imports)]
use serde_json::Value;
#[derive(Debug, Serialize, Deserialize)]
pub struct NodePartitionsNode {
/// Count of how many partitions are included.
#[serde(rename = "count")]
pub count: Option<i32>,
/// Error message, if the HTTP status returned from this node was not 200.
#[ser... |
#[doc = r" Value read from the register"]
pub struct R {
bits: u32,
}
#[doc = r" Value to write to the register"]
pub struct W {
bits: u32,
}
impl super::TX_STATUS {
#[doc = r" Modifies the contents of the register"]
#[inline]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&R, &'w... |
//! ![MODBOT logo][logo]
//!
//! ![Rust version][rust-version]
//! ![Rust edition][rust-edition]
//! ![License][license-badge]
//!
//! MODBOT is a Discord bot for [mod.io] using [`modio-rs`] and [`serenity`].
//!
//!
//! [rust-version]: https://img.shields.io/badge/rust-1.31%2B-blue.svg
//! [rust-edition]: https://img.... |
#[macro_use]
extern crate enum_response_derive;
#[derive(EnumResponse)]
struct Test;
|
use std::env;
use std::fs;
use std::process::{Command, Stdio};
const WORK_DIR: &str = "SEXXI_DIR";
const UPSTREAM_REMOTE_URL: &str = "git@github.com:rust-lang/rust.git";
const UPSTREAM_REMOTE: &str = "origin";
const SG_REMOTE_URL: &str = "git@github.com:sexxi-goose/rust.git";
const SG_REMOTE: &str = "sg";
const SG_... |
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate diesel;
extern crate dotenv;
use dotenv::dotenv;
#[macro_use]
extern crate log;
pub mod db;
mod debug;
pub mod env;
pub mod schema;
pub mod server;
pub mod vars;
fn main() {
dotenv().ok();
debug::init();
server::run().unwrap();
}
|
use std::time::Instant;
pub type FrameId = u64;
#[derive(Debug, Clone, Copy)]
pub struct Frame {
id: FrameId,
instant: Instant,
}
impl Frame {
pub fn id(&self) -> FrameId { self.id }
pub fn instant(&self) -> Instant { self.instant }
pub fn new(id: FrameId, instant: Instant) -> Self {
Fra... |
//! A stage in the rendering pipeline.
use hetseq::*;
use amethyst_core::specs::prelude::SystemData;
use error::{Error, Result};
use fnv::FnvHashMap as HashMap;
use pipe::pass::{CompiledPass, Pass, PassData};
use pipe::{Target, Targets};
use types::{Encoder, Factory};
/// A stage in the rendering pipeline.
#[derive... |
use crate::execution_plans::pseudo_id::ClassPseudoID;
use hashbrown::HashSet;
use readers::prelude::{Index, IndexIterator};
#[derive(Debug)]
pub struct DedupIndexIter<'a, I: IndexIterator> {
pub iter: I,
pub pseudo_id: &'a ClassPseudoID,
pub generated_indices: HashSet<String>,
}
impl<'a, I: IndexIterator> Dedup... |
mod server;
use anyhow::Result;
use server::QueriedServer;
use std::net::SocketAddrV4;
use std::thread;
use std::time::Duration;
use structopt::StructOpt;
const FFA1: &str = "72.5.195.76:27015";
const FFA2: &str = "74.91.125.129:27015";
const FFA3: &str = "74.201.57.120:27015";
const FFA4: &str = "74.91.114.102:27015... |
use crate::rpc_provider::AccountRpcProvider;
use crate::{
local_provider::AccountLocalProvider, private_key_provider::AccountPrivateKeyProvider,
};
use anyhow::{anyhow, Result};
use starcoin_account_api::{AccountProvider, AccountProviderStrategy};
use starcoin_config::account_provider_config::AccountProviderConfig;... |
use crate::cartridge::cartridge_base::CartridgeBase;
use crate::cartridge::{get_ram_size, Cartridge, RamDumper, CARTRIDGE_TYPE_ADDRESS};
pub struct RomOnlyCartridge {
cartridge_base: CartridgeBase,
}
impl RomOnlyCartridge {
pub fn new(rom: Vec<u8>, ram_dumper: Option<Box<dyn RamDumper + Send>>) -> Self {
... |
use arena::*;
lazy_static! {
static ref VIDEO_FRAME_ARENA: std::sync::Mutex<Arena<std::sync::Arc<std::sync::Mutex<VideoFrame>>>> = {
std::sync::Mutex::new(Arena::new())
};
}
impl ArenaAllocator for VideoFrame {
fn allocate() -> ArenaValueWrapper<VideoFrame> {
let arena = &mut VIDEO_FRAME_A... |
use rustc_middle::mir::interpret::{ConstValue, Scalar};
use rustc_middle::{mir::*, thir::*, ty};
use super::{parse_by_kind, PResult, ParseCtxt};
impl<'tcx, 'body> ParseCtxt<'tcx, 'body> {
pub fn parse_statement(&self, expr_id: ExprId) -> PResult<StatementKind<'tcx>> {
parse_by_kind!(self, expr_id, _, "sta... |
use crate::log_unstable::Unstable;
use crate::storage::Storage;
use slog::Logger;
/// Raft 日志实现
pub struct RaftLog<T: Storage> {
/// 保存最新快照中的所有 stable 日志条目
pub store: T,
/// 保存所有 ustable 的日志条目与快照
pub unstable: Unstable,
/// 最新日志存储位置
pub committed: u64,
/// 公式: applied <= committed
pub ... |
use std::cmp;
use ndarray::prelude::*;
use plotters::prelude::*;
use rustfft::{FftPlanner, num_complex::Complex, Fft};
/// プロットに表示するxyの範囲
struct Extent {
xstart: f32,
xend: f32,
ystart: f32,
yend: f32
}
impl Extent {
fn new(xstart: f32, xend: f32, ystart: f32, yend: f32) -> Self {
Self... |
// Copyright 2022 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0
use core::convert::{From, Infallible};
use pyo3::{exceptions, prelude::*};
/// The `Result` structure to wrap the error type for python binding.
pub type Result<T> = std::result::Result<T, Error>;
#[derive(Debug)]
/// The Error type.
pub struct ... |
// Copyright (c) 2016 Fedor Gogolev <knsd@knsd.net>
//
// 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. This file may not be copied, modified, or distributed
/... |
use common::executor::{BoxFutureSpawner, SpawnFuture};
use futures::Future;
use std::pin::Pin;
use std::sync::Arc;
#[derive(Clone)]
pub struct SwarmRuntime {
inner: Arc<dyn BoxFutureSpawner + Send + Sync>,
}
impl SwarmRuntime {
pub fn new<S>(spawner: S) -> SwarmRuntime
where
S: BoxFutureSpawner + ... |
pub fn is_stopword(x: &str) -> bool {
match x {
"a" | "about" | "above" | "according" | "across" | "after" | "afterwards" | "again"
| "against" | "albeit" | "all" | "almost" | "alone" | "along" | "already" | "also"
| "although" | "always" | "am" | "among" | "amongst" | "an" | "and" | "anothe... |
/// NdmpContextsBackupExtended : Get NDMP Context List
#[allow(unused_imports)]
use serde_json::Value;
#[derive(Debug, Serialize, Deserialize)]
pub struct NdmpContextsBackupExtended {
#[serde(rename = "contexts")]
pub contexts: Option<Vec <crate::models::NdmpContextsBackupContext>>,
/// Resume string retu... |
use evo_sys::prog::get_src;
use evo_sys::{Program, Instruction, InstructionResult, InstructionType};
//
//use evo_sys::{Instruction, InstructionType};
use core::config::ProgDefaults;
use params::params::MAX_REGS;
use core::RegIndType;
use params as global_params;
use rand::{Rng, ThreadRng};
use rand::distrib... |
extern crate gl;
extern crate std;
extern crate num;
extern crate cgmath;
use gfx::window::Window;
use std::collections::HashMap;
use gfx::shader::{
Shader,
HasShader,
ShaderBuilder
};
use gfx::object::Object;
pub struct Pipeline {
pub programId: u32,
shaders: Vec<Shader>,
pub objects: HashMap... |
// This file is part of Substrate.
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Softwa... |
use std::borrow::Cow;
use std::fmt::{self, Write};
use std::error::Error;
use std::char;
use crate::keywords;
/// Error returned from `unquote_string` function
///
/// Opaque for now
#[derive(Debug)]
pub struct UnquoteError(String);
/// Converts the string into edgeql-compatible name (of a column or a property)
///
... |
#[macro_export]
macro_rules! def_bitfields {
( $t:ty, $($field:ident($l:expr, $r:expr),)* ) => {
$(
#[allow(non_snake_case)]
pub mod $field {
pub const SHIFT : $t = $r as $t;
pub const BITS : $t = (1 << ($l as $t + 1 - $r as $t)) - ... |
extern crate serde_json;
use std::ops::Add;
use self::serde_json::value::Value;
pub fn json_sum(value: &Value) -> i64 {
match *value {
Value::I64(n) => n,
Value::U64(n) => n as i64,
Value::Array(ref vec) => vec.iter().map(json_sum).fold(0, Add::add),
Value::Object(ref o) => o.value... |
use serenity::{
framework::{
standard::{
Args,
CommandResult,
macros::{
command,
},
},
},
model::{
channel::Message,
id::{
GuildId,
ChannelId
}
},
prelude::*,
};
use std:... |
use once_cell::sync::Lazy;
use parking_lot::RwLock;
use wasm_bindgen::prelude::wasm_bindgen;
#[allow(dead_code)]
pub static ARRAY: Lazy<RwLock<Vec<JoyState>>> = Lazy::new(|| RwLock::new(vec![]));
#[derive(Default, Debug)]
pub struct JoyState {
pub port: usize,
pub up: bool,
pub down: bool,
pub left: b... |
use crate::{utils::binary_read_helper::*, BinaryDecode, BinaryEncode};
use anyhow::Result;
use std::io::Cursor;
#[derive(Debug, Clone, Queryable)]
pub struct FrontDisplayUserPlayerTrack {
pub tid: i64,
pub rotation_x: f32,
pub rotation_y: f32,
pub rotation_z: f32,
pub location_x: f32,
pub locat... |
//! Traits input types have to implement to work with nom combinators
//!
use std::ops::{Range,RangeTo,RangeFrom,RangeFull};
#[cfg(not(feature = "core"))]
use std::str::Chars;
pub trait InputLength {
#[inline]
fn input_len(&self) -> usize;
}
impl<'a, T> InputLength for &'a[T] {
#[inline]
fn input_len(&self) ... |
// Copyright 2020 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 ... |
use std::fs;
use day_02;
fn main() {
let present_dimensions =
fs::read_to_string("puzzle_input.txt").expect("Could not open puzzle input.");
let present_dimensions = present_dimensions.trim();
println!(
"Part One: {} square feet",
day_02::find_total_wrapping(present_dimensions)
... |
// FIXME: imports will be relevant for layout expiration
//use chrono::offset::Utc;
//use chrono::prelude::*;
use serde_derive::{Deserialize, Serialize};
use std::collections::{BTreeMap, HashSet};
use crate::crypto;
use crate::error::Error;
use crate::metadata;
use crate::Result;
// FIXME, we need to tag a spec
//co... |
use std::collections::hash_set::HashSet;
const SIZE: usize = 5;
#[derive(Clone)]
pub struct Board {
numbers: Vec<u32>,
found: HashSet<u32>,
won: bool
}
impl Board {
fn new(vals: Vec<u32>) -> Board {
Board {
numbers: vals,
found: HashSet::new(),
won: false
... |
use std::fmt;
use std::cmp;
use std::time::{Instant, Duration};
use std::net::SocketAddr;
use std::collections::{HashMap, VecDeque};
use std::sync::mpsc::{Sender, Receiver};
use futures::sync::mpsc;
use futures::{Sink, Future};
use tokio_core::io::{EasyBuf};
use mqtt::{Encodable, Decodable, TopicName, QualityOfServi... |
//! A helper module to hold utilities that are used across tests. This file
//! DOES NOT container any of its own tests.
use diesel::PgConnection;
use gdlk_api::{
models::{self, Factory},
server::{create_gql_schema, GqlSchema},
util::{self, PooledConnection},
views::RequestContext,
};
use juniper::{Exe... |
//! Support for Breakpad ASCII symbols, used by the Breakpad and Crashpad libraries.
use std::borrow::Cow;
use std::collections::BTreeMap;
use std::error::Error;
use std::fmt;
use std::ops::Range;
use std::str;
use thiserror::Error;
use symbolic_common::{Arch, AsSelf, CodeId, DebugId, Language, Name, NameMangling};
... |
use near_sdk::borsh::{self, BorshDeserialize, BorshSerialize};
use near_sdk::{near_bindgen, AccountId};
near_sdk::setup_alloc!();
use near_sdk::collections::UnorderedMap;
#[near_bindgen]
#[derive(BorshDeserialize, BorshSerialize)]
pub struct NftOwners {
owners: UnorderedMap<String, AccountId>,
}
impl Default for... |
use async_std::{prelude::*, stream};
use chrono::Utc;
use log::{info, warn};
use serde_derive::{Deserialize, Serialize};
use serde_json::json;
use svc_agent::{
mqtt::{
Agent, IncomingMessage, IncomingRequestProperties, IntoPublishableMessage, OutgoingRequest,
OutgoingResponse, ShortTermTimingProper... |
fn inverse(x: f64) -> Result<f64, String> {
if x == 0.0f64 { return Err("x cannot be zero!".to_string()); }
Ok(1.0f64 / x)
}
fn main() {
let x = inverse(25.0f64);
match x {
Ok(x) => println!("The inverse is: {}", x),
Err(msg) => println!("Error: {}", msg),
}
}
|
// Copyright (c) The Starcoin Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::cli_state::CliState;
use crate::StarcoinOpt;
use anyhow::{format_err, Result};
use clap::Parser;
use network_p2p_types::peer_id::PeerId;
use network_types::peer_info::Multiaddr;
use scmd::{CommandAction, ExecContext};
#[... |
pub mod armdis;
#[macro_use] pub mod debugger;
pub mod bitdesc;
#[macro_use] pub mod logging;
#[macro_use] pub mod profiler;
// not ready.
// pub mod armasm;
pub use ::gba::core::memory::GbaMemory;
use self::armdis::*;
pub fn print_gba_rom_disasm(memory: &mut GbaMemory, thumb_mode: bool) {
if thumb_mode {
print_... |
use super::*;
#[derive(Copy, Clone, PartialEq)]
pub enum Kind {
Expr,
Simple,
Type,
}
pub struct Path {
pub colon: Option<Token![::]>,
pub segs: Puncted<Segment, Token![::]>,
}
impl Path {
pub fn is_ident<I: ?Sized>(&self, i: &I) -> bool
where
Ident: PartialEq<I>,
{
mat... |
use std::cell::RefCell;
use std::collections::HashMap;
use std::rc::Rc;
use rusty_battleships::message::{ShipPlacement, Direction, Message, Reason};
use rusty_battleships::board::{Board, PlayerState, Player, PlayerHandle, HitResult};
use rusty_battleships::ship::Ship;
use rusty_battleships::game::Game;
// From http:/... |
// Copyright 2019 WHTCORPS INC Project Authors. Licensed under Apache-2.0.
mod util;
use criterion::measurement::Measurement;
use milevadb_query_datatype::FieldTypeTp;
use fidel_timeshare::ExprType;
use fidel_timeshare_helper::ExprDefBuilder;
use crate::util::{BenchCase, FixtureBuilder};
/// COUNT(1) GROUP BY COL ... |
use crate::ir::*;
use crate::lexer::KeyWord::*;
use crate::lexer::Symbol::*;
use crate::lexer::Token::{self, *};
use crate::lexer::{TokenItem, TokenStream};
use parser::parser;
use std::collections::{HashMap, VecDeque};
use std::io::Write;
macro_rules! fail {
($fmt:expr, $($arg:tt)+) => {
println!();
... |
// pub(crate) mod animatable_storage;
// pub(crate) mod dense_storage;
// pub(crate) mod style_storage;
// pub(crate) mod dense_vec;
pub(crate) mod shared_set;
pub(crate) mod sparse_set;
pub(crate) mod animatable_set;
pub(crate) mod debug_storage;
pub(crate) mod style_set; |
use std::{fmt, str};
use std::io::{stdin, BufRead};
use regex::Regex;
use im::HashMap;
#[derive(Debug)]
struct ParseMaskError {
failing: char
}
impl fmt::Display for ParseMaskError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Unrecognized mask char '{}'", self.failing)
}... |
use std::cmp::{Eq, PartialEq};
use std::collections::VecDeque;
use std::hash::{Hash, Hasher};
// An entity is an id used to reference data in external storages.
// Rather than having widgets own their data, all state is stored in a single database and
// is stored and loaded using the entities.
#[derive(Clone, Copy, ... |
// This file is part of Substrate.
// Copyright (C) 2022 Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// 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://... |
//! A crate to convert a WebAssembly binary to its textual representation in the
//! WebAssembly Text Format (WAT).
//!
//! This crate is intended for developer toolchains and debugging, supporting
//! human-readable versions of a wasm binary. This can also be useful when
//! developing wasm toolchain support in Rust f... |
pub const PIE_HEADER_PREFIX: [u8; 4] = [45, 50, 49, 45];
pub const PIE_HEADER_LENGTH: usize = 64;
use super::instruction::Opcode;
use nom::types::CompleteStr;
pub mod directive_parser;
pub mod instruction_parser;
pub mod label_parser;
pub mod opcode_parser;
pub mod operand_parser;
pub mod program_parser;
pub mod regi... |
use g_code::{command, emit::Token, parse::ast::Snippet};
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
/// Whether the tool is active (i.e. cutting)
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub enum Tool {
Off,
On,
}
/// The distance mode for movement commands
#[derive(Copy, Clone, Partia... |
mod core;
mod env;
mod error;
mod hashmapkey;
mod reader;
mod value;
use im_rc::{vector, Vector};
use std::{
env::args,
io::{stderr, stdin, stdout, BufRead, Write},
rc::Rc,
};
use crate::{
core::ensure_len,
env::Env,
error as e,
reader::read,
value::{EvalResult, Value},
};
fn rep(s: ... |
// This file is part of Substrate.
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// 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.a... |
#![deny(unsafe_code)]
#![no_main]
#![no_std]
use aux5::{entry, Delay, DelayMs, LedArray, OutputSwitch};
#[entry]
fn main() -> ! {
let (mut delay, mut leds): (Delay, LedArray) = aux5::init();
let ms = 60_u16;
loop {
for i in 0..8 {
let next: usize = (i + 1) % 8;
leds[next]... |
use std::ops::Range;
use std::rc::Rc;
use failure;
use bio_types::annot::loc::Loc;
//use bio_types::annot::pos::Pos;
use bio_types::annot::spliced::Spliced;
use bio_types::strand::*;
use rust_htslib::bam;
use bam_utils::*;
//use codon_assign::*;
use transcript::*;
pub fn record_framing(
trxome: &Transcriptome<R... |
use super::Regex;
#[test]
fn only_matches_at_start_of_text() {
assert!(!Regex::from("ab?c").unwrap().is_match("zac"));
assert!(!Regex::from("ab?c").unwrap().is_match("abbbc"));
}
#[test]
fn matches_simple_examples() {
assert!(Regex::from("a?").unwrap().is_match(""));
assert!(Regex::from("a+").unwrap()... |
use core::any::{Any, TypeId};
use core::marker::PhantomData;
use core::convert::{From, Into};
use core::fmt;
use core::mem;
use core::ptr;
use common::*;
use spin::Mutex;
use util::MemoryObject;
/// Read/write lock for ManagedArc.
mod rwlock;
/// Weak pool storing weak pointers for ManagedArc.
mod weak_pool;
pub use ... |
// This file is part of Substrate.
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// 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.a... |
fn main() {
let mut input = String::new();
let mut s_count = 0;
std::io::stdin().read_line(&mut input).expect("error reading from the input");
for (i, c) in input.chars().enumerate(){
if c == 's' {
s_count = s_count + 1;
if s_count == 2 {
println!("hiss"... |
use {Header, HeaderName, HeaderValue};
/// `Access-Control-Allow-Credentials` header, part of
/// [CORS](http://www.w3.org/TR/cors/#access-control-allow-headers-response-header)
///
/// > The Access-Control-Allow-Credentials HTTP response header indicates whether the
/// > response to request can be exposed when the c... |
use std::mem;
fn main() {
let x: i32 = 10;
let y: i64 = x as i64;
let a = [0u8, 0u8, 0u8, 0u8];
// let b = a as u32;
// the above will not be compiled
unsafe {
let b = mem::transmute::<[u8; 4], u32>(a);
// transmute only checks the size of the data
// there will be an ... |
use crate::error::DatabaseError;
use crate::sqlite::Sqlite;
use bitflags::_core::str::from_utf8_unchecked;
use libsqlite3_sys::{sqlite3, sqlite3_errmsg, sqlite3_extended_errcode};
use std::error::Error as StdError;
use std::ffi::CStr;
use std::fmt::{self, Display};
use std::os::raw::c_int;
#[derive(Debug)]
pub struct ... |
use sdl2::{pixels, keycode};
use sdl2::rect::Point;
use std::default::Default;
use game::entity::{Entity, Asteroid};
use game::location::{Location, Displacement, Acceleration};
use game::Renderer;
static TURN_SPEED: f32 = 0.01;
static ACCELERATION: f64 = 0.00001;
pub struct Loop {
renderer: Renderer,
state: ... |
//! Implements popup handling functions for `Window`
use super::Window;
use core::view_plugins::{ViewHandle, ViewPlugins};
use core::session::SessionHandle;
use super::super::viewdock::{Direction, DockHandle};
use imgui_sys::Imgui;
use prodbg_api::{PDUIINPUTTEXTFLAGS_AUTOSELECTALL, PDUIINPUTTEXTFLAGS_ENTERRETURNSTRUE,... |
// Copyright (c) 2016-2017 Chef Software Inc. and/or applicable contributors
//
// 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
//
// Unl... |
#[doc = "Reader of register WF53"]
pub type R = crate::R<u8, super::WF53>;
#[doc = "Writer for register WF53"]
pub type W = crate::W<u8, super::WF53>;
#[doc = "Register WF53 `reset()`'s with value 0"]
impl crate::ResetValue for super::WF53 {
type Type = u8;
#[inline(always)]
fn reset_value() -> Self::Type {... |
// This file is part of Substrate.
// Copyright (C) 2019-2022 Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// 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
//
// ht... |
extern crate aoc1801;
use aoc::Solvable;
#[test]
fn input() -> aoc::Result<()> {
let input = aoc::reader(2018, 1, "input.txt")?;
assert_eq!(aoc1801::PartTwo::solve(&input)?, 55250);
Ok(())
}
#[test]
fn example_1() -> aoc::Result<()> {
let input = aoc::reader(2018, 1, "example.txt")?;
assert_eq!(aoc1801::PartTwo... |
use packed_simd::u16x32;
use std::cmp::min;
const RAW_INPUT: &str = include_str!("../../inputs/day03.txt");
pub fn day03() -> (usize, u16) {
let input: Vec<_> = parse_input(RAW_INPUT).collect();
(part1(&input), part2(&input))
}
pub fn part1(claims: &[Claim]) -> usize {
let cloth_masks = cloth_masks();
... |
#[macro_export]
macro_rules! punda {
(init = $init_path:ident $(, idle = $idle_path:ident)? $(, button_handler = $button_path:ident)?) => {
use cortex_m_semihosting::{debug, hprintln};
use heapless::{consts::*, spsc};
use microbit::{hal::{nrf51,
delay::DelayTimer,
... |
/**
* [1314] Matrix Block Sum
*
* Given a m x n matrix mat and an integer k, return a matrix answer where each answer[i][j] is the sum of all elements mat[r][c] for:
i - k <= r <= i + k,
j - k <= c <= j + k, and
(r, c) is a valid position in the matrix.
Example 1:
Input: mat = [[1,2,3],[4,5,6],[7,8,9]], k = 1... |
use std::collections::HashMap;
use fixedbitset::FixedBitSet;
use failure::Error;
use ndarray::prelude::*;
use itertools::Itertools;
use utils::Digits;
/// The solution to the prime digit replacement problem,
/// originally solved here `https://gist.github.com/Techcable/965341b217ae82defe1f541b3118c328`.
///
/// My k... |
use env::alias::*;
use std::collections::{HashMap, HashSet};
use std::net::IpAddr;
use std::sync::{Arc, RwLock};
#[derive(Serialize, Deserialize)]
pub struct HostID {
pub vendor: String,
//目标机服务商(云平台名称)
pub asid: String,
//目标机资产ID(实例ID)
pub ip: IpAddr,
}
#[derive(Serialize, Deserialize)]
pub enum ... |
#![allow(clippy::cast_precision_loss)]
use rand::{
distributions::{Alphanumeric, Distribution, WeightedIndex},
rngs::ThreadRng,
seq::SliceRandom,
Rng,
};
use std::{
fmt::{self, Display, Formatter},
iter,
};
const TARGET: &str = "Target123";
trait Dna: Clone {
fn new(rng: &mut ThreadRng) -... |
use gl::types::*;
// Note this requires OpenGL 4.3+ or extensions ARB_debug_output, AMD_debug_output.
// pub fn register_gl_error_handler() {
// gl::Enable(gl::DEBUG_OUTPUT);
// gl::DebugMessageCallback(gl_error_callback, std::ptr::null());
// }
#[cfg(debug_assertions)]
#[macro_export]
macro_rules! assert_no_... |
use std::{
net::{IpAddr, Ipv4Addr, SocketAddr},
thread,
time::Duration,
};
use async_trait::async_trait;
use bytes::Bytes;
use log::{info, warn};
use serde_derive::{Deserialize, Serialize};
use tentacle::secio::SecioKeyPair;
use core_network::{NetworkConfig, NetworkService};
use protocol::{
traits::{C... |
use super::sections::*;
use super::types;
use std::io::{self, Write};
use types::ValType;
/// Specifies the return type of a block
#[derive(Debug, Copy, Clone, PartialEq)]
pub enum BlockType {
// Doesn't return data
Empty,
// Returns a value
Type(types::ValType),
// Returns the type at ... |
pub const STACK_SIZE: usize = 0x8_0000;
pub const KERNEL_STACK_SIZE:usize = 0x8_0000; |
#[allow(unused_imports)]
use serde_json::Value;
#[derive(Debug, Serialize, Deserialize)]
pub struct AuthNetgroups {
#[serde(rename = "netgroups")]
pub netgroups: Option<Vec <crate::models::AuthNetgroup>>,
}
|
use nix::unistd::{sleep};
use std::io::prelude::*;
use std::process::{Command, Stdio};
fn main() {
let seconds = 3;
let process = match Command::new("r_pipe")
.stdin(Stdio::piped())
.spawn() {
Err(why) => panic!("Could not spawn progr... |
pub fn _try_iter() {
println!("--------------------");
println!("try_iter");
println!("--------------------");
let v1 = vec![1, 2, 3];
let v1_iter = v1.iter();
for val in v1_iter {
println!("Got: {}", val);
}
println!("{:?}", v1);
let v1 = vec![1, 2, 3];
{
let... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.