text stringlengths 8 4.13M |
|---|
mod own{
fn say_hi(){
println!("hi");
}
pub fn say_hello(){
println!("hello");
}
}
fn main(){
own::say_hello();
use own::{say_hello as alias};
alias();
}
|
use actix::Actor;
use actix_web::{middleware, App, HttpServer};
use std::path::PathBuf;
use structopt::StructOpt;
#[actix_rt::main]
async fn main() -> std::io::Result<()> {
env_logger::builder().format_timestamp_nanos().init();
let opts: CliOptions = CliOptions::from_args();
let addr = format!("{}:{}", opt... |
use huffr::huffman_tree::*;
use std::collections::BinaryHeap;
use std::fs::File;
use std::io;
use std::io::prelude::*;
fn main() -> io::Result<()> {
let input_file = "mobydick.txt";
let pqueue = huff_queue_gen(input_file)?;
let tree = HuffTree::from_pqueue(pqueue);
println!();
println!();
prin... |
use anyhow::Context;
use rusqlite::{named_params, Transaction};
/// This migration fixes event addresses. Events were incorrectly stored using the transaction's
/// contract address instead of the event's `from_address`.
pub(crate) fn migrate(transaction: &Transaction<'_>) -> anyhow::Result<()> {
let todo: usize =... |
use crate::ebr::{Arc, AtomicArc, Barrier};
use crate::LinkedList;
use std::borrow::Borrow;
use std::cmp::Ordering;
use std::convert::TryInto;
use std::mem::MaybeUninit;
use std::sync::atomic::AtomicU32;
use std::sync::atomic::Ordering::{Acquire, Relaxed, Release};
pub const ARRAY_SIZE: usize = 8;
/// Entry state.
//... |
/*! Day1
* http://adventofcode.com/2018/day/1
*/
extern crate day01;
type Result<T> = std::result::Result<T, Box<std::error::Error>>;
static INPUT: &'static str = include_str!("../../input.txt");
pub fn main() {
println!(
"Solution 1a: {}",
day01::solve1a(parse_input(INPUT).expect("Error Parsi... |
use oxygengine_composite_renderer::{component::CompositeTransform, math::Vec2};
use oxygengine_core::{
app::AppBuilder,
ecs::{
hierarchy::Parent,
pipeline::{PipelineBuilder, PipelineBuilderError},
Comp, Universe, WorldRef,
},
prefab::{Prefab, PrefabComponent, PrefabManager},
... |
use crate::prelude::*;
use actix_web::client::JsonPayloadError;
pub(crate) use actix_web::client::SendRequestError as ClientSendRequestError;
use actix_web::error::{BlockingError, Error as ActixWebError};
use diesel::r2d2::PoolError;
#[derive(ThisError, Debug)]
pub enum CommonError {
#[error("db connect fail.")]
... |
#[derive(Clone)]
pub struct DexFieldNode {
pub name: String,
}
impl DexFieldNode {
pub fn new(name: String) -> Self {
Self { name }
}
}
|
use serde::{Deserialize, Serialize};
use crate::inner_client::InnerClient;
pub struct ReplicateRequest {
client: InnerClient,
payload: ReplicatePayload
}
impl ReplicateRequest {
pub fn new(client: &InnerClient) {
}
}
pub struct Replication {
client: InnerClient,
payloa... |
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
/// Record for an individual surface form and associated anchor counts.
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct SurfaceForm {
/// Surface form.
pub text: String,
/// Map of page titles to counts.
pub anchors... |
pub mod ciphers;
pub mod encrypted_file;
pub mod hashers;
pub mod iv;
pub mod raw_key;
pub mod signers;
|
mod mutex;
mod once;
pub use mutex::*;
pub use once::*;
|
pub mod lcp;
//pub mod plcp;
//use lcp::kasai::LcpKas;
use crate::util::errors::Error;
pub type LcpArray<T> = Vec<T>;
pub type pLcpArray<T> = Vec<T>;
pub trait Lcp <T>{
fn kasai_compute(text: String, sa: Vec<T>) -> Result<LcpArray<T>,Error>;
fn karkk_compute(text: String, sa: Vec<T>) -> Result<LcpArray... |
// Copyright (c) 2021 Thomas J. Otterson
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
use std::{cell::RefCell, cmp::Ordering, fmt::Debug, rc::Rc};
use super::pin::{Mode, PinRef};
/// A convenience alias for a shared internally-mutable reference to a Trace, so we don't... |
macro_rules! try_ffmpeg {
($e:expr, $ctx:expr) => {{
let res = $e;
if res < 0 {
return Err(crate::InternalError::new(res, $ctx).into());
}
res
}};
}
|
use std::path::PathBuf;
use app_dirs::{app_dir, AppDataType, AppDirsError, AppInfo};
const APP_INFO: AppInfo = AppInfo { name: "eitaro", author: "anekos" };
pub fn get_dictionary_path(name: Option<&str>) -> Result<PathBuf, AppDirsError> {
let mut result = app_dir(AppDataType::UserCache, &APP_INFO, "dictionar... |
use std::env;
mod script_module {
include!(concat!(env!("RUST_SCRIPT_BASE_PATH"), "/script-module.rs"));
}
fn main() {
println!("--output--");
let s = include_str!(concat!(env!("RUST_SCRIPT_BASE_PATH"), "/file-to-be-included.txt"));
assert_eq!(script_module::A_VALUE, 1);
println!("{}", s);
}
|
// Copyright 2014-2018 The Rust 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/MIT>,... |
use std::cmp;
use parser::{FileHash, Inherit, Layout, LayoutItem, Member, Type, Unit, Variant, VariantPart};
use crate::print::{self, DiffList, DiffState, Print, PrintState, ValuePrinter};
use crate::Result;
fn print_member(member: &Member, w: &mut dyn ValuePrinter, hash: &FileHash) -> Result<()> {
write!(w, "{}... |
// MIT License
//
// Copyright (c) 2021 Miguel Peláez
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modif... |
use std::io;
use std::vec;
use std::iter;
fn readLine() -> String {
let mut buf = String::new();
io::stdin()
.read_line(&mut buf)
.expect("Something went wrong while reading");
return buf;
}
struct DayData {
ax: usize,
bx: usize,
ay: usize,
by: usize,
}
impl DayData {
fn... |
use lllreduce::{
Basetype,
gram_schmidt_with_coeffs,
lll_reduce};
#[test]
fn main() {
let original_mtx : std::vec::Vec<std::vec::Vec::<Basetype>> = vec![
vec![0.0,3.0,4.0,7.0,8.0],
vec![1.0,0.0,1.0,8.0,7.0],
vec![1.0,1.0,3.0,5.0,6.0],
vec![0.0,3.0,4.0,7.0,6.0],
vec![0.0,3.0... |
extern crate directories;
#[macro_use]
extern crate log;
extern crate sdl2_sys;
extern crate serde;
#[macro_use]
extern crate serde_derive;
extern crate serde_json;
pub mod logger;
pub mod sdl;
pub mod types;
use std::fmt;
use serde::Deserialize;
use types::{Pos2, Size2};
#[derive(Debug)]
pub enum Error {
Init... |
// This file is part of Substrate.
// Copyright (C) 2017-2020 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 F... |
use crate::tokens::{LispError, LispToken};
// function: serves to call the actual parsing function.
pub fn parse(expr: &Vec<char>) -> Result<LispToken, LispError> {
let mut idx = 0;
parse_rd(&expr, &mut idx)
}
// function: converts a vector of chars to a s-expression. returns LispToken on success or LispError... |
use std::io;
fn solve(mut c: Vec<isize>) -> usize {
let mut cost = 0;
for _ in 0..c.len() - 1 {
let (index_min, _) = c.iter().enumerate().min_by(|a, b| a.1.cmp(&b.1)).unwrap();
cost += index_min + 1;
c.remove(index_min);
c[0..index_min].reverse();
}
cost
}
fn main() {
... |
use loc::Loc;
use token::Token;
#[derive(Debug, Clone)]
pub enum ErrorId {
// Errors generated by lexer
InvalidReg,
InvalidChar,
// Errors generated by parser
ExpectedProgram,
ExpectedLine,
ExpectedAtom,
ExpectedParen,
ExpectedSquare,
InvalidNode,
InvalidInstruction
}
#[derive(Debug, Clone)]
pub struct ... |
use actix_web::{post,web,HttpResponse,Responder};
use log::info;
use pam::Authenticator;
use serde::{Serialize, Deserialize};
#[derive(Debug,Deserialize)]
pub struct Request{
username: String,
password: String,
}
#[derive(Debug,Serialize)]
pub struct Response{
result: bool,
}
#[post("/validate_password... |
extern crate greeks;
const UNDERLYING: f64 = 64.68;
const STRIKE: f64 = 65.00;
const VOL: f64 = 0.5051;
const INTEREST_RATE: f64 = 0.0150;
const DIV_YIELD: f64 = 0.0210;
const DAYS_PER_YEAR: f64 = 365.0;
const TIME_TO_EXPIRY: f64 = 23.0 / DAYS_PER_YEAR;
const E_CALL_DELTA: f64 = 0.5079;
fn main() {
let actual_d... |
use std::mem;
#[allow(dead_code)]
struct S {
var1 : i64,
var2 : &'static str
}
fn raw_data_transmute() {
let s = S { var1:100, var2:"hello"};
let raw_bytes : &[u64; 2] = unsafe { mem::transmute(&s) };
for byte in raw_bytes.iter() {
print!(" 0x{:x} ", byte);
}
println!("");
}
impl Drop for S {
fn drop(&... |
use futures::{stream, StreamExt, TryStreamExt};
use k8s_openapi::api::{
apps::v1::Deployment,
core::v1::{ConfigMap, Secret},
};
use kube::{
api::{Api, ResourceExt},
runtime::{watcher, WatchStreamExt},
Client,
};
use tracing::*;
#[tokio::main]
async fn main() -> anyhow::Result<()> {
tracing_subs... |
use std::collections::HashMap;
use std::path::PathBuf;
use serde::{Deserialize, Serialize};
use persist_core::protocol::ProcessSpec;
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ProcessDump {
pub name: String,
pub cmd: Vec<String>,
pub cwd: PathBuf,
pub env: HashMap<Strin... |
use std::panic;
pub mod sql;
pub use self::sql::*;
pub fn run_test<T, U, V>(test: T, setup: U, teardown: V) -> ()
where
T: FnOnce() -> () + panic::UnwindSafe,
U: FnOnce() -> (),
V: FnOnce() -> (),
{
setup();
let result = panic::catch_unwind(|| test());
teardown();
assert!(result.is_ok()... |
fn thirt(n: i64) -> i64 {
let pattern = vec![1, 10, 9, 12, 3, 4];
let mut pattern_it = pattern.iter().cycle();
let result: i64 = n.to_string().chars().rev().fold(0, |sum, c| {
let cur_pat = pattern_it.next().unwrap();
let cur_d = c.to_digit(10).unwrap() as i64;
sum + (cur_pat * cur_d)
});
if re... |
#[derive(Debug)]
enum IpAddress{
ipV2,
ipV6,
}
#[derive(Debug)]
struct IPAddress{
kind:IpAddress,
address:String,
}
fn main() {
let ip=IPAddress{
kind:IpAddress::ipV6,
address:String::from("19.fd.er.er.er")
};
println!("{:#?}",ip);
}
|
// lib.rs
/*
* communicator
* ├─client
* └─network
* ├─server
* └─client
*/
pub mod client;
pub mod network;
#[cfg(test)]
mod tests {
#[test]
fn it_works() {
/*
* communicator // (1)번: 루트 라이브러리로 올라가서 하위 라이브러리 접근, 라이브러리의 규모가 큰
* 경우 복잡해질 수 있다.
* ├─client **여길 찾아가야 함
* ├─test // (2)번: 현재 위치... |
use num;
use num_derive;
#[derive(PartialEq, Debug)]
pub struct ChopperConfiguration {
toff_time: u8,
hysteresis_start: u8,
hysteresis_val: i8,
time_select: ComparatorBlankTime,
high_sensitivity: bool,
microstep_resolution: MicrostepResolution,
interp_to_256_microsteps: bool,
... |
//! A board support library for the TI Stellaris Launchpad
// ****************************************************************************
//
// Imports
//
// ****************************************************************************
// ****************************************************************************
//... |
use super::ast;
use super::*;
use basic_parser::{parse_eval, parse_lines, parse_string};
#[derive(PartialEq)]
struct Named(&'static str);
fn dummy_cksum(name: &str) -> u32 {
if name == "root" {
0
} else {
1000 + name.chars().fold(0, |x, y| (x * 97 + y as u32) % 1361)
}
}
impl UnixUser for... |
//! The main algorithm.
use crate::matrix::Matrix;
use crate::types::{Check, CheckError, ConPat, Lang, Pat, RawPat, Result};
use fast_hash::FxHashSet;
/// Does the check.
///
/// Returns an error if the patterns or types passed don't make sense, or if the
/// `lang` returned an error.
///
/// This should never panic.... |
use async_std::os::unix::net::UnixStream;
use async_std::task;
use std::io::Result;
use std::path::Path;
use crate::State;
mod session;
pub mod socket;
pub use session::Session;
pub async fn run_rpc<P>(socket_path: P, state: State) -> Result<()>
where
P: AsRef<Path>,
{
socket::accept(socket_path, state, on_... |
use crate::com_interface::{IInitializeWithStream, IThumbnailProvider};
use com::sys::{HRESULT, S_OK};
use winapi::shared::minwindef::{DWORD, PUINT, UINT};
use winapi::shared::windef::HBITMAP;
use winapi::shared::wtypes::STATFLAG_NONAME;
use winapi::um::objidlbase::{LPSTREAM, STATSTG};
use winapi::um::wingdi::CreateBi... |
//! Types that can be used to serialize and deserialize types inside databases.
//!
//! How to choose the right type to store things in this database?
//! For specific types you can choose:
//! - [`Str`] to store [`str`](primitive@str)s
//! - [`Unit`] to store `()` types
//! - [`SerdeBincode`] or [`SerdeJson`] to... |
//! Simple PAM module example: MOTD handler.
extern crate openat;
#[macro_use]
extern crate pamsm;
extern crate syslog;
use pamsm::{Pam, PamError, PamFlag, PamServiceModule};
use std::{collections, fs, io, path};
// Local logger type.
type ModLogger = syslog::Logger<syslog::LoggerBackend, String, syslog::Formatter31... |
use std::{
cmp::{ PartialEq, PartialOrd, Ordering, max },
num::FpCategory,
ops::{
Add, Sub,
AddAssign, SubAssign,
Mul, Div, Rem, Neg,
MulAssign, DivAssign, RemAssign,
},
};
use cgmath::ApproxEq;
use noisy_float::types::{ R64, r64 };
use num;
use num::Float as NumFloat;
us... |
use crate::dom;
use crate::dom::component::Component;
use crate::dom::component::Composable;
use crate::native;
use crate::task;
use std::any::Any;
use std::cell::RefCell;
thread_local!(static APP: RefCell<Option<App>> = RefCell::new(None));
struct App {
root_component: Box<dyn Composable>,
dom_renderer: dom:... |
use std::{
env::{args, Args},
io::Read,
net::TcpListener,
};
#[allow(unused)]
struct Config {
ip: String,
port: u16,
}
#[allow(unused)]
fn parse_arguments(mut args: Args) -> Result<Config, &'static str> {
args.next();
let ip_port = args.next().expect("Please use 'exe ip:port' to start");
... |
// Copyright (c) The Starcoin Core Contributors
// SPDX-License-Identifier: Apache-2.0
use anyhow::{format_err, Result};
use libp2p::Multiaddr;
use num_enum::{IntoPrimitive, TryFromPrimitive};
use once_cell::sync::Lazy;
use serde::{Deserialize, Serialize};
use starcoin_crypto::{
ed25519::*, hash::PlainCryptoHash, ... |
use hyper::{Body, Response};
use serde::Serialize;
use nails::error::NailsError;
use nails::{Preroute, Service};
use crate::context::AppCtx;
mod articles;
mod posts;
mod tags;
mod users;
pub fn build_route(_ctx: &AppCtx) -> Service<AppCtx> {
Service::builder()
.add_function_route(index)
.add_fun... |
#[derive(Debug)]
pub struct Queue<T> {
elements: Vec<T>,
}
impl<T: Clone> Queue<T> {
pub fn new() -> Queue<T> {
Queue {
elements: Vec::new(),
}
}
pub fn enqueue(&mut self, value: T) {
self.elements.push(value)
}
pub fn dequeue(&mut self) -> Result<T, &str> ... |
// MIT License
//
// Copyright (c) 2021 Miguel Peláez
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modif... |
use wasm_bindgen::prelude::*;
use web_sys::*;
#[macro_use]
mod util;
#[wasm_bindgen(start)]
pub async fn main() {
std::panic::set_hook(Box::new(console_error_panic_hook::hook));
log!("Hello World!");
} |
use actix_web::web;
use crate::handlers::api::access::*;
use crate::handlers::api::account::*;
use crate::handlers::api::file::*;
use crate::handlers::api::*;
use crate::handlers::*;
use crate::middlewares::auth;
pub fn router(service_config: &mut web::ServiceConfig) {
service_config.service(
web::scope("... |
use std::fs::File;
use std::io::prelude::*;
use std::path::Path;
use std::io::{self, BufRead};
static LOREM_IPSUM: &str = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi... |
use crate::util::replace_urls_rev;
use crate::util::*;
use crate::{AppData, PathConfig, PathConfigKey, StaticResolved, Mode};
use actix_multipart::Multipart;
use actix_web::{
client::{self, Client},
http::{
header::{self, HeaderValue},
StatusCode,
},
web::{self, BytesMut},
Error, Htt... |
// Copyright (c) Meta Platforms, Inc. and affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
#![cfg_attr(not(fbcode_build), allow(unused_variables))]
use ocamlrep_caml_builtins::Int64;
use ocamlrep_custom::Custom;
use rpds::Ha... |
use std::collections::HashMap;
use db::{Database, TextureId, PaletteId};
use glium::{Display, Texture2d, texture::RawImage2d};
use nds;
// TODO: move somewhere more important.
pub type ImageId = (TextureId, Option<PaletteId>);
/// Maintains cache of all the GL texture we use.
pub struct TextureCache {
/// Caches ... |
use indexmap::IndexMap;
use crate::error::{Error, Result};
use crate::field::Field;
use crate::input::DbValue;
pub type DynField = Box<dyn Field + Send + Sync>;
pub struct Models {
pub models: IndexMap<String, Model>,
}
impl Models {
pub fn new() -> Self {
Models {
models: IndexMap::with_... |
/// An enum to represent all characters in the BamumSupplement block.
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
pub enum BamumSupplement {
/// \u{16800}: '𖠀'
BamumLetterPhaseDashANgkueMfon,
/// \u{16801}: '𖠁'
BamumLetterPhaseDashAGbieeFon,
/// \u{16802}: '𖠂'
BamumLetterPhaseDashAPon... |
use crate::mbc::MBC;
pub struct MBC0 {
rom: Vec<u8>,
}
impl MBC0 {
pub fn new(rom: Vec<u8>) -> MBC0 {
MBC0 { rom }
}
}
impl MBC for MBC0 {
fn read_rom(&self, addr: u16) -> u8 {
match self.rom.get(addr as usize) {
Some(byte) => *byte,
None => panic!("Out of boun... |
mod sampler {
use models;
use samplers;
trait Sampler {
fn run<M, S>(pg: ParameterGroup<M, S>);
}
struct ParameterGroup<M, S> {
model: M,
sampler: S,
}
struct Metropolis {}
} |
use std::{
fmt::Debug,
ptr::{read_volatile, write_volatile},
sync::atomic::{AtomicBool, AtomicUsize, Ordering},
thread::{sleep, spawn},
time::Duration,
};
#[allow(non_upper_case_globals)]
static mut threshold: isize = 0;
const MAX_TEST: usize = 100000;
const ELEMENTS_PER_ROW: usize = 6;
const MAX_... |
use std::result;
//use rustc_serialize::json;
pub type Result<Success, Error> = result::Result<Success, Error>;
#[derive(Debug)]
pub enum Success { Success }
#[derive(Debug)]
pub enum Error {
NotOkResponse,
}
pub mod accounts;
pub mod sshkeys; |
// Copyright 2014-2018 The Rust 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/MIT>,... |
use component::{FlagCarrier, IsFlag, LastDrop, Flags};
use server::{Builder, Position, Team};
use specs::*;
use specs::Builder as SpecsBuilder;
use std::time::Instant;
use super::*;
use config;
pub fn register<'a, 'b>(world: &mut World, disp: Builder<'a, 'b>) -> Builder<'a, 'b> {
world.register::<Team>();
world.r... |
use std::path::Path;
use std::fs::File;
use std::io::prelude::*;
use std::error::Error;
pub fn read_inputs<P>(path : P) -> String where P: AsRef<Path> {
let mut file = match File::open(&path) {
Err(why) => panic!("couldn't open file: {}",
why.description()),
Ok(file) => f... |
#[macro_use]
extern crate diesel;
pub mod models;
pub mod routes;
pub mod services;
pub mod db;
|
use crate::ffi::*;
use crate::util::*;
use ::objc::runtime::*;
use objc_foundation::{INSString, NSString};
use std::os::raw::c_void;
use std::ptr::NonNull;
/// Returns an Objective-C `Class` by it's name.
pub fn get_class(class: &str) -> *const Class {
unsafe { objc_getClass(to_c_str(class)) }
}
/// Logs a string to... |
#[doc = "Register `OPTR` reader"]
pub type R = crate::R<OPTR_SPEC>;
#[doc = "Register `OPTR` writer"]
pub type W = crate::W<OPTR_SPEC>;
#[doc = "Field `RDP` reader - Read protection level"]
pub type RDP_R = crate::FieldReader;
#[doc = "Field `RDP` writer - Read protection level"]
pub type RDP_W<'a, REG, const O: u8> = ... |
#![allow(non_upper_case_globals)]
#![allow(non_camel_case_types)]
#![allow(non_snake_case)]
#![allow(dead_code)]
include!(concat!(env!("OUT_DIR"), "/nginx.rs"));
#[no_mangle]
pub unsafe extern "C" fn ngx_http_calculator_handler(
r: *mut ngx_http_request_t,
) -> ngx_int_t {
let rc = ngx_http_read_client_request_bod... |
#![allow(non_camel_case_types, non_snake_case, dead_code)]
type h8 = u8;
type h64 = u64;
type state = [h64; 6];
type u128 = (u64,u64);
fn constant_time_carry(a:u64, b:u64) -> u64 {
((a ^ ((a ^b) | ((a-b)^b))) >> 63)
}
/* Unsure about the logic here; seem to be missing some carry bits */
fn mul_wide(x:u64, y:u64) ... |
// RGB Rust Library
// Written in 2019 by
// Dr. Maxim Orlovsky <dr.orlovsky@gmail.com>
// basing on ideas from the original RGB rust library by
// Alekos Filini <alekos.filini@gmail.com>
//
// To the extent possible under law, the author(s) have dedicated all
// copyright and related and neighboring rights to ... |
/// There is no project code to compile, just many dependencies.
fn main() {
println!("Hello, world!");
}
|
use composite::*;
use mass::metric::Kilogram;
use length::metric::Meter;
use time::Second;
pub type Newton = Mul<Kilogram, Div<Meter, Mul<Second, Second>>>;
|
use async_graphql::{
http::{playground_source, GraphQLPlaygroundConfig},
ObjectType, Schema, SubscriptionType,
};
use std::fmt::Debug;
use tide::http as http_types;
use worker::*;
use crate::integration::tide_gql_integration::endpoint;
mod tide_gql_integration;
async fn wreq_to_treq(mut req: Request) -> Resul... |
//! no_std implementation of DelayMs and DelayUs for cortex-m
#![deny(missing_docs)]
#![no_std]
pub use bitrate;
use bitrate::*;
use cortex_m::asm::delay;
use embedded_hal::blocking::delay::DelayMs;
use embedded_hal::blocking::delay::DelayUs;
/// asm::delay based Timer
pub struct AsmDelay {
freq_base_ms: u32,
... |
use aes_gcm::{
aead::{generic_array::GenericArray, Aead, NewAead, Nonce, Payload},
Aes128Gcm,
};
use byteorder::{BigEndian, ByteOrder};
use bytes::{Bytes, BytesMut};
use rtp::packetizer::Marshaller;
use super::Cipher;
use crate::{error::Error, key_derivation::*};
pub const CIPHER_AEAD_AES_GCM_AUTH_TAG_LEN: us... |
macro_rules! decode_impl {
($l:expr; $(#[$attr: meta])* $parse_macro:ident; $(#[$decode_attr: meta])* $decode_name: ident; $(#[$decode_to_string_attr: meta])* $decode_to_string_name: ident; $(#[$decode_to_vec_attr: meta])* $decode_to_vec_name: ident; $(#[$decode_to_writer_attr: meta])* $decode_to_writer_name: ident... |
#[cfg(target_arch = "x86_64")]
use std::borrow::BorrowMut;
#[cfg(target_arch = "riscv64")]
use core::borrow::BorrowMut;
/// w[0], u[0], and v[0] contain the LEAST significant halfwords.
/// (The words are in little-endian order).
/// This is Knuth's Algorithm M from [Knuth Vol. 2 Third edition (1998)]
/// section 4.3.... |
#[allow(unused_variable)]
#[allow(dead_code)]
enum Pitch {
Frequency(f64,FrequencyUnits),
Period(f64,PeriodUnits),
}
impl Show for Pitch {
#[allow(dead_code)]
enum FrequencyUnits {
Hertz,
BeatsPerMinute,
}
#[allow(dead_code)]
enum PeriodUnits {
MilliSeconds,
Seconds,
}
#[allow(dead_code)]
enum SemanticDire... |
struct Solution;
impl Solution {
pub fn smaller_numbers_than_current(nums: Vec<i32>) -> Vec<i32> {
let mut cnt = vec![0; 101]; // num 最大为 100
// 每个数字出现的次数
for num in nums.iter() {
cnt[*num as usize] += 1;
}
// <= num 的数字个数
for i in 1..cnt.len() {
... |
use pom::parser::*;
use pom::char_class::*;
use crate::types::*;
fn spaces<'a>() -> Parser<'a, u8, ()> {
one_of(b" \n\r,").repeat(0..).discard()
}
fn comment<'a>() -> Parser<'a, u8, ()> {
sym(b';') * none_of(b"\r\n").repeat(0..) * spaces()
}
fn ignored<'a>() -> Parser<'a, u8, ()> {
comment() | spaces()... |
#![no_main]
use libfuzzer_sys::fuzz_target;
use std::str::from_utf8;
use hltas::HLTAS;
fuzz_target!(|data: &[u8]| {
if let Ok(s) = from_utf8(data) {
if let Ok(hltas) = HLTAS::from_str(s) {
let mut output = Vec::new();
hltas.to_writer(&mut output).unwrap();
let hltas_2... |
mod output;
mod rarfiles;
use crate::rarfiles::RarFiles;
use clap::arg_enum;
use log::*;
use output::RealOutput;
use output::{handle_output, FancyHandler, LogHandler, Output, StdoutHandler};
use std::path::PathBuf;
use structopt::StructOpt;
use walkdir::{DirEntry, WalkDir};
arg_enum! {
#[derive(Debug, Clone)]
... |
// This example uses fds() to find out which file descriptors c-ares wants us to listen on, and
// uses select() to satisfy those requirements.
#[cfg(windows)]
extern crate winapi;
#[cfg(windows)]
mod example {
extern crate c_ares;
use std::mem;
use std::net::{Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4,... |
#[cfg(target_arch = "x86_64")]
/// The function, [_MM_SHUFFLE](https://doc.rust-lang.org/core/arch/x86_64/fn._MM_SHUFFLE.html) is
/// only supported on nightly and there has been [some controversy
/// around](https://github.com/rust-lang-nursery/stdsimd/issues/522) it regarding the type
/// signature, so the safe route... |
//==============================================================================
// Notes
//==============================================================================
// mcu::gpio.rs
// Basic control over gpio pins
//==============================================================================
// Crates and Mods
... |
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate slog;
extern crate slog_term;
use slog::DrainExt;
extern crate gtk;
use gtk::prelude::*;
use gtk::{Label, Window, WindowType};
extern crate regex;
extern crate rustc_serialize;
extern crate docopt;
pub mod backend;
mod tools;
pub use tools::Tempera... |
#![allow(non_snake_case)]
#![allow(unused_must_use)]
use std::thread;
use crate::client;
use std::error::Error;
use std::io::prelude::*;
use crate::encoder::EncoderMethods;
use std::net::{self, SocketAddr, SocketAddrV4, SocketAddrV6, Ipv4Addr, Ipv6Addr, TcpStream, TcpListener};
#[allow(unused_imports)]
use log::{trace... |
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
mod abstract_partition_test {
use im::HashSet;
use sparta::datatype::AbstractDomain;
use sparta::datatype::AbstractPa... |
use syn::{ Fields, Variant, token::Comma, punctuated::Punctuated };
use crate::struct_compiler;
use crate::attributes::{ ParentDataType, FieldDataType, get_discriminant, enums::EnumDiscriminant };
use proc_macro2::TokenStream;
pub fn get_clauses(variants: &Punctuated<Variant, Comma>,
name : &proc_macro2::Ident,... |
use core::fmt::Write;
use crate::{input::serial_read, io::{IoReader, IoWriter}, kernel::hardware::uart::*};
pub struct Serial;
impl IoReader<u8> for Serial {
fn read(&mut self) -> Option<u8> {
serial_read()
}
}
impl IoWriter<u8> for Serial {
fn write(&mut self, item : u8) {
write_u8(item)... |
use crate::{
codegen::{
builder::{cast, core, op, ty},
expr::const_expr::const_atom,
unit::Slot,
AatbeModule, CompileError, ValueTypePair,
},
fmt::AatbeFmt,
ty::{LLVMTyInCtx, TypeKind, TypedefKind},
};
use super::builder::value;
use parser::ast::{AtomKind, Boolean, Float... |
pub fn permute(nums: Vec<i32>) -> Vec<Vec<i32>> {
fn next_permutation(nums: &mut Vec<i32>) {
fn swap(v: &mut Vec<i32>, i: usize, j: usize) {
let tmp = v[i];
v[i] = v[j];
v[j] = tmp;
}
match nums.len() {
0 | 1 => return,
2 => {
... |
use encoding_rs::Encoding;
use std::str::FromStr;
use trillium_http::http_types::{
headers::{Headers, CONTENT_TYPE},
mime::Mime,
};
/// a utility function for extracting a character encoding from a set
/// of [`Headers`][http_types::headers::Headers]
pub(crate) fn encoding(headers: &Headers) -> &'static Encodi... |
use {
crate::assert_eq_trimmed, littlebigint::BigUint, num_bigint::BigUint as NumBigUint,
proptest::prelude::*,
};
#[test]
fn basic_shiftleft() {
let mut a_array = [2];
let a = BigUint::from_slice(&mut a_array);
let mut b_array = [1];
let b = BigUint::from_slice(&mut b_array);
assert_eq!(... |
fn main() {
let mut sits = String::from_utf8(std::fs::read("input/day5").unwrap())
.unwrap()
.split_whitespace()
.map(|sit_str| {
sit_str
.chars()
.map(|c| match c {
'F' | 'L' => '0',
_ => '1',
... |
#[doc = "Register `RCR` reader"]
pub type R = crate::R<RCR_SPEC>;
#[doc = "Register `RCR` writer"]
pub type W = crate::W<RCR_SPEC>;
#[doc = "Field `PAGE0_WP` reader - CCM SRAM page write protection bit"]
pub type PAGE0_WP_R = crate::BitReader<PAGE0_WP_A>;
#[doc = "CCM SRAM page write protection bit\n\nValue on reset: 0... |
mod all_storages;
mod fake_borrow;
#[cfg(feature = "non_send")]
mod non_send;
#[cfg(all(feature = "non_send", feature = "non_sync"))]
mod non_send_sync;
#[cfg(feature = "non_sync")]
mod non_sync;
pub use all_storages::AllStoragesBorrow;
pub use fake_borrow::FakeBorrow;
#[cfg(feature = "non_send")]
pub use non_send::No... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.