text stringlengths 8 4.13M |
|---|
use juniper::ScalarValue;
#[derive(Clone, Debug, PartialEq, ScalarValue)]
pub enum DefaultScalarValue {
Int(i32),
Float(f64),
#[value(as_str, as_string, into_string)]
String(String),
#[value(as_bool)]
Boolean(bool),
}
fn main() {}
|
use crate::player::PlayerName;
use serde::Serialize;
use std::error::Error as ErrorT;
use std::fmt;
pub type Result<T> = std::result::Result<T, Error>;
#[derive(Debug, Serialize)]
pub enum Error {
InvalidPlayerName(PlayerName),
InvalidSession,
InvalidSecret,
PlayerNameTaken(PlayerName),
InternalEr... |
use std::cmp::Ordering;
use std::collections::{BTreeSet, HashSet};
use std::sync::RwLock;
use std::time::Duration;
use types::{block::BlockNumber, peer_info::PeerId};
#[derive(Eq, PartialEq, Clone, Debug)]
struct TTLEntry<E>
where
E: Ord + Clone,
{
data: E,
expiration_time: Duration,
block_number: Bloc... |
use hashbrown::{HashMap, HashSet};
use utils::Vector3;
// #[test]
pub fn run() {
let input = read_input(include_str!("input/day24.txt"));
println!("{}", exercise_1(&input));
println!("{}", exercise_2(&input, 100));
}
enum Directions {
EAST,
WEST,
NORTHEAST,
NORTHWEST,
SOUTHEAST,
SO... |
//! # Multireferences (aka _the inverse distributive law_)
//!
//! Ever wanted to get `&[T]` from `[&T]` without cloning anything?
//!
//! Semantically, it doesn't make sense (because a slice wraps a block of
//! _contiguous_ elements). But sometimes it's very convenient to be
//! able to “algebraically” ... |
use std::pin::Pin;
use std::task::{Poll, Waker};
use deck_core::{ManifestId, Source};
use futures_preview::compat::{Future01CompatExt, Stream01CompatExt};
use futures_preview::future::{self, FutureExt, TryFutureExt};
use futures_preview::stream::{self, Stream, StreamExt, TryStreamExt};
use hyper::header::CONTENT_LENGT... |
// modified version of original https://github.com/PonasKovas/mandelbrot/blob/master/src/main.rs
extern crate image;
extern crate rayon;
extern crate num;
use rayon::prelude::*;
macro_rules! max_float {
($x: expr) => ($x);
($x: expr, $($z: expr),+) => {{
let y = max_float!($($z),*);
if $x > y... |
//! Repeated constants used around pathfinder
use crate::macro_prelude::block_hash;
use crate::BlockHash;
/// Vergen string
pub const VERGEN_GIT_DESCRIBE: &str = env!("VERGEN_GIT_DESCRIBE");
/// User agent used in http clients
pub const USER_AGENT: &str = concat!("starknet-pathfinder/", env!("VERGEN_GIT_DESCRIBE"));... |
#![no_std]
#![no_main]
extern crate panic_halt;
use dot_games::games::SelectionScreen;
#[arduino_uno::entry]
fn main() -> ! {
let mut components = dot_games::get_components();
// Run the Selection Screen.
let selected_game_loop = SelectionScreen::new().run(&mut components);
// Run the Game Loop.
... |
use crate::user::User;
use amiquip::{Connection, ConsumerMessage, ConsumerOptions, QueueDeclareOptions, Result};
use bincode::deserialize;
pub fn consume() -> Result<()> {
let mut conn = Connection::insecure_open("amqp://localhost:5672")?;
let ch = conn.open_channel(None)?;
let queue = ch.queue_declare("u... |
fn main() {
let stdin = std::io::stdin();
let mut rd = ProconReader::new(stdin.lock());
let a: i32 = rd.get();
let b: i32 = rd.get();
for x in -1000..=1000 {
for y in -1000..=1000 {
if x + y == a && x - y == b {
println!("{} {}", x, y);
return;
... |
//! Database for long clauses.
use std::mem::transmute;
use partial_ref::{partial, PartialRef};
use varisat_formula::Lit;
use crate::{
context::{parts::*, Context},
prop::Reason,
};
use super::{header::HEADER_LEN, ClauseAlloc, ClauseHeader, ClauseRef};
/// Partitions of the clause database.
///
/// The lon... |
// This file is part of linux-epoll. It is subject to the license terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/linux-epoll/master/COPYRIGHT. No part of linux-epoll, including this file, may be copied, modified, propagated, or distri... |
#![feature(libc)]
extern crate libc;
extern
{
//fn plus(x: libc::c_int, y: libc::c_int) -> libc::c_int;
fn plusone(x: libc::c_int) -> libc::c_int;
fn current_timestamp() -> libc::c_long;
}
use std::env;
fn run(count: libc::c_int)
{
unsafe
{
// start immediately
let start = curren... |
use criterion::{BatchSize, BenchmarkId, Criterion, criterion_group, criterion_main};
use galois_2p8;
use galois_2p8::Field;
use rand;
use rand::{Rng, RngCore};
use reed_solomon_erasure;
use g2p;
g2p::g2p!(GF256, 8);
fn g2p_addition(a: &[u8], b: &[u8], dest: &mut [u8]) {
assert_eq!(a.len(), b.len());
assert_e... |
use crate::calc::raw_log::RawLog;
use crate::TimeTrackerError;
use std::cmp::max;
use std::cmp::min;
use std::collections::HashMap;
use std::convert::TryFrom;
use std::fmt;
use std::fmt::Display;
use std::fmt::Formatter;
const MAX_SECONDS_BETWEEN_RECORDS_IN_SPAN: u64 = 5 * 60;
pub struct Span {
pub name: String,
... |
/*!
galbi is a library that provides shortcut types for idiomatic nested types.
## install
If cargo-edit is installed, you can install it like this:
```sh
cargo add galbi
```
If not, you have to manually add the dependency to Cargo.toml.
```toml
[dependencies]
galbi = "0.2.1"
```
## use
It can be used in the followi... |
foreigner_class!(class Boo {
self_type Boo;
constructor Boo::new() -> Boo;
method Boo::something(&self) -> i32;
});
foreign_enum!(
enum ControlItem {
GNSS = ControlItem::GnssWorking,
GPS_PROVIDER = ControlItem::AndroidGPSOn,
}
);
foreigner_class!(class Foo {
self_type Foo;
construc... |
pub mod generated_types {
pub use generated_types::influxdata::platform::storage::{read_group_request::Group, *};
}
use snafu::Snafu;
use self::generated_types::*;
use super::response::{
FIELD_TAG_KEY_BIN, FIELD_TAG_KEY_TEXT, MEASUREMENT_TAG_KEY_BIN, MEASUREMENT_TAG_KEY_TEXT,
};
use ::generated_types::{aggreg... |
/*
* CoSyNe: A CoSyNe implementation in Rust
*
* https://people.idsia.ch/~juergen/gomez08a.pdf
*/
use crate::vectorizable::Vectorizable;
use rand::prelude::*;
#[derive(Clone, Debug)]
pub struct Cosyne<T: Vectorizable> {
// NxM matrix, one column is one parameter.
population_raw: Vec<f64>,
dimension: u... |
use std::cell::RefCell;
use std::rc::Rc;
use fan::evaluator::NamedFans;
use input::evaluator::InputEvaluator;
use parser::{ Evaluator, Node };
use output::Output;
use util;
// Output evaluator
pub struct OutputEvaluator {
named_fans : Rc<RefCell<NamedFans>>,
input_evaluator : Rc<RefCell<InputEvaluator>>,
}
... |
pub mod effect;
pub mod reducer;
pub mod refs;
pub mod state;
|
use crate::prelude::*;
use std::os::raw::c_void;
use std::ptr;
#[repr(C)]
#[derive(Debug)]
pub struct VkPhysicalDeviceImageFormatInfo2KHR {
pub sType: VkStructureType,
pub pNext: *const c_void,
pub format: VkFormat,
pub imageType: VkImageType,
pub tiling: VkImageTiling,
pub usage: VkImageUsage... |
use crate::twins::mission_twin::types::Waypoint;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DefineMissionEvent {
pub id: String,
pub name: String,
pub waypoints: Vec<Waypoint>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ShowMissionEvent... |
mod utill;
extern crate serde;
extern crate serde_pickle;
use std::collections::BTreeMap;
use std::fs;
use std::f32::consts::PI;
fn main() {
do_all();
}
#[no_mangle]
pub fn do_all(){
//initializing stuff
let mut map = BTreeMap::new();
//initialize all numbers for scenario of h0 = 0
println!("Ente... |
//! Day 2
trait Solution {
fn part_1(&self) -> usize;
fn part_2(&self) -> usize;
}
impl Solution for str {
fn part_1(&self) -> usize {
filter_valid(
&parsers::input(self).expect("Failed to parse the input"),
part_1_rule,
)
.count()
}
fn part_2(&self) ... |
//! Types for Relay-compliant server
mod connection_type;
mod cursor;
mod edge;
mod page_info;
use std::{fmt::Display, future::Future};
pub use connection_type::Connection;
pub use cursor::{CursorType, OpaqueCursor};
pub use edge::Edge;
pub use page_info::PageInfo;
use crate::{Error, ObjectType, OutputType, Result,... |
::windows_sys::core::link ! ( "drt.dll""system" #[doc = "*Required features: `\"Win32_NetworkManagement_P2P\"`*"] fn DrtClose ( hdrt : *const ::core::ffi::c_void ) -> ( ) );
::windows_sys::core::link ! ( "drt.dll""system" #[doc = "*Required features: `\"Win32_NetworkManagement_P2P\"`*"] fn DrtContinueSearch ( hsearchco... |
// Copyright 2023 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 ... |
// Copyright (c) 2021 Quark Container Authors / 2018 The gVisor 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 ... |
// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT.
pub fn parse_http_generic_error(
response: &http::Response<bytes::Bytes>,
) -> Result<smithy_types::Error, smithy_json::deserialize::Error> {
crate::json_errors::parse_generic_error(response.body(), response.headers())
}
pub fn de... |
use ethers::contract::Abigen;
// TODO: Figure out how to write the rerun-if-changed script properly
fn main() {
// Only re-run the builder script if the contract changes
println!("cargo:rerun-if-changed=./abis/*.json");
// bindgen("BalanceSheet");
// bindgen("UniswapV2Pair");
}
#[allow(dead_code)]
fn... |
use std::any::type_name;
#[cfg(feature = "use_serde")]
use serde::{Deserialize, Serialize};
use crate::clickhouse::compacted_tables::schema::{
AggregationMethod, ClickhouseDataType, CompressionMethod, ValidateSchema,
};
use crate::{Error, Named};
#[derive(Debug, PartialEq, Eq, Clone)]
#[cfg_attr(feature = "use_s... |
#![allow(missing_docs)]
//! Document tree traversal to walk a shared borrow of a document tree.
//!
//! Each method of the [`Visit`] trait is a hook that can be overridden
//! to customize the behavior when mutating the corresponding type of node.
//! By default, every method recursively visits the substructure of the... |
use projecteuler::partition;
use projecteuler::primes;
fn main() {
//dbg!(binomial::binomial_coefficient(100, 50));
dbg!(solve(4));
dbg!(solve(5));
dbg!(solve(6));
dbg!(solve(100));
dbg!(solve(5_000));
}
fn solve(n: usize) -> usize {
let primes: Vec<usize> = primes::primes_iterator()
... |
pub(crate) mod future;
pub(crate) mod sink;
pub(crate) mod stream;
|
use bitflags::bitflags;
#[derive(Debug, Clone, Copy, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum Color {
Reset,
Black,
Red,
Green,
Yellow,
Blue,
Magenta,
Cyan,
Gray,
DarkGray,
LightRed,
LightGreen,
LightYellow,
... |
fn main() {
println!("Hello, world! Day 1.");
}
|
/// This part of the program is shared between `ibsc` and `ibswm` to easily manage command. If you
/// modify this part, please also check the `ibswm` package.
use clap::Clap;
#[derive(Clap, Debug)]
#[clap(version = "1.0", author = "Cyril Mizzi <me@p1ngouin.com>")]
pub struct Opts {
/// Verbosity. By default, will... |
//! Tests that use `liblumen_otp` with external dependencies to check that `lumen` can compile the
//! external dependencies and that `liblumen_otp` is supplying all the needed BIFs for those
//! external dependencies. These would normally be tests in the dependencies since they are built
//! on top of OTP, but since ... |
fn calc_fuel(in_val: i32) -> i32 {
(in_val as f32 / 3.0).floor() as i32 - 2
}
fn calc_fuel_2(in_val: i32) -> i32 {
let mut fuel_total = 0;
let mut next_fuel_val = in_val;
loop {
next_fuel_val = calc_fuel(next_fuel_val);
if next_fuel_val < 0 {
break;
}
... |
fn main() {
println!("vis 0.0.0");
}
|
use indexmap::IndexMap;
use crate::dynamic::{
base::{BaseContainer, BaseField},
schema::SchemaInner,
InputObject, Interface, SchemaError, Type,
};
impl SchemaInner {
pub(crate) fn check(&self) -> Result<(), SchemaError> {
self.check_types_exists()?;
self.check_root_types()?;
se... |
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// 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 ... |
// Massbit dependencies
use serde::{Deserialize};
#[allow(dead_code)]
pub struct IndexManager {
http_addr: String,
}
#[derive(Clone, Debug, Deserialize)]
pub struct DeployParams {
pub(crate) index_name: String,
pub(crate) config_path: String,
pub(crate) mapping_path: String,
pub(crate) model_path:... |
#[doc = "Reader of register OR1"]
pub type R = crate::R<u32, super::OR1>;
#[doc = "Writer for register OR1"]
pub type W = crate::W<u32, super::OR1>;
#[doc = "Register OR1 `reset()`'s with value 0"]
impl crate::ResetValue for super::OR1 {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
... |
use crate::actor::Actor;
use crate::Battle;
use lazy_static::lazy_static;
use std::collections::HashMap;
macro_rules! new_card {
($name:expr, $parent:expr, $($atr:ident = $set:expr),*) => {
CardTemplate {
name : $name,
$($atr : $set,)*
..(*$parent).clone() // This syntax... |
use std::io::Write;
use std::time::Duration;
use serialport::{DataBits, StopBits};
fn main(){
let portname = "COM3";
let baudrate = 115200;
let databits = DataBits::Eight;
let stopbits = StopBits::One;
let rate = 1;
let string = "rust";
let build = serialport::new(portname,baudrate)... |
/// Gnome sort
pub fn sort<T: Ord + Clone>(list: &Vec<T>) -> Vec<T> {
let mut sorted = list.clone();
let mut i = 1;
while i < list.len() {
if i == 0 || sorted[i - 1] <= sorted[i] {
i += 1;
} else {
sorted.swap(i - 1, i);
i -= 1;
}
}
return ... |
use crate::thread_worker::Worker;
use crate::types::*;
use crossbeam_channel::{Receiver, Sender, TryRecvError};
use jsonrpc_core::{self, Call, Output};
use std::collections::HashMap;
use std::io::{self, BufRead, BufReader, BufWriter, Error, ErrorKind, Read, Write};
use std::process::{Command, Stdio};
pub struct Langua... |
//! Command `tag`
use crate::{registry::Registry, result::Result};
/// Exec comamnd `tag`
pub fn exec(limit: usize, update: bool) -> Result<()> {
let registry = Registry::new()?;
if update {
println!("Fetching registry...");
registry.update()?;
}
// Get tags
let mut tags = registry... |
extern crate hound;
#[macro_use]
extern crate nom;
extern crate portaudio as pa;
extern crate sample;
pub mod expr;
pub mod eval;
pub mod numeral;
pub mod ops;
pub mod parser;
pub mod player;
pub mod signal;
pub mod wav;
|
use serde_json::Result;
use std::fmt; //fmt METHOD
use serde::{Deserialize, Serialize};
use crate::api::message::meta::*;
use crate::api::message::amount::{Amount, string_or_struct};
use std::error::Error;
#[derive(Serialize, Deserialize, Debug)]
pub struct RequestTxCommand {
#[serde(rename="id")]
id: u64... |
#![feature(iterator_fold_self)]
#[macro_use]
extern crate lazy_static;
extern crate num;
pub mod vigenere;
|
//! A library for reading and writing TAR archives
//!
//! This library provides utilities necessary to manage [TAR archives][1]
//! abstracted over a reader or writer. Great strides are taken to ensure that
//! an archive is never required to be fully resident in memory, and all objects
//! provide largely a streaming... |
fn main(){
proconio::input!{n:u32,m:usize,ss:[(usize, char);m]};
let ans = (0..10i32.pow(n))
.filter(|x| {
let x = x.to_string().as_bytes().to_vec();
x.len() == n as usize
&& ss
.iter()
.all(|(s,c)| matches!(x.get(*s-1), Some(x) if *x as char == *c))
})
.next()
.un... |
extern crate rand;
#[cfg(feature="blas")]
extern crate blas_sys;
extern crate time;
extern crate libc;
extern crate rustc_serialize;
extern crate bincode;
#[macro_use]
extern crate log;
mod model;
pub use model::Model;
pub mod dictionary;
pub use dictionary::Dict;
pub mod matrix;
pub use matrix::Matrix;... |
use std::string::String;
use std::vec::Vec;
use unicode_normalization::UnicodeNormalization;
const ALPHABET_LENGTH: u8 = 26;
pub fn encrypt(message: &String, key: u8) -> String {
let mut result: Vec<char> = Vec::new();
for grapheme in message.nfd() {
if grapheme.is_alphabetic() {
let orig... |
use super::*;
#[test]
fn with_number_or_atom_second_returns_second() {
run!(
|arc_process| {
(
strategy::term::local_reference(arc_process.clone()),
strategy::term::number_or_atom(arc_process.clone()),
)
},
|(first, second)| {
... |
use std::collections::LinkedList;
#[derive(Debug, Clone)]
pub struct FlattenProjectDependency {
pub name : String,
pub version : String,
pub repositoryUrl : String
}
impl FlattenProjectDependency {
pub fn new(name : String, version : String, repositoryUrl : String) -> FlattenProjectDependency
{
... |
use criterion::{criterion_group, criterion_main, Criterion};
use weather_util_rust::{weather_data::WeatherData, weather_forecast::WeatherForecast};
pub fn criterion_benchmark(c: &mut Criterion) {
let buf = include_str!("../tests/weather.json");
let data: WeatherData = serde_json::from_str(buf).unwrap();
... |
use crate::commands::WholeStreamCommand;
use crate::context::CommandRegistry;
use crate::prelude::*;
use nu_errors::ShellError;
use nu_protocol::{ColumnPath, ReturnSuccess, Signature, SyntaxShape, UntaggedValue, Value};
use nu_value_ext::ValueExt;
pub struct Edit;
#[derive(Deserialize)]
pub struct EditArgs {
fiel... |
use winapi::um::winuser::*;
use event::{KeyId, RawEvent, State};
#[derive(Clone, Debug, PartialEq, Eq)]
enum KeyPos {
Left,
Right,
}
pub fn process_keyboard_data(raw_data: &RAWKEYBOARD, id: usize) -> Vec<RawEvent> {
let mut output: Vec<RawEvent> = Vec::new();
let flags = raw_data.Flags as u32;
let... |
#![no_std]
#![no_main]
extern crate panic_halt;
use atmega168_hal::prelude::*;
#[atmega168_hal::entry]
fn main() -> ! {
let mut current_level = 0;
let mut target_level = 0;
let dp = atmega168_hal::pac::Peripherals::take().unwrap();
let mut port_b = dp.PORTB.split();
let mut port_c = dp.PORTC.spl... |
use std::cell::RefCell;
use std::rc::Rc;
use super::row::{PrivateSqliteRow, SqliteRow};
use super::stmt::StatementUse;
use crate::result::QueryResult;
#[allow(missing_debug_implementations)]
pub struct StatementIterator<'a> {
inner: PrivateStatementIterator<'a>,
column_names: Option<Rc<[Option<String>]>>,
... |
use crate::common::{boxvec::BoxVec, lock::PyMutex};
use crate::{
builtins::{
asyncgenerator::PyAsyncGenWrappedValue,
function::{PyCell, PyCellRef, PyFunction},
tuple::{PyTuple, PyTupleTyped},
PyBaseExceptionRef, PyCode, PyCoroutine, PyDict, PyDictRef, PyGenerator, PyList, PySet,
... |
//! Data structures to export a type as though it were a module.
use std::fmt::{self, Display};
use core_extensions::SelfOps;
use crate::{reflection::ModReflMode, type_layout::*};
#[derive(Debug, Serialize, Deserialize)]
pub struct MRItem {
item_name: String,
type_: String,
field_accessor: MRFieldAccess... |
// This file is part of linux-epoll. It is subject to the license terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/linux-epoll/master/COPYRIGHT. No part of linux-epoll, including this file, may be copied, modified, propagated, or distri... |
/*!
Native Windows GUI menu base.
*/
use winapi::shared::windef::{HMENU, HWND};
use winapi::shared::minwindef::UINT;
use super::base_helper::{CUSTOM_ID_BEGIN, to_utf16};
use crate::controls::ControlHandle;
use crate::{NwgError};
use std::{mem, ptr};
use std::sync::atomic::{AtomicU32, Ordering};
static MENU_ITEMS_ID: ... |
//! Definition of response structure.
use std::cmp;
use std::fmt;
use std::ops::Index;
/// Representation of a header.
///
/// For convenience, the header value is trimmed at parsing time (optional spaces are
/// removed from the beginning and the end of the value).
#[derive(PartialEq, Eq, Debug)]
pub struct Header {... |
use core::JsRuntime;
fn main() {
let mut runtime = JsRuntime::new(Default::default());
runtime
.execute(
"<init>",
r#"
const module = new WebAssembly.Module(new Uint8Array([
0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, 0x01, 0x07, 0x01,
0x60, 0x02, 0x7f, 0x7f, 0x01, 0x7f, ... |
#[macro_use]
mod macros;
use itertools::EitherOrBoth;
use itertools::Itertools;
#[cfg(feature = "regex")]
pub use regex;
use std::collections::{BTreeMap, HashMap};
use std::fmt;
use std::iter::FromIterator;
use std::ops::{Deref, DerefMut};
fn segmented(str: &str) -> impl Iterator<Item = &str> {
str.split('/').fil... |
#[no_mangle]
pub fn sum(addr: i32, size: i32) -> i64 {
let v_size = 1000000000;
let mut v = vec![0u8];
for _ in 0..v_size {
v.push(0);
}
let mut u = vec![0u8];
for _ in 0..v_size {
u.push(0);
}
let mut result = 0i64;
let addr = addr as *mut u8;
let input = unsaf... |
#[derive(PartialEq, Eq, Copy, Clone, Debug)]
pub enum Region {
TL,
TR,
BL,
BR,
}
#[derive(Copy, Clone, Debug)]
pub struct Rect {
pub cx: f32,
pub cy: f32,
pub width: f32,
pub height: f32,
}
impl Rect {
fn quad(self, x: f32, y: f32) -> Region {
let is_left = x < self.cx;
... |
// 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::env;
use std::fmt;
use std::io::BufReader;
use std::io::BufRead;
use std::fs::File;
use std::ops::Add;
use std::ops::Div;
use std::collections::HashMap;
use std::collections::HashSet;
#[derive(Copy,Clone,Hash,Eq,PartialEq,PartialOrd,Ord)]
struct Point {
x: u32,
y: u32,
}
fn manhattan_distance(p: &Po... |
use crate::constants::*;
use crate::obstacle::Obstacle;
use crate::rocket::Rocket;
use crate::target::Target;
use rand::seq::SliceRandom;
use sdl2::rect::Point;
pub const ROCKET_HEIGHT: u32 = 15;
pub const ROCKET_WIDTH: u32 = 3;
pub struct Population {
pub rockets: Vec<Rocket>,
origin: Point,
mating_poo... |
use crate::mechanics::damage::DamageMultiplier;
use crate::types::effectiveness::effectiveness_maps::EffectivenessMaps;
use crate::types::MonsterType;
mod effectiveness_maps;
lazy_static! {
pub static ref EFFECTIVENESS_MAPS: EffectivenessMaps = EffectivenessMaps::default();
}
impl MonsterType {
/// Returns a... |
use parser::{Parser, Error as ParseError};
use std::fs::File;
use std::io::Error as IoError;
use std::io::prelude::*;
use std::path::Path;
/// Represents the contents of a material file that has been loaded into memory but has not been
/// sent to the renderer.
#[derive(Debug, PartialEq, Eq)]
pub struct MaterialSource... |
// 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 agre... |
pub fn update_matrix(mat: Vec<Vec<i32>>) -> Vec<Vec<i32>> {
let (width, height) = (mat.len(), mat[0].len());
let distance = std::cell::RefCell::new(vec![vec![i32::MAX; height]; width]);
let mut stack = vec![];
for x in 0..width {
for y in 0..height {
if mat[x][y] == 0 {
... |
// Copyright 2016 PingCAP, Inc.
//
// 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 i... |
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// 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 ... |
// Copyright 2021 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 ... |
mod datatypes;
mod sig;
mod values;
#[macro_use]
extern crate serde_derive;
use ethabi::param_type::ParamType;
use ethabi::{decode, Address};
use serde::Serialize;
use values::{token_to_value, Value};
use wasm_bindgen::prelude::*;
#[cfg(feature = "wee_alloc")]
#[global_allocator]
static ALLOC: wee_alloc::WeeAlloc = ... |
#[derive(Clone, Copy, Debug, Eq, PartialEq, PartialOrd, Ord)]
pub enum Type {
Unknown = -1,
Burning = 0,
Empowered = 1,
Frozen = 2,
Hastened = 3,
Shielded = 4,
Count = 5,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Status {
pub id: i64,
pub type_: Type,
pub wizard_id: i6... |
#![allow(dead_code)]
pub mod cpu;
pub mod bus;
pub mod nes;
pub mod instructions;
pub mod opcodes;
use crate::nes::NES;
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate bitflags;
fn main() {
let mut nes = NES::new();
let testrom = vec![0xc4, 0x00, 0x01];
nes.cpu.load_rom(testrom);
... |
//! Windows system calls in the `io` module.
use crate::backend::c;
use crate::backend::conv::{borrowed_fd, ret};
use crate::backend::fd::LibcFd;
use crate::fd::{BorrowedFd, RawFd};
use crate::io;
use core::mem::MaybeUninit;
pub(crate) unsafe fn close(raw_fd: RawFd) {
let _ = c::close(raw_fd as LibcFd);
}
pub(cr... |
#[doc = "Reader of register MMIS"]
pub type R = crate::R<u32, super::MMIS>;
#[doc = "Reader of field `MIS`"]
pub type MIS_R = crate::R<bool, bool>;
#[doc = "Reader of field `CLKMIS`"]
pub type CLKMIS_R = crate::R<bool, bool>;
impl R {
#[doc = "Bit 0 - Masked Interrupt Status"]
#[inline(always)]
pub fn mis(&... |
use crate::MIXER_PARAMS;
use rand::{Rng, thread_rng};
use typenum::{U16};
use pairing::bn256::{Fr};
use crate::native::{Note, WithdrawPub, WithdrawSec};
use fawkes_crypto::native::{
num::Num,
poseidon::{MerkleProof, poseidon_merkle_proof_root}
};
pub fn gen_test_data() -> (WithdrawPub<Fr>, WithdrawSec<... |
#![feature(test)]
extern crate test;
extern crate infotree;
use infotree::cursor;
use infotree::traits::Leaf;
type CursorMut<L> = cursor::CursorMut<L, ()>;
use test::Bencher;
use std::collections::BTreeSet;
const TOTAL: usize = 8192;
#[derive(Clone)]
struct TestLeaf(usize);
impl Leaf for TestLeaf {
type Inf... |
// fn main() {
// let v = vec![1, 2, 3];
// because we've given i32 values,
// Rust can infer that the type of v is Vec<i32>,
// and the type annotation isn't necessary...
// let v: Vec<i32> = Vec::new();
// let mut v = Vec::new();
// v.push(5);
// v.push(6);
// v.push(7);
... |
#[derive(Clone, Debug)]
pub(crate) struct BinRegistry {
bins: std::collections::BTreeMap<String, crate::schema::Bin>,
fallback: bool,
}
impl BinRegistry {
pub(crate) fn new() -> Self {
Self {
bins: Default::default(),
fallback: true,
}
}
pub(crate) fn regist... |
use crate::{
gma::{GMAEntry, GMAFile, GMAFilePointers, GMAMetadata},
Transaction, GMOD_APP_ID,
};
use image::{DynamicImage, GenericImageView, ImageError, ImageFormat};
use parking_lot::Mutex;
use path_slash::PathBufExt;
use std::{
fs::File,
io::BufReader,
mem::MaybeUninit,
path::{Path, PathBuf},
sync::Arc,
};
us... |
// /*
// * Copyright 2020 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 r... |
use std::cmp::max;
use itertools::all;
use quickcheck::TestResult;
#[cfg(test)]
mod tests {
#[test]
fn it_works() {
assert_eq!(2 + 2, 4);
}
}
#[cfg(test)]
mod properties {
use super::*;
use std::collections::BTreeSet;
#[quickcheck]
// 1. Create a random list
fn iterator_parity... |
/**
El objetivo del ejercicio es implementar un programa de consola para jugar al ahorcado.
Bienvenido al ahorcado de FIUBA!
La palabra hasta el momento es: _ _ _ _ _ _
Adivinaste las siguientes letras:
Te quedan 5 intentos.
Ingresa una letra: r
La palabra hasta el momento es: _ _ _ _ _ r
Adivinaste las siguientes ... |
/*!
A very simple application that show your name in a message box.
See `basic` for the version without the derive macro
*/
extern crate native_windows_gui as nwg;
extern crate native_windows_derive as nwd;
use nwd::NwgUi;
use nwg::NativeUi;
use std::thread;
use std::sync::mpsc::{channel, Receiver};
use std... |
/*
* Rustのトレイト。(C#やJavaでいうインタフェースに類似)
* CreatedAt: 2019-06-28
*/
fn main() {
let v = vec![7, 3, 9, 1, 2];
println!("{:?}: {}", v, largest_copy(&v));
let v = vec!['d', 'f', 'a', 'z', 'c'];
println!("{:?}: {}", v, largest_copy(&v));
let v = vec!["d", "f", "a", "z", "c"];
println!("{:?}: {}", v,... |
use itertools::Itertools;
use rustc_hash::{FxHashMap, FxHashSet};
use crate::{
ast::{
self, AssignmentBody, Ast, AstError, AstKind, AstString, Function, Identifier, Int, List,
Match, MatchCase, OrPattern, Struct, Symbol, Text, TextPart,
},
cst::{self, Cst, CstDb, CstKind, UnwrapWhitespaceAn... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.