text stringlengths 8 4.13M |
|---|
pub mod isr;
pub mod nvic;
|
use crate::constants::MODBYTES;
use super::types::GroupG2;
// Byte size of element in group G2
pub const GROUP_G2_SIZE: usize = (4 * MODBYTES) as usize;
// Byte size of element in group GT
pub const GROUP_GT_SIZE: usize = (12 * MODBYTES) as usize;
lazy_static! {
pub static ref GENERATOR_G2: GroupG2 = GroupG2::ge... |
use ast::{self, Name};
use attr::{self, HasAttrs};
use codemap::{ExpnInfo, MacroAttribute, NameAndSpan, respan};
use ext::base::*;
use ext::build::AstBuilder;
use ext::expand::{MacroExpander, expand_multi_modified};
use parse::token::intern;
use util::small_vector::SmallVector;
pub fn expand_annotatable(
mut item:... |
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Vote {
Now,
NotNow
}
impl Vote {
pub fn now() -> Vote {
Vote::Now
}
pub fn not_now() -> Vote {
Vote::NotNow
}
pub fn description(&self) -> String {
match self {
&Vote::Now => format!("устроить вс... |
extern crate rand;
extern crate rayon;
pub mod parsers;
use self::rayon::prelude::*;
use rand::rngs::SmallRng;
use rand::{FromEntropy, Rng};
use std::iter;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CellState {
Alive,
Dead,
}
impl Into<bool> for CellState {
fn into(self) -> bool {
sel... |
pub(crate) mod contracts;
pub(crate) mod json_vals;
pub(crate) mod lazy_stream;
pub(crate) mod port;
pub(crate) mod structs;
|
extern crate upload_images;
#[cfg(test)]
mod dataset;
use std::env;
use std::fs::File;
use std::io::Read;
use rocket::http::{ContentType, Status};
use rocket::local::Client;
use upload_images::rocket;
#[test]
fn test_valid_single_png_base64() {
let client = Client::new(rocket()).unwrap();
let mut response = cl... |
//! # wun32job-rs
//!
//! A safe API for Windows' job objects, which can be used to set various limits to
//! processes associated with them.
//! See also [Microsoft Docs](https://docs.microsoft.com/en-us/windows/win32/api/jobapi2/nf-jobapi2-createjobobjectw).
//!
//! # Using the higher level API
//!
//! After getting ... |
fn main() {
example::main();
}
|
fn main() {
let ch = 'A' ;
println!("ch is {}", ch );
let ch = 'あ' ;
println!("ch is {}", ch );
let ch = '🐱' ;
println!("ch is {}", ch );
let ch: char = '🐶' ;
println!("ch is {}", ch );
let ch = '\u{1F431}' ;
println!("ch is {}", ch );
println!("char size of {}", std::... |
use std::env;
use std::fs;
use std::process;
fn main() {
let args: Vec<String> = env::args().collect();
if args.len() != 3 {
eprintln!("{:?}: wrong arguments", &args[0]);
process::exit(1);
}
if let Err(why) = fs::hard_link(&args[1], &args[2]) {
eprintln!("{:?}: {:?}", &args[1]... |
use regex::Regex;
use std::collections::HashMap;
use std::collections::HashSet;
use std::fs::File;
use std::io::prelude::*;
use std::io::{self, BufReader};
fn check_map(m: &HashMap<String, String>) -> bool {
for (key, value) in m.iter() {
match &key[..] {
"byr" => {
let my_int =... |
use crate::{
telemetry::PublishCommonOptions,
ttn::{publish_uplink, Uplink},
};
use actix_web::{web, HttpResponse};
use drogue_cloud_endpoint_common::{
auth::DeviceAuthenticator,
error::{EndpointError, HttpEndpointError},
sender::DownstreamSender,
sink::Sink,
x509::ClientCertificateChain,
};... |
use crate::types::{Position, Segment};
pub fn line_of_sight(start: Position, obstacles: &[Segment], destination: Position) -> bool {
return obstacles.iter()
.all(|obstacle| line_of_sight_single(start, obstacle, destination));
}
/// Returns false of obstacle is preventing line of sight between start and de... |
// SPDX-FileCopyrightText: 2020 Alexander Dean-Kennedy <dstar@slackless.com>
// SPDX-FileCopyrightText: 2021 Robin Krahl <robin.krahl@ireas.org>
// SPDX-License-Identifier: Apache-2.0 or MIT
//! Image support for genpdf-rs.
use std::path;
use image::GenericImageView;
use crate::error::{Context as _, Error, ErrorKin... |
#![macro_use]
use core::cell::Cell;
use core::convert::TryInto;
use core::sync::atomic::{compiler_fence, Ordering};
use atomic_polyfill::AtomicU32;
use embassy::interrupt::InterruptExt;
use embassy::time::{Clock as EmbassyClock, TICKS_PER_SECOND};
use crate::interrupt::{CriticalSection, Interrupt, Mutex};
use crate:... |
use reqwest;
use std::collections::HashMap;
#[allow(dead_code)]
pub fn fetch_firebase_key(kid: &String) -> String {
let fetched_map = reqwest::blocking::get("https://www.googleapis.com/robot/v1/metadata/x509/securetoken@system.gserviceaccount.com").unwrap()
.json::<HashMap<String, String>>().unwrap();
... |
use cocoa::base::id;
use cocoa::foundation::NSUInteger;
/// A `MTLRenderPassColorAttachmentDescriptorArray` object contains an array of color
/// attachment descriptors.
pub trait MTLRenderPassColorAttachmentDescriptorArray {
/// Returns the descriptor object for the specified color attachment.
unsafe fn objec... |
//! Index names from authority records.
use std::collections::{HashMap, HashSet};
use std::fs::File;
use std::path::{Path, PathBuf};
use std::thread::{spawn, JoinHandle};
use crossbeam::channel::{bounded, Receiver, Sender};
use csv;
use flate2::write::GzEncoder;
use serde::Serialize;
use rayon::prelude::*;
use crat... |
use std::fmt::Show;
use conduit::{mod, Handler, Request, Response};
use conduit_middleware::Middleware;
use conduit_test::MockRequest;
use cargo_registry::user::{User, EncodableUser};
use cargo_registry::db::RequestTransaction;
#[deriving(Decodable)]
struct AuthResponse { url: String, state: String }
#[deriving(Deco... |
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
pub enum PlayerColor {
White,
Black,
}
#[derive(Debug)]
pub struct Player {
pub color: PlayerColor,
}
impl PlayerColor {
pub fn white(&self) -> bool {
*self == PlayerColor::White
}
pub fn black(&self) -> bool {
*self == Player... |
//! # Intcode
//!
//! `intcode` is a library for executing Intcode programs, as featured in the Advent
//! of Code 2019.
//!
//! This library offers three modes of operation, represented by the structs
//! [`ChannelIOComputer`], [`StreamingIOComputer`] and [`SynchronousComputer`]. All
//! three take an Intcode program... |
fn main() {
/// ## 3.1. Variables and mutability
/// This is sample program written in Rust, which contains following topics.
/// - default mutability (i.e. Rust variable is immutable as default, and you can change it with "mut".
/// - Differences between variables and constants.
/// - ... |
pub struct Solution {}
/// LeetCode Monthly Challenge problem for March 3rd, 2021.
impl Solution {
/// Given an array of distinct numbers in the range [0, n] that is missing
/// one number, finds and returns the missing number.
///
/// # Arguments
/// * nums - A vector of distinct i32 integers in ... |
use crossbeam::channel;
use std::{sync::{atomic::{Ordering, AtomicU64}, Arc}};
use crate::{
beggar_pool::BeggarPool,
sudoku::Sudoku,
worker,
helpers::Res
};
pub struct Pool<T>
where T: Clone
{
beggar_pool: BeggarPool<T>,
success_rx: channel::Receiver<T>,
total_ops: Ar... |
fn find_value_after_2017(init_val: usize, repeat: usize, steps: usize) -> usize {
let mut buffer = Vec::with_capacity(repeat + 1);
buffer.push(init_val);
let mut curr_pos = 0;
for i in 1..repeat + 1 {
curr_pos = (curr_pos + steps) % buffer.len() + 1;
buffer.insert(curr_pos, i);
}
... |
pub trait Rng {
fn next_u32(&mut self) -> u32;
fn next_u64(&mut self) -> u64;
}
pub struct ThreadRng {
seed : u32
}
pub fn thread_rng() -> ThreadRng {
ThreadRng { seed: 0u32 }
}
impl Rng for ThreadRng {
fn next_u32(&mut self) -> u32 {
self.seed += 1u32;
return self.seed;
}
... |
//
// Copyright 2023 The Project Oak Authors
//
// 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 o... |
use lazy_static::lazy_static;
use spin::Mutex;
use uart_16550::SerialPort;
lazy_static! {
pub static ref UART1: Mutex<SerialPort> = {
let mut uart = unsafe { SerialPort::new(0x3F8) };
uart.init();
Mutex::new(uart)
};
}
#[doc(hidden)]
pub fn _print(args: ::core::fmt::Arguments) {
us... |
use super::Stream;
use super::packet::Packet;
/// Translates a string into a stream of packets to be used for local processing and handling
pub fn stream_from_raw(raw: &str) -> Stream {
let mut fin = Stream::new();
let mut data_chunks = raw.split(';');
for i in data_chunks.next() {
match i {
... |
use anyhow::Context;
// Example to listen on port 8080 locally, forwarding to port 80 in the example pod.
// Similar to `kubectl port-forward pod/example 8080:80`.
use futures::{StreamExt, TryStreamExt};
use std::net::SocketAddr;
use tokio::{
io::{AsyncRead, AsyncWrite},
net::TcpListener,
};
use tokio_stream::w... |
pub use self::context::*;
use crate::arch::paging::get_root_page_table_ptr;
use crate::drivers::DRIVERS;
use log::*;
use mips::addr::*;
use mips::interrupts;
use mips::paging::{
PageTable as MIPSPageTable, PageTableEntry, PageTableFlags as EF, TwoLevelPageTable,
};
use mips::registers::cp0;
use mips::tlb;
#[path =... |
use slog::Logger;
use std::process::{Child, Command};
use std::io::{Read, Write};
use std::marker::PhantomData;
use supported_languages::SupportedLanguage;
use neovim::NeovimRPCEvent;
use requests::*;
use futures::{Async, Future, Poll};
use futures::stream::{Stream, BoxStream, Filter, empty};
use std::sync::mpsc;
use s... |
//! Extension traits for `Bytes` and `BytesMut` which support Minecraft types.
use bytes::buf::{Buf, BufExt, BufMut};
use serde::de::DeserializeOwned;
use serde::Serialize;
use std::io::Read;
use std::ops::Deref;
use thiserror::Error;
use uuid::Uuid;
#[derive(Error, Debug)]
pub enum Error {
#[error("Not enough byt... |
use anyhow::Error;
use postgres_query::FromSqlRow;
use serde::{Deserialize, Serialize};
use stack_string::{format_sstr, StackString};
use std::{
collections::HashMap,
fmt::{self, Debug},
};
use time::{Duration, OffsetDateTime};
use uuid::Uuid;
use gdrive_lib::date_time_wrapper::DateTimeWrapper;
use crate::{co... |
// region: lmake_md_to_doc_comments include README.md A //!
//! # rust_wasm_dodrio_router
//!
//! **wasm router for local hash routes for dodrio vdom**
//! ***[repo](https://github.com/bestia-dev/rust_wasm_dodrio_router); version: 0.5.2 date: 2021-01-13 authors: bestia.dev***
//!
//! []
pub enum Mandaic {
/// \u{840}: 'ࡀ'
LetterHalqa,
/// \u{841}: 'ࡁ'
LetterAb,
/// \u{842}: 'ࡂ'
LetterAg,
/// \u{843}: 'ࡃ'
LetterAd,
/// \u{844}: 'ࡄ'
LetterAh,
/// \... |
/**
* Copyright (c) 2020 Ayush Kumar Mishra
*
* This source code is licensed under the MIT License found in
* the LICENSE file in the root directory of this source tree.
*/
extern crate proc_macro;
use proc_macro::{TokenStream, TokenTree};
/// This attribute will enable a function to access the caller's source lo... |
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT license.
*/
#![warn(missing_debug_implementations, missing_docs)]
//! In-memory graph
use std::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard};
use crate::common::ANNError;
use super::VertexAndNeighbors;
/// The entire gra... |
use quote::quote_spanned;
use syn::parse_quote_spanned;
use super::{
make_missing_runtime_msg, FlowProperties, FlowPropertyVal, OperatorCategory,
OperatorConstraints, OperatorWriteOutput, WriteContextArgs, RANGE_0, RANGE_1,
};
use crate::graph::OperatorInstance;
/// > 0 input streams, 1 output stream
///
/// ... |
use crate::color::{color, Color};
use crate::texture::{perlin::Perlin, Texture, TextureColor};
use crate::vec::Vec3;
// TurbulenceTexture
#[derive(Debug, Clone)]
pub struct TurbulenceTexture {
pub noise: Perlin,
pub scale: f64,
}
impl TurbulenceTexture {
pub fn new(seed: u64, scale: f64) -> Texture {
... |
use std::collections::HashMap;
use pretty_assertions::assert_eq;
use sudo_test::{Command, Env, User};
use crate::{
helpers, Result, SUDOERS_ROOT_ALL_NOPASSWD, SUDO_ENV_DEFAULT_PATH, SUDO_ENV_DEFAULT_TERM,
USERNAME,
};
// NOTE if 'env_reset' is not in `/etc/sudoers` it is enabled by default
// see 'environme... |
#![no_std]
#![no_main]
#![feature(alloc_error_handler)]
extern crate alloc;
extern crate chess_engine;
extern crate embedded_hal;
extern crate hd44780_driver;
extern crate numtoa;
extern crate stellaris_launchpad;
extern crate tm4c123x_hal;
use chess_engine::*;
use embedded_hal::blocking::delay::DelayMs;
use embedded... |
use std::collections::HashMap;
use std::io::{self, BufRead};
enum MaskBit { MaskZero, MaskOne, MaskBlank }
struct Mask { mask_bits : Vec<MaskBit> }
struct Write { address : u64, value : u64 }
enum ProgramLine { ProgramMask(Mask), ProgramWrite(Write) }
fn parse_mask(mask : &str) -> Mask {
Mask { mask_bits: mask
... |
use std::io::Read;
use rocket::{Data, Outcome, Request};
use rocket::data::{self, FromDataSimple};
use rocket::http::Status;
use rocket::outcome::Outcome::{Failure, Success};
use rocket::request::FromRequest;
use sha2::{Digest, Sha256};
use crate::mongodb::db::ThreadedDatabase;
use crate::user::token::decode_token;
u... |
use crate::libs::color::Pallet;
use std::rc::Rc;
#[derive(Clone)]
pub struct Tag {
name: Rc<String>,
color: Pallet,
}
impl Tag {
pub fn new() -> Self {
Self {
name: Rc::new(String::from("")),
color: Pallet::blue(5).a(100),
}
}
pub fn name(&self) -> &String ... |
#[doc = "Register `RCC_MC_AHB2ENSETR` reader"]
pub type R = crate::R<RCC_MC_AHB2ENSETR_SPEC>;
#[doc = "Register `RCC_MC_AHB2ENSETR` writer"]
pub type W = crate::W<RCC_MC_AHB2ENSETR_SPEC>;
#[doc = "Field `DMA1EN` reader - DMA1EN"]
pub type DMA1EN_R = crate::BitReader;
#[doc = "Field `DMA1EN` writer - DMA1EN"]
pub type D... |
use crate::format::problem::*;
use crate::format::solution::*;
use crate::helpers::*;
#[test]
fn can_limit_by_max_distance() {
let problem = Problem {
plan: Plan { jobs: vec![create_delivery_job("job1", vec![100., 0.])], relations: Option::None },
fleet: Fleet {
vehicles: vec![VehicleTy... |
use std::io::{Error, ErrorKind, Read, Result};
pub struct Chars<R> {
inner: R,
}
pub trait ReadChars {
fn chars(&mut self) -> Chars<&mut Self>;
}
impl<R: Read> ReadChars for R {
fn chars(&mut self) -> Chars<&mut Self> {
Chars { inner: self }
}
}
fn read_one_byte(reader: &mut dyn Read) -> Opti... |
use super::atom::{btn::Btn, fa, text::Text};
use super::molecule::tab_menu::{self, TabMenu};
use super::organism::{
component_list::{self, ComponentList},
scene_list::{self, SceneList},
};
use crate::arena::{block, ArenaMut, BlockMut};
use crate::libs::random_id::U128Id;
use isaribi::{
style,
styled::{S... |
// Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the root directory of this source tree.
use super::{Assertion, ConstraintDivisor};
use math::{fft, polynom, FieldElement, StarkField};
use utils::collections::{HashMap, Vec};
#[... |
macro_rules! transform {
() => {
};
}
fn main() {
transform!();
}
fn add(left:i32, right: i32) -> i32 {
left + right
}
#[cfg(test)]
/// Creates and runs test cases on the add method.
macro_rules! test_add {
($name:ident: $value:expr) => {
#[test]
fn $name() {
... |
// --------------------------------------------------------------------------
//
// Rusty Kong
// Copyright (C) 2018 Jeff Panici
// All rights reserved.
//
// This software source file is licensed according to the
// MIT License. Refer to the LICENSE file distributed along
// with this source file to learn more.
//
//... |
pub fn string_result_with_prefix <
Type,
PrefixFunction: FnOnce () -> String,
> (
prefix_function: PrefixFunction,
result: Result <Type, String>,
) -> Result <Type, String> {
result.map_err (
|string_error|
format! (
"{}{}",
prefix_function (),
string_error)
)
}
// ex: noet ts=4 filetype=rust
|
#[cfg(target_arch = "x86")]
use core::arch::x86::*;
#[cfg(target_arch = "x86_64")]
use core::arch::x86_64::*;
use super::BLAKE2B_IV;
// #[cfg(target_feature = "sse2")]
// // #[cfg(all(not(target_feature = "sse4.1"), target_feature = "sse2"))]
// #[path = "./sse2.rs"]
// mod feature;
// #[cfg(target_feature = "sse4.1... |
use ratatui::{
backend::Backend,
layout::{Constraint, Direction, Rect},
terminal::Frame,
};
use crate::display::{HeaderDetails, HelpText, Table};
const FIRST_HEIGHT_BREAKPOINT: u16 = 30;
const FIRST_WIDTH_BREAKPOINT: u16 = 120;
fn top_app_and_bottom_split(rect: Rect) -> (Rect, Rect, Rect) {
let parts... |
#![feature(test)]
extern crate test;
extern crate grcov;
use std::path::Path;
use std::fs::File;
use std::io::BufReader;
use test::{black_box, Bencher};
#[bench]
fn bench_parser_lcov(b: &mut Bencher) {
let f = File::open("./test/prova.info").expect("Failed to open lcov file");
b.iter(|| {
let file = B... |
extern crate flatten_json;
#[macro_use]
extern crate serde_json;
#[macro_use]
extern crate error_chain;
extern crate serde;
#[macro_use]
extern crate serde_derive;
#[macro_use]
extern crate log;
use serde_json::Value;
use std::io::{self, Write};
use flatten_json::flatten;
error_chain! {
foreign_links {
Json(... |
#![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 ApplyUpdateProperties {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub status: Option<apply... |
use futures::io::BufReader;
use futures::prelude::*;
use simple_irc::Message;
use crate::config::Server;
use crate::ctcp::{CtcpEvent, CtcpRequest};
use crate::irc_ext::IrcExt;
use crate::irc_state::IrcState;
use crate::privmsg::{PrivMsgEvent, PrivMsgRequest};
pub struct IrcHandler<'a> {
pub server: &'a mut Server... |
extern crate minigrep;
use minigrep::*;
use std::env::args;
use std::process::exit;
fn main() {
let mut env_args = args().collect();
let grep_config = config::Config::new(&mut env_args).unwrap_or_else(|err| {
eprintln!("Argument error: {}", err);
exit(1);
});
let result = logic::run_g... |
use crate::rvals::SteelVal;
use std::ops::Deref;
use std::ops::RangeFrom;
pub type StackFrame = Stack<SteelVal>;
#[derive(Debug, Clone)]
pub struct Stack<T>(pub(crate) Vec<T>);
impl<T> Stack<T> {
// #[inline(always)]
pub fn new() -> Stack<T> {
Stack(Vec::new())
}
pub fn with_capacity(capacit... |
extern crate elevator;
extern crate floating_duration;
use elevator::buildings::{Building, Building1, Building2, Building3, getCumulativeFloorHeight};
use elevator::trip_planning::{FloorRequests, RequestQueue};
use elevator::physics::{ElevatorState, simulate_elevator};
use elevator::motion_controllers::{SmoothMotionCo... |
use nom::sequence::{preceded, terminated};
use nom::IResult;
pub fn surrounded<T, U, V, I, O, O1, O2>(
left_parser: T,
inner: U,
right_parser: V,
) -> impl Fn(I) -> IResult<I, O>
where
T: Fn(I) -> IResult<I, O1>,
U: Fn(I) -> IResult<I, O>,
V: Fn(I) -> IResult<I, O2>,
{
return preceded(left_... |
extern crate regex;
use regex::Regex;
fn change(s: &str, prog: &str, version: &str) -> String {
let mut data: Vec<String> = s.split("\n").into_iter().map({ |e| e.to_string() }).collect();
data[0] = format!("Program: {}", prog);
data[1] = format!("Author: g964");
data[4] = format!("Date: 2019-01-0... |
/*
chapter 4
syntax and semantics
*/
struct Circle {
h: f64,
v: f64,
radius: f64,
}
impl Circle {
/*
fn reference(&self) {
println!("taking self by reference!");
}
*/
fn mutable_reference(&mut self) {
println!("taking self by mutable reference!");
}
/*
... |
/*
* 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
*/
/// SyntheticsBrowserError : Error response object for a browser test.
#[derive(Clone, Debug, Partial... |
use futures::{FutureExt, StreamExt};
use parity_scale_codec::{Decode, Encode};
use parking_lot::{Mutex, RwLock};
use sc_network::config::NonDefaultSetConfig;
use sc_network::PeerId;
use sc_network_gossip::{
GossipEngine, MessageIntent, Syncing as GossipSyncing, ValidationResult, Validator,
ValidatorContext,
};
... |
// Copyright 2017 Dmitry Tantsur <divius.inside@gmail.com>
//
// 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 ap... |
use super::super::*;
use math::*;
use std::collections::HashSet;
#[derive(Clone)]
pub struct StateData {
pub delta_time: f32,
pub frame_dimensions: Vec2<f32>,
pub scaled_frame_dimensions: Vec2<f32>,
pub window_dimensions: Vec2<f32>,
pub aspect_ratio: f32,
pub mouse_position: Vec2<f32>,
pub... |
use futures::executor::block_on_stream;
use futures::stream;
use futures::task::Poll;
use futures::Stream;
pub fn fn_stream() -> impl Stream<Item = usize> {
let mut counter: usize = 2;
stream::poll_fn(move |_| -> Poll<Option<usize>> {
if counter == 0 {
return Poll::Ready(None);
}
... |
use std::fs::File;
use std::io::{Write, Read};
use std::path::Path;
use std::fs;
use std::time;
use super::folder::Folder;
use media::{Item, Container, MediaType, Stream, StreamType, Thumbnail, mediaparser};
use tools::{NameValuePair, XMLParser, XMLEntry, Logger, LogLevel};
/// # DatabaseManager
///
/// This structu... |
use super::{
Typeck
};
use stmt::Statement;
#[derive(Debug, Clone)]
pub struct Module{
pub ident: String,
pub statements: Vec<Statement>,
}
impl<'a> super::Check<'a> for Module{
fn check(&self, typeck: &'a Typeck) -> Result<(), ()> {
for statement in self.statements.iter(){
if let... |
//! Common code for Posix-ish and Windows platforms for implementing
//! [`ReadAt`] and [`WriteAt`] for file-like types which implement
//! [`AsUnsafeFile`].
//!
//! [`WriteAt`]: crate::WriteAt
use crate::{
borrow_streamer::{BorrowStreamer, BorrowStreamerMut},
Advice, ReadAt,
};
use std::{
fs,
io::{sel... |
table! {
design (id) {
id -> Integer,
title -> Varchar,
}
}
|
use crate::{
primitive_values::primitive_base::PrimitiveValueBase,
utils::Ops,
};
#[derive(Clone, Debug, PartialEq)]
pub struct Token {
pub ast_type: Ops,
pub value: String,
pub line: usize,
}
impl Token {
pub fn new(ast_type: Ops, value: String, line: usize) -> Self {
Self {
... |
//! Chain specification for the test runtime.
use crate::domain_chain_spec::testnet_evm_genesis;
use sc_chain_spec::ChainType;
use sp_core::{sr25519, Pair, Public};
use sp_domains::{GenesisDomain, OperatorPublicKey, RuntimeType};
use sp_runtime::traits::{IdentifyAccount, Verify};
use sp_runtime::Percent;
use subspace_... |
extern crate cursive;
use cursive::Cursive;
use cursive::menu::MenuTree;
use cursive::view::Dialog;
use cursive::view::TextView;
use cursive::event::Key;
fn main() {
let mut siv = Cursive::new();
siv.menubar()
.add("File",
MenuTree::new()
.leaf("New", |s| s.add_layer(Dialo... |
use super::Error;
use super::{request::Request, Requests};
use crate::data::MealPlans;
use oikos_api::components::schemas::ShoppingList;
use yew::callback::Callback;
#[derive(Default, Debug)]
pub struct MealPlansService {
requests: Requests,
pub get_meal_plans: Request,
pub get_shopping_list: Request,
... |
#[cfg(target_os = "macos")]
fn are_you_on_macos() {
println!("You are running macos!")
}
#[cfg(not(target_os = "macos"))]
fn are_you_on_macos() {
println!("You are *not* running macos!")
}
fn main() {
are_you_on_macos();
println!("Are you sure?");
if cfg!(target_os = "macos") {
println!(... |
use super::{Pusherator, PusheratorBuild};
pub struct Pivot<I, P>
where
I: Iterator,
P: Pusherator<Item = I::Item>,
{
pull: I,
push: P,
}
impl<I, P> Pivot<I, P>
where
I: Iterator,
P: Pusherator<Item = I::Item>,
{
pub fn new(pull: I, push: P) -> Self {
Self { pull, push }
}
p... |
// In order to be able to reset an io node, the node needs to hold
// the information about the reader
// TODO all nodes need a rest. But nodes that hold state don't need
// to call reset on the input node.
use csv::{ReaderBuilder, StringRecordsIntoIter};
use std::fs::File;
// TODO change Schema to ColumnTypes?
use Sc... |
use num_traits::PrimInt;
use std::iter::Product;
// See https://rosettacode.org/wiki/Chinese_remainder_theorem#Rust
pub fn extended_euclidean<T: PrimInt>(a: T, b: T) -> (T, T, T) {
if a.is_zero() {
(b, T::zero(), T::one())
} else {
let (gcd, x, y) = extended_euclidean(b % a, a);
(gcd, y... |
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - Interrupt status register"]
pub isr: ISR,
#[doc = "0x04 - Interrupt flag clear register"]
pub ifcr: IFCR,
#[doc = "0x08..0xa8 - Channel cluster: CCR?, CNDTR?, CPAR?, CM0AR? and CM1AR registers?"]
pub ch: [CH; 8],
}
... |
pub mod sleeper;
pub mod instant;
pub mod delayed;
pub mod instant_series;
pub mod delayed_series;
pub mod buffered;
|
extern crate tokio_service;
extern crate tokio_proto;
extern crate tokio_minihttp;
extern crate futures;
extern crate num_cpus;
extern crate serde_json;
use futures::future;
use tokio_service::Service;
use tokio_proto::TcpServer;
use tokio_minihttp::{Request, Response, Http};
use serde_json::builder::ObjectBuilder;
s... |
use super::Value;
pub trait Index {
#[doc(hidden)]
fn index_into<'v>(&self, v: &'v Value) -> Option<&'v Value>;
}
impl Index for usize {
fn index_into<'v>(&self, v: &'v Value) -> Option<&'v Value> {
match *v {
Value::Array(ref vec) => vec.get(*self),
_ => None,
}
... |
pub mod system;
pub use system::*;
pub mod parachain_system;
pub use parachain_system::*;
pub mod randomness_collective_flip;
pub use randomness_collective_flip::*;
pub mod timestamp;
pub use timestamp::*;
pub mod parachain_info_;
pub use parachain_info_::*;
pub mod balances;
pub use balances::*;
pub mod transact... |
// Copyright 2018 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 async::TimeoutExt;
use device_watch::{self, NewIfaceDevice};
use failure::Error;
use fidl_mlme::{self, DeviceQueryConfirm, MlmeEventStream};
use future... |
use lase::Dac;
use lase::Point;
use lase::tools::ETHERDREAM_COLOR_MAX;
use lase::tools::ETHERDREAM_X_MAX;
use lase::tools::ETHERDREAM_X_MIN;
use lase::tools::ETHERDREAM_Y_MAX;
use lase::tools::ETHERDREAM_Y_MIN;
use lase::tools::find_first_etherdream_dac;
use std::f64::consts::PI;
use std::f64;
use std::sync::Arc;
use ... |
extern crate lbasi;
use lbasi::*;
use std::io;
use std::io::Write;
fn main() {
loop {
print!("calc > ");
io::stdout().flush().unwrap();
// read the user input
let mut input = String::new();
io::stdin().read_line(&mut input).unwrap();
if input == "exit" || input... |
use crate::data::Client;
use std::sync::Arc;
use std::vec::Vec;
#[derive(Debug)]
pub enum ReplicationRole {
Primary,
Replica,
Confused,
}
#[derive(Debug)]
pub struct ReplicationNode {
client: Arc<Client>,
}
#[derive(Debug)]
pub struct ReplicationConfig {
role: ReplicationRole,
replicas: Vec<... |
extern crate rand;
extern crate num_complex;
extern crate rulinalg;
use std::fmt;
use std::ops::{Sub, Div};
use self::rand::Rng;
use lattice::Site;
use std::cell::RefCell;
use lattice::{Lattice, Spin};
use std::f64;
use plot::CartesianPoint;
use models::{Model, Observables, StateChange};
use std::rc::Rc;
use self::num... |
use std::io;
fn main() {
let mut input = String::new();
io::stdin().read_line(&mut input).unwrap();
let input: Vec<u32> = input.trim().chars().map(|x| x.to_digit(10).unwrap()).collect();
let output: u32 = input.iter().enumerate()
.filter(|&x| *x.1==input[(x.0 + 1) % input.len()])
.map(|x| *x.1)
.... |
use coinbase_pro_rs::{structs::wsfeed::*, WSFeed, WS_SANDBOX_URL};
use futures::{StreamExt, TryStreamExt};
#[tokio::main]
async fn main() {
let stream = WSFeed::connect(WS_SANDBOX_URL, &["BTC-USD"], &[ChannelType::Heartbeat])
.await
.unwrap();
stream
.take(10)
.try_for_each(|ms... |
use {
askama::Template,
http::{header::CONTENT_TYPE, StatusCode},
tsukuyomi::{
endpoint,
test::{self, loc, TestServer},
App, Responder,
},
};
#[test]
fn test_version_sync() {
version_sync::assert_html_root_url_updated!("src/lib.rs");
}
#[test]
fn test_template_derivation() ... |
use std::thread;
use std::time::Duration;
fn main() {
thread::spawn(|| {
for i in 1..10 {
println!("hi number {} from the spawned thread: {:?}!", i, thread::current().id());
thread::sleep(Duration::from_secs(2));
}
});
thread::spawn(|| {
for i in 1..10 {
... |
use crate::plan::Plan;
use crate::policy::space::SFTMap;
use crate::scheduler::Scheduler;
use crate::util::finalizable_processor::FinalizableProcessor;
use crate::util::heap::layout::heap_layout::Mmapper;
use crate::util::heap::layout::heap_layout::VMMap;
use crate::util::heap::layout::map::Map;
use crate::util::option... |
use rand::Rng;
use rnp::{
PingClientConfig, PingResultProcessorCommonConfig, PingResultProcessorConfig, PingWorkerConfig, PingWorkerSchedulerConfig, PortRangeList,
RnpPingConfig, RnpSupportedProtocol,
};
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
use std::path::PathBuf;
use std::str::FromStr;
use s... |
//! Repo for user_address table. UserAddress is an entity that connects
//! users and roles. I.e. this table is for user has-many roles
//! relationship
use diesel;
use diesel::connection::AnsiTransactionManager;
use diesel::pg::Pg;
use diesel::prelude::*;
use diesel::query_dsl::RunQueryDsl;
use diesel::Connection;
us... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.