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 |
|---|---|---|---|---|
graphics.rs | use crate::mthelper::SharedRef;
use bedrock as br;
use br::{
CommandBuffer, CommandPool, Device, Instance, InstanceChild, PhysicalDevice, Queue,
SubmissionBatch,
};
use log::{debug, info, warn};
use std::ops::Deref;
pub type InstanceObject = SharedRef<br::InstanceObject>;
pub type DeviceObject = Shar... |
if self.visible_from_host() {
flags.push("HOST VISIBLE");
}
if self.is_host_cached() {
flags.push("CACHED");
}
if self.is_host_coherent() {
flags.push("COHERENT");
}
if (self.1.propertyFlags & br::vk::VK_MEMORY_PR... | {
flags.push("DEVICE LOCAL");
} | conditional_block |
screen_block.rs | use euclid::*;
use std::cmp;
use std::iter::FusedIterator;
use crate::geometry::*;
/// Coordinates of chunks in the image. The scaling factor is potentially different for every chunk
/// iterator.
struct ChunkSpace;
pub trait ScreenBlockExt {
fn internal_points(&self) -> InternalPoints;
fn spiral_chunks(&sel... |
}
/// Tests that pixel iterator is a well behaved exact length iterator
#[proptest]
fn spiral_iterator_exact_length(block: ScreenBlockWrapper, chunk_size_minus_one: u8) {
let it = block.spiral_chunks(chunk_size_minus_one as u32 + 1);
check_exact_length(it, it.len()); // Using first rep... | {
let mut prev_distance = 0;
for subblock in it {
let distance = cmp::max(
abs_difference(first.min.x, subblock.min.x),
abs_difference(first.min.y, subblock.min.y),
);
assert!(distance >= prev_distance);
... | conditional_block |
screen_block.rs | use euclid::*;
use std::cmp;
use std::iter::FusedIterator;
use crate::geometry::*;
/// Coordinates of chunks in the image. The scaling factor is potentially different for every chunk
/// iterator.
struct ChunkSpace;
pub trait ScreenBlockExt {
fn internal_points(&self) -> InternalPoints;
fn spiral_chunks(&sel... | (block: ScreenBlockWrapper, chunk_size_minus_one: u8) {
let mut it = block.spiral_chunks(chunk_size_minus_one as u32 + 1);
if let Some(first) = it.next() {
let mut prev_distance = 0;
for subblock in it {
let distance = cmp::max(
abs_difference... | spiral_iterator_is_spiral | identifier_name |
screen_block.rs | use euclid::*;
use std::cmp;
use std::iter::FusedIterator;
use crate::geometry::*;
/// Coordinates of chunks in the image. The scaling factor is potentially different for every chunk
/// iterator.
struct ChunkSpace;
pub trait ScreenBlockExt {
fn internal_points(&self) -> InternalPoints;
fn spiral_chunks(&sel... |
/// Tests that pixel iterator is a well behaved exact length iterator
#[proptest]
fn pixel_iterator_exact_length(block: ScreenBlockWrapper) {
check_exact_length(block.internal_points(), safe_area(*block) as usize);
}
/// Tests that sub blocks of a spiral chunk iterator when iterated over ... | {
check_pixel_iterator_covers_block(block.internal_points(), *block);
} | identifier_body |
screen_block.rs | use euclid::*;
use std::cmp;
use std::iter::FusedIterator;
use crate::geometry::*;
/// Coordinates of chunks in the image. The scaling factor is potentially different for every chunk
/// iterator.
struct ChunkSpace;
pub trait ScreenBlockExt {
fn internal_points(&self) -> InternalPoints;
fn spiral_chunks(&sel... | #[should_panic]
fn zero_sized_chunks(block: ScreenBlockWrapper) {
block.spiral_chunks(0);
}
} | random_line_split | |
10_msaa.rs | use itertools::izip;
use log::{info, warn, Level};
use sarekt::{
self,
error::{SarektError, SarektResult},
image_data::ImageData,
renderer::{
buffers_and_images::{
BufferType, IndexBufferElemSize, MagnificationMinificationFilter, TextureAddressMode,
},
config::{Config, MsaaConfig},
drawabl... | for geo in obj_set.objects[0].geometry.iter() {
// For every set of geometry (regardless of material for now).
for shape in geo.shapes.iter() {
// For every face/shape in the set of geometry.
match shape.primitive {
obj::obj::Primitive::Triangle(x, y, z) => {
for &vert in [x, y, ... | random_line_split | |
10_msaa.rs | use itertools::izip;
use log::{info, warn, Level};
use sarekt::{
self,
error::{SarektError, SarektResult},
image_data::ImageData,
renderer::{
buffers_and_images::{
BufferType, IndexBufferElemSize, MagnificationMinificationFilter, TextureAddressMode,
},
config::{Config, MsaaConfig},
drawabl... | let texture_vertices = &obj_set.objects[0].tex_vertices;
let tex_vertex = texture_vertices[vert.1.unwrap()];
// TODO BACKENDS only flip on coordinate systems that should.
let texture_vertex_as_float = [tex_vertex.u as f32, 1f32 - tex_vertex.v as f32];
// Igno... | {
for &vert in [x, y, z].iter() {
// We're only building a buffer of indices and vertices which contain position
// and tex coord.
let index_key = (vert.0, vert.1.unwrap());
if let Some(&vtx_index) = inserted_indices.get(&index_key) {
// Already lo... | conditional_block |
10_msaa.rs | use itertools::izip;
use log::{info, warn, Level};
use sarekt::{
self,
error::{SarektError, SarektResult},
image_data::ImageData,
renderer::{
buffers_and_images::{
BufferType, IndexBufferElemSize, MagnificationMinificationFilter, TextureAddressMode,
},
config::{Config, MsaaConfig},
drawabl... | () {
simple_logger::init_with_level(Level::Info).unwrap();
main_loop();
}
/// Takes full control of the executing thread and runs the event loop for it.
fn main_loop() {
let args: Vec<String> = std::env::args().collect();
let show_fps = args.contains(&"fps".to_owned());
let use_glb = args.contains(&"glb".to_... | main | identifier_name |
10_msaa.rs | use itertools::izip;
use log::{info, warn, Level};
use sarekt::{
self,
error::{SarektError, SarektResult},
image_data::ImageData,
renderer::{
buffers_and_images::{
BufferType, IndexBufferElemSize, MagnificationMinificationFilter, TextureAddressMode,
},
config::{Config, MsaaConfig},
drawabl... | let mut ar = WIDTH as f32 / HEIGHT as f32;
// Build Window.
let mut event_loop = EventLoop::new();
let window = Arc::new(
WindowBuilder::new()
.with_inner_size(LogicalSize::new(WIDTH, HEIGHT))
.build(&event_loop)
.unwrap(),
);
// Build Renderer.
let config = Config::builder()
.requ... | {
let args: Vec<String> = std::env::args().collect();
let show_fps = args.contains(&"fps".to_owned());
let use_glb = args.contains(&"glb".to_owned());
let msaa_level = if args.contains(&"4x".to_owned()) {
4u8
} else if args.contains(&"8x".to_owned()) {
8u8
} else if args.contains(&"noaa".to_owned())... | identifier_body |
op.rs | //! # Implementing differentiable operations
//!
//! Many of well-known ops are pre-defined in [crate::tensor_ops], but you can also
//! implement custom ops by hand.
//! See also [crate::tensor::TensorBuilder].
//!
//! ```
//! use ndarray;
//! use autograd as ag;
//! use autograd::op::OpError;
//! use autograd::tensor... |
// Call Op::grad and return `gxs`
pub(crate) fn compute_input_grads(mut self) -> SmallVec<Option<Tensor<'graph, T>>> {
let id = self.y.id;
// steal op
let stolen = self.graph().access_inner_mut(id).op.take().unwrap();
// call Op::grad
stolen.grad(&mut self);
/... | {
GradientContext {
gy,
y,
graph,
gxs: SmallVec::new(),
}
} | identifier_body |
op.rs | //! # Implementing differentiable operations
//!
//! Many of well-known ops are pre-defined in [crate::tensor_ops], but you can also
//! implement custom ops by hand.
//! See also [crate::tensor::TensorBuilder].
//!
//! ```
//! use ndarray;
//! use autograd as ag;
//! use autograd::op::OpError;
//! use autograd::tensor... | {
NdArrayError(String, ndarray::ShapeError),
IncompatibleShape(String),
TypeUnsupported(String),
InvalidDims(String),
OutOfBounds(String),
}
impl std::error::Error for OpError {}
impl fmt::Display for OpError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
... | OpError | identifier_name |
op.rs | //! # Implementing differentiable operations
//!
//! Many of well-known ops are pre-defined in [crate::tensor_ops], but you can also
//! implement custom ops by hand.
//! See also [crate::tensor::TensorBuilder].
//!
//! ```
//! use ndarray;
//! use autograd as ag;
//! use autograd::op::OpError;
//! use autograd::tensor... | i, i
),
},
OpInput::RdWrVariable(_) => {
panic!(
"Bad op impl: cannot perform mutable borrowing for input({}). Use input_mut() instead.",
i
);
}
}
}
/// Grabs ... | None => panic!(
"Bad op impl: input({})/input_mut({}) cannot be called twice", | random_line_split |
mapfile.rs | use crate::cache::TERRA_DIRECTORY;
use crate::terrain::quadtree::node::VNode;
use crate::terrain::tile_cache::{LayerParams, LayerType, TextureFormat};
use anyhow::Error;
use serde::{Deserialize, Serialize};
use std::fs::{self, File};
use std::io::{BufReader, BufWriter, Read, Write};
use std::path::PathBuf;
use vec_map:... |
}
| {
let value = serde_json::to_vec(&desc).unwrap();
self.textures.insert(name, value)?;
Ok(())
} | identifier_body |
mapfile.rs | use crate::cache::TERRA_DIRECTORY;
use crate::terrain::quadtree::node::VNode;
use crate::terrain::tile_cache::{LayerParams, LayerType, TextureFormat};
use anyhow::Error;
use serde::{Deserialize, Serialize};
use std::fs::{self, File};
use std::io::{BufReader, BufWriter, Read, Write};
use std::path::PathBuf;
use vec_map:... | (
&self,
layer: LayerType,
node: VNode,
base: bool,
) -> Result<TileState, Error> {
let filename = Self::tile_name(layer, node);
let meta = self.lookup_tile_meta(layer, node);
let exists = filename.exists();
let target_state = if base && exists {
... | reload_tile_state | identifier_name |
mapfile.rs | use crate::cache::TERRA_DIRECTORY;
use crate::terrain::quadtree::node::VNode;
use crate::terrain::tile_cache::{LayerParams, LayerType, TextureFormat};
use anyhow::Error;
use serde::{Deserialize, Serialize};
use std::fs::{self, File};
use std::io::{BufReader, BufWriter, Read, Write};
use std::path::PathBuf;
use vec_map:... | for i in self.tiles.scan_prefix(&prefix) {
let (k, v) = i?;
let meta = bincode::deserialize::<TileMeta>(&v)?;
let node = bincode::deserialize::<(LayerType, VNode)>(&k)?.1;
f(node, meta)?;
}
Ok(())
}
fn lookup_texture(&self, name: &str) -> ... | mut f: F,
) -> Result<(), Error> {
let prefix = bincode::serialize(&layer).unwrap(); | random_line_split |
activity_heartbeat_manager.rs | use crate::task_token::TaskToken;
use crate::{
errors::ActivityHeartbeatError,
protos::{
coresdk::{common, ActivityHeartbeat, PayloadsExt},
temporal::api::workflowservice::v1::RecordActivityTaskHeartbeatResponse,
},
ServerGatewayApis,
};
use std::{
collections::HashMap,
sync::{
... | if!self.shutting_down.load(Ordering::Relaxed) {
self.events
.send(LifecycleEvent::Shutdown)
.expect("should be able to send shutdown event");
self.shutting_down.store(true, Ordering::Relaxed);
}
let mut handle = self.join_handle.lock().await;... | /// processors to terminate gracefully.
pub async fn shutdown(&self) {
// If shutdown was called multiple times, shutdown signal has been sent already and consumer
// might have been dropped already, meaning that sending to the channel may fail.
// All we need to do is to simply await on... | random_line_split |
activity_heartbeat_manager.rs | use crate::task_token::TaskToken;
use crate::{
errors::ActivityHeartbeatError,
protos::{
coresdk::{common, ActivityHeartbeat, PayloadsExt},
temporal::api::workflowservice::v1::RecordActivityTaskHeartbeatResponse,
},
ServerGatewayApis,
};
use std::{
collections::HashMap,
sync::{
... | }
Err(e) => {
matches!(e, ActivityHeartbeatError::ShuttingDown);
}
}
}
fn record_heartbeat(
hm: &ActivityHeartbeatManagerHandle,
task_token: Vec<u8>,
i: u8,
delay: Duration,
) {
hm.record(
Activ... | {
let mut mock_gateway = MockServerGatewayApis::new();
mock_gateway
.expect_record_activity_heartbeat()
.returning(|_, _| Ok(RecordActivityTaskHeartbeatResponse::default()))
.times(0);
let hm = ActivityHeartbeatManager::new(Arc::new(mock_gateway));
hm.... | identifier_body |
activity_heartbeat_manager.rs | use crate::task_token::TaskToken;
use crate::{
errors::ActivityHeartbeatError,
protos::{
coresdk::{common, ActivityHeartbeat, PayloadsExt},
temporal::api::workflowservice::v1::RecordActivityTaskHeartbeatResponse,
},
ServerGatewayApis,
};
use std::{
collections::HashMap,
sync::{
... |
Err(e) => {
warn!("Error when recording heartbeat: {:?}", e)
}
}
}
}
#[cfg(test)]
mod test {
use super::*;
use crate::pollers::MockServerGatewayApis;
use crate::protos::coresdk::common::Payload;
use crate::protos::temporal::api::workflowservice::v1::... | {
self.cancels_tx
.send(self.task_token.clone())
.expect("Receive half of heartbeat cancels not blocked");
} | conditional_block |
activity_heartbeat_manager.rs | use crate::task_token::TaskToken;
use crate::{
errors::ActivityHeartbeatError,
protos::{
coresdk::{common, ActivityHeartbeat, PayloadsExt},
temporal::api::workflowservice::v1::RecordActivityTaskHeartbeatResponse,
},
ServerGatewayApis,
};
use std::{
collections::HashMap,
sync::{
... | (&mut self, heartbeat: ValidActivityHeartbeat) {
match self.heartbeat_processors.get(&heartbeat.task_token) {
Some(handle) => {
handle
.heartbeat_tx
.send(heartbeat.details)
.expect("heartbeat channel can't be dropped if we are... | record | identifier_name |
process_vm.rs | MLayout::new(stack_size, 16)?,
];
let process_layout = elf_layouts.iter().chain(other_layouts.iter()).fold(
VMLayout::new_empty(),
|mut process_layout, sub_layout| {
process_layout.add(&sub_layout);
process_layout
},
);
... | {
return USER_SPACE_VM_MANAGER.msync(addr, size);
} | identifier_body | |
process_vm.rs | .heap_size
.unwrap_or(config::LIBOS_CONFIG.process.default_heap_size);
let stack_size = self
.stack_size
.unwrap_or(config::LIBOS_CONFIG.process.default_stack_size);
// Before allocating memory, let's first calculate how much memory
// we need in total by ... | elf_layout.extend(&segment_layout);
elf_layout
})
})
.collect();
// Make heap and stack 16-byte aligned
let other_layouts = vec![
VMLayout::new(heap_size, 16)?,
VMLayout::new(stack_size, 1... | let segment_size = (segment.p_vaddr + segment.p_memsz) as usize;
let segment_align = segment.p_align as usize;
let segment_layout = VMLayout::new(segment_size, segment_align).unwrap(); | random_line_split |
process_vm.rs | .heap_size
.unwrap_or(config::LIBOS_CONFIG.process.default_heap_size);
let stack_size = self
.stack_size
.unwrap_or(config::LIBOS_CONFIG.process.default_stack_size);
// Before allocating memory, let's first calculate how much memory
// we need in total by i... | (&mut self) {
let mut mem_chunks = self.mem_chunks.write().unwrap();
// There are two cases when this drop is called:
// (1) Process exits normally and in the end, drop process VM
// (2) During creating process stage, process VM is ready but there are some other errors when creating the ... | drop | identifier_name |
ledger_cleanup_service.rs | //! The `ledger_cleanup_service` drops older ledger data to limit disk space usage
use solana_ledger::blockstore::Blockstore;
use solana_ledger::blockstore_db::Result as BlockstoreResult;
use solana_measure::measure::Measure;
use solana_metrics::datapoint_debug;
use solana_sdk::clock::Slot;
use std::string::ToString;
... | max_ledger_shreds,
shreds.len(),
total_shreds,
iterate_time
);
if (total_shreds as u64) < max_ledger_shreds {
return (0, 0, 0);
}
let mut cur_shreds = 0;
let mut lowest_slot_to_clean = shreds[0].0;
for (slot, num... | {
let mut shreds = Vec::new();
let mut iterate_time = Measure::start("iterate_time");
let mut total_shreds = 0;
let mut first_slot = 0;
for (i, (slot, meta)) in blockstore.slot_meta_iterator(0).unwrap().enumerate() {
if i == 0 {
first_slot = slot;
... | identifier_body |
ledger_cleanup_service.rs | //! The `ledger_cleanup_service` drops older ledger data to limit disk space usage
use solana_ledger::blockstore::Blockstore;
use solana_ledger::blockstore_db::Result as BlockstoreResult;
use solana_measure::measure::Measure;
use solana_metrics::datapoint_debug;
use solana_sdk::clock::Slot;
use std::string::ToString;
... | () {
solana_logger::setup();
let blockstore_path = get_tmp_ledger_path!();
let blockstore = Blockstore::open(&blockstore_path).unwrap();
let (shreds, _) = make_many_slot_entries(0, 50, 5);
blockstore.insert_shreds(shreds, None, false).unwrap();
let blockstore = Arc::new(b... | test_cleanup | identifier_name |
ledger_cleanup_service.rs | //! The `ledger_cleanup_service` drops older ledger data to limit disk space usage
use solana_ledger::blockstore::Blockstore;
use solana_ledger::blockstore_db::Result as BlockstoreResult;
use solana_measure::measure::Measure;
use solana_metrics::datapoint_debug;
use solana_sdk::clock::Slot;
use std::string::ToString;
... |
//send a signal to kill all but 5 shreds, which will be in the newest slots
let mut last_purge_slot = 0;
sender.send(50).unwrap();
LedgerCleanupService::cleanup_ledger(&receiver, &blockstore, 5, &mut last_purge_slot, 10)
.unwrap();
//check that 0-40 don't exist
... | let blockstore = Arc::new(blockstore);
let (sender, receiver) = channel(); | random_line_split |
tcp.rs | ::Address::zero(), *addr).map(|(laddr, _, _)| Address::Ipv4(laddr)),
}
}
/// Allocate a port for the given local address
fn allocate_port(_addr: &Address) -> Option<u16>
{
// TODO: Could store bitmap against the interface (having a separate bitmap for each interface)
S_PORTS.lock().allocate()
}
fn release_port(_addr... | ConnectionState::Finished => return,
};
self.state_update(quad, new_state);
}
fn state_update(&mut self, quad: &Quad, new_state: ConnectionState)
{
if self.state!= new_state
{
log_trace!("{:?} {:?} -> {:?}", quad, self.state, new_state);
self.state = new_state;
// TODO: If transitioning to `Fin... | ConnectionState::TimeWait => self.state,
| random_line_split |
tcp.rs | Address::zero(), *addr).map(|(laddr, _, _)| Address::Ipv4(laddr)),
}
}
/// Allocate a port for the given local address
fn allocate_port(_addr: &Address) -> Option<u16>
{
// TODO: Could store bitmap against the interface (having a separate bitmap for each interface)
S_PORTS.lock().allocate()
}
fn release_port(_addr: ... |
else if hdr.flags & FLAG_FIN!= 0 {
// FIN received, start a clean shutdown
self.next_rx_seq += 1;
// TODO: Signal to user that the connection is closing (EOF)
ConnectionState::CloseWait
}
else {
if pkt.remain() == 0 {
// Pure ACK, no change
if hdr.flags == FLAG_ACK {
log_tr... | {
// RST received, do an unclean close (reset by peer)
// TODO: Signal to user that the connection is closing (error)
ConnectionState::ForceClose
} | conditional_block |
tcp.rs | Address::zero(), *addr).map(|(laddr, _, _)| Address::Ipv4(laddr)),
}
}
/// Allocate a port for the given local address
fn allocate_port(_addr: &Address) -> Option<u16>
{
// TODO: Could store bitmap against the interface (having a separate bitmap for each interface)
S_PORTS.lock().allocate()
}
fn release_port(_addr: ... | (local_addr: Address, local_port: u16, remote_addr: Address, remote_port: u16) -> Quad
{
Quad {
local_addr, local_port, remote_addr, remote_port
}
}
fn send_packet(&self, seq: u32, ack: u32, flags: u8, window_size: u16, data: &[u8])
{
// Make a header
// TODO: Any options required?
let options_bytes =... | new | identifier_name |
tcp.rs | Address::zero(), *addr).map(|(laddr, _, _)| Address::Ipv4(laddr)),
}
}
/// Allocate a port for the given local address
fn allocate_port(_addr: &Address) -> Option<u16>
{
// TODO: Could store bitmap against the interface (having a separate bitmap for each interface)
S_PORTS.lock().allocate()
}
fn release_port(_addr: ... |
fn send_packet(&self, seq: u32, ack: u32, flags: u8, window_size: u16, data: &[u8])
{
// Make a header
// TODO: Any options required?
let options_bytes = &[];
let opts_len_rounded = ((options_bytes.len() + 3) / 4) * 4;
let hdr = PktHeader {
source_port: self.local_port,
dest_port: self.remote_port,
... | {
Quad {
local_addr, local_port, remote_addr, remote_port
}
} | identifier_body |
reaper-rush.rs | #[macro_use]
extern crate clap;
use rand::prelude::*;
use rust_sc2::prelude::*;
use std::{cmp::Ordering, collections::HashSet};
#[bot]
#[derive(Default)]
struct ReaperRushAI {
reapers_retreat: HashSet<u64>,
last_loop_distributed: u32,
}
impl Player for ReaperRushAI {
fn on_start(&mut self) -> SC2Result<()> {
if... | }
}
if self.counter().all().count(UnitTypeId::Barracks) < 4
&& self.can_afford(UnitTypeId::Barracks, false)
{
if let Some(location) = self.find_placement(
UnitTypeId::Barracks,
main_base,
PlacementOptions {
step: 4,
..Default::default()
},
) {
if let Some(builder) = self... | builder.build(UnitTypeId::SupplyDepot, location, false);
self.subtract_resources(UnitTypeId::SupplyDepot, false);
return;
} | random_line_split |
reaper-rush.rs | #[macro_use]
extern crate clap;
use rand::prelude::*;
use rust_sc2::prelude::*;
use std::{cmp::Ordering, collections::HashSet};
#[bot]
#[derive(Default)]
struct ReaperRushAI {
reapers_retreat: HashSet<u64>,
last_loop_distributed: u32,
}
impl Player for ReaperRushAI {
fn on_start(&mut self) -> SC2Result<()> {
if... | (&mut self) {
if self.minerals < 50 || self.supply_left == 0 {
return;
}
if self.supply_workers < 22 && self.can_afford(UnitTypeId::SCV, true) {
if let Some(cc) = self
.units
.my
.townhalls
.iter()
.find(|u| u.is_ready() && u.is_almost_idle())
{
cc.train(UnitTypeId::SCV, false);
... | train | identifier_name |
reaper-rush.rs | #[macro_use]
extern crate clap;
use rand::prelude::*;
use rust_sc2::prelude::*;
use std::{cmp::Ordering, collections::HashSet};
#[bot]
#[derive(Default)]
struct ReaperRushAI {
reapers_retreat: HashSet<u64>,
last_loop_distributed: u32,
}
impl Player for ReaperRushAI {
fn on_start(&mut self) -> SC2Result<()> {
if... | else {
None
};
for u in &idle_workers {
if let Some(closest) = deficit_geysers.closest(u) {
let tag = closest.tag();
deficit_geysers.remove(tag);
u.gather(tag, false);
} else if let Some(closest) = deficit_minings.closest(u) {
u.gather(
mineral_fields
.closer(11.0, closest)
... | {
let minerals = mineral_fields.filter(|m| bases.iter().any(|base| base.is_closer(11.0, *m)));
if minerals.is_empty() {
None
} else {
Some(minerals)
}
} | conditional_block |
reaper-rush.rs | #[macro_use]
extern crate clap;
use rand::prelude::*;
use rust_sc2::prelude::*;
use std::{cmp::Ordering, collections::HashSet};
#[bot]
#[derive(Default)]
struct ReaperRushAI {
reapers_retreat: HashSet<u64>,
last_loop_distributed: u32,
}
impl Player for ReaperRushAI {
fn on_start(&mut self) -> SC2Result<()> {
if... | .units
.my
.structures
.iter()
.find(|u| u.type_id() == UnitTypeId::Barracks && u.is_ready() && u.is_almost_idle())
{
barracks.train(UnitTypeId::Reaper, false);
self.subtract_resources(UnitTypeId::Reaper, true);
}
}
}
fn throw_mine(&self, reaper: &Unit, target: &Unit) -> bool {
... | {
if self.minerals < 50 || self.supply_left == 0 {
return;
}
if self.supply_workers < 22 && self.can_afford(UnitTypeId::SCV, true) {
if let Some(cc) = self
.units
.my
.townhalls
.iter()
.find(|u| u.is_ready() && u.is_almost_idle())
{
cc.train(UnitTypeId::SCV, false);
self.sub... | identifier_body |
lib.rs | )))
}
}
unsafe impl GlobalAlloc for SafeZoneAllocator {
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
assert!(layout.align().is_power_of_two());
self.0.lock().allocate(layout)
}
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
//let ptr = NonNull::new_unchecked(pt... | let block_is_free = bitval & (1 << first_free) == 0;
if alignment_ok && block_is_free {
return Some((idx, addr));
}
}
}
}
None
}
/// Check if the current `idx` is allocated.
///
... | {
unsafe {
for (base_idx, b) in self.bitfield.iter().enumerate() {
let bitval = *b;
if bitval == u64::max_value() {
continue;
} else {
let negated = !bitval;
let first_free = negated.trailing_... | identifier_body |
lib.rs | )))
}
}
unsafe impl GlobalAlloc for SafeZoneAllocator {
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
assert!(layout.align().is_power_of_two());
self.0.lock().allocate(layout)
}
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
//let ptr = NonNull::new_unchecked(pt... | (current_size: usize) -> Option<usize> {
match current_size {
0...8 => Some(8),
9...16 => Some(16),
17...32 => Some(32),
33...64 => Some(64),
65...128 => Some(128),
129...256 => Some(256),
257...512 => Some(512),
513... | get_max_size | identifier_name |
lib.rs | )))
}
}
unsafe impl GlobalAlloc for SafeZoneAllocator {
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
assert!(layout.align().is_power_of_two());
self.0.lock().allocate(layout)
}
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
//let ptr = NonNull::new_unchecked(pt... |
}
ptr::null_mut()
}
/// Allocates a block of memory with respect to `alignment`.
///
/// In case of failure will try to grow the slab allocator by requesting
/// additional pages and re-try the allocation once more before we give up.
pub fn allocate<'b>(&'b mut self, layout: L... | {
continue;
} | conditional_block |
lib.rs | provider)))
}
}
unsafe impl GlobalAlloc for SafeZoneAllocator {
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
assert!(layout.align().is_power_of_two());
self.0.lock().allocate(layout)
}
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
//let ptr = NonNull::new_unch... | SCAllocator::new(32, pager),
SCAllocator::new(64, pager),
SCAllocator::new(128, pager),
SCAllocator::new(256, pager),
SCAllocator::new(512, pager),
SCAllocator::new(1024, pager),
SCAllocator::new(2048, pager)... | ZoneAllocator {
pager: pager,
slabs: [
SCAllocator::new(8, pager),
SCAllocator::new(16, pager), | random_line_split |
stream_animation.rs | use super::stream_layer::*;
use super::stream_animation_core::*;
use crate::traits::*;
use crate::storage::*;
use crate::storage::file_properties::*;
use crate::storage::layer_properties::*;
use ::desync::*;
use flo_stream::*;
use itertools::*;
use futures::prelude::*;
use futures::task::{Poll};
use futures::stream;
... | (&self) -> ElementId {
// Create a queue to run the 'assign element ID' future on
let core = Arc::clone(&self.core);
// Perform the request and retrieve the result
core.future_desync(|core| core.assign_element_id(ElementId::Unassigned).boxed())
.sync().unwrap()
}
... | assign_element_id | identifier_name |
stream_animation.rs | use super::stream_layer::*;
use super::stream_animation_core::*;
use crate::traits::*;
use crate::storage::*;
use crate::storage::file_properties::*;
use crate::storage::layer_properties::*;
use ::desync::*;
use flo_stream::*;
use itertools::*;
use futures::prelude::*;
use futures::task::{Poll};
use futures::stream;
... |
if let Some(next) = fetched.pop() {
// Just returning the batch we've already fetched
return Poll::Ready(Some(next));
} else if let Some(mut waiting) = next_response.take() {
// Try to retrieve the next item from the batch
... | {
// Fetch up to per_request items for each request
let num_to_fetch = remaining.len();
let num_to_fetch = if num_to_fetch > per_request { per_request } else { num_to_fetch };
let fetch_range = (remaining.start)..(remaining.start ... | conditional_block |
stream_animation.rs | use super::stream_layer::*;
use super::stream_animation_core::*;
use crate::traits::*;
use crate::storage::*;
use crate::storage::file_properties::*;
use crate::storage::layer_properties::*;
use ::desync::*;
use flo_stream::*;
use itertools::*;
use futures::prelude::*;
use futures::task::{Poll};
use futures::stream;
... |
///
/// Retrieves the IDs of the layers in this object
///
fn get_layer_ids(&self) -> Vec<u64> {
self.wait_for_edits();
let layer_responses = self.request_sync(vec![StorageCommand::ReadLayers]).unwrap_or_else(|| vec![]);
layer_responses
.into_iter()
.flat... | self.file_properties().frame_length
} | random_line_split |
stream_animation.rs | use super::stream_layer::*;
use super::stream_animation_core::*;
use crate::traits::*;
use crate::storage::*;
use crate::storage::file_properties::*;
use crate::storage::layer_properties::*;
use ::desync::*;
use flo_stream::*;
use itertools::*;
use futures::prelude::*;
use futures::task::{Poll};
use futures::stream;
... | let core = Arc::new(Desync::new(core));
// Anything published to the editor is piped into the core
pipe_in(Arc::clone(&core), edit_publisher.subscribe(), |core, edits: Arc<Vec<AnimationEdit>>| {
async move {
// Edits require some pre-processing: assign the... | {
// Create the storage requests. When the storage layer is running behind, we'll buffer up to 10 of these
let mut requests = Publisher::new(10);
let commands = requests.subscribe().boxed();
let storage_responses = connect_stream(commands);
let mut edit_publis... | identifier_body |
config.rs | :tt])*
$vis:vis struct $struct_name:ident {
$(
$(#[doc = $d:tt])*
$field_vis:vis $field_name:ident : $field_type:ty, default = $default:expr
)*$(,)*
}
) => {
$(#[doc = $struct_d])*
#[derive(Debug, Clone)]
#[non_exhaustive]
$vis struct $struct... | {
self.0.get(T::PREFIX)?.0.as_any().downcast_ref()
} | identifier_body | |
config.rs | down_filters: bool, default = false
/// If true, filter expressions evaluated during the parquet decoding operation
/// will be reordered heuristically to minimize the cost of evaluation. If false,
/// the filters are applied in the same order as written in the query
pub reorder_filters... | )*
_ => Err($crate::DataFusionError::Internal(
format!(concat!("Config value \"{}\" not found on ", stringify!($struct_name)), key)
))
} | random_line_split | |
config.rs | $(#[doc = $struct_d:tt])*
$vis:vis struct $struct_name:ident {
$(
$(#[doc = $d:tt])*
$field_vis:vis $field_name:ident : $field_type:ty, default = $default:expr
)*$(,)*
}
) => {
$(#[doc = $struct_d])*
#[derive(Debug, Clone)]
#[non_exhaustive]
... | (&mut self, key: &str, description: &'static str) {
self.0.push(ConfigEntry {
key: key.to_string(),
value: None,
description,
})
}
}
let mut v = Visitor(vec![]);
self.visit(&mut v, "datafusio... | none | identifier_name |
glium_backend.rs | );
let rect = glium::Rect {
left: 0,
bottom: 0,
width: img.size.width,
height: img.size.height,
};
let mut raw = glium::texture::RawImage2d::from_raw_rgba(
img.pixels.clone(),
(img.size.width, img.size.height),
... | size | identifier_name | |
glium_backend.rs | // outside the screen.
const BUFFER: u32 = 8;
let monitor_size = display
.gl_window()
.window()
.get_primary_monitor()
.get_dimensions();
let monitor_size = Size2D::new(monitor_size.width as u32, monitor_size.heigh... | pos: [sx + sw, sy],
tex_coord: [1.0, 0.0],
}, | random_line_split | |
glium_backend.rs | ///
/// The custom shader must support a uniform named `tex` for texture data.
pub fn start<'a, S, P>(
width: u32,
height: u32,
title: S,
shader: P,
) -> Result<Backend<V>, Box<Error>>
where
S: Into<String>,
P: Into<glium::program::ProgramCreationInput<'... |
/// Make a new internal texture using image data.
pub fn make_texture(&mut self, img: ImageBuffer) -> TextureIndex {
let mut raw = glium::texture::RawImage2d::from_raw_rgba(
img.pixels,
(img.size.width, img.size.height),
);
raw.format = glium::texture::ClientFor... | {
assert!(
texture < self.textures.len(),
"Trying to write nonexistent texture"
);
let rect = glium::Rect {
left: 0,
bottom: 0,
width: img.size.width,
height: img.size.height,
};
let mut raw = glium::texture:... | identifier_body |
server.rs | #[feature(struct_variant)];
#[feature(macro_rules)];
use std::io::net::ip::{Ipv4Addr, SocketAddr};
use std::io::net::udp::{UdpSocket, UdpStream};
use std::io::timer;
use udptransport::UdpTransport;
use transport::RaftRpcTransport;
use rpc::{ServerId, LogEntry, AppendEntries, AppendEntriesResponse, RequestVote, Request... | if rpc.term >= self.currentTerm {
// we lost the election... D:
self.convertToFollower();
}
// pretend we didn't hear them whether or not they won, the resend will occur anyway
}
// Update the server when it is a Follower
// Paper:
// Respond to RPCs from candidates and leaders
// ... | }
}
fn candidateAppendEntries(&mut self, rpc: AppendEntriesRpc) { | random_line_split |
server.rs | #[feature(struct_variant)];
#[feature(macro_rules)];
use std::io::net::ip::{Ipv4Addr, SocketAddr};
use std::io::net::udp::{UdpSocket, UdpStream};
use std::io::timer;
use udptransport::UdpTransport;
use transport::RaftRpcTransport;
use rpc::{ServerId, LogEntry, AppendEntries, AppendEntriesResponse, RequestVote, Request... |
// 3. If an existing entry conflicts with a new one delete the
// existing entry and all that follow it
let startLogIndex = rpc.prevLogIndex+1;
for logOffset in range(0, rpc.entries.len()) {
let logIndex = startLogIndex + logOffset as int;
let entry = rpc.entries[logOffset].clone();
... | {
return fail;
} | conditional_block |
server.rs | #[feature(struct_variant)];
#[feature(macro_rules)];
use std::io::net::ip::{Ipv4Addr, SocketAddr};
use std::io::net::udp::{UdpSocket, UdpStream};
use std::io::timer;
use udptransport::UdpTransport;
use transport::RaftRpcTransport;
use rpc::{ServerId, LogEntry, AppendEntries, AppendEntriesResponse, RequestVote, Request... |
fn followerVote(&mut self, rpc: &RequestVoteRpc) -> RaftRpc {
// if the candidate's log is at least as up-to-date as ours vote for them
let mut voteGranted = false;
let lastLogIndex = (self.log.len() - 1) as int;
if self.log.len() == 0 || (rpc.lastLogIndex >= lastLogIndex &&
... | {
let fail = RequestVoteResponse(RequestVoteResponseRpc {sender: self.serverId, term: self.currentTerm, voteGranted: false});
if rpc.term < self.currentTerm {
return fail;
}
// if we haven't voted for anything or we voted for candidate
match self.votedFor {
None => {
return self.... | identifier_body |
server.rs | #[feature(struct_variant)];
#[feature(macro_rules)];
use std::io::net::ip::{Ipv4Addr, SocketAddr};
use std::io::net::udp::{UdpSocket, UdpStream};
use std::io::timer;
use udptransport::UdpTransport;
use transport::RaftRpcTransport;
use rpc::{ServerId, LogEntry, AppendEntries, AppendEntriesResponse, RequestVote, Request... | {
currentTerm: int,
votedFor: Option<ServerId>,
log: ~[LogEntry],
commitIndex: int,
lastApplied: int,
serverType: ServerType,
electionTimeout: int,
receivedVotes: int,
// Leader state:
// for each server, index of the next log entry to send to that
// server, initialized to last log index + 1
n... | RaftServer | identifier_name |
main.rs | map: HashMap::new(),
}
}
fn add(&mut self, author: Author, commit: Oid) {
self.map
.entry(author)
.or_insert_with(HashSet::new)
.insert(commit);
}
fn iter(&self) -> impl Iterator<Item = (&Author, usize)> {
self.map.iter().map(|(k, v)| (k, v.len... |
}
new
}
}
fn git(args: &[&str]) -> Result<String, Box<dyn std::error::Error>> {
let mut cmd = Command::new("git");
cmd.args(args);
cmd.stdout(Stdio::piped());
let out = cmd.spawn();
let mut out = match out {
Ok(v) => v,
Err(err) => {
panic!("Failed t... | {
new.map.insert(author.clone(), set.clone());
} | conditional_block |
main.rs | from(std::io::ErrorKind::Other).into());
}
let mut stdout = Vec::new();
out.stdout.unwrap().read_to_end(&mut stdout).unwrap();
Ok(String::from_utf8_lossy(&stdout).into_owned())
}
lazy_static::lazy_static! {
static ref UPDATED: Mutex<HashSet<String>> = Mutex::new(HashSet::new());
}
fn update_repo(... | modules_file | identifier_name | |
main.rs | map: HashMap::new(),
}
}
fn add(&mut self, author: Author, commit: Oid) { | .or_insert_with(HashSet::new)
.insert(commit);
}
fn iter(&self) -> impl Iterator<Item = (&Author, usize)> {
self.map.iter().map(|(k, v)| (k, v.len()))
}
fn extend(&mut self, other: Self) {
for (author, set) in other.map {
self.map
.entry... | self.map
.entry(author) | random_line_split |
main.rs | map: HashMap::new(),
}
}
fn add(&mut self, author: Author, commit: Oid) {
self.map
.entry(author)
.or_insert_with(HashSet::new)
.insert(commit);
}
fn iter(&self) -> impl Iterator<Item = (&Author, usize)> {
self.map.iter().map(|(k, v)| (k, v.len... | out.stdout.unwrap().read_to_end(&mut stdout).unwrap();
Ok(String::from_utf8_lossy(&stdout).into_owned())
}
lazy_static::lazy_static! {
static ref UPDATED: Mutex<HashSet<String>> = Mutex::new(HashSet::new());
}
fn update_repo(url: &str) -> Result<PathBuf, Box<dyn std::error::Error>> {
let mut slug = u... | {
let mut cmd = Command::new("git");
cmd.args(args);
cmd.stdout(Stdio::piped());
let out = cmd.spawn();
let mut out = match out {
Ok(v) => v,
Err(err) => {
panic!("Failed to spawn command `{:?}`: {:?}", cmd, err);
}
};
let status = out.wait().expect("wait... | identifier_body |
graph_layers.rs | use std::cmp::max;
use std::path::{Path, PathBuf};
use common::fixed_length_priority_queue::FixedLengthPriorityQueue;
use itertools::Itertools;
use serde::{Deserialize, Serialize};
use super::graph_links::{GraphLinks, GraphLinksMmap};
use crate::common::file_operations::{atomic_save_bin, read_bin, FileStorageError};
... |
}
impl GraphLayers<GraphLinksMmap> {
pub fn prefault_mmap_pages(&self, path: &Path) -> Option<mmap_ops::PrefaultMmapPages> {
self.links.prefault_mmap_pages(path)
}
}
#[cfg(test)]
mod tests {
use std::fs::File;
use std::io::Write;
use itertools::Itertools;
use rand::rngs::StdRng;
... | {
Ok(atomic_save_bin(path, self)?)
} | identifier_body |
graph_layers.rs | use std::cmp::max;
use std::path::{Path, PathBuf};
use common::fixed_length_priority_queue::FixedLengthPriorityQueue;
use itertools::Itertools;
use serde::{Deserialize, Serialize};
use super::graph_links::{GraphLinks, GraphLinksMmap};
use crate::common::file_operations::{atomic_save_bin, read_bin, FileStorageError};
... | (&self, point_id: PointOffsetType) -> usize {
self.links.point_level(point_id)
}
pub fn search(
&self,
top: usize,
ef: usize,
mut points_scorer: FilteredScorer,
) -> Vec<ScoredPointOffset> {
let entry_point = match self
.entry_points
.ge... | point_level | identifier_name |
graph_layers.rs | use std::cmp::max;
use std::path::{Path, PathBuf};
use common::fixed_length_priority_queue::FixedLengthPriorityQueue;
use itertools::Itertools;
use serde::{Deserialize, Serialize};
use super::graph_links::{GraphLinks, GraphLinksMmap};
use crate::common::file_operations::{atomic_save_bin, read_bin, FileStorageError};
... | Err(err)?
}
}
}
}
pub fn save(&self, path: &Path) -> OperationResult<()> {
Ok(atomic_save_bin(path, self)?)
}
}
impl GraphLayers<GraphLinksMmap> {
pub fn prefault_mmap_pages(&self, path: &Path) -> Option<mmap_ops::PrefaultMmapPages> {
... | {
let try_legacy: Result<GraphLayersBackwardCompatibility, _> = read_bin(graph_path);
if let Ok(legacy) = try_legacy {
log::debug!("Converting legacy graph to new format");
let mut converter = GraphLinksConverter::new(legacy.links_layers);
... | conditional_block |
graph_layers.rs | use std::cmp::max;
use std::path::{Path, PathBuf};
use common::fixed_length_priority_queue::FixedLengthPriorityQueue;
use itertools::Itertools;
use serde::{Deserialize, Serialize};
use super::graph_links::{GraphLinks, GraphLinksMmap};
use crate::common::file_operations::{atomic_save_bin, read_bin, FileStorageError};
... | vector_storage: &TestRawScorerProducer<CosineMetric>,
graph: &GraphLayers<TGraphLinks>,
) -> Vec<ScoredPointOffset> {
let fake_filter_context = FakeFilterContext {};
let raw_scorer = vector_storage.get_raw_scorer(query.to_owned());
let scorer = FilteredScorer::new(raw_scorer.... | top: usize, | random_line_split |
image.rs | use core::ops::Range;
use crate::ImageTrait;
use crate::vec::*;
use crate::rangetools::*;
use std::path::Path;
use static_assertions::*;
pub enum PixelPos {
R,
G,
B,
A,
}
pub fn convert(slice: &mut [Color]) -> &mut [u32] {
assert_eq_size!(Color, u32);
assert_eq_align!(Color, u32);
unsafe { std::slice::from_ra... | )
}
}
pub fn place_repeated_scaled_image(image: &mut Image, repeated_image: &Image, pos: &Vec2i, scale: i32, repeat_x: bool, repeat_y: bool) {
let size = Vec2i::new(repeated_image.get_width() as i32, repeated_image.get_height() as i32) * scale;
let range_x = calc_range_for_repeated_line(repeat_x, pos.x, size.x, ... | random_line_split | |
image.rs | use core::ops::Range;
use crate::ImageTrait;
use crate::vec::*;
use crate::rangetools::*;
use std::path::Path;
use static_assertions::*;
pub enum PixelPos {
R,
G,
B,
A,
}
pub fn convert(slice: &mut [Color]) -> &mut [u32] {
assert_eq_size!(Color, u32);
assert_eq_align!(Color, u32);
unsafe { std::slice::from_ra... | else {
Color::rgba(
blend!(src.r, dst.r),
blend!(src.g, dst.g),
blend!(src.b, dst.b),
(outa / 255) as u8
)
}
}
#[inline]
/// Works on f32 with gamma correction of 2.2 power. Source: https://en.wikipedia.org/wiki/Alpha_compositing#Alpha_blending + https://en.wikipedia.org/wiki/Alpha_compositing#Compos... | {
Color::rgba(0, 0, 0, 0)
} | conditional_block |
image.rs | use core::ops::Range;
use crate::ImageTrait;
use crate::vec::*;
use crate::rangetools::*;
use std::path::Path;
use static_assertions::*;
pub enum PixelPos {
R,
G,
B,
A,
}
pub fn convert(slice: &mut [Color]) -> &mut [u32] {
assert_eq_size!(Color, u32);
assert_eq_align!(Color, u32);
unsafe { std::slice::from_ra... |
pub fn save_png(&self, path: &Path) -> Result<(), std::io::Error> {
use std::fs::File;
use std::io::BufWriter;
let file = File::create(path)?;
let w = &mut BufWriter::new(file);
let mut encoder = png::Encoder::new(w, self.width as u32, self.height as u32);
encoder.set_color(png::ColorType::RGBA);
enc... | {
0..(self.height as i32)
} | identifier_body |
image.rs | use core::ops::Range;
use crate::ImageTrait;
use crate::vec::*;
use crate::rangetools::*;
use std::path::Path;
use static_assertions::*;
pub enum PixelPos {
R,
G,
B,
A,
}
pub fn convert(slice: &mut [Color]) -> &mut [u32] {
assert_eq_size!(Color, u32);
assert_eq_align!(Color, u32);
unsafe { std::slice::from_ra... | (src: &Color, dst: &Color) -> Color {
let srca = src.a as f32 / 255.0;
let dsta = dst.a as f32 / 255.0;
let outa = 1. - (1. - srca) * (1. - dsta);
macro_rules! blend {
($src:expr, $dst:expr) => {
(((($src as f32 / 255.0).powf(2.2) * srca + ($dst as f32 / 255.0).powf(2.2) * dsta * (1.0 - srca)) / outa).powf(1... | ideal_blend | identifier_name |
modular.rs | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT license OR Apache 2.0
use authentication::perform_authentication;
use futures::{
future::{self, TryFutureExt},
Future, Stream, StreamExt, TryStreamExt,
};
use std::sync::Arc;
use tokio::sync::broadcast::{channel as event_channel, Sender as Broadcast... |
};
// Tunnel naming - The tunnel registry is notified of the authenticator-provided tunnel name
{
let tunnel_registry = Arc::clone(&serialized_tunnel_registry);
Self::name_tunnel(id, tunnel_name.clone(), tunnel_registry).instrument(tracing::span!(
tracing::Level::DEBUG,
"naming... | {
let _ = serialized_tunnel_registry.deregister_tunnel(id).await;
return Ok(());
} | conditional_block |
modular.rs | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT license OR Apache 2.0
use authentication::perform_authentication;
use futures::{
future::{self, TryFutureExt},
Future, Stream, StreamExt, TryStreamExt,
};
use std::sync::Arc;
use tokio::sync::broadcast::{channel as event_channel, Sender as Broadcast... | }
}
}
async fn handle_incoming_request_bistream<Services>(
tunnel_id: TunnelId,
link: WrappedStream,
negotiator: Arc<NegotiationService<Services>>,
shutdown: CancellationToken, // TODO: Respond to shutdown listener requests
) -> Result<(), RequestProcessingError>
where
Services: S... | {
match link {
tunnel::TunnelIncomingType::BiStream(link) => {
Self::handle_incoming_request_bistream(id, link, negotiator, shutdown).await | random_line_split |
modular.rs | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT license OR Apache 2.0
use authentication::perform_authentication;
use futures::{
future::{self, TryFutureExt},
Future, Stream, StreamExt, TryStreamExt,
};
use std::sync::Arc;
use tokio::sync::broadcast::{channel as event_channel, Sender as Broadcast... | {
#[error(transparent)]
RegistrationError(#[from] TunnelRegistrationError),
#[error(transparent)]
RegistryNamingError(#[from] TunnelNamingError),
#[error(transparent)]
RequestProcessingError(RequestProcessingError),
#[error("Authentication refused to remote by either breach of protocol or invalid/inadequ... | TunnelLifecycleError | identifier_name |
pixel_format.rs | // The MIT License (MIT)
//
// Copyright (c) 2018 Michael Dilger
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, ... |
}
bitflags! {
pub struct PixelFormatFlags: u32 {
/// Texture contains alpha data.
const ALPHA_PIXELS = 0x1;
/// Alpha channel only uncomressed data (used in older DDS files)
const ALPHA = 0x2;
/// Texture contains compressed RGB data.
const FOURCC = 0x4;
///... | {
let mut pf: PixelFormat = Default::default();
if let Some(bpp) = format.get_bits_per_pixel() {
pf.flags.insert(PixelFormatFlags::RGB); // means uncompressed
pf.rgb_bit_count = Some(bpp as u32)
}
pf.fourcc = Some(FourCC(FourCC::DX10)); // we always use extention ... | identifier_body |
pixel_format.rs | // The MIT License (MIT)
//
// Copyright (c) 2018 Michael Dilger
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, ... |
let flags = PixelFormatFlags::from_bits_truncate(r.read_u32::<LittleEndian>()?);
let fourcc = r.read_u32::<LittleEndian>()?;
let rgb_bit_count = r.read_u32::<LittleEndian>()?;
let r_bit_mask = r.read_u32::<LittleEndian>()?;
let g_bit_mask = r.read_u32::<LittleEndian>()?;
... | {
return Err(Error::InvalidField("Pixel format struct size".to_owned()));
} | conditional_block |
pixel_format.rs | // The MIT License (MIT)
//
// Copyright (c) 2018 Michael Dilger
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, ... | )?;
Ok(())
}
}
impl Default for PixelFormat {
fn default() -> PixelFormat {
PixelFormat {
size: 32, // must be 32
flags: PixelFormatFlags::empty(),
fourcc: None,
rgb_bit_count: None,
r_bit_mask: None,
g_bit_mask: No... | writeln!(
f,
" RGBA bitmasks: {:?}, {:?}, {:?}, {:?}",
self.r_bit_mask, self.g_bit_mask, self.b_bit_mask, self.a_bit_mask | random_line_split |
pixel_format.rs | // The MIT License (MIT)
//
// Copyright (c) 2018 Michael Dilger
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, ... | <W: Write>(&self, w: &mut W) -> Result<(), Error> {
w.write_u32::<LittleEndian>(self.size)?;
w.write_u32::<LittleEndian>(self.flags.bits())?;
w.write_u32::<LittleEndian>(self.fourcc.as_ref().unwrap_or(&FourCC(0)).0)?;
w.write_u32::<LittleEndian>(self.rgb_bit_count.unwrap_or(0))?;
... | write | identifier_name |
main.rs | #![feature(proc_macro)]
#![no_std]
extern crate cortex_m;
extern crate cortex_m_rtfm as rtfm;
extern crate stm32f30x_hal as hal;
extern crate ls010b7dh01;
extern crate rn4870;
extern crate embedded_graphics as graphics;
extern crate panic_abort;
extern crate nb;
mod display;
mod ble;
use cortex_m::asm;
use cortex_m:... | rcc.apb2.rstr().modify(|_, w| w.syscfgrst().clear_bit());
// Enable systick
p.core.SYST.set_clock_source(SystClkSource::Core);
p.core.SYST.set_reload(16_000_000);
p.core.SYST.enable_interrupt();
p.core.SYST.enable_counter();
// Set up our clocks & timer & delay
let clocks = rcc.cfgr.fr... |
// Enable the syscfg
rcc.apb2.enr().modify(|_, w| w.syscfgen().enabled());
rcc.apb2.rstr().modify(|_, w| w.syscfgrst().set_bit()); | random_line_split |
main.rs | #![feature(proc_macro)]
#![no_std]
extern crate cortex_m;
extern crate cortex_m_rtfm as rtfm;
extern crate stm32f30x_hal as hal;
extern crate ls010b7dh01;
extern crate rn4870;
extern crate embedded_graphics as graphics;
extern crate panic_abort;
extern crate nb;
mod display;
mod ble;
use cortex_m::asm;
use cortex_m:... |
fn exti9_5(_t: &mut Threshold, mut r: EXTI9_5::Resources) {
if r.EXTI.pr1.read().pr8().bit_is_set() {
r.EXTI.pr1.modify(|_, w| w.pr8().set_bit());
*r.STATE = State::Ble;
}
if r.EXTI.pr1.read().pr9().bit_is_set() {
r.EXTI.pr1.modify(|_, w| w.pr9().set_bit());
*r.STATE = Sta... | {
let res = r.BLE.read_raw();
match res {
Ok(n) => {
if n < 32 {
return
}
(*r.DRAW_BUFFER)[*r.BUFFER_POS as usize] = n;
*r.BUFFER_POS += 1;
if *r.BUFFER_POS == 16 {
*r.BUFFER_POS = 0;
}
}
... | identifier_body |
main.rs | #![feature(proc_macro)]
#![no_std]
extern crate cortex_m;
extern crate cortex_m_rtfm as rtfm;
extern crate stm32f30x_hal as hal;
extern crate ls010b7dh01;
extern crate rn4870;
extern crate embedded_graphics as graphics;
extern crate panic_abort;
extern crate nb;
mod display;
mod ble;
use cortex_m::asm;
use cortex_m:... |
}
Err(nb::Error::Other(_)) => {
r.BLE.handle_error(|uart| { uart.clear_overflow_error(); } );
}
Err(nb::Error::WouldBlock) => {}
}
}
fn exti9_5(_t: &mut Threshold, mut r: EXTI9_5::Resources) {
if r.EXTI.pr1.read().pr8().bit_is_set() {
r.EXTI.pr1.modify(|_, w... | {
*r.BUFFER_POS = 0;
} | conditional_block |
main.rs | #![feature(proc_macro)]
#![no_std]
extern crate cortex_m;
extern crate cortex_m_rtfm as rtfm;
extern crate stm32f30x_hal as hal;
extern crate ls010b7dh01;
extern crate rn4870;
extern crate embedded_graphics as graphics;
extern crate panic_abort;
extern crate nb;
mod display;
mod ble;
use cortex_m::asm;
use cortex_m:... | (_t: &mut Threshold, mut r: TIM7::Resources) {
}
fn sys_tick(_t: &mut Threshold, mut r: SYS_TICK::Resources) {
let toggle = *r.TOGGLE;
let extcomin = &mut *r.EXTCOMIN;
if *r.RESET_BLE {
r.BLE.hard_reset_on();
*r.RESET_BLE = false;
} else {
r.BLE.hard_reset_off();
}
mat... | tick | identifier_name |
conv2d_compact.rs | use super::{ConstraintSystem, Scalar, MemoryManager, Memory, TensorAddress, SCALAR_SIZE, BigScalar, RangeFull, Range, RangeFrom, RangeTo, Id, min, Functions, ActivationFunction};
use crate::scalar::power_of_two;
impl ConstraintSystem {
pub fn run_conv2d_compact<T: Scalar>(mem: &MemoryManager, param: &[u32], var_di... | }
mul_input.push(mul_input_row);
}
//packing bias
let mut packed_bias: Vec<Vec<TensorAddress>> = Vec::with_capacity(fout as usize);
let mut bias_dim = 0;
let mut bias_scale = 0;
if let Some((b, scale)) = bias {
bias_dim = (col - k_col)... | let mut mul_input_row = Vec::new();
for c in 0..col_packed {
mul_input_row.push(self.mem.save(self.mem[packed_layer].at(&[RangeFull(), Range(r..r + k_row), Id(c)]))); | random_line_split |
conv2d_compact.rs | use super::{ConstraintSystem, Scalar, MemoryManager, Memory, TensorAddress, SCALAR_SIZE, BigScalar, RangeFull, Range, RangeFrom, RangeTo, Id, min, Functions, ActivationFunction};
use crate::scalar::power_of_two;
impl ConstraintSystem {
pub fn run_conv2d_compact<T: Scalar>(mem: &MemoryManager, param: &[u32], var_di... | for r in 0..row - k_row + 1 {
let mut mul_input_row = Vec::new();
for c in 0..col_packed {
mul_input_row.push(self.mem.save(self.mem[packed_layer].at(&[RangeFull(), Range(r..r + k_row), Id(c)])));
}
mul_input.push(mul_input_row);
}
... | {
// packing weight
let dim = &self.mem[weight_rev].dim;
let (fout, fin, k_row, k_col) = (dim[0], dim[1], dim[2], dim[3]);
let packed_weight = self.mem.alloc(&[fout, fin, k_row]);
assert!(k_col * (bit_length as u32) <= SCALAR_SIZE);
self.packing_tensor(weight_rev, packed... | identifier_body |
conv2d_compact.rs | use super::{ConstraintSystem, Scalar, MemoryManager, Memory, TensorAddress, SCALAR_SIZE, BigScalar, RangeFull, Range, RangeFrom, RangeTo, Id, min, Functions, ActivationFunction};
use crate::scalar::power_of_two;
impl ConstraintSystem {
pub fn run_conv2d_compact<T: Scalar>(mem: &MemoryManager, param: &[u32], var_di... | () {
let mut x = ConstraintSystem::new();
let input = x.mem.alloc(&[1,4,3]);
let weight = x.mem.alloc(&[1,1,3,3]);
let output = x.mem.alloc(&[1,2,1]);
let weight_rev = x.mem.save(x.mem[weight].reverse(3));
x.conv2d_compact(input, output, weight_rev, None, 5,ActivationF... | conv2d_compact_test_small | identifier_name |
conv2d_compact.rs | use super::{ConstraintSystem, Scalar, MemoryManager, Memory, TensorAddress, SCALAR_SIZE, BigScalar, RangeFull, Range, RangeFrom, RangeTo, Id, min, Functions, ActivationFunction};
use crate::scalar::power_of_two;
impl ConstraintSystem {
pub fn run_conv2d_compact<T: Scalar>(mem: &MemoryManager, param: &[u32], var_di... | else {
None
};
res[i] = (full, rem);
}
res
}
fn extract_sign_part(c: &mut ConstraintSystem, extracted: TensorAddress, bit_length: u8) {
let output = c.mem.alloc(&c.mem[extracted].dim.to_owned());
c.sign... | {
Some(mem.save(tmp.at(&[RangeFull(), RangeFull(), Id(n), Range(pos[i]..remainder)])))
} | conditional_block |
search.rs | use super::context;
use super::Contrapositive;
use super::{Cuts, Db, Steps};
use crate::offset::{OLit, Offset, Sub};
use crate::subst::Ptr as SubPtr;
use crate::{Lit, Rewind};
use alloc::vec::Vec;
use core::{fmt::Display, hash::Hash, ops::Neg};
use log::debug;
pub struct Search<'t, P, C> {
task: Task<'t, P, C>,
... |
}
impl<C: IntoIterator> Iterator for TaskIter<C> {
type Item = <C::IntoIter as Iterator>::Item;
fn next(&mut self) -> Option<Self::Item> {
self.0.next()
}
}
pub type Task<'t, P, C> = TaskIter<super::clause::OClause<'t, Lit<P, C, usize>>>;
pub type Context<'t, P, C> = context::Context<Vec<OLit<'t... | {
Self(cl.into_iter().skip(0))
} | identifier_body |
search.rs | use super::context;
use super::Contrapositive;
use super::{Cuts, Db, Steps};
use crate::offset::{OLit, Offset, Sub};
use crate::subst::Ptr as SubPtr;
use crate::{Lit, Rewind};
use alloc::vec::Vec;
use core::{fmt::Display, hash::Hash, ops::Neg};
use log::debug;
pub struct Search<'t, P, C> {
task: Task<'t, P, C>,
... | (&mut self) -> State<'t, P, C> {
debug!("try alternative ({} left)", self.alternatives.len());
self.alternatives.pop().ok_or(false).map(|(alt, action)| {
self.rewind(alt);
action
})
}
}
impl<'t, P, C> From<&Search<'t, P, C>> for Alternative<'t, P, C> {
fn from(st... | try_alternative | identifier_name |
search.rs | use super::context;
use super::Contrapositive;
use super::{Cuts, Db, Steps};
use crate::offset::{OLit, Offset, Sub};
use crate::subst::Ptr as SubPtr;
use crate::{Lit, Rewind};
use alloc::vec::Vec;
use core::{fmt::Display, hash::Hash, ops::Neg};
use log::debug;
pub struct Search<'t, P, C> {
task: Task<'t, P, C>,
... | else {
self.ctx.rewind(alt.ctx_ptr);
}
if let Some(promises) = alt.promises {
self.promises = promises;
} else {
assert!(self.promises.len() >= alt.promises_len);
self.promises.truncate(alt.promises_len);
}
self.sub.rewind(&alt.s... | {
self.ctx = ctx;
} | conditional_block |
search.rs | use super::context;
use super::Contrapositive;
use super::{Cuts, Db, Steps};
use crate::offset::{OLit, Offset, Sub};
use crate::subst::Ptr as SubPtr;
use crate::{Lit, Rewind};
use alloc::vec::Vec;
use core::{fmt::Display, hash::Hash, ops::Neg};
use log::debug;
pub struct Search<'t, P, C> {
task: Task<'t, P, C>,
... | }
}
fn ext(&mut self, lit: OLit<'t, P, C>, cs: Contras<'t, P, C>, skip: usize) -> State<'t, P, C> {
let alt = Alternative::from(&*self);
let prm = Promise::from(&*self);
let sub = SubPtr::from(&self.sub);
for (eidx, entry) in cs.iter().enumerate().skip(skip) {
... | let neg = -lit.head().clone();
match self.db.get(&neg) {
Some(entries) => self.ext(lit, entries, 0),
None => self.try_alternative(), | random_line_split |
main.rs | #[macro_use]
extern crate log;
extern crate fern;
extern crate chrono;
extern crate libc;
mod configuration;
use configuration::ServerData;
use configuration::ClientData;
use std::sync::mpsc;
use std::thread;
use std::time;
use std::time::SystemTime;
use std::env;
/*================================================... |
fn get_virtual_link(&self) -> VirtualLink {
VirtualLink::to_iface(self)
}
}
/*==============================================================================
* Host
*
*/
struct Host {
nic: NetworkInterface,
}
impl Host {
fn new() -> Host {
Host {
nic: NetworkInterface::new(),
... | {
self.r.recv().unwrap()
} | identifier_body |
main.rs | #[macro_use]
extern crate log;
extern crate fern;
extern crate chrono;
extern crate libc;
mod configuration;
use configuration::ServerData;
use configuration::ClientData;
use std::sync::mpsc;
use std::thread;
use std::time;
use std::time::SystemTime;
use std::env;
/*================================================... |
(self.total as f64) / (self.samples as f64)
}
}
/*==============================================================================
* Server
*
*/
struct Server {
id: u32,
host: Host,
processing_power: u64
}
impl Server {
fn new(id: u32, server_data: ServerData) -> Server {
Server {
id: id,
... | {
return 0.0;
} | conditional_block |
main.rs | #[macro_use]
extern crate log;
extern crate fern;
extern crate chrono;
extern crate libc;
mod configuration;
use configuration::ServerData;
use configuration::ClientData;
use std::sync::mpsc;
use std::thread;
use std::time;
use std::time::SystemTime;
use std::env;
/*================================================... |
let mut threads = Vec::new();
let mut servers: Vec<Server> = Vec::new();
let mut clients: Vec<Client> = Vec::new();
info!("[T0] Inicializando servidores");
let server_data: Vec<ServerData> = configuration.get_server_dataset();
let mut server_count = 0;
for d in server_data {
server_count += 1;
... | random_line_split | |
main.rs | #[macro_use]
extern crate log;
extern crate fern;
extern crate chrono;
extern crate libc;
mod configuration;
use configuration::ServerData;
use configuration::ClientData;
use std::sync::mpsc;
use std::thread;
use std::time;
use std::time::SystemTime;
use std::env;
/*================================================... | () -> NetworkInterface {
let (tx, rx) = mpsc::channel();
NetworkInterface {
s: tx,
r: rx
}
}
fn read(&self) -> Packet {
self.r.recv().unwrap()
}
fn get_virtual_link(&self) -> VirtualLink {
VirtualLink::to_iface(self)
}
}
/*==================================================... | new | identifier_name |
main.rs | use std::string::ToString;
fn main() |
fn vectors() {
let v: Vec<i32> = Vec::new();
let mut v = vec![1, 2, 3];
match v.binary_search(&16) {
Ok(pos) => v.insert(pos, 16),
Err(_) => v.push(16)
}
match v.binary_search(&12) {
Ok(pos) => v.insert(pos, 12),
Err(pos) => v.insert(pos, 12)
}
println!("... | {
vectors();
strings();
hashmaps();
} | identifier_body |
main.rs | use std::string::ToString;
fn main() {
vectors();
strings();
hashmaps();
}
fn vectors() {
let v: Vec<i32> = Vec::new();
let mut v = vec![1, 2, 3];
match v.binary_search(&16) {
Ok(pos) => v.insert(pos, 16),
Err(_) => v.push(16)
}
match v.binary_search(&12) {
Ok... | let hello = String::from("שָׁלוֹם");
let hello = String::from("नमस्ते");
let hello = String::from("こんにちは");
let hello = String::from("안녕하세요");
let hello = String::from("你好");
let hello = String::from("Olá");
let hello = String::from("Здравствуйте");
let hello = String::from("Hola");
... | let hello = String::from("Dobrý den");
let hello = String::from("Hello"); | random_line_split |
main.rs | use std::string::ToString;
fn main() {
vectors();
strings();
hashmaps();
}
fn vectors() {
let v: Vec<i32> = Vec::new();
let mut v = vec![1, 2, 3];
match v.binary_search(&16) {
Ok(pos) => v.insert(pos, 16),
Err(_) => v.push(16)
}
match v.binary_search(&12) {
Ok... | let mut s = String::new();
let m = String::from("sdfsdf");
let data = "initial contents";
let s = data.to_string();
// the method also works on a literal directly:
let s = "initial contents".to_string();
let hello = String::from("السلام عليكم");
let hello = String::from("Dobrý den");
... | s() {
| identifier_name |
main.rs | use std::fmt;
use std::collections::{VecDeque, HashSet};
use intcode::{Word, util::{parse_stdin_program, GameDisplay}, Program, Registers, ExecutionState};
fn main() {
let mut robot = Robot::new(parse_stdin_program());
let mut gd: GameDisplay<Tile> = GameDisplay::default();
gd.insert(robot.position(), Til... | (gd: &GameDisplay<Tile>, pos: &(Word, Word), target: &(Word, Word)) -> Option<Vec<Direction>> {
//println!("path_to: {:?} to {:?}", pos, target);
use std::collections::{HashMap, BinaryHeap};
use std::collections::hash_map::Entry;
use std::cmp;
let mut ret = Vec::new();
let mut work = BinaryHea... | path_to | identifier_name |
main.rs | use std::fmt;
use std::collections::{VecDeque, HashSet};
use intcode::{Word, util::{parse_stdin_program, GameDisplay}, Program, Registers, ExecutionState};
fn main() {
let mut robot = Robot::new(parse_stdin_program());
let mut gd: GameDisplay<Tile> = GameDisplay::default();
gd.insert(robot.position(), Til... |
if alt < *dist.get(&p2).unwrap_or(&usize::max_value()) {
//println!(" {:?} --{:?}--> {:?}", p, dir, p2);
dist.insert(p2, alt);
prev.insert(p2, p);
work.push(cmp::Reverse((alt, p2)));
}
}
}
None
}
#[test]
fn test... | }
}
for (p2, dir) in adjacent(gd, &p) {
let alt = steps_here + 1; | random_line_split |
connection.rs | pub(crate) keyboard_mapper: RefCell<Option<Keyboard>>,
pub(crate) keyboard_window_id: RefCell<Option<usize>>,
pub(crate) surface_to_window_id: RefCell<HashMap<u32, usize>>,
pub(crate) active_surface_id: RefCell<u32>,
/// Repeats per second
pub(crate) key_repeat_rate: RefCell<i32>,
pub(crat... | }
_ => {}
}
}
_ => {}
}
if let Some(&window_id) = self.keyboard_window_id.borrow().as_ref() {
if let Some(win) = self.window_by_id(window_id) {
let mut inner = win.borrow_mut();
i... | {
let file = unsafe { std::fs::File::from_raw_fd(*fd) };
match format {
KeymapFormat::XkbV1 => {
let mut data = vec![0u8; *size as usize];
file.read_exact_at(&mut data, 0)?;
// Dance around CStrin... | conditional_block |
connection.rs | pub(crate) keyboard_mapper: RefCell<Option<Keyboard>>,
pub(crate) keyboard_window_id: RefCell<Option<usize>>,
pub(crate) surface_to_window_id: RefCell<HashMap<u32, usize>>,
pub(crate) active_surface_id: RefCell<u32>,
/// Repeats per second
pub(crate) key_repeat_rate: RefCell<i32>,
pub(crat... | (
&self,
keyboard: Main<WlKeyboard>,
event: WlKeyboardEvent,
) -> anyhow::Result<()> {
match &event {
WlKeyboardEvent::Enter {
serial, surface,..
} => {
// update global active surface id
*self.active_surface_id.... | keyboard_event | identifier_name |
connection.rs |
pub(crate) keyboard_mapper: RefCell<Option<Keyboard>>,
pub(crate) keyboard_window_id: RefCell<Option<usize>>,
pub(crate) surface_to_window_id: RefCell<HashMap<u32, usize>>,
pub(crate) active_surface_id: RefCell<u32>,
/// Repeats per second
pub(crate) key_repeat_rate: RefCell<i32>,
pub(cra... | windows: RefCell::new(HashMap::new()),
event_q: RefCell::new(event_q),
pointer: RefCell::new(pointer),
seat_listener,
mem_pool: RefCell::new(mem_pool),
gl_connection: RefCell::new(None),
keyboard_mapper: RefCell::new(None),
... | random_line_split | |
connection.rs | pub(crate) keyboard_mapper: RefCell<Option<Keyboard>>,
pub(crate) keyboard_window_id: RefCell<Option<usize>>,
pub(crate) surface_to_window_id: RefCell<HashMap<u32, usize>>,
pub(crate) active_surface_id: RefCell<u32>,
/// Repeats per second
pub(crate) key_repeat_rate: RefCell<i32>,
pub(crat... |
pub(crate) fn next_window_id(&self) -> usize {
self.next_window_id
.fetch_add(1, ::std::sync::atomic::Ordering::Relaxed)
}
fn flush(&self) -> anyhow::Result<()> {
if let Err(e) = self.display.borrow_mut().flush() {
if e.kind()!= ::std::io::ErrorKind::WouldBlock {
... | {
if let Some(&window_id) = self.keyboard_window_id.borrow().as_ref() {
if let Some(win) = self.window_by_id(window_id) {
let mut inner = win.borrow_mut();
inner.events.dispatch(event);
}
}
} | identifier_body |
substitution.rs | use std::{cell::RefCell, default::Default, fmt};
use union_find::{QuickFindUf, Union, UnionByRank, UnionFind, UnionResult};
use crate::base::{
fixed::{FixedVec, FixedVecMap},
kind::ArcKind,
symbol::Symbol,
types::{self, ArcType, Flags, FlagsVisitor, Skolem, Type, TypeContext, Walker},
};
use crate::ty... | (&self, var: u32) -> Option<&T> {
self.variables.get(var as usize)
}
pub fn find_type_for_var(&self, var: u32) -> Option<&T> {
let mut union = self.union.borrow_mut();
if var as usize >= union.size() {
return None;
}
let index = union.find(var as usize);
... | get_var | identifier_name |
substitution.rs | use std::{cell::RefCell, default::Default, fmt};
use union_find::{QuickFindUf, Union, UnionByRank, UnionFind, UnionResult};
use crate::base::{
fixed::{FixedVec, FixedVecMap},
kind::ArcKind,
symbol::Symbol,
types::{self, ArcType, Flags, FlagsVisitor, Skolem, Type, TypeContext, Walker},
};
use crate::ty... | let mut union = self.union.borrow_mut();
union.get_mut(other as usize).level = level;
}
pub fn set_level(&self, var: u32, level: u32) {
let mut union = self.union.borrow_mut();
union.get_mut(var as usize).level = level;
}
pub fn get_level(&self, mut var: u32) -> u32 {
... |
/// Updates the level of `other` to be the minimum level value of `var` and `other`
pub fn update_level(&self, var: u32, other: u32) {
let level = ::std::cmp::min(self.get_level(var), self.get_level(other)); | random_line_split |
day_14.rs | //! This is my solution for [Advent of Code - Day 14](https://adventofcode.com/2020/day/14) -
//! _Docking Data_
//!
//! This was themed around bitwise operations. The challenge was mostly parsing the puzzle
//! description into the bitwise operations needed. This was the first time I needed an Either
//! implementatio... | for &address in addresses.iter() {
new_addresses.insert(address | (1 << i));
}
for &new_address in new_addresses.iter() {
addresses.insert(new_address);
};
}
}
addresses
}
/// Sum a memory snapshot
///
/// Both puzzle par... | let mut new_addresses = HashSet::new();
| random_line_split |
day_14.rs | //! This is my solution for [Advent of Code - Day 14](https://adventofcode.com/2020/day/14) -
//! _Docking Data_
//!
//! This was themed around bitwise operations. The challenge was mostly parsing the puzzle
//! description into the bitwise operations needed. This was the first time I needed an Either
//! implementatio... |
#[test]
fn can_explode_addresses() {
let expected: HashSet<usize> = vec!(26usize, 27usize, 58usize, 59usize).into_iter().collect();
assert_eq!(
expected,
explode_addresses(
&Mask {
mask: 0b000000000000000000000000000000100001,
... | {
let mut expected: HashMap<usize, usize> = HashMap::new();
let program_1 = "mask = XXXXXXXXXXXXXXXXXXXXXXXXXXXXX1XXXX0X\nmem[8] = 11";
expected.insert(8, 73);
assert_eq!(expected, run_program_v1(program_1));
let program_2 = "mask = XXXXXXXXXXXXXXXXXXXXXXXXXXXXX1XXXX0X
mem[8] =... | identifier_body |
day_14.rs | //! This is my solution for [Advent of Code - Day 14](https://adventofcode.com/2020/day/14) -
//! _Docking Data_
//!
//! This was themed around bitwise operations. The challenge was mostly parsing the puzzle
//! description into the bitwise operations needed. This was the first time I needed an Either
//! implementatio... | (line: &str) -> Either<Mask, Mem> {
let mut parts = line.split(" = ");
let inst = parts.next().expect("Invalid line");
let value = parts.next().expect("Invalid line");
if inst == "mask" {
let (mask, data) =
value.chars().fold(
(0usize, 0usize),
|(mask... | parse_line | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.