text stringlengths 8 4.13M |
|---|
use std;
use read_process_memory::CopyAddress;
/// Copies a struct from another process
pub fn copy_struct<T, P>(addr: usize, process: &P) -> std::io::Result<T>
where P: CopyAddress {
let mut data = vec![0; std::mem::size_of::<T>()];
process.copy_address(addr, &mut data)?;
Ok(unsafe { std::ptr::read(da... |
fn main() {
// Set in build.rs.
let compiler_path = env!("COMPILER_PATH");
let mut compiler_command = std::process::Command::new(compiler_path);
// Use the --version flag on everything other than MSVC.
if !cfg!(target_env = "msvc") {
compiler_command.arg("--version");
}
// Run the c... |
mod spiral;
pub fn solve_puzzle_part_1(input: u32) -> String {
//puzzle(input).to_string()
puzzle1(input as usize).to_string()
}
pub fn solve_puzzle_part_2(input: u32) -> String {
puzzle2(input).to_string()
}
fn puzzle1(index: usize) -> u32 {
// loop over all rings, look for the location of index in ... |
use pyo3::prelude::*;
use pyo3::wrap_pyfunction;
use std::fmt;
use std::fs::File;
use std::io::{BufRead, BufReader, Error, ErrorKind};
use std::num::ParseIntError;
use std::{env, error};
use game::Game;
mod game;
mod grid;
#[derive(Debug)]
pub enum ConnectzError {
Incomplete,
IllegalContinue,
IllegalRow,... |
use crate::auth::{AuthenticationError, Credentials};
use crate::{
auth::UserDetail,
server::{
controlchan::{
error::ControlChanError,
handler::{CommandContext, CommandHandler},
Reply, ReplyCode,
},
session::SessionState,
},
storage::{Metadata, ... |
/*!
Traits and types related to loading an abi_stable dynamic library,
as well as functions/modules within.
*/
use std::{
fmt::{self, Display},
io,
marker::PhantomData,
mem,
path::{Path,PathBuf},
sync::atomic,
};
#[allow(unused_imports)]
use core_extensions::prelude::*;
use libloading::{
... |
use std::io::prelude::*;
use std::io::{self, BufReader, BufWriter};
use std::net::TcpStream;
pub struct BufTcpStream {
input: BufReader<TcpStream>,
output: BufWriter<TcpStream>,
}
impl BufTcpStream {
pub fn new(stream: TcpStream) -> io::Result<Self> {
let input = BufReader::new(stream.try_clone()?... |
// From: https://github.com/godot-rust/godot-rust/blob/bddbaedccaa56ce6411db6cb8f74206a01dd1196/examples/dodge_the_creeps/src/extensions.rs
use gdnative::prelude::*;
pub trait NodeExt {
/// Gets a node at `path`, assumes that it's safe to use, and casts it to `T`.
///
/// # Safety
///
/// See `Ptr::assume_sa... |
pub fn start(){
// Declare variable => Immutable by default
let imut_var = 1;
println!("This is Immutable variable: {}", imut_var);
// Declare variable mutable
let mut mut_var = 1;
println!("This is Mutable variable: {}", mut_var);
mut_var = 2;
println!("This is Mutable variable: {}", ... |
use std::collections::VecDeque;
use std::io::{self, Read};
use crate::disk::block::BlockDeviceRef;
use crate::disk::block::Location;
use crate::disk::block::BLOCK_SIZE;
use crate::disk::chain::{ChainIterator, ChainReader};
use crate::disk::directory::{self, DirectoryEntry};
use crate::disk::DiskError;
use crate::disk... |
pub mod http;
pub mod models;
pub mod dao;
pub mod test;
pub mod data;
pub mod additional_service;
pub mod sql_mapper;
pub mod service;
|
/// Assume two values are not equal.
///
/// * When true, return `Ok(true)`.
///
/// * When false, return [`Err`] with a message and the values of the
/// expressions with their debug representations.
///
/// # Example
///
/// ```rust
/// # #[macro_use] extern crate assertable; fn main() {
/// let x = assume_ne!(1, 2... |
fn main() {
{
let xx = String::from("hello hdl!");
let word = first_word(&xx);
println!("{:?}", word);
println!("{:?}", xx);
}
}
// String slice 的类型写法是 &str
fn first_word(ss: &String) -> &str {
let bytes = ss.as_bytes();
for (ii, &item) in bytes.iter().enumerate() {
... |
use super::*;
use std::collections::VecDeque;
use std::sync::{Arc, RwLock};
/// Represents a node in network.
pub struct Node<I: Input, S: Storage<Item = I>> {
/// A weight vector.
pub weights: Vec<f64>,
/// An error of the neuron.
pub error: f64,
/// Tracks amount of times node is selected as BU.
... |
pub mod errors;
pub mod imp;
pub mod decode_pixel;
pub mod encode_pixel; |
pub fn run() {
hello_world(&5);
let status = is_fadil("Fadil");
println!("{}", status);
// ? Closure
let add_nums = |n1: i32, n2: i32| n1 + n2;
println!("C Sum: {}", add_nums(7, 8));
}
fn hello_world(n: &i32) {
for i in 1..*n {
println!("Hello world on index {}", i);
}
prin... |
use super::{comparison_operator::ComparisonOperator, expression::Expression};
use std::sync::Arc;
#[derive(Clone, Debug, PartialEq)]
pub struct ComparisonOperation {
operator: ComparisonOperator,
lhs: Arc<Expression>,
rhs: Arc<Expression>,
}
impl ComparisonOperation {
pub fn new(
operator: Com... |
use std::path::Path;
use std::fs::File;
use std::io::{BufRead, BufReader};
use super::triangle::Triangle;
use super::point::Point;
pub struct MDL {
pub triangles: Vec<Triangle>,
pub points: Vec<Point>,
}
impl MDL {
pub fn open (file_path: &str) -> MDL {
let location = Path::new(file_path);
let file = F... |
use std::path::{Path, PathBuf};
// https://stackoverflow.com/questions/54267608/expand-tilde-in-rust-path-idiomatically
pub fn expand_home<P: AsRef<Path>>(path_user_input: P) -> Option<PathBuf> {
let p = path_user_input.as_ref();
if !p.starts_with("~") {
return Some(p.to_path_buf());
}
if p == ... |
use super::con_back::Command;
use super::*;
use conrod_core as cc;
use gfx_hal::{
command::CommandBuffer,
pso::{Primitive, VertexInputRate},
};
pub struct UiPipeline<B: Backend> {
device: Arc<Dev<B>>,
pub layouts: ManuallyDrop<<B as Backend>::PipelineLayout>,
pub gfx_pipeline: ManuallyDrop<<B as Ba... |
extern crate serde;
#[macro_use]
extern crate serde_derive;
extern crate rmp_serde as rmps;
use serde::{Deserialize, Serialize};
use chrono::{DateTime, Utc};
#[derive(Debug, PartialEq, Deserialize, Serialize)]
enum LogLevel {
Debug,
Info,
Warning,
Error,
Fatal,
}
#[derive(Debug, PartialEq, Deseri... |
use crate::*;
pub fn init_process(globals: &mut Globals) -> Value {
let id = globals.get_ident_id("Process");
let class = ClassRef::from(id, globals.builtins.object);
let mut obj = Value::class(globals, class);
globals.add_builtin_class_method(obj, "clock_gettime", clock_gettime);
let id = globals.... |
#[derive(Debug, PartialEq, Eq, Clone)]
/// An identifier
pub struct Ident<T>(T);
impl<T> AsRef<str> for Ident<T>
where
T: AsRef<str>,
{
fn as_ref(&self) -> &str {
self.0.as_ref()
}
}
impl<T> PartialEq<str> for &Ident<T>
where
T: AsRef<str>,
{
fn eq(&self, other: &str) -> bool {
sel... |
#[macro_use] extern crate itertools;
mod point;
use self::point::Point;
use std::f64::consts::PI;
use std::cmp;
extern crate rayon;
use self::rayon::prelude::*;
mod color;
pub trait Turtle {
fn forward(&mut self, d: f64);
fn turn(&mut self, a: f64);
fn push(&mut self);
fn pop(&mut self);
fn t... |
#[doc = "Register `C2CR` reader"]
pub type R = crate::R<C2CR_SPEC>;
#[doc = "Register `C2CR` writer"]
pub type W = crate::W<C2CR_SPEC>;
#[doc = "Field `PG` reader - Programming"]
pub type PG_R = crate::BitReader<PG_A>;
#[doc = "Programming\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PG_... |
extern crate sdl2;
extern crate num;
use std::collections::vec_deque::VecDeque;
use super::scancodes::*;
use super::super::cpu::CPU;
use super::super::mem::Memory;
use super::super::bios::ByteBdaEntry;
#[derive(Clone,Copy)]
pub struct Keystroke
{
pub scancode: u8,
pub ascii: u8
}
const RSHIFT_FLAG: u8 = 0x1;
cons... |
fn main() {
let mut v : Vec<f64> = vec![1.1, 1.15, 5.5, 1.123, 2.0];
v.sort_by(|a, b| a.partial_cmp(b).unwrap());
println!("{:?}", v);
} |
use serde::{Deserialize, Serialize};
use super::category_taxonomy;
#[derive(Serialize, Deserialize, Debug, PartialEq)]
pub struct Producer {
id: Option<String>,
name: Option<String>,
domain: Option<String>,
cat: Option<String>,
cattax: Option<category_taxonomy::CategoryTaxonomy>,
ext: Option<P... |
// q0056_merge_intervals
struct Solution;
impl Solution {
pub fn merge(intervals: Vec<Vec<i32>>) -> Vec<Vec<i32>> {
if intervals.len() <= 1 {
return intervals;
}
let mut intervals = intervals;
Solution::sort(&mut intervals);
// println!("after soring: {:?}", int... |
use glam::DAffine2;
use glam::DMat2;
use glam::DVec2;
use kurbo::Affine;
use kurbo::Shape as KurboShape;
use crate::intersection::intersect_quad_bez_path;
use crate::LayerId;
use crate::Quad;
use kurbo::BezPath;
use super::style;
use super::style::PathStyle;
use super::LayerData;
use serde::{Deserialize, Serialize}... |
use super::engine::ActionError;
use crate::cards::{BasicCard, BasicDeck, Suit};
use std::cmp::Ordering;
use std::slice;
#[derive(Debug)]
pub struct GameState {
/// current deck
pub deck: BasicDeck,
/// hands for each player
pub hands: [Vec<BasicCard>; 2],
/// score for each player
pub score: ... |
//! This module provides main application class.
mod events;
mod rustzx;
mod settings;
mod sound;
pub(crate) mod video;
// main re-export
pub use self::{rustzx::RustzxApp, settings::Settings};
|
use crate::config::template::config_template;
use config::NymConfig;
use serde::{Deserialize, Deserializer, Serialize};
use std::path::PathBuf;
use std::time;
pub mod persistence;
mod template;
// 'CLIENT'
const DEFAULT_LISTENING_PORT: u16 = 9001;
// 'DEBUG'
// where applicable, the below are defined in milliseconds... |
use std::collections::HashSet;
pub fn anagrams_for<'a>(word: &str, possible_anagrams: &[&str]) -> HashSet<&'a str> {
// Get all letters in word
let mut found_word_buffer: Vec<char> = Vec::new();
let mut found_anagrams: Vec<&str> = Vec::new();
let mut anagrams_hs: HashSet<&'a str> = HashSet::new();
... |
use std::fs;
use std::io;
const WIDTH: usize = 25;
const HEIGHT: usize = 6;
fn main() -> io::Result<()> {
let input = fs::read_to_string("input.txt")?;
let mut input = input.trim().chars().peekable();
let mut layers = Vec::new();
while input.peek().is_some() {
let mut layer: [[char; HEIGHT]; WIDTH] = [['... |
use crate::lexer::parser::*;
pub fn get_lexer_rules() -> LexerOptions {
LexerOptions {
operators: LexerOperators {
arithmetic: vec![
"+".to_string(),
"-".to_string(),
"*".to_string(),
"/".to_string(),
"%".... |
use std::io::{stdin, Read, StdinLock};
use std::str::FromStr;
#[allow(dead_code)]
struct Scanner<'a> {
cin: StdinLock<'a>,
}
#[allow(dead_code)]
impl<'a> Scanner<'a> {
fn new(cin: StdinLock<'a>) -> Scanner<'a> {
Scanner { cin: cin }
}
fn read<T: FromStr>(&mut self) -> Option<T> {
let t... |
#[derive(Debug, Deserialize)]
pub struct Error {
pub ok: bool,
pub error: Option<String>,
}
#[derive(Deserialize, Serialize)]
pub struct Cursor(String); // TODO: Type safety goes here
#[derive(Deserialize)]
pub struct Paging {
pub count: Option<u32>,
pub page: Option<u32>,
pub pages: Option<u32>,
... |
use cancellation::CancellationToken;
use crossbeam::channel::Sender;
use std::sync::Arc;
pub struct HashProgress {
pub bytes_processed: u64,
}
pub trait BlockHasher {
fn read(&mut self) -> usize;
fn update(&mut self, byte_count: usize);
fn digest(&mut self) -> String;
fn set_bytes_processed_event_... |
use crate::random_txn;
use actix::Addr;
use criterion::{BatchSize, Bencher};
use parking_lot::RwLock;
use rand::prelude::*;
use rand::{RngCore, SeedableRng};
use starcoin_bus::BusActor;
use starcoin_chain::{BlockChain, ChainServiceImpl};
use starcoin_config::NodeConfig;
use starcoin_consensus::dummy::DummyConsensus;
us... |
use super::*;
#[test]
fn test_snake_size() {
let cases = [
(vec![1, 1, 1, 1, 1, 1, 1], 2),
(vec![2, 1, 1, 2, 1, 2, 1, 1, 2, 2, 1, 1, 1, 2, 2, 2, 2], 3),
];
for (snake, expected_size) in cases.iter() {
assert_eq!(*expected_size, snake_size(snake));
}
}
#[test]
#[should_panic]
fn... |
/*
* 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
*/
/// Dashboard : A dashboard is Datadog’s tool for visually tracking, analyzing, and displaying key perfo... |
fn main() {
println!("{0}, Thgis is {1}. {1}, this is {0}", "Alice", "Bob"); // Alice, Thgis is Bob. Bob, this is Alice
println!("{subject} {verb} {object}",
object="the lazy dog",
subject="the quick brown fox",
verb="jump over"); // the quick brown fox jump over the lazy do... |
use anyhow::{Context, Result};
use dialoguer::{theme::ColorfulTheme, FuzzySelect};
use crate::config::read_config;
use crate::note::{DbNote, NoteData};
use crate::db::{init_schema, select_notes_for_review};
pub enum ReviewResult {
Easy, Hard, Again
}
fn get_review_result() -> Result<Option<ReviewResult>> {
l... |
use std::{error, fmt};
use crate::serde::SerializerError;
#[derive(Debug)]
pub enum Error {
SchemaDiffer,
SchemaMissing,
WordIndexMissing,
MissingDocumentId,
RocksdbError(rocksdb::Error),
FstError(fst::Error),
BincodeError(bincode::Error),
SerializerError(SerializerError),
}
impl From<... |
pub fn generate_parenthesis(n: i32) -> Vec<String> {
let v1 = vec!["()".to_string()];
let v2 = vec!["()()".to_string(), "(())".to_string()];
match n {
0 => vec!["".to_string()],
1 => v1,
2 => v2,
_ => {
let mut comb = Vec::<Vec<String>>::new();
comb.pu... |
use tantivy::tokenizer::LowerCaser;
#[derive(Clone)]
pub struct LowerCaseFilterFactory {}
impl LowerCaseFilterFactory {
pub fn new() -> Self {
LowerCaseFilterFactory {}
}
pub fn create(self) -> LowerCaser {
LowerCaser {}
}
}
#[cfg(test)]
mod tests {
use tantivy::tokenizer::{Simpl... |
#[doc = "Reader of register CH_CTL"]
pub type R = crate::R<u32, super::CH_CTL>;
#[doc = "Writer for register CH_CTL"]
pub type W = crate::W<u32, super::CH_CTL>;
#[doc = "Register CH_CTL `reset()`'s with value 0x02"]
impl crate::ResetValue for super::CH_CTL {
type Type = u32;
#[inline(always)]
fn reset_value... |
pub mod cpu;
pub mod opcodes;
pub mod rand;
|
use std::path::PathBuf;
pub trait Archive {
fn get_path(&self) -> PathBuf;
}
|
use std::fs::File;
use std::io::BufReader;
use std::io::BufRead;
const INPUT_DIR: &str = "inputs/";
pub fn load_input(name: &str) -> Vec<String> {
let path = format!("{}{}.txt", INPUT_DIR, name);
debug!("Opening path: {}", path);
let file = File::open(path).unwrap();
let mut file = BufReader::new(&fi... |
use mockall::*;
use ssz_types::BitList;
use types::{
beacon_state::BeaconState,
config::Config,
helper_functions_types::Error,
primitives::*,
types::{Attestation, AttestationData, IndexedAttestation},
};
// ok
pub fn get_current_epoch<C: Config>(_state: &BeaconState<C>) -> Epoch {
23
}
// ok
p... |
use std::io;
#[derive(PartialEq, Clone, Debug)]
struct House {
x: i32,
y: i32,
}
fn get_line() -> String {
let mut input = String::new();
let stdin = io::stdin();
stdin.read_line(&mut input).unwrap();
input
}
fn main() {
let input = get_line();
let mut houses: Vec<House> = Vec::new();
... |
use bevy::prelude::*;
fn main() {
App::build()
.add_plugins(DefaultPlugins)
.insert_resource(WindowDescriptor {
title: "Untitled Space Sim!".to_string(),
width: 600.0,
height: 600.0,
..Default::default()
})
.insert_resource(ClearColor(... |
use super::canvas::Canvas;
/// This trait allows an object to be drawn on a canvas like this:
///
/// ```ignore
/// canvas.draw(&object);
/// ```
///
/// If you are experienced with [html5 canvas element](https://www.html5canvastutorials.com/) you can get the
/// [WebSys canvas object](https://docs.rs/web-sys/0.3.35... |
use std::collections::HashSet;
use stringreader::StringReader;
use uvm_core::unity::v2::Manifest;
use uvm_core::unity::{Component};
use uvm_install_graph::{InstallGraph, InstallStatus, Walker};
mod fixures;
use itertools::Itertools;
#[test]
fn create_graph_from_manifest() {
let ini = fixures::UNITY_2019_INI;
l... |
// This modules returns an appropirate color_map for a configuration
// Currently only the num_states is taken into account
static BASE_COLORMAP: [u8; 18] = [
0xB2, 0x1F, 0x35,
0xFF, 0x74, 0x35,
0xFF, 0xF7, 0x35,
0x16, 0xDD, 0x36,
0x00, 0x79, 0xE7,
0xBD, 0x7A, 0xF6,
];
pub fn get_colormap... |
pub mod server;
pub use server::start_ntp_server;
|
/*
same structures as in transpiler grammar, but identifiers are stored as (u8,u8,u8) colors,
transformed into usize for simplicity
*/
#[derive(Debug)]
pub enum Stmt {
Define(usize),
Assign(usize, Box<Expr>),
PrintStmt(Box<Expr>)
}
#[derive(Debug)]
pub enum Expr {
Number(i64),
Variable(usize),
... |
use crate::*;
use std::rc::Rc;
use std::cell::RefCell;
use shoji::*;
// a button that user can click
// contains a label in the middle
// TODO
// how to do a callback / even when the button is clicked/released/enter/leave
// FUTURE
// image button
// link button
// toggle button
// switch
// checkbox
// radio
pub s... |
#[derive(Debug)]
#[repr(packed)] // repr(C) would add unwanted padding before first_section
pub struct BootLoaderNameTag {
typ: u32,
size: u32,
string: u8,
}
impl BootLoaderNameTag {
pub fn name(&self) -> &str {
unsafe { ::core::str::from_utf8_unchecked(::core::slice::from_raw_parts((&self.str... |
fn div_by_three(num: usize) -> bool {
num % 3 == 0
}
fn div_by_five(num: usize) -> bool {
num % 5 == 0
}
fn div_by_fifteen(num: usize) -> bool {
div_by_three(num) && div_by_five(num)
}
fn main() {
for num in (1..101) {
println!("{}",
if div_by_fifteen(num) { "FizzBuzz" }
... |
use std::fs;
use std::io;
use rand::prelude::*;
#[allow(non_snake_case)]
#[derive(Debug)]
struct Registers {
V0: u8, V1: u8, V2: u8, V3: u8, V4: u8, V5: u8, V6: u8, V7: u8,
V8: u8, V9: u8, VA: u8, VB: u8, VC: u8, VD: u8, VE: u8, VF: u8,
I: u16, PC: u16,
}
impl Registers {
fn new() -> Registers {
... |
#[macro_use]
extern crate cfg_if;
extern crate failure;
extern crate libc;
extern crate object;
extern crate uuid;
#[cfg(target_os="macos")]
#[macro_use]
extern crate core_foundation;
#[cfg(target_os="macos")]
extern crate core_foundation_sys;
use failure::Error;
use object::{File, Object};
use std::fmt::Write;
use s... |
fn main() {
// loop
loop {
println!("loop forever!");
break;
}
// while
let mut x: i32 = 5;
let mut done: bool = false;
while !done {
x += x - 3;
println!("{}",x);
if x % 5 == 0 {
done = true;
}
}
// for
for x ... |
/*!
```rudra-poc
[target]
crate = "atomic-option"
version = "0.1.2"
[[target.peer]]
crate = "crossbeam-utils"
version = "0.8.0"
[report]
issue_url = "https://github.com/reem/rust-atomic-option/issues/4"
issue_date = 2020-10-31
rustsec_url = "https://github.com/RustSec/advisory-db/pull/588"
rustsec_id = "RUSTSEC-2020-... |
use crate::{
cost_model::transferred_byte_cycles,
syscalls::{
utils::store_data, Source, SourceEntry, INDEX_OUT_OF_BOUND, LOAD_WITNESS_SYSCALL_NUMBER,
SUCCESS,
},
};
use ckb_types::packed::{Bytes, BytesVec};
use ckb_vm::{
registers::{A0, A3, A4, A7},
Error as VMError, Register, Suppo... |
#![doc = "generated by AutoRust 0.1.0"]
#![allow(non_camel_case_types)]
#![allow(unused_imports)]
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ErrorDetails {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub code: Option<String>,
#[s... |
use std::collections::BTreeMap;
use chrono::{Local, TimeZone};
use regex::Regex;
use serde::Serialize;
#[derive(Debug, Serialize)]
struct Episode {
show_id: String,
description: String,
// I believe this is autoincremented if none
#[serde(skip_serializing_if = "Option::is_none")]
number: Option<St... |
use anyhow::Result;
use rustimate_core::messages::req::RequestMessage;
use wasm_bindgen::prelude::{Closure, JsValue};
use wasm_bindgen::JsCast;
use web_sys::{ErrorEvent, MessageEvent, WebSocket};
#[derive(Clone, Debug)]
pub(crate) struct ClientSocket {
url: String,
binary: bool,
pub(crate) ws: WebSocket
}
impl ... |
use lex::Token;
use std::iter::Peekable;
use std::slice::Iter;
type Tokens<'a> = Peekable<Iter<'a, Token>>;
#[derive(Debug, PartialEq)]
pub enum Object {
Empty,
Nonempty(Box<Members>),
}
#[derive(Debug, PartialEq)]
pub enum Members {
Pair(String, Value),
Pairs(String, Value, Box<Members>),
}
#[deriv... |
extern crate rmp_serde;
extern crate serde;
#[macro_use]
extern crate serde_derive;
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
struct A {
b: B,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(tag = "kind", content = "data")]
#[serde(rename_all = "snake_case")]
pub enum B {
... |
use std::collections::BTreeMap;
use std::process::Stdio;
use k8s_openapi::api::core::v1::Secret;
use kube::api::ObjectMeta;
use oauth2::prelude::*;
use oauth2::AccessToken;
use serde_derive::{Deserialize, Serialize};
use serde_json::{json, Value};
use tokio::prelude::*;
use tokio::process::Command;
use crate::Targets... |
use aoc20::days::day14;
#[test]
fn day14_parse_mask() {
let m = day14::Mask::parse("mask = XXXXXXXXXXXXXXXXXXXXXXXXXXXXX1XXXX0X").unwrap();
assert_eq!(m, day14::Mask::new(0x40, 0xF_FFFF_FFBD));
}
#[test]
fn day14_parse_mem() {
let m = day14::Mem::parse("mem[36932] = 186083").unwrap();
assert_eq!(m, da... |
use std::fs;
use std::io::{self, Write};
use aspotify::{Client, ClientCredentials, Scope};
#[tokio::main]
async fn main() {
// Read .env file into environment variables.
dotenv::dotenv().unwrap();
// Create the Spotify client from the credentials in the env variables.
let client = Client::new(ClientC... |
use consts;
use hidapi::{HidResult, HidApi, HidDevice};
pub struct LuxaforDeviceDescriptor {
pub vendor_id : u16,
pub product_id : u16
}
pub struct LuxaforContext {
hid_api : HidApi
}
pub struct LuxaforDevice<'a> {
hid_device : HidDevice<'a>
}
impl LuxaforContext {
pub fn new() -> HidResult<Lux... |
use lexer::{Input, State, Reader};
use super::super::token::{Token, TokenKind};
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub struct OperatorsReader;
impl Reader<TokenKind> for OperatorsReader {
#[inline(always)]
fn priority(&self) -> usize { 3usize }
fn read(&self, input: &Input, state: &mut State... |
#[cfg(feature = "textfield")]
mod textfield;
#[cfg(feature = "textfield")]
pub use textfield::*;
#[cfg(any(feature = "textfield", feature = "textarea"))]
pub(crate) mod validity_state;
#[cfg(any(feature = "textfield", feature = "textarea"))]
pub use validity_state::ValidityState;
#[cfg(any(feature = "textfield", feat... |
use std::collections::{HashMap, HashSet};
use std::sync::{Arc, RwLock};
use std::sync::mpsc::Sender;
use std::fs;
use std::thread;
use super::{Error, Event, op, Watcher};
use std::path::{Path, PathBuf};
use std::time::Duration;
use self::walkdir::WalkDir;
use filetime::FileTime;
extern crate walkdir;
pub struct Poll... |
use crate::util::prelude::*;
use crate::state::prelude::*;
use crate::gfx;
use crate::gfx::glyph_gfx::*;
use std::collections::{HashMap, HashSet};
#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
pub enum RenderModifier {
GravityInverse,
}
struct CachedRegion {
tick: Tick,
region: GfxRegion
}
pub stru... |
fn main() {
//let target = "world";
let mut target = "world";
let mut greeting = "Hello";
println!("{}, {}", greeting, target);
greeting = "How's it goin'";
target = "mate";
println!("{}, {}", greeting, target);
}
|
use regex::Regex;
fn main() {
let input = include_str!("../data/2015-06.txt");
println!("Part 1: {}", part1(input));
println!("Part 2: {}", part2(input));
}
fn part1(input: &str) -> u32 {
let adjust = |act: &str, light: &mut u16| {
match act {
"turn on" => *light = 1,
"... |
use crate::{KvsError, Result};
use serde::{Deserialize, Serialize};
use serde_json;
use std::collections::HashMap;
use std::fs::{self, OpenOptions};
use std::io::{BufWriter, Write};
use std::io::{BufReader, Read};
use std::io::{Seek, SeekFrom};
use std::path::PathBuf;
const MAX_UNCOMPACTED_SIZE: u64 = 1024 * 1024;
#[... |
#![allow(non_upper_case_globals)]
mod bigger;
mod hint;
mod rankings;
mod skip;
mod stop;
mod tags;
use std::sync::Arc;
use bitflags::bitflags;
use dashmap::mapref::entry::Entry;
use eyre::Report;
use rosu_v2::prelude::GameMode;
use twilight_model::{
application::{
command::CommandOptionChoice,
c... |
#[doc = "Register `AHBSMENR` reader"]
pub type R = crate::R<AHBSMENR_SPEC>;
#[doc = "Register `AHBSMENR` writer"]
pub type W = crate::W<AHBSMENR_SPEC>;
#[doc = "Field `DMASMEN` reader - DMA clock enable during sleep mode bit"]
pub type DMASMEN_R = crate::BitReader<DMASMEN_A>;
#[doc = "DMA clock enable during sleep mode... |
use serde::{Serialize, Deserialize};
#[derive(Debug, Serialize)]
pub struct ViewerServerMsg {
pub msg_type: ViewerServerType,
}
#[derive(Debug, Serialize)]
pub enum ViewerServerType {
Info(Info),
GameEnded,
GameOpened,
GameClosed,
TurnAdvanced,
NewOffsets(Offsets),
NewScores(Vec<(String, f64)>),
NewParticipa... |
fn foo() {
let a = "hello
world";
let b = "hello\
world";
let c = r#"
hello
world
"#;
}
|
use ring;
use std::io::Write;
use crate::msgs::codec;
use crate::msgs::codec::Codec;
use crate::msgs::enums::{ContentType, ProtocolVersion};
use crate::msgs::message::{BorrowMessage, Message, MessagePayload};
use crate::msgs::fragmenter::MAX_FRAGMENT_LEN;
use crate::error::TLSError;
use crate::session::SessionSecrets;
... |
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
use core::fmt;
use core::marker::PhantomData;
use core::ptr::NonNull;
// Only used for `IoSlice`. T... |
use std::io;
use std::str::FromStr;
use crate::base::Part;
pub fn part1(r: &mut dyn io::Read) -> Result<String, String> {
solve(r, Part::One)
}
pub fn part2(r: &mut dyn io::Read) -> Result<String, String> {
solve(r, Part::Two)
}
fn solve(r: &mut dyn io::Read, part: Part) -> Result<String, String> {
let ... |
use chrono::{DateTime, Utc};
use serde::{Serialize, Deserialize};
#[derive(Serialize, Deserialize, Debug)]
pub enum ContractEvent {
Requested {
id: String,
publication_id: String,
author_id: String,
timestamp: DateTime<Utc>,
},
Approved {
id: String,
publicat... |
mod fs;
mod ws;
pub mod service;
pub mod client;
use client::Client;
use fs::FsConnection;
use log::{debug, error, warn};
use serde::Serialize;
use std::{
collections::HashMap,
net::SocketAddr,
sync::Arc,
};
use tokio::sync::RwLock;
use uuid::Uuid;
use warp::ws::{Message, WebSocket};
pub use fs::FsError;
... |
mod secret_number;
fn main() {
}
|
#![doc = "generated by AutoRust 0.1.0"]
#![allow(non_camel_case_types)]
#![allow(unused_imports)]
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct PrivateAtlas {
#[serde(flatten)]
pub tracked_resource: TrackedResource,
#[serde(default, skip_serializi... |
use serde;
use serde_json;
use std::env;
use friday_error::frierr;
use friday_error::propagate;
use friday_error::FridayError;
use std::path::PathBuf;
use std::fs;
pub fn get_config_directory() -> Result<PathBuf, FridayError> {
return env::var("FRIDAY_CONFIG").map_or_else(
|_| frierr!("The environment vari... |
extern crate serde_yaml;
use from_file::FromFile;
#[derive(Serialize, Deserialize, Debug)]
pub struct BundleConfig {
pub bundles: Vec<ConfigItem>,
pub module_blacklist: Option<Vec<String>>,
}
impl Default for BundleConfig {
fn default() -> BundleConfig {
BundleConfig {
bundles: vec![]... |
use core::MatrixArray;
use core::dimension::{U1, U4};
use geometry::{QuaternionBase, UnitQuaternionBase};
/// A statically-allocated quaternion.
pub type Quaternion<N> = QuaternionBase<N, MatrixArray<N, U4, U1>>;
/// A statically-allocated unit quaternion.
pub type UnitQuaternion<N> = UnitQuaternionBase<N, MatrixArr... |
use schema::horus_users;
#[derive(Queryable, Identifiable, Associations, Insertable, Serialize, Deserialize)]
#[table_name = "horus_users"]
pub struct User
{
pub id: i32,
pub first_name: String,
pub last_name: Option<String>,
pub email: String,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct Pub... |
struct A; //concrete type A
struct S(A); //concrete type S
struct SGEN<T>(T); //generic type SGEN
fn reg_fn(_s: S) {}
fn gen_spec_t(_s: SGEN<A>) {}
fn gen_spec_i32(_s: SGEN<i32>) {}
fn generic<T>(_s: SGEN<T>) {}
pub fn gen_fn() {
reg_fn(S(A)); //传入S结构体,成员为A
gen_spec_t(SGEN(A));
gen_spec... |
#[doc = "Reader of register CMD_RESP_STATUS"]
pub type R = crate::R<u32, super::CMD_RESP_STATUS>;
#[doc = "Reader of field `CURR_RD_ADDR`"]
pub type CURR_RD_ADDR_R = crate::R<u16, u16>;
#[doc = "Reader of field `CURR_WR_ADDR`"]
pub type CURR_WR_ADDR_R = crate::R<u16, u16>;
#[doc = "Reader of field `CMD_RESP_EC_BUS_BUSY... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.