text stringlengths 8 4.13M |
|---|
/*
* 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.
*/
//! This crate provides the protocol that is to be used when communicating with
//! global state. T... |
use super::super::error::Result;
use super::super::traits::AsyncBufRead;
use core::pin::Pin;
use futures::future::Future;
use futures::ready;
use futures::task::{Context, Poll};
pub struct ReadBuf<'a, R: ?Sized> {
reader: Option<&'a mut R>,
}
impl<R: ?Sized + Unpin> Unpin for ReadBuf<'_, R> {}
impl<'a, R: Async... |
// Copyright (C) 2018-2021 Parity Technologies (UK) Ltd.
// Copyright (C) 2021 Subspace Labs, Inc.
// 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
//
... |
//! Handles interactions with the current page table.
use super::inactive_page_table::InactivePageTable;
use super::page_table::{Level1, Level4, PageTable};
use super::page_table_entry::*;
use super::page_table_manager::PageTableManager;
use super::{Page, PageFrame};
use core::cell::UnsafeCell;
use core::ops::{Deref, ... |
//! Runtime implementations.
pub mod tokio;
pub mod tokio_global;
|
use std::cmp;
use std::iter::{FromIterator, Sum};
use std::mem;
use std::ops::{Add, Sub, Mul, MulAssign, Div, Neg, Deref, DerefMut, Index, IndexMut};
use std::ptr;
use void::Void;
use iter_exact::{CollectExactExt, FromExactSizeIterator};
use linalg::matrix::*;
use linalg::traits::*;
use num::traits::*;
use typehack::... |
use a653rs::prelude::PartitionExt;
use a653rs_macros::partition;
mod deps;
fn main() {
hello::Partition.run();
}
#[partition(crate::deps::dummy::DummyHypervisor)]
mod hello {
#[sampling_out(name = "Ch1", msg_size = "10KB")]
struct Channel1;
#[sampling_in(refresh_period = "500ms")]
#[sampling_in(... |
mod rectangle; // Additional tests here
pub fn add_two(a: i32) -> i32 {
a + 2
}
pub fn greeting(name: &str) -> String {
format!("Hello {}!", name)
}
pub fn this_will_panic() {
panic!("AHHHHH!");
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_adds_two() {
assert_eq!(4, add_tw... |
use crate::rtb_type_strict;
rtb_type_strict! {
Display,
Html = 1;
AmpHtml = 2;
StructuredImageObject = 3;
StructuredNativeObject = 4
}
rtb_type_strict! {
Video,
Vast1 = 1;
Vast2 = 2;
Vast3 = 3;
Vast1Wrapper = 4;
Vast2Wrapper = 5;
Vast3Wrapper = 6;
Vast4 = 7;
Vast4wraperr =8;
Daast1 = 9;
Dasast1Wrapper = 10;
Vast4_1=1... |
use model;
use filehandler;
use util;
use std::collections::HashSet;
//
// This generate Method is the entry point to generation
// of html documentation about the given types
//
pub fn generate(tree:model::ParserResult, folder:&str) {
for ifa in tree.interfaces.iter() {
let result = gen_interface(ifa, tree.t... |
use crate::relayer::error::{Error, Misbehavior};
use ckb_types::{core, packed};
pub struct BlockUnclesVerifier {}
impl BlockUnclesVerifier {
pub(crate) fn verify(
block: &packed::CompactBlock,
indexes: &[u32],
uncles: &[core::UncleBlockView],
) -> Result<(), Error> {
let expect... |
pub mod password;
pub mod user;
|
use std::rc::Rc;
macro_rules! as_f32a {
[$($v:expr),*$(,)?] => {
[$(($v) as f32,)*]
};
}
macro_rules! as_f64a {
[$($v:expr),*$(,)?] => {
[$(($v) as f64,)*]
};
}
mod framebuffer;
mod libs;
mod mesh;
mod assist;
pub mod new;
pub mod render;
pub mod util;
use libs::*;
use id_table::Id... |
//! Image type.
use crate::geometry::Size;
#[cfg(feature = "image")]
use image::{DynamicImage, ImageBuffer, ImageResult, Luma, LumaA, Primitive, Rgb, Rgba};
use std::fmt;
use std::path::Path;
/// An image to be used for drawing operations.
#[derive(Debug, Clone, PartialEq)]
pub struct Image {
data: Option<ImageDat... |
use near_sdk::json_types::{U128, U64};
use near_sdk::{AccountId};
use near_sdk::serde_json::json;
use near_sdk::serde_json;
use near_sdk_sim::{call, transaction::ExecutionStatus, view, DEFAULT_GAS, UserAccount};
use chrono::{TimeZone, Utc};
// use utils::{init as init, register_user};
use crate::utils::{
init, pt... |
// #![allow(dead_code)]
use crate::graphics::{CurrentFrame, GraphicsState};
use crate::vertex::Vertex;
use rand::Rng;
pub struct RendererSimpleTriangle {
pipeline: wgpu::RenderPipeline,
buffer: wgpu::Buffer,
}
impl RendererSimpleTriangle {
pub(crate) fn new(graphics_state: &mut GraphicsState) -> Self {
... |
use crate::prelude::*;
use rdisk_shared::AsByteSlice;
pub(crate) fn calc_header_bytes_checksum<H: AsByteSlice>(header: &H) -> u32 {
let mut new_checksum = 0_u32;
for b in unsafe { header.as_byte_slice() } {
new_checksum += *b as u32;
}
!new_checksum
}
macro_rules! calc_header_checksum {
(... |
use crate::parser::Parser;
use std::cell::RefCell;
use std::io::{Read, Seek};
use std::ops::Index;
// glm aliases
pub type Mat4 = glm::Mat4x4;
pub type Vec2 = glm::Vec2;
pub type Vec3 = glm::Vec3;
pub type Vec4 = glm::Vec4;
// helpers
pub fn matmul(m: &Mat4, v: &Vec3) -> Vec3 {
(m * Vec4::new(v.x, v.y, v.z, 1.0))... |
use std::io::{stdin, stdout, Write};
use termion::cursor::Goto;
use termion::event::Key;
use termion::input::TermRead;
use termion::raw::IntoRawMode;
use crate::{
controllers::Mode,
models::{Coordinates, Game, Label},
views::LabelView,
};
pub fn endscreen_controller(game: &mut Game) {
let mut stdout =... |
use tui::buffer::Buffer;
use tui::layout::Rect;
use tui::widgets::{border, Widget, Block};
use tui::style::{Color, Modifier, Style};
use chrono::naive::date::NaiveDate;
use chrono::offset::local::Local;
use chrono::Datelike;
use std::sync::Arc;
use ::{DAY_NAMES, MONTH_NAMES, one_day};
use ::database::Database;
pub ... |
// Copyright (c) The Starcoin Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::impl_hash;
use crate::{
channel_transaction::ChannelTransaction, channel_transaction_sigs::ChannelTransactionSigs,
};
use anyhow::{ensure, Error, Result};
use libra_crypto::HashValue;
use libra_crypto_derive::CryptoH... |
use std::time::Duration;
use log::{info, warn};
use tokio::sync::RwLock;
use url::Url;
use crate::AciObject;
use crate::auth::ApicAuthenticator;
use crate::conn::{ApicCommError, ApicConnection, QuerySettings};
#[derive(Debug)]
struct ApicConnectionHolder<A: ApicAuthenticator + Clone> {
pub index: usize,
pub... |
#[derive(Debug, Clone, Eq, PartialEq, Fail)]
pub enum VObjectErrorKind {
#[fail(display = "Parser error: {}", _0)]
ParserError(String),
#[fail(display = "Not a Vcard")]
NotAVCard,
#[fail(display = "Not a Icalendar: {}", _0)]
NotAnICalendar(String),
#[cfg(feature = "timeconversions")]
... |
use rocket::data::{Data, ToByteUnit};
use serde::{Serialize, Deserialize};
use reqwest;
// Image file size limit set at ~4 MB, just below Azure Face API limit
const IMAGE_SIZE_LIMIT: usize = 4000000;
// Alright, alright let's get all of the boilerplate out of the way...
#[derive(Debug, Serialize, Deserialize)]
pub st... |
#[doc = "Register `D3PCR1L` reader"]
pub type R = crate::R<D3PCR1L_SPEC>;
#[doc = "Register `D3PCR1L` writer"]
pub type W = crate::W<D3PCR1L_SPEC>;
#[doc = "Field `PCS0` reader - D3 Pending request clear input signal selection on Event input x = truncate (n/2)"]
pub type PCS0_R = crate::FieldReader<PCS0_A>;
#[doc = "D3... |
fn add_sum(x: i32,y: i32) -> i32
{
println!("hello fucker");
x+y
}
fn main() {
let f=add_sum;
let d=add_sum(2,3);
f(2,3);
d;
println!("{}",f(3,4));
println!("{}",d);
}
|
use regex::Regex;
use std::collections::HashMap;
const INPUT: &str = include_str!("../input");
const PARSE_REGEX: &str = r"#(\d+) @ (\d+),(\d+): (\d+)x(\d+)";
fn main() {
let parsed_input = parse_input(INPUT);
println!("{}", count_overlapping_fabric_claim_units(&parsed_input));
println!("{}", find_fabric_... |
use async_lapin::LapinAsyncIoExt;
use lapin::ConnectionProperties;
// ConnectionProperties extension
pub trait LapinAsyncStdExt {
fn with_async_std(self) -> Self
where
Self: Sized,
{
self.with_async_std_executor().with_async_std_reactor()
}
fn with_async_std_executor(self) -> Self... |
use anyhow::{anyhow, Result};
use std::fs;
type TreeMap = Vec<Vec<bool>>;
fn parse_map(input: &str) -> Result<TreeMap> {
input.lines().map(|line| {
line.chars().map(|c| match c {
'#' => Ok(true),
'.' => Ok(false),
_ => Err(anyhow!("invalid character")),
}).coll... |
mod unpacker;
use anyhow::Context;
use clap::{AppSettings, ArgGroup, Clap};
use std::path::{Path, PathBuf};
use mila::BinArchive;
fn read_bin_archive_input(input_path: &Path) -> anyhow::Result<BinArchive> {
let input = std::fs::read(input_path).context("Failed to read input file.")?;
let input = if let Some(... |
pub(crate) trait CheckingStringCharacter {
fn is_dash(&self) -> bool;
fn is_comma(&self) -> bool;
fn is_space(&self) -> bool;
}
|
use quote::ToTokens;
use syn::parse_quote;
use syn::Expr;
use syn::ItemFn;
use syn::Stmt;
pub(crate) fn nop_stmt() -> Stmt {
let nop: ItemFn = parse_quote! {fn nop(){nop}};
return nop.block.stmts[0].clone();
}
pub(crate) fn else_stmt() -> Stmt {
let nop: ItemFn = parse_quote! {fn nop(){else_stmt}};
re... |
pub mod ast;
pub mod lexer;
pub mod msg;
pub mod parser;
pub mod reader;
pub mod token;
|
use super::ctx::Ctx;
pub mod animation;
pub trait Frame: Send {
fn frame(&mut self, timestamp: f64) -> bool;
}
lazy_static! {
static ref FRAME_OBJECTS: Ctx<Vec<Ctx<Frame>>> = Ctx::new(vec![]);
}
pub fn bind(fo: Ctx<Frame>) {
let mut frame_objects = FRAME_OBJECTS.get();
if frame_objects.len() == 0 {
... |
use std::error::Error;
use std::fs::File;
use std::io::Write;
use clap::{App, Arg};
use futures::stream::FuturesUnordered;
use indicatif::ProgressIterator;
use reqwest::Client;
use serde_json::Value;
// https://github.com/HackerNews/API
const API_URL: &str = "https://hacker-news.firebaseio.com/v0";
async fn get_item... |
//
// Field Access
// An example that demonstrates setting and retrieving values from public
// fields on objects.
//
extern crate rjni;
use std::path::PathBuf;
use std::env;
use rjni::{JavaVM, Version, Classpath, Options, Value, Type};
fn main() {
// Find the path to the manifest folder, then append the examp... |
// 给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。
// 有效字符串需满足:
// 左括号必须用相同类型的右括号闭合。
// 左括号必须以正确的顺序闭合。
// 注意空字符串可被认为是有效字符串。
// 示例 1:
// 输入: "()"
// 输出: true
// 示例 2:
// 输入: "()[]{}"
// 输出: true
// 示例 3:
// 输入: "(]"
// 输出: false
// 示例 4:
// 输入: "([)]"
// 输出: false
// 示例 5:
// 输入: "{[]}"
// 输出: true
struct Solut... |
use std::{collections::HashMap, sync::Arc};
use druid::{
BoxConstraints, Env, Event, EventCtx, LayoutCtx, LifeCycle, LifeCycleCtx,
PaintCtx, Size, Widget, WidgetId, WindowId,
};
use parking_lot::Mutex;
use crate::{
command::LapceUICommand,
command::LAPCE_UI_COMMAND,
explorer::FileExplorerState,
... |
use crate::{
grid::config::{ColoredConfig, Entity, Position, SpannedConfig},
grid::records::{ExactRecords, Records},
settings::CellOption,
};
use super::Offset;
/// [`BorderChar`] sets a char to a specific location on a horizontal line.
///
/// # Example
///
/// ```rust
/// use tabled::{Table, settings::{... |
//! `ur20-modbus` is a [Rust](https://rust-lang.org) library for communicating
//! with the Modbus TCP fieldbus coupler Weidmüller UR20-FBC-MOD-TCP.
//!
//! # Example:
//!```rust,no_run
//! use std::error::Error;
//! use ur20_modbus::Coupler;
//!
//! #[tokio::main]
//! async fn main() -> Result<(), Box<dyn Error>> {
//... |
use std::error::Error;
use crate::inst;
use std::collections::HashMap;
pub struct Prog<'a> {
pub name: &'a str,
lines: Vec<(usize, inst::InstLine<'a>)>,
symbol_map: HashMap<&'a str, usize>,
}
impl<'a> Prog<'a> {
pub fn new (name: &'a str, contents: &'a str) -> Result<Prog<'a>, Box<dyn Error>> {
... |
use pic8259_simple::ChainedPics;
use spin;
use lazy_static::lazy_static;
use x86_64::structures::idt::{ ExceptionStackFrame, InterruptDescriptorTable };
pub const PIC_1_OFFSET: u8 = 32;
pub const PIC_2_OFFSET: u8 = PIC_1_OFFSET + 8;
pub const TIMER_INTERRUPT_ID: u8 = PIC_1_OFFSET + 0;
pub const KEYBOARD_INTERRUPT_ID:... |
#![feature(extern_crate_item_prelude)]
#![feature(test)]
extern crate test;
extern crate wasm_bindgen;
use wasm_bindgen::prelude::*;
fn create_buffer(width: usize, height: usize) -> Vec<u8> {
let size = 4 * width * height;
let mut bytes = Vec::with_capacity(size);
bytes.resize(size, 0);
bytes
}
#[wa... |
use std::fmt;
/// The config reads the environment variables and saves the values to configure the server
#[derive(Debug, Clone)]
pub struct Config {
pub server_address: String,
pub db_address: String,
pub pool_limit: Option<u32>,
}
impl Config {
//TODO: impl optional arguments!
pub fn new() -> Se... |
use svc_authz::IntentObject;
#[derive(Clone)]
pub struct AuthzObject {
object: Vec<String>,
ban_key: Option<Vec<String>>,
}
impl AuthzObject {
pub fn new(obj: &[&str]) -> Self {
Self {
object: obj.iter().map(|s| s.to_string()).collect(),
ban_key: None,
}
}
... |
// Copyright (C) 2019-2021 Parity Technologies (UK) Ltd.
// Copyright (C) 2021 Subspace Labs, Inc.
// 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
//
... |
mod card;
mod command;
mod deck;
mod foundation;
mod game;
mod pile;
mod results;
mod stock;
mod tableau;
mod waste;
pub use results::Success;
pub use results::Failure;
const HELP_TEXT: &str =
"-----------------------------------------------------\n\
? . . . . .: Display Help\n\
r : Retire Current Gam... |
extern crate edocore;
use edocore::debug;
use edocore::{
math::{
vector::Vector3,
},
};
extern crate edorenderer;
use edorenderer::{
backend,
states::{
halstate::HalState,
types::{mesh::Mesh, image::Image, rendertext::RenderText},
pipelineconfig::PipelineConfig,
... |
use std::fmt;
use serde::de;
use crate::schema::Schema;
#[derive(Debug)]
pub struct Property {
name: String,
schema: Schema,
}
impl Property {
pub fn name(&self) -> &str {
&self.name
}
pub fn schema(&self) -> &Schema {
&self.schema
}
}
struct PropertyVisitor;
impl<'de> de:... |
#![no_std]
#![deny(unsafe_code)]
#![feature(proc_macro)]
extern crate cortex_m_semihosting;
extern crate stm32f103xx;
extern crate cortex_m_rtfm as rtfm;
use core::fmt::Write;
use cortex_m_semihosting::hio;
//use stm32f103xx::DWT;
use rtfm::{app, Threshold};
app! {
device: stm32f103xx,
// resources: {
... |
use async_graphql::http::{playground_source, GraphQLPlaygroundConfig};
use async_graphql::{EmptyMutation, EmptySubscription, Schema};
use async_std::task;
use starwars::{QueryRoot, StarWars};
use std::env;
use tide::{http::mime, Body, Response, StatusCode};
type Result<T> = std::result::Result<T, Box<dyn std::error::Er... |
use std::fs;
use std::path::Path;
use std::ops::{Index, IndexMut};
struct IntcodeProgram {
input: Vec<usize>,
memory: Vec<usize>,
instruction_pointer: usize,
}
impl IntcodeProgram {
fn new(input: &str) -> IntcodeProgram {
let input: Vec<usize> = input.split(',')
.map(|item| item.pa... |
use std::cell::RefCell;
use std::rc::Rc;
use crate::config::{Metronome as MetronomeConfig, MetronomeNote, MidiPort};
use crate::midi::{
bus::{BusAddress, BusNode, BusQuery, MidiBusLock, NodeClass, NodeFeature},
messages::Message,
};
use crate::song::transport::Transport;
use crate::time::{
ticks::TICKS_RESOLUTIO... |
use core::mem;
use std::ops::Deref;
use std::sync::Arc;
use smallvec::SmallVec;
use crate::BenchStr;
/// a hand-optimized version using things from std-lib; should have about the same performance
/// as `SStr` from `abin` (maybe even a bit better, since has less functionality; less overhead).
#[derive(Clone)]
pub en... |
use std::env;
use rocket::local::Client;
use rocket::http::{Status, ContentType};
use serde_json;
fn rocket_client() -> Client {
env::set_var("REPO_DIR", "./fixtures");
Client::new(super::configure_server()).unwrap()
}
#[test]
fn get_index_page() {
let client = rocket_client();
let mut resp = client... |
#[doc = "Register `CR3` reader"]
pub type R = crate::R<CR3_SPEC>;
#[doc = "Register `CR3` writer"]
pub type W = crate::W<CR3_SPEC>;
#[doc = "Field `EIE` reader - Error interrupt enable"]
pub type EIE_R = crate::BitReader;
#[doc = "Field `EIE` writer - Error interrupt enable"]
pub type EIE_W<'a, REG, const O: u8> = crat... |
use std::{
fmt::{self, Display, Formatter, Write},
ops::{Deref, DerefMut},
};
use crate::{
chunk::disassemble_instruction,
op::Opcode,
stack::Stack,
value::{
make_ptr, BoundMethod, Class, Closure, Function, Instance, NativeFn, NativeFnPtr, Object, Table, Upvalue, Value,
},
};
/*
TO... |
use core::num::NonZeroUsize;
use serde::Deserialize;
use necsim_core_bond::PositiveF64;
use crate::cache::DirectMappedCache;
mod reporter;
pub mod individuals;
pub mod landscape;
pub mod monolithic;
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct AbsoluteDedupCache {
pub capacity: NonZe... |
// Copyright 2017 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use std::fmt;
use std::io::{self, Read, Write};
use futures::{Async, Poll};
use mio::fuchsia::EventedHandle;
use zircon::{self, AsHandleRef};
use tokio_c... |
// A type can implement many different traits. What if two traits both
// require the same name? For example, many traits might have a method
// name `get()`. They might event have different return types!
//
// Good news: because each trait implementation gets its own `impl` block,
// it's clear which trait... |
use crate::prelude::*;
pub fn monster_ai_system(world: &mut World) {
match world.resource_clone::<RunState>() {
Ok(RunState::AiTurn) => {}
_ => return,
}
let mut attack_cmd_batch = Vec::new();
{
if let Some((player_entity, (_, player_pos, _player_name))) = world
.q... |
use crate::util::{Point, Size};
use std::{
fmt,
io::{self, Write},
};
pub mod event;
mod sys;
/// Defines the terminal width and height boundary. 255 cells.
pub type SIZE = u8;
#[cfg(not(debug_assertions))]
pub struct Terminal {
pub handle: io::Stdout,
pub size: Size,
}
#[cfg(debug_assertions)]
pub st... |
#![feature(trait_alias)]
// #![feature(unboxed_closures, fn_traits)]
#[macro_use]
extern crate clap;
extern crate num_cpus;
#[macro_use]
extern crate nom;
extern crate rust_decimal;
pub mod app;
|
// Copyright 2020 The VectorDB Authors.
//
// Code is licensed under Apache License, Version 2.0.
use super::*;
#[derive(Debug)]
pub struct FilterPlanner {
pub planners: MapPlanner,
}
impl FilterPlanner {
pub fn default() -> Self {
FilterPlanner {
planners: MapPlanner::new(),
}
... |
#![recursion_limit="1024"]
#[macro_use]
extern crate arrayfire as af;
#[macro_use]
extern crate clap;
#[macro_use]
extern crate slog;
extern crate slog_term;
extern crate time;
extern crate rand;
#[macro_use]
extern crate itertools;
#[macro_use]
extern crate nom;
mod ahelper;
mod tsp;
mod app;
mod ga;
use ahelper a... |
pub use util::mutate::Mutate;
pub mod mutate;
pub mod panic_handler;
|
#[macro_use]
extern crate askama;
use askama::Template;
mod base;
use base::*;
// remove `pub` and this compiles
#[derive(Template)]
#[template(path = "test.html")]
pub struct Test {
pub _parent: Base,
}
fn main() {
let t = Test {
_parent: Base {
henlo: Some("hi".into()),
},
};
println!("{}",... |
#[cfg(test)]
mod tests {
use lib::get_sum_numbers_combinations_quantity_for_amount;
#[test]
fn tests_get_sum_numbers_combinations_quantity_for_amount() {
let allowed_numbers: [u8; 3] = [1, 2, 3];
let amount: u32 = 5;
assert_eq!(
get_sum_numbers_combinations_quantity_f... |
pub fn solve_v1() -> i32 {
let data = super::load_file("day10.txt");
let mut jolts = data.lines().map(|c| c.parse::<u8>().unwrap()).collect::<Vec<u8>>();
jolts.sort();
let mut diff_1j = 0;
let mut diff_3j = 1; // for the device's built-adapter difference
// for the first outlet difference
... |
#[doc = "Register `OTG_GUSBCFG` reader"]
pub type R = crate::R<OTG_GUSBCFG_SPEC>;
#[doc = "Register `OTG_GUSBCFG` writer"]
pub type W = crate::W<OTG_GUSBCFG_SPEC>;
#[doc = "Field `TOCAL` reader - TOCAL"]
pub type TOCAL_R = crate::FieldReader;
#[doc = "Field `TOCAL` writer - TOCAL"]
pub type TOCAL_W<'a, REG, const O: u8... |
mod model;
mod schema;
use std::fs::{File, OpenOptions};
use std::sync::{Arc, Mutex};
use std::io::Write;
use diesel::prelude::*;
use diesel::sqlite::SqliteConnection;
use diesel::{Connection, RunQueryDsl};
use uuid::Uuid;
use backuplib::rpc::FileMetadata;
use crate::storage::StorageManager;
use crate::storage::sqli... |
#[doc = "Register `CRC_POL` reader"]
pub type R = crate::R<CRC_POL_SPEC>;
#[doc = "Register `CRC_POL` writer"]
pub type W = crate::W<CRC_POL_SPEC>;
#[doc = "Field `POL` reader - POL"]
pub type POL_R = crate::FieldReader<u32>;
#[doc = "Field `POL` writer - POL"]
pub type POL_W<'a, REG, const O: u8> = crate::FieldWriter<... |
/**
### 核心的trie树
这个算是整个系统稍微复杂一点的部分
核心就是一个Trie树
node是一个trie树
每个节点都是以.分割的字符串
foo.bar.aa
foo.cc.aa
foo.bb.dd
foo.dd
```
foo
/ / | \ \ \
* > bar cc bb dd
| | | |
aa aa aa aa
```
当一个订阅foo.> 插入这个树上的时候, 这个订阅会放到>中去 ,称之为sub1
当一个foo.* 插入的时候,订阅会放到* sub2
当一个订... |
use arboard::Clipboard;
fn main() {
let mut clipboard = Clipboard::new().unwrap();
println!("Clipboard text was: {}", clipboard.get_text().unwrap());
let the_string = "Hello, world!";
clipboard.set_text(the_string.into()).unwrap();
println!("But now the clipboard text should be: \"{}\"", the_string);
}
|
use rust_ml::rl::prelude::*;
use std::{thread, time};
use rust_ml::rl::agents::QTableAgent;
use rust_ml::rl::environments::FlappyEnvironment;
use rust_ml::rl::trainers::q_learning::QLearner;
fn main() {
// build training environment
let env_size = 12;
let hole_size = 3;
let env = FlappyEnvironment::n... |
extern crate advent_of_code_2017_day_12;
use advent_of_code_2017_day_12::*;
#[test]
fn part_1_example() {
let input = "\
0 <-> 2
1 <-> 1
2 <-> 0, 3, 4
3 <-> 2, 4
4 <-> 2, 3, 6
5 <-> 6
6 <-> 4, 5";
assert_eq!(solve_puzzle_part_1(input), "6");
}
#[test]
fn part_2_example() {
let input = "\
0 <-> 2
1 <-> 1
... |
use crate::core::ClientToClientWriter;
use crate::input_controller::keyboard::KeyStroke;
use crate::input_controller::{Response, PASTE_BUFFER};
use xi_rpc::Peer;
pub fn insert_keystroke(view_id: &str, key: KeyStroke, core: &dyn Peer) -> Response {
let output = match key {
KeyStroke::Char(c) => c.to_string... |
use frame_support::weights::{constants::RocksDbWeight as DbWeight, Weight};
impl crate::WeightInfo for () {
fn buy() -> Weight {
(87_000_000 as Weight)
.saturating_add(DbWeight::get().reads(2 as Weight))
.saturating_add(DbWeight::get().writes(1 as Weight))
}
fn list() -> Wei... |
use cocoa::base::{id, nil};
use cocoa::foundation::NSString;
use std::ffi::CStr;
use std::mem;
use sys::MTLCommandEncoder;
use Device;
#[derive(Debug)]
pub struct CommandEncoder(id);
impl CommandEncoder {
pub fn end_encoding(&mut self) {
unsafe { self.0.endEncoding(); }
}
pub fn insert_debug_sign... |
#[doc = "Register `DAC_STMODR` reader"]
pub type R = crate::R<DAC_STMODR_SPEC>;
#[doc = "Register `DAC_STMODR` writer"]
pub type W = crate::W<DAC_STMODR_SPEC>;
#[doc = "Field `STRSTTRIGSEL1` reader - DAC Channel 1 Sawtooth Reset trigger selection"]
pub type STRSTTRIGSEL1_R = crate::FieldReader;
#[doc = "Field `STRSTTRI... |
// https://projecteuler.net/problem=15
/*
If the numbers 1 to 5 are written out in words: one, two, three, four,
five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total.
If all the numbers from 1 to 1000 (one thousand) inclusive were
written out in words, how many letters would be used?
NOTE: Do not coun... |
mod ast;
mod codegen;
mod parser;
use crate::{ast::Ast, codegen::Function};
fn main() {
let node = parser::parse("(((5)+42)*8)").unwrap().1;
assert!(
matches!(node.ast, Ast::Literal(_)),
"constant propagation failed",
);
println!("{}", node.eval(&Default::default()).unwrap());
let... |
#[doc = "Register `GICD_ICPENDR0` reader"]
pub type R = crate::R<GICD_ICPENDR0_SPEC>;
#[doc = "Register `GICD_ICPENDR0` writer"]
pub type W = crate::W<GICD_ICPENDR0_SPEC>;
#[doc = "Field `ICPENDR0` reader - ICPENDR0"]
pub type ICPENDR0_R = crate::FieldReader<u32>;
#[doc = "Field `ICPENDR0` writer - ICPENDR0"]
pub type ... |
#![crate_type="lib"]
#![feature(no_std)]
#![feature(braced_empty_structs)]
#![no_std]
extern crate redox;
mod table;
mod djb2;
mod ptr;
mod archive;
mod data;
mod header;
//mod extract;
|
use std::convert::TryInto;
struct Input {
matrix: Vec<Vec<char>>,
is_fixpoint: bool,
}
impl Input {
fn new(inputs: &[&str]) -> Input {
let matrix: Vec<Vec<char>> = inputs.iter().map(|val| val.chars().collect()).collect();
Input {
matrix,
is_fixpoint: false,
... |
use neovim_lib::*;
use rusqlite::*;
fn main() {
let mut event_handler = EventHandler::new();
event_handler.recv();
}
struct Discusser {
connection: Connection,
}
const COMMENT_DB: &'static str = ".comment_code.db";
impl Discusser {
fn init_connection() -> Result<Connection> {
let connection... |
use std::collections::HashMap;
use std::iter::FromIterator;
pub use chrono::Weekday;
use indexmap::IndexMap;
pub use time::Duration;
pub use crate::agenda::Agenda;
pub use crate::timetable::{TimeRange, Timetable, WeekTime};
/// A collection of Workers.
pub struct Roster {
// A mapping of Workers by their names.
... |
use super::*;
#[derive(Clone, Debug, Default, PartialEq)]
/// A container of MS1 ratios, and associated sequence and residue information
pub struct Peptide {
pub sequence: String,
pub residue: Residue,
pub ms2: usize,
/// A ratio can be set to None if it's filtered out, or if it's
/// not quantifie... |
use std::collections::HashMap;
use std::error;
use std::fmt;
use std::result;
use Result;
use types::{Oid, Kind};
use error::{SqlState, ErrorPosition, ConnectError, Error};
/// Information about an unknown type.
#[derive(PartialEq, Eq, Clone, Debug)]
pub struct Other {
name: String,
oid: Oid,
kind: Kind,
... |
#[macro_use]
extern crate log;
use fxhash::FxHashMap;
use http::Method;
use inflector::string::{pluralize::to_plural, singularize::to_singular};
use path_tree::PathTree;
use std::{fmt, sync::Arc};
use trek_core::{
box_dyn_handler_into_middleware, into_box_dyn_handler, BoxDynHandler, Handler, Middleware,
};
mod r... |
#![doc = "generated by AutoRust 0.1.0"]
#![allow(unused_mut)]
#![allow(unused_variables)]
#![allow(unused_imports)]
use crate::models::*;
use reqwest::StatusCode;
use snafu::{ResultExt, Snafu};
pub mod operations {
use crate::models::*;
use reqwest::StatusCode;
use snafu::{ResultExt, Snafu};
pub async f... |
use std::{
env,
fs::read_dir,
path::{Path, PathBuf},
process::Command,
};
fn compile(benchmark: &Path) {
let stem = benchmark.file_stem().unwrap().to_str().unwrap();
let rustc = env::var("RUSTC_BOEHM").expect("RUSTC_BOEHM environment var not specified");
if stem.starts_with("bench_rustc") {... |
use crate::error::RPCError;
use ckb_chain::{chain::ChainController, switch::Switch};
use ckb_jsonrpc_types::{Block, BlockView, Cycle, Transaction};
use ckb_logger::error;
use ckb_network::NetworkController;
use ckb_shared::shared::Shared;
use ckb_store::ChainStore;
use ckb_sync::NetworkProtocol;
use ckb_types::{core, p... |
use std::fmt::{self, Debug};
use image::{DynamicImage, Rgba};
use image::codecs::jpeg::JpegEncoder;
use image::imageops::overlay;
use image::io::Reader;
use imageproc::geometric_transformations::{Interpolation, rotate};
use once_cell::sync::Lazy;
use rand::prelude::*;
use rand::distributions::Uniform;
use imageproc::d... |
use egui::{
plot::{Bar, BarChart, Line, Plot, Value, Values},
Grid, Ui,
};
use gba::GbaAudioSampler;
use util::circular::CircularBuffer;
use crate::{rgb, GbaData};
pub struct AudioPane {
sampler: GbaAudioSampler,
samples_l: CircularBuffer<f32, { Self::BUFFER_SIZE }>,
samples_r: CircularBuffer<f32,... |
#[test]
fn cli_tests() {
trycmd::TestCases::new()
.default_bin_name("rq")
.case("tests/cmd/*.toml")
.case("../../README.md")
.case("../../book/src/**/*.md")
.run();
}
|
use crate::rtb_type_strict;
rtb_type_strict! {
DeviceType,
Mobile=1;
PersonalComputer=2;
ConnectedTv=3;
Phone=4;
Tablet=5;
ConnectedDevice=6;
SetTopBox=7
}
|
use bootloader::{
bootinfo::{MemoryMap, MemoryRegionType},
BootInfo,
};
use x86_64::{
registers::control::Cr3,
structures::paging::{
FrameAllocator, Mapper, OffsetPageTable, Page, PageTable, PageTableFlags, PhysFrame,
Size4KiB,
},
PhysAddr, VirtAddr,
};
use crate::heap;
pub fn ... |
#[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::ALTPADCFGD {
#[doc = r" Modifies the contents of the register"]
#[inline]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&R, &'... |
use std::io;
fn main() {
let x = get_number_input("Enter the number:", -100.00, 100.00);
let n = get_number_input("Enter the exponent: ", -20.00, 20.00);
let result = power(x, n);
println!("{} raised to the power of {} is {:.2}.", x, n, result);
}
fn get_number_input (prompt: &str, min_val: f64, max_v... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.