text
stringlengths
8
4.13M
use proc_macro2::{Span, TokenStream}; use quote::quote; use std::iter; use syn::Ident; use crate::composites::Field; use crate::enums::Variant; pub fn transparent_body(field: &syn::Field) -> TokenStream { let ty = &field.ty; quote! { <#ty as ::postgres_types::ToSql>::accepts(type_) } } pub fn do...
use super::visitor::Visitor; use crate::visitor::Accept; use log::info; use shared::types::*; use std::collections::HashMap; pub struct Bindings { vbls: Vec<Symbol>, usages: HashMap<Symbol, usize>, counter: usize, } impl Bindings { pub fn new() -> Self { Bindings { vbls: vec![], ...
#[derive(Debug, Clone)] pub struct Octopus<'a> { x: usize, y: usize, grid: *mut Vec<Vec<Self>>, pub energy: u32, has_flashed: bool, } impl<'a> Octopus<'a> { pub fn new(x: usize, y: usize, grid: *mut Vec<Vec<Self>>, energy: u32) -> Self { Self { x, y, g...
use std::mem; use winapi::shared::windowsx::{GET_X_LPARAM, GET_Y_LPARAM}; use std::ptr::null_mut; use winapi::shared::minwindef::*; use winapi::shared::windef::*; use winapi::um::wingdi::*; use winapi::um::winuser::*; use std::alloc::{self, Layout}; use crate::util::default_rect; use crate::brushes::*; enum ButtonSt...
use common; use std::collections::HashSet; use std::iter::FromIterator; use itertools::Itertools; /// sort string by character to create unique char fingerprint fn sort_string(s : &str) -> String { s.chars() .sorted() .iter() .collect() } /// check if given passphrase is valid /// # Argu...
// Copyright (c) The Starcoin Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::AccountInfo; use anyhow::Result; use starcoin_service_registry::ServiceRequest; use starcoin_types::account_address::AccountAddress; use starcoin_types::account_config::token_code::TokenCode; use starcoin_types::sign_mess...
use Timeout; use Timestamp; use arrayvec::ArrayVec; use buffer::Buffer; use buffer::BufferRef; use buffer::with_buffer; use protocol::ChunksIter; use protocol::ConnectedPacket; use protocol::ConnectedPacketType; use protocol::ControlPacket; use protocol::MAX_PACKETSIZE; use protocol::MAX_PAYLOAD; use protocol::Packet; ...
use std::fmt; use thiserror::Error; #[derive(Error, Debug)] pub enum DnsError { #[error(transparent)] Dns { source: CloudDnsError }, #[error(transparent)] Auth(#[from] tame_oauth::Error), #[error(transparent)] Json(#[from] serde_path_to_error::Error<serde_json::Error>), #[error(transparent...
//! シミュレータで使われる状態機械. use futures::{Async, Poll, Stream}; use raftlog::cluster::ClusterMembers; use raftlog::node::NodeId; use raftlog::Event; use std::collections::BTreeMap; use trackable::error::ErrorKindExt; use crate::process::Process; use crate::types::LogicalDuration; use crate::{DeterministicIoBuilder, Error, Er...
use std::collections::HashMap; use std::hash::Hash; #[derive(Debug)] pub struct GraphErr{ mess: String, } impl GraphErr { pub fn new(s: &str) -> Self { GraphErr { mess: s.to_string(), } } } // Mappointer based #[derive(Debug)] pub struct Graph<T, E, ID: Hash + Eq>{ // d...
use std::sync::Arc; use hyper::{body, Body, Request, Response, StatusCode, Method}; use rustc_serialize; use crate::state; use crate::messages::{HealthCheck}; type GenericError = Box<dyn std::error::Error + Send + Sync>; /// Call the web server's request handler(s). /// pub async fn call(req: Request<Body>, state:...
use crate::{ai::Ai, fighter::Fighter, item::Item, messages::Messages}; use serde::{Deserialize, Serialize}; use tcod::{colors::WHITE, BackgroundFlag, Color, Console}; /// This is a generic object: the player, a monster, an item, the stairs... /// It's always represented by a character on screen. #[derive(Debug, Serial...
use binjs_io::{ self, Deserialization, TokenReader, TokenReaderError, TokenWriterError, TokenWriterTreeAdapter, }; pub use binjs_io::{Serialization, TokenSerializer, TokenWriter}; use binjs_shared::{ self, FieldName, IdentifierName, InterfaceName, Offset, PropertyKey, SharedString, }; use std::io::{Read, Seek}...
/* 4. Detect single-character XOR One of the 60-character strings at: https://gist.github.com/3132713 has been encrypted by single-character XOR. Find it. (Your code from #3 should help.) */ extern mod extra; extern mod std; use std::trie::TrieMap; use std::io::buffered::BufferedReader; use std::io::File; mod x...
/* This file is part of bacon. * Copyright (c) Wyatt Campbell. * * See repository LICENSE for information. */ use super::{IVPSolver, IVPStatus}; use crate::roots::secant; use nalgebra::{ allocator::Allocator, dimension::DimMin, ComplexField, DefaultAllocator, DimName, RealField, VectorN, U1, U3, U7, }; use...
/// Compute the value of the counter can take depending on the values the increments can take. pub fn compute_counter({{>choice.arg_defs ../this}} ir_instance: &ir::Function, store: &DomainStore, diff: &DomainDiff) -> {{~#if half}} HalfRange {...
// Copyright 2020 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 crate::mir::trees as mir; use crate::mir::typed::*; use crate::lir::typed::*; use crate::lir::trees as lir; use crate::hir::ops::*; use crate::common::names::*; pub struct Translate; impl Translate { pub fn translate(r: &mir::Root) -> lir::Root { let externs = r.externs.iter().map(|p| lir::Param { na...
use super::{Command, Execution}; use crate::{errors::RitError, objects, repository::Repository, workspace::Entry, Session}; pub struct Add { paths: Vec<String>, repo: Repository, } impl Add { pub fn new(session: Session, paths: Vec<String>) -> Self { let repo = Repository::new(session.project_dir)...
#[macro_use] extern crate log; use std::error::Error; use std::fs; use clap::{crate_authors, crate_description, crate_name, crate_version, App, AppSettings, Arg}; use dirs; use pretty_env_logger; use smitemotd::{Model, Smite}; mod notify; #[macro_use] mod macros; mod pickledb; macro_rules! arg_env { ($arg:expr, ...
/// Public key for verifying the request pub type PublicKey<'a> = &'a [u8]; /// Private key for signing the request pub struct PrivateKey<'a> { /// ID of the associated public key (this is usually an URL pointing to the key) pub(crate) key_id: &'a str, /// Private key in PKCS#8 PEM format pub(crate) d...
use std::env; use std::fs::File; use std::io::Write; use std::path::Path; use std::process::Command; use std::panic; fn main() { panic::catch_unwind(|| { let out_dir = env::var("OUT_DIR").unwrap(); let dest_path = Path::new(&out_dir).join("commit_id.rs"); let mut f = File::create(&dest_pat...
pub struct Solution {} impl Solution { pub fn find_order(num_courses: i32, prerequisites: Vec<Vec<i32>>) -> Vec<i32> { let mut nodes = vec![vec![]; num_courses as usize]; let mut degrees = vec![0; num_courses as usize]; for prerequisite in prerequisites { nodes[prerequisite[0] a...
#[test] fn test_link() { use rustix::fs::{link, open, readlink, stat, Mode, OFlags}; let tmp = tempfile::tempdir().unwrap(); let _ = open( tmp.path().join("foo"), OFlags::CREATE | OFlags::WRONLY, Mode::RUSR, ) .unwrap(); link(tmp.path().join("foo"), tmp.path().join("li...
pub mod graph_build_error; pub mod parse_attr_error;
use erased_serde::serialize_trait_object; use futures::executor; use crate::{ characteristic::{ accessory_flags::AccessoryFlagsCharacteristic, hardware_revision::HardwareRevisionCharacteristic, HapCharacteristic, }, pointer, service::{accessory_information::AccessoryInformationS...
use syntax::ast::TokenTree::{self, TtToken}; use syntax::codemap::Span; use syntax::ext::base::{ExtCtxt, MacEager, MacResult}; use syntax::parse::token::IdentStyle::Plain; use syntax::parse::token::Token::{Comma, Ident}; use syntax::util::small_vector::SmallVector; pub fn expand<'cx>(ecx: &'cx mut ExtCtxt, span: Span,...
extern crate fbas_analyzer; use fbas_analyzer::*; extern crate csv; extern crate serde; use quicli::prelude::*; use structopt::StructOpt; use std::collections::BTreeMap; use std::error::Error; use std::io; use std::path::PathBuf; use csv::{Reader, Writer}; use par_map::ParMap; use sha3::{Digest, Sha3_256}; /// Bul...
pub struct Solution {} impl Solution { pub fn num_trees(n: i32) -> i32 { if n < 3 { return n; } let n = n as usize; let mut counts = vec![1; n + 1]; for i in 2..=n { counts[i] = (0..i).map(|idx| counts[idx] * counts[i - 1 - idx]).sum(); } ...
use crate::{print, user}; pub fn main(args: &[&str]) -> user::shell::ExitCode { let n = args.len(); for i in 1..n { print!("{}", args[i]); if i < n - 1 { print!(" "); } } print!("\n"); user::shell::ExitCode::CommandSuccessful }
use shipyard::prelude::*; #[system(RefMut)] fn run(ref mut usizes: &mut usize) { let _result: Result<&mut usize, _> = usizes.get(EntityId::dead()); } #[system(Ref)] fn run(ref usizes: &usize, ref u32s: &u32) { (usizes, u32s).get(EntityId::dead()).unwrap(); (usizes, u32s).get(EntityId::dead()).unwrap(); ...
use message_types::bs_ps::BackgroundStatus; use serde::{Deserialize, Serialize}; use std::collections::HashSet; use wallet::BalanceEntry; use yew::worker::*; #[derive(Serialize, Deserialize, Debug)] pub enum Request { WalletBalanceUpdate(Vec<BalanceEntry>), BackgroundStatus(BackgroundStatus), } #[derive(Serial...
mod map; mod widget; use super::core; use super::temp; use crate::common::url; use crate::prelude::*; use clap::Args; use clap::Parser; const POSSIBLE_VALUES: &[&str] = &[ "url::open", "welcome", "widget::last_command", "map::expand", "temp", ]; impl FromStr for Func { type Err = &'static str...
/* * Copyright 2018-2020 TON DEV SOLUTIONS LTD. * * Licensed under the SOFTWARE EVALUATION License (the "License"); you may not use * this file except in compliance with the License. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS I...
use support::project; macro_rules! touch_command { ($project:ident, $file_name:literal) => { if cfg!(windows) { format!("cmd /c copy nul {}\\{}", $project.path().display(), $file_name) } else { format!("touch {}", $file_name) } }; } #[test] fn test_git_clean_wo...
#![allow(unused_imports)] use ate_files::accessor::FileAccessor; use tracing::{info, warn, debug, error, trace, instrument, span, Level}; use std::ffi::{OsStr, OsString}; use std::sync::Arc; use std::time::{Duration, SystemTime}; use std::vec::IntoIter; use parking_lot::Mutex; use ::ate::{crypto::DerivedEncryptKey, p...
fn foo() -> [u8; 1024] { let x = [0; 1024]; return x; } fn main() { println!("Hello, world!"); }
use std::{borrow::Cow, fmt}; use regex::Regex; use crate::{ pattern::{Pattern, PatternElement}, scoring, }; #[derive(Clone, Copy)] pub struct ClustererOptions { pub max_dist: f64, pub min_members: u32, } pub struct Clusterer { clusters: Vec<Cluster<'static>>, options: ClustererOptions, p...
#[doc = "Register `STAT` reader"] pub struct R(crate::R<STAT_SPEC>); impl core::ops::Deref for R { type Target = crate::R<STAT_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<STAT_SPEC>> for R { #[inline(always)] fn from(reader: crate::R<STAT_SP...
/* * @lc app=leetcode id=1131 lang=rust * * [1131] Maximum of Absolute Value Expression * * https://leetcode.com/problems/maximum-of-absolute-value-expression/description/ * * algorithms * Medium (49.55%) * Total Accepted: 2.4K * Total Submissions: 4.7K * Testcase Example: '[1,2,3,4]\r\n[-1,4,5,6]\r' * ...
use async_std::net::{TcpListener, TcpStream}; use async_std::prelude::*; use async_std::task::sleep; use spwn::spwn; use std::{io::Error as IoError, time::Duration}; pub async fn test_asyncstd_net(port: usize) -> Result<(), IoError> { spwn!(server(port)); sleep(Duration::from_millis(100)).await; let r = ...
use std::boxed::Box; use std::iter::DoubleEndedIterator; #[derive(PartialEq, Eq, Clone, Debug)] pub struct ListNode { pub val: i32, pub next: Option<Box<ListNode>> } impl ListNode { #[inline] fn new(val: i32) -> Self { ListNode { next: None, val } } } impl ListNode { #[inline] p...
use std::io::{Error, ErrorKind, Result}; use std::pin::Pin; use std::task::{Context, Poll}; use crate::{AsyncReadAll, AsyncWriteAll, Request, Response}; use hash::Hash; use protocol::Protocol; pub struct AsyncSharding<B, H, P> { idx: usize, shards: Vec<B>, hasher: H, parser: P, } impl<B, H, P> AsyncS...
//! A shape type representing spheres used for drawing. //! //! # Examples //! //! You can create a [Sphere] using [`Sphere::new`]: //! //! ``` //! # use pix_engine::prelude::*; //! let s = Sphere::new(10, 20, 100, 200); //! ``` //! //! ...or by using the [sphere!] macro: //! //! ``` //! # use pix_engine::prelude::*; /...
use super::server_core; use std::net::{SocketAddr}; use std::{thread}; extern crate signal_hook; use std::io::Error; use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; pub fn main(my_addr: SocketAddr, parent_addr: SocketAddr) -> Result<(), Error> { let mut server: server_core::ServerCore = serve...
extern crate loggerv; extern crate rumqtt; use std::thread; use std::time::Duration; use rumqtt::{MqttClient, MqttOptions, ReconnectOptions}; fn main() { loggerv::init_with_verbosity(1).unwrap(); let mqtt_opts = MqttOptions::new("rumqtt-core", "127.0.0.1:1883") .set_reconnect_opts(ReconnectOptions::A...
use winapi::um::taskschd::IRegisteredTask; use super::IUnknownWrapper; pub struct RegisteredTask(IUnknownWrapper<IRegisteredTask>); impl From<*mut IRegisteredTask> for RegisteredTask { fn from(definition: *mut IRegisteredTask) -> Self { Self(definition.into()) } }
use serde::{Deserialize, Serialize}; #[derive(Clone, Deserialize, Serialize)] #[cfg_attr( feature = "config-schema", derive(schemars::JsonSchema), schemars(deny_unknown_fields) )] #[serde(default)] pub struct TimeConfig<'a> { pub format: &'a str, pub style: &'a str, pub use_12hr: bool, #[se...
use std::io; //apparament dans ce langage, pour dire le type qui va être retourné, on utilise -> type pub fn menu() -> i32 { println!(" Menu: \n Que souhaitez vous faire? \n 1) Nouvelle partie \n 2) Charger une partie \n 3) Quitter le jeu"); let mut choix = String::new(); io::stdin() ...
#[macro_use] pub mod macros; pub mod activation; pub mod aggregation; pub mod checkpoint; pub mod config; pub mod fitness; pub mod gene; pub mod genome; pub mod innovation; pub mod speciation;
//! This library provides [`eyre::ErrReport`][ErrReport], a trait object based error //! type for easy idiomatic error handling in Rust applications. //! //! This crate is a fork of [`anyhow`] by @dtolnay. By default this crate does not //! add any new features that anyhow doesn't already support, though it does rename...
use sycamore_router::Route; #[derive(Route)] enum Routes1 { #[not_found] NotFound, } #[derive(Route)] enum Routes2 { #[to("/")] Home, #[to("/about")] About, #[not_found] NotFound, } #[derive(Route)] enum Routes3 { #[to("/hello/<name>/<age>")] Hello(String, u32), #[to("/acc...
/// This is an example for using different auths with actix use actix_files::Files; use actix_web::{http::header, middleware, web, App, HttpResponse, HttpServer}; use std::fs; mod auth; mod config; mod db; mod handlers; mod models; mod templating; #[actix_rt::main] async fn main() -> std::io::Result<()> { env_log...
use super::fs; use super::transpiler; use anyhow::Error; use regex::Regex; pub struct Transpiler {} impl Transpiler { pub fn new() -> Self { Self {} } } lazy_static! { static ref REGEX: Regex = Regex::new(r"(\s*)([^\s]*)\(([^\)]+)").expect("Invalid regex"); } impl transpiler::Transpiler for Tran...
use log::{debug, error}; use crate::{ traits::*, BuildServer, Git, Minifest, RemoteBuildError, Svn, VcsSystem, utils, Flavors, utils::request_build_for, cli::Opt }; use std::env; /// set up the build using local information gleaned from the manifest and the local vcs repo pub fn do_local( opts: Opt) -> ...
//! An Intermediate Representation based on LLVM for compiler construction. //! pub mod value; pub mod instruction; pub mod basic_block; pub mod function;
use crate::sign; use serde_derive::{Deserialize, Serialize}; use sodiumoxide::crypto::box_; use sodiumoxide::crypto::sign::ed25519::{PublicKey, SecretKey}; /// Basic Node configuration #[derive(Serialize, Deserialize, Debug)] pub struct NodeConfig { pub public_key: String, pub secret_key: String, pub port:...
use hyper::Client; use hubcaps::{Github, ReleaseOptions, Credentials}; use error::Error; use super::USERAGENT; use config::Config; pub fn release(config: &Config, tag_name: &str, tag_message: &str) -> Result<(), Error> { let user = &config.user[..]; let repo_name = &config.repository_name[..]; let bra...
use crate::{FromPyObject, IntoPy, PyAny, PyObject, PyResult, Python, ToPyObject}; use std::borrow::Cow; use std::ffi::OsString; use std::path::{Path, PathBuf}; impl ToPyObject for Path { fn to_object(&self, py: Python) -> PyObject { self.as_os_str().to_object(py) } } // See osstr.rs for why there's no...
impl Default for Status { fn default() -> Self { Status::Success } } // I0x6985SO/IEC 7816-4, 5.1.3 "Status bytes" #[derive(Copy, Clone, Debug, Eq, PartialEq)] pub enum Status { ////////////////////////////// // Normal processing (90, 61) ////////////////////////////// /// 9000 Success, ...
use std::path::PathBuf; use std::time::{SystemTime, UNIX_EPOCH}; use std::process::{Command, Stdio}; use std::io::{Write, stderr}; use log::LogLevel; use global::GLOBAL; #[derive(Debug)] pub struct BackupEntity { pub path: PathBuf, pub recursive: bool, pub trigger_changes: u64, pub trigger_timer: u64,...
extern crate rand; use std::io; // Allow us to get access to the standart input use std::cmp::Ordering; /* Returns the number entered by the use */ fn get_number() -> u32 { let mut number = String::new(); io::stdin().read_line(&mut number) .expect("Failed to read the line"); let guess: u32...
use crate::{CalendarEvent, ID}; use itertools::Itertools; use rand::{thread_rng, Rng}; use serde::{Deserialize, Serialize}; /// Round robin algorithm to decide which member should be assigned a /// `Service Event` when there are multiple members of a `Service` #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]...
use std::io::{self, ErrorKind, Read, Write}; use std::net::TcpStream; use std::sync::mpsc::{self, TryRecvError}; use std::thread; use std::time::Duration; fn main() { println!("Hello, world!"); }
/** * [1376] Time Needed to Inform All Employees * * A company has n employees with a unique ID for each employee from 0 to n - 1. The head of the company is the one with headID. Each employee has one direct manager given in the manager array where manager[i] is the direct manager of the i-th employee, manager[headI...
use card_deck::Deck; use crate::strategy::Strategy; use crate::track::{Rider, RiderType, Track}; pub fn rouler_cards() -> Deck<usize> { Deck::new(vec![3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6, 7, 7, 7]) } pub fn sprinter_cards() -> Deck<usize> { Deck::new(vec![2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 9, 9, 9]) } pub f...
use std::fmt; #[derive(Debug, Clone, Copy)] pub struct Location { pub begin: Position, pub end: Position, } #[derive(Debug, Clone, Copy)] pub struct Position { pub line: usize, pub column: usize, } impl Location { pub fn new(begin_line: usize, begin_column: usize, en...
#[derive(Debug)] pub enum Error { IO(std::io::Error), Parse, } impl std::error::Error for Error { } impl std::fmt::Display for Error { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Error::IO(e) => e.fmt(f), Error::Parse => f.write_str("Parse error"), } }...
use std::sync::Arc; use async_trait::async_trait; use prost::Message; use super::Storage; use crate::{ error::Result, format::{TableBuilder, TableDesc, TableReader, Timestamp}, }; pub struct HybridStorage { read: Arc<dyn Storage>, writes: Vec<Arc<dyn Storage>>, } impl HybridStorage { #[allow(dea...
// Integers are encoded with LEB128 (Little Endian Base 128) // - https://webassembly.github.io/spec/core/binary/values.html#integers // - https://en.wikipedia.org/wiki/LEB128 use crate::error::ErrorKind; type Result<T> = ::std::result::Result<T, Box<ErrorKind>>; // Note: Self must be Sized because trait function re...
#[doc = "Reader of register SOPT1_CFG"] pub type R = crate::R<u32, super::SOPT1_CFG>; #[doc = "Writer for register SOPT1_CFG"] pub type W = crate::W<u32, super::SOPT1_CFG>; #[doc = "Register SOPT1_CFG `reset()`'s with value 0"] impl crate::ResetValue for super::SOPT1_CFG { type Type = u32; #[inline(always)] ...
use crate::cryptocurrency::Cryptocurrency; use crate::currency::Currency; use serde::{Deserialize, Serialize}; // THIS IS SO ANNOYING!!! :( #[derive(Deserialize, Serialize, Clone, Copy, PartialEq, PartialOrd)] #[serde(try_from = "&str", into = "String")] pub struct KrakenFloat(f64); impl Into<String> for KrakenFloat ...
use num::BigUint; fn main() { let x = "3141592653589793238462643383279502884197169399375105820974944592".parse::<BigUint>().unwrap(); let y = "2718281828459045235360287471352662497757247093699959574966967627".parse::<BigUint>().unwrap(); let result = integer_multiplication::karatsuba_multiplication(&x, &y, ...
use std::convert::TryInto; use std::iter; use group::ff::Field; use halo2_proofs::{ circuit::{AssignedCell, Cell, Chip, Layouter, Region, Value}, plonk::{ Advice, Any, Column, ConstraintSystem, Constraints, Error, Expression, Fixed, Selector, }, poly::Rotation, }; use super::{ primitives::...
use crate::{ hittables::hittable::HitRecord, rays::ray::Ray, utils::vec3_utils::{dot, reflect, unit_vector}, vectors::vec3::Vec3, }; use super::material::Material; use std::option::Option; pub struct Metal { pub albedo: Vec3, pub fuzz: f64, } impl Material for Metal { fn scatter(&self, r...
use tomorrow_recuperator::Request; pub struct GoogleRequest { pub query: String } impl GoogleRequest { pub fn new(query: &str) -> Self { GoogleRequest { query: format!("search?q={}", query) } } } impl Request for GoogleRequest {}
#[doc = "Register `BMSTRG` reader"] pub struct R(crate::R<BMSTRG_SPEC>); impl core::ops::Deref for R { type Target = crate::R<BMSTRG_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<BMSTRG_SPEC>> for R { #[inline(always)] fn from(reader: crate::R...
use ezmath::*; /// chunk component #[derive(Debug, Clone)] pub struct CChunk { /// position of the min block in the chunk pos: int3, } impl CChunk { /// create a new chunk component, given the minimum chunk /// position. that position is automatically adjusted to /// snap to the 32x32x32 chunk gri...
use chrono::TimeZone; use chrono_tz::{Tz, UTC}; use serde::{Deserialize, Serialize}; #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub enum OutlookCalendarAccessRole { Writer, Reader, } // https://docs.microsoft.com/en-us/graph/api/resources/datetimetimezone?view=graph-rest...
extern crate image; extern crate minifb; extern crate rand; use minifb::{Key, Window, WindowOptions}; use rand::Rng; use std::ops::Add; use std::ops::Div; use std::ops::Mul; use std::ops::Sub; use std::path::Path; use std::time::Instant; const RESOLUTION: usize = 768; #[derive(Copy, Clone, Debug)] st...
use std::cell::RefCell; use std::collections::hash_map::Entry; use std::collections::HashMap; use std::ops::RangeInclusive; #[derive(Debug, Hash, PartialEq, Eq, PartialOrd, Ord)] struct BankAddress(Option<i16>, u16); #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] struct Symbol { synthetic: bool, symb...
use iron::{Middleware, Request, Response, Status}; use std::sync::Arc; /// `Middleware` implementing this trait can be linked using `Shared` so that /// they are not cloned for each request. This can vastly improve performance /// for immutable middleware that are not modified while handling requests. pub trait Sharea...
#![feature(core_intrinsics)] use std::mem; fn main() { let x: Option<Box<[u8]>> = unsafe { let z = std::intrinsics::add_with_overflow(0usize, 0usize); std::mem::transmute::<(usize, bool), Option<Box<[u8]>>>(z) }; let y = &x; // Now read this bytewise. There should be (`ptr_size + 1`) d...
mod functions; fn main() { let input = functions::file_utils::get_input(); println!("Done getting Input"); println!("Result: {}", input.iter().filter(|&n| n.is_valid()).count()); println!( "Result2: {}", input.iter().filter(|&n| n.is_valid2()).count() ); }
use linux_io_uring::{ opcode, IoUring }; #[test] fn test_full() -> anyhow::Result<()> { let mut io_uring = IoUring::new(4)?; // squeue full { let mut queue = io_uring.submission().available(); assert!(queue.is_empty()); for _ in 0..queue.capacity() { unsafe { ...
// 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...
// variables3.rs // Make me compile! Execute the command `rustlings hint variables3` if you want a hint :) /* By default, all variables behave like in functional programming languages, * where the value of the variable is immutable. We must explicitly state that * the variable is mutable to change it after its initi...
pub mod syntax; pub use self::syntax::*;
#![feature(globs)] extern crate native; extern crate glfw; extern crate gl; use glfw::Context; use gl::types::*; // Vertex data static vertices: [GLfloat, ..6] = [ 0.0, 0.5, 0.5, -0.5, -0.5, -0.5 ]; // Shader sources static vertex_src: &'static str = "#version 330\n\ in vec2 position;\n\ v...
extern crate web_logger; extern crate yew; extern crate trading; use yew::prelude::*; use yew::services::fetch::FetchService; use trading::context::Context; use trading::Model; fn main() { web_logger::init(); yew::initialize(); let context = Context::new(); let app: App<_, Model> = App::new(context); ...
use std::fs::File; use std::io::prelude::*; use std::io::BufReader; use std::str::FromStr; use clap::{App, Arg}; fn main() -> std::io::Result<()> { let matches = App::new("AOC2020 Day 2") .arg( Arg::with_name("INPUT") .help("Input file name") .required(true) ...
use std::ops::Range; /// Array Shape Structure #[derive(Clone)] pub struct Shape { shape: Vec<i32>, strides: Vec<usize>, start: usize, end: usize, } impl Shape { /// Returns shape products for easier converting indices to linear index /// /// # Arguments /// /// * `shape` - Shape...
fn main() { let v: Vec<u32> = vec![1, 2, 3]; }
use parking_lot::RwLock; use std::{ any::{Any, TypeId}, hash::{BuildHasher, Hash}, sync::Arc, }; type ErrorObject = Arc<dyn Any + Send + Sync + 'static>; type Waiter<V> = Arc<RwLock<Option<Result<V, ErrorObject>>>>; pub(crate) enum InitResult<V, E> { Initialized(V), ReadExisting(V), InitErr(Ar...
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may...
//@ignore-target-windows: File handling is not implemented yet //@error-in-other-file: `open` not available when isolation is enabled fn main() { let _file = std::fs::File::open("file.txt").unwrap(); }
use super::water; #[derive(Clone, Copy, PartialEq, Eq)] pub enum Crop { // biennial (harvest and replant each year) Root, // annual Bean, // specialize into clover :o // very short lived perennial that can adapt to summer or winter Gourd, // perennial? usable as straw, hay, and cereal G...
use std::{thread::sleep, time::Duration}; use image::{open, GrayImage}; use rand::{thread_rng, Rng}; fn main() { // 1. perkenalan // 2. tools // 3. + - // 4. algoritma // 5. run // 6. penutup let mut img = open("sora.jpg").unwrap().into_luma8(); let mut k1 = generate_random_index(256)...
// Lumol, an extensible molecular simulation engine // Copyright (C) Lumol's contributors — BSD license //! Metropolis Monte Carlo propagator implementation use std::ops::{Deref, DerefMut}; use rand::{self, Rng, SeedableRng}; use log::{warn, info, trace}; use lumol_core::consts::K_BOLTZMANN; use lumol_core::{Degree...
mod mocks; use std::sync::Arc; use tempdir::TempDir; use octobot::config::Config; use octobot::db::Database; use octobot::github; use octobot::messenger::{self, Messenger}; use octobot::slack; use mocks::mock_slack::MockSlack; fn new_test() -> (Arc<Config>, TempDir) { let temp_dir = TempDir::new("repos.rs").un...