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
list_view.rs
use std::{ cmp::Ordering, io::{stdout, Write}, }; use crossterm::{ cursor::MoveTo, queue, style::{Color, SetBackgroundColor}, terminal::{Clear, ClearType}, }; use crate::{ compute_scrollbar, errors::Result, gray, Alignment, Area, CompoundStyle, MadSkin, Spacing, }; pub struct ListViewCell...
else { self.area.height } } /// return an option which when filled contains /// a tupple with the top and bottom of the vertical /// scrollbar. Return none when the content fits /// the available space. #[inline(always)] pub fn scrollbar(&self) -> Option<(u16, u16)> {...
{ self.area.height - 2 }
conditional_block
list_view.rs
use std::{ cmp::Ordering, io::{stdout, Write}, }; use crossterm::{ cursor::MoveTo, queue, style::{Color, SetBackgroundColor}, terminal::{Clear, ClearType}, }; use crate::{ compute_scrollbar, errors::Result, gray, Alignment, Area, CompoundStyle, MadSkin, Spacing, }; pub struct ListViewCell...
self.row_order = Some(sort); } /// return the height which is available for rows #[inline(always)] pub const fn tbody_height(&self) -> u16 { if self.area.height > 2 { self.area.height - 2 } else { self.area.height } } /// return an option w...
/// set a comparator for row sorting #[allow(clippy::type_complexity)] pub fn sort(&mut self, sort: Box<dyn Fn(&T, &T) -> Ordering>) {
random_line_split
list_view.rs
use std::{ cmp::Ordering, io::{stdout, Write}, }; use crossterm::{ cursor::MoveTo, queue, style::{Color, SetBackgroundColor}, terminal::{Clear, ClearType}, }; use crate::{ compute_scrollbar, errors::Result, gray, Alignment, Area, CompoundStyle, MadSkin, Spacing, }; pub struct ListViewCell...
(&mut self, data: T) { let stick_to_bottom = self.row_order.is_none() && self.do_scroll_show_bottom(); let displayed = match &self.filter { Some(fun) => fun(&data), None => true, }; if displayed { self.displayed_rows_count += 1; } if st...
add_row
identifier_name
lib.rs
// `error_chain!` can recurse deeply #![recursion_limit = "1024"] // Import the macro. Don't forget to add `error-chain` in your // `Cargo.toml`! #[macro_use] extern crate error_chain; #[macro_use] extern crate log; extern crate clap; extern crate byteorder; extern crate ansi_term; extern crate pbr; pub mod network...
(&self, index: u32) -> Result<&FileInfo> { return self.files.get(&index) .ok_or_else(|| ErrorKind::UnknownFile(index).into()); } pub fn run(&self) -> Result<()> { //@Expansion: Maybe don't use fixed ports let listener = std::net::TcpListener::bind((self.interface.addr, 2222))...
get_file
identifier_name
lib.rs
// `error_chain!` can recurse deeply #![recursion_limit = "1024"] // Import the macro. Don't forget to add `error-chain` in your // `Cargo.toml`! #[macro_use] extern crate error_chain; #[macro_use] extern crate log; extern crate clap; extern crate byteorder; extern crate ansi_term; extern crate pbr; pub mod network...
//TODO: Make some error wrapper let mut file = std::fs::File::create(new_path)?; let mut buffer = [0u8; 8192]; loop{ let read = message.file.read(&mut buffer) .chain_err(|| ErrorKind::ReadContent)?; if read == 0 { break; ...
{ bail!(ErrorKind::FileExists(new_path)); }
conditional_block
lib.rs
// `error_chain!` can recurse deeply #![recursion_limit = "1024"] // Import the macro. Don't forget to add `error-chain` in your // `Cargo.toml`! #[macro_use] extern crate error_chain; #[macro_use] extern crate log; extern crate clap; extern crate byteorder; extern crate ansi_term; extern crate pbr; pub mod network;...
}; } pub fn present(&self, t: &Transport) -> Result<String> { let parts = (t.max_state() as f64).log(self.dict_entries as f64).ceil() as u32; let mut part_representation: Vec<&str> = Vec::with_capacity(parts as usize); let mut remainder = t.state(); for _ in 0..parts {...
dictionary: dictionary, dict_entries: dict_entries,
random_line_split
lib.rs
// `error_chain!` can recurse deeply #![recursion_limit = "1024"] // Import the macro. Don't forget to add `error-chain` in your // `Cargo.toml`! #[macro_use] extern crate error_chain; #[macro_use] extern crate log; extern crate clap; extern crate byteorder; extern crate ansi_term; extern crate pbr; pub mod network...
fn from_transport<T: PartialTransport>(t: T) -> Result<Self> { return Ok(std::net::Ipv4Addr::from(t.state())); } } #[derive(Clone)] pub struct FileInfo{ path: PathBuf, len: u64, } impl FileInfo { fn new(path: PathBuf, len: u64) -> FileInfo { return FileInfo { path: pa...
{ return Ok(ServerTransport::new(u32::from(self.clone()), std::u32::MAX)); }
identifier_body
bulk.rs
use bitcoincash::blockdata::block::Block; use bitcoincash::consensus::encode::{deserialize, Decodable}; use bitcoincash::hash_types::BlockHash; use std::collections::HashSet; use std::fs; use std::io::Cursor; use std::path::{Path, PathBuf}; use std::sync::{ mpsc::{Receiver, SyncSender}, Arc, Mutex, }; use std::...
(blob: Vec<u8>, magic: u32) -> Result<Vec<Block>> { let mut cursor = Cursor::new(&blob); let mut blocks = vec![]; let max_pos = blob.len() as u64; while cursor.position() < max_pos { let offset = cursor.position(); match u32::consensus_decode(&mut cursor) { Ok(value) => { ...
parse_blocks
identifier_name
bulk.rs
use bitcoincash::blockdata::block::Block; use bitcoincash::consensus::encode::{deserialize, Decodable}; use bitcoincash::hash_types::BlockHash; use std::collections::HashSet; use std::fs; use std::io::Cursor; use std::path::{Path, PathBuf}; use std::sync::{ mpsc::{Receiver, SyncSender}, Arc, Mutex, }; use std::...
let chan = SyncChannel::new(0); let blobs = chan.sender(); let handle = spawn_thread("bulk_read", move || -> Result<()> { for path in blk_files { blobs .send((parser.read_blkfile(&path)?, path)) .expect("failed to send blk*.dat contents"); } ...
type JoinHandle = thread::JoinHandle<Result<()>>; type BlobReceiver = Arc<Mutex<Receiver<(Vec<u8>, PathBuf)>>>; fn start_reader(blk_files: Vec<PathBuf>, parser: Arc<Parser>) -> (BlobReceiver, JoinHandle) {
random_line_split
bulk.rs
use bitcoincash::blockdata::block::Block; use bitcoincash::consensus::encode::{deserialize, Decodable}; use bitcoincash::hash_types::BlockHash; use std::collections::HashSet; use std::fs; use std::io::Cursor; use std::path::{Path, PathBuf}; use std::sync::{ mpsc::{Receiver, SyncSender}, Arc, Mutex, }; use std::...
bytes_read: metrics.histogram(prometheus::HistogramOpts::new( "electrscash_parse_bytes_read", "# of bytes read (from blk*.dat)", )), })) } fn last_indexed_row(&self) -> Row { // TODO: use JSONRPC for missing blocks, and don't use 'L' row...
{ Ok(Arc::new(Parser { magic: daemon.disk_magic(), current_headers: load_headers(daemon)?, indexed_blockhashes: Mutex::new(indexed_blockhashes), cashaccount_activation_height, duration: metrics.histogram_vec( prometheus::HistogramOpts::...
identifier_body
lib.rs
// SPDX-FileCopyrightText: 2020 Robin Krahl <robin.krahl@ireas.org> // SPDX-License-Identifier: Apache-2.0 or MIT //! `cursive-markup` provides the [`MarkupView`][] for [`cursive`][] that can render HTML or other //! markup. //! //! # Quickstart //! //! To render an HTML document, create a [`MarkupView`][] with the [`...
/// [`set_maximum_width`][] method. /// /// [`RenderedDocument`]: struct.RenderedDocument.html /// [`Renderer`]: trait.Renderer.html /// [`render`]: trait.Renderer.html#method.render /// [`on_link_select`]: #method.on_link_select /// [`on_link_focus`]: #method.on_link_focus /// [`set_maximum_width`]: #method.set_maximu...
/// /// You can also limit the available width by setting a maximum line width with the
random_line_split
lib.rs
// SPDX-FileCopyrightText: 2020 Robin Krahl <robin.krahl@ireas.org> // SPDX-License-Identifier: Apache-2.0 or MIT //! `cursive-markup` provides the [`MarkupView`][] for [`cursive`][] that can render HTML or other //! markup. //! //! # Quickstart //! //! To render an HTML document, create a [`MarkupView`][] with the [`...
fn layout(&mut self, constraint: cursive_core::XY<usize>) { self.render(constraint); } fn required_size(&mut self, constraint: cursive_core::XY<usize>) -> cursive_core::XY<usize> { self.render(constraint) } fn take_focus(&mut self, direction: cursive_core::direction::Direction) -> ...
let doc = &self.doc.as_ref().expect("layout not called before draw"); for (y, line) in doc.lines.iter().enumerate() { let mut x = 0; for element in line { let mut style = element.style; if let Some(link_idx) = element.link_idx { ...
identifier_body
lib.rs
// SPDX-FileCopyrightText: 2020 Robin Krahl <robin.krahl@ireas.org> // SPDX-License-Identifier: Apache-2.0 or MIT //! `cursive-markup` provides the [`MarkupView`][] for [`cursive`][] that can render HTML or other //! markup. //! //! # Quickstart //! //! To render an HTML document, create a [`MarkupView`][] with the [`...
text: String, style: theme::Style, link_target: Option<String>, } #[derive(Clone, Debug, Default)] struct RenderedElement { text: String, style: theme::Style, link_idx: Option<usize>, } #[derive(Clone, Debug, Default)] struct LinkHandler { links: Vec<Link>, focus: usize, } #[derive(C...
ement {
identifier_name
spec.rs
// Copyright 2015-2019 Parity Technologies (UK) Ltd. // This file is part of Parity Ethereum. // Parity Ethereum is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at yo...
else { Machine::regular(params, builtins) } } /// Convert engine spec into a arc'd Engine of the right underlying type. /// TODO avoid this hard-coded nastiness - use dynamic-linked plugin framework instead. fn engine( spec_params: SpecParams, engine_spec: ethjson::spec::Engine, params: CommonParams, ...
{ Machine::with_ethash_extensions(params, builtins, ethash.params.clone().into()) }
conditional_block
spec.rs
// Copyright 2015-2019 Parity Technologies (UK) Ltd. // This file is part of Parity Ethereum. // Parity Ethereum is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at yo...
}) } /// Loads spec from json file. Provide factories for executing contracts and ensuring /// storage goes to the right place. pub fn load<'a, T: Into<SpecParams<'a>>, R: Read>(params: T, reader: R) -> Result<Self, Error> { ethjson::spec::Spec::load(reader) .map_err(|e| Error::Msg(e.to_string())) .and_...
let params = CommonParams::from(s.params); Spec::machine(&s.engine, params, builtins)
random_line_split
spec.rs
// Copyright 2015-2019 Parity Technologies (UK) Ltd. // This file is part of Parity Ethereum. // Parity Ethereum is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at yo...
( spec_params: SpecParams, engine_spec: ethjson::spec::Engine, params: CommonParams, builtins: BTreeMap<Address, Builtin>, ) -> Arc<dyn Engine> { let machine = Self::machine(&engine_spec, params, builtins); match engine_spec { ethjson::spec::Engine::Null(null) => Arc::new(NullEngine::new(null.params.in...
engine
identifier_name
spec.rs
// Copyright 2015-2019 Parity Technologies (UK) Ltd. // This file is part of Parity Ethereum. // Parity Ethereum is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at yo...
} impl<'a, T: AsRef<Path>> From<&'a T> for SpecParams<'a> { fn from(path: &'a T) -> Self { Self::from_path(path.as_ref()) } } /// given a pre-constructor state, run all the given constructors and produce a new state and /// state root. fn run_constructors<T: Backend>( genesis_state: &PodState, constructors: &[...
{ SpecParams { cache_dir: path, optimization_setting: Some(optimization), } }
identifier_body
dynamic_scene.rs
use std::any::TypeId; use crate::{DynamicSceneBuilder, Scene, SceneSpawnError}; use anyhow::Result; use bevy_ecs::{ entity::Entity, reflect::{AppTypeRegistry, ReflectComponent, ReflectMapEntities}, world::World, }; use bevy_reflect::{Reflect, TypePath, TypeRegistryArc, TypeUuid}; use bevy_utils::HashMap; ...
use crate::dynamic_scene_builder::DynamicSceneBuilder; #[test] fn components_not_defined_in_scene_should_not_be_affected_by_scene_entity_map() { // Testing that scene reloading applies EntityMap correctly to MapEntities components. // First, we create a simple world with a parent and a chi...
use bevy_hierarchy::{AddChild, Parent}; use bevy_utils::HashMap;
random_line_split
dynamic_scene.rs
use std::any::TypeId; use crate::{DynamicSceneBuilder, Scene, SceneSpawnError}; use anyhow::Result; use bevy_ecs::{ entity::Entity, reflect::{AppTypeRegistry, ReflectComponent, ReflectMapEntities}, world::World, }; use bevy_reflect::{Reflect, TypePath, TypeRegistryArc, TypeUuid}; use bevy_utils::HashMap; ...
} Ok(()) } /// Write the resources, the dynamic entities, and their corresponding components to the given world. /// /// This method will return a [`SceneSpawnError`] if a type either is not registered /// in the world's [`AppTypeRegistry`] resource, or doesn't reflect the ///...
{ map_entities_reflect.map_entities(world, entity_map, &entities); }
conditional_block
dynamic_scene.rs
use std::any::TypeId; use crate::{DynamicSceneBuilder, Scene, SceneSpawnError}; use anyhow::Result; use bevy_ecs::{ entity::Entity, reflect::{AppTypeRegistry, ReflectComponent, ReflectMapEntities}, world::World, }; use bevy_reflect::{Reflect, TypePath, TypeRegistryArc, TypeUuid}; use bevy_utils::HashMap; ...
#[cfg(test)] mod tests { use bevy_ecs::{reflect::AppTypeRegistry, system::Command, world::World}; use bevy_hierarchy::{AddChild, Parent}; use bevy_utils::HashMap; use crate::dynamic_scene_builder::DynamicSceneBuilder; #[test] fn components_not_defined_in_scene_should_not_be_affected_by_scene...
{ let pretty_config = ron::ser::PrettyConfig::default() .indentor(" ".to_string()) .new_line("\n".to_string()); ron::ser::to_string_pretty(&serialize, pretty_config) }
identifier_body
dynamic_scene.rs
use std::any::TypeId; use crate::{DynamicSceneBuilder, Scene, SceneSpawnError}; use anyhow::Result; use bevy_ecs::{ entity::Entity, reflect::{AppTypeRegistry, ReflectComponent, ReflectMapEntities}, world::World, }; use bevy_reflect::{Reflect, TypePath, TypeRegistryArc, TypeUuid}; use bevy_utils::HashMap; ...
{ /// The identifier of the entity, unique within a scene (and the world it may have been generated from). /// /// Components that reference this entity must consistently use this identifier. pub entity: Entity, /// A vector of boxed components that belong to the given entity and /// implement ...
DynamicEntity
identifier_name
bank.rs
#[macro_use] extern crate clap; extern crate rand; extern crate distributary; use std::sync; use std::thread; use std::time; use std::collections::HashMap; use distributary::{Blender, Base, Aggregation, JoinBuilder, Datas, DataType, Token, Mutator}; use rand::Rng; extern crate hdrsample; use hdrsample::Histogram...
fn client(i: usize, mut transfers_put: Box<Putter>, balances_get: Box<Getter>, naccounts: i64, start: time::Instant, runtime: time::Duration, verbose: bool, cdf: bool, audit: bool, transactions: &mut Vec<(i64, i64, i64)>) ...
{ // prepopulate non-transactionally (this is okay because we add no accounts while running the // benchmark) println!("Connected. Setting up {} accounts.", naccounts); { // let accounts_put = bank.accounts.as_ref().unwrap(); let mut money_put = transfers_put.transfer(); for i in...
identifier_body
bank.rs
#[macro_use] extern crate clap; extern crate rand; extern crate distributary; use std::sync; use std::thread; use std::time; use std::collections::HashMap; use distributary::{Blender, Base, Aggregation, JoinBuilder, Datas, DataType, Token, Mutator}; use rand::Rng; extern crate hdrsample; use hdrsample::Histogram...
(naccounts: i64, transfers_put: &mut Box<Putter>) { // prepopulate non-transactionally (this is okay because we add no accounts while running the // benchmark) println!("Connected. Setting up {} accounts.", naccounts); { // let accounts_put = bank.accounts.as_ref().unwrap(); let mut mone...
populate
identifier_name
bank.rs
#[macro_use] extern crate clap; extern crate rand; extern crate distributary; use std::sync; use std::thread; use std::time; use std::collections::HashMap; use distributary::{Blender, Base, Aggregation, JoinBuilder, Datas, DataType, Token, Mutator}; use rand::Rng; extern crate hdrsample; use hdrsample::Histogram...
let avg_put_throughput = |th: Vec<f64>| if avg { let sum: f64 = th.iter().sum(); println!("avg PUT: {:.2}", sum / th.len() as f64); }; if let Some(duration) = migrate_after { thread::sleep(duration); println!("----- starting migration -----"); let start = time::Inst...
}) }) .collect::<Vec<_>>();
random_line_split
lib.rs
use byteorder::{NativeEndian, ReadBytesExt}; use fftw::array::AlignedVec; use fftw::plan::*; use fftw::types::*; use num_complex::Complex; use ron::de::from_reader; use serde::Deserialize; use std::f64::consts::PI; use std::fs::File; use std::io::prelude::*; use std::io::BufReader; /// A struct containing the configur...
/// Calculates the cross power spectrum of the given 3D grids (note if the same /// grid is given twice then this is the auto power spectrum). /// /// # Examples /// /// ``` /// let output: Output = correlate(&config, grid1, grid2).unwrap(); /// ``` pub fn correlate( config: &Config, out1: AlignedVec<c64>, ...
{ let mut out = AlignedVec::new(ngrid3); match plan.c2c(&mut grid, &mut out) { Ok(_) => (), Err(_) => return Err("Failed to FFT grid."), }; Ok(out) }
identifier_body
lib.rs
use byteorder::{NativeEndian, ReadBytesExt}; use fftw::array::AlignedVec; use fftw::plan::*; use fftw::types::*; use num_complex::Complex; use ron::de::from_reader; use serde::Deserialize; use std::f64::consts::PI; use std::fs::File; use std::io::prelude::*; use std::io::BufReader; /// A struct containing the configur...
} /// Performs FFT on grids /// /// # Examples /// /// ``` /// let output: Output = correlate(&config, grid1, grid2).unwrap(); /// ``` pub fn perform_fft( config: &Config, grid1: AlignedVec<c64>, grid2: AlignedVec<c64>, ) -> Result<(AlignedVec<c64>, AlignedVec<c64>), &'static str> { println!("\nPerform...
}); Ok(grid)
random_line_split
lib.rs
use byteorder::{NativeEndian, ReadBytesExt}; use fftw::array::AlignedVec; use fftw::plan::*; use fftw::types::*; use num_complex::Complex; use ron::de::from_reader; use serde::Deserialize; use std::f64::consts::PI; use std::fs::File; use std::io::prelude::*; use std::io::BufReader; /// A struct containing the configur...
(config: &Config, num: usize) -> Result<AlignedVec<c64>, &'static str> { let filename = match num { 1 => &config.grid1_filename, 2 => &config.grid2_filename, _ => return Err("Need to load either grid 1 or 2!"), }; println!("\nOpening grid from file: {}", filename); let ngrid: usi...
load_grid
identifier_name
jenkins-mod-main.rs
#[macro_use] extern crate error_chain; extern crate hyper; extern crate log4rs; #[macro_use] extern crate log; #[macro_use] extern crate serde_derive; extern crate serde_json; extern crate structopt; #[macro_use] extern crate structopt_derive; extern crate toml; use hyper::client::{Client, RedirectPolicy}; use serd...
// write the body here let mut client = Client::new(); client.set_redirect_policy(RedirectPolicy::FollowAll); let mut resp = client.get(&config.update_center_url).send().chain_err(|| { format!( "Unable to perform HTTP request with URL string '{}'", config.update_center_u...
})?; info!("Completed configuration initialization!");
random_line_split
jenkins-mod-main.rs
#[macro_use] extern crate error_chain; extern crate hyper; extern crate log4rs; #[macro_use] extern crate log; #[macro_use] extern crate serde_derive; extern crate serde_json; extern crate structopt; #[macro_use] extern crate structopt_derive; extern crate toml; use hyper::client::{Client, RedirectPolicy}; use serd...
None => Ok(()), } }; create_parent_dir_if_present(config.modified_json_file_path.parent())?; create_parent_dir_if_present(config.url_list_json_file_path.parent())?; } let mut json_file = File::create(&config.modified_json_file_path) .chain_err(|| "U...
{ info!("Creating directory chain: {:?}", dir); fs::create_dir_all(dir) .chain_err(|| format!("Unable to create directory chain: {:?}", dir)) }
conditional_block
jenkins-mod-main.rs
#[macro_use] extern crate error_chain; extern crate hyper; extern crate log4rs; #[macro_use] extern crate log; #[macro_use] extern crate serde_derive; extern crate serde_json; extern crate structopt; #[macro_use] extern crate structopt_derive; extern crate toml; use hyper::client::{Client, RedirectPolicy}; use serd...
<S: Into<String>>( resp_outer_map: &mut MapStrVal, connection_check_url_change: S, ) -> Result<()> { let connection_check_url = match resp_outer_map.get_mut(CONNECTION_CHECK_URL_KEY) { Some(connection_check_url) => connection_check_url, None => bail!(format!( "Unable to find '{}'...
change_connection_check_url
identifier_name
mod.rs
use core::iter::Iterator; use super::*; use crate::error_consts::*; //#[test] //mod test; #[derive(Clone)] pub struct Line { tag: char, matched: bool, text: String, } pub struct VecBuffer { saved: bool, // Chars used for tagging. No tag equates to NULL in the char buffer: Vec<Line>, clipboard: Vec<Line...
; // If there is no newline at the end, join next line if!after.ends_with('\n') { if tail.len() > 0 { after.push_str(&tail.remove(0).text); } else { after.push('\n'); } } // Split on newlines and add all lines to the buffer for line in after.lines() { se...
{ regex.replace(&tmp.text, pattern.1).to_string() }
conditional_block
mod.rs
use core::iter::Iterator; use super::*; use crate::error_consts::*; //#[test] //mod test; #[derive(Clone)] pub struct Line { tag: char, matched: bool, text: String, } pub struct VecBuffer { saved: bool, // Chars used for tagging. No tag equates to NULL in the char buffer: Vec<Line>, clipboard: Vec<Line...
(&mut self, selection: Option<(usize, usize)>, path: &str, append: bool) -> Result<(), &'static str> { let data = match selection { Some(sel) => self.get_selection(sel)?, None => Box::new(self.buffer[..].iter().map(|line| &line.text[..])), }; file::write_file(path, data, append)?; if s...
write_to
identifier_name
mod.rs
use core::iter::Iterator; use super::*; use crate::error_consts::*; //#[test] //mod test; #[derive(Clone)] pub struct Line { tag: char, matched: bool, text: String, } pub struct VecBuffer { saved: bool, // Chars used for tagging. No tag equates to NULL in the char buffer: Vec<Line>, clipboard: Vec<Line...
buffer: Vec::new(), clipboard: Vec::new(), } } } impl Buffer for VecBuffer { // Index operations, get and verify fn len(&self) -> usize { self.buffer.len() } fn get_tag(&self, tag: char) -> Result<usize, &'static str> { let mut index = 0; for line in &self.buffer[..] { ...
saved: true,
random_line_split
day24b.rs
#![feature(drain_filter)] use clap::Parser; use env_logger::Env; use log::{debug, info}; use std::cell::Cell; use std::fmt; use std::fs::File; use std::io::{BufRead, BufReader}; /// Advent of Code 2022, Day 24 #[derive(Parser, Debug)] #[command(author, version, about, long_about = None)] struct Args { /// Input fi...
} fn main() { env_logger::Builder::from_env(Env::default().default_filter_or("info")) .format_timestamp(None) .init(); let args = Args::parse(); let nways: usize = match args.part { 1 => 1, // start-exit 2 => 3, // start-exit-start-exit part @ _ => panic!("Don't know ...
)) .collect::<String>() .trim_end() ) }
random_line_split
day24b.rs
#![feature(drain_filter)] use clap::Parser; use env_logger::Env; use log::{debug, info}; use std::cell::Cell; use std::fmt; use std::fs::File; use std::io::{BufRead, BufReader}; /// Advent of Code 2022, Day 24 #[derive(Parser, Debug)] #[command(author, version, about, long_about = None)] struct Args { /// Input fi...
} impl Map { /// Create a new empty Map with the specified dimensions. pub fn empty((nrows, ncols): (usize, usize)) -> Map { let start = (1, 0); let exit = (ncols - 2, nrows - 1); Map { grid: (0..nrows) .map(|nrow| { (0..ncols) ...
{ let nblizzards = self.blizzards.len(); match (self, nblizzards) { (MapPos { wall: true, .. }, _) => '#', (MapPos { wall: false, .. }, 0) => '.', (MapPos { wall: false, .. }, 1) => self.blizzards[0], (MapPos { wall: false, .. }, 2 | 3 | 4 | 5 | 6 | 7 | 8 ...
identifier_body
day24b.rs
#![feature(drain_filter)] use clap::Parser; use env_logger::Env; use log::{debug, info}; use std::cell::Cell; use std::fmt; use std::fs::File; use std::io::{BufRead, BufReader}; /// Advent of Code 2022, Day 24 #[derive(Parser, Debug)] #[command(author, version, about, long_about = None)] struct Args { /// Input fi...
(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, "\n{}", self.grid .iter() .enumerate() .map(|(rownum, row)| format!( "{}\n", row.iter() .enumerate() ...
fmt
identifier_name
interface.rs
//! All the nitty gritty details regarding COM interface for the shell extension //! are defined here. //! //! See: https://docs.microsoft.com/en-us/windows/win32/shell/handlers#implementing-shell-extension-handlers use com::sys::HRESULT; use guid_win::Guid; use once_cell::sync::Lazy; use std::cell::RefCell; use std::...
} winerror::CLASS_E_CLASSNOTAVAILABLE } /// Add in-process server keys into registry. /// /// See: https://docs.microsoft.com/en-us/windows/win32/api/olectl/nf-olectl-dllregisterserver #[no_mangle] extern "system" fn DllRegisterServer() -> HRESULT { let hinstance = unsafe { DLL_HANDLE }; let path = mat...
random_line_split
interface.rs
//! All the nitty gritty details regarding COM interface for the shell extension //! are defined here. //! //! See: https://docs.microsoft.com/en-us/windows/win32/shell/handlers#implementing-shell-extension-handlers use com::sys::HRESULT; use guid_win::Guid; use once_cell::sync::Lazy; use std::cell::RefCell; use std::...
winerror::CLASS_E_CLASSNOTAVAILABLE } /// Add in-process server keys into registry. /// /// See: https://docs.microsoft.com/en-us/windows/win32/api/olectl/nf-olectl-dllregisterserver #[no_mangle] extern "system" fn DllRegisterServer() -> HRESULT { let hinstance = unsafe { DLL_HANDLE }; let path = match ge...
{ log::warn!("Unsupported class: {}", class_guid); }
conditional_block
interface.rs
//! All the nitty gritty details regarding COM interface for the shell extension //! are defined here. //! //! See: https://docs.microsoft.com/en-us/windows/win32/shell/handlers#implementing-shell-extension-handlers use com::sys::HRESULT; use guid_win::Guid; use once_cell::sync::Lazy; use std::cell::RefCell; use std::...
/// Convert Win32 GUID pointer to Guid struct. const fn guid_from_ref(clsid: *const guiddef::GUID) -> Guid { Guid { 0: unsafe { *clsid }, } } /// Get path to loaded DLL file. fn get_module_path(hinstance: win::HINSTANCE) -> Result<PathBuf, Error> { use std::ffi::OsString; use std::os::windows...
{ match wslscript_common::registry::remove_server_from_registry() { Ok(_) => (), Err(e) => { log::error!("Failed to unregister server: {}", e); return winerror::E_UNEXPECTED; } } winerror::S_OK }
identifier_body
interface.rs
//! All the nitty gritty details regarding COM interface for the shell extension //! are defined here. //! //! See: https://docs.microsoft.com/en-us/windows/win32/shell/handlers#implementing-shell-extension-handlers use com::sys::HRESULT; use guid_win::Guid; use once_cell::sync::Lazy; use std::cell::RefCell; use std::...
() -> HRESULT { let hinstance = unsafe { DLL_HANDLE }; let path = match get_module_path(hinstance) { Ok(p) => p, Err(_) => return winerror::E_UNEXPECTED, }; log::debug!("DllRegisterServer for {}", path.to_string_lossy()); match wslscript_common::registry::add_server_to_registry(&path...
DllRegisterServer
identifier_name
server.rs
use super::router::HttpRouter; use super::ProbeRegistration; use futures::future::BoxFuture; use futures::future::FusedFuture; use futures::future::FutureExt; use futures::lock::Mutex; use hyper::server::{ conn::{AddrIncoming, AddrStream}, Server, }; use hyper::service::Service; use hyper::Body; use hyper::Req...
} /** * Return the result of registering the server's DTrace USDT probes. * * See [`ProbeRegistration`] for details. */ pub fn probe_registration(&self) -> &ProbeRegistration { &self.probe_registration } } /* * For graceful termination, the `close()` function is preferred...
{ Ok(()) }
conditional_block
server.rs
use super::router::HttpRouter; use super::ProbeRegistration; use futures::future::BoxFuture; use futures::future::FusedFuture; use futures::future::FutureExt; use futures::lock::Mutex; use hyper::server::{ conn::{AddrIncoming, AddrStream}, Server, }; use hyper::service::Service; use hyper::Body; use hyper::Re...
self.app_state.log, "failed to register DTrace USDT probes: {}", msg ); ProbeRegistration::Failed(msg) } } } else { debug!( self.app_state.log, "DTrace ...
} Err(e) => { let msg = e.to_string(); error!(
random_line_split
server.rs
use super::router::HttpRouter; use super::ProbeRegistration; use futures::future::BoxFuture; use futures::future::FusedFuture; use futures::future::FutureExt; use futures::lock::Mutex; use hyper::server::{ conn::{AddrIncoming, AddrStream}, Server, }; use hyper::service::Service; use hyper::Body; use hyper::Req...
( _rqctx: Arc<RequestContext<i32>>, ) -> Result<HttpResponseOk<u64>, HttpError> { Ok(HttpResponseOk(3)) } struct TestConfig { log_context: LogContext, } impl TestConfig { fn log(&self) -> &slog::Logger { &self.log_context.log } } fn crea...
handler
identifier_name
kflash.rs
//! Kendryte K210 UART ISP, based on [`kflash.py`] //! (https://github.com/sipeed/kflash.py) use anyhow::Result; use crc::{crc32, Hasher32}; use std::{future::Future, marker::Unpin, path::Path, pin::Pin, sync::Mutex, time::Duration}; use tokio::{ io::{AsyncBufRead, AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt...
( reader: &mut (impl AsyncRead + Unpin), ) -> std::io::Result<std::convert::Infallible> { let mut buf = [0u8; 256]; loop { let num_bytes = reader.read(&mut buf).await?; log::trace!("Discarding {} byte(s)", num_bytes); } } #[derive(thiserror::Error, Debug)] enum ProcessElfError { #[e...
read_to_end_and_discard
identifier_name
kflash.rs
//! Kendryte K210 UART ISP, based on [`kflash.py`] //! (https://github.com/sipeed/kflash.py) use anyhow::Result; use crc::{crc32, Hasher32}; use std::{future::Future, marker::Unpin, path::Path, pin::Pin, sync::Mutex, time::Duration}; use tokio::{ io::{AsyncBufRead, AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt...
BadInitialization, BadExec, Unknown(u8), } impl From<u8> for IspReasonCode { fn from(x: u8) -> Self { match x { 0x00 => Self::Default, 0xe0 => Self::Ok, 0xe1 => Self::BadDataLen, 0xe2 => Self::BadDataChecksum, 0xe3 => Self::InvalidComm...
BadDataChecksum, InvalidCommand,
random_line_split
semaphore.rs
use std::{fmt, mem}; use std::panic::{RefUnwindSafe, UnwindSafe}; use std::sync::atomic::Ordering::{Relaxed, Acquire}; use crate::state::ReleaseState::Unlocked; use crate::state::AcquireState::{Available, Queued}; use std::fmt::{Debug, Formatter}; use crate::state::{AcquireStep, Waiter, Permits, AcquireState, ReleaseSt...
} } } } /// Like [acquire](#method.acquire), but takes an [`Arc`] `<Semaphore>` and returns a guard that is `'static`, [`Send`] and [`Sync`]. /// # Examples /// ``` /// # use async_weighted_semaphore::{Semaphore, PoisonError, SemaphoreGuardArc}; /// # use st...
{ return Ok(SemaphoreGuard::new(self, amount)); }
conditional_block
semaphore.rs
use std::{fmt, mem}; use std::panic::{RefUnwindSafe, UnwindSafe}; use std::sync::atomic::Ordering::{Relaxed, Acquire}; use crate::state::ReleaseState::Unlocked; use crate::state::AcquireState::{Available, Queued}; use std::fmt::{Debug, Formatter}; use crate::state::{AcquireStep, Waiter, Permits, AcquireState, ReleaseSt...
(&self, amount: usize) -> Result<SemaphoreGuard, TryAcquireError> { let mut current = self.acquire.load(Acquire); loop { match current { Queued(_) => return Err(TryAcquireError::WouldBlock), Available(available) => { let available = availab...
try_acquire
identifier_name
semaphore.rs
use std::{fmt, mem}; use std::panic::{RefUnwindSafe, UnwindSafe}; use std::sync::atomic::Ordering::{Relaxed, Acquire}; use crate::state::ReleaseState::Unlocked; use crate::state::AcquireState::{Available, Queued}; use std::fmt::{Debug, Formatter}; use crate::state::{AcquireStep, Waiter, Permits, AcquireState, ReleaseSt...
} impl Semaphore { /// The maximum number of permits that can be made available. This is slightly smaller than /// [`usize::MAX`]. If the number of available permits exceeds this number, it may poison the /// semaphore. /// # Examples /// ``` /// # use async_weighted_semaphore::{Semaphore, Se...
{ match self.acquire.load(Relaxed) { Available(available) => write!(f, "Semaphore::Ready({:?})", available)?, Queued(_) => match self.release.load(Relaxed) { Unlocked(available) => write!(f, "Semaphore::Blocked({:?})", available)?, _ => write!(f, "Semaphor...
identifier_body
semaphore.rs
use std::{fmt, mem}; use std::panic::{RefUnwindSafe, UnwindSafe}; use std::sync::atomic::Ordering::{Relaxed, Acquire}; use crate::state::ReleaseState::Unlocked; use crate::state::AcquireState::{Available, Queued}; use std::fmt::{Debug, Formatter}; use crate::state::{AcquireStep, Waiter, Permits, AcquireState, ReleaseSt...
pub fn acquire_arc(self: &Arc<Self>, amount: usize) -> AcquireFutureArc { AcquireFutureArc { arc: self.clone(), inner: unsafe { mem::transmute::<AcquireFuture, AcquireFuture>(self.acquire(amount)) }, } } /// Like [try_acquire](#method.try_acquire), but takes an [`Ar...
/// ```
random_line_split
14.rs
// --- Day 14: Disk Defragmentation --- // Suddenly, a scheduled job activates the system's disk defragmenter. Were the situation different, you might sit and watch it for a while, but today, you just don't have that kind of time. It's soaking up valuable system resources that are needed elsewhere, and so the only opt...
(size: u32, occupied: &Vec<Vec<bool>>) { for row in occupied.iter().take(size as usize) { println!("\n{}", row.iter().take(size as usize).map(|c| match c { &true => "#", &false => ".", }) .collect::<Vec<&str>>() .join(" ")); } } /* This algori...
print_small_grid
identifier_name
14.rs
// --- Day 14: Disk Defragmentation --- // Suddenly, a scheduled job activates the system's disk defragmenter. Were the situation different, you might sit and watch it for a while, but today, you just don't have that kind of time. It's soaking up valuable system resources that are needed elsewhere, and so the only opt...
} else { clusters.set_empty(Loc(i, j)) } } } // clusters.print_small(10); clusters.index.keys().len() as u32 } fn part_two() { let grid = make_grid("jxqlasbh"); let count = count_clusters(&grid); println!("14-2: {} clust...
{ clusters.new_cluster(Loc(i, j)); }
conditional_block
14.rs
// --- Day 14: Disk Defragmentation --- // Suddenly, a scheduled job activates the system's disk defragmenter. Were the situation different, you might sit and watch it for a while, but today, you just don't have that kind of time. It's soaking up valuable system resources that are needed elsewhere, and so the only opt...
fn bitcount_hash(hash: &str) -> u32 { let mut bitsum = 0; for j in 0..32 { let slice = &hash[j..j+1]; let num = u32::from_str_radix(slice, 16).unwrap(); bitsum += num.count_ones(); } bitsum } fn count_hash_seed(s: &str) -> u32 { let mut bitsum = 0; for ha...
{ (0..128) .map(|i| format!("{}-{}", seed, i)) .map(|plaintext| { let mut knot = Knot::new(); knot.hash(Cursor::new(plaintext)) }) .collect() }
identifier_body
14.rs
// --- Day 14: Disk Defragmentation --- // Suddenly, a scheduled job activates the system's disk defragmenter. Were the situation different, you might sit and watch it for a while, but today, you just don't have that kind of time. It's soaking up valuable system resources that are needed elsewhere, and so the only opt...
} fn new_cluster(&mut self, loc: Loc) { let id = self.next_id; self.next_id += 1; self.add_to_cluster(loc, id); } fn add_to_cluster(&mut self, loc: Loc, id: ClusterId) { self.add_grid(&loc, id); match self.index.entry(id) { Occupied(mut e) => ...
random_line_split
types.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use serde::{ de::{Deserializer, Error}, Deserialize, Serialize, }; use serde_repr::{Deserialize_repr, Serialize_repr}; use uuid::Uuid; use crate::payment_command::Actor; /// A header set with a unique UUID (according to RFC412...
: PaymentObject) -> Self { Self { object_type: ObjectType::PaymentCommand, payment, } } pub fn payment(&self) -> &PaymentObject { &self.payment } pub fn into_payment(self) -> PaymentObject { self.payment } } /// A `PaymentActorObject` repres...
ent
identifier_name
types.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use serde::{ de::{Deserializer, Error}, Deserialize, Serialize, }; use serde_repr::{Deserialize_repr, Serialize_repr}; use uuid::Uuid; use crate::payment_command::Actor; /// A header set with a unique UUID (according to RFC412...
} } #[derive(Deserialize, Serialize)] pub struct CommandRequestObject { #[serde(deserialize_with = "ObjectType::deserialize_request")] #[serde(rename = "_ObjectType")] object_type: ObjectType, #[serde(flatten)] command: Command, cid: Uuid, } impl CommandRequestObject { pub fn new(comm...
{ Err(D::Error::custom(format_args!("expected {:?}", variant))) }
conditional_block
types.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use serde::{ de::{Deserializer, Error}, Deserialize, Serialize, }; use serde_repr::{Deserialize_repr, Serialize_repr}; use uuid::Uuid; use crate::payment_command::Actor; /// A header set with a unique UUID (according to RFC412...
b fn into_payment(self) -> PaymentObject { self.payment } } /// A `PaymentActorObject` represents a participant in a payment - either sender or receiver. It /// also includes the status of the actor, indicates missing information or willingness to settle /// or abort the payment, and the Know-Your-Customer...
&self.payment } pu
identifier_body
types.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use serde::{ de::{Deserializer, Error}, Deserialize, Serialize, }; use serde_repr::{Deserialize_repr, Serialize_repr}; use uuid::Uuid; use crate::payment_command::Actor; /// A header set with a unique UUID (according to RFC412...
/// Two-letter country code (https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) pub country: Option<String>, /// Indicates the type of the ID #[serde(rename = "type")] pub id_type: Option<String>, } /// Represents a physical address #[derive(Clone, Debug, Default, PartialEq, Deserialize, Serialize...
random_line_split
goto_definition.rs
use super::NavigationTarget; use crate::def::{AstPtr, Expr, Literal, ResolveResult}; use crate::{DefDatabase, FileId, FilePos, ModuleKind, VfsPath}; use nix_interop::FLAKE_FILE; use syntax::ast::{self, AstNode}; use syntax::{best_token_at_offset, match_ast, SyntaxKind, SyntaxToken}; #[derive(Debug, Clone, PartialEq, E...
#[track_caller] fn check(fixture: &str, expect: Expect) { let (db, f) = TestDB::from_fixture(fixture).unwrap(); assert_eq!(f.markers().len(), 1, "Missing markers"); let mut got = match goto_definition(&db, f[0]).expect("No definition") { GotoDefinitionResult::Path(path) => ...
{ let (db, f) = TestDB::from_fixture(fixture).unwrap(); assert_eq!(f.markers().len(), 1, "Missing markers"); assert_eq!(goto_definition(&db, f[0]), None); }
identifier_body
goto_definition.rs
use super::NavigationTarget; use crate::def::{AstPtr, Expr, Literal, ResolveResult}; use crate::{DefDatabase, FileId, FilePos, ModuleKind, VfsPath}; use nix_interop::FLAKE_FILE; use syntax::ast::{self, AstNode}; use syntax::{best_token_at_offset, match_ast, SyntaxKind, SyntaxToken}; #[derive(Debug, Clone, PartialEq, E...
full_range: with_header, }) }) .collect() } // Currently builtin names cannot "goto-definition". ResolveResult::Builtin(_) => return None, }; Some(GotoDefinitionResult::Targets(targets)) } fn goto_flake_input( ...
{ withs .iter() .filter_map(|&with_expr| { // with expr; body // ^--^ focus // ^--------^ full let with_node = source_map .node_for_expr(with_expr) ...
conditional_block
goto_definition.rs
use super::NavigationTarget; use crate::def::{AstPtr, Expr, Literal, ResolveResult}; use crate::{DefDatabase, FileId, FilePos, ModuleKind, VfsPath}; use nix_interop::FLAKE_FILE; use syntax::ast::{self, AstNode}; use syntax::{best_token_at_offset, match_ast, SyntaxKind, SyntaxToken}; #[derive(Debug, Clone, PartialEq, E...
(fixture: &str, expect: Expect) { let (db, f) = TestDB::from_fixture(fixture).unwrap(); assert_eq!(f.markers().len(), 1, "Missing markers"); let mut got = match goto_definition(&db, f[0]).expect("No definition") { GotoDefinitionResult::Path(path) => format!("file://{}", path.display(...
check
identifier_name
goto_definition.rs
use super::NavigationTarget; use crate::def::{AstPtr, Expr, Literal, ResolveResult}; use crate::{DefDatabase, FileId, FilePos, ModuleKind, VfsPath}; use nix_interop::FLAKE_FILE; use syntax::ast::{self, AstNode}; use syntax::{best_token_at_offset, match_ast, SyntaxKind, SyntaxToken}; #[derive(Debug, Clone, PartialEq, E...
expect!["<a> = a;"], ); check( "let a = $0a; in rec { inherit a; b = a; }", expect!["<a> = a;"], ); } #[test] fn left_and_right() { check("let a = 1; in $0a ", expect!["<a> = 1;"]); check("let a = 1; in a$0 ", expect!["<a> = 1;"]);...
expect!["inherit <a>;"], ); check( "let a = a; in rec { inherit $0a; b = a; }",
random_line_split
amqp.rs
// Copyright 2020-2021, The Tremor Team // // 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 agr...
(&mut self, _signal: Event) -> ResultVec { //self.drain_fatal_errors()?; Ok(Vec::new()) } fn is_active(&self) -> bool { true } fn auto_ack(&self) -> bool { false } async fn terminate(&mut self) { if let Some(channel) = self.channel.as_ref() { i...
on_signal
identifier_name
amqp.rs
// Copyright 2020-2021, The Tremor Team // // 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 agr...
impl ConfigImpl for Config {} /// Amqp offramp connector pub(crate) struct Amqp { sink_url: TremorUrl, config: Config, postprocessors: Postprocessors, reply_channel: Sender<sink::Reply>, channel: Option<Channel>, error_rx: Receiver<()>, error_tx: Sender<()>, } impl fmt::Debug for Amqp { ...
} } }
random_line_split
amqp.rs
// Copyright 2020-2021, The Tremor Team // // 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 agr...
} #[async_trait::async_trait] impl Sink for Amqp { async fn on_event( &mut self, _input: &str, codec: &mut dyn Codec, _codec_map: &HashMap<String, Box<dyn Codec>>, event: Event, ) -> ResultVec { self.handle_channel().await?; let ingest_ns = event.ingest_...
{ while let Ok(()) = self.error_rx.try_recv() { self.channel = None; } if self.channel.is_none() { match self.config.channel().await.await { Ok(channel) => self.channel = Some(channel), Err(error) => return Err(error.into()), } ...
identifier_body
amqp.rs
// Copyright 2020-2021, The Tremor Team // // 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 agr...
Confirmation::Nack(err) => { if let Some(e) = err { error!( "[Sink::{}] failed to send message: {} {}", &self.sink_url, e.reply_code, e.reply_text ...
{ if event.transactional { let mut insight = insight_event.clone(); insight.cb = CbAction::Ack; // we hopefully enver wait more then u64 ... if we do we got // bigg...
conditional_block
mod.rs
::{Error, ErrorKind, Result}; use crate::status::StatusBackend; pub mod cached_itarbundle; pub mod dirbundle; pub mod filesystem; pub mod format_cache; pub mod memory; pub mod setup; pub mod stack; pub mod stdstreams; pub mod zipbundle; pub trait InputFeatures: Read { fn get_size(&mut self) -> Result<usize>; ...
/// Open the "primary" input file, which in the context of TeX is the main /// input that it's given. When the build is being done using the /// filesystem and the input is a file on the filesystem, this function /// isn't necesssarily that important, but those conditions don't always /// hold. ...
OpenResult::NotAvailable }
identifier_body
mod.rs
errors::{Error, ErrorKind, Result}; use crate::status::StatusBackend; pub mod cached_itarbundle; pub mod dirbundle; pub mod filesystem; pub mod format_cache; pub mod memory; pub mod setup; pub mod stack; pub mod stdstreams; pub mod zipbundle; pub trait InputFeatures: Read { fn get_size(&mut self) -> Result<usize>...
_ => r.push(c), } } let r = repeat("..") .take(parent_level) .chain(r.into_iter()) // No `join` on `Iterator`. .collect::<Vec<_>>() .join("/"); if r.is_empty() { if has_root { Some("/".into()) } else { Some("."...
_ => {} } }
random_line_split
mod.rs
::{Error, ErrorKind, Result}; use crate::status::StatusBackend; pub mod cached_itarbundle; pub mod dirbundle; pub mod filesystem; pub mod format_cache; pub mod memory; pub mod setup; pub mod stack; pub mod stdstreams; pub mod zipbundle; pub trait InputFeatures: Read { fn get_size(&mut self) -> Result<usize>; ...
} } /// Normalize a TeX path in a system independent™ way by stripping any `.`, `..`, /// or extra separators '/' so that it is of the form /// /// ```text /// path/to/my/file.txt ///../../path/to/parent/dir/file.txt /// /absolute/path/to/file.txt /// ``` /// /// Does not strip whitespace. /// /// Returns `None` ...
OpenResult::Err(e.into()) } }
conditional_block
mod.rs
::{Error, ErrorKind, Result}; use crate::status::StatusBackend; pub mod cached_itarbundle; pub mod dirbundle; pub mod filesystem; pub mod format_cache; pub mod memory; pub mod setup; pub mod stack; pub mod stdstreams; pub mod zipbundle; pub trait InputFeatures: Read { fn get_size(&mut self) -> Result<usize>; ...
:'static + Write>(name: &OsStr, inner: T) -> OutputHandle { OutputHandle { name: name.to_os_string(), inner: Box::new(inner), digest: digest::create(), } } pub fn name(&self) -> &OsStr { self.name.as_os_str() } /// Consumes the object and ret...
w<T
identifier_name
execution.rs
// Copyright 2018-2021 Parity Technologies (UK) Ltd. // // 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 applicab...
} /// Trait used to convert return types of contract initializer routines. /// /// Only `()` and `Result<(), E>` are allowed contract initializer return types. /// For `WrapReturnType<C>` where `C` is the contract type the trait converts /// `()` into `C` and `Result<(), E>` into `Result<C, E>`. pub trait Initializer...
{ &self.0 }
identifier_body
execution.rs
// Copyright 2018-2021 Parity Technologies (UK) Ltd. // // 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 applicab...
if TypeId::of::<R>()!= TypeId::of::<()>() { // In case the return type is `()` we do not return a value. ink_env::return_value::<R>(ReturnFlags::default(), result) } Ok(()) } #[inline] fn finalize_fallible_message<R>(result: &R) ->! where R: scale::Encode +'static, { // There is no...
{ alloc::finalize(); }
conditional_block
execution.rs
// Copyright 2018-2021 Parity Technologies (UK) Ltd. // // 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 applicab...
<Contract, F, R>( initializer: F, ) -> <R as InitializerReturnType<Contract>>::Wrapped where Contract: ContractRootKey + SpreadAllocate, F: FnOnce(&mut Contract) -> R, R: InitializerReturnType<Contract>, { let mut key_ptr = KeyPtr::from(<Contract as ContractRootKey>::ROOT_KEY); let mut instance ...
initialize_contract
identifier_name
execution.rs
// Copyright 2018-2021 Parity Technologies (UK) Ltd. // // 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 applicab...
/// where `E` is some unspecified error type. /// If the contract initializer returns `Result::Err` the utility /// method that is used to initialize an ink! smart contract will /// revert the state of the contract instantiation. pub trait ConstructorReturnType<C>: private::Sealed { /// Is `true` if `Self` is `Resu...
random_line_split
exec.rs
// Copyright 2018 Grove Enterprises LLC // // 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 ...
df.write("_uk_cities_wkt.csv").unwrap(); //TODO: check that generated file has expected contents } fn create_context() -> ExecutionContext { // create execution context let mut ctx = ExecutionContext::new(); // define schemas for test data ctx.define_schema("p...
ctx.define_function(&STPointFunc {}); let df = ctx.sql(&"SELECT ST_AsText(ST_Point(lat, lng)) FROM uk_cities").unwrap();
random_line_split
exec.rs
// Copyright 2018 Grove Enterprises LLC // // 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 ...
(&self, expr: Vec<Expr>) -> Result<Box<DataFrame>, DataFrameError> { let plan = LogicalPlan::Projection { expr: expr, input: self.plan.clone(), schema: self.plan.schema().clone() }; Ok(Box::new(DF { ctx: self.ctx.clone(), plan: Box::new(plan) })) } ...
select
identifier_name
exec.rs
// Copyright 2018 Grove Enterprises LLC // // 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 fn udf(&self, name: &str, args: Vec<Expr>) -> Expr { Expr::ScalarFunction { name: name.to_string(), args: args.clone() } } } pub struct DF { ctx: Box<ExecutionContext>, plan: Box<LogicalPlan> } impl DataFrame for DF { fn select(&self, expr: Vec<Expr>) -> Result<Box<DataFrame>, D...
{ //TODO: this is a huge hack since the functions have already been registered with the // execution context ... I need to implement this so it dynamically loads the functions match function_name.to_lowercase().as_ref() { "sqrt" => Ok(Box::new(SqrtFunction {})), "st_poi...
identifier_body
main.rs
extern crate hsl; extern crate rand; extern crate sdl2; use sdl2::audio::{AudioCVT, AudioSpecDesired, AudioSpecWAV, AudioQueue}; use sdl2::event::Event; use sdl2::image::{INIT_PNG, LoadSurface}; use sdl2::gfx::rotozoom::RotozoomSurface; use sdl2::keyboard::Keycode; use sdl2::pixels::Color; use sdl2::rect::Rect; use sd...
} struct RandomPositionStrategy {} impl PositionStrategy for RandomPositionStrategy { // Return a random position that fits rect within rect fn next_position(&mut self, rect: Rect, within_rect: Rect) -> Rect { let rx: f64 = thread_rng().gen(); let ry: f64 = thread_rng().gen(); let pos...
{ }
identifier_body
main.rs
extern crate hsl; extern crate rand; extern crate sdl2; use sdl2::audio::{AudioCVT, AudioSpecDesired, AudioSpecWAV, AudioQueue}; use sdl2::event::Event; use sdl2::image::{INIT_PNG, LoadSurface}; use sdl2::gfx::rotozoom::RotozoomSurface; use sdl2::keyboard::Keycode; use sdl2::pixels::Color; use sdl2::rect::Rect; use sd...
.collect(); let mut background_color = random_colour(Color::RGB(255, 255, 255)); 'running: loop { for event in event_pump.poll_iter() { match event { Event::Quit {.. } | Event::KeyDown { keycode: Some(Keycode::Escape), ...
("U", "upsiedaisy"), ("W", "woody"), ].iter() .map(|(s1, s2)| (s1.to_string(), s2.to_string()))
random_line_split
main.rs
extern crate hsl; extern crate rand; extern crate sdl2; use sdl2::audio::{AudioCVT, AudioSpecDesired, AudioSpecWAV, AudioQueue}; use sdl2::event::Event; use sdl2::image::{INIT_PNG, LoadSurface}; use sdl2::gfx::rotozoom::RotozoomSurface; use sdl2::keyboard::Keycode; use sdl2::pixels::Color; use sdl2::rect::Rect; use sd...
(&mut self) { } } struct RandomPositionStrategy {} impl PositionStrategy for RandomPositionStrategy { // Return a random position that fits rect within rect fn next_position(&mut self, rect: Rect, within_rect: Rect) -> Rect { let rx: f64 = thread_rng().gen(); let ry: f64 = thread_rng().ge...
reset
identifier_name
main.rs
extern crate hsl; extern crate rand; extern crate sdl2; use sdl2::audio::{AudioCVT, AudioSpecDesired, AudioSpecWAV, AudioQueue}; use sdl2::event::Event; use sdl2::image::{INIT_PNG, LoadSurface}; use sdl2::gfx::rotozoom::RotozoomSurface; use sdl2::keyboard::Keycode; use sdl2::pixels::Color; use sdl2::rect::Rect; use sd...
} _ => {} } } // Draw the chars canvas.set_draw_color(background_color); canvas.clear(); for &(ref texture, target) in drawables.iter() { canvas.copy(&texture, None, Some(target.clone())).unwrap(); } canvas....
{ let mut surface = load_image(&filename); let sf = (100f64 / surface.height() as f64); println!("{}", sf ); let surface = surface.rotozoom(0f64, sf, false).unwrap(); let texture = texture_creator ...
conditional_block
system.rs
// This file is part of Substrate. // Copyright (C) 2017-2020 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 // // ht...
} if let Some(new_authorities) = o_new_authorities { digest.push(generic::DigestItem::Consensus(*b"aura", new_authorities.encode())); digest.push(generic::DigestItem::Consensus(*b"babe", new_authorities.encode())); } if let Some(new_config) = new_changes_trie_config { digest.push(generic::DigestItem::Change...
{ let extrinsic_index: u32 = storage::unhashed::take(well_known_keys::EXTRINSIC_INDEX).unwrap(); let txs: Vec<_> = (0..extrinsic_index).map(ExtrinsicData::take).collect(); let extrinsics_root = trie::blake2_256_ordered_root(txs).into(); let number = <Number>::take().expect("Number is set by `initialize_block`"); l...
identifier_body
system.rs
// This file is part of Substrate. // Copyright (C) 2017-2020 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 // // ht...
else { vec![] }; let provides = vec![encode(&tx.from, tx.nonce)]; Ok(ValidTransaction { priority: tx.amount, requires, provides, longevity: 64, propagate: true }) } /// Execute a transaction outside of the block execution function. /// This doesn't attempt to validate anything regarding the block. pub fn execu...
{ vec![encode(&tx.from, tx.nonce - 1)] }
conditional_block
system.rs
// This file is part of Substrate. // Copyright (C) 2017-2020 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 // // ht...
{ Verify, Overwrite, } /// Actually execute all transitioning for `block`. pub fn polish_block(block: &mut Block) { execute_block_with_state_root_handler(block, Mode::Overwrite); } pub fn execute_block(mut block: Block) { execute_block_with_state_root_handler(&mut block, Mode::Verify); } fn execute_block_with_s...
Mode
identifier_name
system.rs
// This file is part of Substrate. // Copyright (C) 2017-2020 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 // // ht...
} } pub fn balance_of_key(who: AccountId) -> Vec<u8> { who.to_keyed_vec(BALANCE_OF) } pub fn balance_of(who: AccountId) -> u64 { storage::hashed::get_or(&blake2_256, &balance_of_key(who), 0) } pub fn nonce_of(who: AccountId) -> u64 { storage::hashed::get_or(&blake2_256, &who.to_keyed_vec(NONCE_OF), 0) } pub fn ...
NewAuthorities get(fn new_authorities): Option<Vec<AuthorityId>>; NewChangesTrieConfig get(fn new_changes_trie_config): Option<Option<ChangesTrieConfiguration>>; StorageDigest get(fn storage_digest): Option<Digest>; Authorities get(fn authorities) config(): Vec<AuthorityId>;
random_line_split
delaunay_triangulation.rs
and half-edge ids are related. The half-edges of triangle t are 3*t, 3*t + 1, and 3*t + 2. The triangle of half-edge id e is floor(e/3 # Example ```rust use delaunator::triangulate; use structures::Point2D let points = vec![ Point2D { x: 0., y: 0. }, Point2D { x: 1., y: 0. }, Point2D { x: 1., y...
r. pub fn triangle_center(&self, points: &[Point2D], triangle: usize) -> Point2D { let p = self.points_of_triangle(triangle); points[p[0]].circumcenter(&points[p[1]], &points[p[2]]) } /// Returns the edges around a point connected to halfedge '*start*'. pub fn edges_around_point(&self, ...
angle(t) // .into_iter() // .map(|e| self.triangles[*e]) // .collect() let e = self.edges_of_triangle(triangle); [ self.triangles[e[0]], self.triangles[e[1]], self.triangles[e[2]], ] } /// Triangle circumcente
identifier_body
delaunay_triangulation.rs
ids and half-edge ids are related. The half-edges of triangle t are 3*t, 3*t + 1, and 3*t + 2. The triangle of half-edge id e is floor(e/3 # Example ```rust use delaunator::triangulate; use structures::Point2D let points = vec![ Point2D { x: 0., y: 0. }, Point2D { x: 1., y: 0. }, Point2D { x: 1...
result.push(incoming); break; } // i += 1; // if i > 100 { // // println!("{} {} {}", outgoing, incoming, start); // break; // } } result } pub fn natural_neighbours_from_incoming_edge...
} else if incoming == start {
conditional_block
delaunay_triangulation.rs
Triangle ids and half-edge ids are related. The half-edges of triangle t are 3*t, 3*t + 1, and 3*t + 2. The triangle of half-edge id e is floor(e/3 # Example ```rust use delaunator::triangulate; use structures::Point2D let points = vec![ Point2D { x: 0., y: 0. }, Point2D { x: 1., y: 0. }, Point2...
} impl Triangulation { /// Constructs a new *Triangulation*. fn new(n: usize) -> Self { let max_triangles = 2 * n - 5; Self { triangles: Vec::with_capacity(max_triangles * 3), halfedges: Vec::with_capacity(max_triangles * 3), hull: Vec::new(), } }...
/// counter-clockwise. pub hull: Vec<usize>,
random_line_split
delaunay_triangulation.rs
ids and half-edge ids are related. The half-edges of triangle t are 3*t, 3*t + 1, and 3*t + 2. The triangle of half-edge id e is floor(e/3 # Example ```rust use delaunator::triangulate; use structures::Point2D let points = vec![ Point2D { x: 0., y: 0. }, Point2D { x: 1., y: 0. }, Point2D { x: 1...
0: usize, i1: usize, i2: usize, a: usize, b: usize, c: usize, ) -> usize { let t = self.triangles.len(); self.triangles.push(i0); self.triangles.push(i1); self.triangles.push(i2); self.halfedges.push(a); self.halfedges.push(b)...
f, i
identifier_name
toggle.rs
use bars_duration_ticks; use conrod_core::{self as conrod, widget}; use env; use ruler; use time_calc::{self as time, Ticks}; use track; pub use env::{Point, PointTrait, Toggle as ToggleValue, Trait as EnvelopeTrait}; /// The envelope type compatible with the `Toggle` automation track. pub type Envelope = env::bounde...
{ ids: Ids, } widget_ids! { struct Ids { circles[], rectangles[], phantom_line, } } #[derive(Copy, Clone, Debug, Default, PartialEq, WidgetStyle)] pub struct Style { #[conrod(default = "theme.shape_color")] pub color: Option<conrod::Color>, #[conrod(default = "4.0")] ...
State
identifier_name
toggle.rs
use bars_duration_ticks; use conrod_core::{self as conrod, widget}; use env; use ruler; use time_calc::{self as time, Ticks}; use track; pub use env::{Point, PointTrait, Toggle as ToggleValue, Trait as EnvelopeTrait}; /// The envelope type compatible with the `Toggle` automation track. pub type Envelope = env::bounde...
builder_methods! { pub point_radius { style.point_radius = Some(conrod::Scalar) } } } impl<'a> track::Widget for Toggle<'a> { fn playhead(mut self, playhead: (Ticks, Ticks)) -> Self { self.maybe_playhead = Some(playhead); self } } impl<'a> conrod::Colorable for Toggle<'a> { ...
{ Toggle { bars: bars, ppqn: ppqn, maybe_playhead: None, envelope: envelope, common: widget::CommonBuilder::default(), style: Style::default(), } }
identifier_body
toggle.rs
use bars_duration_ticks; use conrod_core::{self as conrod, widget}; use env; use ruler; use time_calc::{self as time, Ticks}; use track; pub use env::{Point, PointTrait, Toggle as ToggleValue, Trait as EnvelopeTrait}; /// The envelope type compatible with the `Toggle` automation track. pub type Envelope = env::bounde...
// _ => return, // }, // // Only draw the clicked point if it is still after the last point. // Clicked(Elem::AfterLastPoint, _, _) => // match envelope.points().last() { // Some(p) if p.ticks <= tic...
// // Only draw the clicked point if it is still before the first point. // Clicked(Elem::BeforeFirstPoint, _, _) => // match envelope.points().nth(0) { // Some(p) if ticks <= p.ticks => color.clicked().alpha(0.7),
random_line_split
route_planner.rs
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use crate::{ future_help::{Observer, PollMutex}, labels::{NodeId, NodeLinkId}, link::LinkStatus, router::Router, }; use anyhow::{bail, form...
} Ok::<_, Error>(()) }, async move { while let Some(status) = local_updates.next().await { let mut node_table = local_node_table.lock().await; let root_node = node_table.root_node; if let Err(e) = node_table.update_link...
{ log::warn!("Update remote links from {:?} failed: {:?}", from_node_id, e); continue; }
conditional_block
route_planner.rs
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use crate::{ future_help::{Observer, PollMutex}, labels::{NodeId, NodeLinkId}, link::LinkStatus, router::Router, }; use anyhow::{bail, form...
async move { while let Some(status) = local_updates.next().await { let mut node_table = local_node_table.lock().await; let root_node = node_table.root_node; if let Err(e) = node_table.update_links(root_node, status) { log::warn!("Up...
} Ok::<_, Error>(()) },
random_line_split
route_planner.rs
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use crate::{ future_help::{Observer, PollMutex}, labels::{NodeId, NodeLinkId}, link::LinkStatus, router::Router, }; use anyhow::{bail, form...
fn update_links(&mut self, from: NodeId, links: Vec<LinkStatus>) -> Result<(), Error> { self.get_or_create_node_mut(from).links.clear(); for LinkStatus { to, local_id, round_trip_time } in links.into_iter() { self.update_link(from, to, local_id, LinkDescription { round_trip_time })?; ...
{ log::trace!( "{:?} update_link: from:{:?} to:{:?} link_id:{:?} desc:{:?}", self.root_node, from, to, link_id, desc ); if from == to { bail!("Circular link seen"); } self.get_or_create_node_mut(t...
identifier_body
route_planner.rs
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use crate::{ future_help::{Observer, PollMutex}, labels::{NodeId, NodeLinkId}, link::LinkStatus, router::Router, }; use anyhow::{bail, form...
( &mut self, from: NodeId, to: NodeId, link_id: NodeLinkId, desc: LinkDescription, ) -> Result<(), Error> { log::trace!( "{:?} update_link: from:{:?} to:{:?} link_id:{:?} desc:{:?}", self.root_node, from, to, ...
update_link
identifier_name
lib.rs
mod data; mod nn; use std::mem; use std::slice; //use std::os::raw::{/*c_double, c_int, */c_void}; // for js functions imports use once_cell::sync::Lazy; use std::sync::Mutex; // for lazy_static // for global variables use ndarray::prelude::*; use ndarray::{array, Array, Array1, Array3, Axis, Zip}; use data::Data...
}); } #[cfg(test)] mod kernel_test { use super::*; static POINT_DRAW_TIMES: Lazy<Mutex<u32>> = Lazy::new(|| Mutex::new(0)); // Override the extern functions #[no_mangle] extern "C" fn draw_point(_: u32, _: u32, _: f32) { *POINT_DRAW_TIMES.lock().unwrap() += 1; } use std:...
{ // floor let x = x as u32; let y = y as u32; let label_ratio = label as f32 / num_classes; unsafe { draw_point(x, y, label_ratio); } }
conditional_block
lib.rs
mod data; mod nn; use std::mem; use std::slice; //use std::os::raw::{/*c_double, c_int, */c_void}; // for js functions imports use once_cell::sync::Lazy; use std::sync::Mutex; // for lazy_static // for global variables use ndarray::prelude::*; use ndarray::{array, Array, Array1, Array3, Axis, Zip}; use data::Data...
const DATA_GEN_RADIUS: f32 = 1f32; const SPIN_SPAN: f32 = PI; const NUM_CLASSES: u32 = 3; const DATA_NUM: u32 = 300; const FC_SIZE: u32 = 100; const REGULAR_RATE: f32 = 0.001f32; const DESCENT_RATE: f32 = 1f32; const DATA_GEN_RAND_MAX: f32 = 0.25f32; const NETWORK_GEN_RAND_MAX: f32 ...
*POINT_DRAW_TIMES.lock().unwrap() += 1; } use std::f32::consts::PI; // for math functions
random_line_split
lib.rs
mod data; mod nn; use std::mem; use std::slice; //use std::os::raw::{/*c_double, c_int, */c_void}; // for js functions imports use once_cell::sync::Lazy; use std::sync::Mutex; // for lazy_static // for global variables use ndarray::prelude::*; use ndarray::{array, Array, Array1, Array3, Axis, Zip}; use data::Data...
#[test] fn test_buffer_allocation() { let buffer = alloc(114514); free(buffer, 114514); } #[test] fn test_draw_prediction() { init( DATA_GEN_RADIUS, SPIN_SPAN, DATA_NUM, NUM_CLASSES, DATA_GEN_RAND_MAX, ...
{ init( DATA_GEN_RADIUS, SPIN_SPAN, DATA_NUM, NUM_CLASSES, DATA_GEN_RAND_MAX, NETWORK_GEN_RAND_MAX, FC_SIZE, DESCENT_RATE, REGULAR_RATE, ); let loss_before: f32 = train(); for _ in...
identifier_body
lib.rs
mod data; mod nn; use std::mem; use std::slice; //use std::os::raw::{/*c_double, c_int, */c_void}; // for js functions imports use once_cell::sync::Lazy; use std::sync::Mutex; // for lazy_static // for global variables use ndarray::prelude::*; use ndarray::{array, Array, Array1, Array3, Axis, Zip}; use data::Data...
{ fc_size: u32, num_classes: u32, descent_rate: f32, regular_rate: f32, } #[derive(Default)] struct CriticalSection(MetaData, Data, Network); // Imported js functions extern "C" { // for debug fn log_u64(num: u32); // for data pointer draw // x,y: the offset from upper left corner ...
MetaData
identifier_name
cache.rs
did = *last; let path = match self.paths.get(&did) { // The current stack not necessarily has correlation // for where the type was defined. On the other // hand, `paths` always has the right ...
{ match *clean_type { clean::ResolvedPath { ref path, .. } => { let segments = &path.segments; let path_segment = segments.into_iter().last().unwrap_or_else(|| panic!( "get_index_type_name(clean_type: {:?}, accept_generic: {:?}) had length zero path", ...
identifier_body