text stringlengths 8 4.13M |
|---|
extern crate derive_more;
use derive_more::Display;
use web3::Error as Web3Error;
#[derive(Debug, Display)]
pub enum Error {
/// invalid rpc url or service is unreachable
#[display(fmt = "server is unreachable")]
RpcUnreachable,
/// send tx failed
TxFailed,
/// invalid params value
#[displa... |
// This file was generated by gir (https://github.com/gtk-rs/gir)
// from gir-files (https://github.com/gtk-rs/gir-files)
// DO NOT EDIT
use ffi;
use glib::object::IsA;
use glib::translate::*;
use glib_ffi;
use gobject_ffi;
use std::mem;
use std::ptr;
glib_wrapper! {
pub struct HitTestResult(Object<ffi::WebKitHit... |
use proc_macro::TokenStream;
use quote::quote;
use std::env;
use syn::parse::{Parse, ParseStream, Result};
use syn::{parse_macro_input, LitStr};
struct Input {
contents: LitStr,
}
impl Parse for Input {
fn parse(input: ParseStream<'_>) -> Result<Self> {
let contents = input.parse()?;
Ok(Self {... |
use bevy::input::keyboard::KeyboardInput;
use bevy::input::ElementState;
use bevy::prelude::*;
use bitmask_enum::bitmask;
use static_init::dynamic;
use std::collections::{HashMap, HashSet};
use crate::platform::Platform;
pub struct Player {
velocity: Vec3,
state: PlayerState,
}
#[bitmask(u8)]
pub enum Player... |
extern crate amethyst;
#[macro_use]
extern crate serde;
extern crate ron;
#[macro_use]
extern crate log;
//extern crate crossterm;
extern crate dirty;
extern crate fern;
extern crate partial_function;
extern crate rand;
use rand::{thread_rng, Rng};
use amethyst::animation::AnimationBundle;
use amethyst::assets::{Asse... |
use std::io;
use mio::*;
use mio::tcp::{TcpListener, TcpStream};
use std::collections::HashMap;
use client::WebSocketClient;
//
// config
//
pub const SERVER: Token = Token(0);
//
// server
//
pub struct WebSocketServer {
pub socket: TcpListener,
pub token_counter: usize,
pub clients: HashMap<Token, WebS... |
fn main() {
let (mut max, mut it, mut jt) = (0, 0, 0);
for i in 100..999 {
for j in 100..i{
if palindrome(i*j) {
if i*j > max {
max = i*j;
it = i;
jt = j;
}
}
}
}
println!(... |
use ntapi::ntrtl::{
RtlRbInsertNodeEx, RtlReleaseSRWLockExclusive, RtlTryAcquireSRWLockExclusive, RTL_RB_TREE,
};
use std::{ffi::c_void, io::Result, ops::{Deref, DerefMut}, ptr::null_mut};
use winapi::{
shared::{minwindef::DWORD, ntdef::PRTL_BALANCED_NODE},
um::{
handleapi::CloseHandle,
memo... |
#[doc = "Reader of register WF29"]
pub type R = crate::R<u8, super::WF29>;
#[doc = "Writer for register WF29"]
pub type W = crate::W<u8, super::WF29>;
#[doc = "Register WF29 `reset()`'s with value 0"]
impl crate::ResetValue for super::WF29 {
type Type = u8;
#[inline(always)]
fn reset_value() -> Self::Type {... |
use crate::error::Error;
pub(crate) fn cd(command: &[String]) -> crate::Result<u8> {
match command.len() {
1 => Err(Error::OtherError("cd requires 1 parameter with the path to change into".to_owned())),
2 => {
let mut path = command[1].clone();
if let Some(index) = path.find('~') {
path.replace_range(in... |
use crate::read;
fn clean(file_data: &String) -> [u64; 9] {
let mut fish_arr = [0; 9];
file_data.split(",")
.map(|temp_num| temp_num.parse::<u8>().unwrap())
.for_each(|temp_num| {
fish_arr[temp_num as usize] += 1;
});
return fish_arr;
}
fn days(day_loop: u16, data_clean: &[u64; 9]) -> u64 {
let mut fish_... |
/// Box an object.
macro_rules! bx {
($ex:expr) => {
Box::new($ex)
};
}
/// Rc an object.
macro_rules! rc {
($ex:expr) => {
Rc::new($ex)
};
}
/// RefCell an object.
macro_rules! cell {
($ex:expr) => {
RefCell::new($ex)
};
}
/// Rc::new(RefCell::new(X))
macro_rules! rce... |
#![feature(proc_macro_hygiene, decl_macro)]
#[macro_use]
extern crate rocket;
use rocket_contrib::json::Json;
use serde::Serialize;
#[derive(Serialize)]
struct Status {
pub clans: Vec<String>,
pub prize_pool: u64,
}
#[get("/")]
fn index() -> Json<Status> {
Json(Status {
clans: vec![
... |
use std;
error_chain! {
types {
Error, ErrorKind, ResultExt;
}
foreign_links {
Io(std::io::Error);
FromUtf8(std::string::FromUtf8Error);
TryFromIntError(std::num::TryFromIntError);
CharTryFromError(std::char::CharTryFromError);
UuidParseError(::uuid::ParseE... |
#![no_std]
#![no_main]
use punda::serial;
punda::punda!(init = init);
fn init(cx: &mut punda::context::InitContext) {
serial::println(cx, "Hello, world!".into());
}
|
use std::f64::consts::PI;
use gtk::{DrawingArea, Inhibit, cairo::{FontSlant, FontWeight}, prelude::{ContainerExt, WidgetExt}};
const MARGIN: i32 = 5;
pub struct DrawingAreaBox {
pub _box: gtk::Box,
}
impl DrawingAreaBox {
pub fn new() -> Self {
let _box = gtk::Box::new(gtk::Orientation::Vertical, MAR... |
#[no_mangle]
extern "C" fn malloc(_: usize) -> *mut std::ffi::c_void {
//~^ HELP: the `malloc` symbol is defined here
unreachable!()
}
fn main() {
extern "C" {
fn malloc(_: usize) -> *mut std::ffi::c_void;
}
unsafe {
malloc(0);
//~^ ERROR: found `malloc` symbol definition th... |
use axgeom::Rect;
use dinotree_alg::Num;
use std::cmp::Ordering;
pub struct Counter(usize);
pub fn from_rect<I: Num>(counter: &mut Counter, rect: Rect<I>) -> Rect<DataNum<I>> {
let ((a, b), (c, d)) = rect.get();
Rect::new(
counter.new_num(a),
counter.new_num(b),
counter.new_num(c),
... |
pub fn is_id_start(c: char) -> bool {
c.is_ascii_alphabetic() || c == '_' || c == '@'
}
pub fn is_hex_signifier(c: char) -> bool {
c == '$'
}
pub fn is_bin_signifier(c: char) -> bool {
c == '%'
}
pub fn is_dec_signifier(c: char) -> bool {
c.is_digit(10)
}
pub fn is_num_signifier(c: char) -> bool {
is_hex_... |
use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
use std::fs::File;
use std::io::{Cursor, Read, Write};
use std::path::Path;
use crate::chunk::Chunk;
use crate::{Error, Result};
/// A BEAM File
///
/// ```
/// use beam_file::BeamFile;
/// use beam_file::chunk::{Chunk, RawChunk};
///
/// let beam = BeamFile::<... |
use std::io::{ErrorKind, Read, Write};
use std::net::{SocketAddr, TcpListener};
pub fn tcp_server_std(addr: SocketAddr) {
println!(
"\n\
RUN TCP SERVER: STD ==================\n\
address: {}\n\
======================================\n",
addr
);
let listener = TcpLis... |
mod no_wrap;
mod match_error;
extern crate proc_macro;
use quote::{ToTokens, quote, quote_spanned};
use syn::{Arm, Expr, ExprPath, Ident, braced, parenthesized, parse::{Parse, ParseStream, Parser}, punctuated::Punctuated};
struct Syscall();
impl Syscall {
fn parse(stream: ParseStream<'_>) -> syn::Result<proc_macro2... |
// This file is part of Substrate.
// Copyright (C) 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 Free Softwa... |
// Copyright (c) The Starcoin Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::{TaskError, TaskEventHandle};
use anyhow::{Error, Result};
use async_std::task::JoinHandle;
use futures::channel::mpsc::{channel, Sender};
use futures::task::{Context, Poll};
use futures::{Sink, StreamExt};
use log::debug... |
//! This module is a gnarly hack around the fact opentelemetry doesn't currently let you
//! register an observer multiple times with the same name
//!
//! See <https://github.com/open-telemetry/opentelemetry-rust/issues/541>
use std::collections::hash_map::Entry;
use std::collections::HashMap;
use std::sync::Arc;
us... |
use std::io::Cursor;
use rocket::http::Status;
use rocket::Response;
use crate::core::esi::ESIError;
use crate::core::sse::SSEError;
use crate::{core::auth::AuthorizationError, data::skills::SkillsError};
use eve_data_core::{FitError, TypeError};
#[derive(thiserror::Error, Debug)]
pub enum Madness {
#[error("da... |
use std::fmt;
use std::fs::DirEntry;
/// Wrapper struct around [`std::fs::DirEntry`]
///
/// This wrapper is used to display files when listing directories. The display
/// trait [`fmt::Display`] will represent the file as a HTML link to the file
/// with the corresponding file or folder name.
pub struct File(pub DirE... |
extern crate futures;
extern crate grpc;
extern crate grpc_protobuf;
extern crate protobuf;
#[macro_use]
extern crate log;
// Skip formatting the two modules because they are generated by grpc framework.
#[rustfmt::skip]
pub mod occlum_exec;
#[rustfmt::skip]
pub mod occlum_exec_grpc;
pub mod server;
pub const DEFAUL... |
use crate::lex::Lexer;
use crate::parse::parser::parse;
use crate::untyped_ast::build_untyped_ast;
use crate::untyped_ast::types::TopStatement;
use crate::untyped_ast::types::Type;
use crate::untyped_ast::types::{BaseType, Root};
#[test]
fn test_forward_declaration() {
let text = "int a(int arg); int b(int, int a2... |
//! Common types used across the crate, including file blocking data
extern crate nix;
use nix::libc::{O_RDWR, O_WRONLY};
use std::fmt;
use std::path::PathBuf;
/// `open` mode to block
#[derive(PartialEq, Debug, Clone)]
pub enum OpenType {
Read,
Write,
All,
}
impl fmt::Display for OpenType {
fn fmt(... |
use itertools::Itertools;
use regex::Regex;
use crate::utils::string_from_file;
pub fn run() {
let input = string_from_file("src/04input");
println!("{}", solve(input));
}
pub fn solve(input: String) -> usize {
input.split("\n\n").map(|p| {
let l = p.lines().join(" ");
println!("{}", l);... |
use std::fmt::Debug;
use std::marker::PhantomData;
use std::slice::{Iter, IterMut};
use std::ops::{Index, IndexMut};
use std::collections::HashMap;
use crate::opt::int::IntUtils;
use crate::opt::str::StrUtils;
use crate::opt::uint::UintUtils;
use crate::opt::flt::FltUtils;
use crate::opt::array::ArrayUtils;
use crate:... |
//!
//! # Describe Template
//!
//! Describe object boilerplate behind a trait.
//!
use serde::Serialize;
use crate::error::CliError;
use crate::common::{KeyValOutputHandler, TableOutputHandler};
// -----------------------------------
// Data Structures
// -----------------------------------
#[derive(Serialize, De... |
//! The `Chunk` trait and implementations of commonly used chunks.
//!
//! # Reference
//! - [BEAM File Format][BEAM]
//! - [`beam_lib`](http://erlang.org/doc/man/beam_lib.html)
//!
//! [BEAM]: http://rnyingma.synrc.com/publications/cat/Functional%20Languages/Erlang/BEAM.pdf
use byteorder::{BigEndian, ReadBytesExt, Wri... |
use super::common::Primes;
fn highest_pow_under(i: u64, under: u64) -> u64 {
let power = (under as f64).log(i as f64).floor();
i.pow(power as u32)
}
pub fn solve(up_to: u64) -> u64 {
Primes::new()
.take_while(|&p| p <= up_to)
.map(|i| highest_pow_under(i, up_to))
.product()
}
#[cf... |
use std::net::SocketAddr;
use ed25519_dalek::Keypair as Ed25519Keypair;
use eui48::MacAddress;
use rand::{rngs::OsRng, Rng};
use serde::{Deserialize, Serialize};
use crate::{accessory::AccessoryCategory, BonjourFeatureFlag, BonjourStatusFlag, Pin};
/// The `Config` struct is used to store configuration options for t... |
use std::{cmp::Reverse, collections::BinaryHeap};
use async_trait::async_trait;
use super::{
iterator::{Entry, Iterator},
Timestamp,
};
use crate::error::Result;
pub struct MergingIterator {
heap: BinaryHeap<Reverse<Box<dyn Iterator>>>,
}
impl MergingIterator {
pub fn new(children: Vec<Box<dyn Itera... |
use crate::db::{DatabaseImpl, Diagnostics};
use errors::FileDatabase;
use parser::{dump_debug, ParseDatabase};
use semant::HirDatabase;
use std::fs::File;
use std::io::{self, Write};
use std::path::PathBuf;
use structopt::StructOpt;
#[derive(StructOpt, Debug)]
#[structopt(name = "tox")]
pub struct Cli {
/// The so... |
use std::f64;
use std::time::Instant;
fn main() {
let mut n = 0; // Starting at 100^0 (gets 1 digit)
loop {
let start_time = Instant::now();
let m1: f64 = f64::MIN_POSITIVE; // Mass of first (small) block
let m2 = (100.0f64).powi(n) * m1; // mass of second (large) block
let mut ... |
use std::mem;
const MOL:u8 = 42; // no fixed address
static mol:i32 = 123;
static mut mol1:i32 = 123;
fn scope_and_shadowing() {
let a = 123;
{
let b = 10;
println!("inside, b = {}", b);
println!("inside, a = {}", a);
let a = b + 10;
println!("inside1, a = {}", a);
... |
extern crate tcod;
extern crate verbonia;
use verbonia::gui::{Console, GUI};
use verbonia::engine::Game;
use verbonia::util::units::Size;
fn main() {
let game = Game::new();
let console = Console::new(Size::new(80, 50));
let mut gui = GUI::new(game, console);
gui.run();
}
|
pub mod kafka_tpcc_source;
pub mod kafka_merchant_source;
|
//
//! Copyright 2020 Alibaba Group Holding Limited.
//!
//! 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 ... |
extern crate colored;
use std::net::UdpSocket;
use std::thread::sleep;
use std::time;
use colored::Colorize;
use std::io;
use std::io::Write;
fn main() {
println!("{}","
###########################################################################
# UDPlant - UDP implant made by trickster0 ... |
use martlet_common::service::Service;
use martlet_proxy::service::mysql::MySQLService;
pub fn new_service() -> Box<&'static dyn Service> {
Box::new(&MySQLService {} as &Service)
} |
$NetBSD: patch-.._vendor_sys-info-0.7.0_lib.rs,v 1.1 2021/03/11 19:25:04 fox Exp $
Adds NetBSD support for sys-info crate.
This patch has been upstreamed. And will be removed once it is merged.
Upstream PR: https://github.com/FillZpp/sys-info-rs/pull/91
--- ../vendor/sys-info-0.7.0/lib.rs.orig 2021-03-10 06:17:13.8... |
//! Function to construct expressions
use std::collections::HashMap;
use crate::mutators::peephole::eggsy::encoder::TraversalEvent;
use crate::mutators::peephole::Lang;
use egg::{Id, Language, RecExpr};
/// Build RecExpr from tree information
pub fn build_expr<'a>(root: Id, id_to_lang: impl Fn(Id) -> &'a Lang) -> Rec... |
#[doc = "Register `T32MIS2` reader"]
pub struct R(crate::R<T32MIS2_SPEC>);
impl core::ops::Deref for R {
type Target = crate::R<T32MIS2_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<crate::R<T32MIS2_SPEC>> for R {
#[inline(always)]
fn from(reader: crat... |
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - Starts continuous PDM transfer"]
pub tasks_start: TASKS_START,
#[doc = "0x04 - Stops PDM transfer"]
pub tasks_stop: TASKS_STOP,
_reserved2: [u8; 0xf8],
#[doc = "0x100 - PDM transfer has started"]
pub events_star... |
use bitvec::prelude::*;
use commons::io::load_file_records;
use multimap::MultiMap;
use std::collections::{HashMap, HashSet, VecDeque};
#[derive(Debug, Clone)]
struct Tile {
id: u64,
rows: Vec<BitVec>,
}
impl Tile {
fn edges_and_flipped(&self) -> Vec<(BitVec, BitVec)> {
let unflipped = self.edges(... |
fn main () {
match x {
#[arm_outer]
0 => true,
}
}
fn expressions() {
#[box_outer]
box 1;
// #[inplace_outer]
// x <- 1;
#[vec_outer]
[ #![vec_inner] 1, 2, 3];
#[call_outer]
foo(1, 2, 3);
#[methodcall_outer]
x.foo(1, 2, 3);
#[tuple_outer]
( #![tuple_inner] 1, 2, 3);
#[tuple_out... |
// loop (infinite)
fn test1() {
let mut i = 0;
loop {
if i > 2 {
break;
}
i += 1;
}
assert_eq!(i, 3);
}
// loop returns a value
fn test2() {
let mut i = 0;
let ret_val = loop {
if i > 8 {
break i * 30;
}
i += 1;
};
... |
// Copyright (c) The cargo-guppy Contributors
// SPDX-License-Identifier: MIT OR Apache-2.0
pub mod summaries;
use crate::summaries::*;
use anyhow::{anyhow, bail, Result};
use clap::arg_enum;
use fixtures::json::JsonFixture;
use structopt::StructOpt;
#[derive(Debug, StructOpt)]
pub struct FixtureManager {
// TOD... |
use std::fs::File;
use std::io::ErrorKind;
use std::io::Read;
use std::io::Error;
// 错误处理
// 错误分为两类:可恢复和不可恢复
fn main() {
// 不可恢复,出现panic!时,程序默认会unwinding,即回溯栈并清理它遇到的每一个数据。
// 如果在Cargo.toml的 [profile] 中增加 panic = 'abort,则不清理数据,由操作系统来清理。
// panic!("crash and burn");
// 设置 RUST_BACKTRACE环境变量可得到完整错误栈,为得到... |
use serde::Deserialize;
use crate::{
bootstrap::JSLAND_SNAPSHOT,
ctx::{native_invoke_entry, NI_ENTRY_KEY},
registry::SymbolRegistry,
v8util::set_up_v8_globally,
};
use super::util::v8_deserialize;
pub struct ApiTester {
isolate: v8::OwnedIsolate,
global_ctx: v8::Global<v8::Context>,
}
fn ensure_init() {... |
#![cfg(feature = "run-docker-tests")]
#![feature(async_closure)]
#![feature(custom_test_frameworks)]
#![feature(test)]
#![test_runner(docker_tests_runner)]
#![feature(drain_filter)]
#![feature(hash_raw_entry)]
#![cfg(not(target_arch = "wasm32"))]
#[cfg(test)]
#[macro_use]
extern crate common;
#[cfg(test)]
#[macro_use]... |
/**
* [1721] Swapping Nodes in a Linked List
*
* You are given the head of a linked list, and an integer k.
Return the head of the linked list after swapping the values of the kth node from the beginning and the kth node from the end (the list is 1-indexed).
Example 1:
Input: head = [1,2,3,4,5], k = 2
Output: [1,4... |
#![feature(proc_macro_hygiene, decl_macro)]
#[macro_use] extern crate rocket;
#[cfg(test)] mod tests;
// FIXME: Declare a `GET /` route named `index` that returns `Hello, world!`.
fn main() {
// FIXME: Ignite a rocket, mount some routes, and launch it.
}
|
use crate::{
compute_enc_pending_balance, confidential_transaction_file, construct_path,
create_rng_from_seed, errors::Error, last_ordering_state, load_object, non_empty_account_id,
save_object, user_public_account_balance_file, user_public_account_file, OrderedPubAccount,
OrderedTransferInstruction, Tr... |
use chrono::prelude::*;
use chrono::DateTime;
use chrono_tz::Tz;
use serde::{Deserialize, Serialize};
use std::error::Error;
/// A `TimeSpan` type represents a time interval (duration of time)
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TimeSpan {
start_ts: i64,
... |
pub mod block;
pub mod block_proof;
pub mod boot;
pub mod config;
pub mod db;
pub mod error;
pub mod engine;
pub mod engine_traits;
pub mod engine_operations;
pub mod full_node;
pub mod macros;
pub mod network;
pub mod shard_state;
pub mod types;
#[cfg(feature = "tracing")]
pub mod jaeger;
#[cfg(not(feature = "tracin... |
use lexer::Lexer;
use lexer::Token;
use lexer::Ident;
pub struct Parser {
lexer: Lexer,
}
impl Parser {
pub fn new(buffer: String) -> Parser {
let lexer = Lexer::new(buffer);
Parser {lexer: lexer}
}
pub fn parse(&mut self){
// loop through the buffer until all the tokens have ... |
pub mod funcs {
use num::Float;
pub fn sigmoid<T: Float>(x: T) -> T {
num::one::<T>() / (num::one::<T>() + (-x).exp())
}
pub fn relu<T: Float>(x: T) -> T {
if x > num::zero::<T>() {
x
}
else {
num::zero::<T>()
}
}
}
#[cfg(test)]
mod ... |
use std::old_io;
use rand;
/// Checks if x in [a,b].
///
/// # Examples
///
/// ```
/// use twenty48::util::check_bounded;
/// assert!(check_bounded(5, 2, 7));
/// assert!(check_bounded(-3, -3, -3));
/// assert!(!check_bounded(12, 12, 11));
/// ```
pub fn check_bounded(x: i32, a: i32, b: i32) -> bool {
return x >= a... |
use super::{
calc, hz_from_perc, letter_octave_from_perc, mel_from_perc, scaled_perc_from_perc,
step_from_perc, Hz, Letter, LetterOctave, Mel, Octave, ScaleWeight, ScaledPerc, Step,
DEFAULT_SCALE_WEIGHT,
};
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
use std::cmp::Ordering;
use std::ops::... |
use crate::instructions::base::bytecode_reader::BytecodeReader;
use crate::instructions::base::instruction::{Instruction, NoOperandsInstruction};
use crate::runtime::frame::Frame;
///aconst_null
pub struct AconstNull(NoOperandsInstruction);
impl AconstNull {
#[inline]
pub const fn new() -> AconstNull {
... |
use std::sync::{Arc, Mutex, mpsc};
use std::net::{TcpStream, SocketAddr};
use std::thread;
use std::io::prelude::*;
use std::time::Duration;
use rustc_serialize::json;
use std::path::PathBuf;
use io::config::{get_config_path, Config};
use networking::UDPSocket;
use ui::FrontendData;
use networking::WatchDogClient;
us... |
// Copyright 2020 WHTCORPS INC. Licensed under Apache-2.0.
use super::Result;
/// `UNSPECIFIED_FSP` is the unspecified fractional seconds part.
pub const UNSPECIFIED_FSP: i8 = -1;
/// `MAX_FSP` is the maximum digit of fractional seconds part.
pub const MAX_FSP: i8 = 6;
/// `MIN_FSP` is the minimum digit of fractional ... |
/**
* [1042] Flower Planting With No Adjacent
*
* You have N gardens, labelled 1 to N. In each garden, you want to plant one of 4 types of flowers.
*
* paths[i] = [x, y] describes the existence of a bidirectional path from garden x to garden y.
*
* Also, there is no garden that has more than 3 paths coming into... |
use std::sync::Arc;
use crate::core::pbrt::{Float, consts::PI, radians};
use crate::core::shape::Shape;
use crate::core::geometry::{Bounding3, Bounds3f, Ray, Point2f, Point3f, Normal3f, Vector3f};
use crate::core::transform::Transform;
use crate::core::material::Material;
use crate::core::interaction::*;
use crate::cor... |
/*
* Copyright 2018 Fluence Labs Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or a... |
#[doc = "Register `APORTCONFLICT` reader"]
pub struct R(crate::R<APORTCONFLICT_SPEC>);
impl core::ops::Deref for R {
type Target = crate::R<APORTCONFLICT_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<crate::R<APORTCONFLICT_SPEC>> for R {
#[inline(always)]
... |
use crate::dd_challenge::Solution;
impl Solution {
pub fn length_of_last_word(s: String) -> i32 {
match s.split_whitespace().last(){
Some(ss) => ss.len() as i32,
None => 0
}
}
}
#[cfg(test)]
mod tests {
use crate::dd_challenge::Solution;
#[test]
fn test_len... |
use crate::diagram::{SequenceDiagram, TimelineEvent};
use crate::participant::Participant;
use crate::rendering::layout::{string_width, GridSize, ReservedWidth};
use crate::rendering::renderer::{LineStyle, Renderer};
use nalgebra::Point2;
use std::cell::RefCell;
use std::rc::Rc;
#[derive(Debug, Clone)]
pub struct Mess... |
use std::sync::mpsc;
use std::net::SocketAddr;
use dcpu::emulator::*;
use event_loop;
pub struct Server {
dcpus: Vec<Computer>,
commands: mpsc::Receiver<event_loop::ServerCommand>,
}
impl Server {
pub fn start(addr: SocketAddr) -> event_loop::Result<Server> {
Ok(Server {
dcpus: Vec::d... |
/// Default type for TYPO3 UID fields
pub type ID = i32;
|
use super::untrusted_event::{set_event, wait_event};
use super::{ProcessFilter, ProcessRef, TermStatus, ThreadId, ThreadRef};
use crate::fs::FileTable;
use crate::interrupt::broadcast_interrupts;
use crate::prelude::*;
use crate::syscall::CpuContext;
use std::collections::HashMap;
use std::mem;
// From Man page: The c... |
use sol5::process_program;
#[cfg(test)]
mod tests_basic {
use super::*;
#[test]
fn test_basic_1() {
let program = "1,0,0,0,99";
let (result, _o) = process_program(program, &[]);
assert_eq!(*result.memory(), vec![2, 0, 0, 0, 99]);
}
#[test]
fn test_basic_2() {
l... |
use ntapi::ntexapi::{
NtQuerySystemInformation, NtSetSystemInformation, SystemMemoryListInformation,
SYSTEM_MEMORY_LIST_INFORMATION,
};
use winapi::um::{
handleapi::CloseHandle,
processthreadsapi::{GetCurrentProcess, OpenProcessToken},
securitybaseapi::AdjustTokenPrivileges,
synchapi::WaitForSi... |
use std::io::{self, Read};
#[derive(Debug)]
struct Rotator {
letters: Vec<u8>,
}
impl Rotator {
pub fn new(init_state: &str) -> Rotator {
Rotator { letters: init_state.as_bytes().to_vec() }
}
}
impl Iterator for Rotator {
type Item = String;
fn next(&mut self) -> Option<String> {
... |
#![warn(clippy::all)]
use j4rs::{ClasspathEntry, Instance, InvocationArg, Jvm, JvmBuilder};
use std::error::Error;
static CP_ENTRIES: &[&str] = &[
"/home/fred/Eclipse/javaparser-javaparser-parent-3.13.7/\
javaparser-core/target/javaparser-core-3.13.7.jar",
"/home/fred/Eclipse/javaparser-javaparser-parent... |
mod approximation;
mod config;
mod plot;
mod renderer;
mod text;
use config::{ColorScheme, DataConfig};
use glfw::{Action, Context, Key};
use nalgebra::{Matrix3, Vector2};
use ordered_float::OrderedFloat;
use rusttype::Font;
use std::cmp;
use std::collections::BTreeMap;
use std::io;
use std::io::BufRead;
use std::sync... |
use std::env;
/// Fetch an environment variable, but return a default value if not found
fn get_env(key: String, default: String) -> String {
let found = env::var_os(key);
if found.is_some() {
found.unwrap().into_string().unwrap()
} else {
default
}
}
/// Return the configured authe... |
use core::fmt;
pub struct Hex<T>(pub T);
impl fmt::Display for Hex<u8> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:#04x}", self.0)
}
}
impl fmt::Display for Hex<u64> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.0 <= 0xff {
... |
// System tests for compiling C code.
//
// Copyright 2016 Mozilla Foundation
//
// 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
//
// Un... |
use gtk::{Image, Builder};
use gtk::prelude::{*};
use gdk_pixbuf;
use std::any::Any;
use gdk::enums::key::union;
const HEIGT :i32 = 200;
const WIDTH :i32 = 200;
const BORDER_UP: (f64, f64)= (0.0,0.0);
const BORDER_BOTTON: (f64,f64) = (WIDTH as f64, HEIGT as f64);
pub struct ImageArea{
image : Image,
image... |
use anim::{AnimParam, Key, Interpolation, Sampler};
use luminance::Mode;
use luminance_gl::gl33::Tessellation;
/// A unit plane, aligned with the (x,y) plane.
pub fn new_plane() -> Tessellation {
let vertices = [
[ 1., -1., 0.],
[ 1., 1., 0.],
[-1., -1., 0.],
[-1., 1., 0.]
];
Tessellation::new... |
/*
* Isilon SDK
*
* Isilon SDK - Language bindings for the OneFS API
*
* OpenAPI spec version: 5
* Contact: sdk@isilon.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
use std::borrow::Borrow;
use std::rc::Rc;
use futures;
use futures::Future;
use hyper;
use super::{configuration, qu... |
/// Doc-test test
/// ```rust
/// assert!(cargo_miri_test::make_true());
/// ```
/// ```rust,no_run
/// assert!(!cargo_miri_test::make_true());
/// ```
/// ```rust,compile_fail
/// assert!(cargo_miri_test::make_true() == 5);
/// ```
#[no_mangle]
pub fn make_true() -> bool {
issue_1567::use_the_dependency();
iss... |
// This file is part of Substrate.
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.a... |
use structopt::StructOpt;
#[derive(Clone, PartialEq, StructOpt)]
pub struct OpenOptions {
}
#[derive(Clone, PartialEq, StructOpt)]
pub struct ListOptions {
}
#[derive(Clone, PartialEq, StructOpt)]
pub struct CreateOptions {
/// name for new cpuset
#[structopt(long)]
pub name: String
}
#[derive(C... |
// Copyright 2022 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to ... |
use std::convert::{Into, TryFrom};
use std::io;
/// Contains all lower-case latin letters
pub static CHARSET_ALPHA_LOWER: [char; 26] = [
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',
'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
];
/// Contains all upper-case latin letter... |
use std::collections::HashSet;
pub struct Solution {}
impl Solution {
pub fn is_happy(n: i32) -> bool {
let mut set = HashSet::new();
let mut num = n;
while num != 1 {
if !set.insert(num) {
break;
}
let mut num_tmp = num;
num ... |
#[cfg(test)]
mod tests {
#[test]
fn it_works() {
let s = r#"{ a : 100, b : "abc" }"#.to_string();
crate::de::from_str(&s);
}
}
|
// This file is part of Substrate.
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.a... |
use std::{
env,
fs::{self, File},
io::Read,
path::Path,
};
use diesel::prelude::*;
use futures::executor::ThreadPool;
use glob::glob;
use lp::models::ReleaseId;
use lp_import::{parameterize, readers, Context};
use lp_magick::resize;
use rand::distributions::Uniform;
use rand::prelude::*;
use toml::Valu... |
use std::sync::atomic::Ordering;
use crossbeam::deque::Injector;
use crossbeam::queue::SegQueue;
use dynqueue::IntoDynQueue;
use parking_lot::{MutexGuard, RwLock};
use rayon::iter::{IntoParallelIterator, ParallelIterator};
use crate::collector::dropper::DropMessage;
use crate::collector::{Collector, GcExclusiveWarran... |
pub fn sqrt(x:i32,precision:f32)->f32{
if x==0 ||x==1{return x as f32;}
let mut left=0f32;
let mut right=x as f32;
let mut res=0f32;
while left<=right{
let mid:f32=(right-left)/2.0+left;
if (right-left).abs()<precision{return mid;}
if mid > x as f32 / mid{
right=... |
extern "C" {
pub fn db(a :i32)->i32;
pub fn sayHello();
}
fn main() {
unsafe{
println!("Hello, 3*2={}", db(3));
sayHello();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.