text
stringlengths
8
4.13M
use anyhow::*; use std::alloc::Layout; pub(crate) fn bucket_allocate_cont<T>(buckets: usize) -> Result<Vec<T>> { // debug_assert!((buckets != 0) && ((buckets & (buckets - 1)) == 0), "Capacity should be power of 2"); // Array of buckets let data = Layout::array::<T>(buckets)?; unsafe { let p =...
use std::borrow::Cow; use std::cmp; use std::fs; use std::fs::OpenOptions; use std::io::prelude::*; use std::io::{self, Error, ErrorKind, SeekFrom}; use std::marker; use std::path::{Component, Path, PathBuf}; use filetime::{self, FileTime}; use crate::archive::ArchiveInner; use crate::error::TarError; use crate::head...
// Authors: Matthew Bartlett & Arron Harman // Major: (Software Development & Math) & (Software Development) // Creation Date: October 27, 2020 // Due Date: November 24, 2020 // Course: CSC328 // Professor Name: Dr. Frye // Assignment: Chat Server // File...
use crate::error::{GameError, GameResult}; use crate::math::Delta; use crate::event::{Event, KeyAction}; use crate::filesystem::{Filesystem, FilesystemConfig}; use crate::window::{Window, WindowConfig, LogicalPosition, LogicalSize}; use crate::graphics::{Graphics, GraphicsConfig}; use crate::timer::{Timer, TimerConfig}...
use add_one; use rand; fn main() { let num = 10; println!("Hello, world! {} plus one is {}", num, add_one::add_one(num)); let thre = rand::thread_rng(); println!("Next random : {}", add_one::ret_rand(thre)); }
use serde::Serializer; use serde::ser::Serialize; /// тестовая форма #[derive(FromForm)] pub struct MyForm { pub field: String, } impl MyForm { pub fn new() -> MyForm { MyForm { field: String::new() } } } impl Serialize for MyForm { /// хитрим и рендерим форму для шаблона fn serialize<S>(...
use std::collections::HashMap; use std::fs; use std::time::Instant; use pcre2::bytes::Regex; fn process_input(puzzle: Vec<&str>) -> (HashMap<&str, Vec<Vec<&str>>>, Vec<&str>) { let mut rules_map: HashMap<&str, Vec<Vec<&str>>> = HashMap::new(); assert!(!puzzle.is_empty()); let mut it = puzzle.iter(); lo...
#[derive(Debug)] pub struct User{ pub name: String, pub email: String, pub age: u16, pub user_type: UserType } impl User{ pub fn print_user(self){ println!("The name of the user is {}.\nHis email is: {}.\nHe is {} old.\nType of user: {:?}", self.name, self.email, self.age, self.user_type); } } #[derive(Debug)...
//! A slab-like, pre-allocated storage where the slab is divided into immovable //! slots. Each allocated slot doubles the capacity of the slab. //! //! Converted from <https://github.com/carllerche/slab>, this slab however //! contains a growable collection of fixed-size regions called slots. //! This allows is to sto...
// 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 ...
/// ```rust,ignore /// 89. 格雷编码 /// 格雷编码是一个二进制数字系统,在该系统中,两个连续的数值仅有一个位数的差异。 /// /// 给定一个代表编码总位数的非负整数 n,打印其格雷编码序列。格雷编码序列必须以 0 开头。 /// /// 示例 1: /// /// 输入: 2 /// 输出: [0,1,3,2] /// 解释: /// 00 - 0 /// 01 - 1 /// 11 - 3 /// 10 - 2 /// /// 对于给定的 n,其格雷编码序列并不唯一。 /// 例如,[0,2,3,1] 也是一个有效的格雷编码序列。 /// /// 00 - 0 /// 10 - 2 /// 11 ...
use input_i_scanner::InputIScanner; use std::collections::HashSet; fn main() { let stdin = std::io::stdin(); let mut _i_i = InputIScanner::from(stdin.lock()); macro_rules! scan { (($($t: ty),+)) => { ($(scan!($t)),+) }; ($t: ty) => { _i_i.scan::<$t>() as $t ...
use super::{LayerVariablesBuilder}; use super::super::{algebra, Layer, LayerInstance}; use ndarray::Dimension; // Performs batch normalization during inference. This layer only supports inference and does NOT // implement proper batch normalization during training since this library has no concept of // batches right...
use super::*; mod with_small_integer_time; // BigInt is not tested because it would take too long and would always count as `long_term` for the // super shot soon and later wheel sizes used for `cfg(test)` #[test] fn without_non_negative_integer_time_errors_badarg() { run!( |arc_process| { ( ...
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)] #[link(name = "windows")] extern "system" { pub fn CloseIMsgSession(lpmsgsess: *mut _MSGSESS); #[cfg(feature = "Win32_System_AddressBook")] pub fn GetAttribIMsgOnIStg(lpobject: *mut ::core::ffi...
use proconio::input; fn main() { input! { n: usize, a: [usize; n], m: usize, b: [usize; m], x: usize, }; let mut ban = vec![false; x + 1]; for b in b { ban[b] = true; } let mut dp = vec![false; x + 1]; dp[0] = true; for i in 0..x { ...
use crate::{onTagClose, onTagOpen, ParsingError}; #[derive(Clone, Copy)] #[repr(C)] pub enum CustomEventType { /// Variant that can be used to log various information on the RxPlayer's /// logger. /// /// Useful for debugging, for example. #[allow(dead_code)] Log = 0, /// Variant used to r...
use crate::datastructure::bvh::boundingbox::BoundingBox; use crate::scene::triangle::Triangle; use crate::util::vector::Vector; use core::fmt; use log::debug; use std::fmt::{Display, Formatter}; pub enum BVHNode<'d> { Leaf { bounding_box: BoundingBox, triangles: Vec<&'d Triangle<'d>>, }, No...
mod column_type; use std::fs::File; use std::path::{Path, PathBuf}; use std::rc::Rc; use std::cell::{Cell, RefCell}; use std::str::FromStr; use gtk::prelude::*; use gtk::{self, Builder, Window, Statusbar, Adjustment, TreeView, TreeViewColumn, TreeIter, ListStore, CellRendererText, MenuItem, FileChooserDialog, FileCho...
#![no_std] #![no_main] // pick a panicking behavior use panic_probe as _; #[allow(unused)] use stm32f4xx_hal::stm32::interrupt; use cortex_m::asm; use cortex_m_rt::entry; use rtt_target::{rtt_init_print, rprintln}; #[entry] fn main() -> ! { rtt_init_print!(); rprintln!("Hello, world!"); loop { asm::bkpt(...
// error-pattern:quux use std; import std::str::*; import std::uint::*; fn nop(a: uint, b: uint) : le(a, b) { fail "quux"; } fn main() { let a: uint = 5u; let b: uint = 4u; claim (le(a, b)); nop(a, b); }
//! CSC use static_assertions::const_assert_eq; register! { Control, u32, RW, Fields [ Bits WIDTH(U32) OFFSET(U0), ] } register! { Coef, u32, RW, Fields [ Bits WIDTH(U32) OFFSET(U0), ] } const_assert_eq!(core::mem::size_of::<RegisterBlock>(), 0x40); #[repr(...
use tracing::Subscriber; use tracing_bunyan_formatter::{BunyanFormattingLayer, JsonStorageLayer}; use tracing_subscriber::{layer::SubscriberExt, EnvFilter, Registry}; pub fn get_subscriber(app_name: String, env_filter: String) -> impl Subscriber + Send + Sync { let env_filter = EnvFilter::try_from_default_...
use std::io; enum Cell { E, X, O, } impl Copy for Cell {} impl Clone for Cell { fn clone(&self) -> Cell { *self } } struct Field { field : Vec<Vec<Cell>>, } impl Field { //"Constructor" fn new (size: usize) -> Field { Field { field: vec![vec!(Cell::E;size); size] } } ...
#![allow(non_upper_case_globals)] #![allow(non_camel_case_types)] #![allow(non_snake_case)] #[cfg(all(target_os = "linux", target_pointer_width = "64"))] pub type size_t = ::std::os::raw::c_ulong; #[cfg(all(target_os = "windows", target_pointer_width = "64"))] pub type size_t = ::std::os::raw::c_ulonglong; #[cfg(tar...
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)] #[link(name = "windows")] extern "system" {} pub type FileInformation = *mut ::core::ffi::c_void; pub type FileInformationFactory = *mut ::core::ffi::c_void; pub type FolderInformation = *mut ::core::ffi::...
//! An idiomatic Rust PulseAudio interface. // Documentation: https://freedesktop.org/software/pulseaudio/doxygen/ // Ref: https://gist.github.com/toroidal-code/8798775 #[macro_use] mod error; pub use self::error::{Error, Result}; mod enums; pub use self::enums::ContextState; mod main_loop; pub use self::main_loop::...
use std::fmt; use titlecase::titlecase; use super::formatter::format_change; use super::{db, Command, CommandArgs, Error, Result}; pub(super) struct Bulls; struct Mover { pub name: String, pub ticker: String, pub diff: f32 } pub struct Movers { movers: Vec<Mover> } impl Bulls { fn query(&sel...
use std::{ collections::{HashMap, VecDeque}, rc::Rc, vec::Vec, }; use crate::{ actors::actor_type::ActorType, events::{ event::{Event, EventClone}, event_type::EventType, }, manifest::Manifest, PacketReader, }; /// Handles incoming/outgoing events, tracks the delivery s...
use std::cmp::Ordering; pub type NodeBox<T> = Option<Box<Node<T>>>; /// A binary tree with data at every node. Each branch may or may not contain /// another node. #[derive(Clone, Debug, Default, PartialEq)] pub struct Node<T> { pub value: T, pub left: NodeBox<T>, pub right: NodeBox<T>, } impl<T: Default...
use std::collections::HashMap; #[derive(Debug)] pub struct MonDef { id: String, species: String, types: Vec<String>, abilities: Vec<String>, evos: Vec<String>, learnset: Vec<(i64, String)>, base_exp: i64, pub hp: i64, pub atk: i64, pub spatk: i64, pub def: i64, pub spde...
#[macro_use] pub mod console; mod application; mod aspect; mod attribute; pub mod html; mod lazy; mod listener; mod mailbox; mod property; pub mod router; pub mod subscription; pub mod svg; pub mod url; mod velement; mod vnode; mod vtext; pub use self::application::{start, Application}; pub use self::aspect::Aspect; p...
use std::io; use std::os::unix::io::{RawFd, AsRawFd, FromRawFd}; use failure::Error; use nix::unistd; use nix::fcntl::{fcntl, FcntlArg, OFlag}; use nix::sys::termios::{tcgetattr, tcsetattr, cfmakeraw}; use nix::sys::termios::{Termios, SetArg}; use libc; use futures::prelude::*; use tokio::prelude::*; use tokio::reac...
pub fn mutability() { println!("\n--- mutability() ---"); let immutable = 1; println!("immutable={}", immutable); //immutable = 2; //not allowed because immutable by default let immutable = 2; //allowed because a is shadowed println!("immutable={}", immutable); let mut mutable = 1; pr...
use super::atom::atom_val; use super::error::PineResult; use super::input::{Input, StrRange}; use super::utils::skip_ws; use nom::{branch::alt, bytes::complete::tag, combinator::map}; #[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)] pub enum BinaryOp { Plus, Minus, Mul, Div, Mod, Lt, ...
//! Modules for the runtime representation and interpretation of Piccolo bytecode. pub mod chunk; pub mod memory; pub mod object; pub mod op; pub mod value; pub mod vm; pub type ConstantIdx = u16; pub type LocalSlotIdx = u16; pub type LocalScopeDepth = u16; pub type Line = usize; pub type ChunkOffset = usize; pub typ...
//! Write systems to disk. use error::Result; use grafen::system::{Component, System}; use std::fs::File; use std::io::{BufWriter, Write}; /// Output a system to disk as a GROMOS formatted file. /// The filename extension is adjusted to .gro. /// /// # Errors /// Returns an error if the file could not be written to...
use crate::{DocBase, VarType}; pub fn gen_doc() -> Vec<DocBase> { let fn_doc = DocBase { var_type: VarType::Function, name: "highest", signatures: vec![], description: "Highest value for a given number of bars back.", example: "", returns: "Highest value.", a...
//! External interrupt and event controller use crate::rcc; use stm32l0x3::{exti, EXTI, SYSCFG_COMP}; /// Extension trait that constrains the `EXTI` peripheral pub trait ExtiExt { /// Constrains the `EXTI` peripheral so it plays nicely with the other abstractions fn constrain(self) -> Exti; } impl ExtiExt fo...
#![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)]...
pub struct Runtime { pub module: String, pub module_instance: String, pub store: String, } impl Runtime { fn new() -> Self { Runtime { module: "m1".to_string(), module_instance: "m2".to_string(), store: "m3".to_string(), } } fn exec() { ...
#[macro_use] extern crate defmac; fn solve(p: usize, m: usize) { let mut circle = linked_list::LinkedList::new(); circle.push_front(0); let mut score = vec![0; p]; let mut cur = circle.cursor(); cur.next(); defmac!(forward => if cur.next().is_none() { cur.next(); } ); defmac!(backward => ...
use proconio::input; fn main() { input! { n: usize, a: [u32; n], }; let ans = a.into_iter().filter(|&x| x % 2 == 0).collect::<Vec<_>>(); for i in 0..ans.len() { print!("{}", ans[i]); if i + 1 < ans.len() { print!(" "); } else { print!("\n...
pub type Label = String; #[derive(Debug, PartialEq, Clone)] pub enum Source { Expansion, Accumulator, Memory, Operand(u8), LabelLo(Label), LabelHi(Label), } #[derive(Debug, PartialEq, Clone)] pub enum Destination { Memory, MemAddressLo, MemAddressHi, Accumulator, Accumulato...
use crate::prelude::*; #[repr(C)] #[derive(Debug, Default)] pub struct VkPhysicalDeviceLimits { pub maxImageDimension1D: u32, pub maxImageDimension2D: u32, pub maxImageDimension3D: u32, pub maxImageDimensionCube: u32, pub maxImageArrayLayers: u32, pub maxTexelBufferElements: u32, pub maxUni...
use std::{ cell::RefCell, collections::HashMap, fmt::{Debug, Display}, rc::Rc, }; use super::{ environment::Environment, instance::Instance, interpreter::Interpreter, stmt::Stmt, value::Value, }; pub trait Callable { fn arity(&self) -> usize; fn call(&self, interpreter: &mut Interprete...
use std::sync::mpsc::sync_channel; const N: u32 = 10; #[tokio::test] async fn explore_sync_channel() { let (tx, rx) = sync_channel(0); let th1 = tokio::spawn(async move { let start = std::time::Instant::now(); for id in 0..N { println!("sent value = {:?} at {:?}", id, start.elapse...
extern crate serde; use serde::Serialize; use serde::Deserialize; #[derive(Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct AuthRequestData { #[serde(skip_serializing_if = "Option::is_none")] pub personal_number: Option<String>, pub end_user_ip: String, #[serde(skip_s...
use proconio::{input, marker::Usize1}; fn main() { input! { n: usize, a: [Usize1; n], }; let mut called = vec![false; n]; for i in 0..n { if called[i] == false { called[a[i]] = true; } } let mut ans = Vec::new(); for i in 0..n { if calle...
use memblock::*; fn main() { let mut source = MemBlock::new((5, 5)); let mut copy = MemBlock::new((2, 2)); let dma_target = (0, 1); println!("Source:"); source.table(); for y in 0..copy.size().1 { for x in 0..copy.size().0 { copy.write((x, y), 0xFFFFFFFF); } } ...
use crate::display::Display; use crate::keyboard::Keyboard; use crate::ram::Ram; /// /// CHIP-8 memory map /// /// +---------------+= 0xFFF (4095) End of Chip-8 RAM /// | | /// | | /// | | /// | | /// | | /// | 0x200 to 0xFFF| /// | Chip-8 | ...
//! The following SMB2 Access Mask flag values can be used when accessing a file, pipe or printer. use rand::{ distributions::{Distribution, Standard}, Rng, }; /// File_Pipe_Printer_Access_Mask (4 bytes): For a file, pipe, or printer, /// the value MUST be constructed using the following values (for a printer...
//! Provides the process function, as well as housing the internals for computing convex hulls. use io::input::Input; use io::output::Output; use shape::orientation::Orientation; use shape::coord::Coord; use shape::segment::Segment; use std::collections::HashSet; use shape::hull::Hull; use std::hash::BuildHasher; ///...
use std::collections::HashMap; use std::fs::File; use std::io::{BufReader, BufRead}; fn parse_file(file: BufReader<&File>) -> HashMap<(i32, i32), (i32, Vec<i32>)> { let mut res = HashMap::new(); for line in file.lines() { let l = line.unwrap(); let tokens:Vec<&str> = l.split(" ").collect(); ...
pub struct Post {} impl Post { pub fn new() -> DraftPost { DraftPost { content: String::new(), } } } pub struct DraftPost { content: String, } impl DraftPost { pub fn add_text(&mut self, text: &str) { self.content.push_str(text); } pub fn request_review(se...
// 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 ...
#[doc = "Reader of register ROUTELOC0"] pub type R = crate::R<u32, super::ROUTELOC0>; #[doc = "Writer for register ROUTELOC0"] pub type W = crate::W<u32, super::ROUTELOC0>; #[doc = "Register ROUTELOC0 `reset()`'s with value 0"] impl crate::ResetValue for super::ROUTELOC0 { type Type = u32; #[inline(always)] ...
#[doc = "Reader of register SEED3"] pub type R = crate::R<u8, super::SEED3>; #[doc = "Reader of field `seed`"] pub type SEED_R = crate::R<u8, u8>; impl R { #[doc = "Bits 0:7"] #[inline(always)] pub fn seed(&self) -> SEED_R { SEED_R::new((self.bits & 0xff) as u8) } }
#[desc = "Rust hello-world package."] #[license = "MIT"] #[version = "0.1.0"] pub fn world() { println("Hello, world"); }
//! Framed dispatcher service and related utilities use std::collections::VecDeque; use std::marker::PhantomData; use std::mem; use actix_codec::{AsyncRead, AsyncWrite, Decoder, Encoder, Framed}; use actix_service::{IntoNewService, IntoService, NewService, Service}; use futures::future::{ok, FutureResult}; use futures...
use std::env; use std::fs; use std::process::Command; fn main() { // Tell Cargo that if the given file changes, to rerun this build script. println!("cargo:rerun-if-changed=../../shaders/"); let engine_dir = env::current_dir().unwrap(); // . let project_dir = engine_dir.parent().unwrap().parent().unwr...
//! [`recvmsg`], [`sendmsg`], and related functions. #![allow(unsafe_code)] use crate::backend::{self, c}; use crate::fd::{AsFd, BorrowedFd, OwnedFd}; use crate::io::{self, IoSlice, IoSliceMut}; use core::iter::FusedIterator; use core::marker::PhantomData; use core::mem::{size_of, size_of_val, take}; use core::{ptr,...
mod extractor{ }
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or // http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or // http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or distributed except according to those terms. use super::toplevel::{Dec...
use alloc::heap::{Alloc, Layout, AllocErr}; extern "C" { pub fn IOMalloc(size: usize) -> *mut u8; pub fn IOFree(ptr: *mut u8, size: usize); pub fn IOMallocAligned(size: usize, alignment: usize) -> *mut u8; pub fn IOFreeAligned(ptr: *mut u8, size: usize); } pub struct Allocator; unsafe impl<'a> Alloc ...
pub mod game; pub mod resources; pub mod scene_manager; pub mod camera; pub mod physics;
use fn_search_backend_db::diesel::{pg::PgConnection, prelude::*, result::QueryResult}; use fn_search_backend_db::models::FunctionWithRepo; pub fn get_all_func_sigs(conn: &PgConnection) -> QueryResult<Vec<(String, i64)>> { use fn_search_backend_db::schema::functions::dsl::*; Ok(functions .select((type_s...
use crate::models::{Level, Score}; use deadpool_postgres::Client; use tokio_pg_mapper::FromTokioPostgresRow; pub async fn get_levels(client: &Client) -> Vec<Level> { let statement = client.prepare("select * from levels").await.unwrap(); let levels = client .query(&statement, &[]) .await ...
#[cfg(feature = "stm32f4xx-hal")] use stm32f4xx_hal::stm32; #[cfg(feature = "stm32f7xx-hal")] use stm32f7xx_hal::pac as stm32; use stm32::ethernet_mac::{MACMIIAR, MACMIIDR}; use core::option::Option; use crate::smi::SMI; #[allow(dead_code)] mod consts { pub const PHY_REG_BCR: u8 = 0x00; pub const PHY_REG_BS...
extern crate time; extern crate term; use std::io::net::udp::UdpSocket; use std::io::net::ip::{Ipv4Addr, SocketAddr}; use std::collections::HashMap; use std::num::SignedInt; //use std::io::prelude::*; use message::Message; use resource::Resource; use question::Question; use data::Data; #[deriving(Clone)] pub struct ...
pub mod db; pub mod graphql; pub mod member; pub mod project; pub mod response; pub mod user;
#[derive(juniper::ScalarValue)] enum ScalarValue { Variant { first: i32, second: u64 }, } fn main() {}
// auto generated, do not modify. // created: Mon Feb 22 23:57:02 2016 // src-file: /QtCore/qvariantanimation.h // dst-file: /src/core/qvariantanimation.rs // // header block begin => #![feature(libc)] #![feature(core)] #![feature(collections)] extern crate libc; use self::libc::*; // <= header block end // main bl...
use sea_orm::entity::prelude::*; use serde::{Deserialize, Serialize}; #[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq, Serialize, Deserialize)] #[sea_orm(table_name = "tags")] pub struct Model { #[sea_orm(primary_key)] #[serde(skip_deserializing)] pub id: i32, #[sea_orm(unique)] pub slug: String, } #[de...
mod lib; use anyhow::{anyhow, Result}; use lib::{Eoip, TunnelConfig}; const VERSION: &'static str = env!("CARGO_PKG_VERSION"); const HELP_MESSAGE: &str = r#"eoip-rs USAGE: eoip-rs [OPTIONS] OPTIONS: -l, --local IP address of local tunnel endpoint -r, --remote IP address of remote tunnel endpo...
use std::f64::consts; use std::fmt; use std::mem; use std::slice; use approx; use num; use angle; use angle::{Angle, FromAngle, IntoAngle, Turns, Rad, Deg}; use channel::{PosNormalBoundedChannel, AngularChannel, ChannelFormatCast, ChannelCast, PosNormalChannelScalar, AngularChannelScalar, ColorChannel}; u...
extern crate rand; extern crate sfml; mod fireworks; mod snow; use sfml::graphics::*; use sfml::system::*; use sfml::window::*; pub static WINDOW_WIDTH: u32 = 800; pub static WINDOW_HEIGHT: u32 = 600; fn load_font() -> SfBox<Font> { let font = Font::from_file("res/LiberationMono-Regular.ttf"); if font.is_no...
use cgmath::{EuclideanSpace, InnerSpace, MetricSpace, Point3, Vector3}; use crate::{config, P3, V3}; use std::f64::EPSILON; use std::ops::Neg; #[derive(Copy, Clone, Debug)] pub struct Positioned<T> { pos: P3, value: T, } impl<T: Default> Default for Positioned<T> { fn default() -> Self { Self { ...
use std::fs::File; use std::io::{self, Read, Write}; pub fn update_values_in_files(word_to_replace: &str, new_word: &str, path: &String) -> Result<(), io::Error> { let mut src = File::open(&path)?; let mut data = String::new(); src.read_to_string(&mut data)?; drop(src); // Close the file early let new_dat...
// auto generated, do not modify. // created: Mon Feb 22 23:57:02 2016 // src-file: /QtCore/qobjectdefs.h // dst-file: /src/core/qobjectdefs.rs // // header block begin => #![feature(libc)] #![feature(core)] #![feature(collections)] extern crate libc; use self::libc::*; // <= header block end // main block begin =>...
//! https://github.com/lumen/otp/tree/lumen/lib/ssh/src use super::*; test_compiles_lumen_otp!(ssh); test_compiles_lumen_otp!(ssh_acceptor); test_compiles_lumen_otp!(ssh_acceptor_sup); test_compiles_lumen_otp!(ssh_agent); test_compiles_lumen_otp!(ssh_app imports "lib/stdlib/src/supervisor"); test_compiles_lumen_otp!(...
extern crate regex; use super::Graph; use std::collections::HashMap; use std::collections::hash_map::DefaultHasher; use std::hash::{Hash, Hasher}; use std::fs::File; use std::io::BufReader; use std::io::prelude::*; use std::io::Result; use self::regex::Regex; use std::str::FromStr; use std::fmt::Display; pub fn uncon...
use std::collections::HashSet; use std::env; use actix_web::{web, App, HttpRequest, HttpServer, Responder, HttpResponse}; use std::time::{SystemTime, UNIX_EPOCH}; #[actix_web::main] async fn main() -> std::io::Result<()> { let redis_url = env::var("FLY_REDIS_CACHE_URL").unwrap(); println!("Using {}", redis_url...
use { derive_new::new, rough::{ amethyst::{ controls::{HideCursor, WindowFocus}, core::{bundle::SystemBundle, ecs::prelude::*}, derive::SystemDesc, prelude::*, shrev::{EventChannel, ReaderId}, winit::{Event, Window, WindowEvent}, ...
#![no_main] #![no_std] #![feature(alloc_error_handler)] #[macro_use(singleton)] extern crate cortex_m; use bluepill::clocks::*; use bluepill::hal::delay::Delay; use bluepill::hal::dma::{CircReadDma, Half, RxDma}; use bluepill::hal::gpio::gpioc::PC13; use bluepill::hal::gpio::{Output, PushPull}; use bluepill::hal::{ ...
use std::{thread, time}; use test_deps::deps; static mut BOOL_IGN_OK: bool = false; #[deps(IGN_OK_000)] #[test] fn with_ignore_attribute_000() { thread::sleep(time::Duration::from_millis(250)); unsafe { assert!(!BOOL_IGN_OK); BOOL_IGN_OK = true; } } #[deps(IGN_OK_001: IGN_OK_000)] #[ignor...
// 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 ...
pub fn is_prime(n: usize) -> bool { if n == 0 { return false; } else if n == 1 { return false; } else if n == 2 { return true; } if n % 2 == 0 { return false; } for i in 3..n { if n < i * i { break; } if n % i == 0 { ...
use std::fmt::{self, Display, Formatter}; use crate::mssql::protocol::type_info::{DataType, TypeInfo as ProtocolTypeInfo}; use crate::type_info::TypeInfo; #[derive(Debug, Clone, PartialEq, Eq)] #[cfg_attr(feature = "offline", derive(serde::Serialize, serde::Deserialize))] pub struct MssqlTypeInfo(pub(crate) ProtocolT...
#[doc = "Reader of register MCS"] pub type R = crate::R<u32, super::MCS>; #[doc = "Writer for register MCS"] pub type W = crate::W<u32, super::MCS>; #[doc = "Register MCS `reset()`'s with value 0"] impl crate::ResetValue for super::MCS { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { ...
pub mod domain; pub mod stat; pub mod user;
/* 给定一个整数数组 nums,其中恰好有两个元素只出现一次,其余所有元素均出现两次。 找出只出现一次的那两个元素。 示例 : 输入: [1,2,1,3,2,5] 输出: [3,5] 注意: 结果输出的顺序并不重要,对于上面的例子, [5, 3] 也是正确答案。 你的算法应该具有线性时间复杂度。你能否仅使用常数空间复杂度来实现? 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/single-number-iii 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 */ impl Solution { pub fn single_number...
// Copyright 2017 Dasein Phaos aka. Luxko // // 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>, at your // option. This file may not be copied, modified, or distributed // except a...
use serde::Deserialize; #[derive(Deserialize, Debug, PartialEq)] pub struct Mash {}
//! Futures //! //! This module contains the `Future` trait and a number of adaptors for this //! trait. See the crate docs, and the docs for `Future`, for full detail. use core::fmt; use core::result; // Primitive futures mod empty; mod lazy; mod poll_fn; #[path = "result.rs"] mod result_; mod loop_fn; mod option; p...
//! Provides types for fetching tool distributions into the Notion catalog. mod error; pub mod node; pub mod yarn; use catalog::Collection; use notion_fail::Fallible; use semver::Version; use std::fs::File; /// The result of a requested installation. pub enum Fetched { /// Indicates that the given tool was alrea...
use num_bigint::BigInt; use num_complex::Complex64; use num_traits::ToPrimitive; use std::collections::hash_map::DefaultHasher; use std::hash::{Hash, Hasher}; use std::num::Wrapping; pub type PyHash = i64; pub type PyUHash = u64; /// Prime multiplier used in string and various other hashes. pub const MULTIPLIER: PyHa...
extern crate proconio; use proconio::input; fn main() { input! { n: f64, m: f64, d: i64, } println!( "{}", if d == 0 { 1.0 / n * (m - 1.0) } else { (n - (d as f64)) * 2.0 / n / n * (m - 1.0) } ); }
use std::env; use std::fs::File; use std::io::Read; use std::path::Path; use std::vec::Vec; use vtf::Error; fn main() -> Result<(), Error> { let args: Vec<_> = env::args().collect(); if args.len() != 2 { panic!("Usage: info <path to vtf file>"); } let path = Path::new(&args[1]); let mut f...
mod receiver; mod sender; pub use self::{receiver::Receiver, sender::Sender};