file_name
large_stringlengths
4
69
prefix
large_stringlengths
0
26.7k
suffix
large_stringlengths
0
24.8k
middle
large_stringlengths
0
2.12k
fim_type
large_stringclasses
4 values
day_14.rs
//! This is my solution for [Advent of Code - Day 14](https://adventofcode.com/2020/day/14) - //! _Docking Data_ //! //! This was themed around bitwise operations. The challenge was mostly parsing the puzzle //! description into the bitwise operations needed. This was the first time I needed an Either //! implementatio...
else { let re = Regex::new(r"^mem\[(\d+)]$").unwrap(); match re.captures(inst) { Some(cap) => Right(Mem { address: cap.get(1).unwrap().as_str().parse::<usize>().unwrap(), value: value.parse::<usize>().unwrap(), }), None => panic!("Inv...
{ let (mask, data) = value.chars().fold( (0usize, 0usize), |(mask, data), char| ( mask << 1 | if char == 'X' { 1 } else { 0 }, data << 1 | if char == '1' { 1 } else { 0 } ), ); Left(Mask { ma...
conditional_block
schedule.rs
use crate::{ borrow::{Exclusive, RefMut}, command::CommandBuffer, resource::ResourceTypeId, storage::ComponentTypeId, world::World, }; use bit_set::BitSet; use itertools::izip; use std::iter::repeat; use std::{ collections::{HashMap, HashSet}, sync::atomic::{AtomicUsize, Ordering}, }; #[cfg...
let mut component_mutated = HashMap::<ComponentTypeId, Vec<usize>>::with_capacity(64); for (i, system) in systems.iter().enumerate() { log::debug!("Building dependency: {}", system.name()); let (read_res, read_comp) = system.reads(); let (write_r...
random_line_split
schedule.rs
use crate::{ borrow::{Exclusive, RefMut}, command::CommandBuffer, resource::ResourceTypeId, storage::ComponentTypeId, world::World, }; use bit_set::BitSet; use itertools::izip; use std::iter::repeat; use std::{ collections::{HashMap, HashSet}, sync::atomic::{AtomicUsize, Ordering}, }; #[cfg...
(&mut self, world: &mut World) { self.systems.iter_mut().for_each(|system| { system.run(world); }); // Flush the command buffers of all the systems self.systems.iter().for_each(|system| { system.command_buffer_mut().write(world); }); } /// Execut...
execute
identifier_name
edge.rs
use delaunator::{Point, Triangulation}; use itertools::Itertools; use std::collections::HashMap; #[derive(Clone, Copy)] pub struct Edge { pub vertex1: usize, pub vertex2: usize, pub edge_type1: EdgeType, pub edge_type2: EdgeType, pub active: bool, pub length: f64, } #[derive(PartialEq, Copy, Clone)] pub enum Ed...
pub fn calculate_connected_components(&mut self) { let mut cc_index = 1; while let Some(v) = self .verticies .iter_mut() .position(|x|!x.edges.is_empty() && x.label == 0) { self.build_connected_component(v, cc_index); cc_index += 1; } let groups = self.calculate_cc_sizes(); for (label, si...
{ if self.verticies[vertex_index].label != label { self.verticies[vertex_index].label = label; for i in 0..self.verticies[vertex_index].edges.len() { let edge_index = self.verticies[vertex_index].edges[i]; if self.edge_is_active(edge_index) && self.verticies[self.active_edges[edge_index].other(vert...
identifier_body
edge.rs
use delaunator::{Point, Triangulation}; use itertools::Itertools; use std::collections::HashMap; #[derive(Clone, Copy)] pub struct Edge { pub vertex1: usize, pub vertex2: usize, pub edge_type1: EdgeType, pub edge_type2: EdgeType, pub active: bool, pub length: f64, } #[derive(PartialEq, Copy, Clone)] pub enum Ed...
} } } } pub fn restore_edges(&mut self) { struct LabelReference { size: usize, label: usize, edge_index: usize, }; let mut cc_sizes = self.calculate_cc_sizes(); let mut reassign_map: HashMap<usize, usize> = HashMap::new(); for i in 0..self.verticies.len() { let short_edges: Vec<&Edge> ...
self.active_edges[edge].active = true; } if self.verticies[other].label != label { self.active_edges[edge].active = false;
random_line_split
edge.rs
use delaunator::{Point, Triangulation}; use itertools::Itertools; use std::collections::HashMap; #[derive(Clone, Copy)] pub struct Edge { pub vertex1: usize, pub vertex2: usize, pub edge_type1: EdgeType, pub edge_type2: EdgeType, pub active: bool, pub length: f64, } #[derive(PartialEq, Copy, Clone)] pub enum Ed...
} pub fn calculate_connected_components(&mut self) { let mut cc_index = 1; while let Some(v) = self .verticies .iter_mut() .position(|x|!x.edges.is_empty() && x.label == 0) { self.build_connected_component(v, cc_index); cc_index += 1; } let groups = self.calculate_cc_sizes(); for (label,...
{ self.verticies[vertex_index].label = label; for i in 0..self.verticies[vertex_index].edges.len() { let edge_index = self.verticies[vertex_index].edges[i]; if self.edge_is_active(edge_index) && self.verticies[self.active_edges[edge_index].other(vertex_index)].label == 0 { self.build_connect...
conditional_block
edge.rs
use delaunator::{Point, Triangulation}; use itertools::Itertools; use std::collections::HashMap; #[derive(Clone, Copy)] pub struct Edge { pub vertex1: usize, pub vertex2: usize, pub edge_type1: EdgeType, pub edge_type2: EdgeType, pub active: bool, pub length: f64, } #[derive(PartialEq, Copy, Clone)] pub enum Ed...
{ size: usize, label: usize, edge_index: usize, }; let mut cc_sizes = self.calculate_cc_sizes(); let mut reassign_map: HashMap<usize, usize> = HashMap::new(); for i in 0..self.verticies.len() { let short_edges: Vec<&Edge> = self.verticies[i] .edges .iter() .filter(|e| self.active_edges[...
LabelReference
identifier_name
garmin_util.rs
use anyhow::{format_err, Error}; use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine}; use fitparser::Value; use flate2::{read::GzEncoder, Compression}; use futures::{Stream, TryStreamExt}; use log::{debug, error}; use num_traits::pow::Pow; use postgres_query::{query, Error as PqError}; use rand::{ distri...
#[must_use] pub fn days_in_year(year: i32) -> i64 { (Date::from_calendar_date(year + 1, Month::January, 1).unwrap_or(date!(1969 - 01 - 01)) - Date::from_calendar_date(year, Month::January, 1).unwrap_or(date!(1969 - 01 - 01))) .whole_days() } #[must_use] pub fn days_in_month(year: i32, month: u32) -> i64...
random_line_split
garmin_util.rs
use anyhow::{format_err, Error}; use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine}; use fitparser::Value; use flate2::{read::GzEncoder, Compression}; use futures::{Stream, TryStreamExt}; use log::{debug, error}; use num_traits::pow::Pow; use postgres_query::{query, Error as PqError}; use rand::{ distri...
#[must_use] pub fn expected_calories(weight: f64, pace_min_per_mile: f64, distance: f64) -> f64 { let cal_per_mi = weight * (0.0395 + 0.003_27 * (60. / pace_min_per_mile) + 0.000_455 * (60. / pace_min_per_mile).pow(2.0) + 0.000_801 * ((weight / 154.0) * ...
{ let mut y1 = year; let mut m1 = month + 1; if m1 == 13 { y1 += 1; m1 = 1; } let month: Month = (month as u8).try_into().unwrap_or(Month::January); let m1: Month = (m1 as u8).try_into().unwrap_or(Month::January); (Date::from_calendar_date(y1, m1, 1).unwrap_or(date!(1969 - 01...
identifier_body
garmin_util.rs
use anyhow::{format_err, Error}; use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine}; use fitparser::Value; use flate2::{read::GzEncoder, Compression}; use futures::{Stream, TryStreamExt}; use log::{debug, error}; use num_traits::pow::Pow; use postgres_query::{query, Error as PqError}; use rand::{ distri...
<T, U, F>(f: T) -> Result<U, Error> where T: Fn() -> F, F: Future<Output = Result<U, Error>>, { let mut timeout: f64 = 1.0; let range = Uniform::from(0..1000); loop { match f().await { Ok(resp) => return Ok(resp), Err(err) => { sleep(Duration::from_mil...
exponential_retry
identifier_name
garmin_util.rs
use anyhow::{format_err, Error}; use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine}; use fitparser::Value; use flate2::{read::GzEncoder, Compression}; use futures::{Stream, TryStreamExt}; use log::{debug, error}; use num_traits::pow::Pow; use postgres_query::{query, Error as PqError}; use rand::{ distri...
Ok(()) } /// # Errors /// Return error if unzip fails pub fn extract_zip_from_garmin_connect( filename: &Path, ziptmpdir: &Path, ) -> Result<PathBuf, Error> { extract_zip(filename, ziptmpdir)?; let new_filename = filename .file_stem() .ok_or_else(|| format_err!("Bad filename {}", fil...
{ if let Some(mut f) = process.stdout.as_ref() { let mut buf = String::new(); f.read_to_string(&mut buf)?; error!("{}", buf); } return Err(format_err!("Failed with exit status {exit_status:?}")); }
conditional_block
intrinsicck.rs
// Copyright 2012-2014 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-MI...
(&self, def_id: DefId) -> bool { let intrinsic = match ty::lookup_item_type(self.tcx, def_id).ty.sty { ty::ty_bare_fn(_, ref bfty) => bfty.abi == RustIntrinsic, _ => return false }; if def_id.krate == ast::LOCAL_CRATE { match self.tcx.map.get(def_id.node) { ...
def_id_is_transmute
identifier_name
intrinsicck.rs
// Copyright 2012-2014 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-MI...
} impl<'a, 'tcx, 'v> Visitor<'v> for IntrinsicCheckingVisitor<'a, 'tcx> { fn visit_fn(&mut self, fk: visit::FnKind<'v>, fd: &'v ast::FnDecl, b: &'v ast::Block, s: Span, id: ast::NodeId) { match fk { visit::FkItemFn(..) | visit::FkMethod(..) => { let param_env = ...
{ debug!("Pushing transmute restriction: {}", restriction.repr(self.tcx)); self.tcx.transmute_restrictions.borrow_mut().push(restriction); }
identifier_body
intrinsicck.rs
// Copyright 2012-2014 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-MI...
use syntax::codemap::Span; use syntax::parse::token; use syntax::visit::Visitor; use syntax::visit; pub fn check_crate(tcx: &ctxt) { let mut visitor = IntrinsicCheckingVisitor { tcx: tcx, param_envs: Vec::new(), dummy_sized_ty: tcx.types.isize, dummy_unsized_ty: ty::mk_vec(tcx, tcx....
use syntax::ast_map::NodeForeignItem;
random_line_split
output.rs
use std::io; use std::string::ToString; use std::thread::sleep; use std::time::Duration; use std::{collections::BTreeMap, path::PathBuf}; use anyhow::Result; use comfy_table::presets::UTF8_HORIZONTAL_BORDERS_ONLY; use comfy_table::*; use snap::read::FrameDecoder; use pueue::log::{get_log_file_handles, get_log_paths};...
(task_id: usize, settings: &Settings) { let (mut stdout_log, mut stderr_log) = match get_log_file_handles(task_id, &settings.shared.pueue_directory) { Ok((stdout, stderr)) => (stdout, stderr), Err(err) => { println!("Failed to get log file handles: {}", err); ...
print_local_log_output
identifier_name
output.rs
use std::io; use std::string::ToString; use std::thread::sleep; use std::time::Duration; use std::{collections::BTreeMap, path::PathBuf}; use anyhow::Result; use comfy_table::presets::UTF8_HORIZONTAL_BORDERS_ONLY; use comfy_table::*; use snap::read::FrameDecoder; use pueue::log::{get_log_file_handles, get_log_paths};...
pub fn print_error(message: &str) { let styled = style_text(message, Some(Color::Red), None); println!("{}", styled); } pub fn print_groups(message: GroupResponseMessage) { let mut text = String::new(); let mut group_iter = message.groups.iter().peekable(); while let Some((name, status)) = group_...
{ println!("{}", message); }
identifier_body
output.rs
use std::io; use std::string::ToString; use std::thread::sleep; use std::time::Duration; use std::{collections::BTreeMap, path::PathBuf}; use anyhow::Result; use comfy_table::presets::UTF8_HORIZONTAL_BORDERS_ONLY; use comfy_table::*; use snap::read::FrameDecoder; use pueue::log::{get_log_file_handles, get_log_paths};...
if group.eq("default") { continue; } // Skip unwanted groups, if a single group is requested if let Some(group_only) = &group_only { if group_only!= group { continue; } } let headline = get_group_headline( &...
while let Some((group, tasks)) = sorted_iter.next() { // We always want to print the default group at the very top. // That's why we print it outside of this loop and skip it in here.
random_line_split
player.rs
use std::f32; use nalgebra::{norm, zero, Point2, Rotation2, Vector2}; use specs::prelude::*; use specs::storage::BTreeStorage; use defs::{EntityId, GameInfo, PlayerId, PlayerInput, INVALID_ENTITY_ID}; use event::{self, Event}; use game::entity::hook; use game::ComponentType; use physics::collision::{self, CollisionG...
( world: &mut World, _inputs: &[(PlayerId, PlayerInput, Entity)], ) -> Result<(), repl::Error> { hook::run_input_post_sim(&world)?; world.write::<hook::CurrentInput>().clear(); world.write::<CurrentInput>().clear(); Ok(()) } pub mod auth { use super::*; pub fn create(world: &mut Worl...
run_input_post_sim
identifier_name
player.rs
use std::f32; use nalgebra::{norm, zero, Point2, Rotation2, Vector2}; use specs::prelude::*; use specs::storage::BTreeStorage; use defs::{EntityId, GameInfo, PlayerId, PlayerInput, INVALID_ENTITY_ID}; use event::{self, Event}; use game::entity::hook; use game::ComponentType; use physics::collision::{self, CollisionG...
pub mod auth { use super::*; pub fn create(world: &mut World, owner: PlayerId, pos: Point2<f32>) -> (EntityId, Entity) { let (id, entity) = repl::entity::auth::create(world, owner, "player", |builder| { builder.with(Position(pos)) }); let mut hooks = [INVALID_ENTITY_ID; N...
{ hook::run_input_post_sim(&world)?; world.write::<hook::CurrentInput>().clear(); world.write::<CurrentInput>().clear(); Ok(()) }
identifier_body
player.rs
use std::f32; use nalgebra::{norm, zero, Point2, Rotation2, Vector2}; use specs::prelude::*; use specs::storage::BTreeStorage; use defs::{EntityId, GameInfo, PlayerId, PlayerInput, INVALID_ENTITY_ID}; use event::{self, Event}; use game::entity::hook; use game::ComponentType; use physics::collision::{self, CollisionG...
if input.1[MOVE_RIGHT_KEY] { state.dash(right); } if input.1[MOVE_LEFT_KEY] { state.dash(-right); } state.update_dash(dt); if let Some(dash_state) = state.dash_state.as_ref() { velocity.0 += Vector...
{ state.dash(-forward); }
conditional_block
player.rs
use std::f32; use nalgebra::{norm, zero, Point2, Rotation2, Vector2}; use specs::prelude::*; use specs::storage::BTreeStorage; use defs::{EntityId, GameInfo, PlayerId, PlayerInput, INVALID_ENTITY_ID}; use event::{self, Event}; use game::entity::hook; use game::ComponentType; use physics::collision::{self, CollisionG...
fn class(&self) -> event::Class { event::Class::Order } } /// Component that is attached whenever player input should be executed for an entity. #[derive(Component, Clone, Debug)] #[storage(BTreeStorage)] pub struct CurrentInput(pub PlayerInput, [bool; NUM_TAP_KEYS]); impl CurrentInput { fn new(in...
impl Event for DashedEvent {
random_line_split
linktypes.rs
//! LINK-LAYER HEADER TYPE VALUES [https://www.tcpdump.org/linktypes.html](https://www.tcpdump.org/linktypes.html) //! //! LINKTYPE_ name | LINKTYPE_ value | Corresponding DLT_ name | Description /// DLT_NULL BSD loopback encapsulation; the link layer header is a 4-byte field, in host byte order, containing a value of...
/// DLT_AX25_KISS AX.25 packet, with a 1-byte KISS header containing a type indicator. pub const AX25_KISS: i32 = 202; /// DLT_LAPD Link Access Procedures on the D Channel (LAPD) frames, as specified by ITU-T Recommendation Q.920 and ITU-T Recommendation Q.921, starting with the address field, with no pseudo-header. pu...
pub const ERF: i32 = 197; /// DLT_BLUETOOTH_HCI_H4_WITH_PHDR Bluetooth HCI UART transport layer; the frame contains a 4-byte direction field, in network byte order (big-endian), the low-order bit of which is set if the frame was sent from the host to the controller and clear if the frame was received by the host from t...
random_line_split
storage.rs
//! A module encapsulating the Raft storage interface. use actix::{ dev::ToEnvelope, prelude::*, }; use futures::sync::mpsc::UnboundedReceiver; use failure::Fail; use crate::{ proto, raft::NodeId, }; /// An error type which wraps a `dyn Fail` type coming from the storage layer. /// /// This does requ...
/// state record; and the index of the last log applied to the state machine. pub struct GetInitialState; impl Message for GetInitialState { type Result = StorageResult<InitialState>; } /// A struct used to represent the initial state which a Raft node needs when first starting. pub struct InitialState { /// ...
/// The storage impl may need to look in a few different places to accurately respond to this /// request. That last entry in the log for `last_log_index` & `last_log_term`; the node's hard
random_line_split
storage.rs
//! A module encapsulating the Raft storage interface. use actix::{ dev::ToEnvelope, prelude::*, }; use futures::sync::mpsc::UnboundedReceiver; use failure::Fail; use crate::{ proto, raft::NodeId, }; /// An error type which wraps a `dyn Fail` type coming from the storage layer. /// /// This does requ...
(pub Box<dyn Fail>); /// The result type of all `RaftStorage` interfaces. pub type StorageResult<T> = Result<T, StorageError>; ////////////////////////////////////////////////////////////////////////////// // GetInitialState /////////////////////////////////////////////////////////// /// An actix message type for re...
StorageError
identifier_name
main.rs
use std::collections::HashMap; // To allow me to use the hashmap I created with the menu items. /* This function will remove any newline characters or returns that are read in. In this the string is passed by reference. I created this as an example and initially used both remove, and removed, but for convienence I en...
(mut string: String) -> String { if let Some('\n')=string.chars().next_back() { string.pop(); } if let Some('\r')=string.chars().next_back() { string.pop(); } string } /*This will set up to take input from the keyboard. It will then remove any newline or return characters, by ca...
removed
identifier_name
main.rs
use std::collections::HashMap; // To allow me to use the hashmap I created with the menu items. /* This function will remove any newline characters or returns that are read in. In this the string is passed by reference. I created this as an example and initially used both remove, and removed, but for convienence I en...
} else if tip == 4{ println!("Please enter a specific amount, including the change. Ex '10.00':"); total += rdin().parse::<f32>().unwrap(); //Will convert the string to a floating point number. Will break if letters are read in. } else{ println!("I...
} else if tip == 3{ total += DOLLAR;
random_line_split
main.rs
use std::collections::HashMap; // To allow me to use the hashmap I created with the menu items. /* This function will remove any newline characters or returns that are read in. In this the string is passed by reference. I created this as an example and initially used both remove, and removed, but for convienence I en...
items.insert(String::from("pizza"), 2.95); items.insert(String::from("fries"), 1.95); items.insert(String::from("stake"), 9.95); //Creates a vector. It is necessary to specify the data type that will be in the vector. let mut itemPrice: Vec<f32> = Vec::new(); let mut total: f32; let mut five...
{ //Constants declared for the tax rate, default tip rates, and special tip cases. const TAX: f32 = 0.06; const FIVE: f32 = 0.05; const TEN: f32 = 0.10; const FTN: f32 = 0.15; const TWN: f32 = 0.20; const QRT: f32 = 0.25; const HALF: f32 = 0.50; const DOLLAR: f32 = 1.00; //use mu...
identifier_body
lib.rs
*death_watch += 1; } } // prune all filters with an expired death ticker let level = &self.desperation_level; self.trackers .retain(|(_id, death_count, _tracker)| death_count < level); return predictions; } pub fn dump_filter_rea...
{ ImageBuffer::from_vec(width, height, buf.iter().map(|c| *c as u8).collect()).unwrap() }
identifier_body
lib.rs
for i in 0..width { for j in 0..height { let cww = ((f32::consts::PI * i as f32) / (width - 1) as f32).sin(); let cwh = ((f32::consts::PI * j as f32) / (height - 1) as f32).sin(); prepped[position] = cww.min(cwh) * prepped[position]; position += 1; } ...
(&self) -> usize { self.trackers.len() } } pub struct Prediction { pub location: (u32, u32), pub psr: f32, } pub struct MosseTracker { filter: Vec<Complex<f32>>, // constants frame height frame_width: u32, frame_height: u32, // stores dimensions of tracking window and its cen...
size
identifier_name
lib.rs
track_new_frame(frame); predictions.push((*id, pred)); // if the tracker made the PSR threshold, update it. // if not, we increment its death ticker. if tracker.last_psr > self.settings.psr_threshold { tracker.update(frame); *death_watch =...
fn index_to_coords(width: u32, index: u32) -> (u32, u32) { // modulo/remainder ops are theoretically O(1) // checked_rem returns None if rhs == 0, which would indicate an upstream error (width == 0). let x = index.checked_rem(width).unwrap();
random_line_split
main.rs
#![deny(unused_must_use)] #![type_length_limit = "1340885"] extern crate serenity; extern crate ctrlc; #[macro_use] pub mod logger; pub mod canary_update; pub mod dogebotno; pub mod permissions; pub mod servers; pub mod voice; use canary_update::*; use futures::{Stream, StreamExt}; use lazy_static::*; use logger::get_...
async fn ready(&self, ctx: Context, _data: Ready) { log_timestamp!("INFO", format!("Shard {} ready", ctx.shard_id)); } async fn cache_ready(&self, ctx: Context, guilds: Vec<GuildId>) { let shard = ctx.shard_id; let rctx = &ctx; // Get all the guilds that this shard is connected to // Not that this bot wil...
{ log_timestamp!("INFO", "Reconnected to discord"); }
identifier_body
main.rs
#![deny(unused_must_use)] #![type_length_limit = "1340885"] extern crate serenity; extern crate ctrlc; #[macro_use] pub mod logger; pub mod canary_update; pub mod dogebotno; pub mod permissions; pub mod servers; pub mod voice; use canary_update::*; use futures::{Stream, StreamExt}; use lazy_static::*; use logger::get_...
}) .log_err(); // Hah you think this bot is big enough to be sharded? Nice joke // But if yours is use.start_autosharded() client.start().await?; Ok(()) } /// Handles the @someone ping. Yes im evil. async fn someone_ping(ctx: &Context, msg: &Message) { let guild_id: Option<GuildId> = msg.guild_id; let channel_...
std::process::exit(0);
random_line_split
main.rs
#![deny(unused_must_use)] #![type_length_limit = "1340885"] extern crate serenity; extern crate ctrlc; #[macro_use] pub mod logger; pub mod canary_update; pub mod dogebotno; pub mod permissions; pub mod servers; pub mod voice; use canary_update::*; use futures::{Stream, StreamExt}; use lazy_static::*; use logger::get_...
(ctx: &Context, msg: &Message) -> CommandResult { if msg.author.id!= 453344368913547265 { msg.channel_id.say(&ctx, "No").await.log_err(); return Ok(()); } //let canary = ctx.data.read().get::<CanaryUpdateHandler>().cloned().unwrap(); //let lock = canary.lock()?; //let res = lock.create_db(); //res.log_err(); ...
test
identifier_name
backend.rs
use crate::intrinsics::Intrinsics; use inkwell::{ memory_buffer::MemoryBuffer, module::Module, targets::{CodeModel, FileType, InitializationConfig, RelocMode, Target, TargetMachine}, OptimizationLevel, }; use libc::{ c_char, mmap, mprotect, munmap, MAP_ANON, MAP_PRIVATE, PROT_EXEC, PROT_NONE, PROT_R...
{ NONE, READ, READ_WRITE, READ_EXECUTE, } #[allow(non_camel_case_types, dead_code)] #[derive(Debug, Copy, Clone, PartialEq, Eq)] #[repr(C)] enum LLVMResult { OK, ALLOCATE_FAILURE, PROTECT_FAILURE, DEALLOC_FAILURE, OBJECT_LOAD_FAILURE, } #[repr(C)] struct Callbacks { alloc_memo...
MemProtect
identifier_name
backend.rs
use crate::intrinsics::Intrinsics; use inkwell::{ memory_buffer::MemoryBuffer, module::Module, targets::{CodeModel, FileType, InitializationConfig, RelocMode, Target, TargetMachine}, OptimizationLevel, }; use libc::{ c_char, mmap, mprotect, munmap, MAP_ANON, MAP_PRIVATE, PROT_EXEC, PROT_NONE, PROT_R...
let name_slice = unsafe { slice::from_raw_parts(name_ptr as *const u8, length) }; let name = str::from_utf8(name_slice).unwrap(); match name { fn_name!("vm.memory.grow.dynamic.local") => vmcalls::local_dynamic_memory_grow as _, fn_name!("vm.memory.size.dynamic.local") =>...
random_line_split
kernel.rs
use crate::core::kernel::*; use crate::core::program::*; use mesa_rust_util::ptr::*; use mesa_rust_util::string::*; use rusticl_opencl_gen::*; use std::collections::HashSet; use std::os::raw::c_void; use std::ptr; use std::slice; use std::sync::Arc; impl CLInfo<cl_kernel_info> for cl_kernel { fn query(&self, q:...
if arg_value.is_null() { return Err(CL_INVALID_ARG_VALUE); } } _ => {} }; // let's create the arg now let arg = unsafe { if arg.dead { KernelArgValue::None } else { ...
} // If the argument is of type sampler_t, the arg_value entry must be a pointer to the // sampler object. KernelArgType::Constant | KernelArgType::Sampler => {
random_line_split
kernel.rs
use crate::core::kernel::*; use crate::core::program::*; use mesa_rust_util::ptr::*; use mesa_rust_util::string::*; use rusticl_opencl_gen::*; use std::collections::HashSet; use std::os::raw::c_void; use std::ptr; use std::slice; use std::sync::Arc; impl CLInfo<cl_kernel_info> for cl_kernel { fn query(&self, q: ...
( kernel: cl_kernel, arg_index: cl_uint, arg_size: usize, arg_value: *const ::std::os::raw::c_void, ) -> CLResult<()> { let k = kernel.get_arc()?; // CL_INVALID_ARG_INDEX if arg_index is not a valid argument index. if let Some(arg) = k.args.get(arg_index as usize) { // CL_INVALID_AR...
set_kernel_arg
identifier_name
kernel.rs
use crate::core::kernel::*; use crate::core::program::*; use mesa_rust_util::ptr::*; use mesa_rust_util::string::*; use rusticl_opencl_gen::*; use std::collections::HashSet; use std::os::raw::c_void; use std::ptr; use std::slice; use std::sync::Arc; impl CLInfo<cl_kernel_info> for cl_kernel { fn query(&self, q: ...
// kernel_name such as the number of arguments, the argument types are not the same for all // devices for which the program executable has been built. let devs = get_devices_with_valid_build(&p)?; let kernel_args: HashSet<_> = devs.iter().map(|d| p.args(d, &name)).collect(); if kernel_args.len()!= ...
{ let p = program.get_arc()?; let name = c_string_to_string(kernel_name); // CL_INVALID_VALUE if kernel_name is NULL. if kernel_name.is_null() { return Err(CL_INVALID_VALUE); } // CL_INVALID_PROGRAM_EXECUTABLE if there is no successfully built executable for program. if p.kernels()...
identifier_body
kernel.rs
use crate::core::kernel::*; use crate::core::program::*; use mesa_rust_util::ptr::*; use mesa_rust_util::string::*; use rusticl_opencl_gen::*; use std::collections::HashSet; use std::os::raw::c_void; use std::ptr; use std::slice; use std::sync::Arc; impl CLInfo<cl_kernel_info> for cl_kernel { fn query(&self, q: ...
_ => { if arg.size!= arg_size { return Err(CL_INVALID_ARG_SIZE); } } } // CL_INVALID_ARG_VALUE if arg_value specified is not a valid value. match arg.kind { // If the argument is declared with the local qua...
{ if arg_size != std::mem::size_of::<cl_mem>() { return Err(CL_INVALID_ARG_SIZE); } }
conditional_block
view.rs
, &dbopts, )?; { let txn = db.transaction()?; let mut maybe_guesser = if opts.guess_ranges { Some(SegmentRangeGuesser::new(&txn, "")?) } else { None }; let mut tag_editor = |segment_id: i64, tags: &mut json::JsonValue| -> Result<()> { ...
writer.write_fmt(format_args!( "\"{}\",\"~{}:{}-{}\"\n", name,
random_line_split
view.rs
NO_MUTEX, &dbopts, )?; { let txn = db.transaction()?; let mut maybe_guesser = if opts.guess_ranges { Some(SegmentRangeGuesser::new(&txn, "")?) } else { None }; let mut tag_editor = |segment_id: i64, tags: &mut json::JsonValue| -> Result<()...
(db: &rusqlite::Connection, writer: &mut dyn io::Write) -> Result<()> { let tags_json: String = db.query_row( "SELECT tags_json FROM gfa1_header WHERE _rowid_ = 1", [], |row| row.get(0), )?; writer.write(b"H")?; write_tags("gfa1_header", 1, &tags_json, writer)?; writer.write(...
write_header
identifier_name
view.rs
NO_MUTEX, &dbopts, )?; { let txn = db.transaction()?; let mut maybe_guesser = if opts.guess_ranges { Some(SegmentRangeGuesser::new(&txn, "")?) } else { None }; let mut tag_editor = |segment_id: i64, tags: &mut json::JsonValue| -> Result<()...
if!gfa_filename.ends_with(".gfa") { warn!("output filename should end with.gfa") } Ok(Box::new(io::BufWriter::new(fs::File::create( gfa_filename, )?))) } /// Start `less -S` and call `write` with its standard input pipe. /// Tolerate BrokenPipe errors (user exited before viewing all da...
{ return Ok(Box::new(io::BufWriter::new(io::stdout()))); }
conditional_block
main.rs
use std::fs::File; use std::io::Write; use std::str; use std::collections::HashMap; use std::mem; use std::fmt; use std::thread; use std::sync::mpsc; use std::sync::{Mutex, Arc}; use std::time::Duration; use std::io::Read; use std::collections::HashSet; extern crate bio; extern crate clap; extern crate flate2; extern...
(seq: &[u8]) -> Result<u64, &str> { let mut res: u64 = 0; let mut res_rc: u64 = 0; let end = seq.len() - 1; for i in 0..seq.len() { if i >= 32 { return Err("Seq can't longer than 32.") } let m = SEQ_NT4_TABLE[seq[i] as usize]; res |= m << i*2; res_rc |...
compress_seq
identifier_name
main.rs
use std::fs::File; use std::io::Write; use std::str; use std::collections::HashMap; use std::mem; use std::fmt; use std::thread; use std::sync::mpsc; use std::sync::{Mutex, Arc}; use std::time::Duration; use std::io::Read; use std::collections::HashSet; extern crate bio; extern crate clap; extern crate flate2; extern...
for (k0, k1, v) in kv_vec { let _ = writeln!(cnt_file, "{}\t{}\t{}", k0, k1, v); } info!("Write sequences to fastq file: {}", fq_out_path); let mut key_vec = key_set.into_iter().collect::<Vec<u64>>(); key_vec.sort(); for k in key_vec { let seq = recover_seq(k, flanking); ...
random_line_split
network.rs
Vec<Option<Crossroad>>> { type Output = Option<Crossroad>; #[inline] fn index(&self, index: CrossroadId) -> &Option<Crossroad> { &self[index.y][index.x] } } /// Allows mutable indexing of the grid by the crossroad coordinates. impl IndexMut<CrossroadId> for Vec<Vec<Option<Crossroad>>> { #[...
else { '-' }; let (x, y) = (2*start.x, 2*start.y); for k in 1..(2*length) { char_map[(y as i32 + k * dy) as usize][(x as i32 + k * dx) as usize] = c; } } // We collect the characters into a string. char_map.into_iter().map(|line| { line.into...
{ '|' }
conditional_block
network.rs
{ pub x: usize, // Abscissa pub y: usize, // Ordinate } use std::ops::{ Index, IndexMut }; /// Allows indexing the grid by the crossroad coordinates. impl Index<CrossroadId> for Vec<Vec<Option<Crossroad>>> { type Output = Option<Crossroad>; #[inline] fn index(&self, index: CrossroadId) -> &O...
CrossroadId
identifier_name
network.rs
// with specified destination crossroad. STEP(i32), // The car performs a step of specified length. VANISH, // The car vanished. CROSS(RoadInfo), // The car crossed and is now on s...
pub enum Move { NONE, // None happened. SPAWN(RoadInfo, usize, CrossroadId), // The car has spawned at specified road, position,
random_line_split
network.rs
Vec<Option<Crossroad>>> { type Output = Option<Crossroad>; #[inline] fn index(&self, index: CrossroadId) -> &Option<Crossroad> { &self[index.y][index.x] } } /// Allows mutable indexing of the grid by the crossroad coordinates. impl IndexMut<CrossroadId> for Vec<Vec<Option<Crossroad>>> { #[...
self.crossroad_mut(src).roads[d1][side] = Some(id); self.crossroad_mut(dest).roads_arriving[d1][side] = Some(id); // Then, it builds the two corresponding edges in the graph. let (n1, n2) = { let c = self.crossroad(src); (c.nodes[d1], c.nodes[previous_direction(d...
{ // We get the parameters of the road. let (dx, dy, length) = src.join(dest); let length = length * self.cars_per_unit - self.cars_per_crossroad; let (d1, d2) = compute_directions(dx, dy, side); let id = self.roads.len(); // First, it builds the road in the network. ...
identifier_body
lib.rs
//! A high-level API for programmatically interacting with web pages //! through WebDriver. //! //! [WebDriver protocol]: https://www.w3.org/TR/webdriver/ //! [CSS selectors]: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors //! [powerful]: https://developer.mozilla.org/en-US/docs/Web/CSS/Pseudo-classes /...
( &self, locator: Locator, root: Option<WebElement>, ) -> Result<WebElement> { let cmd = match root { Option::None => WebDriverCommand::FindElement(locator.into()), Option::Some(elt) => { WebDriverCommand::FindElementElement(elt, locator.into()...
find
identifier_name
lib.rs
//! A high-level API for programmatically interacting with web pages //! through WebDriver. //! //! [WebDriver protocol]: https://www.w3.org/TR/webdriver/ //! [CSS selectors]: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors //! [powerful]: https://developer.mozilla.org/en-US/docs/Web/CSS/Pseudo-classes /...
/// Wait for the specified element(s) to appear on the page pub async fn $name( &self, search: Locator, root: Option<WebElement> ) -> Result<$return_typ> { loop { match self.$search_fn(search.clone(), root.clone()).await { ...
($name:ident, $search_fn:ident, $return_typ:ty) => {
random_line_split
lib.rs
//! A high-level API for programmatically interacting with web pages //! through WebDriver. //! //! [WebDriver protocol]: https://www.w3.org/TR/webdriver/ //! [CSS selectors]: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors //! [powerful]: https://developer.mozilla.org/en-US/docs/Web/CSS/Pseudo-classes /...
/// Set the `value` of the input element named `name` which is a child of `eid` pub async fn set_by_name( &self, eid: WebElement, name: String, value: String, ) -> Result<()> { let locator = Locator::Css(format!("input[name='{}']", name)); let elt = self.clo...
{ match self.clone().attr(eid.clone(), String::from("href")).await? { None => bail!("no href attribute"), Some(href) => { let current = self.current_url().await?.join(&href)?; self.goto(current.as_str()).await } } }
identifier_body
lib.rs
//! Brainfuck interpreter types //! //! This crate contains all the data types necessary for the Brainfuck //! interpreter project. #![deny(missing_docs)] use std::fmt; use std::io; use std::path::{Path, PathBuf}; use thiserror::Error; /// Represents a Brainfuck Types Error. #[derive(Error, fmt::Debug)] pub enum Br...
(s: &str) -> Vec<Self> { let mut instrs: Vec<BrainfuckInstr> = Vec::new(); for (l, pline) in s.lines().enumerate() { for (c, pbyte) in pline.bytes().enumerate() { if let Some(iraw) = BrainfuckInstrRaw::from_byte(pbyte) { instrs.push(BrainfuckInstr { ...
instrs_from_str
identifier_name
lib.rs
//! Brainfuck interpreter types //! //! This crate contains all the data types necessary for the Brainfuck //! interpreter project. #![deny(missing_docs)]
use thiserror::Error; /// Represents a Brainfuck Types Error. #[derive(Error, fmt::Debug)] pub enum BrainfuckTypesError { /// When an unmatched left or right bracket is found #[error("unmatched bracket, {0:?}")] UnmatchedBracket(BrainfuckInstr), } /// Represents the eight raw Brainfuck instructions. #[de...
use std::fmt; use std::io; use std::path::{Path, PathBuf};
random_line_split
sse_server.rs
//! Server-sent-event server for the note viewer feature. //! This module contains also the web browser Javascript client code. use crate::config::CFG; use crate::config::VIEWER_SERVED_MIME_TYPES_MAP; use crate::viewer::error::ViewerError; use crate::viewer::http_response::HttpResponse; use crate::viewer::init::LOCALH...
{ /// Receiver side of the channel where `update` events are sent. rx: Receiver<SseToken>, /// Byte stream coming from a TCP connection. pub(crate) stream: TcpStream, /// A list of referenced relative URLs to images or other /// documents as they appear in the delivered Tp-Note documents. /...
ServerThread
identifier_name
sse_server.rs
//! Server-sent-event server for the note viewer feature. //! This module contains also the web browser Javascript client code. use crate::config::CFG; use crate::config::VIEWER_SERVED_MIME_TYPES_MAP; use crate::viewer::error::ViewerError; use crate::viewer::http_response::HttpResponse; use crate::viewer::init::LOCALH...
'tcp_connection: loop { // This is inspired by the Spook crate. // Read the request. let mut read_buffer = [0u8; TCP_READ_BUFFER_SIZE]; let mut buffer = Vec::new(); let (method, path) = 'assemble_tcp_chunks: loop { // Read the request, ...
{ // One reference is hold by the `manage_connections` thread and does not count. // This is why we subtract 1. let open_connections = Arc::<()>::strong_count(&self.conn_counter) - 1; log::trace!( "TCP port local {} to peer {}: New incoming TCP connection ({} open).", ...
identifier_body
sse_server.rs
//! Server-sent-event server for the note viewer feature. //! This module contains also the web browser Javascript client code. use crate::config::CFG; use crate::config::VIEWER_SERVED_MIME_TYPES_MAP; use crate::viewer::error::ViewerError; use crate::viewer::http_response::HttpResponse; use crate::viewer::init::LOCALH...
pub enum SseToken { /// Server-Sent-Event token to request nothing but check if the client is still /// there. Ping, /// Server-Sent-Event token to request a page update. Update, } pub fn manage_connections( event_tx_list: Arc<Mutex<Vec<SyncSender<SseToken>>>>, listener: TcpListener, do...
/// Server-Sent-Event tokens our HTTP client has registered to receive. #[derive(Debug, Clone, Copy)]
random_line_split
inner_product_proof.rs
#![allow(non_snake_case)] #![doc(include = "../docs/inner-product-protocol.md")] use std::borrow::Borrow; use std::iter; use curve25519_dalek::ristretto::RistrettoPoint; use curve25519_dalek::scalar::Scalar; use curve25519_dalek::traits::VartimeMultiscalarMul; use proof_transcript::ProofTranscript; #[derive(Serial...
} } /// Computes an inner product of two vectors /// \\[ /// {\langle {\mathbf{a}}, {\mathbf{b}} \rangle} = \sum\_{i=0}^{n-1} a\_i \cdot b\_i. /// \\] /// Panics if the lengths of \\(\mathbf{a}\\) and \\(\mathbf{b}\\) are not equal. pub fn inner_product(a: &[Scalar], b: &[Scalar]) -> Scalar { let mut out =...
{ Err(()) }
conditional_block
inner_product_proof.rs
#![allow(non_snake_case)] #![doc(include = "../docs/inner-product-protocol.md")] use std::borrow::Borrow; use std::iter; use curve25519_dalek::ristretto::RistrettoPoint; use curve25519_dalek::scalar::Scalar; use curve25519_dalek::traits::VartimeMultiscalarMul; use proof_transcript::ProofTranscript; #[derive(Serial...
( &self, transcript: &mut ProofTranscript, ) -> (Vec<Scalar>, Vec<Scalar>, Vec<Scalar>) { let lg_n = self.L_vec.len(); let n = 1 << lg_n; // 1. Recompute x_k,...,x_1 based on the proof transcript let mut challenges = Vec::with_capacity(lg_n); for (L, R) in s...
verification_scalars
identifier_name
inner_product_proof.rs
#![allow(non_snake_case)] #![doc(include = "../docs/inner-product-protocol.md")] use std::borrow::Borrow; use std::iter; use curve25519_dalek::ristretto::RistrettoPoint; use curve25519_dalek::scalar::Scalar; use curve25519_dalek::traits::VartimeMultiscalarMul; use proof_transcript::ProofTranscript; #[derive(Serial...
// where b' = b \circ y^(-n) let b_prime = b.iter().zip(util::exp_iter(y_inv)).map(|(bi, yi)| bi * yi); // a.iter() has Item=&Scalar, need Item=Scalar to chain with b_prime let a_prime = a.iter().cloned(); let P = RistrettoPoint::vartime_multiscalar_mul( a_prime.chai...
// P would be determined upstream, but we need a correct P to check the proof. // // To generate P = <a,G> + <b,H'> + <a,b> Q, compute // P = <a,G> + <b',H> + <a,b> Q,
random_line_split
main.rs
#[macro_use] extern crate errln; #[macro_use] extern crate error_chain; extern crate clap; extern crate hex; extern crate lalrpop_util; extern crate parser_haskell; extern crate regex; extern crate tempdir; extern crate walkdir; extern crate corollary; extern crate inflector; use parser_haskell::util::{print_parse_err...
match parser_haskell::parse(&mut errors, &contents) { Ok(v) => { // errln!("{:?}", v); if dump_ast { println!("{}", format!("{:#?}", v).replace(" ", " ")); } else { writeln!(file_out, "// Original file: {:?}", p.file_name().unwrap())?;...
{ let mut contents = input.to_string(); let mut file_out = String::new(); let mut rust_out = String::new(); // Parse out HASKELL /HASKELL RUST /RUST sections. let re = Regex::new(r#"HASKELL[\s\S]*?/HASKELL"#).unwrap(); contents = re.replace(&contents, "").to_string(); let re = Regex::new(r#...
identifier_body
main.rs
#[macro_use] extern crate errln; #[macro_use] extern crate error_chain; extern crate clap; extern crate hex; extern crate lalrpop_util; extern crate parser_haskell; extern crate regex; extern crate tempdir; extern crate walkdir; extern crate corollary; extern crate inflector; use parser_haskell::util::{print_parse_err...
} // Starting message. if arg_run { errln!("running {:?}...", arg_input); } else { errln!("cross-compiling {:?}...", arg_input); } // Read file contents. let mut file = File::open(arg_input) .chain_err(|| format!("Could not open {:?}", arg_input))?; let mut conte...
} if (arg_run || arg_out.is_some()) && arg_ast { bail!("Cannot use --ast and (--run or --out) at the same time.");
random_line_split
main.rs
#[macro_use] extern crate errln; #[macro_use] extern crate error_chain; extern crate clap; extern crate hex; extern crate lalrpop_util; extern crate parser_haskell; extern crate regex; extern crate tempdir; extern crate walkdir; extern crate corollary; extern crate inflector; use parser_haskell::util::{print_parse_err...
(input: &str, p: &Path, inline_mod: bool, dump_ast: bool) -> Result<(String, String)> { let mut contents = input.to_string(); let mut file_out = String::new(); let mut rust_out = String::new(); // Parse out HASKELL /HASKELL RUST /RUST sections. let re = Regex::new(r#"HASKELL[\s\S]*?/HASKELL"#).unwr...
convert_file
identifier_name
main.rs
#[macro_use] extern crate errln; #[macro_use] extern crate error_chain; extern crate clap; extern crate hex; extern crate lalrpop_util; extern crate parser_haskell; extern crate regex; extern crate tempdir; extern crate walkdir; extern crate corollary; extern crate inflector; use parser_haskell::util::{print_parse_err...
else { writeln!(file_out, "#[macro_use] use corollary_support::*;")?; writeln!(file_out, "")?; let state = PrintState::new(); writeln!(file_out, "{}", print_item_list(state, &v.items, true))?; } } } ...
{ writeln!(file_out, "pub mod {} {{", v.name.0.replace(".", "_"))?; writeln!(file_out, " use haskell_support::*;")?; writeln!(file_out, "")?; let state = PrintState::new(); writeln!(file_out, "{}", print_item_list(sta...
conditional_block
exec.rs
use re_builder::RegexOptions; use re_set; use re_trait::{RegularExpression, Slot, Locations, as_slots}; use re_unicode; use utf8::next_utf8; /// `Exec` manages the execution of a regular expression. /// /// In particular, this manages the various compiled forms of a single regular /// expression and the choice of whi...
/// /// This overrides whatever was previously set via the `nfa` or /// `bounded_backtracking` methods. pub fn automatic(mut self) -> Self { self.match_type = None; self } /// Sets the matching engine to use the NFA algorithm no matter what /// optimizations are possible. ...
random_line_split
exec.rs
use re_builder::RegexOptions; use re_set; use re_trait::{RegularExpression, Slot, Locations, as_slots}; use re_unicode; use utf8::next_utf8; /// `Exec` manages the execution of a regular expression. /// /// In particular, this manages the various compiled forms of a single regular /// expression and the choice of whic...
<'c>(ExecNoSync<'c>); /// `ExecReadOnly` comprises all read only state for a regex. Namely, all such /// state is determined at compile time and never changes during search. #[derive(Debug)] struct ExecReadOnly { /// The original regular expressions given by the caller to compile. res: Vec<String>, /// A c...
ExecNoSyncStr
identifier_name
exec.rs
use re_builder::RegexOptions; use re_set; use re_trait::{RegularExpression, Slot, Locations, as_slots}; use re_unicode; use utf8::next_utf8; /// `Exec` manages the execution of a regular expression. /// /// In particular, this manages the various compiled forms of a single regular /// expression and the choice of whic...
#[inline(always)] // reduces constant overhead fn is_match_at(&self, text: &str, start: usize) -> bool { self.0.is_match_at(text.as_bytes(), start) } #[inline(always)] // reduces constant overhead fn find_at(&self, text: &str, start: usize) -> Option<(usize, usize)> { self.0.find_...
{ self.0.shortest_match_at(text.as_bytes(), start) }
identifier_body
blob_store.rs
// Copyright 2014 Google Inc. All rights reserved. // // 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...
for &(ref id, chunk) in ids.iter() { if chunk.len() > 0 { match backend.retrieve(id.name.as_slice()) { Ok(_) => (), Err(e) => fail!(e), } } } // All chunks must be available through the blob store: for &(ref id, chunk) in ids.iter() { ...
{ fn prop(chunks: Vec<Vec<u8>>) -> bool { let mut backend = MemoryBackend::new(); let local_backend = backend.clone(); let bsP: BlobStoreProcess<MemoryBackend> = Process::new(proc() { BlobStore::new_for_testing(local_backend, 1024) }); let mut ids = Vec::new(); for chunk in c...
identifier_body
blob_store.rs
// Copyright 2014 Google Inc. All rights reserved. // // 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...
() -> blob_index::BlobDesc { blob_index::BlobDesc{name: b"".into_vec(), id: 0} } impl <B: BlobStoreBackend> BlobStore<B> { pub fn new(index: BlobIndexProcess, backend: B, max_blob_size: uint) -> BlobStore<B> { let mut bs = BlobStore{ backend: backend, blob_index: index, blob_de...
empty_blob_desc
identifier_name
blob_store.rs
// Copyright 2014 Google Inc. All rights reserved. // // 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...
}, None => break, } } self.blob_index.send_reply(blob_index::InAir(old_blob_desc.clone())); self.backend_store(old_blob_desc.name.as_slice(), blob.as_slice()); self.blob_index.send_reply(blob_index::CommitDone(old_blob_desc)); // Go through callbacks for (blobid, cb) in r...
blob.push_all(chunk.as_slice());
random_line_split
mod.rs
#![warn(missing_docs)] //! Contains all data structures and method to work with model resources. //! //! Model is an isolated scene that is used to create copies of its data - this //! process is known as `instantiation`. Isolation in this context means that //! such scene cannot be modified, rendered, etc. It just a ...
/// A set of options that will be applied to a model resource when loading it from external source. /// /// # Details /// /// The engine has a convenient way of storing import options in a `.options` files. For example you may /// have a `foo.fbx` 3d model, to change import options create a new file with additional `.o...
Self::MaterialsDirectory(path.as_ref().to_path_buf()) } }
random_line_split
mod.rs
#![warn(missing_docs)] //! Contains all data structures and method to work with model resources. //! //! Model is an isolated scene that is used to create copies of its data - this //! process is known as `instantiation`. Isolation in this context means that //! such scene cannot be modified, rendered, etc. It just a ...
ModelLoadError::NotSupported(v) => { write!(f, "Model format is not supported: {v}") } ModelLoadError::Fbx(v) => v.fmt(f), } } } impl From<FbxError> for ModelLoadError { fn from(fbx: FbxError) -> Self { ModelLoadError::Fbx(fbx) } } impl ...
{ write!(f, "An error occurred while reading a data source {v:?}") }
conditional_block
mod.rs
#![warn(missing_docs)] //! Contains all data structures and method to work with model resources. //! //! Model is an isolated scene that is used to create copies of its data - this //! process is known as `instantiation`. Isolation in this context means that //! such scene cannot be modified, rendered, etc. It just a ...
} impl Model { pub(crate) async fn load<P: AsRef<Path>>( path: P, serialization_context: Arc<SerializationContext>, resource_manager: ResourceManager, model_import_options: ModelImportOptions, ) -> Result<Self, ModelLoadError> { let extension = path .as_ref()...
{ ModelLoadError::Visit(e) }
identifier_body
mod.rs
#![warn(missing_docs)] //! Contains all data structures and method to work with model resources. //! //! Model is an isolated scene that is used to create copies of its data - this //! process is known as `instantiation`. Isolation in this context means that //! such scene cannot be modified, rendered, etc. It just a ...
{ pub(crate) path: PathBuf, #[visit(skip)] pub(crate) mapping: NodeMapping, #[visit(skip)] scene: Scene, } impl TypeUuidProvider for Model { fn type_uuid() -> Uuid { MODEL_RESOURCE_UUID } } /// Type alias for model resources. pub type ModelResource = Resource<Model>; /// Extensio...
Model
identifier_name
io.rs
//! Persistent storage backend for blocks. use std::collections::VecDeque; use std::fs; use std::io::{self, Read, Seek, Write}; use std::iter; use std::mem; use std::path::Path; use nakamoto_common::bitcoin::consensus::encode::{Decodable, Encodable}; use nakamoto_common::block::store::{Error, Store}; use nakamoto_com...
Err(err) => return Err(err.into()), } self.index += buf.len() as u64; let items = buf.len() / size; let mut cursor = io::Cursor::new(buf); let mut item = vec![0; size]; for _ in 0..items { cursor.read_exact(&mut i...
{ self.file.seek(io::SeekFrom::Start(from))?; let n = self.file.read_to_end(&mut buf)?; buf.truncate(n); }
conditional_block
io.rs
//! Persistent storage backend for blocks. use std::collections::VecDeque; use std::fs; use std::io::{self, Read, Seek, Write}; use std::iter; use std::mem; use std::path::Path; use nakamoto_common::bitcoin::consensus::encode::{Decodable, Encodable}; use nakamoto_common::block::store::{Error, Store}; use nakamoto_com...
} } Ok(self.queue.pop_front()) } } /// An iterator over block headers in a file. #[derive(Debug)] pub struct Iter<H> { height: Height, file: FileReader<H>, } impl<H: Decodable> Iter<H> { fn new(file: fs::File) -> Self { Self { file: FileReader::new(file)...
for _ in 0..items { cursor.read_exact(&mut item)?; let item = H::consensus_decode(&mut item.as_slice())?; self.queue.push_back(item);
random_line_split
io.rs
//! Persistent storage backend for blocks. use std::collections::VecDeque; use std::fs; use std::io::{self, Read, Seek, Write}; use std::iter; use std::mem; use std::path::Path; use nakamoto_common::bitcoin::consensus::encode::{Decodable, Encodable}; use nakamoto_common::block::store::{Error, Store}; use nakamoto_com...
(&mut self) -> Option<Self::Item> { let height = self.height; assert!(height > 0); match self.file.next() { // If we hit this branch, it's because we're trying to read passed the end // of the file, which means there are no further headers remaining. Err(Err...
next
identifier_name
yuva_info.rs
use super::image_info; use crate::{prelude::*, EncodedOrigin, ISize, Matrix}; use skia_bindings::{self as sb, SkYUVAInfo, SkYUVAInfo_Subsampling}; use std::{fmt, ptr}; /// Specifies the structure of planes for a YUV image with optional alpha. The actual planar data /// is not part of this structure and depending on us...
(&self, plane_index: usize) -> (i32, i32) { plane_subsampling_factors(self.plane_config(), self.subsampling(), plane_index) } /// Dimensions of the full resolution image (after planes have been oriented to how the image /// is displayed as indicated by fOrigin). pub fn dimensions(&self) -> ISiz...
plane_subsampling_factors
identifier_name
yuva_info.rs
use super::image_info; use crate::{prelude::*, EncodedOrigin, ISize, Matrix}; use skia_bindings::{self as sb, SkYUVAInfo, SkYUVAInfo_Subsampling}; use std::{fmt, ptr}; /// Specifies the structure of planes for a YUV image with optional alpha. The actual planar data /// is not part of this structure and depending on us...
/// Number of Y, U, V, A channels in the ith plane for a given [PlaneConfig] (or [None] if i is /// invalid). pub fn num_channels_in_plane(config: PlaneConfig, i: usize) -> Option<usize> { (i < num_planes(config)).if_true_then_some(|| { unsafe { sb::C_SkYUVAInfo_NumChannelsInPlane(config, i.try_into().unw...
{ unsafe { sb::C_SkYUVAInfo_NumPlanes(config) } .try_into() .unwrap() }
identifier_body
yuva_info.rs
use super::image_info; use crate::{prelude::*, EncodedOrigin, ISize, Matrix}; use skia_bindings::{self as sb, SkYUVAInfo, SkYUVAInfo_Subsampling}; use std::{fmt, ptr}; /// Specifies the structure of planes for a YUV image with optional alpha. The actual planar data /// is not part of this structure and depending on us...
pub fn has_alpha(&self) -> bool { has_alpha(self.plane_config()) } /// Returns the dimensions for each plane. Dimensions are as stored in memory, before /// transformation to image display space as indicated by [origin(&self)]. pub fn plane_dimensions(&self) -> Vec<ISize> { self::pl...
random_line_split
weapon.rs
use std::{ path::Path, sync::{Arc, Mutex}, }; use crate::{ projectile::{ Projectile, ProjectileKind, }, actor::Actor, HandleFromSelf, GameTime, level::CleanUp, }; use rg3d::{ physics::{RayCastOptions, Physics}, sound::{ source::Source, buffer::Buff...
(&self) -> PoolIterator<Weapon> { self.pool.iter() } pub fn iter_mut(&mut self) -> PoolIteratorMut<Weapon> { self.pool.iter_mut() } pub fn get(&self, handle: Handle<Weapon>) -> &Weapon { self.pool.borrow(handle) } pub fn get_mut(&mut self, handle: Handle<Weapon>) -> &m...
iter
identifier_name
weapon.rs
use std::{ path::Path, sync::{Arc, Mutex}, }; use crate::{ projectile::{ Projectile, ProjectileKind, }, actor::Actor, HandleFromSelf, GameTime, level::CleanUp, }; use rg3d::{ physics::{RayCastOptions, Physics}, sound::{ source::Source, buffer::Buff...
Some(Projectile::new(ProjectileKind::Plasma, resource_manager, scene, dir, pos, self.self_handle, weapon_velocity)) } } } else { None } } } impl CleanUp for Weapon { fn clean_up(&mut self, scen...
{ if self.ammo != 0 && time.elapsed - self.last_shot_time >= 0.1 { self.ammo -= 1; self.offset = Vec3::new(0.0, 0.0, -0.05); self.last_shot_time = time.elapsed; self.play_shot_sound(resource_manager, sound_context); let (dir, pos) = { ...
identifier_body
weapon.rs
use std::{ path::Path, sync::{Arc, Mutex}, }; use crate::{ projectile::{ Projectile, ProjectileKind, }, actor::Actor, HandleFromSelf, GameTime, level::CleanUp, }; use rg3d::{ physics::{RayCastOptions, Physics}, sound::{ source::Source, buffer::Buff...
} impl Visit for WeaponContainer { fn visit(&mut self, name: &str, visitor: &mut Visitor) -> VisitResult { visitor.enter_region(name)?; self.pool.visit("Pool", visitor)?; visitor.leave_region() } }
weapon.update(scene) } }
random_line_split
weapon.rs
use std::{ path::Path, sync::{Arc, Mutex}, }; use crate::{ projectile::{ Projectile, ProjectileKind, }, actor::Actor, HandleFromSelf, GameTime, level::CleanUp, }; use rg3d::{ physics::{RayCastOptions, Physics}, sound::{ source::Source, buffer::Buff...
WeaponKind::PlasmaRifle => { Some(Projectile::new(ProjectileKind::Plasma, resource_manager, scene, dir, pos, self.self_handle, weapon_velocity)) } } } else { None } } } impl CleanUp...
{ Some(Projectile::new(ProjectileKind::Bullet, resource_manager, scene, dir, pos, self.self_handle, weapon_velocity)) }
conditional_block
package.rs
//! An interpreter for the rust-installer package format. Responsible //! for installing from a directory or tarball to an installation //! prefix, represented by a `Components` instance. use crate::dist::component::components::*; use crate::dist::component::transaction::*; use crate::dist::temp; use crate::errors::...
pub fn handle(&mut self, unpacked: tar::Unpacked) { if let tar::Unpacked::File(f) = unpacked { self.n_files.fetch_add(1, Ordering::Relaxed); let n_files = self.n_files.clone(); self.pool.execute(move || { drop(f); ...
{ // Defaults to hardware thread count threads; this is suitable for // our needs as IO bound operations tend to show up as write latencies // rather than close latencies, so we don't need to look at // more threads to get more IO dispatched at this stage in the process. ...
identifier_body
package.rs
//! An interpreter for the rust-installer package format. Responsible //! for installing from a directory or tarball to an installation //! prefix, represented by a `Components` instance. use crate::dist::component::components::*; use crate::dist::component::transaction::*; use crate::dist::temp; use crate::errors::...
<'a> { n_files: Arc<AtomicUsize>, pool: threadpool::ThreadPool, notify_handler: Option<&'a dyn Fn(Notification<'_>)>, } impl<'a> Unpacker<'a> { pub fn new(notify_handler: Option<&'a dyn Fn(Notification<'_>)>) -> Self { // Defaults to hardware thread count threads; th...
Unpacker
identifier_name
package.rs
//! An interpreter for the rust-installer package format. Responsible //! for installing from a directory or tarball to an installation //! prefix, represented by a `Components` instance. use crate::dist::component::components::*; use crate::dist::component::transaction::*; use crate::dist::temp; use crate::errors::...
handler(Notification::DownloadContentLengthReceived( prev_files as u64, )) }); if prev_files > 50 { println!("Closing {} deferred file handles", prev_files); } let buf: Vec<u8> = vec![0; prev_files]; ...
let mut prev_files = self.n_files.load(Ordering::Relaxed); self.notify_handler.map(|handler| {
random_line_split
package.rs
//! An interpreter for the rust-installer package format. Responsible //! for installing from a directory or tarball to an installation //! prefix, represented by a `Components` instance. use crate::dist::component::components::*; use crate::dist::component::transaction::*; use crate::dist::temp; use crate::errors::...
else { 0o644 }); fs::set_permissions(dest_path, perm) .chain_err(|| ErrorKind::ComponentFilePermissionsFailed)?; } Ok(()) } #[cfg(windows)] fn set_file_perms(_dest_path: &Path, _src_path: &Path) -> Result<()> { Ok(()) } #[derive(Debug)] pub struct TarPackage<'a>(Di...
{ 0o755 }
conditional_block
config.rs
use crate::utility::location::Location; use crate::exit_on_bad_config; use origen_metal::{config, scrub_path}; use origen_metal::config::{Environment, File}; use std::collections::HashMap; use std::path::{Path, PathBuf}; use crate::om::glob::glob; use std::process::exit; use super::target; const PUBLISHER_OPTIONS: &[&...
pub fn cmd_paths(&self) -> Vec<PathBuf> { let mut retn = vec!(); if let Some(cmds) = self.commands.as_ref() { // Load in only the commands explicitly given for cmds_toml in cmds { let ct = self.root.as_ref().unwrap().join("config").join(cmds_toml); ...
{ let mut unknowns: Vec<String> = vec![]; if let Some(p) = &self.publisher { for (opt, _) in p.iter() { if !PUBLISHER_OPTIONS.contains(&opt.as_str()) { unknowns.push(opt.clone()); } } } unknowns }
identifier_body
config.rs
use crate::utility::location::Location; use crate::exit_on_bad_config; use origen_metal::{config, scrub_path}; use origen_metal::config::{Environment, File}; use std::collections::HashMap; use std::path::{Path, PathBuf}; use crate::om::glob::glob; use std::process::exit; use super::target; const PUBLISHER_OPTIONS: &[&...
{ pub target: Option<Vec<String>> } impl CurrentState { pub fn build(root: &PathBuf) -> Self { let file = root.join(".origen").join("application.toml"); let mut s = config::Config::builder().set_default("target", None::<Vec<String>>).unwrap(); if file.exists() { s = s.add_s...
CurrentState
identifier_name
config.rs
use crate::utility::location::Location; use crate::exit_on_bad_config; use origen_metal::{config, scrub_path}; use origen_metal::config::{Environment, File}; use std::collections::HashMap; use std::path::{Path, PathBuf}; use crate::om::glob::glob; use std::process::exit; use super::target; const PUBLISHER_OPTIONS: &[&...
} } if use_app_config!() { let file = root.join("config").join("application.toml"); if file.exists() { files.push(file); } } else { // Bypass Origen's default configuration lookup - use only the enumerated conf...
{ log_error!( "Config path {} either does not exists or is not accessible", path.display() ); exit(1); }
conditional_block
config.rs
use crate::utility::location::Location; use crate::exit_on_bad_config; use origen_metal::{config, scrub_path}; use origen_metal::config::{Environment, File}; use std::collections::HashMap; use std::path::{Path, PathBuf}; use crate::om::glob::glob; use std::process::exit; use super::target; const PUBLISHER_OPTIONS: &[&...
let mut slf = Self::build(config.root.as_ref().unwrap()); slf.apply_to(config); } } } #[derive(Debug, Deserialize)] // If you add an attribute to this you must also update: // * pyapi/src/lib.rs to convert it to Python // * default function below to define the default value // * add...
} } pub fn build_and_apply(config: &mut Config) { if use_app_config!() {
random_line_split
beacon_chain_builder.rs
use crate::{BeaconChain, BeaconChainTypes}; use eth2_hashing::hash; use lighthouse_bootstrap::Bootstrapper; use merkle_proof::MerkleTree; use rayon::prelude::*; use slog::Logger; use ssz::{Decode, Encode}; use state_processing::initialize_beacon_state_from_eth1; use std::fs::File; use std::io::prelude::*; use std::path...
let (_, mut proof) = tree.generate_proof(i, depth); proof.push(Hash256::from_slice(&int_to_bytes32(i + 1))); assert_eq!( proof.len(), depth + 1, "Deposit proof should be correct len" ); proofs.push(proof); } let deposits = datas ...
{ return Err(String::from("Failed to push leaf")); }
conditional_block
beacon_chain_builder.rs
use crate::{BeaconChain, BeaconChainTypes}; use eth2_hashing::hash; use lighthouse_bootstrap::Bootstrapper; use merkle_proof::MerkleTree; use rayon::prelude::*; use slog::Logger; use ssz::{Decode, Encode}; use state_processing::initialize_beacon_state_from_eth1; use std::fs::File; use std::io::prelude::*; use std::path...
let creds = v.withdrawal_credentials.as_bytes(); assert_eq!( creds[0], spec.bls_withdrawal_prefix_byte, "first byte of withdrawal creds should be bls prefix" ); assert_eq!( &creds[1..], &hash(&v.pubkey.as_ssz...
"validator balances should be max effective balance" ); } for v in &state.validators {
random_line_split
beacon_chain_builder.rs
use crate::{BeaconChain, BeaconChainTypes}; use eth2_hashing::hash; use lighthouse_bootstrap::Bootstrapper; use merkle_proof::MerkleTree; use rayon::prelude::*; use slog::Logger; use ssz::{Decode, Encode}; use state_processing::initialize_beacon_state_from_eth1; use std::fs::File; use std::io::prelude::*; use std::path...
(file: &PathBuf, spec: ChainSpec, log: Logger) -> Result<Self, String> { let mut file = File::open(file.clone()) .map_err(|e| format!("Unable to open SSZ genesis state file {:?}: {:?}", file, e))?; let mut bytes = vec![]; file.read_to_end(&mut bytes) .map_err(|e| format!("...
ssz_state
identifier_name
beacon_chain_builder.rs
use crate::{BeaconChain, BeaconChainTypes}; use eth2_hashing::hash; use lighthouse_bootstrap::Bootstrapper; use merkle_proof::MerkleTree; use rayon::prelude::*; use slog::Logger; use ssz::{Decode, Encode}; use state_processing::initialize_beacon_state_from_eth1; use std::fs::File; use std::io::prelude::*; use std::path...
pub fn http_bootstrap(server: &str, spec: ChainSpec, log: Logger) -> Result<Self, String> { let bootstrapper = Bootstrapper::connect(server.to_string(), &log) .map_err(|e| format!("Failed to initialize bootstrap client: {}", e))?; let (genesis_state, genesis_block) = bootstrapper ...
{ let file = File::open(file.clone()) .map_err(|e| format!("Unable to open JSON genesis state file {:?}: {:?}", file, e))?; let genesis_state = serde_json::from_reader(file) .map_err(|e| format!("Unable to parse JSON genesis state file: {:?}", e))?; Ok(Self::from_genesi...
identifier_body
networking.rs
use std::io::{Read, Write, Result, BufRead, BufReader, BufWriter}; use std::fs::File; use std::net::{TcpListener, TcpStream}; use std::mem::size_of; use std::sync::Arc; use std::sync::mpsc::{Sender, Receiver, channel}; use std::thread; use std::thread::sleep_ms; use byteorder::{LittleEndian, ReadBytesExt, WriteBytesEx...
{ pub graph: u64, // graph identifier pub channel: u64, // index of channel pub source: u64, // index of worker sending message pub target: u64, // index of worker receiving message pub length: u64, // number of bytes in message } impl MessageHeader { // returns a...
MessageHeader
identifier_name
networking.rs
use std::io::{Read, Write, Result, BufRead, BufReader, BufWriter}; use std::fs::File; use std::net::{TcpListener, TcpStream}; use std::mem::size_of; use std::sync::Arc; use std::sync::mpsc::{Sender, Receiver, channel}; use std::thread; use std::thread::sleep_ms; use byteorder::{LittleEndian, ReadBytesExt, WriteBytesEx...
// we'll need more space / to read more at once. let's double the buffer! if self.length >= self.buffer.len() / 2 { self.buffer.extend(::std::iter::repeat(0u8).take(self.length)); } // attempt to read some more bytes into our buffer let read =...
random_line_split
networking.rs
use std::io::{Read, Write, Result, BufRead, BufReader, BufWriter}; use std::fs::File; use std::net::{TcpListener, TcpStream}; use std::mem::size_of; use std::sync::Arc; use std::sync::mpsc::{Sender, Receiver, channel}; use std::thread; use std::thread::sleep_ms; use byteorder::{LittleEndian, ReadBytesExt, WriteBytesEx...
{ let mut results: Vec<_> = (0..(addresses.len() - my_index as usize - 1)).map(|_| None).collect(); let listener = try!(TcpListener::bind(&addresses[my_index as usize][..])); for _ in (my_index as usize + 1 .. addresses.len()) { let mut stream = try!(listener.accept()).0; let identifier = t...
identifier_body
traits.rs
use core::marker::Sized; use embedded_hal::{ blocking::{delay::*, spi::Write}, digital::v2::*, }; /// All commands need to have this trait which gives the address of the command /// which needs to be send via SPI with activated CommandsPin (Data/Command Pin in CommandMode) pub(crate) trait Command: Copy { ...
/// Updates and displays the new frame. fn update_and_display_new_frame( &mut self, spi: &mut SPI, buffer: &[u8], delay: &mut DELAY, ) -> Result<(), SPI::Error>; /// Updates the old frame for a portion of the display. #[allow(clippy::too_many_arguments)] fn updat...
/// Displays the new frame fn display_new_frame(&mut self, spi: &mut SPI, _delay: &mut DELAY) -> Result<(), SPI::Error>;
random_line_split
traits.rs
use core::marker::Sized; use embedded_hal::{ blocking::{delay::*, spi::Write}, digital::v2::*, }; /// All commands need to have this trait which gives the address of the command /// which needs to be send via SPI with activated CommandsPin (Data/Command Pin in CommandMode) pub(crate) trait Command: Copy { ...
{ /// The "normal" full Lookuptable for the Refresh-Sequence #[default] Full, /// The quick LUT where not the full refresh sequence is followed. /// This might lead to some Quick, } pub(crate) trait InternalWiAdditions<SPI, CS, BUSY, DC, RST, DELAY> where SPI: Write<u8>, CS: OutputPin,...
RefreshLut
identifier_name