text
stringlengths
8
4.13M
use crate::instructions::base::bytecode_reader::BytecodeReader; use crate::instructions::base::instruction::{ Instruction, LocalVarsInstruction, NoOperandsInstruction, }; use crate::runtime::frame::Frame; fn d_store(frame: &mut Frame, index: usize) { let val = frame .operand_stack() .expect("op...
use crate::apiclient::APIClient; use crate::endpoint::{Endpoint, Method}; use crate::response::{APIFailure, APIResponse, APIResult}; use reqwest; pub struct MockAPIClient {} // This endpoint does nothing. Designed for use with MockAPIClient. pub struct NoopEndpoint {} impl Endpoint<NoopResult> for NoopEndpoint { ...
pub fn solve(){ const INPUT : &str = include_str!("../../inputs/2015/24"); let mut weights : Vec<usize> = INPUT .lines() .map(|l| l.parse().unwrap()) .collect(); weights.sort_by(|a, b| b.cmp(a)); let g1 = find_best_first_group(&weights, 3); let qe = g1.iter().product::<usi...
#[cfg(test)] mod tests { extern crate rsipfix; use self::rsipfix::{formatter, parser, state}; use std::net::Ipv4Addr; use std::sync::{Arc, RwLock}; // shall not cause infinite loop #[test] fn looper_01() { let b = include_bytes!("./looper_01.bin"); let mut s = state::State:...
// //! Copyright 2020 Alibaba Group Holding 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 a...
pub fn pkcs_7_pad(buf: &mut Vec<u8>, len: usize) { if len < buf.len() { return } let padlen = len - buf.len(); for _ in 0..padlen { buf.push(padlen as u8); } }
use crate::{ast::{Name, AstNode}, SyntaxNode, TokenText}; impl Name { pub fn text(&self) -> TokenText { text_of_first_token(self.syntax()) } } fn text_of_first_token(node: &SyntaxNode) -> TokenText { let first_token = node .green() .children() .next() .and_then(|it|...
// #![feature(wasm_target_feature)] // #![feature(stdsimd)] use futures_channel::oneshot; use js_sys::{Promise, Uint8ClampedArray, WebAssembly}; use rayon::prelude::*; use wasm_bindgen::prelude::*; use wasm_bindgen::JsCast;// needed for unchecked_into use wasm_bindgen::__rt::std::collections::HashMap; use colorous; us...
// File-storage index-file and mmap index use std::io::prelude::*; use byteorder::{ReadBytesExt, WriteBytesExt}; use crate::util; pub type Index = std::collections::btree_map::BTreeMap<util::Oid, u64>; static MAGIC: &'static [u8] = b"fs2i"; pub fn save_index(index: &Index, path: &str, segment_siz...
use std::collections::{HashMap, BTreeMap, VecDeque}; use std::fmt::Display; use std::fmt; use std::time::Duration; use std::cmp::{min, max}; type Matrix = Vec<Vec<bool>>; struct MGraph { vertex: BTreeMap<String, usize>, edges: Matrix, } impl MGraph { pub fn new_empty(n: usize) -> Self { let x = ...
pub mod termion_wrapper; pub mod tui; mod bar; mod button; mod canvas; mod color_scheme; mod container; mod controller; mod dial; mod display; mod item_selection; mod label; mod marker_manager; mod midi_learn; mod mouse; mod observer; mod printer; mod select; mod slider; mod statemachine; mod stdio_printer; mod surfac...
use std::thread; use std::sync::mpsc::channel; use std::io::Write; use std::time::Duration; fn main() { let (tx, rx) = channel(); thread::spawn(move || { loop { match rx.recv() { Ok(msg) => println!("Received message '{}'", msg), Err(err) => { eprintln!("Receive Error: {}, clos...
use cargo_snippet::snippet; #[snippet("EularTour")] #[derive(Debug)] struct EularTour { g: Vec<Vec<usize>>, n: usize, vid: usize, enter: Vec<usize>, leave: Vec<usize>, } #[snippet("EularTour")] impl EularTour { pub fn new(n: usize) -> EularTour { EularTour { g: vec![vec![];n...
struct Solution; use std::i32; impl Solution { fn replace_elements(mut arr: Vec<i32>) -> Vec<i32> { let mut max = -1; let n = arr.len(); for i in (0..n).rev() { let t = max; max = i32::max(arr[i], max); arr[i] = t; } arr } } #[test] f...
#![allow(unused_variables)] pub fn verse(n: u32) -> String { let mut s = String::with_capacity(130); if n != 0 { let n_str = String::from(&n.to_string()); let n_str_next: String = match n { 1 => String::new(), _ => String::from(&(n - 1).to_string()), }; ...
#[doc = "Reader of register WF19TO16"] pub type R = crate::R<u32, super::WF19TO16>; #[doc = "Writer for register WF19TO16"] pub type W = crate::W<u32, super::WF19TO16>; #[doc = "Register WF19TO16 `reset()`'s with value 0"] impl crate::ResetValue for super::WF19TO16 { type Type = u32; #[inline(always)] fn re...
use machine::state::State; pub fn fint(state: &mut State, x: u8, y: u8, z: u8) { // Load operands let op1: f64 = state.gpr[z].into(); // Execute let res: f64 = match y { 1 => op1.round(), // round off 2 => op1.ceil(), // round up 3 => op1.floor(), // round down ...
use std::fs::File; use std::io; use std::io::Read; #[cfg_attr(rustfmt, rustfmt_skip)] static SQUARE_KEYPAD: [[u32; 3]; 3] = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]; #[cfg_attr(rustfmt, rustfmt_skip)] static DIAMOND_KEYPAD: [[char; 5]; 5] = [['0',...
use bevy::prelude::*; mod todomvc; fn main() { App::build() .add_default_plugins() .add_plugin(todomvc::TodoPlugin) .run(); }
// Copyright (c) 2020 kprotty // // 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 in wri...
#[allow(unused_imports)] use serde_json::Value; #[derive(Debug, Serialize, Deserialize)] pub struct ClusterPatchPatchesPatch { /// A long comment about the patch. #[serde(rename = "comment")] pub comment: Option<String>, /// Other patches that this patch conflicts with. #[serde(rename = "conflicts"...
use super::*; #[derive(Clone, Debug, Default)] pub struct Insert { extend: bool, } impl Insert { pub fn new_normal() -> Self { Self { extend: false } } pub fn new_extend() -> Self { Self { extend: true } } } impl Mode for Insert { fn name(&self) -> &str { "insert" ...
use std::fs::File; use std::io::prelude::*; use std::io::{BufReader, BufWriter}; fn main() { let file = File::open("../nock10/src/poplular-names.txt").unwrap(); let mut writer = BufWriter::new(File::create("src/format-popular-names2.txt").unwrap()); let file = BufReader::new(file); for i in file.lines(...
// 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...
use components::app; use std::io; use std::sync::mpsc::Receiver; use structs::app::events::Event; use termion::input::MouseTerminal; use termion::raw::IntoRawMode; use termion::screen::AlternateScreen; use tui::backend::TermionBackend; use tui::terminal::CompletedFrame; use tui::Terminal; pub fn keep_alive(receiver:...
use std::path::PathBuf; use std::sync::atomic::Ordering; use gtk::prelude::*; use gtk::{ self, Builder, Button, CellRendererText, ComboBox, CheckButton, Entry, FileChooserDialog, ListBox, ProgressBar, TreeView, TreeStore, TreeViewColumn, Scale, SpinButton, Switch, Window, WindowType }; use crate::co...
// Mas bucles fn main() { let mut m = 0; while m < 100 { // la función de rango tiene el mismo comportamiento // que en python for n in range(1,100) { if n % 10 == 0 { m+=1; }else if n % 2 == 0 { m+=1; }else{ println!("{}",n); } } } }
pub const OPC_RETURN: u8 = 0x0f;
// examples/reader_trans1 #[allow(unused_imports)] use monadic::{rdrt_mdo, monad::{Monad}, reader_trans::{ReaderT, ask, local}}; use num::Integer; use partial_application::partial; use std::collections::HashMap; /// mandatory type alias Env as it is used in the macro /// to save you type annotations ty...
extern crate fnv; use fnv::FnvHashSet; struct Set<T>(FnvHashSet<T>); impl<T: Eq + Hash> Set<T> { fn new(cap: usize) -> Self { Set(FnvHashSet::with_capacity_and_hasher(cap, Default::default())) } } impl<'a, T> Into<&'a FnvHashSet<T>> for &'a Set<T> { fn into(self) -> &'a FnvHashSet<T> { let &Set(ref has...
// 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 ...
/*! This crate provides the ability to create overloadable functions in rust through the use of a macro. # Syntax: ```ignore # #![feature(fn_traits, unboxed_closures, proc_macro_hygiene)] # struct function_types; # struct optional_return_type; # trait constraints {} # const code_body: () = (); use o...
#![no_std] pub use raspi_pico_sdk_sys::*;
extern "C" { fn native_dep() -> isize; } fn main() { println!("{}", unsafe { native_dep() }) }
use crate::{renderer::RenderContext, shapes::Shape}; use std::ops::{Deref, DerefMut}; use std::rc::Rc; pub struct TextContainer; pub struct ShapeContainer<S> where S: Shape, { pub shapes: Vec<S>, pub render_context: Rc<RenderContext<S>>, } impl<S> ShapeContainer<S> where S: Shape, <S as Shape>::V...
extern crate futures; extern crate grpcio; extern crate protobuf; extern crate serde; extern crate serde_json; //#[macro_use] //extern crate serde_derive; //pub mod consignment; //pub mod consignment_grpc; pub mod log_util;
fn main() { // kprimes_step(2, 2, 0, 50); // kprimes_step(6, 14, 2113665, 2113889); kprimes_step(2, 8, 27553, 27829); // println!("k primes for 10 -> {}", factor(10)); } // fn test() { // kprimes_step(2, 2, 0, 50); // // kprimes_step(6, 14, 2113665, 2113889); // // kprimes_step(2, 10, 0, 50); // // kpr...
#![allow(dead_code)] #![feature(test)] extern crate test; mod easy;
fn main(){ let t = (1, "2"); println!("{:?}", t); println!("{}", t.0); println!("{}", t.1); }
#![allow(dead_code)] use crate::error::*; use crate::executor::simplify; use falcon::il; use lazy_static::lazy_static; use std::collections::HashMap; use std::sync::RwLock; lazy_static! { pub static ref HASH_EXPRESSION_STORE: RwLock<HashExpressionStore> = RwLock::new(HashExpressionStore::new()); } // has...
#![allow(unused_imports)] use tracing::{info, warn, debug, error, trace, instrument, span, Level}; use serde::*; use ate::prelude::*; use std::time::Duration; #[derive(Debug, Serialize, Deserialize, Clone)] pub struct SudoRequest { pub session: AteSessionUser, pub authenticator_code: String, } #[derive(Debug,...
// Copyright 2021 The BMW Developers // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed...
pub const MAGIC_HEADER: [u8; 4] = [0x91, 0x16, 0x10, 0x81];
//! Filesystem stream utilities. use std::cmp; use std::io::{self, SeekFrom}; use std::ops::Range; use std::path::{Path, PathBuf}; use std::pin::Pin; use std::task::Poll; use anyhow::{ensure, Result}; use bytes::BytesMut; use futures::{prelude::*, ready}; use tokio::fs; use tokio::io::{AsyncSeekExt, AsyncWriteExt}; ...
use crate::sbi; use core::panic::PanicInfo; #[panic_handler] fn on_panic(info: &PanicInfo) -> ! { println!("\x1b[1;31mpanic: '{:?}'\x1b[0m", info); sbi::shutdown() }
use amethyst::{ core::{math::clamp, Time}, ecs::{Join, Read, ReadExpect, ReadStorage, System, WriteStorage}, }; use crate::{ components::{Dead, Player, PlayerActions, WorldPosition}, data_resources::GameScene, Vector2, ZeroVector, }; pub struct PlayerMovementSystem; const PLAYER_SPEED: f32 = 200....
#[derive(Clone, Copy, Debug, PartialEq)] enum Cell { Empty, Mine, Number(u32), } fn to_cells(s: &str) -> Vec<Cell> { s.chars() .map(|c: char| { match c { '*' => Cell::Mine, ' ' => Cell::Empty, x => Cell::Number(x.to_digit(10).unwrap())...
use core::f64; use core::fmt; use serde::Deserialize; #[derive(Debug, Deserialize, Clone, Copy)] pub struct OHLC { pub open_time: Option<f64>, pub open: Option<f64>, pub high: Option<f64>, pub low: Option<f64>, pub close: Option<f64>, pub close_time: Option<f64>, } impl OHLC { pub fn new()...
use super::*; pub(super) fn eval_arg(env: &Environment, last_return: i32, arg: &str) -> String { if arg.as_bytes()[0] == b'$' { let key: &str = &arg[1..]; match key { "?" => format!("{}", last_return), _ => match env.get(key) { Some(v) => v.clone(), ...
use drone_macros_core::unkeywordize; use heck::{ToSnakeCase, ToUpperCamelCase}; use proc_macro::TokenStream; use proc_macro2::{Span, TokenStream as TokenStream2}; use quote::{format_ident, quote}; use std::collections::HashSet; use syn::parse::{Parse, ParseStream, Result}; use syn::{braced, parse_macro_input, Attribute...
// Copyright 2016 Jeremy Mason // // 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...
use crate::{ error::NettuError, shared::usecase::{execute, UseCase}, }; use actix_web::{web, HttpResponse}; use nettu_scheduler_api_structs::create_account::{APIResponse, RequestBody}; use nettu_scheduler_domain::Account; use nettu_scheduler_infra::NettuContext; pub async fn create_account_controller( ctx:...
pub fn selection_sort(elements: &[i32]) -> Vec<i32> { selection_sort_aux(elements, &mut Vec::with_capacity(elements.len())) } fn selection_sort_aux(elements: &[i32], sorted: &mut Vec<i32>) -> Vec<i32> { if elements.is_empty() { return sorted.to_vec(); } let i = find_smallest(elements); sort...
use std::time::{Duration, Instant}; use amethyst::assets::Handle; use amethyst::ecs::{Component, DenseVecStorage, VecStorage}; use amethyst::renderer::{Material, Mesh}; use rhusics::ecs::collide::prelude2d::{BodyPose2, Collider, CollisionShape2}; pub type Shape = CollisionShape2<BodyPose2, ObjectType>; #[repr(u8)] #...
use hyper::mime::{Attr, Mime, SubLevel, TopLevel, Value}; use reqwest; use reqwest::{Client, Error, Method, Response, StatusCode}; use reqwest::header::{qitem, Accept, Authorization, Basic, ContentType, UserAgent}; use serde::de::DeserializeOwned; use serde_json; pub struct Headers { pub headers: reqwest::header::...
///extern 的使用无需 unsafe fn using_extern_functions_to_call_external_clode() { extern "C" { //集成 C 标准库中的 abs 函数 fn abs(input: i32) -> i32; } unsafe { println!("Absolute value of -3 according to C: {}", abs(-3)); } } #[no_mangle] pub extern "C" fn call_from_c() { println!("Jus...
use sai::{System}; use tokio::signal; mod gotham_server; mod db; mod foo_controller; mod tide_server; mod root_registry; use root_registry::RootRegistry; #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> { let mut system : System<RootRegistry> = System::new(); println!("System startin...
fn different_arguments(int: i32, float: f32, boolean: bool) { println!("Entered integer: {}", int); println!("Entered float: {}", float); println!("Entered boolean: {}", boolean); } fn main() { different_arguments(42, 32.0, true); }
use crate::ast::*; use std::collections::HashMap; #[derive(Default)] pub struct Expander<'a> { pub to_prepend: Vec<ModuleField<'a>>, func_types: HashMap<(Vec<ValType<'a>>, Vec<ValType<'a>>), u32>, ntypes: u32, } impl<'a> Expander<'a> { pub fn expand(&mut self, item: &mut ModuleField<'a>) { mat...
use nom::character::complete::alpha1; use super::error::{ParseError, ParseResult}; use crate::types::Dimension; pub fn parse_dimension(input: &str) -> ParseResult<Dimension> { let (input, dim) = alpha1(input)?; match dim { "s" | "sec" | "secs" | "second" | "seconds" => { Ok((input, Dimension::Second)) } "m...
//! Simple Open Framing Header (SOFH) support. //! //! SOFH provides encoding-agnostic message framing. By SOFH rules, each payload //! is preceded by a header that consists of six (6) bytes, which contain //! information regarding both //! - payload's encoding type //! - payload's total length //! //! Please refer to ...
mod config; mod findup; mod search_path; use crate::Error; pub use config::Config; use search_path::SearchPath; use std::env; use std::fs; use std::io::BufReader; use std::path::Path; pub struct Settings { pub search_paths: Vec<SearchPath>, } fn from_file<P: AsRef<Path>>(path: P) -> Result<Settings, Error> { ...
use num_traits::PrimInt as Int; /// The modulo function (handles negatives differently to Rust's remainder `%` operator). #[inline] pub fn modulo<I: Int>(a: I, b: I) -> I { match a % b { r if (r > I::zero() && b < I::zero()) || (r < I::zero() && b > I::zero()) => r + b, r => r, } }
use crate::Error; use chrono::{Duration, Utc}; use http::uri::Authority; use moka::future::Cache; use rcgen::{ DistinguishedName, DnType, ExtendedKeyUsagePurpose, KeyPair, KeyUsagePurpose, RcgenError, SanType, }; use std::{ sync::{Arc, Mutex}, time::{SystemTime, UNIX_EPOCH}, }; use tokio_rustls::rustls:...
use api::ChannelState; #[derive(Clone,Debug,PartialEq)] pub enum Error { SendBufferTooSmall, ReceiveBufferTooSmall, GeneratorError, ParserError, InvalidState(InvalidState), InvalidMethod, InvalidChannel, NotConnected, UnexpectedAnswer, } #[derive(Clone,Debug,PartialEq)] pub struct InvalidState { ...
use compiler::transform::PluginPass; use compiler::transform::Plugin; use std::result::Result; use std::error::Error; use compiler::ast::statement::StatementTerminator; use compiler::ast::expression::Expression; pub struct PrettifyPlugin {} impl Plugin for PrettifyPlugin { fn handle(&self, pass: &mut PluginPas...
use svm_sdk_mock::template; #[template] mod Template { #[fundable_hook] #[fundable_hook] fn get(value: svm_sdk::Amount) {} } fn main() {}
use git2; use std::error::Error; #[cfg(test)] use std::path::Path; use crate::author::Author; type StoreResult<T> = Result<T, Box<dyn Error>>; pub trait Store { fn add(&mut self, author: &Author) -> StoreResult<()>; fn active(&self) -> StoreResult<Vec<Author>>; fn authors(&self) -> StoreResult<Vec<Autho...
use std::collections::HashMap; use rand::prelude::*; use tbsux::playered::Player; use crate::{ cards::{Card, Rank}, error::{SechsUndSechzigError, SusResult}, variant::Variant, }; #[derive(Debug, Copy, Clone)] pub enum HandType { First, Full, } #[derive(Debug, Clone)] pub struct Hand(Vec<Card>); ...
struct Foo { x: i32, } /* 参照は、 & 演算子によってリソースへのアクセスを借用できるようにしてくれます。 参照も、他のリソースと同様にドロップされます。 */ fn main() { let foo = Foo { x: 42 }; let f = &foo; println!("{}", f.x); println!("{}", foo.x); let mut foo = Foo { x: 33342 }; println!("{}", f.x); // 42 println!("{}", foo.x); foo = Foo...
//Copyright 2020 EinsteinDB Project Authors & WHTCORPS Inc. Licensed under Apache-2.0. use ekvproto::meta_timeshare::Brane; use violetabft::StateRole; use violetabftstore::interlock::{ BoxBraneChangeSemaphore, Interlock, SemaphoreContext, BraneChangeEvent, BraneChangeSemaphore, }; use violetabftstore::store::util:...
//! Methods for expanding structs use std::collections::{HashMap, VecDeque}; use anyhow::{Context as _, Result}; use inflector::Inflector; use proc_macro2::TokenStream; use quote::quote; use ethers_core::abi::{ param_type::Reader, struct_def::{FieldDeclaration, FieldType, StructFieldType, StructType}, Par...
pub mod plans; pub mod topological_sorting;
//! Convert the JSON file which contains possibly invalid structure into BinAST //! file. extern crate binjs; extern crate clap; extern crate env_logger; use binjs::io::{TokenReader, TokenWriter}; use binjs::generic::Node; use std::io::*; use std::thread; use clap::*; /// A dummy struct for enter_tagged_tuple_at/...
#![feature(core_intrinsics)] fn main() { // division by 0 unsafe { std::intrinsics::exact_div(2, 0) }; //~ ERROR: divisor of zero }
struct Solution; impl Solution { pub fn length_of_longest_substring(s: String) -> i32 { let mut set = std::collections::HashSet::new(); let (mut head, mut tail) = (0, 0); let cs = s.chars().collect::<Vec<char>>(); let mut max = 0; while tail < cs.len() { if let S...
/// convert clust spec to statefulset for input use std::collections::HashMap; use k8_metadata::core::metadata::InputK8Obj; use k8_metadata::core::metadata::InputObjectMeta; use k8_metadata::core::metadata::Env; use k8_metadata::core::metadata::ObjectMeta; use k8_metadata::core::metadata::TemplateMeta; use k8_metadata...
use strategies::{Strategy, StrategyBuilder}; pub struct SingleStaticBuilder {} impl StrategyBuilder for SingleStaticBuilder { fn build<'a, T: Clone> (items: Vec<&'a T>) -> Strategy<'a, T> { Box::new(move || items[0].clone()) } } #[cfg(test)] mod tests { use strategies::{StrategyBuilder}; us...
struct Solution; impl Solution { fn number_of_subarrays(nums: Vec<i32>, k: i32) -> i32 { let n = nums.len(); let mut count = vec![0; n + 1]; let k = k as usize; count[0] = 1; let mut prev = 0; let mut res = 0; for i in 0..n { if nums[i] % 2 == 1 {...
use bencher::Bencher; pub fn baseline(b: &mut Bencher) { b.iter(|| { let json_build = object!{ "test" => "abc" }; assert_eq!(json_build.dump(), super::BASELINE); }); } pub fn serial(b: &mut Bencher) { b.iter(|| { let json_build = object!{ "test1" => 1, "test2" => 2, "test...
use slog; use risso_api::logs::macros::*; use actix_web::{Error, FromRequest, HttpRequest}; use actix_web_requestid::RequestIDGetter; use std::ops::Deref; /// A `FromRequest` integrating `slog` with the `actix_request_id` crate: it resolves to a /// `slog::Logger` that has a `request_id` key/value pair to allow trac...
use crate::lightning::ln_db::{DBPaymentsFilter, HTLCStatus, PaymentInfo, PaymentType}; use crate::lightning::ln_platform::h256_json_from_txid; use crate::H256Json; use lightning::chain::channelmonitor::Balance; use lightning::ln::channelmanager::ChannelDetails; use secp256k1v24::PublicKey; use serde::{de, Serialize, Se...
table! { use diesel::sql_types::*; use crate::model::posts::Post_state; comments (id) { id -> Int4, comment -> Nullable<Text>, published_at -> Timestamptz, author -> Int4, post -> Int4, } } table! { use diesel::sql_types::*; use crate::model::posts::Post...
use fnv::{FnvHashMap, FnvHashSet}; use crate::{ handle::{Direction, Handle, NodeId}, packed::{self, *}, }; use super::{ defragment::Defragment, edges::EdgeListIx, graph::NARROW_PAGE_WIDTH, index::{NodeRecordId, OneBasedIndex, RecordIndex}, occurrences::OccurListIx, sequence::{SeqRecord...
extern crate ansi_term; extern crate chrono; extern crate git2; extern crate rustc_serialize; extern crate toml; extern crate walkdir; pub mod configuration; pub mod file; pub mod git; pub mod scan; use toml::{Encoder, Table}; /// /// Static variable to get the name of the git main directory /// pub static GIT_DIR_N...
use crate::Float; //use super::FilterData; use super::FilterType; // One pole filter used to construct Oberheim Moog ladder filter pub struct VAOnePole { //sample_rate: Float, // Only needed if filter is used stand-alone filter_type: FilterType, alpha: Float, beta: Float, gamma: Float, delta: F...
use std::rand; use std::rand::distributions::{IndependentSample,Range}; use std::io; use std::io::BufferedReader; fn generate_number(from: isize, to: isize) -> isize{ let between = Range::new(from,to); let mut rng = rand::thread_rng(); if from < 0 { panic!("Cant' have a negative lower bound."); } betwee...
//! Simple gluing structs that abstracts away multi cloud access use crate::pc_errors::{PointCloudError, PointCloudResult}; use crate::base_traits::*; use fxhash::FxBuildHasher; use hashbrown::HashMap; /// For large numbers of underlying point clouds #[derive(Debug)] pub struct HashGluedCloud<D> { addresses: Ha...
use std::sync::Arc; use std::boxed::Box; use std::any::Any; use std::ops::Deref; pub trait ToBoxedOwned { fn to_boxed_owned(&self) -> Box<Any>; } pub enum CowPtr<T> where T: ToBoxedOwned + 'static + ?Sized { Borrowed(Arc<T>), Owned(Box<T>), } unsafe impl<T: Send + ToBoxedOwned + 'static + ?Sized> Send for CowP...
fn test1() { let a = vec![1000,20,300]; for i in a.iter() { println!("{:?}", i); } } fn main() { let a = [10,5,8]; let b: Vec<i32> = a.into_iter().map(|x| {20*x}).collect(); println!("{:?}", a); }
use std::fmt; use crate::dnn::DictValue; use crate::prelude::*; impl fmt::Debug for DictValue { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let mut d = f.debug_struct("DictValue"); d.field("is_int", &self.is_int().map_err(|_| fmt::Error)?) .field("is_real", &self.is_real().map_err(|_| fmt::Error)?)...
use std::ops::Range; /// A 4 component floating-point color #[derive(Copy, Clone, Debug, PartialEq)] pub struct Color { pub r: f32, pub g: f32, pub b: f32, pub a: f32 } impl Color { /// Creates a new color from its 4 components pub fn new(r: f32, g: f32, b: f32, a: f32) -> Color { Colo...
#![feature(test)] extern crate test; extern crate numas; #[cfg(test)] mod tests { use test::Bencher; use numas::factory::{ fill, }; use numas::array::Array; #[bench] fn sin(b: &mut Bencher) { let a = fill::full(5, vec![10, 100, 100]); b.iter(|| a.sin()); } #[b...
// Copyright 2018-2021 Cargill Incorporated // // 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...
use older::Version as SpookyVersion; use semver::Version; fn main() { let version_1 = bincode::serialize(&Version::parse("1.3.0").unwrap()).unwrap(); let version_2 = bincode::serialize(&SpookyVersion::parse("1.3.0").unwrap()).unwrap(); assert_eq!(version_1, version_2); }
extern crate imageproc; extern crate image; pub struct HessianPyramid { num_octaves: u64, num_intervals: u64, initial_step_size: u64, } impl HessianPyramid { pub fn build_pyramid(&mut self, img: image::ImageBuffer<image::Rgba<u8>, Vec<u8>>) { let mut pyramid: Vec<Vec<Vec<f64>>> = Vec::new(); // resiz...
use std::env; use std::fs; struct PacketReader<'a> { bytes: &'a [u8], current: usize, bits: u8, read: u64, } impl<'a> PacketReader<'a> { fn new(bytes: &[u8]) -> PacketReader { PacketReader { bytes, current: 0, bits: 0, read: 0, } ...
// An attribute to hide the warnins for unused code. #![allow(dead_code)] enum Status { Rich, Poor, } enum Work { Civilian, Soldier, } fn main() { // Explicity `use` each name so they are available wihtout // manual scoping use Status::{Poor, Rich}; // Automotically `use` each name in...
#![allow(dead_code)] #![forbid(unconditional_recursion, future_incompatible)] #![warn(unused_lifetimes)] #![feature(associated_type_bounds)] #![feature(box_patterns)] #![feature(const_trait_impl)] #![feature(if_let_guard)] #![feature(let_chains)] #![feature(min_specialization)] #![feature(negative_impls)] #![feature(st...
#![deny(clippy::all)] use anyhow::Context; use gdlk::{Compiler, HardwareSpec, ProgramSpec}; use serde::de::DeserializeOwned; use std::{ fs, path::{Path, PathBuf}, process, }; use structopt::StructOpt; /// The sub-command to execute. #[derive(Debug, StructOpt)] enum Command { /// Compile source code. ...