text
stringlengths
8
4.13M
//! This crate includes the compiled python bytecode of the RustPython standard library. The most //! common way to use this crate is to just add the `"freeze-stdlib"` feature to `rustpython-vm`, //! in order to automatically include the python part of the standard library into the binary. // windows needs to read the...
#[macro_export] macro_rules! check_value { ($block: expr, $key: expr) => { check_none!($block, $key); check_off!($block, $key); }; } #[macro_export] macro_rules! check_none { ($block: expr, $key: expr) => { match $block.get($key) { Some(d) => { if d.is_bl...
use crate::entities::Item; use crate::game_event::GameEventType; use crate::room::RoomType; use crate::sound::AudioEvent; pub enum ActionHandled { Handled, NotHandled, } #[derive(Debug, PartialEq, Eq, Hash, Clone, Display)] pub enum Action { // System Actions. Tick(u64), Message(String, GameEventT...
mod pushable; pub use self::pushable::Pushable;
use crate::bindings::*; use crate::core::*; use crate::http::status::*; use std::ptr; use std::os::raw::c_void; #[macro_export] macro_rules! http_request_handler { ( $x: ident, $y: expr ) => { #[no_mangle] extern "C" fn $x(r: *mut ngx_http_request_t) -> ngx_int_t { let status: Status ...
use std::cell::RefCell; use std::collections::HashMap; use std::sync::{Arc, Mutex}; use crate::config::Config; use crate::exts::LockIt; use crate::signals::order::{ dev_mgmt::{SessionManager, CAPS_MANAGER}, server_actions::SendData, }; use crate::tts::{Gender, Tts, TtsData, TtsFactory, VoiceDescr}; use anyhow...
// Copyright 2020 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use { fuchsia_async as fasync, fuchsia_cobalt::{CobaltConnector, CobaltSender, ConnectionType}, time_metrics_registry::{ RealTimeClockE...
/* * 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 required by applicable law or a...
use rwm::config::Config; use rwm::manager::Manager; use simple_logger; use rwm::displays::xcb_server::XcbDisplayServer; #[tokio::main] async fn main() { simple_logger::init().unwrap(); Manager::<XcbDisplayServer>::new(Config::new()).stream().await; }
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)]...
use crate::{common::*, functional::Func}; pub use base::*; pub use ops::*; mod base { // maybe def /// A trait analogous to [Option](std::option::Option). pub trait Maybe {} // just def /// A type analogous to `Some`. pub struct Just<T>(T); impl<T> Maybe for Just<T> {} // nothing ...
use bevy::{math::*, prelude::*}; use meshie::Meshie; pub mod systems; pub struct MovementDebug; #[derive(Default, Debug)] pub struct EffectsResource { pub mesh_handle: Handle<Mesh>, pub availability: Vec<Availability>, pub vertices: Vec<ds_range::Range>, pub chunk_size: u32, pub max_chunks: u32, ...
use polyhedron_ops as p_ops; fn nsi_camera(c: &nsi::Context, name: &str, _camera_xform: &[f64; 16], samples: u32) { // Setup a camera transform. c.create("camera_xform", nsi::NodeType::Transform, &[]); c.connect("camera_xform", "", ".root", "objects", &[]); c.set_attribute( "camera_xform", ...
use std::env; use std::fs; use std::process; use tini::prelude::*; fn main() { let mut args = env::args().skip(1); let filename = match args.next() { Some(arg) => arg, None => { eprintln!("Error: too few arguments. Expected one."); println!("Usage: tinii <file>"); ...
///Defines a payoff applied to the underlying spot value. pub trait Payoff { ///Applies the payoff to the spot value of the underlying. fn apply(&self, spot: f64) -> f64; } ///Defines the payoff for a Call Option #[derive(Debug)] pub struct CallPayoff { strike: f64, } impl CallPayoff { pub fn new(stri...
// #![windows_subsystem = "windows"] // #![warn(bare_trait_objects)] extern crate ggez; // mod imgui_wrapper; // extern crate nalgebra; // use rand::{thread_rng, Rng}; // use nalgebra::{Point2, Vector2}; // use crate::imgui_wrapper::ImGuiWrapper; use ggez::{ conf, event::{self, EventHandler, KeyCode, KeyMod...
#[doc = "Reader of register NWDA2"] pub type R = crate::R<u32, super::NWDA2>; #[doc = "Reader of field `NEWDAT`"] pub type NEWDAT_R = crate::R<u16, u16>; impl R { #[doc = "Bits 0:15 - New Data Bits"] #[inline(always)] pub fn newdat(&self) -> NEWDAT_R { NEWDAT_R::new((self.bits & 0xffff) as u16) ...
use std::fmt; use std::marker::PhantomData; use bytes::{Buf, BufMut}; use prost::{DecodeError, Message}; use tower_grpc::client::codec::{Codec, DecodeBuf, EncodeBuf}; /// A protobuf codec. pub struct Protobuf<T, U>(PhantomData<(T, U)>); impl<T, U> Protobuf<T, U> { pub fn new() -> Self { Protobuf(PhantomD...
mod srs; pub use gdal_sys::OGRAxisOrientation; pub use srs::{AxisOrientationType, CoordTransform, SpatialRef}; #[cfg(test)] mod tests;
use std::collections::HashMap; use rust_mal_lib::types::{MalError, MalResult, MalValue}; use rust_mal_lib::{env::Environment, reader, types}; use rust_mal_steps::scaffold::*; #[derive(Clone)] struct FlatEnv { data: HashMap<String, MalValue>, } impl Environment for FlatEnv { fn new(_outer: Option<&Self>) -> ...
#[macro_use] pub mod counter; mod metrics; pub use crate::metrics::flush; pub use crate::metrics::query; pub use crate::metrics::set_panic_hook; pub use crate::metrics::submit; pub use influx_db_client as influxdb;
#[doc = "Reader of register MMCTXRIS"] pub type R = crate::R<u32, super::MMCTXRIS>; #[doc = "Reader of field `GBF`"] pub type GBF_R = crate::R<bool, bool>; #[doc = "Reader of field `SCOLLGF`"] pub type SCOLLGF_R = crate::R<bool, bool>; #[doc = "Reader of field `MCOLLGF`"] pub type MCOLLGF_R = crate::R<bool, bool>; #[do...
use std::collections::HashMap; fn main() { let mut map = HashMap::new(); map.insert('(', ')'); map.insert('[', ']'); map.insert('{', '}'); println!("{:?}", map.get(&'[') == Some(&']')); let mut stack = Vec::new(); stack.push(']'); let x = '['; match (stack.pop().as_ref(), map...
/* Copyright (c) 2015, 2016 Saurav Sachidanand Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, di...
use crate::fs_helper::AppContext; use std::collections::HashMap; use uuid::Uuid; const VAL_STRING2: &str = "asd"; const VAL_DEFAULT: &str = "default"; const VAL_LOCAL_DATE: &str = "2021-01-01"; const VAL_LOCAL_DATE_TIME: &str = "2021-01-01T00:00:00"; const VAL_INTEGER: &str = "1"; const VAL_DOUBLE: &str = "1.3"; const...
use iced::{ pick_list, button, scrollable, Element, Row, PickList, Scrollable, Button, Text, Align, Length, Container, }; use crate::gui::{CustomSelect, CustomButton}; use std::fmt::{Display, Formatter, Result}; #[derive(Debug, Clone)] pub struct DefaultAppPage { scroll: scrollable::State, audio_player: (&'s...
use rppal::gpio::{Gpio, Level, Trigger}; use std::{sync::mpsc, time::Instant}; const PIN: u8 = 4; fn main() { let gpio = Gpio::new().unwrap(); let mut pin = gpio.get(PIN).unwrap().into_input(); let start = Instant::now(); let mut pulses: Vec<(Level, f64)> = vec![]; let (tx, rx) = mpsc::channel(...
pub fn sort(array: &mut [isize]) { sort_in_range(array, 0, array.len() - 1); } fn sort_in_range(array: &mut [isize], first: usize, last: usize) { if first < last { let midpoint = partition(array, first, last); sort_in_range(array, first, midpoint - 1); sort_in_range(array, midpoint + 1,...
use std::hash::Hash; use graph_lib::safe_tree::Tree; use policy::policy::Policy; use policy::score::Score; use sim_result::SimResult; use rules::{Action, Rules}; pub(crate) type MctsNode<A> = Tree<A, SimResult>; pub trait Mcts<A: Action, S: Rules<A>> { fn root(&self) -> MctsNode<A>; fn selection<Sc: Score>(&...
use std::sync::Arc; use std::sync::Mutex; lazy_static! { static ref APP_STATE: Mutex<Arc<AppState>> = Mutex::new(Arc::new(AppState::new())); } pub fn update_dynamic_data(time: f32, canvas_width: f32, canvas_height: f32) { let mut data = APP_STATE.lock().unwrap(); *data = Arc::new(AppState { canvas_width, ...
// RGB standard library // Written in 2020 by // Dr. Maxim Orlovsky <orlovsky@pandoracore.com> // // To the extent possible under law, the author(s) have dedicated all // copyright and related and neighboring rights to this software to // the public domain worldwide. This software is distributed without // any warr...
#[doc = "Reader of register COMP2_CSR"] pub type R = crate::R<u32, super::COMP2_CSR>; #[doc = "Writer for register COMP2_CSR"] pub type W = crate::W<u32, super::COMP2_CSR>; #[doc = "Register COMP2_CSR `reset()`'s with value 0"] impl crate::ResetValue for super::COMP2_CSR { type Type = u32; #[inline(always)] ...
// This file is part of syslog2. 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/syslog2/master/COPYRIGHT. No part of syslog2, including this file, may be copied, modified, propagated, or distributed except...
use graphics::math::Vec2d; pub struct AABB { pub center: Vec2d, pub half_size: Vec2d } impl AABB { pub fn new(center: Vec2d, half_size: Vec2d) -> AABB { AABB { center: center, half_size: half_size } } pub fn overlaps(&self, other: AABB) -> bool { if (...
use crate::rpc; use crate::transaction_info::{Access, AccessMode, Target, TransactionInfo}; use std::collections::{BinaryHeap, HashMap, HashSet}; use web3::types::U256; fn is_wr_conflict(first: &TransactionInfo, second: &TransactionInfo) -> bool { for acc in second .accesses .iter() .filter...
#[derive(Debug)] #[derive(Clone)] enum Operator { Plus } #[derive(Debug)] #[derive(Clone)] enum Token { LeftParen, RightParen, Int(i32), Operator(Operator), Unknown, } fn tokenize_operator(st: &str) -> Token { return match st { "+" => Token::Operator(Operator::Plus), _ => T...
use openssl::rsa::{Padding, Rsa}; use openssl::symm::{Cipher, Crypter, Mode}; //base64 use base64; //hex use rustc_serialize::hex::ToHex; //json use serde_json::{json, Value}; //random use rand::Rng; use lazy_static::*; lazy_static! { static ref IV: Vec<u8> = "0102030405060708".to_string().into_bytes(); st...
use axum::{ http::StatusCode, response::{IntoResponse, Response}, }; pub struct AppError(anyhow::Error); impl IntoResponse for AppError { fn into_response(self) -> Response { let AppError(err) = self; ( StatusCode::INTERNAL_SERVER_ERROR, err.backtrace().to_string(), ) .into_response() } } impl<E>...
use tge::error::GameResult; use tge::math::{Vector, Position, Point, Scale, Size, Angle}; use tge::engine::{Engine, EngineBuilder}; use tge::window::WindowConfig; use tge::graphics::*; use tge::mouse::MouseButton; use tge::game::Game; use rand::Rng; use rand::rngs::ThreadRng; const TITLE: &str = "Sprites"; const STEP_...
use std::convert::TryFrom; use std::path::Path; use std::str; use anyhow::{Context, Result}; use needletail::{parse_sequence_path, SequenceRecord}; use crate::{Alignment, Sequence}; /// Reads an Alignment contained in a fasta file into the Alignment struct. /// The name of the Alignment is the `file_stem` (the non-e...
use crate::bot::utils::Utils; use crate::extensions::ClientContextExt; use serenity::model::prelude::Guild; use serenity::prelude::Context; pub struct GuildCreateEvent; impl GuildCreateEvent { pub async fn run(ctx: &Context, guild: &Guild, is_new: &bool) { if !is_new { return; } ...
//! Sup Commands use crate::result::Result; use std::path::PathBuf; use structopt::{clap::AppSettings, StructOpt}; pub mod new; pub mod source; pub mod tag; pub mod update; pub mod upgrade; #[derive(StructOpt, Debug)] #[structopt(setting = AppSettings::InferSubcommands)] enum Opt { /// Create a new substrate node...
use sqlx::postgres::PgPool; use crate::utils::config::{is_containerized_development_mode, is_production_mode, CONFIG}; // Mode control lazy_static! { static ref DATABASE_URL: String = { match is_production_mode() { true => format!( "postgres://{}:{}@{}:{}/{}", C...
use std::error::Error; use std::fs; use std::path::Path; use heed::types::*; use heed::{Database, EnvOpenOptions}; fn main() -> Result<(), Box<dyn Error>> { let env1_path = Path::new("target").join("env1.mdb"); let env2_path = Path::new("target").join("env2.mdb"); fs::create_dir_all(&env1_path)?; let...
use rand; use rand::Rng; /// Generates random numbers with help of random-number /// generator `rand::Rng` obtained via `rand::thread_rng` /// https://docs.rs/rand/ pub fn run_basic() { // Each thread has an automatically-initialised random number generator: let mut rng = rand::thread_rng(); // Integers ...
#[doc = "Reader of register _9BITADDR"] pub type R = crate::R<u32, super::_9BITADDR>; #[doc = "Writer for register _9BITADDR"] pub type W = crate::W<u32, super::_9BITADDR>; #[doc = "Register _9BITADDR `reset()`'s with value 0"] impl crate::ResetValue for super::_9BITADDR { type Type = u32; #[inline(always)] ...
//! Custom test runner for building/running unit tests on the 3DS. extern crate test; use std::io; use test::{ColorConfig, OutputFormat, TestDescAndFn, TestFn, TestOpts}; use crate::prelude::*; /// A custom runner to be used with `#[test_runner]`. This simple implementation /// runs all tests in series, "failing" ...
// pub enum Dir { // N, // S, // E, // W // } use commons::add_u32; #[derive(Debug, Clone, Copy, PartialEq, Hash)] pub struct GridCoord { pub x: u32, pub y: u32, } impl GridCoord { pub fn new(x: u32, y: u32) -> Self { GridCoord { x, y } } pub fn translate(&self, dx: i32, ...
use crate::{ geom::Rectangle, graphics::Image }; use std::rc::Rc; #[derive(Debug)] struct AnimationData { frames: Vec<Image> } #[derive(Clone, Debug)] /// A linear series of images with a constant frame delay /// /// Frames advance by discrete ticks, which should be run in the `update` section of a /// q...
// Sedgewick, p.249 // Cormen, p.29 /// Selection sort. /// /// Time complexity: /// /// * best: Ω(n^2) /// * avg: Θ(n^2) /// * worst: O(n^2) /// /// Space complexity: /// /// * O(1) pub fn sort<T: Ord>(input: &mut Vec<T>) { let size = input.len(); for i in 0..size { let mu...
mod with_atom_process_identifier; mod with_local_pid_process_identifier; mod with_tuple_process_identifier; use super::*; #[test] fn without_process_identifier_errors_badarg() { with_process_arc(|arc_process| { TestRunner::new(Config::with_source_file(file!())) .run( &is_not_pr...
use std::ops; use std::f32; use super::deg2rad; #[derive(Debug, Clone, PartialEq)] pub struct Vec2 { pub x: f32, pub y: f32 } // indices impl ops::Index<usize> for Vec2 { type Output = f32; fn index<'a>(&'a self, index: usize) -> &f32 { match index { 0 => &self.x, 1 =>...
use proconio::input; #[allow(unused_imports)] use proconio::marker::*; #[allow(unused_imports)] use std::cmp::{max, min}; #[allow(unused_imports)] use std::collections::*; #[allow(unused_imports)] use std::f64::consts::*; #[allow(unused)] const INF: usize = std::usize::MAX / 4; #[allow(unused)] const M: usize = 100000...
// Copyright 2016 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 ...
#[macro_export] macro_rules! name_type { ($ident:ident) => { #[derive( Debug, PartialEq, Eq, Clone, Copy, Default, Hash, PartialOrd, Ord, crate::bytes::Read, crate::bytes::Writ...
#[doc = r"Value read from the register"] pub struct R { bits: u32, } #[doc = r"Value to write to the register"] pub struct W { bits: u32, } impl super::MMCTXIM { #[doc = r"Modifies the contents of the register"] #[inline(always)] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, ...
//! use chart_builder::charts::*; /// Structure used for storing chart related data and the drawing of a Box and Whisker Plot. /// /// This chart is used for statistical analysis of data. /// Shows variations within a set of data. #[derive(Clone)] pub struct BoxWhiskerPlot { data_labels: Vec<String>, data: Ve...
use std::error::Error; use std::fs; type MyResult<T> = Result<T, Box<Error>>; fn main() -> MyResult<()> { let input = fs::read_to_string("test.txt")?; let polymer : Vec<char> = input.chars().collect(); part1(polymer)?; Ok(()) } fn part1(input : Vec<char>) -> MyResult<()> { // let test : Vec<&[char]> = input.c...
use core::fmt::{self, Display}; use core::ops::{Add, Div, Mul, Rem, Sub}; use core::time::Duration; use num_bigint::BigInt; // Must be at least a `u64` because `u32` is only ~49 days (`(1 << 32)`) /// A duration in milliseconds between `Monotonic` times. #[derive(Clone, Copy, Eq, Debug, PartialEq, PartialOrd)] pub st...
// Original PistonDevelopers/camera_controllers license: // // The MIT License (MIT) // // Copyright (c) 2015 PistonDevelopers // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without re...
use crate::game::{self, Action, Game}; use crate::{rng, Direction, PLAYER}; #[derive(Debug)] pub enum Ai { Basic, Idle, Confused { previous: Box<Ai>, num_turns: i32 }, } impl Ai { /// Calculate an Ai turn pub fn turn(self, id: usize, game: &Game) -> (game::Turn, Self) { match self { ...
use tonic::{transport::Server, Request, Response, Status}; use tokio::sync::mpsc; use std::collections::HashMap; use std::sync::{Arc, RwLock}; pub mod pubsub { tonic::include_proto!("pubsub"); } use pubsub::message_service_server::{MessageService, MessageServiceServer}; use pubsub::{Message, SubscribeRequest}; ...
//! Initialization code #![feature(panic_implementation)] #![no_std] #[macro_use] extern crate cortex_m; #[macro_use] extern crate cortex_m_rt; extern crate f3; use core::panic::PanicInfo; pub use cortex_m::asm::bkpt; use cortex_m::asm; pub use cortex_m::peripheral::ITM; use cortex_m_rt::ExceptionFrame; pub use f3:...
use serde::Deserialize; use serde_yaml; use std::collections::HashMap; #[derive(Debug, Deserialize)] pub struct AppConfig { pub commands: HashMap<String, AppCommand>, pub hosts: HashMap<String, AppHost>, } #[derive(Debug, Deserialize)] pub struct AppCommand { pub command: String, } #[derive(Debug, Deseri...
use crate::{ caveat::{CaveatBuilder, CaveatType}, error::MacaroonError, serialization::macaroon_builder::MacaroonBuilder, Macaroon, }; use rustc_serialize::base64::{FromBase64, ToBase64, STANDARD}; use serde::{Deserialize, Serialize}; use std::str; #[derive(Debug, Default, Deserialize, Serialize)] stru...
#[doc = r"Value read from the register"] pub struct R { bits: u32, } #[doc = r"Value to write to the register"] pub struct W { bits: u32, } impl super::DCCMP0 { #[doc = r"Modifies the contents of the register"] #[inline(always)] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &...
// Enables `quote!` to work on bigger chunks of code. #![recursion_limit = "256"] #![deny(bare_trait_objects, unused_lifetimes)] #![warn(clippy::all)] use utils::generated_file; pub mod ast; mod constraint; mod flat_filter; pub mod ir; pub mod lexer; generated_file!(pub parser); pub mod error; mod print; mod truth_tab...
use models; use schema; use diesel::prelude::*; use diesel::MysqlConnection; use super::file_entry_types; /// Queries a single organization with the given slug. pub fn find_by_user( user_id: i32, titan_primary: &MysqlConnection ) -> Result<Vec<models::UserFileEntryWithType>, diesel::result::Error> { let fi...
fn main() { let array1 = [1, 2, 3]; let array2 = [1, 2, 3]; let array3 = [2, 3, 4]; if array1.eq(&array2) { println!("array1 dan array2 sama!"); } if array1.ne(&array3) { println!("array1 dan array3 tidak sama!"); } }
use std::mem; // handle of binary-search-tree #[derive(Debug)] pub struct BST { pub root: Link, size: usize, } // branch to node #[derive(Debug, PartialEq)] pub enum Link { Empty, More(Box<Node>), } // populated node #[derive(Debug, PartialEq)] pub struct Node { elem: i32, left: Link, rig...
use image::{DynamicImage, Rgba}; use imageproc::definitions::HasBlack; use imageproc::drawing::{draw_text_mut, Canvas}; use rusttype::{Font, Point, Scale}; use std::fs; fn open_font(font: &str) -> std::vec::Vec<u8> { let font_vec1 = fs::read(font).expect("Unable to read file"); return font_vec1; } #[derive(De...
use anyhow::{Context as _, Error}; use std::path::PathBuf; use std::sync::Arc; use swc::common::FileName; use swc::config::{Options, SourceMapsConfig}; use swc::{Compiler, TransformOutput}; use swc_ecmascript::ast::Program; use swc_wallaby::transform::{ exec_transform, my_transform, TransformOptions, TransformOutpu...
#[repr(C)] #[derive(Debug, Copy, Clone, Default)] pub struct VkViewport { pub x: f32, pub y: f32, pub width: f32, pub height: f32, pub minDepth: f32, pub maxDepth: f32, }
//! Runtime helpers for keeping track of Kubernetes resources mod informer; mod reflector; pub use informer::Informer; pub use reflector::Reflector;
#[derive(Debug)] struct User { name: String, addr: String } impl User { fn get_name(&self) ->&str { &(self.name[..]) } fn get_addr(&self) ->&str { &(self.addr[..]) } } fn main() { let user = User{ name: String::from("wuhaurou"), addr: String::from("中国") }; println!("u...
use std::{cell::RefCell, rc::Rc}; use futures::StreamExt as _; use medea_reactive::ObservableVec; use tokio::task::spawn_local; use crate::{component, sys::RtcPeerConnection}; pub struct Room { pub peers: RefCell<ObservableVec<Rc<component::Peer>>>, } impl Room { pub fn new() -> Self { Self { ...
use crate::renderer::Renderer; use fs_extra::dir; use log::info; use model::Site; use std::{ fs, path::{Path, PathBuf}, process::Command, }; use structopt::StructOpt; mod markdown; mod model; mod renderer; #[derive(Debug, StructOpt)] #[structopt( name = "static-wiki", about = "Generate static html ...
// Translation of vector operations to LLVM IR, in destination-passing style. import back::abi; import lib::llvm::llvm; import llvm::ValueRef; import middle::trans; import middle::trans_common; import middle::trans_dps; import middle::ty; import syntax::ast; import syntax::codemap::span; import trans::alloca; import t...
use std::mem; use liblumen_alloc::erts::exception::InternalResult; use liblumen_alloc::erts::term::prelude::*; use liblumen_alloc::erts::Process; use crate::distribution::external_term_format::try_split_at; use crate::distribution::nodes::node; use super::{arc_node, u16, u32, u64}; pub fn decode<'a>( process: &...
wit_bindgen::generate!("cart"); struct Component; export_cart!(Component); impl Cart for Component { fn create(id: CartId) -> CartData { CartData::EmptyCart(EmptyCart { id: id.clone() }) } fn add_item(state: CartData, item: ItemId, qty: Quantity) -> Option<CartData> { if qty == 0 { ...
#![feature(plugin, custom_derive)] #![plugin(rocket_codegen)] extern crate bcrypt; extern crate rusqlite; extern crate rocket_contrib; extern crate rocket; extern crate serde_json; #[macro_use] extern crate serde_derive; use rocket::http; use rocket::Response; use rocket::response::{Redirect, NamedFile, Failure}; us...
use std::collections::HashMap; use std::io; fn valid_day2a_password(password: &str, param: char, min_count: usize, max_count: usize) -> bool { let mut counts = HashMap::new(); for c in password.chars() { let counter = counts.entry(c).or_insert(0); *counter += 1; } let char_count = mat...
use std::borrow::Cow; use std::env; use crate::spec::{FramePointer, LldFlavor, SplitDebugInfo, TargetOptions}; pub fn opts(os: &'static str) -> TargetOptions { // ELF TLS is only available in macOS 10.7+. If you try to compile for 10.6 // either the linker will complain if it is used or the binary will end up...
use std::time::Duration; use hyper::{ client::{Client, HttpConnector}, Body, }; use hyper_rustls::{HttpsConnector, HttpsConnectorBuilder}; pub type HttpClient = Client<HttpsConnector<HttpConnector>, Body>; /// Create a HTTP 1 client instance. /// /// Parameter: Timeout for idle sockets being kept-alive pub f...
#[doc = "Reader of register SR2"] pub type R = crate::R<u32, super::SR2>; #[doc = "Writer for register SR2"] pub type W = crate::W<u32, super::SR2>; #[doc = "Register SR2 `reset()`'s with value 0"] impl crate::ResetValue for super::SR2 { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { ...
rs_prog login: [ input : [name(X), password(Y)], output: [loginSuccessful, loginUnsuccessful], module get_login: [ input : [name(X), password(Y), goodLogin, badLogin, tooManyAttempts], output : [loginSuccessful, loginUnsuccessful, checkLogin(X,Y)], t_signal:[], p_signal: [gotName(X), gotPa...
//! Static configuration (the bootstrap node(s)). /// The supported bootstrap nodes (/dnsaddr is not yet supported). This will be updated to contain /// the latest known supported IPFS bootstrap peers. // FIXME: it would be nice to parse these into MultiaddrWithPeerId with const fn. pub const BOOTSTRAP_NODES: &[&str] ...
use lock_api::{MutexGuard, RawMutex}; use std::{fmt, marker::PhantomData, ops::Deref}; /// A mutex guard that has an exclusive lock, but only an immutable reference; useful if you /// need to map a mutex guard with a function that returns an `&T`. Construct using the /// [`MapImmutable`] trait. pub struct ImmutableMap...
#![allow(non_camel_case_types)] pub type u1 = u8; pub type u2 = u16; pub type u4 = u32;
//! # parse_chg //! //! Парсинг файла формата *.chg (Мономах) //! //! Парсим файл, затем собираем его обратно. Модули _raw для анализа фрагментов исходного файла //! //! <hr/> #![recursion_limit = "128"] extern crate nom; #[macro_use] extern crate arrayref; extern crate byteorder; extern crate core; extern crate walk...
use ::yaml_rust::Yaml; use ::std::collections::BTreeMap; use ::std::collections::btree_map::Entry; use ::parse::*; use ::errors::*; pub fn pathjoin<'a>(paths: &[&YamlPath]) -> YamlPath { let mut ret = vec![]; for elem in paths.iter().flat_map(|x| x.iter()) { match elem { YamlPathElem::Up => { ret.pop(); }, // I...
use std::collections::{VecDeque}; use std::rc::{Rc}; use std::cell::{RefCell}; use template::{EventHook}; /// Data for interacting with an active UI component tree inserted through a template. #[derive(Clone)] pub struct EventSink { events: Rc<RefCell<VecDeque<String>>>, } impl EventSink { pub(crate) fn new(...
use graphics::math::*; use std::collections::HashMap; use std::rc::Rc; use std::cell::RefCell; use std::cell::RefMut; use opengl_graphics::Texture; use super::texture_loader::TextureLoader; use super::animator::Animator; pub struct AnimationManager { animators: HashMap<String, RefCell<Animator>>, tex_loader: R...
use std::marker::PhantomData; use std::ops::{Index, IndexMut}; use boots::cfg::ControlFlowGraph; use boots::dfg::DataFlowGraph; struct Function { next_block: usize, dfg: DataFlowGraph, cfg: ControlFlowGraph, } impl Function { fn new() -> Function { Function { next_block: 0, ...
use proconio::input; fn len(mut x: u64) -> usize { let mut l = 0; while x > 0 { x /= 10; l += 1; } l } fn main() { input! { n: usize, a: [u64; n], }; let mut b = a.clone(); b.sort_by_key(|&x| len(x)); b.reverse(); let v = if len(b[0]) == len(b[1...
// Copyright (c) 2016 Chef Software Inc. and/or applicable contributors // // 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 bytes::BytesMut; const BUFFER_CHUNK_SIZE: usize = 25 * 1024 * 1024; // 25mb #[derive(Clone)] pub struct WriteBuffer { pub offset: u64, pub data: BytesMut, } impl WriteBuffer { pub fn new(offset: u64, data: &[u8]) -> Self { Self { offset, data: data.into(), } ...
import syntax::ast::*; import syntax::visit; import std::ivec; import std::option::*; import aux::*; import tstate::ann::pre_and_post; import tstate::ann::precond; import tstate::ann::postcond; import tstate::ann::prestate; import tstate::ann::poststate; import tstate::ann::relax_prestate; import tstate::ann::relax_pre...
use async_std::{io::{Read,Write},fs}; use std::path::PathBuf; pub trait RW: Read+Write+Send+Sync+Unpin {} impl RW for fs::File {} type Error = Box<dyn std::error::Error+Send+Sync>; #[async_trait::async_trait] pub trait Storage<S>: Send+Sync+Unpin where S: RW { async fn open(&mut self, name: &str) -> Result<S,Error...
extern crate gfx_hal as hal; extern crate rendy; extern crate winit; use hal::{Adapter, Backend, Instance}; use rendy::{ command::{CapabilityFlags, Families, Family, FamilyId}, Config, Device, Factory, QueuesPicker, RenderBuilder, }; use winit::{EventsLoop, WindowBuilder}; use std::marker::PhantomData; fn ma...