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
vga_buffer.rs
use core::fmt; use volatile::Volatile; use spin::Mutex; #[allow(dead_code)] // prevents compiler warnings that some enumerations are never used #[derive(Debug, Clone, Copy, PartialEq, Eq)] // enables copy semantics for the type: makes printable & comparable #[repr(u8)] // makes each enum variant be stor...
} // Provides a static Writer object which utilizes non-const functions // Requires locking to provide interior mutability: since it utilizes &mut self for writing // it requires mutability, but its mutibility is not provided to users, therefore it is interior // mutability. The Mutex allows safe usage internally. la...
{ self.write_string(s); Ok(()) }
identifier_body
mod.rs
query(&self, spec: &str) -> CargoResult<&PackageId> { let spec = try!(PackageIdSpec::parse(spec).chain_error(|| { human(format!("invalid package id specification: `{}`", spec)) })); let mut ids = self.iter().filter(|p| spec.matches(*p)); let ret = match ids.next() { ...
} impl fmt::Debug for Resolve { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { try!(write!(fmt, "graph: {:?}\n", self.graph)); try!(write!(fmt, "\nfeatures: {{\n")); for (pkg, features) in &self.features { try!(write!(fmt, " {}: {:?}\n", pkg, features)); } ...
{ self.features.get(pkg) }
identifier_body
mod.rs
`", spec)) })); let mut ids = self.iter().filter(|p| spec.matches(*p)); let ret = match ids.next() { Some(id) => id, None => return Err(human(format!("package id specification `{}` \ matched no packages", spec))), }; ...
{ for key in s.features().keys() { try!(add_feature(s, key, &mut deps, &mut used, &mut visited)); } for dep in s.dependencies().iter().filter(|d| d.is_optional()) { try!(add_feature(s, dep.name(), &mut deps, &mut used, ...
conditional_block
mod.rs
(&self) -> Nodes<PackageId> { self.graph.iter() } pub fn root(&self) -> &PackageId { &self.root } pub fn deps(&self, pkg: &PackageId) -> Option<Edges<PackageId>> { self.graph.edges(pkg) } pub fn query(&self, spec: &str) -> CargoResult<&PackageId> { let spec = try!(PackageI...
iter
identifier_name
mod.rs
pub fn query(&self, spec: &str) -> CargoResult<&PackageId> { let spec = try!(PackageIdSpec::parse(spec).chain_error(|| { human(format!("invalid package id specification: `{}`", spec)) })); let mut ids = self.iter().filter(|p| spec.matches(*p)); let ret = match ids.next() { ...
continue } let mut base = feature_deps.remove(dep.name()).unwrap_or(vec![]); for feature in dep.features().iter() { base.push(feature.clone()); if feature.contains("/") { return Err(human(format!("features in dependencies \ ...
// Next, sanitize all requested features by whitelisting all the requested // features that correspond to optional dependencies for dep in deps { // weed out optional dependencies, but not those required if dep.is_optional() && !feature_deps.contains_key(dep.name()) {
random_line_split
update.rs
//! Types used to describe updates on graphs. use std::convert::TryInto; use std::fs::File; use std::sync::Mutex; use crate::errors::{GraphAnnisCoreError, Result}; use crate::serializer::KeySerializer; use bincode::Options; use serde::de::Error as DeserializeError; use serde::de::{MapAccess, Visitor}; use serde::ser:...
else { (0, None) } } } impl Serialize for GraphUpdate { fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> where S: Serializer, { let iter = self.iter().map_err(S::Error::custom)?; let number_of_updates = self.len().map_err(S::Erro...
{ (s, Some(s)) }
conditional_block
update.rs
//! Types used to describe updates on graphs. use std::convert::TryInto; use std::fs::File; use std::sync::Mutex; use crate::errors::{GraphAnnisCoreError, Result}; use crate::serializer::KeySerializer; use bincode::Options; use serde::de::Error as DeserializeError; use serde::de::{MapAccess, Visitor}; use serde::ser:...
if let Ok(s) = self.size_hint.try_into() { (s, Some(s)) } else { (0, None) } } } impl Serialize for GraphUpdate { fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> where S: Serializer, { let iter = self.iter().m...
fn size_hint(&self) -> (usize, Option<usize>) {
random_line_split
update.rs
//! Types used to describe updates on graphs. use std::convert::TryInto; use std::fs::File; use std::sync::Mutex; use crate::errors::{GraphAnnisCoreError, Result}; use crate::serializer::KeySerializer; use bincode::Options; use serde::de::Error as DeserializeError; use serde::de::{MapAccess, Visitor}; use serde::ser:...
{ InProgress { table_builder: Box<TableBuilder<File>>, outfile: NamedTempFile, }, Finished { table: Table, }, } /// A list of changes to apply to an graph. pub struct GraphUpdate { changesets: Mutex<Vec<ChangeSet>>, event_counter: u64, serialization: bincode::config...
ChangeSet
identifier_name
update.rs
//! Types used to describe updates on graphs. use std::convert::TryInto; use std::fs::File; use std::sync::Mutex; use crate::errors::{GraphAnnisCoreError, Result}; use crate::serializer::KeySerializer; use bincode::Options; use serde::de::Error as DeserializeError; use serde::de::{MapAccess, Visitor}; use serde::ser:...
} } None } fn size_hint(&self) -> (usize, Option<usize>) { if let Ok(s) = self.size_hint.try_into() { (s, Some(s)) } else { (0, None) } } } impl Serialize for GraphUpdate { fn serialize<S>(&self, serializer: S) -> std::result...
{ // Remove all empty table iterators. self.iterators.retain(|it| it.valid()); if let Some(it) = self.iterators.first_mut() { // Get the current values if let Some((key, value)) = sstable::current_key_val(it) { // Create the actual types l...
identifier_body
main.rs
#![warn(clippy::all)] #![forbid(unsafe_code)] // Import from other crates. use csv::ByteRecord; use humansize::{file_size_opts, FileSize}; use lazy_static::lazy_static; use log::debug; use regex::bytes::Regex; use std::{ borrow::Cow, fs, io::{self, prelude::*}, path::PathBuf, process, }; use struct...
{ /// Input file (uses stdin if omitted). input: Option<PathBuf>, /// Character used to separate fields in a row (must be a single ASCII /// byte, or "tab"). #[structopt( value_name = "CHAR", short = "d", long = "delimiter", default_value = "," )] delimiter:...
Opt
identifier_name
main.rs
#![warn(clippy::all)] #![forbid(unsafe_code)] // Import from other crates. use csv::ByteRecord; use humansize::{file_size_opts, FileSize}; use lazy_static::lazy_static; use log::debug; use regex::bytes::Regex; use std::{ borrow::Cow, fs, io::{self, prelude::*}, path::PathBuf, process, }; use struct...
// flush, not on every tiny write. let stdin = io::stdin(); let input: Box<dyn Read> = if let Some(ref path) = opt.input { Box::new( fs::File::open(path) .with_context(|_| format!("cannot open {}", path.display()))?, ) } else { Box::new(stdin.lock()) ...
// implementing `Read`, stored on the heap." This allows us to do runtime // dispatch (as if Rust were object oriented). But because `csv` wraps a // `BufReader` around the box, we only do that dispatch once per buffer
random_line_split
main.rs
#![warn(clippy::all)] #![forbid(unsafe_code)] // Import from other crates. use csv::ByteRecord; use humansize::{file_size_opts, FileSize}; use lazy_static::lazy_static; use log::debug; use regex::bytes::Regex; use std::{ borrow::Cow, fs, io::{self, prelude::*}, path::PathBuf, process, }; use struct...
// Remove whitespace from our cells. if opt.trim_whitespace { // We do this manually, because the built-in `trim` only // works on UTF-8 strings, and we work on any // "ASCII-compatible" encoding. let first...
{ if null_re.is_match(val) { val = &[] } }
conditional_block
extractor.rs
use crate::{ client, config::{Configuration, CONFIGURATION}, scanner::SCANNED_URLS, statistics::{ StatCommand::{self, UpdateUsizeField}, StatField::{LinksExtracted, TotalExpected}, }, utils::{format_url, make_request}, FeroxResponse, }; use lazy_static::lazy_static; use regex...
}; if SCANNED_URLS.get_scan_by_url(&new_url.to_string()).is_some() { //we've seen the url before and don't need to scan again log::trace!("exit: request_feroxresponse_from_new_link -> None"); return None; } // make the request and store the response let new_response = matc...
{ log::trace!("exit: request_feroxresponse_from_new_link -> None"); return None; }
conditional_block
extractor.rs
use crate::{ client, config::{Configuration, CONFIGURATION}, scanner::SCANNED_URLS, statistics::{ StatCommand::{self, UpdateUsizeField}, StatField::{LinksExtracted, TotalExpected}, }, utils::{format_url, make_request}, FeroxResponse, }; use lazy_static::lazy_static; use regex...
( response: &FeroxResponse, tx_stats: UnboundedSender<StatCommand>, ) -> HashSet<String> { log::trace!( "enter: get_links({}, {:?})", response.url().as_str(), tx_stats ); let mut links = HashSet::<String>::new(); let body = response.text(); for capture in LINKS_REG...
get_links
identifier_name
extractor.rs
use crate::{ client, config::{Configuration, CONFIGURATION}, scanner::SCANNED_URLS, statistics::{ StatCommand::{self, UpdateUsizeField}, StatField::{LinksExtracted, TotalExpected}, }, utils::{format_url, make_request}, FeroxResponse, }; use lazy_static::lazy_static; use regex...
let links = get_links(&ferox_response, tx).await; assert!(links.is_empty()); assert_eq!(mock.hits(), 1); Ok(()) } #[tokio::test(flavor = "multi_thread", worker_threads = 1)] /// test that /robots.txt is correctly requested given a base url (happy path) async fn reques...
let (tx, _): FeroxChannel<StatCommand> = mpsc::unbounded_channel(); let response = make_request(&client, &url, tx.clone()).await.unwrap(); let ferox_response = FeroxResponse::from(response, true).await;
random_line_split
extractor.rs
use crate::{ client, config::{Configuration, CONFIGURATION}, scanner::SCANNED_URLS, statistics::{ StatCommand::{self, UpdateUsizeField}, StatField::{LinksExtracted, TotalExpected}, }, utils::{format_url, make_request}, FeroxResponse, }; use lazy_static::lazy_static; use regex...
assert_eq!(mock.hits(), 2); } }
{ let srv = MockServer::start(); let mock = srv.mock(|when, then| { when.method(GET).path("/robots.txt"); then.status(200).body("this is a test"); }); let mut config = Configuration::default(); let (tx, _): FeroxChannel<StatCommand> = mpsc::unbounded_ch...
identifier_body
keyboard.rs
use crate::input::device::{Device, DeviceType}; use crate::input::event_filter::{EventFilter, EventFilterManager}; use crate::input::events::{InputEvent, KeyboardEvent}; use crate::{config::ConfigManager, input::seat::SeatManager}; use log::debug; use serde::{Deserialize, Serialize}; use std::cell::RefCell; use std::op...
} } wayland_listener!( KeyboardEventManager, Weak<Keyboard>, [ modifiers => modifiers_func: |this: &mut KeyboardEventManager, _data: *mut libc::c_void,| unsafe { if let Some(handler) = this.data.upgrade() { handler.modifiers(); } }; key => key_func: |this: &mut KeyboardEventMan...
{ unsafe { // Otherwise, we pass it along to the client. wlr_seat_set_keyboard(self.seat_manager.raw_seat(), self.device.raw_ptr()); wlr_seat_keyboard_notify_key( self.seat_manager.raw_seat(), event.time_msec(), event.libinput_keycode(), event.raw_st...
conditional_block
keyboard.rs
use crate::input::device::{Device, DeviceType}; use crate::input::event_filter::{EventFilter, EventFilterManager}; use crate::input::events::{InputEvent, KeyboardEvent}; use crate::{config::ConfigManager, input::seat::SeatManager}; use log::debug; use serde::{Deserialize, Serialize}; use std::cell::RefCell; use std::op...
{ seat_manager: Rc<SeatManager>, event_filter_manager: Rc<EventFilterManager>, device: Rc<Device>, keyboard: *mut wlr_keyboard, xkb_state: RefCell<xkb::State>, event_manager: RefCell<Option<Pin<Box<KeyboardEventManager>>>>, } impl Keyboard { fn init( config_manager: Rc<ConfigManager>, seat_mana...
Keyboard
identifier_name
keyboard.rs
use crate::input::device::{Device, DeviceType}; use crate::input::event_filter::{EventFilter, EventFilterManager}; use crate::input::events::{InputEvent, KeyboardEvent}; use crate::{config::ConfigManager, input::seat::SeatManager}; use log::debug; use serde::{Deserialize, Serialize}; use std::cell::RefCell; use std::op...
} } pub(crate) trait KeyboardEventHandler { fn modifiers(&self); fn key(&self, event: *const wlr_event_keyboard_key); } impl KeyboardEventHandler for Keyboard { fn modifiers(&self) { unsafe { // A seat can only have one keyboard, but this is a limitation of the // Wayland protocol - not wlroot...
config.repeat_delay.0 as i32, );
random_line_split
quic.rs
use { crossbeam_channel::Sender, futures_util::stream::StreamExt, pem::Pem, pkcs8::{der::Document, AlgorithmIdentifier, ObjectIdentifier}, quinn::{Endpoint, EndpointConfig, ServerConfig}, rcgen::{CertificateParams, DistinguishedName, DnType, SanType}, solana_perf::packet::PacketBatch, so...
{ #[error("Server configure failed")] ConfigureFailed, #[error("Endpoint creation failed")] EndpointFailed, } // Return true if the server should drop the stream fn handle_chunk( chunk: &Result<Option<quinn::Chunk>, quinn::ReadError>, maybe_batch: &mut Option<PacketBatch>, remote_addr: &S...
QuicServerError
identifier_name
quic.rs
use { crossbeam_channel::Sender, futures_util::stream::StreamExt, pem::Pem, pkcs8::{der::Document, AlgorithmIdentifier, ObjectIdentifier}, quinn::{Endpoint, EndpointConfig, ServerConfig}, rcgen::{CertificateParams, DistinguishedName, DnType, SanType}, solana_perf::packet::PacketBatch, so...
contents: cert.0.clone(), }) .collect(); let cert_chain_pem = pem::encode_many(&cert_chain_pem_parts); let mut server_config = ServerConfig::with_single_cert(cert_chain, priv_key) .map_err(|_e| QuicServerError::ConfigureFailed)?; let config = Arc::get_mut(&mut server_confi...
new_cert(identity_keypair, gossip_host).map_err(|_e| QuicServerError::ConfigureFailed)?; let cert_chain_pem_parts: Vec<Pem> = cert_chain .iter() .map(|cert| Pem { tag: "CERTIFICATE".to_string(),
random_line_split
quic.rs
use { crossbeam_channel::Sender, futures_util::stream::StreamExt, pem::Pem, pkcs8::{der::Document, AlgorithmIdentifier, ObjectIdentifier}, quinn::{Endpoint, EndpointConfig, ServerConfig}, rcgen::{CertificateParams, DistinguishedName, DnType, SanType}, solana_perf::packet::PacketBatch, so...
let mut s1 = c1.connection.open_uni().await.unwrap(); let mut s2 = c2.connection.open_uni().await.unwrap(); s1.write_all(&[0u8]).await.unwrap(); s1.finish().await.unwrap(); s2.write_all(&[0u8]).await.unwrap(); s2.finish().aw...
{ solana_logger::setup(); let s = UdpSocket::bind("127.0.0.1:0").unwrap(); let exit = Arc::new(AtomicBool::new(false)); let (sender, receiver) = unbounded(); let keypair = Keypair::new(); let ip = "127.0.0.1".parse().unwrap(); let server_address = s.local_addr().u...
identifier_body
render.rs
//! Definitions, constructors, and management for the EnsoGL shapes that are used to draw an edge. //! //! The core function of this module is to translate edge layouts into the shape parameters that //! will implement them. use crate::prelude::*; use ensogl::display::shape::*; use crate::GraphLayers; use super::lay...
/// Create a shape object to render the little bit at the target end of the edge, that draws on /// top of the node. fn new_target_attachment(&self) -> Rectangle { let new = Rectangle::new(); new.set_size_x(LINE_WIDTH); new.set_border_color(color::Rgba::transparent()); new.s...
arc.stroke_width.set(LINE_WIDTH); self.display_object().add_child(&arc); self.layers().edge_below_nodes.add(&arc); arc }
random_line_split
render.rs
//! Definitions, constructors, and management for the EnsoGL shapes that are used to draw an edge. //! //! The core function of this module is to translate edge layouts into the shape parameters that //! will implement them. use crate::prelude::*; use ensogl::display::shape::*; use crate::GraphLayers; use super::lay...
( &self, parent: &impl ShapeParent, corners: &[Oriented<Corner>], ) { let hover_factory = self .hover_sections .take() .into_iter() .chain(iter::repeat_with(|| parent.new_hover_section())); *self.hover_sections.borrow_mut() = corner...
redraw_hover_sections
identifier_name
render.rs
//! Definitions, constructors, and management for the EnsoGL shapes that are used to draw an edge. //! //! The core function of this module is to translate edge layouts into the shape parameters that //! will implement them. use crate::prelude::*; use ensogl::display::shape::*; use crate::GraphLayers; use super::lay...
/// Create a shape object to render the cutout mask for the edge nearby the source node. fn new_cutout(&self) -> Rectangle { let cutout = Rectangle::new(); self.display_object().add_child(&cutout); // FIXME (temporary assumption): Currently we assume that the node background is a recta...
{ let new = SimpleTriangle::from_size(arrow::SIZE); new.set_pointer_events(false); self.display_object().add_child(&new); new.into() }
identifier_body
render.rs
//! Definitions, constructors, and management for the EnsoGL shapes that are used to draw an edge. //! //! The core function of this module is to translate edge layouts into the shape parameters that //! will implement them. use crate::prelude::*; use ensogl::display::shape::*; use crate::GraphLayers; use super::lay...
} else { min(a, b) } } fn minor_arc_sector(a: f32, b: f32) -> f32 { let a = a.abs(); let b = b.abs(); let ab = (a - b).abs(); min(ab, TAU - ab) }
{ a }
conditional_block
worker_actions.rs
//! Tasks and task execution of workes //! //! Note: This module and submodules will sooner or later need some refactoring. //! For now, I am still don't really know how I want it to look like. mod worker_abilities; mod worker_updates; use crate::db::DB; use crate::game_master::event::*; use crate::game_master::town_...
(&self) -> i32 { self.y } fn task_type(&self) -> &TaskType { &self.task_type } fn target(&self) -> Option<HoboKey> { self.target_hobo_id.map(HoboKey) } } impl WorkerAction for Task { fn x(&self) -> i32 { self.x } fn y(&self) -> i32 { self.y } ...
y
identifier_name
worker_actions.rs
//! Tasks and task execution of workes //! //! Note: This module and submodules will sooner or later need some refactoring. //! For now, I am still don't really know how I want it to look like. mod worker_abilities; mod worker_updates; use crate::db::DB; use crate::game_master::event::*; use crate::game_master::town_...
TaskType::WelcomeAbility => { if let Some(mana) = &mut worker.mana { let cost = AbilityType::Welcome.mana_cost(); if *mana >= cost { *mana = *mana - cost; Ok(()) } else { Err("Not enough mana...
{ town.state .register_task_begin(*task.task_type()) .map_err(|e| e.to_string())?; worker_into_building(town, worker, (task.x() as usize, task.y() as usize)) }
conditional_block
worker_actions.rs
//! Tasks and task execution of workes //! //! Note: This module and submodules will sooner or later need some refactoring. //! For now, I am still don't really know how I want it to look like. mod worker_abilities; mod worker_updates; use crate::db::DB; use crate::game_master::event::*; use crate::game_master::town_...
fn y(&self) -> i32 { self.y } fn task_type(&self) -> &TaskType { &self.task_type } fn target(&self) -> Option<HoboKey> { self.target_hobo_id.map(HoboKey) } }
{ self.x }
identifier_body
worker_actions.rs
//! Tasks and task execution of workes //! //! Note: This module and submodules will sooner or later need some refactoring. //! For now, I am still don't really know how I want it to look like. mod worker_abilities; mod worker_updates; use crate::db::DB; use crate::game_master::event::*; use crate::game_master::town_...
// Validate target hobo exists if there is one if let Some(target_id) = task.target { db.hobo(HoboKey(target_id)).ok_or("No such hobo id")?; } validate_ability(db, task.task_type, worker_id, timestamp)?; let new_task = NewTask { worker_id: worker_id.num(...
let mut tasks = vec![]; for task in tl.tasks.iter() {
random_line_split
lockfree.rs
use crate::{ arenas::atomic_bucket::{AtomicBucket, AtomicBucketList}, Capacity, LassoError, LassoErrorKind, LassoResult, MemoryLimits, }; use core::{ fmt::{self, Debug}, num::NonZeroUsize, slice, str, sync::atomic::{AtomicUsize, Ordering}, }; /// An arena allocator that dynamically grows in siz...
(&self, requested_mem: usize) -> LassoResult<()> { if self.memory_usage.load(Ordering::Relaxed) + requested_mem > self.max_memory_usage.load(Ordering::Relaxed) { Err(LassoError::new(LassoErrorKind::MemoryLimitReached)) } else { self.memory_usage ...
allocate_memory
identifier_name
lockfree.rs
use crate::{ arenas::atomic_bucket::{AtomicBucket, AtomicBucketList}, Capacity, LassoError, LassoErrorKind, LassoResult, MemoryLimits, }; use core::{ fmt::{self, Debug}, num::NonZeroUsize, slice, str, sync::atomic::{AtomicUsize, Ordering}, }; /// An arena allocator that dynamically grows in siz...
// TODO: Push the bucket to the back or something so that we can get it somewhat out // of the search path, reduce the `n` in the `O(n)` list traversal self.buckets.push_front(bucket.into_ref()); Ok(allocated_string) // Otherwise just a...
{ let memory_usage = self.current_memory_usage(); let max_memory_usage = self.get_max_memory_usage(); // If trying to use the doubled capacity will surpass our memory limit, just allocate as much as we can if memory_usage + next_capacity > max_memory_usage { ...
conditional_block
lockfree.rs
use crate::{ arenas::atomic_bucket::{AtomicBucket, AtomicBucketList}, Capacity, LassoError, LassoErrorKind, LassoResult, MemoryLimits, }; use core::{ fmt::{self, Debug}, num::NonZeroUsize, slice, str, sync::atomic::{AtomicUsize, Ordering}, }; /// An arena allocator that dynamically grows in siz...
memory_usage: AtomicUsize, max_memory_usage: AtomicUsize, } impl LockfreeArena { /// Create a new Arena with the default bucket size of 4096 bytes pub fn new(capacity: NonZeroUsize, max_memory_usage: usize) -> LassoResult<Self> { Ok(Self { // Allocate one bucket buckets:...
bucket_capacity: AtomicUsize,
random_line_split
lockfree.rs
use crate::{ arenas::atomic_bucket::{AtomicBucket, AtomicBucketList}, Capacity, LassoError, LassoErrorKind, LassoResult, MemoryLimits, }; use core::{ fmt::{self, Debug}, num::NonZeroUsize, slice, str, sync::atomic::{AtomicUsize, Ordering}, }; /// An arena allocator that dynamically grows in siz...
}
{ let arena = LockfreeArena::new(NonZeroUsize::new(1).unwrap(), 1000).unwrap(); unsafe { assert!(arena.store_str("abcdefghijklmnopqrstuvwxyz").is_ok()); } }
identifier_body
config.rs
use std::collections::HashMap; use std::fs::File; use std::io::Read; use std::net::SocketAddr; use std::ops::Range; use std::time::Duration; use clap::{app_from_crate, crate_authors, crate_description, crate_name, crate_version, value_t, Arg, SubCommand}; use toml; use serde_derive::{Deserialize, Serialize}; use raf...
else { // shold be unreachable unreachable!("clap bug?") } } else { (system, Command::Daemon) } } }
{ let c_action = value_t!(args.value_of("action"), ConsensusAction).expect("bad consensus action"); let l_action = value_t!(args.value_of("leader_action"), LeaderAction).expect("bad leader action"); (system, Command::Query(MgmtCommand::ConsensusCommand(c_action, l_action)...
conditional_block
config.rs
use std::collections::HashMap; use std::fs::File; use std::io::Read; use std::net::SocketAddr; use std::ops::Range; use std::time::Duration; use clap::{app_from_crate, crate_authors, crate_description, crate_name, crate_version, value_t, Arg, SubCommand}; use toml; use serde_derive::{Deserialize, Serialize}; use raf...
async_sockets: 4, nodes: Vec::new(), snapshot_interval: 1000, } } } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "kebab-case", default, deny_unknown_fields)] pub struct Consul { /// Start in disabled leader finding mode pub start_as: Conse...
buffer_flush_time: 0, greens: 4,
random_line_split
config.rs
use std::collections::HashMap; use std::fs::File; use std::io::Read; use std::net::SocketAddr; use std::ops::Range; use std::time::Duration; use clap::{app_from_crate, crate_authors, crate_description, crate_name, crate_version, value_t, Arg, SubCommand}; use toml; use serde_derive::{Deserialize, Serialize}; use raf...
{ Daemon, Query(MgmtCommand, String), } impl System { pub fn load() -> (Self, Command) { // This is a first copy of args - with the "config" option let app = app_from_crate!() .long_version(concat!(crate_version!(), " ", env!("VERGEN_COMMIT_DATE"), " ", env!("VERGEN_SHA_SHORT"))...
Command
identifier_name
building.rs
use std::collections::{BTreeMap, HashSet, VecDeque}; use std::fmt; use serde::{Deserialize, Serialize}; use strum::IntoEnumIterator; use strum_macros::{Display, EnumIter, EnumString}; use abstutil::{ deserialize_btreemap, deserialize_usize, serialize_btreemap, serialize_usize, Tags, }; use geom::{Distance, PolyLi...
/// Returns (biking position, sidewalk position). Could fail if the biking graph is /// disconnected. pub fn biking_connection(&self, map: &Map) -> Option<(Position, Position)> { // Easy case: the building is directly next to a usable lane if let Some(pair) = sidewalk_to_bike(self.sidewalk...
{ let lane = map .get_parent(self.sidewalk()) .find_closest_lane(self.sidewalk(), |l| PathConstraints::Car.can_use(l, map))?; // TODO Do we need to insist on this buffer, now that we can make cars gradually appear? let pos = self .sidewalk_pos .equ...
identifier_body
building.rs
use std::collections::{BTreeMap, HashSet, VecDeque}; use std::fmt; use serde::{Deserialize, Serialize}; use strum::IntoEnumIterator; use strum_macros::{Display, EnumIter, EnumString}; use abstutil::{ deserialize_btreemap, deserialize_usize, serialize_btreemap, serialize_usize, Tags, }; use geom::{Distance, PolyLi...
{ Bank, Bar, Beauty, Bike, Cafe, CarRepair, CarShare, Childcare, ConvenienceStore, Culture, Exercise, FastFood, Food, GreenSpace, Hotel, Laundry, Library, Medical, Pet, Playground, Pool, PostOffice, Religious, School, S...
AmenityType
identifier_name
building.rs
use std::collections::{BTreeMap, HashSet, VecDeque}; use std::fmt; use serde::{Deserialize, Serialize}; use strum::IntoEnumIterator; use strum_macros::{Display, EnumIter, EnumString}; use abstutil::{ deserialize_btreemap, deserialize_usize, serialize_btreemap, serialize_usize, Tags, }; use geom::{Distance, PolyLi...
return name; } &self.0[&None] } pub fn new(tags: &Tags) -> Option<NamePerLanguage> { let native_name = tags.get(osm::NAME)?; let mut map = BTreeMap::new(); map.insert(None, native_name.to_string()); for (k, v) in tags.inner() { if let Some...
random_line_split
building.rs
use std::collections::{BTreeMap, HashSet, VecDeque}; use std::fmt; use serde::{Deserialize, Serialize}; use strum::IntoEnumIterator; use strum_macros::{Display, EnumIter, EnumString}; use abstutil::{ deserialize_btreemap, deserialize_usize, serialize_btreemap, serialize_usize, Tags, }; use geom::{Distance, PolyLi...
} false } } fn sidewalk_to_bike(sidewalk_pos: Position, map: &Map) -> Option<(Position, Position)> { let lane = map .get_parent(sidewalk_pos.lane()) .find_closest_lane(sidewalk_pos.lane(), |l| { !l.biking_blackhole && PathConstraints::Bike.can_use(l, map) })?; ...
{ return true; }
conditional_block
types.rs
use super::parser::{Expr, Literal, Pattern}; #[derive(Eq, PartialEq, Debug, Clone)] pub enum Type { Int64, Int32, Float, Dataset(im::HashMap<String, Type>), /// T -> U TyArr(Box<Type>, Box<Type>), /// Type variable TyVar(String), // Data type TyCon(String), } static COUNTER: st...
(subs: Subs, subs2: Subs) -> im::HashMap<String, Type> { let mut h = im::HashMap::new(); for (key, value) in subs.into_iter() { h = h.update(key.to_string(), apply_sub_type(subs, &value.clone())); } h.union(subs2.clone()) } fn ftv_ty(ty: &Type) -> im::HashSet<String> { match ty { Ty...
compose
identifier_name
types.rs
use super::parser::{Expr, Literal, Pattern}; #[derive(Eq, PartialEq, Debug, Clone)] pub enum Type { Int64, Int32, Float, Dataset(im::HashMap<String, Type>), /// T -> U TyArr(Box<Type>, Box<Type>), /// Type variable TyVar(String), // Data type TyCon(String), } static COUNTER: st...
fn unify(ty1: &Type, ty2: &Type) -> Result<im::HashMap<String, Type>, String> { match (ty1, ty2) { (Type::TyArr(l, r), Type::TyArr(l1, r1)) => { let s1 = unify(l, l1)?; let s2 = unify(&apply_sub_type(&s1, &r), &apply_sub_type(&s1, &r1))?; Ok(compose(&s2, &s1)) ...
{ let xs = ftv_ty(ty); let ys = ftv_env(env); let a = xs.difference(ys); (a, ty.clone()) }
identifier_body
types.rs
use super::parser::{Expr, Literal, Pattern}; #[derive(Eq, PartialEq, Debug, Clone)] pub enum Type { Int64, Int32, Float, Dataset(im::HashMap<String, Type>), /// T -> U TyArr(Box<Type>, Box<Type>), /// Type variable TyVar(String), // Data type TyCon(String), } static COUNTER: st...
.iter() .map(|(k, items)| convert_inner(env, k, items)) .flatten() .collect(); if d.len() == items.len() { Ok((im::HashMap::new(), Type::Dataset(d))) } else { Err("Not all ...
let d: im::HashMap<String, Type> = items
random_line_split
util.rs
use super::{ converter::BaseConvertInfo, flags::RuntimeHelper, ir::{JsExpr as Js, VNodeIR}, parser::{Directive, DirectiveArg, ElemProp, Element}, scanner::Attribute, }; use std::{ borrow::{Borrow, BorrowMut}, cell::UnsafeCell, marker::PhantomData, ops::Deref, }; #[macro_export] macr...
} type DirFound<'a, E> = PropFound<'a, E, Directive<'a>>; // sometimes mutable access to the element is not available so // Borrow is used to refine PropFound so `take` is optional pub fn dir_finder<'a, E, P>(elem: E, pat: P) -> PropFinder<'a, E, P, Directive<'a>> where E: Borrow<Element<'a>>, P: PropPattern,...
{ pub fn take(mut self) -> M { // TODO: avoid O(n) behavior M::take(self.elem.borrow_mut().properties.remove(self.pos)) }
random_line_split
util.rs
use super::{ converter::BaseConvertInfo, flags::RuntimeHelper, ir::{JsExpr as Js, VNodeIR}, parser::{Directive, DirectiveArg, ElemProp, Element}, scanner::Attribute, }; use std::{ borrow::{Borrow, BorrowMut}, cell::UnsafeCell, marker::PhantomData, ops::Deref, }; #[macro_export] macr...
// since std::lazy::Lazy is not stable // it is not thread safe, not Sync. // it is Send if F and T is Send pub struct Lazy<T, F = fn() -> T>(UnsafeCell<Result<T, Option<F>>>) where F: FnOnce() -> T; impl<T, F> Lazy<T, F> where F: FnOnce() -> T, { pub fn new(f: F) -> Self { Self(UnsafeCell::new(E...
{ PropFinder::new(elem, pat) }
identifier_body
util.rs
use super::{ converter::BaseConvertInfo, flags::RuntimeHelper, ir::{JsExpr as Js, VNodeIR}, parser::{Directive, DirectiveArg, ElemProp, Element}, scanner::Attribute, }; use std::{ borrow::{Borrow, BorrowMut}, cell::UnsafeCell, marker::PhantomData, ops::Deref, }; #[macro_export] macr...
} impl<'a> PropMatcher<'a> for ElemProp<'a> { fn get_name_and_exp(prop: &ElemProp<'a>) -> NameExp<'a> { match prop { ElemProp::Attr(Attribute { name, value,.. }) => { let exp = value.as_ref().map(|v| v.content); Some((name, exp)) } ElemPr...
{ None }
conditional_block
util.rs
use super::{ converter::BaseConvertInfo, flags::RuntimeHelper, ir::{JsExpr as Js, VNodeIR}, parser::{Directive, DirectiveArg, ElemProp, Element}, scanner::Attribute, }; use std::{ borrow::{Borrow, BorrowMut}, cell::UnsafeCell, marker::PhantomData, ops::Deref, }; #[macro_export] macr...
<'a, E, M> where E: Borrow<Element<'a>>, M: PropMatcher<'a>, { elem: E, pos: usize, m: PhantomData<&'a M>, } impl<'a, E, M> PropFound<'a, E, M> where E: Borrow<Element<'a>>, M: PropMatcher<'a>, { fn new(elem: E, pos: usize) -> Option<Self> { Some(Self { elem, ...
PropFound
identifier_name
lib.rs
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy // SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: MIT #![cfg_attr(doc_cfg, feature(doc_cfg))] pub use anyhow::Result; use cargo_toml::{Dependency, Manifest}; use heck::AsShoutySnakeCase; use tauri_utils::{ config::Config, reso...
/// Sets the icon to use on the window. Currently only used on Windows. #[must_use] pub fn windows_attributes(mut self, windows_attributes: WindowsAttributes) -> Self { self.windows_attributes = windows_attributes; self } } /// Run all build time helpers for your Tauri Application. /// /// The curren...
{ Self::default() }
identifier_body
lib.rs
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy // SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: MIT #![cfg_attr(doc_cfg, feature(doc_cfg))] pub use anyhow::Result; use cargo_toml::{Dependency, Manifest}; use heck::AsShoutySnakeCase; use tauri_utils::{ config::Config, reso...
(mut self, windows_attributes: WindowsAttributes) -> Self { self.windows_attributes = windows_attributes; self } } /// Run all build time helpers for your Tauri Application. /// /// The current helpers include the following: /// * Generates a Windows Resource file when targeting Windows. /// /// # Platforms ...
windows_attributes
identifier_name
lib.rs
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy // SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: MIT #![cfg_attr(doc_cfg, feature(doc_cfg))] pub use anyhow::Result; use cargo_toml::{Dependency, Manifest}; use heck::AsShoutySnakeCase; use tauri_utils::{ config::Config, reso...
; let diff = features_diff( &features .into_iter() .filter(|f| all_cli_managed_features.contains(&f.as_str())) .collect::<Vec<String>>(), &expected, ); let mut error_message = String::new(); if!diff.remove.is_empty() { error_message.push_str("remove the `"); error_message.push_s...
{ config .tauri .features() .into_iter() .map(|f| f.to_string()) .collect::<Vec<String>>() }
conditional_block
lib.rs
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy // SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: MIT #![cfg_attr(doc_cfg, feature(doc_cfg))] pub use anyhow::Result; use cargo_toml::{Dependency, Manifest}; use heck::AsShoutySnakeCase; use tauri_utils::{ config::Config, reso...
.icon .iter() .find(|i| predicate(i)) .cloned() .unwrap_or_else(|| default.to_string()); icon_path.into() } let window_icon_path = attributes .windows_attributes .window_icon_path .unwrap_or_else(|| find_icon(&config, |i| i.ends_with(".ico"), "icons/icon....
.tauri .bundle
random_line_split
main.rs
use clap::{App, AppSettings, Arg, SubCommand}; use default_boxed::DefaultBoxed; #[derive(DefaultBoxed)] struct Outer<'a, 'b> { inner: HeapApp<'a, 'b>, } struct HeapApp<'a, 'b> { app: App<'a, 'b>, } impl<'a, 'b> Default for HeapApp<'a, 'b> { fn default() -> Self { let mut app = App::new("serviceus...
{ // TODO: set homedir afterwards, once the address is unmovable, or use Pin for the very first time // to allow a self-referential structure :D! let _home_dir = dirs::config_dir() .expect("configuration directory can be obtained") .join("google-service-cli"); let outer = Outer::default_...
identifier_body
main.rs
use clap::{App, AppSettings, Arg, SubCommand}; use default_boxed::DefaultBoxed; #[derive(DefaultBoxed)] struct Outer<'a, 'b> { inner: HeapApp<'a, 'b>, } struct HeapApp<'a, 'b> { app: App<'a, 'b>, } impl<'a, 'b> Default for HeapApp<'a, 'b> { fn default() -> Self { let mut app = App::new("serviceus...
{ let mcmd = SubCommand::with_name("create").about("Creates a consumer override. A consumer override is applied to the consumer on its own authority to limit its own quota usage. Consumer overrides cannot be used to grant more quota than would be allowed by admin overrides, producer overrides, or th...
let mut consumer_overrides3 = SubCommand::with_name("consumer_overrides") .setting(AppSettings::ColoredHelp) .about("methods: create, delete, list and patch");
random_line_split
main.rs
use clap::{App, AppSettings, Arg, SubCommand}; use default_boxed::DefaultBoxed; #[derive(DefaultBoxed)] struct Outer<'a, 'b> { inner: HeapApp<'a, 'b>, } struct
<'a, 'b> { app: App<'a, 'b>, } impl<'a, 'b> Default for HeapApp<'a, 'b> { fn default() -> Self { let mut app = App::new("serviceusage1_beta1") .setting(clap::AppSettings::ColoredHelp) .author("Sebastian Thiel <byronimo@gmail.com>") .version("0.1.0-20210317") ...
HeapApp
identifier_name
fmt.rs
use std::{ borrow::Cow, fmt::{self, Write as _}, io, time::Duration, }; use termcolor::{ColorSpec, WriteColor}; use unicode_width::UnicodeWidthChar; use crate::{markup, Markup, MarkupElement}; /// A stack-allocated linked-list of [MarkupElement] slices pub enum MarkupElements<'a> { Root, Node...
{ let mut adapter = SanitizeAdapter { writer: &mut buffer, error: Ok(()), }; adapter.write_str(INPUT).unwrap(); adapter.error.unwrap(); } assert_eq!(from_utf8(&buffer).unwrap(), OUTPUT); } }
const INPUT: &str = "t\tes t\r\n\u{202D}t\0es\x07t\u{202E}\nt\u{200B}es🐛t"; const OUTPUT: &str = "t\tes t\r\n\u{FFFD}t\u{FFFD}es\u{FFFD}t\u{FFFD}\nt\u{FFFD}es🐛t"; let mut buffer = Vec::new();
random_line_split
fmt.rs
use std::{ borrow::Cow, fmt::{self, Write as _}, io, time::Duration, }; use termcolor::{ColorSpec, WriteColor}; use unicode_width::UnicodeWidthChar; use crate::{markup, Markup, MarkupElement}; /// A stack-allocated linked-list of [MarkupElement] slices pub enum MarkupElements<'a> { Root, Node...
/// Write a piece of markup into this formatter pub fn write_markup(&mut self, markup: Markup) -> io::Result<()> { for node in markup.0 { let mut fmt = self.with_elements(node.elements); node.content.fmt(&mut fmt)?; } Ok(()) } /// Write a slice of text...
{ Formatter { state: MarkupElements::Node(&self.state, elements), writer: self.writer, } }
identifier_body
fmt.rs
use std::{ borrow::Cow, fmt::{self, Write as _}, io, time::Duration, }; use termcolor::{ColorSpec, WriteColor}; use unicode_width::UnicodeWidthChar; use crate::{markup, Markup, MarkupElement}; /// A stack-allocated linked-list of [MarkupElement] slices pub enum MarkupElements<'a> { Root, Node...
else { // SanitizeAdapter can only fail if the underlying // writer returns an error unreachable!() } } } }) } fn write_fmt(&mut self, elements: &MarkupElements, content: fmt::Argume...
{ adapter.error }
conditional_block
fmt.rs
use std::{ borrow::Cow, fmt::{self, Write as _}, io, time::Duration, }; use termcolor::{ColorSpec, WriteColor}; use unicode_width::UnicodeWidthChar; use crate::{markup, Markup, MarkupElement}; /// A stack-allocated linked-list of [MarkupElement] slices pub enum MarkupElements<'a> { Root, Node...
(&mut self, content: &str) -> fmt::Result { let mut buffer = [0; 4]; for item in content.chars() { // Replace non-whitespace, zero-width characters with the Unicode replacement character let is_whitespace = item.is_whitespace(); let is_zero_width = UnicodeWidthChar::...
write_str
identifier_name
serial.rs
// Copyright 2016 taskqueue developers // // Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or // http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or // http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or distributed except according ...
/// Like `Queue::foreach` but provides a mutable reference to the bound variable /// /// # Example /// /// ``` /// # use taskqueue::*; /// # let queue = SerialQueue::new(); /// let bound = queue.with(|| 2); /// let doubled: Vec<i32> = bound.foreach_with((0..20), |factor, x| x*facto...
{ self.queue.sync(move || operation(unsafe { self.binding.get_mut() })) }
identifier_body
serial.rs
// Copyright 2016 taskqueue developers // // Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or // http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or // http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or distributed except according ...
<R, F>(&self, operation: F) -> Future<R> where R: Send +'static, F: FnOnce() -> R + Send +'static { let (tx, rx) = mailbox(); let operation: Box<FnBox() + Send +'static> = Stack::assemble(self, move || { tx.send(operation()); }); debug!("Queue ({:?}...
async
identifier_name
serial.rs
// Copyright 2016 taskqueue developers // // Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or // http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or // http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or distributed except according ...
{ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "SerialQueue ({})", self.id) } } unsafe impl Send for SerialQueue {} unsafe impl Sync for SerialQueue {} impl SerialQueue { /// Create a new SerialQueue and assign it to the global thread pool pub fn new() -> SerialQueue ...
impl fmt::Debug for SerialQueue
random_line_split
main0.rs
use std::error::Error; use mio::net::{ TcpListener, TcpStream, UdpSocket}; use mio::{Events, Interest, Poll, Token}; use std::io::{Read, Write}; use hex; use rand::{thread_rng, Rng}; use keccak_hash::keccak; use secp256k1::{SecretKey, PublicKey, Message, RecoveryId, Signature, sign, recover}; use rlp::{Rlp, RlpStream};...
} else if message_type == 0x02 { // got a pong message let from_peer = PeerInfo::decode_rlp(&rlp.at(0)?)?; let hash_bytes = rlp.at(1)?.data()?; ...
println!("pong bytes is {:?}", bytes.len()); send_queue.push_back(bytes); // send_queue
random_line_split
main0.rs
use std::error::Error; use mio::net::{ TcpListener, TcpStream, UdpSocket}; use mio::{Events, Interest, Poll, Token}; use std::io::{Read, Write}; use hex; use rand::{thread_rng, Rng}; use keccak_hash::keccak; use secp256k1::{SecretKey, PublicKey, Message, RecoveryId, Signature, sign, recover}; use rlp::{Rlp, RlpStream};...
, Err(err) => { println!("read data error {:?}", err); } } } println!("client socket is writable"); } ...
{ println!("write ok"); }
conditional_block
main0.rs
use std::error::Error; use mio::net::{ TcpListener, TcpStream, UdpSocket}; use mio::{Events, Interest, Poll, Token}; use std::io::{Read, Write}; use hex; use rand::{thread_rng, Rng}; use keccak_hash::keccak; use secp256k1::{SecretKey, PublicKey, Message, RecoveryId, Signature, sign, recover}; use rlp::{Rlp, RlpStream};...
}, } } fn main() -> Result<(), Box<dyn Error>> { let mut arr = [0u8; 32]; thread_rng().fill(&mut arr[..]); // let data = vec![0x83, b'c', b'a', b't']; // let aa: String = rlp::decode(&data).unwrap(); // println!("aa = {:?}", aa); // let pk = hex::decode("ee5495585eff78f2fcf95bab21...
{ match message_type { 0x01 => { println!("ping message"); }, 0x02 => { println!("pong message"); }, 0x03 => { println!("find neighbours message"); }, 0x04 => { println!("neighbours message"); }, ...
identifier_body
main0.rs
use std::error::Error; use mio::net::{ TcpListener, TcpStream, UdpSocket}; use mio::{Events, Interest, Poll, Token}; use std::io::{Read, Write}; use hex; use rand::{thread_rng, Rng}; use keccak_hash::keccak; use secp256k1::{SecretKey, PublicKey, Message, RecoveryId, Signature, sign, recover}; use rlp::{Rlp, RlpStream};...
() -> Result<(), Box<dyn Error>> { let mut arr = [0u8; 32]; thread_rng().fill(&mut arr[..]); // let data = vec![0x83, b'c', b'a', b't']; // let aa: String = rlp::decode(&data).unwrap(); // println!("aa = {:?}", aa); // let pk = hex::decode("ee5495585eff78f2fcf95bab21ef1a598c54d1e3c672e23b3bb97...
main
identifier_name
tx.rs
use std::convert::TryInto; use std::io::Write; use clap; use bitcoin::hashes::Hash; use bitcoin; use elements::encode::{deserialize, serialize}; use elements::{ confidential, AssetIssuance, OutPoint, Transaction, TxIn, TxInWitness, TxOut, TxOutWitness, Script, }; use elements::secp256k1_zkp::{ Generator, PedersenCo...
} fn create_script_pubkey(spk: OutputScriptInfo, used_network: &mut Option<Network>) -> Script { if spk.type_.is_some() { warn!("Field \"type\" of output is ignored."); } if let Some(hex) = spk.hex { if spk.asm.is_some() { warn!("Field \"asm\" of output is ignored."); } if spk.address.is_some() { wa...
{ let has_issuance = input.has_issuance.unwrap_or(input.asset_issuance.is_some()); let is_pegin = input.is_pegin.unwrap_or(input.pegin_data.is_some()); let prevout = outpoint_from_input_info(&input); TxIn { previous_output: prevout, script_sig: input.script_sig.map(create_script_sig).unwrap_or_default(), seq...
identifier_body
tx.rs
use std::convert::TryInto; use std::io::Write; use clap; use bitcoin::hashes::Hash; use bitcoin; use elements::encode::{deserialize, serialize}; use elements::{ confidential, AssetIssuance, OutPoint, Transaction, TxIn, TxInWitness, TxOut, TxOutWitness, Script, }; use elements::secp256k1_zkp::{ Generator, PedersenCo...
(input: &InputInfo) -> OutPoint { let op1: Option<OutPoint> = input.prevout.as_ref().map(|ref op| op.parse().expect("invalid prevout format")); let op2 = match input.txid { Some(txid) => match input.vout { Some(vout) => Some(OutPoint { txid: txid, vout: vout, }), None => panic!("\"txid\" field gi...
outpoint_from_input_info
identifier_name
tx.rs
use std::convert::TryInto; use std::io::Write; use clap; use bitcoin::hashes::Hash; use bitcoin; use elements::encode::{deserialize, serialize}; use elements::{ confidential, AssetIssuance, OutPoint, Transaction, TxIn, TxInWitness, TxOut, TxOutWitness, Script, }; use elements::secp256k1_zkp::{ Generator, PedersenCo...
} else { print!("{}", hex::encode(&tx_bytes)); } } fn cmd_decode<'a>() -> clap::App<'a, 'a> { cmd::subcommand("decode", "decode a raw transaction to JSON") .args(&cmd::opts_networks()) .args(&[cmd::opt_yaml(), cmd::arg("raw-tx", "the raw transaction in hex").required(false)]) } fn exec_decode<'a>(matches: &c...
::std::io::stdout().write_all(&tx_bytes).unwrap();
random_line_split
term_gui.rs
// Copyright (c) The Swiboe development team. All rights reserved. // Licensed under the Apache License, Version 2.0. See LICENSE.txt // in the project root for license information. #[macro_use] extern crate clap; extern crate rustbox; extern crate serde_json; extern crate subsequence_match; extern crate swiboe; exter...
fn draw(&mut self, buffer_view: &buffer_views::BufferView, rustbox: &rustbox::RustBox) { let mut row = 0; let top_line_index = buffer_view.top_line_index as usize; self.cursor_id = buffer_view.cursor.id().to_string(); let mut cursor_drawn = false; while row < rustbox.height...
cursor_id: String::new(), } }
random_line_split
term_gui.rs
// Copyright (c) The Swiboe development team. All rights reserved. // Licensed under the Apache License, Version 2.0. See LICENSE.txt // in the project root for license information. #[macro_use] extern crate clap; extern crate rustbox; extern crate serde_json; extern crate subsequence_match; extern crate swiboe; exter...
, rustbox::Key::Left => { self.config_file_runner.keymap_handler.key_down( delta_t_in_seconds, keymap_handler::Key::Left); }, rustbox::Key::Right => { self.config_file_runner.keymap_handler.key_down( delta_t_in_s...
{ self.config_file_runner.keymap_handler.key_down( delta_t_in_seconds, keymap_handler::Key::Down); }
conditional_block
term_gui.rs
// Copyright (c) The Swiboe development team. All rights reserved. // Licensed under the Apache License, Version 2.0. See LICENSE.txt // in the project root for license information. #[macro_use] extern crate clap; extern crate rustbox; extern crate serde_json; extern crate subsequence_match; extern crate swiboe; exter...
{ let options = parse_options(); let mut gui = TerminalGui::new(&options).unwrap(); while gui.handle_events().unwrap() { gui.draw(); } }
identifier_body
term_gui.rs
// Copyright (c) The Swiboe development team. All rights reserved. // Licensed under the Apache License, Version 2.0. See LICENSE.txt // in the project root for license information. #[macro_use] extern crate clap; extern crate rustbox; extern crate serde_json; extern crate subsequence_match; extern crate swiboe; exter...
(&mut self, key: rustbox::Key) -> CompleterState { match key { rustbox::Key::Char(c) => { self.query.push(c); self.results.clear(); CompleterState::Running }, rustbox::Key::Backspace => { self.query.pop(); ...
on_key
identifier_name
write.rs
use std::{ cmp, convert::TryInto, io::{self, Write}, }; use byteorder::{ByteOrder, LittleEndian, WriteBytesExt}; use cgmath::prelude::*; use crate::{ prelude::*, io::{PropKind, Error, ErrorKind}, }; use super::{Encoding, RawTriangle}; // ----------------------------------------------------------...
() -> Self { Self::new(Encoding::Binary) } /// Creates a new builder instance for an ASCII STL file. /// /// **Note**: please don't use this. STL ASCII files are even more space /// inefficient than binary STL files. If you can avoid it, never use ASCII /// STL. In fact, consider not us...
binary
identifier_name
write.rs
use std::{ cmp, convert::TryInto, io::{self, Write}, }; use byteorder::{ByteOrder, LittleEndian, WriteBytesExt}; use cgmath::prelude::*; use crate::{ prelude::*, io::{PropKind, Error, ErrorKind}, }; use super::{Encoding, RawTriangle}; // ----------------------------------------------------------...
#[inline(never)] pub fn write_raw_binary( self, num_triangles: u32, triangles: impl IntoIterator<Item = Result<RawTriangle, Error>>, ) -> Result<(), Error> { let config = self.config; let mut w = self.writer; // First, a 80 bytes useless header that must no...
{ if self.config.encoding == Encoding::Ascii { self.write_raw_ascii(triangles) } else { self.write_raw_binary(num_triangles, triangles) } }
identifier_body
write.rs
use std::{ cmp, convert::TryInto, io::{self, Write}, };
use cgmath::prelude::*; use crate::{ prelude::*, io::{PropKind, Error, ErrorKind}, }; use super::{Encoding, RawTriangle}; // ---------------------------------------------------------------------------- /// The solid name used when the user didn't specify one. const DEFAULT_SOLID_NAME: &str = "mesh"; // ==...
use byteorder::{ByteOrder, LittleEndian, WriteBytesExt};
random_line_split
write.rs
use std::{ cmp, convert::TryInto, io::{self, Write}, }; use byteorder::{ByteOrder, LittleEndian, WriteBytesExt}; use cgmath::prelude::*; use crate::{ prelude::*, io::{PropKind, Error, ErrorKind}, }; use super::{Encoding, RawTriangle}; // ----------------------------------------------------------...
let mesh = src.core_mesh(); let has_normals = src.face_normal_type().is_some(); // The triangle iterator let triangles = mesh.face_handles().map(|fh| { let mut it = mesh.vertices_around_face(fh); let va = it.next().expect("bug: less than 3 vertices around face"...
{ return Err(Error::new(|| ErrorKind::DataIncomplete { prop: PropKind::VertexPosition, msg: "source does not provide vertex positions, but STL requires them".into(), })); }
conditional_block
parse.rs
::FromStr; use crate::repr::{AnchorLocation, Pattern, Repetition}; /// The entry point for this module: Parse a string into a `Pattern` that can be optimized and/or /// compiled. pub fn parse(s: &str) -> Result<Pattern, String> { let src: Vec<char> = s.chars().collect(); parse_re(ParseState::new(&src)).map(|t...
#[test] fn test_parse_res() { let case1 = ( "a(Bcd)e", Pattern::Concat(vec![ Pattern::Char('a'), Pattern::Submatch(Box::new(Pattern::Concat(vec![ Pattern::Char('B'), Pattern::Char('c'), ...
{ let case1 = ( "a(b)c", Pattern::Concat(vec![ Pattern::Char('a'), Pattern::Submatch(Box::new(Pattern::Char('b'))), Pattern::Char('c'), ]), ); let case2 = ("(b)", Pattern::Submatch(Box::new(Pattern::Char('b'))));...
identifier_body
parse.rs
str::FromStr; use crate::repr::{AnchorLocation, Pattern, Repetition}; /// The entry point for this module: Parse a string into a `Pattern` that can be optimized and/or /// compiled. pub fn parse(s: &str) -> Result<Pattern, String> { let src: Vec<char> = s.chars().collect(); parse_re(ParseState::new(&src)).map...
} else { return s.err("repetition {} without pattern to repeat", 0); } } None => return s.err("unmatched {", s.len()), }; } c => { stack.push(Patter...
if let Some(p) = stack.pop() { let rep = parse_specific_repetition(rep, p)?; stack.push(rep); s = newst;
random_line_split
parse.rs
::FromStr; use crate::repr::{AnchorLocation, Pattern, Repetition}; /// The entry point for this module: Parse a string into a `Pattern` that can be optimized and/or /// compiled. pub fn parse(s: &str) -> Result<Pattern, String> { let src: Vec<char> = s.chars().collect(); parse_re(ParseState::new(&src)).map(|t...
<'a> { /// The string to parse. This may be a substring of the "overall" matched string. src: &'a [char], /// The position within the overall string (for error reporting). pos: usize, } impl<'a> ParseState<'a> { /// new returns a new ParseState operating on the specified input string. fn new(s:...
ParseState
identifier_name
fib.rs
rev ref paren: WeakNode<I, T>, child: Node<I, T>, /// Indicate that it has lost a child marked: bool, } //////////////////////////////////////////////////////////////////////////////// //// Implementation impl<I: Debug, T: Debug> Debug for Node_<I, T> { fn fmt(&self, f: &mut std::fmt::Formatter...
(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { writeln!(f, "R({:?}) ", self)?; let mut curq = vec![(self.clone(), self.children())]; loop { let mut nxtq = vec![]; for (p, children) in curq { if children.is_empty() { bre...
fmt
identifier_name
fib.rs
rev ref paren: WeakNode<I, T>, child: Node<I, T>, /// Indicate that it has lost a child marked: bool, } //////////////////////////////////////////////////////////////////////////////// //// Implementation impl<I: Debug, T: Debug> Debug for Node_<I, T> { fn fmt(&self, f: &mut std::fmt::Formatter...
/// replace with new val, return old val fn replace_key(&self, val: T) -> T where I: Debug, T: Debug { replace(val_mut!(self), val) } fn replace(&mut self, x: Self) -> Self { let old = Self(self.0.clone()); self.0 = x.0; old } #[cfg(tes...
{ if !left!(x).is_none() { right!(left!(x).upgrade(), right!(x)); } else { debug_assert!(child!(self).rc_eq(&x)); child!(self, right!(x)); } if !right!(x).is_none() { left!(right!(x), left!(x)); } rank!(self, rank!(self) -...
identifier_body
fib.rs
rev ref paren: WeakNode<I, T>, child: Node<I, T>, /// Indicate that it has lost a child marked: bool, } //////////////////////////////////////////////////////////////////////////////// //// Implementation impl<I: Debug, T: Debug> Debug for Node_<I, T> { fn fmt(&self, f: &mut std::fmt::Formatter...
} writeln!(f, "{}>> end <<{}", "-".repeat(28), "-".repeat(28))?; Ok(()) } } impl<I: Ord + Hash + Clone + Debug, T: Ord + Clone + Debug> Clone for FibHeap<I, T> { fn clone(&self) -> Self { let len = self.len; let rcnt = self.rcnt; let mut nodes = HashMap::new(); ...
(sib.is_some()); sib = right!(sib);
conditional_block
fib.rs
while child.is_some() { res.push(child.clone()); child = right!(child); } res } /// remove paren, left and right fn purge_as_root(&self) { paren!(self, WeakNode::none()); left!(self, WeakNode::none()); right!(self, Node::none()); } ...
min = Node::none(); }
random_line_split
main.rs
use std::collections::HashMap; use std::fs::File; use std::io::{BufRead, BufReader}; const COLLECTED_ORE: u64 = 1000000000000; #[derive(Debug, Eq, PartialEq)] struct Reaction { output: (String, u64), ingredients: Vec<(String, u64)>, } type ReactionMap = HashMap<String, Reaction>; fn calc_ore(reactions: &Rea...
let used_ore = calc_ore_for_fuel(current, reactions); if used_ore < ore { lower = current; } else { upper = current; } if upper - 1 == lower { return lower; } } } fn parse_chemical(chemical: &str) -> (String, u64) { let mut ...
{ let mut lower = 1; let mut current; let mut upper = 1; // Find an upper bound to use for binary search. loop { let used_ore = calc_ore_for_fuel(upper, reactions); if used_ore < ore { upper *= 2; } else { break; } } // Binary search ...
identifier_body
main.rs
use std::collections::HashMap; use std::fs::File; use std::io::{BufRead, BufReader}; const COLLECTED_ORE: u64 = 1000000000000; #[derive(Debug, Eq, PartialEq)] struct Reaction { output: (String, u64), ingredients: Vec<(String, u64)>, } type ReactionMap = HashMap<String, Reaction>; fn calc_ore(reactions: &Rea...
() { let input = vec![String::from("7 A, 1 E => 1 FUEL")]; let reactions = parse_reactions(input.as_slice()); let result = reactions.get(&String::from("FUEL")); assert!(result.is_some()); let reaction = result.unwrap(); assert_eq!( *reaction, Rea...
test_parse
identifier_name
main.rs
use std::collections::HashMap; use std::fs::File; use std::io::{BufRead, BufReader}; const COLLECTED_ORE: u64 = 1000000000000; #[derive(Debug, Eq, PartialEq)] struct Reaction { output: (String, u64), ingredients: Vec<(String, u64)>, } type ReactionMap = HashMap<String, Reaction>; fn calc_ore(reactions: &Rea...
} fn parse_input(filename: &str) -> ReactionMap { let file = File::open(filename).expect("Failed to open file"); let reader = BufReader::new(file); let reactions: Vec<String> = reader .lines() .map(|l| l.expect("Failed to read line")) .map(|l| String::from(l.trim())) .collect()...
} reactions
random_line_split
main.rs
use std::collections::HashMap; use std::fs::File; use std::io::{BufRead, BufReader}; const COLLECTED_ORE: u64 = 1000000000000; #[derive(Debug, Eq, PartialEq)] struct Reaction { output: (String, u64), ingredients: Vec<(String, u64)>, } type ReactionMap = HashMap<String, Reaction>; fn calc_ore(reactions: &Rea...
} // Binary search to find the highest amount of fuel we can // produce without using all the ore. loop { current = (upper - lower) / 2 + lower; let used_ore = calc_ore_for_fuel(current, reactions); if used_ore < ore { lower = current; } else { ...
{ break; }
conditional_block
ecvrf.rs
// Copyright (c) The XPeer Core Contributors // SPDX-License-Identifier: Apache-2.0 //! This module implements an instantiation of a verifiable random function known as //! [ECVRF-ED25519-SHA512-TAI](https://tools.ietf.org/html/draft-irtf-cfrg-vrf-04). //! //! # Examples //! //! ``` //! use nextgen_crypto::{traits::Un...
} impl TryFrom<&[u8]> for VRFPrivateKey { type Error = CryptoMaterialError; fn try_from(bytes: &[u8]) -> std::result::Result<VRFPrivateKey, CryptoMaterialError> { Ok(VRFPrivateKey( ed25519_PrivateKey::from_bytes(bytes).unwrap(), )) } } impl TryFrom<&[u8]> for VRFPublicKey { ...
{ VRFPrivateKey(ed25519_PrivateKey::generate(rng)) }
identifier_body
ecvrf.rs
// Copyright (c) The XPeer Core Contributors // SPDX-License-Identifier: Apache-2.0 //! This module implements an instantiation of a verifiable random function known as //! [ECVRF-ED25519-SHA512-TAI](https://tools.ietf.org/html/draft-irtf-cfrg-vrf-04). //! //! # Examples //! //! ``` //! use nextgen_crypto::{traits::Un...
.result()[..], ); k_buf } pub(super) fn hash_points(points: &[EdwardsPoint]) -> ed25519_Scalar { let mut result = [0u8; 32]; let mut hash = Sha512::new().chain(&[SUITE, TWO]); for point in points.iter() { hash = hash.chain(point.compress().to_bytes()); } result[..16].copy...
random_line_split
ecvrf.rs
// Copyright (c) The XPeer Core Contributors // SPDX-License-Identifier: Apache-2.0 //! This module implements an instantiation of a verifiable random function known as //! [ECVRF-ED25519-SHA512-TAI](https://tools.ietf.org/html/draft-irtf-cfrg-vrf-04). //! //! # Examples //! //! ``` //! use nextgen_crypto::{traits::Un...
else { bail!("The proof failed to verify for this public key") } } pub(super) fn hash_to_curve(&self, alpha: &[u8]) -> EdwardsPoint { let mut result = [0u8; 32]; let mut counter = 0; let mut wrapped_point: Option<EdwardsPoint> = None; while wrapped_point.is...
{ Ok(()) }
conditional_block
ecvrf.rs
// Copyright (c) The XPeer Core Contributors // SPDX-License-Identifier: Apache-2.0 //! This module implements an instantiation of a verifiable random function known as //! [ECVRF-ED25519-SHA512-TAI](https://tools.ietf.org/html/draft-irtf-cfrg-vrf-04). //! //! # Examples //! //! ``` //! use nextgen_crypto::{traits::Un...
(bytes: &[u8]) -> std::result::Result<VRFPublicKey, CryptoMaterialError> { if bytes.len()!= ed25519_dalek::PUBLIC_KEY_LENGTH { return Err(CryptoMaterialError::WrongLengthError); } let mut bits: [u8; 32] = [0u8; 32]; bits.copy_from_slice(&bytes[..32]); let compressed...
try_from
identifier_name
parser.rs
use crate::Result; use pom::char_class::{alpha, alphanum, multispace}; use pom::parser::*; use std::str::FromStr; use std::collections::HashMap; use std::fmt::{Display, Formatter}; #[derive(Debug, Clone, PartialEq)] pub struct StateMachine { pub name: String, pub states: Vec<State>, pub accept_states: Vec<...
<'a>() -> Parser<'a, u8, Vec<State>> { fn tag_starting_state(idx: usize, state: State) -> State { State { is_starting_state: idx == 0, ..state } }; state().repeat(0..).map(|states| states.into_iter().enumerate().map(|(idx, state)| tag_starting_state(idx, state)).collec...
state_list
identifier_name
parser.rs
use crate::Result; use pom::char_class::{alpha, alphanum, multispace}; use pom::parser::*; use std::str::FromStr; use std::collections::HashMap; use std::fmt::{Display, Formatter}; #[derive(Debug, Clone, PartialEq)] pub struct StateMachine { pub name: String, pub states: Vec<State>, pub accept_states: Vec<...
#[test] fn line_counter_works() { let file_path_str = "assets/fsml/simple-state-machine.fsml"; let byte_vec: Vec<u8> = std::fs::read(file_path_str).unwrap(); let actual = count_lines(&byte_vec); assert_eq!(12, actual); } #[test] fn parse_state_machine_file() { ...
{ let line_parser = (to_eol() - eol()).repeat(0..); let parse_result = line_parser.parse(byte_slice).unwrap(); parse_result.len() }
identifier_body
parser.rs
use crate::Result; use pom::char_class::{alpha, alphanum, multispace}; use pom::parser::*; use std::str::FromStr; use std::collections::HashMap; use std::fmt::{Display, Formatter}; #[derive(Debug, Clone, PartialEq)] pub struct StateMachine { pub name: String, pub states: Vec<State>, pub accept_states: Vec<...
Err(e) => panic!("{}", e), }; println!("{:?}", parse_result); } }
{ let start_str = &byte_vec[0..position]; let line = count_lines(start_str) + 1; let end = min(position + 50, file_content.len() - 1); let extract = &file_content[position..end]; let extract = extract .to_string() ...
conditional_block
parser.rs
use crate::Result; use pom::char_class::{alpha, alphanum, multispace}; use pom::parser::*; use std::str::FromStr; use std::collections::HashMap; use std::fmt::{Display, Formatter}; #[derive(Debug, Clone, PartialEq)] pub struct StateMachine { pub name: String, pub states: Vec<State>, pub accept_states: Vec<...
fn accept_states_list<'a>() -> Parser<'a, u8, Vec<AcceptState>> { accept_states_chain() .repeat(0..) .map(|chains| chains.into_iter().flatten().collect()) } fn accept_states_chain<'a>() -> Parser<'a, u8, Vec<AcceptState>> { let raw = spaced(list(spaced(state_id()), keyword(b"->"))) - semi(); ...
} }; state().repeat(0..).map(|states| states.into_iter().enumerate().map(|(idx, state)| tag_starting_state(idx, state)).collect()) }
random_line_split
lib.rs
// (A,X,E,R,S) // // Lizzie Borden took an axe // And gave her mother forty whacks. // When she saw what she had done, // She gave her father forty-one. // #![feature(struct_variant)] #![allow(dead_code)] #![allow(uppercase_variables)] #![allow(unused_variable)] #![allow(unused_imports)] //#![allow(visible_private_typ...
let ix_opt = self.vars.iter().position(|v| { v == var }); match ix_opt { Some(ix) => { *self.vals.get_mut(ix) = val }, None => self.vals.push(val) }; } fn extend(&self, vars: Vec<String>, vals: Vec<Obj>) -> Scope { Scope{ parent: Some(box self.clone...
identifier_name
lib.rs
// (A,X,E,R,S) // // Lizzie Borden took an axe // And gave her mother forty whacks. // When she saw what she had done, // She gave her father forty-one. // #![feature(struct_variant)] #![allow(dead_code)] #![allow(uppercase_variables)] #![allow(unused_variable)] #![allow(unused_imports)] //#![allow(visible_private_typ...
e(I.vars, E, I.body); X = I.next CLOSE {vars:ref vars, body:ref body, k:ref k} => { let a = Closure { params:vars.clone(), env:E.clone(), body:body.clone() }; A = OClosure(a); k.clone() }, // case TEST : I: TEST ; X = (A == true)? I.thenc : I.elsec TEST {kthen:ref kthen, kelse:ref kelse} => { let...
case CLOSE : I: CLOSE ; A = Closur
conditional_block
lib.rs
// (A,X,E,R,S) // // Lizzie Borden took an axe // And gave her mother forty whacks. // When she saw what she had done, // She gave her father forty-one. // #![feature(struct_variant)] #![allow(dead_code)] #![allow(uppercase_variables)] #![allow(unused_variable)] #![allow(unused_imports)] //#![allow(visible_private_typ...
S: Frame } impl VMState { fn make(a:Obj, x:Code, e:Scope, r:Vec<Obj>, s:Frame) -> VMState { VMState { A:a, X:x, E:e, R:r, S:s } } fn accumulator(&self) -> &Obj { &self.A } fn program(&self) -> &Code { &self.X } fn environment(&self) -> &Scope { &self.E } fn ...
// control stack (ptr to top call frame; frames have link to prev frame)
random_line_split
nvg.rs
//! NanoVG is small antialiased vector graphics rendering library with a lean //! API modeled after the HTML5 Canvas API. It can be used to draw gauge //! instruments in MSFS. See `Gauge::create_nanovg`. use crate::sys; type Result = std::result::Result<(), Box<dyn std::error::Error>>; /// A NanoVG render context. p...
(self) -> sys::NVGwinding { match self { Direction::Clockwise => sys::NVGwinding_NVG_CW, Direction::CounterClockwise => sys::NVGwinding_NVG_CCW, } } } #[derive(Debug)] #[doc(hidden)] pub enum PaintOrColor { Paint(Paint), Color(Color), } impl From<Paint> for PaintOrC...
to_sys
identifier_name