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
stack.rs
// Copyright 2017-2018 the authors. See the 'Copyright and license' section of the // README.md file at the top-level directory of this repository. // // Licensed under the Apache License, Version 2.0 (the LICENSE-APACHE file) or // the MIT license (the LICENSE-MIT file) at your option. This file may not be // copied, ...
loop { let candidate = num_obj + 1; // total_hdr_size = size of header, post-header padding, and stack let total_hdr_size = stack_begin_offset + Stack::<usize>::bytes_for(candidate); // Padding between the pointer stack and the array of objects. NOTE: ...
let stack_begin_offset = hdr_size + pre_stack_padding; // Find the largest number of objects we can fit in the slab. array_begin_offset is the // offset from the beginning of the slab of the array of objects. let (mut num_obj, mut array_begin_offset) = (0, 0);
random_line_split
stack.rs
// Copyright 2017-2018 the authors. See the 'Copyright and license' section of the // README.md file at the top-level directory of this repository. // // Licensed under the Apache License, Version 2.0 (the LICENSE-APACHE file) or // the MIT license (the LICENSE-MIT file) at your option. This file may not be // copied, ...
else { break; } } if num_obj == 0 { return None; } assert!(array_begin_offset > 0); let unused_space = slab_size - array_begin_offset - (num_obj * obj_size); let l = Layout { num_obj: num_obj, layout: layou...
{ num_obj = candidate; array_begin_offset = total_hdr_size + post_stack_padding; }
conditional_block
stack.rs
// Copyright 2017-2018 the authors. See the 'Copyright and license' section of the // README.md file at the top-level directory of this repository. // // Licensed under the Apache License, Version 2.0 (the LICENSE-APACHE file) or // the MIT license (the LICENSE-MIT file) at your option. This file may not be // copied, ...
} pub struct SlabHeader { stack: Stack<usize>, // note: this is only the metadata; the real stack comes after this header color: Color, // extra padding added before array beginning next: Option<NonNull<SlabHeader>>, prev: Option<NonNull<SlabHeader>>, } impl Linkable for SlabHeader { fn ne...
{ unsafe { let slab = self.data.ptr_to_slab(self.alloc.layout().size(), obj); let was_empty = (*slab.as_ptr()).stack.size() == 0; let stack_data_ptr = self.layout.stack_begin(slab); (*slab.as_ptr()) .stack .push(stack_data_ptr, I::...
identifier_body
text.rs
use std::cmp::max; use std::collections::HashMap; use std::string::ToString; use sdl2::pixels::Color; use sdl2::rect::Rect; use sdl2::render::{BlendMode, Canvas, Texture, TextureCreator, WindowCanvas}; use sdl2::surface::Surface; use sdl2::ttf::Font as Sdl2Font; use sdl2::video::WindowContext; use crate::ui::types::{...
total_width += w; total_height = h; } else { return Err(format!("Unsupported character: {}", c)); } } let mut font_canvas = Surface::new( total_width, total_height, texture_creator.default_pixel...
{ let mut total_width = 0; let mut total_height = 0; let mut glyphs: Vec<GlyphRegion> = Vec::new(); let mut space_advance = 0; for c in ASCII.chars() { if let Some(metric) = font.find_glyph_metrics(c) { let (w, h) = font.size_of_char(c).map_err(to_str...
identifier_body
text.rs
use std::cmp::max; use std::collections::HashMap; use std::string::ToString; use sdl2::pixels::Color; use sdl2::rect::Rect; use sdl2::render::{BlendMode, Canvas, Texture, TextureCreator, WindowCanvas}; use sdl2::surface::Surface; use sdl2::ttf::Font as Sdl2Font; use sdl2::video::WindowContext; use crate::ui::types::{...
line_height: total_height, space_advance, texture_creator, cached_texts: HashMap::new(), }) } pub fn draw(&mut self, screen_txt: ScreenText, cvs: &mut WindowCanvas) -> Result<(), String> { let cache_key = screen_txt.text.to_string(); if l...
font_canvas: font_canvas, glyphs,
random_line_split
text.rs
use std::cmp::max; use std::collections::HashMap; use std::string::ToString; use sdl2::pixels::Color; use sdl2::rect::Rect; use sdl2::render::{BlendMode, Canvas, Texture, TextureCreator, WindowCanvas}; use sdl2::surface::Surface; use sdl2::ttf::Font as Sdl2Font; use sdl2::video::WindowContext; use crate::ui::types::{...
(scale_factor: f32, w: u32, h: u32) -> (u32, u32) { ( (w as f32 * scale_factor).round() as u32, (h as f32 * scale_factor).round() as u32, ) } fn align_line_horizontal(a: Align, line_width: u32, text_width: u32) -> i32 { match a { Align::TopLeft => 0, Align::MidCenter => (tex...
scale_dim
identifier_name
text.rs
use std::cmp::max; use std::collections::HashMap; use std::string::ToString; use sdl2::pixels::Color; use sdl2::rect::Rect; use sdl2::render::{BlendMode, Canvas, Texture, TextureCreator, WindowCanvas}; use sdl2::surface::Surface; use sdl2::ttf::Font as Sdl2Font; use sdl2::video::WindowContext; use crate::ui::types::{...
else { return Err(format!("Unsupported character: {}", c)); } } let mut font_canvas = Surface::new( total_width, total_height, texture_creator.default_pixel_format(), )? .into_canvas()?; let font_texture_creator = ...
{ let (w, h) = font.size_of_char(c).map_err(to_string)?; glyphs.push(GlyphRegion { start: total_width as i32, width: w, height: h, advance: metric.advance, }); if c == ' ' { ...
conditional_block
common.rs
use std::collections::HashSet; pub type PlayerId = usize; /// Represent a player during a game. #[derive(Serialize, Clone, Debug, PartialEq)] pub struct Player { /// An integer that uniquely identifies each player during a game pub id: PlayerId, /// Number of tiles the player currently owns #[serde(s...
Up, Down, } #[derive(Copy, Clone, Debug, PartialEq)] /// Outcome of a move pub enum MoveOutcome { /// Outcome when a move resulted in a general being captured. The player ID is the ID of the /// defeated player. GeneralCaptured(PlayerId), /// Outcome when a move resulted in an open tile or a ci...
Right, Left,
random_line_split
common.rs
use std::collections::HashSet; pub type PlayerId = usize; /// Represent a player during a game. #[derive(Serialize, Clone, Debug, PartialEq)] pub struct Player { /// An integer that uniquely identifies each player during a game pub id: PlayerId, /// Number of tiles the player currently owns #[serde(s...
InvalidMove::SourceTileNotOwned => { "the source tile does not belong to the player making the move" } } } fn cause(&self) -> Option<&Error> { None } } impl fmt::Display for InvalidMove { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { ...
{ "the source tile is either a mountain or not on the map" }
conditional_block
common.rs
use std::collections::HashSet; pub type PlayerId = usize; /// Represent a player during a game. #[derive(Serialize, Clone, Debug, PartialEq)] pub struct Player { /// An integer that uniquely identifies each player during a game pub id: PlayerId, /// Number of tiles the player currently owns #[serde(s...
(&mut self, player: PlayerId) { let was_visible = self.visible_by.remove(&player); if was_visible { self.dirty_for.insert(player); } } /// Mark the tile as visible for the given player, updating the source and destination tiles /// state if necessary (number of units, ow...
hide_from
identifier_name
common.rs
use std::collections::HashSet; pub type PlayerId = usize; /// Represent a player during a game. #[derive(Serialize, Clone, Debug, PartialEq)] pub struct Player { /// An integer that uniquely identifies each player during a game pub id: PlayerId, /// Number of tiles the player currently owns #[serde(s...
// The attacker has more units. Capture the tile. else { dst.units = self.units - 1 - dst.units; dst.owner = self.owner; // We're capturing a general if dst.kind == TileKind::General { ...
{ if self.is_mountain() { return Err(InvalidMove::FromInvalidTile); } if dst.is_mountain() { return Err(InvalidMove::ToInvalidTile); } if self.units() < 2 { return Err(InvalidMove::NotEnoughUnits); } let attacker = self.owner.ok...
identifier_body
from_str.rs
use fen4::{Position, PositionParseError}; use std::str::FromStr; use crate::types::*; use thiserror::Error; #[derive(Error, PartialEq, Clone, Debug)] pub enum MoveError { #[error("Basic move is malformed.")] Other, #[error("A move starts with O-O, but is not a correct type of move.")] Castle, #[e...
(string: &str) -> Result<(Turn, &str), IntermediateError> { use IntermediateError::*; let trimmed = string.trim_start(); let dot_loc = trimmed.find('.').ok_or(TurnNumber(trimmed.len()))?; let (number_str, dots) = trimmed.split_at(dot_loc); let number = if number_str == "" { 0 } else { ...
parse_turn
identifier_name
from_str.rs
use fen4::{Position, PositionParseError}; use std::str::FromStr; use crate::types::*; use thiserror::Error; #[derive(Error, PartialEq, Clone, Debug)] pub enum MoveError { #[error("Basic move is malformed.")] Other, #[error("A move starts with O-O, but is not a correct type of move.")] Castle, #[e...
_ => Normal(string.parse::<BasicMove>()?), }) } } struct MovePair { main: Move, modifier: Option<Move>, stalemate: bool, } impl FromStr for MovePair { type Err = MoveError; fn from_str(string: &str) -> Result<Self, Self::Err> { let mut stalemate = false; le...
{ let mateless = s.trim_end_matches('#'); let mates = s.len() - mateless.len(); match mateless { "O-O-O" => QueenCastle(mates), "O-O" => KingCastle(mates), _ => return Err(MoveError::Castle), } ...
conditional_block
from_str.rs
use fen4::{Position, PositionParseError}; use std::str::FromStr; use crate::types::*; use thiserror::Error; #[derive(Error, PartialEq, Clone, Debug)] pub enum MoveError { #[error("Basic move is malformed.")] Other, #[error("A move starts with O-O, but is not a correct type of move.")] Castle, #[e...
}, rest, )) } fn parse_turn(string: &str) -> Result<(Turn, &str), IntermediateError> { use IntermediateError::*; let trimmed = string.trim_start(); let dot_loc = trimmed.find('.').ok_or(TurnNumber(trimmed.len()))?; let (number_str, dots) = trimmed.split_at(dot_loc); let number =...
alternatives,
random_line_split
base.rs
/// Returns a human readable name of the object kind. /// /// This is also used in alternate formatting: /// /// ```rust /// # use symbolic_debuginfo::ObjectKind; /// assert_eq!(format!("{:#}", ObjectKind::Executable), ObjectKind::Executable.human_name()); /// ``` pub fn human_name(...
} /// A dynamically dispatched iterator over items with the given lifetime. pub type DynIterator<'a, T> = Box<dyn Iterator<Item = T> + 'a>; /// A stateful session for interfacing with debug information. /// /// Debug sessions can be obtained via [`ObjectLike::debug_session`]. Since computing a session may /// be a c...
{ f.debug_struct("Function") .field("address", &format_args!("{:#x}", self.address)) .field("size", &format_args!("{:#x}", self.size)) .field("name", &self.name) .field( "compilation_dir", &String::from_utf8_lossy(self.compilation_d...
identifier_body
base.rs
} /// Returns a human readable name of the object kind. /// /// This is also used in alternate formatting: /// /// ```rust /// # use symbolic_debuginfo::ObjectKind; /// assert_eq!(format!("{:#}", ObjectKind::Executable), ObjectKind::Executable.human_name()); /// ``` pub fn human_na...
impl<'data> FileInfo<'data> { /// Creates a `FileInfo` with a given directory and the file name. #[cfg(feature = "dwarf")] pub fn new(dir: Cow<'data, [u8]>, name: Cow<'data, [u8]>) -> Self { FileInfo { name, dir } } /// Creates a `FileInfo` from a joined path by trying to split it. #[cf...
/// Path to the file. dir: Cow<'data, [u8]>, }
random_line_split
base.rs
/// Returns a human readable name of the object kind. /// /// This is also used in alternate formatting: /// /// ```rust /// # use symbolic_debuginfo::ObjectKind; /// assert_eq!(format!("{:#}", ObjectKind::Executable), ObjectKind::Executable.human_name()); /// ``` pub fn human_name(...
(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("FileInfo") .field("compilation_dir", &self.compilation_dir_str()) .field("name", &self.name_str()) .field("dir", &self.dir_str()) .finish() } } impl<'data> Deref for FileEntry<'data> { type ...
fmt
identifier_name
mod.rs
_codec::{Decode, Encode}; use sp_consensus_grandpa::{AuthorityId, AuthorityWeight, SetId}; use sp_core::H256; use sp_runtime::traits::{Block as BlockT, Header, NumberFor}; use sp_runtime::EncodedJustification; pub use types::{AuthoritySet, AuthoritySetChange}; #[derive(Encode, Decode, Clone, PartialEq, Serialize, Des...
items: &[(&[u8], &[u8])], // &[(key, value)] ) -> Result<()> { let checker = StorageProofChecker::<T::Hashing>::new(state_root, proof)?; for (k, v) in items { let actual_value = checker .read_value(k)? .ok_or_else(|| anyhow::Error::msg(Error::Storage...
proof: StorageProof,
random_line_split
mod.rs
::{Decode, Encode}; use sp_consensus_grandpa::{AuthorityId, AuthorityWeight, SetId}; use sp_core::H256; use sp_runtime::traits::{Block as BlockT, Header, NumberFor}; use sp_runtime::EncodedJustification; pub use types::{AuthoritySet, AuthoritySetChange}; #[derive(Encode, Decode, Clone, PartialEq, Serialize, Deseriali...
} type BridgeId = u64; pub trait Config: frame_system::Config<Hash = H256> { type Block: BlockT<Hash = H256, Header = Self::Header>; } impl Config for chain::Runtime { type Block = chain::Block; } #[derive(Encode, Decode, Clone, Serialize, Deserialize)] pub struct LightValidation<T: Config> { num_bridg...
{ BridgeInfo { last_finalized_block_header: block_header, current_set: validator_set, } }
identifier_body
mod.rs
::{Decode, Encode}; use sp_consensus_grandpa::{AuthorityId, AuthorityWeight, SetId}; use sp_core::H256; use sp_runtime::traits::{Block as BlockT, Header, NumberFor}; use sp_runtime::EncodedJustification; pub use types::{AuthoritySet, AuthoritySetChange}; #[derive(Encode, Decode, Clone, PartialEq, Serialize, Deseriali...
( &mut self, block_header: T::Header, validator_set: AuthoritySet, proof: StorageProof, ) -> Result<BridgeId> { let state_root = block_header.state_root(); Self::check_validator_set_proof(state_root, proof, &validator_set.list, validator_set.id) .map_err(a...
initialize_bridge
identifier_name
codegen.rs
use super::*; use crate::ops::cast::cast; use crate::ops::math::add; use crate::ops::matmul::lir_unary::{ AddMatMulGeometry, LirMatMulUnary, MapOutputAxisToInput, ProtoFusedSpec, }; use crate::ops::matmul::mir_quant::{ combine_scales, compensate_zero_points, requant, wire_offset_u8_as_i8, }; use crate::ops::mat...
( op: &EinSum, model: &TypedModel, node: &TypedNode, (_, k_axis, _): (&Axis, &Axis, &Axis), ) -> TractResult<Option<TypedModelPatch>> { let name = &node.name; let mut patch = TypedModelPatch::new("Dequantizing einsum"); let taps = patch.taps(model, &node.inputs)?; let [a, b, bias, mut a0...
dequant
identifier_name
codegen.rs
use super::*; use crate::ops::cast::cast; use crate::ops::math::add; use crate::ops::matmul::lir_unary::{ AddMatMulGeometry, LirMatMulUnary, MapOutputAxisToInput, ProtoFusedSpec, }; use crate::ops::matmul::mir_quant::{ combine_scales, compensate_zero_points, requant, wire_offset_u8_as_i8, }; use crate::ops::mat...
else { non_trivial_k_axis.get(0).copied().or_else(|| candidate_k_axes.get(0)).copied() }; let Some(k_axis) = k_axis else { return Ok(AxesOrPatch::Patch(inject_k_axis(op, model, node)?)); }; let m_axis = op .axes .iter_all_axes() .filter(|a| { a.inputs[0]...
{ // TODO: handle case where multiple consecutive k in the same order in both input. bail!("Multiple k-axis candidate found"); }
conditional_block
codegen.rs
use super::*; use crate::ops::cast::cast; use crate::ops::math::add; use crate::ops::matmul::lir_unary::{ AddMatMulGeometry, LirMatMulUnary, MapOutputAxisToInput, ProtoFusedSpec, }; use crate::ops::matmul::mir_quant::{ combine_scales, compensate_zero_points, requant, wire_offset_u8_as_i8, }; use crate::ops::mat...
// TODO: handle case where multiple consecutive k in the same order in both input. bail!("Multiple k-axis candidate found"); } else { non_trivial_k_axis.get(0).copied().or_else(|| candidate_k_axes.get(0)).copied() }; let Some(k_axis) = k_axis else { return Ok(AxesOrPatch::Pat...
{ let input_facts = model.node_input_facts(node.id)?; let input_shapes: TVec<&[TDim]> = input_facts.iter().map(|f| &*f.shape).collect(); let output_shape = super::eval::output_shape(&op.axes, &input_shapes); let candidate_k_axes: TVec<&Axis> = op .axes .iter_all_axes() // Filter ...
identifier_body
codegen.rs
use super::*; use crate::ops::cast::cast; use crate::ops::math::add; use crate::ops::matmul::lir_unary::{ AddMatMulGeometry, LirMatMulUnary, MapOutputAxisToInput, ProtoFusedSpec, }; use crate::ops::matmul::mir_quant::{ combine_scales, compensate_zero_points, requant, wire_offset_u8_as_i8, }; use crate::ops::mat...
)?[0]; } } let a = wire_offset_u8_as_i8(&mut patch, &node.name, a, "a", &mut a0, "a0")?; let b = wire_offset_u8_as_i8(&mut patch, &node.name, b, "b", &mut b0, "b0")?; let mut output = patch.wire_node( &node.name, EinSum { q_params: None, axes...
for i in 1..(output_rank - q_axis_in_output) { a_scale = patch.wire_node( format!("{name}.a_scale_axis_fix_{i}"), AxisOp::Add(i), &[a_scale],
random_line_split
game.rs
use std::convert::TryFrom; use hdk::{ utils, entry_definition::ValidatingEntryType, error::{ZomeApiResult, ZomeApiError}, holochain_persistence_api::{ cas::content::{AddressableContent, Address}, }, holochain_json_api::{ error::JsonError, json::JsonString, }, holochain_co...
let new_state = moves.iter().fold(GameState::initial(), move |state, new_move| state.evolve(game.clone(), new_move)); Ok(new_state) /* get_state_local_chain is similar to get_state function. It takes local_chain and game_address as parameters and return the GameState. * we first get all the moves assoc...
let game = get_game_local_chain(local_chain, game_address)?;
random_line_split
game.rs
use std::convert::TryFrom; use hdk::{ utils, entry_definition::ValidatingEntryType, error::{ZomeApiResult, ZomeApiError}, holochain_persistence_api::{ cas::content::{AddressableContent, Address}, }, holochain_json_api::{ error::JsonError, json::JsonString, }, holochain_co...
(game_address: &Address) -> ZomeApiResult<Vec<Move>> { match hdk::get_links(game_address, LinkMatch::Any, LinkMatch::Any)?.addresses().into_iter().next() { /* get links returns the ZomeApiResult<GetLinksResult>. * This will get entries that are linked to the first argument. * Since ZomeApi...
get_moves
identifier_name
game.rs
use std::convert::TryFrom; use hdk::{ utils, entry_definition::ValidatingEntryType, error::{ZomeApiResult, ZomeApiError}, holochain_persistence_api::{ cas::content::{AddressableContent, Address}, }, holochain_json_api::{ error::JsonError, json::JsonString, }, holochain_co...
else { None } }) .next() .ok_or(ZomeApiError::HashNotFound) /* get_game_local_chain() gets all the Entry in the local_chain as well as the address of the game and will return ZomeApiResult<Game>. * now we will call the iter() method on the local_chain so that ...
{ Some(Game::try_from(entry_data.clone()).unwrap()) }
conditional_block
game.rs
use std::convert::TryFrom; use hdk::{ utils, entry_definition::ValidatingEntryType, error::{ZomeApiResult, ZomeApiError}, holochain_persistence_api::{ cas::content::{AddressableContent, Address}, }, holochain_json_api::{ error::JsonError, json::JsonString, }, holochain_co...
None => { false }, } } /* In this match operator, we first cater to Some(first_move). The name is first_move because * the Game entry is always linked to the first_move made by Player 2. * S...
{ match hdk::get_links(game_address, LinkMatch::Any, LinkMatch::Any)?.addresses().into_iter().next() { /* get links returns the ZomeApiResult<GetLinksResult>. * This will get entries that are linked to the first argument. * Since ZomeApiResult returns Result<T, ZomeApiError>(where T in thi...
identifier_body
server.rs
use crate::adapter::Adapter; use crate::socket::{ subscribe_socket_to_transport_events, Callback, Socket, SocketCloseReason, SocketEvent, }; use crate::transport::{Transport, TransportCreateData, TransportKind}; use crate::util::{HttpMethod, RequestContext, SendPacketError, ServerError, SetCookie}; use dashmap::Das...
pub fn try_subscribe( &self, ) -> Result<bmrng::RequestReceiver<ServerEvent, Packet>, AlreadySubscribedError> { let mut state = self.state.lock().unwrap(); let old_state = std::mem::replace(&mut *state, ServerState::Subscribed); match old_state { ServerState::Subscr...
{ self.try_subscribe() .expect("Already subscribed to engine_io_server::Server") }
identifier_body
server.rs
use crate::adapter::Adapter; use crate::socket::{ subscribe_socket_to_transport_events, Callback, Socket, SocketCloseReason, SocketEvent, }; use crate::transport::{Transport, TransportCreateData, TransportKind}; use crate::util::{HttpMethod, RequestContext, SendPacketError, ServerError, SetCookie}; use dashmap::Das...
// TODO: or drop the whole thing. The server, the sockets, everything. todo!(); // for socket in self.clients.iter() { // socket.value().close(true); // } } pub async fn close_socket(&self, connection_id: &str) { if let Some((_key, socket)) = self.clients.rem...
// TODO: consider sending signals or dropping channels instead of closing them like this?
random_line_split
server.rs
use crate::adapter::Adapter; use crate::socket::{ subscribe_socket_to_transport_events, Callback, Socket, SocketCloseReason, SocketEvent, }; use crate::transport::{Transport, TransportCreateData, TransportKind}; use crate::util::{HttpMethod, RequestContext, SendPacketError, ServerError, SetCookie}; use dashmap::Das...
( &self, sid: Option<&String>, upgrade: bool, transport_kind: TransportKind, http_method: HttpMethod, ) -> Result<(), ServerError> { if let Some(sid) = sid { let client = self.clients.get(sid); if let Some(client) = client { let...
verify_request
identifier_name
id.rs
pub fn bug(name: impl AsRef<str>) -> usize { let name = name.as_ref().to_lowercase(); match BUGS.iter().position(|&other| other == name) { Some(index) => index, _ => panic!("bug '{}' has no id yet", name), } } pub fn fish(name: impl AsRef<str>) -> usize { let name = name.as_ref().to_l...
pub fn art(name: impl AsRef<str>) -> usize { let name = name.as_ref().to_lowercase(); match ART.iter().position(|&other| other == name) { Some(index) => index, _ => panic!("art '{}' has no id yet", name), } } pub fn villager(name: impl AsRef<str>) -> usize { let name = name.as_ref()....
{ let name = name.as_ref().to_lowercase(); match FLOWERS.iter().position(|&other| other == name) { Some(index) => index, _ => panic!("flower '{}' has no id yet", name), } }
identifier_body
id.rs
pub fn bug(name: impl AsRef<str>) -> usize { let name = name.as_ref().to_lowercase(); match BUGS.iter().position(|&other| other == name) { Some(index) => index, _ => panic!("bug '{}' has no id yet", name), } } pub fn fish(name: impl AsRef<str>) -> usize { let name = name.as_ref().to_l...
(name: impl AsRef<str>) -> usize { let name = name.as_ref().to_lowercase(); match ART.iter().position(|&other| other == name) { Some(index) => index, _ => panic!("art '{}' has no id yet", name), } } pub fn villager(name: impl AsRef<str>) -> usize { let name = name.as_ref().to_lowercase...
art
identifier_name
id.rs
pub fn bug(name: impl AsRef<str>) -> usize { let name = name.as_ref().to_lowercase(); match BUGS.iter().position(|&other| other == name) { Some(index) => index, _ => panic!("bug '{}' has no id yet", name), } } pub fn fish(name: impl AsRef<str>) -> usize { let name = name.as_ref().to_lo...
"black cosmos", "white tulips", "red tulips", "yellow tulips", "pink tulips", "orange tulips", "purple tulips", "black tulips", "yellow pansies", "red pansies", "white pansies", "orange pansies", "purple pansies", "blue pansies", "white roses", "red roses"...
"white cosmos", "yellow cosmos", "pink cosmos", "orange cosmos",
random_line_split
main.rs
use std::f64::consts::PI; use clap::*; use gre::*; use noise::*; use rand::Rng; use svg::node::element::path::Data; use svg::node::element::*; #[derive(Parser)] #[clap()] pub struct Opts { #[clap(short, long, default_value = "image.svg")] file: String, #[clap(short, long, default_value = "100.0")] pub width: ...
a += rng.gen_range(-0.5, 0.5) * rng.gen_range(0.0, 1.0); } } rng.shuffle(&mut positions); let disp = rng.gen_range(0.5, 3.0); let mut eagles = Vec::new(); for p in positions { if rng.gen_bool(0.2) { continue; } let scale = rng.gen_range(0.3, 0.5); let p = ( p.0 + disp ...
if p.0 < pad || p.0 > width - pad || p.1 < pad || p.1 > height - pad { break; } p = (p.0 + amp * a.cos(), p.1 + amp * a.sin()); positions.push(p);
random_line_split
main.rs
use std::f64::consts::PI; use clap::*; use gre::*; use noise::*; use rand::Rng; use svg::node::element::path::Data; use svg::node::element::*; #[derive(Parser)] #[clap()] pub struct Opts { #[clap(short, long, default_value = "image.svg")] file: String, #[clap(short, long, default_value = "100.0")] pub width: ...
fn eagle<R: Rng>( origin: (f64, f64), scale: f64, rotation: f64, xreverse: bool, rng: &mut R, ) -> Vec<Vec<(f64, f64)>> { let xmul = if xreverse { -1.0 } else { 1.0 }; let count = 2 + (scale * 3.0) as usize; let mut routes: Vec<Vec<(f64, f64)>> = Vec::new(); let shaking = scale * 0.1; // body ...
{ path .iter() .map(|&(x, y)| { let dx = rng.gen_range(-scale, scale); let dy = rng.gen_range(-scale, scale); (x + dx, y + dy) }) .collect() }
identifier_body
main.rs
use std::f64::consts::PI; use clap::*; use gre::*; use noise::*; use rand::Rng; use svg::node::element::path::Data; use svg::node::element::*; #[derive(Parser)] #[clap()] pub struct
{ #[clap(short, long, default_value = "image.svg")] file: String, #[clap(short, long, default_value = "100.0")] pub width: f64, #[clap(short, long, default_value = "150.0")] pub height: f64, #[clap(short, long, default_value = "5.0")] pub pad: f64, #[clap(short, long, default_value = "0.0")] pub se...
Opts
identifier_name
main.rs
use std::f64::consts::PI; use clap::*; use gre::*; use noise::*; use rand::Rng; use svg::node::element::path::Data; use svg::node::element::*; #[derive(Parser)] #[clap()] pub struct Opts { #[clap(short, long, default_value = "image.svg")] file: String, #[clap(short, long, default_value = "100.0")] pub width: ...
else { rng.gen_range(-3.0, 3.0) }; let spread1 = 1.0 + rng.gen_range(0.0, 1.0) * rng.gen_range(0.0, 1.0); let spread2 = 1.0 + rng.gen_range(0.0, 1.0) * rng.gen_range(0.0, 1.0); let offset1 = rng.gen_range(-1.0, 0.6) * rng.gen_range(0.0, 1.0); let offset2 = rng.gen_range(-1.0, 0.6) * rng.gen_range(0.0, 1....
{ -dx1 }
conditional_block
leetcode.rs
//! The common data structure definition for leetcode problems. /** The definition of `ListNode`, used by many problems. */ #[derive(PartialEq, Eq, Debug)] pub(crate) struct ListNode { val: i32, next: Option<Box<Self>>, } impl ListNode { #[inline] fn new(val: i32) -> Self { Self { next: None, val } } } ...
{ val: i32, left: Option<Rc<RefCell<Self>>>, right: Option<Rc<RefCell<Self>>>, } impl TreeNode { #[inline] fn new(val: i32) -> Self { TreeNode { val, left: None, right: None, } } #[inline] fn new_option(val: Option<i32>) -> Option<Rc<RefCell<Self>>> { val.map(|v| Rc::new...
TreeNode
identifier_name
leetcode.rs
//! The common data structure definition for leetcode problems. /** The definition of `ListNode`, used by many problems. */ #[derive(PartialEq, Eq, Debug)] pub(crate) struct ListNode { val: i32, next: Option<Box<Self>>, } impl ListNode { #[inline] fn new(val: i32) -> Self { Self { next: None, val } } } ...
} } count == 1 } /// Check element content equivalence without element order. fn check_element_eq<T>(v1: T, v2: T) -> bool where T: IntoIterator, T::Item: Eq + std::hash::Hash + std::fmt::Debug, { use std::collections::HashMap; let (mut length1, mut length2) = (0, 0); let (mut content1, mut conten...
{ return false; }
conditional_block
leetcode.rs
//! The common data structure definition for leetcode problems. /** The definition of `ListNode`, used by many problems. */ #[derive(PartialEq, Eq, Debug)] pub(crate) struct ListNode { val: i32, next: Option<Box<Self>>, } impl ListNode { #[inline] fn new(val: i32) -> Self { Self { next: None, val } } } ...
mod q87_scramble_string; mod q89_gray_code; mod q8_my_atoi; mod q90_subsets_ii; mod q91_decode_ways; mod q92_reverse_linked_list_ii; mod q93_restore_ip_addresses; mod q94_binary_tree_inorder_traversal; mod q95_unique_binary_search_trees_ii; mod q96_unique_binary_search_trees; mod q97_interleaving_string; mod q98_valida...
mod q84_largest_rectangle_in_histogram; mod q85_maximal_rectangle; mod q86_partition_list;
random_line_split
lib.rs
#![no_std] //! //! You can populate [`Petnames`] with your own word lists, but the word lists //! from upstream [petname](https://github.com/dustinkirkland/petname) are //! included with the `default_dictionary` feature (enabled by default). See //! [`Petnames::small`], [`Petnames::medium`], and [`Petnames::large`] to ...
<RNG>(&'a self, rng: &'a mut RNG, words: u8, separator: &str) -> Names<'a, RNG> where RNG: rand::Rng, { Names { petnames: self, rng, words, separator: separator.to_string() } } /// Iterator yielding unique – i.e. non-repeating – petnames. /// /// # Examples /// /// ```ru...
iter
identifier_name
lib.rs
#![no_std] //! //! You can populate [`Petnames`] with your own word lists, but the word lists //! from upstream [petname](https://github.com/dustinkirkland/petname) are //! included with the `default_dictionary` feature (enabled by default). See //! [`Petnames::small`], [`Petnames::medium`], and [`Petnames::large`] to ...
{ self.adjectives.to_mut().retain(|word| predicate(word)); self.adverbs.to_mut().retain(|word| predicate(word)); self.names.to_mut().retain(|word| predicate(word)); } /// Calculate the cardinality of this `Petnames`. /// /// If this is low, names may be repeated by the gener...
/// the adjectives, adverbs, and names lists. /// pub fn retain<F>(&mut self, mut predicate: F) where F: FnMut(&str) -> bool,
random_line_split
lib.rs
#![no_std] //! //! You can populate [`Petnames`] with your own word lists, but the word lists //! from upstream [petname](https://github.com/dustinkirkland/petname) are //! included with the `default_dictionary` feature (enabled by default). See //! [`Petnames::small`], [`Petnames::medium`], and [`Petnames::large`] to ...
size_hint(&self) -> (usize, Option<usize>) { let remains = match self { Self::Adverb(n) => (n + 3) as usize, Self::Adjective => 2, Self::Name => 1, Self::Done => 0, }; (remains, Some(remains)) } } /// Iterator yielding petnames. pub struct N...
let list = match self { Self::Adjective => Some(List::Adjective), Self::Adverb(_) => Some(List::Adverb), Self::Name => Some(List::Name), Self::Done => None, }; self.advance(); list } fn
identifier_body
main.rs
// main struggle problems in this section were 11 and 18, and to some extent, 12 and 14. 17 was annoying to debug, but not hard. extern crate timings_proc_macro; use timings_proc_macro::timings; #[timings] fn
() { let s: Vec<usize> = std::fs::read_to_string("src/e11.txt") .unwrap() .split_whitespace() .map(|n| n.parse::<usize>().unwrap()) .collect(); //println!("{:?}", s); // could just run with s, but let's build our 2d array. let mut v = [[0; 20]; 20]; (0..400).for_each(|i| ...
e11
identifier_name
main.rs
// main struggle problems in this section were 11 and 18, and to some extent, 12 and 14. 17 was annoying to debug, but not hard. extern crate timings_proc_macro; use timings_proc_macro::timings; #[timings] fn e11() { let s: Vec<usize> = std::fs::read_to_string("src/e11.txt") .unwrap() .split_whitespa...
/// traverse the triangle picking the greatest value at the next binary choice #[allow(dead_code)] fn e18_naive_r(t: &[Vec<usize>], running_sum: usize, last_index: usize) -> usize { if t.is_empty() { running_sum } else { let (rs, li) = if t[0][last_index] > t[0][last_index + 1] { (t[...
let triangle: Vec<Vec<usize>> = std::fs::read_to_string("src/e18.txt") .unwrap() .lines() .map(|l| { l.split_whitespace() .into_iter() .map(|n| n.parse::<usize>().unwrap()) .collect::<Vec<usize>>() }) .collect(); ...
identifier_body
main.rs
// main struggle problems in this section were 11 and 18, and to some extent, 12 and 14. 17 was annoying to debug, but not hard. extern crate timings_proc_macro; use timings_proc_macro::timings; #[timings] fn e11() { let s: Vec<usize> = std::fs::read_to_string("src/e11.txt") .unwrap() .split_whitespa...
else { let mut p_left = path.clone(); p_left.push((t[0][last_index], last_index)); let left = peek_ahead_r( &t[1..], running_sum + t[0][last_index], last_index, peek_dist - 1, first_step.clone().unwrap_or(Dir::Left).into(), ...
// if tie: prefer rightward motion, THIS IS A (temporarily acceptable) BUG if t[0][last_index] > t[0][last_index + 1] { path.push((t[0][last_index], last_index)); ( t[0][last_index] + running_sum, first_step.unwrap_or(Dir::Left), ...
conditional_block
main.rs
// main struggle problems in this section were 11 and 18, and to some extent, 12 and 14. 17 was annoying to debug, but not hard. extern crate timings_proc_macro; use timings_proc_macro::timings; #[timings] fn e11() { let s: Vec<usize> = std::fs::read_to_string("src/e11.txt") .unwrap() .split_whitespa...
} } } #[timings] fn e13() { let s: Vec<String> = std::fs::read_to_string("src/e13.txt") .unwrap() .split_whitespace() .map(|s| s.parse::<String>().unwrap()) .collect(); let s13: Vec<usize> = s .iter() .map(|l| l[..13].parse::<usize>().unwrap()) .coll...
random_line_split
tabs.rs
// Copyright 2016 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable...
} } /// Adds a new view to an existing editor instance. #[allow(unreachable_code, unused_variables, dead_code)] fn add_view(&mut self, view_id: &str, buffer_id: BufferIdentifier) { panic!("add_view should not currently be accessible"); let editor = self.buffers.get(&buffer_id)...
{ // TODO: we should be reporting errors to the client // (if this is even an error? we treat opening a non-existent file as a new buffer, // but set the editor's path) print_err!("unable to read file: {}, error: {:?}", buffer_id, err); self...
conditional_block
tabs.rs
// Copyright 2016 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable...
self.buffers.remove(&buf_id); if let Some(path) = path { self.open_files.remove(&path); } } } fn do_save(&mut self, view_id: &str, file_path: &str) -> Option<Value> { let buffer_id = self.views.get(view_id) .expect(&format!("missing...
(editor.has_views(), editor.get_path().map(PathBuf::from)) }; if !has_views {
random_line_split
tabs.rs
// Copyright 2016 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable...
<P: AsRef<Path>>(&self, path: P) -> io::Result<String> { let mut f = File::open(path)?; let mut s = String::new(); f.read_to_string(&mut s)?; Ok(s) } fn close_view(&mut self, view_id: &str) { let buf_id = self.views.remove(view_id).expect("missing buffer id when clos...
read_file
identifier_name
tabs.rs
// Copyright 2016 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable...
fn close_view(&mut self, view_id: &str) { let buf_id = self.views.remove(view_id).expect("missing buffer id when closing view"); let (has_views, path) = { let editor = self.buffers.get(&buf_id).expect("missing editor when closing view"); let mut editor = editor.lock().u...
{ let mut f = File::open(path)?; let mut s = String::new(); f.read_to_string(&mut s)?; Ok(s) }
identifier_body
features.rs
use bio::io::{bed, gff}; use bio::utils::Strand; use bio::utils::Strand::*; use crate::lib::{Config, ConfigFeature}; use crate::lib::{Database, GeneNameEachReference, GeneNameTree, Region}; use rocks::rocksdb::*; use std::collections::HashMap; use std::error::Error; use std::fs::File; use std::io::{BufRead, BufReader};...
Ok(rec) => match rec.feature_type() { "gene" => { let reg = match opt_strand_to_opt_bool(rec.strand()) { Some(false) => Region { path: rec.seqname().to_string(), stop: *rec.start(), ...
for record in reader.records() { index += 1; match record {
random_line_split
features.rs
use bio::io::{bed, gff}; use bio::utils::Strand; use bio::utils::Strand::*; use crate::lib::{Config, ConfigFeature}; use crate::lib::{Database, GeneNameEachReference, GeneNameTree, Region}; use rocks::rocksdb::*; use std::collections::HashMap; use std::error::Error; use std::fs::File; use std::io::{BufRead, BufReader};...
( record: bed::Record, coord_map: &CoordToNodeId, bed_id: u64, chr_prefix: &Option<String>, ) -> HashMap<u64, Feature> { let mut hash_map: HashMap<u64, Feature> = HashMap::new(); let chr = match *chr_prefix { Some(ref k) => record.chrom().replace(k, ""), None => record.chrom().to...
record_to_nodes
identifier_name
v0.rs
<CompressionCaches<'tcx>>>, binders: Vec<BinderLevel>, out: String, } impl SymbolMangler<'tcx> { fn push(&mut self, s: &str) { self.out.push_str(s); } /// Push a `_`-terminated base 62 integer, using the format /// specified in the RFC as `<base-62-number>`, that is: /// * `x = 0` ...
// Replace `-` with `_`. if let Some(c) = punycode_bytes.iter_mut().rfind(|&&mut c| c == b'-') { *c = b'_'; } // FIXME(eddyb) avoid rechecking UTF-8 validity. punycode_string = String::from_utf8(punycode_bytes).unwrap(); &punycode_...
{ let mut use_punycode = false; for b in ident.bytes() { match b { b'_' | b'a'..=b'z' | b'A'..=b'Z' | b'0'..=b'9' => {} 0x80..=0xff => use_punycode = true, _ => bug!("symbol_names: bad byte {} in ident {:?}", b, ident), } } ...
identifier_body
v0.rs
Box<CompressionCaches<'tcx>>>, binders: Vec<BinderLevel>, out: String, } impl SymbolMangler<'tcx> { fn push(&mut self, s: &str) { self.out.push_str(s); } /// Push a `_`-terminated base 62 integer, using the format /// specified in the RFC as `<base-62-number>`, that is: /// * `x = ...
self = self.print_def_path(def_id, &[])?; } ty::FnPtr(sig) => { self.push("F"); self = self.in_binder(&sig, |mut cx, sig| { if sig.unsafety == hir::Unsafety::Unsafe { cx.push("U"); } ...
} ty::Foreign(def_id) => {
random_line_split
v0.rs
<CompressionCaches<'tcx>>>, binders: Vec<BinderLevel>, out: String, } impl SymbolMangler<'tcx> { fn push(&mut self, s: &str) { self.out.push_str(s); } /// Push a `_`-terminated base 62 integer, using the format /// specified in the RFC as `<base-62-number>`, that is: /// * `x = 0` ...
( mut self, predicates: &'tcx ty::List<ty::ExistentialPredicate<'tcx>>, ) -> Result<Self::DynExistential, Self::Error> { for predicate in predicates { match *predicate { ty::ExistentialPredicate::Trait(trait_ref) => { // Use a type that can't a...
print_dyn_existential
identifier_name
v0.rs
<CompressionCaches<'tcx>>>, binders: Vec<BinderLevel>, out: String, } impl SymbolMangler<'tcx> { fn push(&mut self, s: &str) { self.out.push_str(s); } /// Push a `_`-terminated base 62 integer, using the format /// specified in the RFC as `<base-62-number>`, that is: /// * `x = 0` ...
// FIXME(eddyb) avoid rechecking UTF-8 validity. punycode_string = String::from_utf8(punycode_bytes).unwrap(); &punycode_string } else { ident }; let _ = write!(self.out, "{}", ident.len()); // Write a separating `_` if necessary (leadi...
{ *c = b'_'; }
conditional_block
executor.rs
//! The executor runs on all nodes and is resonsible for reconciling the requested state (from the //! cluster's master), and the locally running containers. //! //! When a new state is received, it queries Docker Engine to see if: //! 1) any scheduled containers are not currently running //! 2) and running containers ...
{ state: ClusterState, node_id: NodeId, system: sysinfo::System, } impl Executor { fn join<S: ToSocketAddrs>( &mut self, join_host: S, local_port: u16, ) -> impl Future<Item = (), Error = Error> { let join_host = join_host.to_socket_addrs().unwrap().next().unwrap();...
Executor
identifier_name
executor.rs
//! The executor runs on all nodes and is resonsible for reconciling the requested state (from the //! cluster's master), and the locally running containers. //! //! When a new state is received, it queries Docker Engine to see if: //! 1) any scheduled containers are not currently running //! 2) and running containers ...
} None => Err(err_msg("Master unknown.")), } } } /// Message requesting resource usage of the local node pub struct GetNodeResources; impl Message for GetNodeResources { type Result = Result<NodeResources, Error>; } impl Handler<GetNodeResources> for Executor { type Resul...
{ Ok(Some(master.cluster_address)) }
conditional_block
executor.rs
//! The executor runs on all nodes and is resonsible for reconciling the requested state (from the //! cluster's master), and the locally running containers. //! //! When a new state is received, it queries Docker Engine to see if: //! 1) any scheduled containers are not currently running //! 2) and running containers ...
.map(move |_| info!("Image already pulled: {:?}", image)) .or_else(move |_| { docker.images().pull(&pull_opts).for_each(|p| { debug!("Pull: {:?}", p); Ok(()) }) }) .and_th...
.inspect()
random_line_split
messages.rs
//! Structures for some of the messages used in the Marionette protocol, these can //! be used with the traits in serde to convert into the corresponding json. //! #![allow(non_snake_case)] use std::fmt; use std::path::Path; use std::collections::HashMap; use serde::{Serialize, Serializer, Deserialize, Deserializer}; ...
{ focus: bool, element: Option<String>, } impl FrameSwitch { /// Switch to the top level frame pub fn top(focus: bool) -> Self { FrameSwitch { focus: focus, element: None, } } /// Switch to the frame given by passed element pub fn from_element(focus...
FrameSwitch
identifier_name
messages.rs
//! Structures for some of the messages used in the Marionette protocol, these can //! be used with the traits in serde to convert into the corresponding json. //! #![allow(non_snake_case)] use std::fmt; use std::path::Path; use std::collections::HashMap; use serde::{Serialize, Serializer, Deserialize, Deserializer}; ...
/// Switch to the frame given by passed element pub fn from_element(focus: bool, element: Option<ElementRef>) -> Self { FrameSwitch { focus: focus, element: element.map(|elem| elem.reference.to_owned()), } } } #[derive(Serialize, Debug)] pub struct AddonInstall<'a> {...
random_line_split
rpc.rs
//! Types related the `ActorRef` Remote Procedure Call (RPC) mechanism. //! //! RPC is implemented by sending a [`RpcMessage`] to the actor, which contains //! the request message and a [`RpcResponse`]. The `RpcResponse` allows the //! receiving actor to send back a response to the sending actor. //! //! To support RPC...
//! [`from_message`]: crate::from_message //! //! # Examples //! //! Using RPC to communicate with another actor. //! //! ``` //! # #![feature(never_type)] //! # //! use heph::actor; //! use heph::actor_ref::{ActorRef, RpcMessage}; //! use heph::rt::{self, Runtime, ThreadLocal}; //! use heph::spawn::ActorOptions; //! u...
//!
random_line_split
rpc.rs
//! Types related the `ActorRef` Remote Procedure Call (RPC) mechanism. //! //! RPC is implemented by sending a [`RpcMessage`] to the actor, which contains //! the request message and a [`RpcResponse`]. The `RpcResponse` allows the //! receiving actor to send back a response to the sending actor. //! //! To support RPC...
<Req, Res> { /// The request object. pub request: Req, /// A way to [`respond`] to the call. /// /// [`respond`]: RpcResponse::respond pub response: RpcResponse<Res>, } impl<Req, Res> RpcMessage<Req, Res> { /// Convenience method to handle a `Req`uest and return a `Res`ponse. /// //...
RpcMessage
identifier_name
rpc.rs
//! Types related the `ActorRef` Remote Procedure Call (RPC) mechanism. //! //! RPC is implemented by sending a [`RpcMessage`] to the actor, which contains //! the request message and a [`RpcResponse`]. The `RpcResponse` allows the //! receiving actor to send back a response to the sending actor. //! //! To support RPC...
} /// Structure to respond to an [`Rpc`] request. #[derive(Debug)] pub struct RpcResponse<Res> { sender: Sender<Res>, } impl<Res> RpcResponse<Res> { /// Respond to a RPC request. pub fn respond(self, response: Res) -> Result<(), SendError> { self.sender.try_send(response).map_err(|_| SendError) ...
{ if self.response.is_connected() { let response = f(self.request); self.response.respond(response) } else { // If the receiving actor is no longer waiting we can skip the // request. Ok(()) } }
identifier_body
build.rs
use std::{ env, fs::{self, File}, io::Write, path::{Path, PathBuf}, process::{self, Command}, }; use toml::Value; let target = env::var("TARGET").expect("TARGET not set"); let (firmware, expected_target) = if cfg!(feature =...
let out_dir = PathBuf::from(env::var("OUT_DIR").expect("OUT_DIR not set")); let kernel = PathBuf::from(match env::var("KERNEL") { Ok(kernel) => kernel, Err(_) => { eprintln!( "The KERNEL environment variable must be set for building the bootl...
{ panic!( "The {} bootloader must be compiled for the `{}` target.", firmware, expected_target, ); }
conditional_block
build.rs
use std::{ env, fs::{self, File}, io::Write, path::{Path, PathBuf}, process::{self, Command}, }; use toml::Value; let target = env::var("TARGET").expect("TARGET not set"); let (firmware, expected_target) = if cfg!(feature =...
; impl serde::de::Visitor<'_> for AlignedAddressVisitor { type Value = AlignedAddress; fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { write!( formatter, "a page-aligned memory address, either as integer or as decimal or he...
AlignedAddressVisitor
identifier_name
build.rs
use std::{ env, fs::{self, File}, io::Write, path::{Path, PathBuf}, process::{self, Command}, }; use toml::Value; let target = env::var("TARGET").expect("TARGET not set"); let (firmware, expected_target) = if cfg!(feature ...
// Parse configuration from the kernel's Cargo.toml let config = match env::var("KERNEL_MANIFEST") { Err(env::VarError::NotPresent) => { panic!("The KERNEL_MANIFEST environment variable must be set for building the bootloader.\n\n\ Please use `cargo builder` ...
kernel_file_name ); }
random_line_split
state.rs
use std::collections::HashMap; use num_traits::{AsPrimitive, Float}; use sdl2::{ keyboard::Keycode, pixels::Color, rect::{Point, Rect}, render::Canvas, video::Window, }; use crate::{ ext::ColorExt, key_state_handler::KeyStateHandler, map::Map, math::vector::Vec2D, WINDOW_HEIGHT, WINDOW_WID...
pub fn mouse_motion(&mut self, dx: i32) { self.angle += MOUSE_SENSITIVITY * dx as f64; } fn calculate_collisions(&mut self) { let mut current_angle = self.angle - (self.fov.to_radians() / 2.); let end_angle = current_angle + (self.radian_per_column * self.resolution as f64); ...
{ self.wall_colors.get(index).copied().unwrap_or(Color::WHITE) }
identifier_body
state.rs
use std::collections::HashMap; use num_traits::{AsPrimitive, Float}; use sdl2::{ keyboard::Keycode, pixels::Color, rect::{Point, Rect}, render::Canvas, video::Window, }; use crate::{ ext::ColorExt, key_state_handler::KeyStateHandler, map::Map, math::vector::Vec2D, WINDOW_HEIGHT, WINDOW_WID...
pub fn update(&mut self) { self.update_camera(); self.calculate_collisions(); } pub fn draw_minimap( &self, canvas: &mut Canvas<Window>, dims: (f64, f64), ) -> Result<(), String> { let minimap_offset = (dims.0.max(dims.1) / 4.); let minimap_base =...
self.position.add_x_y_raw(delta.x_y()); self.position.clamp(self.map.dims, PLAYER_WALL_PADDING); }
random_line_split
state.rs
use std::collections::HashMap; use num_traits::{AsPrimitive, Float}; use sdl2::{ keyboard::Keycode, pixels::Color, rect::{Point, Rect}, render::Canvas, video::Window, }; use crate::{ ext::ColorExt, key_state_handler::KeyStateHandler, map::Map, math::vector::Vec2D, WINDOW_HEIGHT, WINDOW_WID...
} if max_height.is_infinite() { self.columns.push((0, 0)); } else { self.columns .push((wall_color_index, max_height.round() as u32)); } current_angle += self.radian_per_column; } } fn updat...
{ let raw_distance = ray.dist(&intersection_vector); let delta = current_angle - self.angle; let corrected_distance = raw_distance * (delta.cos() as f64); let projected_height = self.projection_factor / corrected_distance; ...
conditional_block
state.rs
use std::collections::HashMap; use num_traits::{AsPrimitive, Float}; use sdl2::{ keyboard::Keycode, pixels::Color, rect::{Point, Rect}, render::Canvas, video::Window, }; use crate::{ ext::ColorExt, key_state_handler::KeyStateHandler, map::Map, math::vector::Vec2D, WINDOW_HEIGHT, WINDOW_WID...
(&self, canvas: &mut Canvas<Window>) -> Result<(), String> { self.render_frame(canvas)?; self.draw_minimap(canvas, (WINDOW_WIDTH as f64 / 5., WINDOW_WIDTH as f64 / 5.))?; Ok(()) } }
draw
identifier_name
opdb.rs
/* @author: xiao cai niao @datetime: 2019/11/6 */ use actix_web::{web}; use crate::webroute::route::{HostInfo, PostUserInfo, EditInfo, EditMainTain}; use crate::storage::rocks::{DbInfo, KeyValue, CfNameTypeCode, PrefixTypeCode}; use crate::ha::procotol::{DownNodeCheck, RecoveryInfo, ReplicationState, MysqlMonitorStatus...
pub cluster_name: String, pub delay: usize } impl SlaveBehindSetting{ pub fn new(cluster_name: &String) -> SlaveBehindSetting { SlaveBehindSetting{ cluster_name: cluster_name.clone(), delay: 100 } } pub fn save(&self, db: &web::Data<DbInfo>) -> Result<(), Box<dyn Error>>{ db.prefix_put...
eCode::NodesState.get())?; Ok(()) } } /// /// /// slave behind 配置结构体 #[derive(Serialize, Deserialize, Debug)] pub struct SlaveBehindSetting{
conditional_block
opdb.rs
/* @author: xiao cai niao @datetime: 2019/11/6 */ use actix_web::{web}; use crate::webroute::route::{HostInfo, PostUserInfo, EditInfo, EditMainTain}; use crate::storage::rocks::{DbInfo, KeyValue, CfNameTypeCode, PrefixTypeCode}; use crate::ha::procotol::{DownNodeCheck, RecoveryInfo, ReplicationState, MysqlMonitorStatus...
ata: web::Data<DbInfo>, info: &web::Json<HostInfo>) -> Result<(), Box<dyn Error>> { let check_unique = data.get(&info.host, &CfNameTypeCode::HaNodesInfo.get()); match check_unique { Ok(v) => { if v.value.len() > 0 { let a = format!("this key: ({}) already exists in the databa...
sert_mysql_host_info(d
identifier_name
opdb.rs
/* @author: xiao cai niao @datetime: 2019/11/6 */ use actix_web::{web}; use crate::webroute::route::{HostInfo, PostUserInfo, EditInfo, EditMainTain}; use crate::storage::rocks::{DbInfo, KeyValue, CfNameTypeCode, PrefixTypeCode}; use crate::ha::procotol::{DownNodeCheck, RecoveryInfo, ReplicationState, MysqlMonitorStatus...
} self.update_time = crate::timestamp(); } /// /// 获取当前节点在db中保存的状态信息 pub fn get_state(&self, db: &web::Data<DbInfo>) -> Result<MysqlState, Box<dyn Error>> { let kv = db.get(&self.host, &CfNameTypeCode::NodesState.get())?; if kv.value.len() > 0 { let state: My...
if info.maintain == "true".to_string() { self.maintain = false; }else { self.maintain = true;
random_line_split
opdb.rs
/* @author: xiao cai niao @datetime: 2019/11/6 */ use actix_web::{web}; use crate::webroute::route::{HostInfo, PostUserInfo, EditInfo, EditMainTain}; use crate::storage::rocks::{DbInfo, KeyValue, CfNameTypeCode, PrefixTypeCode}; use crate::ha::procotol::{DownNodeCheck, RecoveryInfo, ReplicationState, MysqlMonitorStatus...
ult 3306 pub rtype: String, //db、route pub cluster_name: String, //集群名称,route类型默认default pub online: bool, //db是否在线, true、false pub insert_time: i64, pub update_time: i64, pub maintain: bool, //是否处于维护模式,true、false } impl HostInfoValue { pub fn new(info: &HostInfo) -> Result<HostInfoVal...
o.password.clone(), hook_id: rand_string(), create_time, update_time } } } /// /// /// /// 节点基础信息, host做为key #[derive(Serialize, Deserialize, Debug, Clone)] pub struct HostInfoValue { pub host: String, //127.0.0.1:3306 pub dbport: usize, //defa
identifier_body
conn.rs
// Copyright 2016 The Grin Developers // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agree...
<W: ser::Writeable>(&self, t: Type, body: &W) -> Result<(), Error> { let mut body_data = vec![]; try!(ser::serialize(&mut body_data, body)); let mut data = vec![]; try!(ser::serialize( &mut data, &MsgHeader::new(t, body_data.len() as u64), )); data.append(&mut body_data); self.outbound_chan .unb...
send_msg
identifier_name
conn.rs
// Copyright 2016 The Grin Developers // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agree...
let (conn, fut) = Connection::listen(conn, move |sender, header: MsgHeader, data| { let msg_type = header.msg_type; let recv_h = try!(handler.handle(sender, header, data)); let mut expects = exp.lock().unwrap(); let filtered = expects .iter() .filter(|&&(typ, h, _): &&(Type, Option<Hash>, Instant...
// Decorates the handler to remove the "subscription" from the expected // responses. We got our replies, so no timeout should occur. let exp = expects.clone();
random_line_split
conn.rs
// Copyright 2016 The Grin Developers // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agree...
} /// A higher level connection wrapping the TcpStream. Maintains the amount of /// data transmitted and deals with the low-level task of sending and /// receiving data, parsing message headers and timeouts. #[allow(dead_code)] pub struct Connection { // Channel to push bytes to the remote peer outbound_chan: Unbou...
{ self(sender, header, body) }
identifier_body
conn.rs
// Copyright 2016 The Grin Developers // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agree...
Ok(reader) }) }); Box::new(read_msg) } /// Utility function to send any Writeable. Handles adding the header and /// serialization. pub fn send_msg<W: ser::Writeable>(&self, t: Type, body: &W) -> Result<(), Error> { let mut body_data = vec![]; try!(ser::serialize(&mut body_data, body)); let mu...
{ debug!(LOGGER, "Invalid {:?} message: {}", msg_type, e); return Err(Error::Serialization(e)); }
conditional_block
client.rs
use std::thread; use std::net::SocketAddr; use std::net::ToSocketAddrs; use std::sync::mpsc; use std::sync::Arc; use futures; use futures::Future; use futures::stream::Stream; use tokio_core; use tokio_core::reactor; use solicit::http::HttpScheme; use solicit::http::HttpError; use solicit::http::Header; use solicit:...
fn data_frame(&mut self, chunk: Vec<u8>) -> bool { self.tr.data_frame(chunk) } fn trailers(&mut self, headers: Vec<StaticHeader>) -> bool { self.tr.trailers(headers) } fn end(&mut self) { self.tr.end() } } // Data sent from event loop to GrpcClient struct LoopToClien...
}
random_line_split
client.rs
use std::thread; use std::net::SocketAddr; use std::net::ToSocketAddrs; use std::sync::mpsc; use std::sync::Arc; use futures; use futures::Future; use futures::stream::Stream; use tokio_core; use tokio_core::reactor; use solicit::http::HttpScheme; use solicit::http::HttpError; use solicit::http::Header; use solicit:...
<Req : Send +'static, Resp : Send +'static>(&self, req: GrpcStreamSend<Req>, method: Arc<MethodDescriptor<Req, Resp>>) -> GrpcFutureSend<Resp> { stream_single_send(self.call_impl(req, method)) } pub fn call_bidi<Req : Send +'static, Resp : Send +'static>(&self, req: GrpcStreamSend<Req>, met...
call_client_streaming
identifier_name
client.rs
use std::thread; use std::net::SocketAddr; use std::net::ToSocketAddrs; use std::sync::mpsc; use std::sync::Arc; use futures; use futures::Future; use futures::stream::Stream; use tokio_core; use tokio_core::reactor; use solicit::http::HttpScheme; use solicit::http::HttpError; use solicit::http::Header; use solicit:...
} // Event loop entry point fn run_client_event_loop( socket_addr: SocketAddr, send_to_back: mpsc::Sender<LoopToClient>) { // Create an event loop. let mut lp = reactor::Core::new().unwrap(); // Create a channel to receive shutdown signal. let (shutdown_tx, shutdown_rx) = tokio_core::channel...
{ // ignore error because even loop may be already dead self.loop_to_client.shutdown_tx.send(()).ok(); // do not ignore errors because we own event loop thread self.thread_join_handle.take().expect("handle.take") .join().expect("join thread"); }
identifier_body
fixed.rs
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may...
<T>(_col: &PrimitiveArray<T>) -> usize where T: ArrowPrimitiveType, T::Native: FixedLengthEncoding, { T::Native::ENCODED_LEN } /// Fixed width types are encoded as /// /// - 1 byte `0` if null or `1` if valid /// - bytes of [`FixedLengthEncoding`] pub fn encode<T: FixedLengthEncoding, I: IntoIterator<Item ...
encoded_len
identifier_name
fixed.rs
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may...
fn encode(self) -> [u8; 8] { // https://github.com/rust-lang/rust/blob/9c20b2a8cc7588decb6de25ac6a7912dcef24d65/library/core/src/num/f32.rs#L1176-L1260 let s = self.to_bits() as i64; let val = s ^ (((s >> 63) as u64) >> 1) as i64; val.encode() } fn decode(encoded: Self::Enc...
impl FixedLengthEncoding for f64 { type Encoded = [u8; 8];
random_line_split
fixed.rs
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may...
to_write[1..].copy_from_slice(encoded.as_ref()) } else { data[*offset] = null_sentinel(opts); } *offset = end_offset; } } pub fn encode_fixed_size_binary( data: &mut [u8], offsets: &mut [usize], array: &FixedSizeBinaryArray, opts: SortOptions, ) { ...
{ // Flip bits to reverse order encoded.as_mut().iter_mut().for_each(|v| *v = !*v) }
conditional_block
fixed.rs
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may...
fn decode(encoded: Self::Encoded) -> Self { encoded[0]!= 0 } } macro_rules! encode_signed { ($n:expr, $t:ty) => { impl FixedLengthEncoding for $t { type Encoded = [u8; $n]; fn encode(self) -> [u8; $n] { let mut b = self.to_be_bytes(); ...
{ [self as u8] }
identifier_body
mod.rs
// Copyright (c) The Starcoin Core Contributors // SPDX-License-Identifier: Apache-2.0 // Copyright (c) The Libra Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::{ account_address::AccountAddress, account_config::stc_type_tag, block_metadata::BlockMetadata, contract_event::Contract...
( sender: AccountAddress, sequence_number: u64, script: Script, max_gas_amount: u64, gas_unit_price: u64, expiration_time: Duration, ) -> Self { RawUserTransaction { sender, sequence_number, payload: TransactionPayload::Scri...
new_script
identifier_name
mod.rs
// Copyright (c) The Starcoin Core Contributors // SPDX-License-Identifier: Apache-2.0 // Copyright (c) The Libra Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::{ account_address::AccountAddress, account_config::stc_type_tag, block_metadata::BlockMetadata, contract_event::Contract...
expiration_time: Duration, } // TODO(#1307) fn serialize_duration<S>(d: &Duration, serializer: S) -> std::result::Result<S::Ok, S::Error> where S: ser::Serializer, { serializer.serialize_u64(d.as_secs()) } fn deserialize_duration<'de, D>(deserializer: D) -> std::result::Result<Duration, D::Error> where ...
// A transaction that doesn't expire is represented by a very large value like // u64::max_value(). #[serde(serialize_with = "serialize_duration")] #[serde(deserialize_with = "deserialize_duration")]
random_line_split
mod.rs
// Copyright (c) The Starcoin Core Contributors // SPDX-License-Identifier: Apache-2.0 // Copyright (c) The Libra Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::{ account_address::AccountAddress, account_config::stc_type_tag, block_metadata::BlockMetadata, contract_event::Contract...
pub fn sender(&self) -> AccountAddress { self.raw_txn.sender } pub fn into_raw_transaction(self) -> RawUserTransaction { self.raw_txn } pub fn sequence_number(&self) -> u64 { self.raw_txn.sequence_number } pub fn payload(&self) -> &TransactionPayload { &s...
{ &self.raw_txn }
identifier_body
config.rs
// Copyright 2019 Twitter, Inc. // Licensed under the Apache License, Version 2.0 // http://www.apache.org/licenses/LICENSE-2.0 use crate::common::*; use clap::{App, Arg, ArgMatches}; use logger::*; use std::collections::{HashMap, HashSet}; use std::fs::File; use std::io::{BufRead, BufReader}; use std::net::SocketAddr...
(&self, pkey: &str) -> bool { self.data.get(pkey).is_some() } /// Remove a `pkey`+`lkey` pub fn remove(&mut self, pkey: &str, lkey: &str) { if let Some(entry) = self.data.get_mut(pkey) { entry.remove(lkey); } } /// Remove the `pkey` and all `lkey`s under it ...
contains_pkey
identifier_name
config.rs
// Copyright 2019 Twitter, Inc. // Licensed under the Apache License, Version 2.0 // http://www.apache.org/licenses/LICENSE-2.0 use crate::common::*; use clap::{App, Arg, ArgMatches}; use logger::*; use std::collections::{HashMap, HashSet}; use std::fs::File; use std::io::{BufRead, BufReader}; use std::net::SocketAddr...
/// the timeout for sampler execution pub fn sampler_timeout(&self) -> Duration { self.sampler_timeout } /// maximum consecutive sampler timeouts pub fn max_sampler_timeouts(&self) -> usize { self.max_sampler_timeouts } /// get listen address pub fn listen(&self) -> S...
{ self.sample_rate }
identifier_body
config.rs
// Copyright 2019 Twitter, Inc. // Licensed under the Apache License, Version 2.0 // http://www.apache.org/licenses/LICENSE-2.0 use crate::common::*; use clap::{App, Arg, ArgMatches}; use logger::*; use std::collections::{HashMap, HashSet}; use std::fs::File; use std::io::{BufRead, BufReader}; use std::net::SocketAddr...
else { None }; let sample_rate = parse_float_arg(&matches, "sample-rate").unwrap_or(DEFAULT_SAMPLE_RATE_HZ); let sampler_timeout = Duration::from_millis( parse_numeric_arg(&matches, "sampler-timeout") .unwrap_or(DEFAULT_SAMPLER_TIMEOUT_MILLISE...
{ let socket = sock.parse().unwrap_or_else(|_| { println!("ERROR: memcache address is malformed"); process::exit(1); }); Some(socket) }
conditional_block
config.rs
// Copyright 2019 Twitter, Inc. // Licensed under the Apache License, Version 2.0 // http://www.apache.org/licenses/LICENSE-2.0 use crate::common::*; use clap::{App, Arg, ArgMatches}; use logger::*; use std::collections::{HashMap, HashSet}; use std::fs::File; use std::io::{BufRead, BufReader}; use std::net::SocketAddr...
} /// helper function to discover the number of hardware threads pub fn hardware_threads() -> Result<usize, ()> { let path = "/sys/devices/system/cpu/present"; let f = File::open(path).map_err(|e| error!("failed to open file ({:?}): {}", path, e))?; let mut f = BufReader::new(f); let mut line = String...
}) })
random_line_split
tag.rs
//! Utilities and constants for OpenType tags. //! //! See also the [`tag!`](../macro.tag.html) macro for creating tags from a byte string. use crate::error::ParseError; use std::{fmt, str}; /// Generate a 4-byte OpenType tag from byte string /// /// Example: /// /// ``` /// use allsorts::tag; /// assert_eq!(tag!(b"g...
#[test] fn test_three_chars() { let tag = from_string("BEN").expect("invalid tag"); assert_eq!(tag, 1111838240); } } mod display_tag { use crate::tag::{DisplayTag, NAME}; #[test] fn test_simple_ascii() { assert_eq!(DisplayT...
{ let tag = from_string("beng").expect("invalid tag"); assert_eq!(tag, 1650814567); }
identifier_body
tag.rs
//! Utilities and constants for OpenType tags. //! //! See also the [`tag!`](../macro.tag.html) macro for creating tags from a byte string. use crate::error::ParseError; use std::{fmt, str}; /// Generate a 4-byte OpenType tag from byte string /// /// Example: /// /// ``` /// use allsorts::tag; /// assert_eq!(tag!(b"g...
(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let tag = self.0; let bytes = tag.to_be_bytes(); if bytes.iter().all(|c| c.is_ascii() &&!c.is_ascii_control()) { let s = str::from_utf8(&bytes).unwrap(); // unwrap safe due to above check s.fmt(f) } else { ...
fmt
identifier_name
tag.rs
//! Utilities and constants for OpenType tags. //! //! See also the [`tag!`](../macro.tag.html) macro for creating tags from a byte string. use crate::error::ParseError; use std::{fmt, str}; /// Generate a 4-byte OpenType tag from byte string /// /// Example: /// /// ``` /// use allsorts::tag; /// assert_eq!(tag!(b"g...
pub const MKMK: u32 = tag!(b"mkmk"); /// `mlm2` pub const MLM2: u32 = tag!(b"mlm2"); /// `mlym` pub const MLYM: u32 = tag!(b"mlym"); /// `mort` pub const MORT: u32 = tag!(b"mort"); /// `morx` pub const MORX: u32 = tag!(b"morx"); /// `mset` pub const MSET: u32 = tag!(b"mset"); /// `name` pub const NAME: u32 = tag!(b"nam...
pub const MEDI: u32 = tag!(b"medi"); /// `mkmk`
random_line_split
tag.rs
//! Utilities and constants for OpenType tags. //! //! See also the [`tag!`](../macro.tag.html) macro for creating tags from a byte string. use crate::error::ParseError; use std::{fmt, str}; /// Generate a 4-byte OpenType tag from byte string /// /// Example: /// /// ``` /// use allsorts::tag; /// assert_eq!(tag!(b"g...
tag = (tag << 8) | (c as u32); count += 1; } while count < 4 { tag = (tag << 8) | (''as u32); count += 1; } Ok(tag) } impl fmt::Display for DisplayTag { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let tag = self.0; let bytes = tag.t...
{ return Err(ParseError::BadValue); }
conditional_block
lib.rs
/*! * This library provides an API client for Diffbot. * * Making API requests * ------------------- * * There are a handful of different ways to make API calls: * * 1. The most basic way to make a request is with the ``call()`` function. * Everything must be specified for each request. * * 2. Use the ``D...
(&self, url: &Url, api: &str, fields: &[&str]) -> Result<json::Object, Error> { call(url, self.token, api, fields, self.version) } /// Prepare a request to any Diffbot API with the stored token and API version. /// /// See the ``call()`` function for an explanation of the paramet...
call
identifier_name