text stringlengths 8 4.13M |
|---|
/** Topic: Enums **/
/** Example: IP Address Struct with an Enum **/
enum IpAddrKind {
V4,
V6
}
struct IpAddr {
kind: IpAddrKind,
address: String
}
fn ip_addresses() {
let home = IpAddr {
kind: IpAddrKind::V4,
address: String::from("127.0.0.1")
};
let loopback = IpAddr {... |
use serde_derive::{Serialize, Deserialize};
use strum_macros::Display as EnumDisplay;
#[derive(Debug, EnumDisplay, Serialize, Deserialize)]
pub enum MoveType {
Forward,
Backward,
CWSpin,
CCWSpin
}
#[derive(Debug, Serialize, Deserialize)]
pub struct MoveRequest {
pub r#type: MoveType,
pub speed... |
use crate::{
bson::doc,
error::{ErrorKind, WriteFailure},
operation::{test::handle_response_test, DropCollection},
};
#[test]
fn handle_success() {
let op = DropCollection::empty();
let ok_response = doc! { "ok": 1.0 };
handle_response_test(&op, ok_response).unwrap();
let ok_extra = doc! {... |
use super::hash::Sha256Proxy;
use crate::{
types::{Address, Signature, TransactionRequest, H256},
utils::{hash_message, keccak256},
};
use rand::{CryptoRng, Rng};
use rustc_hex::FromHex;
use serde::{
de::Error as DeserializeError,
de::{SeqAccess, Visitor},
ser::SerializeTuple,
Deserialize, Dese... |
#[doc = "Register `RCC_DSICKSELR` reader"]
pub type R = crate::R<RCC_DSICKSELR_SPEC>;
#[doc = "Register `RCC_DSICKSELR` writer"]
pub type W = crate::W<RCC_DSICKSELR_SPEC>;
#[doc = "Field `DSISRC` reader - DSISRC"]
pub type DSISRC_R = crate::BitReader;
#[doc = "Field `DSISRC` writer - DSISRC"]
pub type DSISRC_W<'a, REG,... |
use strum::{Display, EnumIter};
#[derive(Display, Copy, Clone, Debug, Eq, Ord, PartialEq, PartialOrd, EnumIter)]
pub enum Contract {
Petite,
Garde,
#[strum(serialize = "Garde Sans")]
GardeSans,
#[strum(serialize = "Garde Contre")]
GardeContre,
}
impl Contract {
#[must_use]
pub const fn... |
#[doc = "Register `TWCR` reader"]
pub type R = crate::R<TWCR_SPEC>;
#[doc = "Register `TWCR` writer"]
pub type W = crate::W<TWCR_SPEC>;
#[doc = "Field `TOTALH` reader - Total Height (in units of horizontal scan line)"]
pub type TOTALH_R = crate::FieldReader<u16>;
#[doc = "Field `TOTALH` writer - Total Height (in units ... |
use super::{
super::{dfa::Dfa, prelude::*},
builder::{NfaBuilder, NfaNodeRef},
};
use std::{
borrow::Cow,
collections::{BTreeSet, HashMap, HashSet},
fmt::{self, Debug, Write},
hash::Hash,
};
pub type NfaTable<T, S> = HashMap<S, HashMap<Option<T>, HashSet<S>>>;
pub struct Nfa<T, S> {
states: NfaTable<T, ... |
pub mod icosahedron;
|
use std::{fs::File, env::current_dir};
use std::io::{self, BufRead};
use std::path::Path;
pub fn read_day(day_number: usize) -> io::Lines<io::BufReader<File>> {
let root_dir = current_dir().unwrap();
let puzzle_path = root_dir.join("Input").join(format!("day_{}.txt", day_number));
match read_lines(puzzle_path) {
... |
use fast_hash::FxHashMap;
#[derive(Debug)]
pub(crate) struct TokenDb {
pub(crate) punctuation: FxHashMap<ungrammar::Token, Token>,
pub(crate) keywords: FxHashMap<ungrammar::Token, Token>,
pub(crate) special: FxHashMap<ungrammar::Token, Token>,
}
/// A token kind.
#[derive(Debug)]
pub enum TokenKind {
/// Punc... |
/*
use std::io::{self, BufRead, Write};
#[macro_use]
extern crate clap;
use clap::App;
fn main() {
/*
* parse the command line arugmnet
*/
let yaml = load_yaml!("../arguments.yml");
let matches = App::from_yaml(yaml).get_matches();
let mut contest = atcoder::Contest::new();
if matches.... |
pub use descartes::{N, P3, P2, V3, V4, M4, Iso3, Persp3, Into2d, Into3d, WithUniqueOrthogonal,
Area, LinePath, Segment};
use compact::CVec;
use compact_macros::Compact;
use std::rc::Rc;
use crate::sculpt::{Sculpture, SpannedSurface, SculptLine};
#[derive(Copy, Clone, Debug)]
pub struct Vertex {
pub position: [f32... |
use std::time::Instant;
use md5::Digest;
const INPUT: &str = include_str!("../input.txt");
fn inputs(prefix: &str) -> impl Iterator<Item = Digest> + '_ {
let prefix_bytes = prefix.as_bytes();
(1..).map(move |n| {
let to_hash = [prefix_bytes, n.to_string().as_bytes()].concat();
md5::compute(... |
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, FromPrimitive, ToPrimitive)]
pub enum LidarMode {
LidarModeNormal = 1,
LidarModePowerSaving = 2,
LidarModeStandby = 3,
}
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, FromPrimitive, ToPrimitive)]
pub enum LidarState {
LidarStateInit = 0,
Lidar... |
mod shapes;
extern crate rand;
use shapes::Rectangle;
use std::collections::HashMap;
use rand::Rng;
fn main() {
println!("Hello, world!");
print_value(188, 166);
let value: i32 = 2;
println!("After increase_by_one: {}", increase_by_one(value));
println!("Origin value is: {}", value);
// if 语句
let x:... |
// Note: This file is only currently used on targets that call out to the code
// in `mod libs_dl_iterate_phdr` (e.g. linux, freebsd, ...); it may be more
// general purpose, but it hasn't been tested elsewhere.
use super::mystd::fs::File;
use super::mystd::io::Read;
use super::mystd::str::FromStr;
use super::{OsStrin... |
//! A simple example of hooking up stdin/stdout to a WebSocket stream.
//!
//! This example will connect to a server specified in the argument list and
//! then forward all data read on stdin to the server, printing out all data
//! received on stdout.
//!
//! Note that this is not currently optimized for performance, ... |
use std::fs::File;
use std::io::Bytes;
const COMMENT_CHAR: char = ';';
const NEWLINE_CHAR: char = '\n';
const COMMA_CHAR: char = ',';
const SPACE_CHAR: char = ' ';
const TAB_CHAR: char = '\t';
#[derive(Debug, Copy, Clone)]
pub enum Mnemonic {
Add, And, Call, Cls,
Drw, Jp, Ld, Or,
Ret, Rnd, Se, Shl,
S... |
use std::fmt;
use crate::trit::Trit;
use crate::byte::Byte;
use crate::operation::Operation;
use crate::byte_le;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Word {
pub bytes: [Byte; Word::BYTE_COUNT],
}
impl Word {
pub const BYTE_COUNT: usize = 2;
pub const IBYTE_COUNT: isize = 2;
pu... |
use super::*;
/// A row in a [`Table`][`Table`].
///
/// # Semantics
///
/// A row contains cell which can contain content.
///
/// # Syntax
///
/// There are two kinds of table rows:
///
/// - normal: vertical bar and any number of [`TableCell`][`objects::TableCell`]s
/// ```text
/// | cell 1 | cell 2 | ... |
///... |
use aoc2019::io::{slurp_stdin, parse_intcode_program};
use aoc2019::intcode;
use aoc2019::intcode::{Mem,Ptr};
use aoc2019::permutation::Permutations;
fn run_phase(program: Vec<Mem>, phases: Vec<Mem>) -> Result<Mem, String> {
let mut last_output = 0;
for phase in phases {
let mut input = Vec::<Mem>::new... |
use super::sacak_u32s;
use proptest::prelude::*;
proptest! {
#[test]
fn sacak_u32s_correctness(mut s in ints(1..8192_usize)) {
prop_assert!(check(&mut s[..]));
}
}
fn ints(
scale: impl Strategy<Value = usize>,
) -> impl Strategy<Value = Vec<u32>> {
scale.prop_flat_map(|k| prop::collection:... |
use ::{Package, PackageInfo, Search};
pub struct Info {
package: String,
version: Option<String>
}
impl Info {
pub fn new(package: &str) -> Info {
Info { package: String::from(package), version: None }
}
pub fn execute(&self) -> Result<PackageInfo, Vec<Package>> {
let package = P... |
extern crate curl;
extern crate regex;
extern crate telegram_bot;
extern crate tokio_core;
use curl::easy::Easy;
use regex::Regex;
use std::env;
use tokio_core::reactor::Core;
use telegram_bot::{Api, GetMe};
fn main2() {
let mut easy = Easy::new();
easy.url("https://scanlibs.com/").unwrap();
easy.write... |
use actix_web::{App, HttpServer};
use std::panic::PanicInfo;
pub mod apis;
#[actix_web::main]
async fn main() -> std::io::Result<()> {
// On panic we must do some emergency things in order to correctly shutdown the server
std::panic::set_hook(Box::new(panic_hook));
// Setup the actix's http server
Htt... |
use connectorx::{
destinations::arrow::ArrowDestination, prelude::*, sources::bigquery::BigQuerySource,
sql::CXQuery, transports::BigQueryArrowTransport,
};
use std::env;
use std::sync::Arc;
use tokio::runtime::Runtime;
#[test]
#[ignore]
fn test_source() {
let dburl = env::var("BIGQUERY_URL").unwrap();
... |
use crate::{
bytecode::{opcodes::Op, TypeFeedBack},
runtime::{
arguments::Arguments,
env::Env,
error::{JsError, JsTypeError},
function::JsVMFunction,
js_arguments::JsArguments,
object::{JsHint, JsObject, ObjectTag},
slot::Slot,
string::JsString,
... |
use std::fs::File;
use std::io::prelude::*;
use crate::protocol::Protocol;
use crate::region::Region;
use crate::case::Case;
pub struct Reader {
protocol: Protocol,
processor_quantity: u32
}
impl Reader {
pub fn new(host: String,
processor_queue: String,
processor_quantity: u32) -> Reader... |
use std::{collections::HashMap, fs};
use napi::{CallContext, Error, JsNumber, JsObject, JsString, Result};
use crate::{generate_schema, parse_ts, GraphQLKind};
#[cfg(all(
any(windows, unix),
target_arch = "x86_64",
not(target_env = "musl"),
not(debug_assertions)
))]
#[global_allocator]
static ALLOC: ... |
use mongodb::Document;
use rocket_contrib::database;
pub mod helpers;
#[database("primary_db")]
pub struct PrimaryDb(pub mongodb::db::Database);
pub trait FromDoc {
fn from_doc(item : Document) -> Self;
}
|
mod double_keyframe;
mod multi_dimensional;
mod multi_dimensional_keyframed;
mod offset_keyframe;
mod shape;
mod shape_keyframed;
mod shape_prop;
mod shape_prop_keyframe;
mod value;
mod value_keyframe;
mod value_keyframed;
pub use self::{
double_keyframe::*, multi_dimensional::*, multi_dimensional_keyframed::*, of... |
use std::collections::HashMap;
use super::super::error::Response::Wrong;
use super::*;
pub struct Frame {
pub locals: HashMap<String, Object>,
}
impl Frame {
pub fn new() -> Self {
Frame {
locals: HashMap::new()
}
}
pub fn set_name(&mut self, name: &String, value: Object) {
self.locals.ins... |
use crate::util::misc::*;
use core::time::Duration;
pub mod cpuid;
#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CPUPrivLevel
{
Ring0 = 0,
Ring3 = 3,
}
impl CPUPrivLevel
{
pub const fn n(&self) -> u8
{
*self as u8
}
pub const fn get_cs(&self) -> u16
{
match self {
Self::Ring0 => 0x... |
use {NssStatus, gethostbyname};
use libc::{c_char, size_t, hostent, AF_INET};
use libc::{ENOENT, ERANGE};
use std::ffi::CStr;
use std::str;
use std::mem::size_of;
use std::ptr;
#[no_mangle]
pub unsafe extern "C" fn _nss_openvpn_gethostbyname2_r(
name: *const c_char,
af: i32,
result: *mut hostent,
buff... |
fn part(side: char, range: (u32, u32)) -> (u32, u32) {
let (min, max) = range;
let mid = ((max - min) / 2) + min;
match side {
'F' | 'L' => (min, mid),
'B' | 'R' => (mid + 1, max),
_ => (min, max)
}
}
fn seat_row_col(seat: &str) -> (u32, u32) {
let row_str = &seat[..7];
... |
#![allow(unused_variables)]
use block::Block;
use cocoa::base::{BOOL, id};
use cocoa::foundation::NSUInteger;
use libc::c_void;
use {MTLFeatureSet, MTLPipelineOption, MTLResourceOptions, MTLSize};
/// The `MTLDevice` protocol defines the interface to a single graphics processor (GPU). You use
/// an object that confo... |
use exprtk_rs::*;
use approx::relative_eq;
use arbitrary::Arbitrary;
#[derive(Debug, Arbitrary)]
pub struct Data {
var_sym: char,
const_sym: char,
str_sym: char,
vec_sym: char,
func_sym: char,
formula: String,
}
pub fn validate_input(data: Data) {
let mut symbols = SymbolTable::new();
... |
extern crate testing;
#[cfg(not(test))]
fn main() {
println!("Hello, world!")
}
#[test]
fn is_one_equal_to_one() {
assert_eq!(1i, 1i);
} |
use structopt::StructOpt;
/// This struct models the command line options
#[derive(Debug, StructOpt)]
#[structopt(name = "mncalc", about = "Simple Mixed Numbers Calculator")]
pub struct Config {
#[structopt(short = "e", long = "eval", help = "The expression to evaluate")]
expression: Option<String>
}
/// The ... |
struct Student {
roll_no: u8,
// name: &'a str,
name: String,
age: u8,
}
fn main(){
let mut x = 5;
x += 3;
let y = 6;
let z = x + y;
println!("Sum of nos is {}", z);
fn next_birthday(name: String, age: u8) {
let next_age = age + 1;
println!("Hi {},On next birthday you will ... |
// This file is part of Substrate.
// Copyright (C) 2017-2020 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... |
#[cfg(target_arch = "aarch64")]
mod aarch64;
#[cfg(all(target_arch = "arm", not(target_feature = "thumb-mode")))]
mod arm;
#[cfg(all(target_arch = "arm", target_feature = "thumb-mode"))]
mod arm_thumb;
#[cfg(target_arch = "mips")]
mod mips;
#[cfg(target_arch = "mips64")]
mod mips64;
#[cfg(target_arch = "powerpc")]
mod ... |
use anyhow::{bail, Result};
use fs_err as fs;
use maturin::Target;
use normpath::PathExt as _;
use std::path::Path;
use std::path::PathBuf;
use std::process::{Command, Stdio};
use std::{env, io, str};
pub mod develop;
pub mod errors;
pub mod integration;
pub mod other;
/// Check that the package is either not install... |
use std::convert::From;
use std::io::Read;
use std::io::Seek;
use std::path::Path;
use std::rc::Rc;
use super::super::error::Error;
use super::super::error::ErrorKind;
use super::super::error::Result;
use super::file::IsoFile;
use super::node::Node;
use super::IsoFs;
/// Metadata information about an ISO-9600 files... |
use crate::rerrs::{ErrorKind, SteelErr};
use crate::rvals::{Result, SteelVal};
use crate::stop;
use crate::primitives::lists::ListOperations;
macro_rules! ok_string {
($string:expr) => {
Ok(SteelVal::StringV($string.into()))
};
}
pub struct StringOperations {}
impl StringOperations {
pub fn strin... |
//! This example demonstrates using the [`Width`] [`TableOption`] to expand and
//! contract a [`Table`] display.
//!
//! * Note how table-wide size adjustments are applied proportionally to all columns.
//!
//! * Note how [fluent](https://en.wikipedia.org/wiki/Fluent_interface) functions
//! are available to make subt... |
//! [Mixed-script detection](https://www.unicode.org/reports/tr39/#Mixed_Script_Detection)
use core::fmt::{self, Debug};
use unicode_script::{Script, ScriptExtension};
/// An Augmented script set, as defined by UTS 39
///
/// https://www.unicode.org/reports/tr39/#def-augmented-script-set
#[derive(Copy, Clone, Partial... |
/// An enum to represent all characters in the MeroiticHieroglyphs block.
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
pub enum MeroiticHieroglyphs {
/// \u{10980}: '𐦀'
MeroiticHieroglyphicLetterA,
/// \u{10981}: '𐦁'
MeroiticHieroglyphicLetterE,
/// \u{10982}: '𐦂'
MeroiticHieroglyphicL... |
mod helpers;
use jsonprima;
// [
test!(test_1, "[", vec![("E127", 0, 1)]);
test!(test_2, " [", vec![("E127", 1, 2)]);
test!(test_3, "[ ", vec![("E127", 1, 2)]);
test!(test_4, " [ ", vec![("E127", 2, 3)]);
// ]
test!(test_5, "]", vec![("E126", 0, 1)]);
test!(test_6, " ]", vec![("E126", 1, 2)]);
test!(test_7, "] ", ve... |
use md5;
use std::fs::File;
use std::io::Read;
use std::str;
pub fn generate_signature(filename: &str) -> Signature {
let mut file = match File::open(filename) {
Ok(file) => file,
Err(e) => panic!("Could not open file {}: {}", filename, e),
};
let mut buf = vec![];
match file.read_to... |
extern crate dotenv;
//use diesel::prelude::*;
use crate::schema::characters;
use chrono::*;
#[derive(Identifiable, Queryable, PartialEq, Debug, Associations, Clone)]
#[table_name = "characters"]
pub struct Character {
pub id: i32,
pub name: String,
pub created_at: NaiveDateTime,
pub updated_at: Naiv... |
use anilist::models::User;
use serenity::builder::CreateEmbed;
use serenity::framework::standard::CommandResult;
use serenity::model::prelude::{ChannelId, Reaction, ReactionType, UserId};
use serenity::prelude::Context;
use crate::anilist::embeds::{user_favourites_embed, user_overview_embed, user_stats_embed};
use cra... |
use std::cell::RefCell;
use std::rc::Rc;
use wasm_bindgen_futures;
use web_sys::HtmlImageElement;
use web_sys::WebGl2RenderingContext;
use web_sys::WebGl2RenderingContext as GL;
use web_sys::WebGlTexture;
pub struct Texture {
pub width: u32,
pub height: u32,
pub texture: WebGlTexture,
}
impl Texture {
... |
extern crate itertools;
extern crate unicode_segmentation;
use itertools::Itertools;
use unicode_segmentation::UnicodeSegmentation;
mod array_2d;
pub use array_2d::Array2D;
pub fn graphemes(s: &str) -> Vec<&str> {
UnicodeSegmentation::graphemes(s, true).collect::<Vec<&str>>()
}
pub fn generate_bigrams(s: &str) ... |
#[doc = "Register `MPCBB1_VCTR6` reader"]
pub type R = crate::R<MPCBB1_VCTR6_SPEC>;
#[doc = "Register `MPCBB1_VCTR6` writer"]
pub type W = crate::W<MPCBB1_VCTR6_SPEC>;
#[doc = "Field `B192` reader - B192"]
pub type B192_R = crate::BitReader;
#[doc = "Field `B192` writer - B192"]
pub type B192_W<'a, REG, const O: u8> = ... |
// Copyright (c) 2016 mussh 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,
// ... |
pub(crate) mod database_name;
|
use super::MapArchitect;
use crate::prelude::*;
pub struct EmptyArchitect {}
impl MapArchitect for EmptyArchitect {
fn new(&mut self, rng: &mut RandomNumberGenerator) -> MapBuilder {
let mut mb = MapBuilder::empty();
mb.fill(TileType::Floor);
mb.player_start = mb.map.center();
mb.... |
extern crate regex;
use std::collections::HashMap;
use std::collections::hash_map::Entry;
pub fn word_count(s: &str) -> HashMap<String, u32> {
if s == "" {
return HashMap::new();
}
let re = regex::Regex::new(r"[^A-Za-z0-9]+").unwrap();
let s = re.split(s).collect::<Vec<&str>>();
let mut h: HashMap<String... |
use crate::{Timestamp, Uint32};
use serde::{Deserialize, Serialize};
#[derive(Deserialize, Serialize, Debug)]
pub struct PeerState {
// TODO use peer_id
// peer session id
peer: Uint32,
// last updated timestamp
last_updated: Timestamp,
// blocks count has request but not receive response yet
... |
use Error;
use wire::pretty_print::{PrettyPrint, PrettyPrinter};
use super::Device;
/// A tracer device.
///
/// A tracer is a device that prints all packets traversing it
/// to the standard output, and delegates to another device otherwise.
pub struct Tracer<T: Device, U: PrettyPrint> {
lower: T,
writer: ... |
/**********************************************
> File Name : TextEditor.rs
> Author : lunar
> Email : lunar_ubuntu@qq.com
> Created Time : Fri Aug 12 23:33:35 2022
> Location : Shanghai
> Copyright@ https://github.com/xiaoqixian
**********************************************/
use std::ptr:... |
fn middle_three_digits(x: i32) -> Result<String, String> {
let s: String = x.abs().to_string();
let len = s.len();
if len < 3 {
Err("Too short".into())
} else if len % 2 == 0 {
Err("Even number of digits".into())
} else {
Ok(s[len/2 - 1 .. len/2 + 2].to_owned())
}
}
fn ... |
#![recursion_limit = "512"]
extern crate proc_macro;
mod items;
use proc_macro::TokenStream;
use quote::quote;
use syn::{
braced, parenthesized,
parse::{self, Parse, ParseStream},
parse_macro_input,
punctuated::Punctuated,
token, Attribute, Ident, Token, Visibility,
};
use items::{Item, encode_i... |
use bevy::prelude::*;
use crate::player::Player;
use crate::collision::{Hurtbox, Team, CanHitTeam, HitBoxEvent};
#[derive(Bundle)]
pub struct SkeletonBundle {
skeleton: Skeleton,
hurtbox: Hurtbox,
#[bundle]
sprite: SpriteBundle
}
impl SkeletonBundle {
pub fn new(materials: &mut Assets<ColorMaterial... |
extern crate toml;
#[test]
fn bad() {
fn bad(s: &str) {
assert!(s.parse::<toml::Value>().is_err());
}
bad("a = 01");
bad("a = 1__1");
bad("a = 1_");
bad("''");
bad("a = nan");
bad("a = -inf");
bad("a = inf");
bad("a = 9e99999");
}
|
use super::shared_vec_slice::SharedVecSlice;
use common::make_io_err;
use directory::error::{DeleteError, IOError, OpenReadError, OpenWriteError};
use directory::WritePtr;
use directory::{Directory, ReadOnlySource};
use std::collections::HashMap;
use std::fmt;
use std::io::{self, BufWriter, Cursor, Seek, SeekFrom, Writ... |
use response::RawPagedResponse;
pub trait PagedRequest {
type Item;
fn retrieve_single_page(&self, url: String) -> Result<RawPagedResponse<Self::Item>, String>;
}
|
use std::io::*;
pub fn get_player_move() -> ((usize, usize), (usize, usize)) {
let mut parsed: Option<((usize, usize), (usize, usize))> = None;
while let None = parsed {
println!("Input move: <start> <end>");
parsed = parse_input(get_input());
}
parsed.unwrap()
}
pub fn parse_input(inp... |
/*
* Datadog API V1 Collection
*
* Collection of all Datadog Public endpoints.
*
* The version of the OpenAPI document: 1.0
* Contact: support@datadoghq.com
* Generated by: https://openapi-generator.tech
*/
/// WidgetSizeFormat : Size of the widget.
/// Size of the widget.
#[derive(Clone, Copy, Debug, Eq, Par... |
// use std::ops::{Add, AddAssign, Sub, SubAssign, Mul, MulAssign, Div, DivAssign};
#[macro_export]
macro_rules! use_elem_wise_ops {
() => {
use std::ops::{Add, AddAssign};
use std::ops::{Sub, SubAssign};
use std::ops::{Mul, MulAssign};
use std::ops::{Div, DivAssign};
}
}
#[macr... |
// Copyright 2015 The Rust-Windows Project Developers. See the
// COPYRIGHT file at the top-level directory of this distribution.
//
// 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/MI... |
#[path = "util.rs"] mod util;
use util::*;
/// A distribution of n indistinguishable elements in m possible cells
#[derive(Debug)]
pub struct IDistribution {
pub n: u16,
pub m: u16
}
pub struct IDistributionIter<'a> {
distr: &'a IDistribution,
index: u64
}
impl<'a> IntoIterator for &'a IDistribution {
type... |
extern crate sdl2;
extern crate chiprs;
mod sdl_interface;
use crate::sdl_interface::run_sdl_interface;
use chiprs::Chip;
fn main() {
let args: Vec<String> = std::env::args().collect();
match args.len() {
2 => {
let filename = &args[1];
run(filename);
}
_ => {... |
use std::{cell::Cell, time::Duration};
use xidlehook_core::{timers::CallbackTimer, Xidlehook};
const TEST_UNIT: Duration = Duration::from_millis(50);
#[test]
fn general_timer_test() {
let triggered = Cell::new(0);
let mut timer = Xidlehook::new(vec![
CallbackTimer::new(TEST_UNIT * 100, || triggered.s... |
// Copyright 2014 Tyler Neely
//
// 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 in writ... |
/*!
# QR Code Generator
This crate provides functions to generate QR Code matrices and images in RAW, PNG and SVG formats.
## Examples
#### Encode any data to a QR Code matrix which is `Vec<Vec<bool>>`.
```rust
use qrcode_generator::QrCodeEcc;
let result: Vec<Vec<bool>> = qrcode_generator::to_matrix("Hello world!"... |
#[derive(Debug)]
enum IpAddrKind {
V4,
V6,
}
fn main() {
let four : IpAddrKind = IpAddrKind::V4;
let six = IpAddrKind::V6;
println!("Hello, world! {:?}", four);
let mut some_u8_value = Some(9u8);
some_u8_value = match some_u8_value {
Some(3) => {
println!("three");
... |
use super::alu::add;
use super::alu::dec_hl;
use super::alu::inc_hl;
use super::flags::SUB;
use super::flags::ZERO;
use crate::cpu::CPU;
use crate::mmu::MMU;
pub fn ld_a_n(cpu: &mut CPU, mmu: &mut MMU) -> u8 {
cpu.regs.a = cpu.fetch_byte(mmu);
8
}
pub fn ld_b_n(cpu: &mut CPU, mmu: &mut MMU) -> u8... |
use std::io;
use std::path::{PathBuf};
use rocket::response::{NamedFile, Redirect};
// use rocket_contrib::Template;
// for web assembly
#[get("/1.js")]
fn web() -> io::Result<NamedFile> {
NamedFile::open("static/video/1.js")
}
#[get("/")]
fn index() -> io::Result<NamedFile> {
NamedFile::open("static/index.h... |
use blake2_rfc::blake2b::{Blake2b, blake2b};
pub type Hash = [u8; 32];
// Copied from: https://github.com/paritytech/substrate/blob/master/core/primitives/src/hashing.rs
/// Do a Blake2 256-bit hash and place result in `dest`.
pub fn blake2b_256_into(data: &[u8], dest: &mut Hash) {
dest.copy_from_slice(blake2b(32... |
//! Nom, eating data byte by byte
//!
//! The goal is to make a parser combinator library that is safe,
//! supports streaming (push and pull), and as much as possible zero copy.
//!
//! The code is available on [Github](https://github.com/Geal/nom)
//!
//! # Example
//!
//! ```
//! #[macro_use]
//! extern crate nom;
/... |
extern crate hyper;
use std::convert::From;
use hyper::mime;
use hyper::header::{Basic, ContentType, ContentLength};
pub struct Twiml {
data: String,
}
impl From<Twiml> for hyper::Response {
fn from(owned_twiml:Twiml) -> hyper::Response {
hyper::Response::new()
.with_header(ContentType(m... |
mod hello;
pub use hello::get_module; |
use std::io;
fn main() -> io::Result<()> {
for handle in nihao_stlink::handles()? {
// println!("Handle: {:?}", handle);
match handle {
Ok(handle) => {
println!("Desc: {:?}", handle.as_ref().device_descriptor());
print_one(&handle);
},
... |
// Copyright 2019 King's College London.
// Created by the Software Development Team <http://soft-dev.org/>.
//
// 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... |
mod functions;
mod implementation;
mod traits;
mod bounds;
mod multi_bounds;
mod where_clauses;
mod associated_types;
mod phantom_type;
#[cfg(test)]
mod tests {
use crate::{A, Single, SingleGen};
#[test]
fn main() {
let _s = Single(A);
let _char = SingleGen('a');
let _t = SingleGe... |
use pom::parser::*;
use pom::{Parser, TextInput};
use crate::dictionary::Text;
use crate::parser::utils::*;
const SPECIALS: &str = "{}〈〉《》◆■〔〕\n";
pub fn parse_line(input: &str) -> Result<Vec<Text>, pom::Error> {
let mut input = TextInput::new(input);
text().parse(&mut input)
}
fn with_spaces(p: Parser<... |
use crate::page::{Anchor, Page};
use std::io::{self, Write};
pub trait PageWriter {
/// Write Page data.
fn write<W: Write>(page: Page, writer: &mut W) -> io::Result<()>;
}
/// Write page categories.
pub struct CategoryWriterTSV;
pub struct CategoryWriterJSONL;
impl PageWriter for CategoryWriterTSV {
fn ... |
//! This is a simple "Flat" rendering pipeline.
//! It doesn't support blended objects and uses front-to-back ordering.
//! The pipeline is meant for simple applications and fall-back paths.
use std::marker::PhantomData;
use gfx;
use gfx_phase;
use gfx_scene;
/// A short typedef for the phase.
pub type Phase<R> = gfx... |
//Restarted script log at Fri 12 Jul 2013 15:21:12 CEST
getBody(5).deselect();
getBody(2).deselect();
getBody(1).deselect();
getBody(5).select();
getBody(1).select();
getBody(2).select();
getBody(5).deselect();
getBody(2).deselect();
getBody(1).deselect();
getBody(5).select();
getBody(2).select();
getBody(1).select();
... |
use std::fmt;
use crate::format::{format_directives, Displayable, Formatter, Style};
use crate::query::ast::*;
use crate::query::refs::{
FieldRef, FragmentSpreadRef, InlineFragmentRef, SelectionRef, SelectionSetRef,
};
impl<'a> Document<'a> {
/// Format a document according to style
pub fn format(&self, ... |
use std::f32;
use std::cmp;
#[derive(Debug)]
pub struct BiQuadCoeffs {
a1: f32,
a2: f32,
b0: f32,
b1: f32,
b2: f32
}
impl BiQuadCoeffs {
pub fn new(b0: f32, b1: f32, b2: f32, a1: f32, a2: f32) -> BiQuadCoeffs {
BiQuadCoeffs {
b0,
b1,
b2,
... |
#[doc = "Register `MACTSSR` reader"]
pub type R = crate::R<MACTSSR_SPEC>;
#[doc = "Field `TSSOVF` reader - Timestamp Seconds Overflow"]
pub type TSSOVF_R = crate::BitReader;
#[doc = "Field `TSTARGT0` reader - Timestamp Target Time Reached"]
pub type TSTARGT0_R = crate::BitReader;
#[doc = "Field `AUXTSTRIG` reader - Aux... |
use std::collections::HashMap;
use sudo_test::{Command, Env, TextFile};
use crate::{Result, SUDOERS_ALL_ALL_NOPASSWD, USERNAME};
macro_rules! assert_snapshot {
($($tt:tt)*) => {
insta::with_settings!({
prepend_module_to_snapshot => false,
snapshot_path => "../snapshots/flag_shell"... |
#[doc = "Reader of register NVIC_IPR7"]
pub type R = crate::R<u32, super::NVIC_IPR7>;
#[doc = "Writer for register NVIC_IPR7"]
pub type W = crate::W<u32, super::NVIC_IPR7>;
#[doc = "Register NVIC_IPR7 `reset()`'s with value 0"]
impl crate::ResetValue for super::NVIC_IPR7 {
type Type = u32;
#[inline(always)]
... |
pub fn run(){
// i32
let x = 1;
let xy: i8 = 2;
println!("max i32:{}",std::i32::MAX);
let is_active = true;
let is_greater = 1>-1;
println!("{:?}",(x,xy,is_active,is_greater));
let ch = '\u{1F600}';
println!("{:?}",(x,xy,is_active,is_greater,ch));
} |
use anyhow::{anyhow, Result};
use directories_next::ProjectDirs;
use std::path::Path;
/// Returns the path to the storage folder containing the `entries_file`
pub fn storage_dir() -> Result<String> {
match std::env::var("PAGE_STORAGE_FOLDER") {
Ok(f) => Ok(f),
Err(_) => match ProjectDirs::from("", ... |
#[cfg(feature = "unstable")]
use std::str::pattern::{Pattern,Searcher};
#[derive(Copy,Clone,Debug,PartialEq)]
pub enum SplitType<'a> {
Match(&'a str),
Delimiter(&'a str),
}
#[cfg(feature = "unstable")]
pub struct SplitKeepingDelimiter<'p, P>
where P: Pattern<'p>
{
searcher: P::Searcher,
start: usi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.