text stringlengths 8 4.13M |
|---|
#![no_std]
#![feature(start)]
#![feature(asm)]
#![no_main]
use core::panic::PanicInfo;
#[no_mangle]
pub extern "C" fn _start() {
syscall(0, 0, 0);
main();
}
#[panic_handler]
pub fn panic(_: &PanicInfo) -> ! {
unsafe { asm!("push rax", "mov rax, 1", "int 80h", "pop rax") }
unsafe { asm!("push 0", "ret... |
use std::{convert::TryInto, path::PathBuf};
use anyhow::{bail, Result};
use mongodb::{
bson::{doc, Bson, Document},
Client,
Collection,
Database,
};
use serde_json::Value;
use crate::{
bench::{drop_database, Benchmark, COLL_NAME, DATABASE_NAME},
fs::read_to_string,
};
pub struct FindOneBenchm... |
pub struct PhysicsSystem {
}
impl System for PhysicsSystem {
fn execute(&self, &mut World);
}
|
use log::trace;
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
enum State {
Vacant,
Split,
Occupied(usize),
}
pub struct BuddyAllocator {
size: usize,
unit: usize,
max_order: u32,
buddies: Vec<State>,
}
impl BuddyAllocator {
pub fn new(size: usize, max_order: u32) -> BuddyAllocator {
... |
//The model that follows the db schema
use crate::schema::producers;
use getset::{CopyGetters, Setters};
#[repr(i16)]
#[derive(Serialize, Deserialize)]
pub enum ProducerType {
GENERIC = 1,
PLANT = 2,
COFFEE = 3,
MEAT = 4,
MILL = 5
}
#[table_name="producers"]
#[derive(Setters, CopyGetters, Serializ... |
//! At the time of writing the only way to ensure some cleanup code is
//! run is by implementing Drop. Drop has some limitations however: you
//! can't pass extra arguments or report errors from it. Even the
//! standard library faces this problem:
//!
//! ```ignore
//! impl Drop for FileDesc {
//! fn drop(&mut se... |
/*
* 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
*/
/// Host : Object representing a host.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub... |
use amethyst::ecs::{Component, NullStorage};
#[derive(Debug, Default)]
pub struct Player;
impl Component for Player {
type Storage = NullStorage<Self>;
}
|
use std::env;
use std::fs;
use std::path::PathBuf;
fn main() {
let out = PathBuf::from(env::var_os("OUT_DIR").unwrap());
fs::remove_dir_all(&out).unwrap();
fs::create_dir(&out).unwrap();
cc::Build::new()
.file("src/foo.c")
.flag_if_supported("-Wall")
.flag_if_supported("-Wfoo-b... |
extern crate colored;
use colored::*;
fn main() {
let x = {
let y = five();
y + (y * 2) // no semicolon dawg
};
let mut y = 1;
println!("let's explore show_xy in a weird while loop:");
while y <= 9 {
show_xy(x, y);
y = y + 1;
}
println!("\nhow about a for ... |
use std::io;
use std::sync::mpsc;
use std::thread;
use termion::event::Key;
use termion::input::TermRead;
use std::time::Duration;
pub enum Event<I> {
Input(I),
Tick,
}
pub struct Events {
rx: mpsc::Receiver<Event<Key>>,
}
// TODO should either the sender or receiver use tokio's version?
impl Events {
... |
use crate::node::{Clip, Fill, Real, Stroke, Transform, TransformMatrix};
#[derive(Default, Debug, Clone, PartialEq)]
pub struct Group {
pub id: Option<String>,
pub transparency: Option<Real>,
pub stroke: Option<Stroke>,
pub fill: Option<Fill>,
pub clip: Clip,
pub transform: Transform,
}
impl G... |
use std::collections::HashMap;
use std::sync::mpsc::{channel, Sender, Receiver};
use std::thread::Builder;
use battle_state::BattleContext;
use login::AccountBox;
use net::{
OutPacket,
ServerSlot,
ServerSlotId,
SlotInMsg,
};
use sector_data::{SectorData, SectorId};
use sector_state::SectorState;
use ve... |
use std::fmt::Formatter;
use std::string::FromUtf8Error;
/// `Error` represents custom errors in this crate.
#[derive(Debug, Eq, PartialEq, Clone)]
pub enum Error {
/// `None` represents for no error.
None,
/// `LogNotFound` when the specific log entry is not found
LogNotFound,
/// `PipelineRepli... |
use lib::Forecast;
mod lib;
pub fn forecast(api: String) -> Forecast {
let url = format!("http://api.openweathermap.org/data/2.5/weather?q={},{}&appid={}","Dublin", "IE", api);
let client = reqwest::blocking::Client::new();
let res = client.get(&url)
.send()
.unwrap()
.json::<Fore... |
use crate::connection::Throughput as ThroughputEnum;
use crate::estimate::Estimate;
use crate::model::BenchmarkGroup;
use crate::report::{
compare_to_threshold, BenchmarkId, ComparisonResult, MeasurementData, Report, ReportContext,
};
use crate::value_formatter::ValueFormatter;
use anyhow::Result;
use serde... |
// This file is part of Substrate.
// Copyright (C) 2019-2020 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
//
// ht... |
extern crate bela_sys;
use bela_sys::{BelaContext, BelaInitSettings};
use std::convert::TryInto;
use std::{mem, slice};
use std::{thread, time};
pub mod error;
pub enum DigitalDirection {
INPUT,
OUTPUT,
}
#[repr(C)]
pub enum BelaHw {
NoHw = bela_sys::BelaHw_BelaHw_NoHw as isize,
Bela = bela_sys::Bel... |
use cosmwasm_std::{
Api, Binary, Env, Extern, HandleResponse, InitResponse,
MigrateResult, Querier, StdResult, Storage,
};
use cw20_base::contract::{handle as cw20_handle, init as cw20_init, query as cw20_query, migrate as cw20_migrate};
use cw20_base::msg::{HandleMsg, InitMsg, MigrateMsg, QueryMsg};
pub fn i... |
test_normalize! {"
error[E0308]: mismatched types
--> tests/compile-fail/surface_source_interval_badarg.rs:7:25
|
5 | let mut df = hydroflow_syntax! {
| __________________-
6 | | // Should be a `Duration`.
7 | | source_interval(5) -> for_each(std::mem::drop);
| | ... |
use common::{Item, Result};
use std::sync::{Arc, Mutex};
pub trait IOutput: Send + Sync + 'static {
fn write(&mut self, item: Item) -> Result<()>;
}
#[derive(Debug)]
pub struct Output<T: ?Sized + IOutput> {
o: T,
}
unsafe impl<T: IOutput> Send for Output<T> {}
unsafe impl<T: IOutput> Sync for Output<T> {}
i... |
use std::io::{Error as IOError, Write};
use std::sync::mpsc::Receiver;
use deco::{dprintln, dwrite, dwriteln};
use crate::dictionary::{Entry, Text};
use crate::errors::AppResultU;
use crate::pager::with_pager;
pub fn main(rx: Receiver<Option<Vec<Entry>>>) -> AppResultU {
for entries in rx {
if let Som... |
use crate::data::GcpAccessToken;
use serenity::prelude::*;
use std::{sync::Arc, time::Duration};
macro_rules! unwrap {
($e:expr) => {
match $e {
Some(e) => e,
None => continue,
}
};
}
pub async fn renew_token(ctx: Arc<Context>) {
let ctx = Arc::clone(&ctx);
toki... |
#![no_std]
#![no_main]
#![feature(asm)]
#![feature(abi_x86_interrupt)]
#![feature(custom_test_frameworks)]
#![test_runner(test_runner)]
#![reexport_test_harness_main = "test_main"]
use blanc_os::test_runner;
use coop::{executor::Executor, Task};
use memory::{allocator, phys::PhysFrameAllocator};
use core::panic::Pani... |
#[cfg(feature = "sled-storage")]
use gluesql::{parse, Glue, Payload::*, Query};
use sqlparser::ast::{OrderByExpr, Statement};
use std::rc::Rc;
use crate::applic_folder::compileargs::*;
use crate::applic_folder::get_storage::get_storage;
use crate::applic_folder::orderby::*;
use crate::applic_folder::show_select::*;
... |
use bytes::Bytes;
#[derive(Debug)]
pub enum Command {
/* Client initiated commands.
* These commands are initiated by clients
* which connect to the server.*/
/* "GET" command. */
Get {
key: String,
id: i64,
},
/* "SET" command. */
Set {
key: String,
va... |
use std::iter;
use crate::jit;
const JMP_SIZE: usize = 8;
const TRAMPOLINE_ENTRYPOINT: [u8; 10] = [
0x48, 0xff, 0xc0, // inc rax
0xe9, 0x02, 0x00, 0x00, 0x00, // jmp 0x7
0x31, 0xc0, // xor eax, eax
];
//const TRAMPOLINE_END: [u8; 19] = [
// 0xe8, 0x00, 0x00, 0... |
mod context;
mod device;
mod swapchain;
pub mod sys;
mod text;
pub use device::Device;
pub use swapchain::Swapchain;
|
//! Exposes utility constants, enums, classes and functions for easy use.
mod event_loop;
mod errors;
pub use self::event_loop::EventLoop;
pub use self::errors::AppError;
|
use serde::Serialize;
use time::PreciseTime;
pub struct OpenTimer<'a> {
name: &'static str,
timer_tree: &'a mut TimerTree,
start: PreciseTime,
depth: u32,
}
impl<'a> OpenTimer<'a> {
/// Starts timing a new named subtask
///
/// The timer is stopped automatically
/// when the `OpenTimer... |
use crate::server::ChatServer;
use actix::prelude::*;
use actix::Handler;
pub struct ListRooms;
impl actix::Message for ListRooms {
type Result = Vec<String>;
}
impl Handler<ListRooms> for ChatServer {
type Result = MessageResult<ListRooms>;
fn handle(&mut self, _: ListRooms, _: &mut Context<Self>) -> Se... |
#[derive(Clone, Copy, PartialEq, Hash)]
pub struct Board {
pub board: u64,
}
impl Board {
pub fn transpose(&self) -> Board {
// https://github.com/nneonneo/2048-ai
let x = self.board;
let a1 = x & 0xF0F00F0FF0F00F0F;
let a2 = x & 0x0000F0F00000F0F0;
let a3 = x & 0x0F0F00... |
extern crate aoc2017;
use aoc2017::days::day20;
fn main() {
let input = aoc2017::read("input/day20.txt").unwrap();
let value1 = day20::part1::parse(&input, 10_000);
let value2 = day20::part2::parse(&input, 10_000);
println!("Day 20 part 1 value: {}", value1);
println!("Day 20 part 2 value: {}", v... |
use std::cmp::Ordering;
use std::collections::{BinaryHeap, HashMap, VecDeque};
use std::fs::File;
use std::io::{BufRead, BufReader};
lazy_static! {
static ref ALPHABET_BITS: HashMap<char, u32> = "abcdefghijklmnopqrstuvwxyz"
.chars()
.enumerate()
.map(|(i, c)| (c, 1u32 << i))
.collec... |
/*
* Copyright Stalwart Labs Ltd. See the COPYING
* file at the top-level directory of this distribution.
*
* Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
* https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
* <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
* optio... |
use grid_printer::GridPrinter;
use grid_printer::style::{Fg, Bg, Sgr, StyleOpt};
use std::error::Error;
fn main() -> Result<(), Box<dyn Error>> {
let grid = vec![
vec![1, 2, 3, 4, ],
vec![5, 6, 7, 8, ],
vec![9, 10, 11, 12, ],
];
let rows = grid.len();
let cols = grid[0].len();... |
use gl;
use graphics::texture::Texture;
use std::ops::Drop;
pub struct FrameBuffer {
gl_handle: u32,
color_buffer: Texture,
highlights: Texture,
}
impl FrameBuffer {
pub fn new(width: u32, height: u32) -> FrameBuffer {
let mut frame_buffer = FrameBuffer {
gl_handle: 0,
... |
// Copyright 2019 The Grin Developers
//
// 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 agree... |
use itertools::Itertools;
use std::env::args;
use std::result::Result;
#[derive(PartialEq)]
enum Seat {
ROW,
COLUMN,
}
#[derive(Debug, Clone)]
struct BoardingPass {
pass: String,
row: usize,
column: usize,
seat_id: usize,
}
impl BoardingPass {
pub fn new(new_pass: String) -> BoardingPass ... |
use std::sync::Arc;
use anyhow::Context;
use axum::extract::{Extension, Path, Query};
use hyper::{Body, Request, Response};
use percent_encoding::{percent_encode, NON_ALPHANUMERIC};
use serde_derive::Deserialize;
use serde_json::Value as JsonValue;
use svc_utils::extractors::AccountIdExtractor;
use tracing::error;
use... |
#[doc = "Register `HSECR` reader"]
pub type R = crate::R<HSECR_SPEC>;
#[doc = "Register `HSECR` writer"]
pub type W = crate::W<HSECR_SPEC>;
#[doc = "Field `UNLOCKED` reader - Register lock system"]
pub type UNLOCKED_R = crate::BitReader;
#[doc = "Field `UNLOCKED` writer - Register lock system"]
pub type UNLOCKED_W<'a, ... |
use common::Result;
use event::obj::Dispatch;
use serde::{Deserialize, Serialize};
use std::convert::AsRef;
use std::{
collections::HashMap,
sync::{Arc, Mutex},
};
use strum::AsRefStr;
#[derive(AsRefStr, Debug)]
pub enum Event {
#[strum(serialize = "Add")]
Add,
#[strum(serialize = "Delete")]
De... |
// 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>,... |
//! This module contains the various end point definitions for stellar's horizon
//! API server.
use error::Result;
use serde::de::DeserializeOwned;
use http;
pub mod account;
pub mod asset;
pub mod ledger;
pub mod payment;
pub mod transaction;
mod records;
pub use self::records::Records;
/// Represents the body of ... |
use std::collections::HashMap;
use game::{State, Action, Reward};
use game::Action::*;
use gpi::Alg;
use util::VaryingStepSizer;
type ValueFn = HashMap<(State, Action), Reward>;
pub struct MonteCarlo {
value_fn: ValueFn,
step_sizer: VaryingStepSizer,
reward_this_episode: Reward,
visited_this_episode:... |
pub fn parse(data: &str) -> usize {
data.lines().map(|line| {
let row: Vec<usize> = line.split_whitespace().map(|chr| {
chr.parse::<usize>().unwrap()
}).collect();
let max = row.iter().max().unwrap();
let min = row.iter().min().unwrap();
max - min
}).sum()
}
... |
use async_trait::async_trait;
use crate::event::EventHandler;
use crate::result::Result;
#[async_trait]
pub trait EventSubscriber {
async fn subscribe(
&self,
handler: Box<dyn EventHandler>, // TODO: use generics.
) -> Result<bool>;
}
|
use crate::{
regressor::{
sgd::SGD,
adagrad::AdaGrad,
rmsprop::RMSProp,
adam::Adam,
utils::*,
}
};
#[derive(Copy, Clone, Debug)]
pub struct Config {
/// The maximum number of passes over the training data.
pub iterations: usize,
/// Constant that multiplies t... |
//! blsic
/// Isolate lowest set bit and complement
pub trait Blsic {
/// Clears least significant bit and sets all other bits.
///
/// If there is no set bit in `self`, it sets all the bits.
///
/// # Instructions
///
/// - [`BLSIC`](http://support.amd.com/TechDocs/24594.pdf):
/// - ... |
use Pixel;
pub static ALICE_BLUE: Pixel = Pixel {r: 240, g: 248, b: 255 };
pub static ANTIQUE_WHITE: Pixel = Pixel {r: 250, g: 235, b: 215 };
pub static AQUA: Pixel = Pixel {r: 0, g: 255, b: 255 };
pub static AQUAMARINE: Pixel = Pixel {r: 127, g: 255, b: 212 };
pub ... |
use core::cmp::min;
use crate::TinyMT32;
const TINYMT32_MEXP: usize = 127;
const TINYMT32_SH0: u32 = 1;
const TINYMT32_SH1: u32 = 10;
const TINYMT32_SH8: u32 = 8;
const TINYMT32_MASK: u32 = 0x7fff_ffff_u32;
const TINYMT32_MUL: f64 = 1.0f64 / 16_777_216.0_f64;
const MIN_LOOP: usize = 8;
const PRE_LOOP: usize = 8;
imp... |
//! Config parameters for building kernel
/// Length of the message buffer in pages
pub const MSG_BUF_LEN: usize = 1;
/// Maximum number of logical cpu's supported
pub const MAX_CPUS: usize = 16;
/// How long between interrupts sent by the timer
pub const TIMER_PERIOD: Duration = Duration::from_millis(40);
/// amou... |
use std::fmt::Display;
//就像泛型类型参数,泛型生命周期参数需要声明在函数名和参数列表间的尖括号中。
// 生命周期注解告诉 Rust 多个引用的泛型生命周期参数如何相互联系的。
// 这里我们想要告诉 Rust longest 函数返回的引用的生命周期应该与传入参数的生命周期中较短那个保持一致。
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() {
x
} else {
y
}
}
pub fn lifetime_complex_test() {
... |
use std::io;
fn get_line() -> String {
let mut input = String::new();
let stdin = io::stdin();
stdin.read_line(&mut input).unwrap();
input
}
fn main() {
let mut line = get_line();
let mut twos = 0;
let mut threes = 0;
while &line != "" {
let mut letters = [0; 26];
for c ... |
mod blockchain;
extern crate durian;
use ethereum_types::{U256, Address};
use blockchain::Blockchain;
use durian::stateless_vm::StatelessVM;
use durian::transaction::Transaction;
use std::fs::File;
use std::io::Read;
use std::sync::Arc;
fn main() {
let mut bc = Blockchain::new();
let file_path = "./compiled... |
#[macro_use]
extern crate clap;
extern crate osm_xml as osm;
mod schemes;
mod utils;
use clap::{App, Arg, ArgMatches, SubCommand};
use std::error::Error;
use std::fmt;
use schemes::chase::matrix::SE;
use utils::prf::PRF;
use utils::prp::PRP;
use std::path::Path;
use std::process;
use std::fs::File;
const EXTENSION_JS... |
use dynamic_pool::DynamicPool;
pub use dynamic_pool::{DynamicPoolItem, DynamicReset};
use thiserror::Error;
#[derive(Error, Debug)]
pub enum SizedPoolError {
#[error("the given size exceeds the maximum allowed size of the pool")]
SizeExceedMaxSize,
}
pub trait SizedAllocatable {
fn new(size: usize) -> Sel... |
use std::env::{remove_var, set_var, var};
use crate::{bson::Document, client::auth::aws::test_utils::*, test::DEFAULT_URI, Client};
use super::TestClient;
#[cfg_attr(feature = "tokio-runtime", tokio::test)]
#[cfg_attr(feature = "async-std-runtime", async_std::test)]
async fn auth_aws() {
let client = TestClient:... |
use std::cmp::Ordering;
use std::rc::Rc;
use std::collections::HashMap;
const WORLD_SIZE : usize = 10;
#[derive(PartialEq, Debug, Eq, Hash, Clone, Copy)]
struct Point {
x: i32,
y: i32
}
fn pt(x : i32, y : i32) -> Point {
Point {x : x, y :y}
}
impl Point {
fn add(&self, p : Point) -> Point {
Poin... |
use core::fmt;
use core::marker::PhantomData;
use conquer_pointer::{MarkedNonNull, MarkedPtr, Null};
use crate::traits::Reclaim;
use crate::{Maybe, Protected, Shared};
/********** impl Clone ****************************************************************************/
impl<T, R, const N: usize> Clone for Protected<... |
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use std::collections::HashSet;
use cosmwasm_std::{
HumanAddr,
};
//use cosmwasm_std::{CanonicalAddr, Storage};
//use cosmwasm_storage::{singleton, singleton_read, ReadonlySingleton, Singleton};
#[derive(Serialize, Deserialize, Clone, Debug, JsonSchem... |
use math::round::half_up;
pub type LabColor = [f64; 3];
pub fn sub(color: LabColor, other: LabColor) -> LabColor {
[
color[0] - other[0],
color[1] - other[1],
color[2] - other[2],
]
}
// Illuminant and reference angle for output values: D65 2°
pub fn rgb_2_lab(color: [f64; 3]) -> LabC... |
#[cfg(target_arch = "x86")]
use core::arch::x86::*;
#[cfg(target_arch = "x86_64")]
use core::arch::x86_64::*;
// 参考:
// https://www.intel.cn/content/dam/www/public/us/en/documents/white-papers/carry-less-multiplication-instruction-in-gcm-mode-paper.pdf
#[derive(Clone)]
pub struct GHash {
key: __m128i,
buf: __... |
pub fn is_valid(s: String) -> bool {
let n = s.len();
if n == 0 {
return true
}
if n % 2 == 1 {
return false
}
let mut previous_pos = vec![0; n];
let chars: Vec<char> = s.chars().collect();
let mut last_position = 0;
let mut counter = 0;
for i in 0..n {
... |
//! A component that keeps track of the current route string and can modify its wrapped children via props
//! to indicate the route.
use crate::agent::{bridge::RouteAgentBridge, RouteRequest};
use crate::route_info::RouteInfo;
use crate::router_component::YewRouterState;
use std::fmt::{Debug, Error as FmtError, Format... |
use ckb_fixed_hash::H256;
use lazy_static::lazy_static;
pub type Message = H256;
lazy_static! {
pub static ref SECP256K1: secp256k1::Secp256k1<secp256k1::All> = secp256k1::Secp256k1::new();
}
mod error;
mod generator;
mod privkey;
mod pubkey;
mod signature;
pub use self::error::Error;
pub use self::generator::G... |
use std::net::SocketAddr;
use std::net::{IpAddr, Ipv4Addr};
use actix_web::{middleware, web, App, HttpRequest, HttpServer, HttpResponse, delete, get, head, options, patch, post, put};
#[actix_web::main]
pub async fn start_server() -> std::io::Result<()> {
let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127,... |
use crate::backend::db::DbPool;
use crate::backend::result::{JsResult, Result};
use crate::backend::schema::*;
use crate::common::models::*;
use actix_web::http::StatusCode;
use actix_web::web::{Data, Json, Path, ServiceConfig};
use actix_web::{get, post, put, Error, HttpRequest, HttpResponse, Responder};
use diesel::... |
pub extern crate rusty_sword;
use rusty_sword::*;
fn main() {
// To avoid lock contention for this group of objects, we'll follow the rule:
// - You must have a lock on floor before trying to lock anything else
// - You must unlock all other locks before (or when) floor gets unlocked
let floor =... |
use std::io::Write;
/// The `Hash` trait specifies the common interface for hash functions.
///
/// The `write` from `Write` trait adds more data to the running hash.
/// It never returns an error.
pub trait Hash: Write {
/// block_size returns the hash's underlying block size.
/// The Write method must be abl... |
use std::fmt;
use strum_macros::{EnumIter, EnumString};
#[derive(Debug, PartialEq, EnumString, EnumIter)]
pub enum Alpha3 {
None,
// ENUM START
AFG,
AGO,
ALB,
AND,
ANT,
ARE,
ARG,
ARM,
AUT,
AZE,
BDI,
BEL,
BEN,
BFA,
BGD,
BGR,
BIH,
BLR,
B... |
use apllodb_server::Record;
pub(super) trait RecordCliDisplay {
fn cli_display(self) -> String;
}
impl RecordCliDisplay for Record {
fn cli_display(self) -> String {
let mut s = String::new();
for (name, value) in self.into_name_values() {
s.push_str(&format!("{}: {}\t", name, valu... |
mod termion;
pub use self::termion::TermionKeyboard;
pub trait Keyboard {
fn get_next_keystroke(&mut self) -> Option<KeyStroke>;
}
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub enum KeyStroke {
Char(char),
KeyF(u8),
Alt(char),
KeyUp,
KeyDown,
KeyLeft,
KeyRight,
KeyPreviou... |
//use std::fmt;
use futures::{Async, Future, Poll};
/// This is created by the `FutureInspector::inspect_err` method.
#[derive(Debug)]
#[must_use = "futures do nothing unless polled"]
pub struct InspectErr<A, F>
where
A: Future,
{
future: A,
f: Option<F>,
}
impl<A, F> InspectErr<A, F>
where
A: Future... |
use crate::parser::{ Parser, gen::Compiler };
use crate::common::Closure;
use crate::vm::VM;
use std::io::prelude::*;
use std::fs::File;
pub fn compile_file(name: String) -> Result<Closure, String> {
let mut file = File::open(name.clone()).expect("could not open file");
let mut str = String::new();
file.read_t... |
use serde::Serialize;
use crate::domain::author::Author;
use crate::domain::category::Category;
use crate::domain::collection::Collection;
use crate::domain::interaction::Review;
use crate::domain::publication::{Image, Page, Publication, Statistics};
use crate::domain::reader::Reader;
#[derive(Serialize)]
pub struct ... |
use std::cmp;
#[derive(Clone, Copy)]
struct Edge {
to: usize,
cap: usize,
rev: usize,
}
pub struct Maxflow {
graph: Vec<Vec<Edge>>,
used: Vec<bool>,
max_v: usize,
}
impl Maxflow {
pub fn new(max_v: usize) -> Self {
Maxflow {
graph: vec![vec![]; max_v],
used... |
use crate::things::thing::Thing;
pub struct Camera {
pub x: f32,
pub y: f32,
pub z: f32,
pub rx: f32,
pub ry: f32,
pub radius: f32,
}
impl Camera {
pub fn new(x: f32, y: f32, z: f32, rx: f32, ry: f32, radius: f32) -> Self {
Camera { x, y, z, rx, ry, radius }
}
pub fn updat... |
use actix::prelude::*;
use actix_web::{dev::Body, http::StatusCode, web::HttpResponse, ResponseError};
use diesel::prelude::*;
use failure_derive::Fail;
use lazy_static::lazy_static;
use uaparser::{Parser as _, UserAgentParser};
use crate::db::models::Log;
use crate::db::DbExecutor;
use crate::logs::LogEntry;
lazy_st... |
use session::Session;
use stream;
use util::FileId;
use byteorder::{BigEndian, WriteBytesExt};
use std::io::Write;
const CHUNK_SIZE: usize = 0x20000;
pub enum Response<H> {
// Wait(H),
Continue(H),
Seek(H, usize),
Close,
}
pub trait Handler : Sized + Send + 'static {
fn on_header(self, header_id:... |
use crate::participants::viewer_folder::viewer::Viewer;
use actix::prelude::*;
#[derive(Message)]
#[rtype(result = "()")]
pub struct RegisterAddressGetInfo {
pub name: String,
pub addr: Addr<Viewer>,
}
|
//! Tests auto-converted from "sass-spec/spec/non_conformant/mixin/content"
#[allow(unused)]
use super::rsass;
mod arguments;
// From "sass-spec/spec/non_conformant/mixin/content/before_if.hrx"
#[test]
fn before_if() {
assert_eq!(
rsass(
"// Regression test for sass/dart-sass#482.\
... |
use crate::db::models::User;
use crate::db::repository::{PostgrSQLUserRepository, UserRepository};
use crate::errors::AuthError;
use crate::utils;
/// Public function for the login
/// See `_login` for more info
///
pub fn login(username: &str, passwd: &str) -> Result<User, AuthError> {
let repository = PostgrSQLU... |
use async_std;
use crate::heartbeat::Timestamp;
use crate::locks::*;
use std;
use std::collections::{HashMap, HashSet};
use std::fs::{File, OpenOptions};
// Vars
lazy_static! {
pub static ref DEBUG: RwLockOption<bool> = RwLockOption::new();
pub static ref LOG_FILE: RwLockOption<File> = RwLockOption::new();
... |
use crossbeam::atomic::AtomicCell;
use std::cell::RefCell;
use std::rc::Rc;
// use parking_lot::RefCell
#[derive(Default)]
pub struct ColumnWidthsVec {
widths_hdr: Rc<RefCell<Vec<f32>>>,
widths: Rc<RefCell<Vec<f32>>>,
}
impl ColumnWidthsVec {
pub fn get(&self) -> Vec<f32> {
let prev_hdr = self.wid... |
struct FOO
{
f: i32,
}
struct Link<'a>{
link: &'a FOO,
}
fn store_foo<'a>(x: &mut Link<'a>, y: &'a FOO)
{
x.link=y;
}
fn main() {
let a=FOO{f: 30};
let x=&mut Link{link: &a};
{
let b=FOO{f: 12};
store_foo(x,&b);
}
println!("{}",x.link.f);
}
|
use bevy::prelude::*;
use crate::{
collider::{Collider,BallHitEvent},
game_data::LevelFinishedEvent
};
pub struct Destroyable {
pub hp: u16,
}
pub const BRICK_SIZE_X: f32 = 150.;
const BRICK_SIZE_Y: f32 = 70.;
pub fn spawn_brick (commands: &mut Commands, material: Handle<ColorMaterial>, x:... |
/**
<summary>
All defined in MSDN: [Window Constants (Windows)]/[Window Styles]
The following are the window styles. After the window has been created,
these styles cannot be modified, except as noted.
</summary>
<applies-to>Desktop apps only</applies-to>
<requirements>
<m... |
use std::f32;
fn main() {
let rect_height = 12;
let rect_width = 20;
let square_size = 10;
let circle_radius = 15.0;
let triangle_sides = (10.0, 6.0, 7.0);
let rect = Rectangle { width: rect_width, height: rect_height };
let sq = Rectangle::square(square_size);
let circle = Circle { radius: circle_rad... |
//! This module contains all the logic dealing with images:
//! Parsing the config file data, shuffling pixels of big images,
//! ordering pixels of small images and sorting the signatures to the end.
use crate::ascii_art::DEFAULT_IMAGES;
use crate::ascii_art::IMAGE_KNOWN_SIGNATURES;
use crate::dictionary::ConfigParse... |
use packed_simd::f32x8;
use ndarray::{ArrayView,ArrayViewMut,Ix2};
use crate::my_ndarray;
use crate::vectorisation;
use std::slice::{from_raw_parts, from_raw_parts_mut};
#[cfg(test)]
use crate::naive_sequential;
#[cfg(test)]
use ndarray::{linalg,Array};
#[cfg(test)]
use rand::Rng;
fn multiply_add_packed_sim( mut into... |
#[doc = "Register `PDCRC` reader"]
pub type R = crate::R<PDCRC_SPEC>;
#[doc = "Register `PDCRC` writer"]
pub type W = crate::W<PDCRC_SPEC>;
#[doc = "Field `PD0` reader - PD0"]
pub type PD0_R = crate::BitReader<PD0_A>;
#[doc = "PD0\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PD0_A {
... |
use rltk::{Point, RGB};
use specs::prelude::*;
use specs_derive::*;
use std::cmp::{max, min, Ordering};
use std::ops::{Add, Sub};
// ------------------------------------------------------------------------------------------------------------------ //
pub fn range<T: std::cmp::Ord>(l: T, v: T, u: T) -> T {
min(u, m... |
use std::fs::File;
use std::io::prelude::*;
/// Given an input string, return the floor that we ended up on.
fn calculate_final_position(input_value: String) -> i32 {
let mut tally = 0;
for character in input_value.chars() {
if character == '(' {
tally += 1
} else if character == ')... |
struct Solution {}
impl Solution {
pub fn my_atoi(s: String) -> i32 {
let mut num : i32 = 0;
let observed : u8;
let ( mut signed, mut sign_observed, mut overflow ) : (bool, bool, bool) = ( false, false, false );
let mut overflow_checker : i32 = 0;
for &c in s.as_bytes() {
... |
use crate::common::factories::RandomizedBuilder;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
#[derive(Debug, Clone)]
pub struct IpAddrBuilder {
pub version: IpVersion,
pub multicast: bool,
}
impl Default for IpAddrBuilder {
fn default() -> Self {
Self {
version: Default::default(),
... |
// Copyright (c) 2017 Brandon Thomas <bt@brand.io>
// Painting with Lasers
extern crate argparse;
extern crate beam;
extern crate camera_capture;
extern crate image;
extern crate lase;
extern crate piston;
extern crate piston_window;
extern crate router;
extern crate rscam;
extern crate texture;
mod arguments;
mod dr... |
#[macro_use]
extern crate explanation;
#[allow(unused_variables)]
extern crate rand;
extern crate timely;
extern crate graph_map;
extern crate differential_dataflow;
use std::cell::RefCell;
use std::io::BufRead;
use graph_map::GraphMMap;
use timely::dataflow::*;
use timely::dataflow::scopes::Child;
use timely::dataf... |
extern crate flint;
extern crate gmp;
#[macro_use]
extern crate hilbert_qexp;
extern crate serde;
extern crate serde_pickle;
pub mod parallel_wt;
pub mod mixed_wt;
pub mod structure;
|
pub fn hellodep() -> String {
println!("I'm in a procmacro as a dependency");
String::from("hello!")
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.