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 |
|---|---|---|---|---|
read_pool.rs | // Copyright 2020 EinsteinDB Project Authors. Licensed under Apache-2.0.
use futures::channel::oneshot;
use futures::future::TryFutureExt;
use prometheus::IntGauge;
use std::future::Future;
use std::sync::{Arc, Mutex};
use thiserror::Error;
use yatp::pool::Remote;
use yatp::queue::Extras;
use yatp::task::future::Task... | (
max_concurrent_reads: usize,
remote: Remote,
extras: Extras,
pending_reads_gauge: IntGauge,
) -> Self {
let pool = yatp::pool::Pool::new(
max_concurrent_reads,
remote,
extras,
);
Self {
pool,
pendin... | new | identifier_name |
write.rs | .field("epochs", &self.epochs)
.field("w_handle", &self.w_handle)
.field("oplog", &self.oplog)
.field("swap_index", &self.swap_index)
.field("r_handle", &self.r_handle)
.field("first", &self.first)
.field("second", &self.second)
.finis... | else {
self.oplog.extend(ops);
}
}
}
/// `WriteHandle` can be sent across thread boundaries:
///
/// ```
/// use left_right::WriteHandle;
///
/// struct Data;
/// impl left_right::Absorb<()> for Data {
/// fn absorb_first(&mut self, _: &mut (), _: &Self) {}
/// fn sync_with(&mut self, ... | {
// Safety: we know there are no outstanding w_handle readers, since we haven't
// refreshed ever before, so we can modify it directly!
let mut w_inner = self.raw_write_handle();
let w_inner = unsafe { w_inner.as_mut() };
let r_handle = self.enter().expect("m... | conditional_block |
write.rs | // ensure that the subsequent epoch reads aren't re-ordered to before the swap
fence(Ordering::SeqCst);
// all readers have now observed the NULL, so we own both handles.
// all operations have been applied to both w_handle and r_handle.
// give the underlying data structure an opport... | {
let (mut w, _) = crate::new::<i32, _>();
// Until we refresh, writes are written directly instead of going to the
// oplog (because there can't be any readers on the w_handle table).
assert!(!w.has_pending_operations());
w.publish();
assert!(!w.has_pending_operations()... | identifier_body | |
write.rs | .field("epochs", &self.epochs)
.field("w_handle", &self.w_handle)
.field("oplog", &self.oplog)
.field("swap_index", &self.swap_index)
.field("r_handle", &self.r_handle)
.field("first", &self.first)
.field("second", &self.second)
.fini... | #[test]
fn take_test() {
// publish twice then take with no pending operations
let (mut w, _r) = crate::new_from_empty::<i32, _>(2);
w.append(CounterAddOp(1));
w.publish();
w.append(CounterAddOp(1));
w.publish();
assert_eq!(*w.take(), 4);
// publi... | assert_eq!(w.oplog.len(), 2);
}
| random_line_split |
write.rs | <T, O>
where
T: Absorb<O>,
{
epochs: crate::Epochs,
w_handle: NonNull<T>,
oplog: VecDeque<O>,
swap_index: usize,
r_handle: ReadHandle<T>,
last_epochs: Vec<usize>,
#[cfg(test)]
refreshes: usize,
#[cfg(test)]
is_waiting: Arc<AtomicBool>,
/// Write directly to the write hand... | WriteHandle | identifier_name | |
codec.rs | // single parity arrays for compatibility with a faster future codec.
if f == 1 {
isa_l::gf_gen_rs_matrix(&mut enc_matrix, m, k);
} else {
isa_l::gf_gen_cauchy1_matrix(&mut enc_matrix, m, k);
}
// The encoding tables only use the encoding matrix's parity rows ... | /// `f` parity columns, where one or more columns is missing, reconstruct
/// the data from the missing columns. Takes as a parameter exactly `k`
/// surviving columns, even if more than `k` columns survive. These *must*
/// be the lowest `k` surviving columns. For example, in a 5+3 array where
/... |
/// Reconstruct missing data from partial surviving columns
///
/// Given a `Codec` with `m` total columns composed of `k` data columns and | random_line_split |
codec.rs | // single parity arrays for compatibility with a faster future codec.
if f == 1 {
isa_l::gf_gen_rs_matrix(&mut enc_matrix, m, k);
} else {
isa_l::gf_gen_cauchy1_matrix(&mut enc_matrix, m, k);
}
// The encoding tables only use the encoding matrix's parity rows (e... |
for j in 0..k {
dec_rows[k * i + j] =
dec_matrix[k * r + j];
}
}
// Finally generate the fast encoding tables
isa_l::ec_init_tables(k as u32, errs as u32, &dec_rows, &mut dec_tables);
dec_tables
}
/// Return the degre... | {
break; // Exclude missing parity columns
} | conditional_block |
codec.rs | // single parity arrays for compatibility with a faster future codec.
if f == 1 {
isa_l::gf_gen_rs_matrix(&mut enc_matrix, m, k);
} else {
isa_l::gf_gen_cauchy1_matrix(&mut enc_matrix, m, k);
}
// The encoding tables only use the encoding matrix's parity rows (e... | (&self, _len: usize, _data: &[*const u8],
_parity: &[*const u8]) -> FixedBitSet {
panic!("Unimplemented");
}
/// Reconstruct missing data from partial surviving columns
///
/// Given a `Codec` with `m` total columns composed of `k` data columns and
/// `f` parity columns, w... | check | identifier_name |
codec.rs | // single parity arrays for compatibility with a faster future codec.
if f == 1 {
isa_l::gf_gen_rs_matrix(&mut enc_matrix, m, k);
} else {
isa_l::gf_gen_cauchy1_matrix(&mut enc_matrix, m, k);
}
// The encoding tables only use the encoding matrix's parity rows (e... | data.push(column);
}
for _ in 0..maxparity {
let column = vec![0u8; len];
parity.push(column);
}
for _ in 0..(maxparity as usize) {
reconstructed.push(vec![0u8; len]);
}
for cfg in &cfgs {
let m = cfg.0;
... | {
let cfgs = [
(3, 1), (9, 1),
(4, 2), (10, 2),
(6, 3), (19, 3),
(8, 4), (20, 4)
];
let len = 64;
let maxdata = 28;
let maxparity = 4;
let mut rng = rand::thread_rng();
let mut data = Vec::<Vec<u8>>::new();
... | identifier_body |
level.rs |
use ggez;
use ggez::graphics;
use ggez_goodies::scene;
use ggez_goodies::tilemap::tiled as tiled;
use ggez_goodies::tilemap::Map as Map;
use log::*;
use specs::{self, Join};
use specs::world::Builder;
use warmy;
// use std::path;
use ggez::nalgebra as na;
use ncollide2d as nc;
use crate::components as c;
use crate::... |
fn update_collisions(&mut self, world: &mut World) {
let mut collide_world = world.specs_world.write_resource::<nc::world::CollisionWorld<f32, specs::Entity>>();
collide_world.update();
let mut motions = world.specs_world.write_storage::<c::Motion>();
// gameworld.collide_world.... | {
let builder = specs::DispatcherBuilder::new()
.with(MovementSystem, "sys_movement", &[])
.with(CollisionSystem, "sys_collision", &[]);
// builder.add_thread_local(RenderSystem);
builder.build()
} | identifier_body |
level.rs |
use ggez;
use ggez::graphics;
use ggez_goodies::scene;
use ggez_goodies::tilemap::tiled as tiled;
use ggez_goodies::tilemap::Map as Map;
use log::*;
use specs::{self, Join};
use specs::world::Builder;
use warmy;
// use std::path;
use ggez::nalgebra as na;
use ncollide2d as nc;
use crate::components as c;
use crate::... | // motion.velocity = rotation.transform_vector(&player_motion.acceleration);
}
}
ncollide2d::pipeline::narrow_phase::ContactEvent::Stopped(handle1, handle2) =>
{
println!("contact ended");
... | {
println!("contact started!");
// look up collision object
let obj1 = collide_world.collision_object(*handle1).expect("missing coll obj1");
// look up entity
let entity1: &specs::Entity = obj1.data(... | conditional_block |
level.rs | use ggez;
use ggez::graphics;
use ggez_goodies::scene;
use ggez_goodies::tilemap::tiled as tiled;
use ggez_goodies::tilemap::Map as Map;
use log::*;
use specs::{self, Join};
use specs::world::Builder;
use warmy;
// use std::path;
use ggez::nalgebra as na;
use ncollide2d as nc;
use crate::components as c;
use crate::u... | fn update(&mut self, gameworld: &mut World, _ctx: &mut ggez::Context) -> scenes::Switch {
self.dispatcher.dispatch(&mut gameworld.specs_world.res);
self.update_collisions(gameworld);
if self.done {
scene::SceneSwitch::Pop
} else {
scene::SceneSwitch::None
... | // fn camera_draw(ctx: &mut ggez::Context, drawable: &graphics::Drawable, params: graphics::DrawParam) -> ggez::GameResult<()> {
// Ok(())
// }
impl scene::Scene<World, input::Event> for LevelScene { | random_line_split |
level.rs |
use ggez;
use ggez::graphics;
use ggez_goodies::scene;
use ggez_goodies::tilemap::tiled as tiled;
use ggez_goodies::tilemap::Map as Map;
use log::*;
use specs::{self, Join};
use specs::world::Builder;
use warmy;
// use std::path;
use ggez::nalgebra as na;
use ncollide2d as nc;
use crate::components as c;
use crate::... | () -> specs::Dispatcher<'static,'static> {
let builder = specs::DispatcherBuilder::new()
.with(MovementSystem, "sys_movement", &[])
.with(CollisionSystem, "sys_collision", &[]);
// builder.add_thread_local(RenderSystem);
builder.build()
}
fn update_collisions(&mut... | register_systems | identifier_name |
lib.rs | .0, 0.0)
}
}
impl Default for Settings {
fn default() -> Settings {
Settings {
text_width: 8.0,
text_height: 16.0,
}
}
}
enum Anchor{
Start,
Middle,
End
}
#[derive(Debug)]
struct Body{
memes: Vec<Meme>,
rest_str: Vec<(usize, String)>
}
impl Bo... |
}
y += 1;
}
(svg_elements, relines, get_styles())
}
/// parse the memes and return the svg together with the unmatched strings
fn line_to_svg_with_excess_str(y: usize, s: &str, settings:&Settings) -> Option<(Vec<Box<Node>>, String)>{
let body = parse_memes(s);
if body.has_memes(){
... | {
relines.push_str(line);
relines.push('\n');
} | conditional_block |
lib.rs | .0, 0.0)
}
}
impl Default for Settings {
fn default() -> Settings {
Settings {
text_width: 8.0,
text_height: 16.0,
}
}
}
enum Anchor{
Start,
Middle,
End
}
#[derive(Debug)]
struct Body{
memes: Vec<Meme>,
rest_str: Vec<(usize, String)>
}
impl Bo... | (s: &str, x: f32, y: f32, settings: &Settings, anchor: Anchor) -> SvgText {
to_svg_text_pixel_escaped(&escape_str(s), x, y, settings, anchor)
}
fn to_svg_text_pixel_escaped(s: &str, x: f32, y: f32, settings: &Settings, anchor: Anchor) -> SvgText {
let (offsetx, offsety) = settings.offset();
let sx = x + of... | to_svg_text_pixel | identifier_name |
lib.rs | (0.0, 0.0)
}
}
impl Default for Settings {
fn default() -> Settings {
Settings {
text_width: 8.0,
text_height: 16.0,
}
}
}
enum Anchor{
Start,
Middle,
End
}
#[derive(Debug)]
struct Body{
memes: Vec<Meme>,
rest_str: Vec<(usize, String)>
}
impl... | let mut new_group = vec![];
//println!("regrouping text..");
for &(start,ref rest) in rest_text{
if new_group.is_empty(){
new_group.push((start, rest.clone()));
}else{
if let Some((lastx, last_rest)) = new_group.pop(){
if lastx + last_rest.width() == st... | }
}
fn regroup_rest_text(rest_text: &Vec<(usize, String)>)->Vec<(usize, String)>{ | random_line_split |
service.rs | /*
* Copyright 2019 OysterPack Inc.
*
* 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 applicabl... |
}
impl IsError for UnsupportedMessageType<'_> {
fn error_id(&self) -> Id {
Self::ERROR_ID
}
fn error_level(&self) -> Level {
Self::ERROR_LEVEL
}
}
impl fmt::Display for UnsupportedMessageType<'_> {
fn fmt(&self, f: &mut fmt::Formatter) ... | {
UnsupportedMessageType {
sender,
message_type,
}
} | identifier_body |
service.rs | /*
* Copyright 2019 OysterPack Inc.
*
* 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 applicabl... | }
}
fn log_config() -> oysterpack_log::LogConfig {
oysterpack_log::config::LogConfigBuilder::new(oysterpack_log::Level::Info).build()
}
const MESSAGE_SERVICE: actor::arbiters::Name = actor::arbiters::Name("MESSAGE_SERVICE");
#[test]
fn message_service() {
let (client_p... | actix::MessageResult(Ok(req.0)) | random_line_split |
service.rs | /*
* Copyright 2019 OysterPack Inc.
*
* 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 applicabl... | (&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"{}: mailbox delivery error for message type: {} : {}",
self.sender, self.message_type, self.err,
)
}
}
}
#[allow(warnings)]
#[cfg(test)]
mod tests {
use crate::actor;
... | fmt | identifier_name |
tar_helper.rs | ///! Tar helper is internal to `/get` implementation. It uses some private parts of the `tar-rs`
///! crate to provide a `BytesMut` writing implementation instead of one using `std::io` interfaces.
///!
///! Code was originally taken and modified from the dependency version of `tar-rs`. The most
///! important copied p... | fn path2bytes(p: &Path) -> &[u8] {
p.as_os_str()
.to_str()
.expect("we should only have unicode compatible bytes even on windows")
.as_bytes()
} | random_line_split | |
tar_helper.rs | ///! Tar helper is internal to `/get` implementation. It uses some private parts of the `tar-rs`
///! crate to provide a `BytesMut` writing implementation instead of one using `std::io` interfaces.
///!
///! Code was originally taken and modified from the dependency version of `tar-rs`. The most
///! important copied p... | }
fn new_default_header() -> tar::Header {
let mut header = tar::Header::new_gnu();
header.set_mtime(0);
header.set_uid(0);
header.set_gid(0);
header
}
fn new_long_filename_header() -> tar::Header {
let mut long_filename_header = tar::Header::new_gnu()... | {
let bytes = BytesMut::with_capacity(n);
// these are 512 a piece
let header = Self::new_default_header();
let long_filename_header = Self::new_long_filename_header();
let mut zeroes = BytesMut::with_capacity(512);
for _ in 0..(512 / 8) {
zeroes.put_u64(0);
... | identifier_body |
tar_helper.rs | ///! Tar helper is internal to `/get` implementation. It uses some private parts of the `tar-rs`
///! crate to provide a `BytesMut` writing implementation instead of one using `std::io` interfaces.
///!
///! Code was originally taken and modified from the dependency version of `tar-rs`. The most
///! important copied p... | (
&mut self,
path: &Path,
metadata: &Metadata,
total_size: u64,
) -> Result<[Option<Bytes>; 3], GetError> {
let mut ret: [Option<Bytes>; 3] = Default::default();
if let Err(e) = self.header.set_path(path) {
let data =
prepare_long_header(&... | apply_file | identifier_name |
root.rs | //! The root task.
use crate::consts::HSI_CLK;
use crate::{
drv::{
exti::{ExtiDrv, ExtiSetup},
flash::Flash,
gpio::GpioHead,
hsi::Hsi,
lse::Lse,
pll::Pll,
rcc::Rcc,
},
drv_gpio_pins,
sys::{gpio_pins::GpioPins, system::System},
thr,
thr::{T... | (
res: &SystemRes,
thr: &Thrs,
exti5: &ExtiDrv<Exti5, thr::Exti95>,
gpio_pins: &GpioPins,
hclk: u32,
) -> Event {
println!("Enter listen, hclk={}", hclk);
// Attach a listener that will notify us on user button pressed.
let mut button_stream = exti5.create_saturating_stream();
// At... | listen | identifier_name |
root.rs | //! The root task.
use crate::consts::HSI_CLK;
use crate::{
drv::{
exti::{ExtiDrv, ExtiSetup},
flash::Flash,
gpio::GpioHead,
hsi::Hsi,
lse::Lse,
pll::Pll,
rcc::Rcc,
},
drv_gpio_pins,
sys::{gpio_pins::GpioPins, system::System},
thr,
thr::{T... |
}
}
}
Event::Push
}
| {
doubleclick_protection = 0;
println!("++");
} | conditional_block |
root.rs | //! The root task.
use crate::consts::HSI_CLK;
use crate::{
drv::{
exti::{ExtiDrv, ExtiSetup},
flash::Flash,
gpio::GpioHead,
hsi::Hsi,
lse::Lse,
pll::Pll,
rcc::Rcc,
},
drv_gpio_pins,
sys::{gpio_pins::GpioPins, system::System},
thr,
thr::{T... |
'user_button_pressed: loop {
// Reset the clock control registers to their default.
System::reset_rcc(&res);
// Apply the current clock tree configuration.
System::apply_clock_config(&res);
// Calculate the configured clock speed.
let hclk = System::calculate_hclk(... | falling: false, // trigger the interrupt on a falling edge.
rising: true, // don't trigger the interrupt on a rising edge.
}); | random_line_split |
wait_cell.rs | <'a> {
/// The [`WaitCell`] being waited on.
cell: &'a WaitCell,
}
#[derive(Eq, PartialEq, Copy, Clone)]
struct State(usize);
// === impl WaitCell ===
impl WaitCell {
loom_const_fn! {
/// Returns a new `WaitCell`, with no [`Waker`] stored in it.
#[must_use]
pub fn new() -> Self {
... | Subscribe | identifier_name | |
wait_cell.rs | (Eq, PartialEq, Copy, Clone)]
struct State(usize);
// === impl WaitCell ===
impl WaitCell {
loom_const_fn! {
/// Returns a new `WaitCell`, with no [`Waker`] stored in it.
#[must_use]
pub fn new() -> Self {
Self {
state: CachePadded::new(AtomicUsize::new(State::W... |
Ok(())
}
}
#[cfg(all(feature = "alloc", not(loom), test))]
mod tests {
use super::*;
use crate::scheduler::Scheduler;
use alloc::sync::Arc;
use tokio_test::{assert_pending, assert_ready, assert_ready_ok, task};
#[test]
fn wait_smoke() {
static COMPLETED: AtomicUsize = At... | {
if *self == Self::WAITING {
return f.write_str("WAITING");
}
f.debug_tuple("UnknownState")
.field(&format_args!("{:#b}", self.0))
.finish()?;
} | conditional_block |
wait_cell.rs | derive(Eq, PartialEq, Copy, Clone)]
struct State(usize);
// === impl WaitCell ===
impl WaitCell {
loom_const_fn! {
/// Returns a new `WaitCell`, with no [`Waker`] stored in it.
#[must_use]
pub fn new() -> Self {
Self {
state: CachePadded::new(AtomicUsize::new(St... | Poll::Ready(Err(PollWaitError::Busy)) => {
// Someone else is in the process of registering. Yield now so we
// can wait until that task is done, and then try again.
cx.waker().wake_by_ref();
return Poll::Pending;
}
Poll... | random_line_split | |
text.rs | Normalization](https://www.w3.org/TR/xml11/#AVNormalize):
///
/// Before the value of an attribute is passed to the application or checked for validity, the XML
/// processor must normalize the attribute value by applying the algorithm below, or by using some
/// other method such that the value passed to the applicat... | || (c >= '\u{D8}' && c <= '\u{F6}')
|| (c >= '\u{0F8}' && c <= '\u{2FF}')
|| (c >= '\u{370}' && c <= '\u{37D}')
|| (c >= '\u{037F}' && c <= '\u{1FFF}')
|| (c >= '\u{200C}' && c <= '\u{200D}')
|| (c >= '\u{2070}' && c <= '\u{218F}')
|| (c >= '\u{2C00}' && c <= '\u{... | || c == '_'
|| (c >= 'a' && c <= 'z')
|| (c >= '\u{C0}' && c <= '\u{D6}') | random_line_split |
text.rs | ization](https://www.w3.org/TR/xml11/#AVNormalize):
///
/// Before the value of an attribute is passed to the application or checked for validity, the XML
/// processor must normalize the attribute value by applying the algorithm below, or by using some
/// other method such that the value passed to the application is ... | else if let Some(a_match) = capture.name("char") {
let replacement = char_from_entity(a_match.as_str());
(a_match.start(), a_match.end(), replacement)
} else if let Some(a_match) = capture.name("char_hex") {
let replacement = char_from_entity(a_match.as_str())... |
//
// TODO: this does not yet deal with entity references.
//
let replacement = match resolver.resolve(a_match.as_str()) {
None => panic!("unknown entity reference {}", a_match.as_str()),
Some(replacement) => {
... | conditional_block |
text.rs | ization](https://www.w3.org/TR/xml11/#AVNormalize):
///
/// Before the value of an attribute is passed to the application or checked for validity, the XML
/// processor must normalize the attribute value by applying the algorithm below, or by using some
/// other method such that the value passed to the application is ... | ------------------------------------------------------------------------------------------------
// Unit Tests
// ------------------------------------------------------------------------------------------------
#[cfg(test)]
mod tests {
use super::*;
use std::borrow::Borrow;
use std::collections::HashMap;
... | if s == XML_NS_ATTR_SPACE_DEFAULT {
Ok(SpaceHandling::Default)
} else if s == XML_NS_ATTR_SPACE_PRESERVE {
Ok(SpaceHandling::Preserve)
} else {
Err(())
}
}
}
// | identifier_body |
text.rs | /// Handling, so the rest of this algorithm operates on text normalized in this way.
/// 2. Begin with a normalized value consisting of the empty string.
/// 3. For each character, entity reference, or character reference in the unnormalized attribute
/// value, beginning with the first and continuing to the last... | lize_avalue_entity_resolver() {
| identifier_name | |
lib.rs | // Copyright 2018. Matthew Pelland <matt@pelland.io>.
//
// 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 applica... | <Input, Output>(input: Input, expected_outputs: Output)
where
Input: AsRef<Path>,
Output: IntoIterator + Copy,
Output::Item: AsRef<Path>,
{
let rel_include_path = PathBuf::from("test/assets/protos");
let abs_include_path = Path::new(env!("CARGO_MANIFEST_DIR")).join(&rel_i... | assert_compile_grpc_protos | identifier_name |
lib.rs | // Copyright 2018. Matthew Pelland <matt@pelland.io>.
//
// 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 applica... |
fn normalize<Paths, Bases>(
paths: Paths,
bases: Bases,
) -> CompileResult<(Vec<PathBuf>, Vec<PathBuf>, Vec<PathBuf>)>
where
Paths: IntoIterator,
Paths::Item: AsRef<Path>,
Bases: IntoIterator,
Bases::Item: AsRef<Path>,
{
let absolutized_bases = bases
.into_iter()
.map(absolut... | {
let p = path.as_ref();
if p.is_relative() {
match std::env::current_dir() {
Ok(cwd) => Ok(cwd.join(p)),
Err(err) => Err(format_err!(
"Failed to determine CWD needed to absolutize a relative path: {:?}",
err
)),
}
} else {
... | identifier_body |
lib.rs | // Copyright 2018. Matthew Pelland <matt@pelland.io>.
//
// 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 applica... | .as_slice(),
includes: stringified_includes
.iter()
.map(String::as_str)
.collect::<Vec<&str>>()
.as_slice(),
include_imports: true,
})
.context("failed to write descriptor set")?;
let mut serialized_d... | .iter()
.map(String::as_str)
.collect::<Vec<&str>>() | random_line_split |
encoder.rs | extern crate deflate;
use std::borrow::Cow;
use std::error;
use std::fmt;
use std::io::{self, Write};
use std::mem;
use std::result;
use chunk;
use crc::Crc32;
use common::{AnimationControl, FrameControl, Info, ColorType, BitDepth};
use filter::{FilterType, filter};
use traits::{WriteBytesExt, HasParameters, Paramete... | else {
Err(EncodingError::Format("invalid number of frames for an animated PNG".into()))
}
}
pub fn write_header(self) -> Result<Writer<W>> {
Writer::new(self.w, self.info).init()
}
}
impl<W: Write> HasParameters for Encoder<W> {}
impl<W: Write> Parameter<Encoder<W>> for Col... | {
let mut encoder = Encoder::new(w, width, height);
let animation_ctl = AnimationControl { num_frames: frames, num_plays: 0 };
let mut frame_ctl = FrameControl::default();
frame_ctl.width = width;
frame_ctl.height = height;
encoder.info.animation... | conditional_block |
encoder.rs | extern crate deflate;
use std::borrow::Cow;
use std::error;
use std::fmt;
use std::io::{self, Write};
use std::mem;
use std::result;
use chunk;
use crc::Crc32;
use common::{AnimationControl, FrameControl, Info, ColorType, BitDepth};
use filter::{FilterType, filter};
use traits::{WriteBytesExt, HasParameters, Paramete... | use self::EncodingError::*;
match *self {
IoError(ref err) => err.description(),
Format(ref desc) => &desc,
}
}
}
impl fmt::Display for EncodingError {
fn fmt(&self, fmt: &mut fmt::Formatter) -> result::Result<(), fmt::Error> {
write!(fmt, "{}", (self as ... | fn description(&self) -> &str { | random_line_split |
encoder.rs | extern crate deflate;
use std::borrow::Cow;
use std::error;
use std::fmt;
use std::io::{self, Write};
use std::mem;
use std::result;
use chunk;
use crc::Crc32;
use common::{AnimationControl, FrameControl, Info, ColorType, BitDepth};
use filter::{FilterType, filter};
use traits::{WriteBytesExt, HasParameters, Paramete... | (&mut self) {
let _ = self.write_chunk(chunk::IEND, &[]);
}
}
#[test]
fn roundtrip() {
use std::fs::File;
// Decode image
let decoder = ::Decoder::new(File::open("tests/pngsuite/basi0g01.png").unwrap());
let (info, mut reader) = decoder.read_info().unwrap();
let mut buf = vec![0; info.b... | drop | identifier_name |
encoder.rs | extern crate deflate;
use std::borrow::Cow;
use std::error;
use std::fmt;
use std::io::{self, Write};
use std::mem;
use std::result;
use chunk;
use crc::Crc32;
use common::{AnimationControl, FrameControl, Info, ColorType, BitDepth};
use filter::{FilterType, filter};
use traits::{WriteBytesExt, HasParameters, Paramete... |
}
/// PNG Encoder
pub struct Encoder<W: Write> {
w: W,
info: Info,
}
impl<W: Write> Encoder<W> {
pub fn new(w: W, width: u32, height: u32) -> Encoder<W> {
let mut info = Info::default();
info.width = width;
info.height = height;
Encoder { w: w, info: info }
}
pub ... | {
io::Error::new(io::ErrorKind::Other, (&err as &error::Error).description())
} | identifier_body |
conn.rs | use serialize::json;
use std::comm;
use std::io;
use std::io::{BufferedReader, LineBufferedWriter, Reader, Writer};
use std::io::net::addrinfo;
use std::io::net::tcp::TcpStream;
use std::io::net::ip::SocketAddr;
use std::io::process;
use std::io::stdio::StdWriter;
use rand;
use rand::Rng;
use std::str;
use term;
use ... | else if packet_id == 0x2 {
let json = packet.read_string();
debug!("Got chat message: {}", json);
// Let's wrap up the Json so that we can
// deal with it more easily
let j = json::from_str(json).unwrap();
let j = ExtraJSON::new(j);
... | {
let x = packet.read_be_i32().unwrap();
// Need to respond
let mut resp = Packet::new_out(0x0);
resp.write_be_i32(x);
self.write_packet(resp);
// Chat Message
} | conditional_block |
conn.rs | use serialize::json;
use std::comm;
use std::io;
use std::io::{BufferedReader, LineBufferedWriter, Reader, Writer};
use std::io::net::addrinfo;
use std::io::net::tcp::TcpStream;
use std::io::net::ip::SocketAddr;
use std::io::process;
use std::io::stdio::StdWriter;
use rand;
use rand::Rng;
use std::str;
use term;
use ... |
}
| {
match *self {
Some(ref mut s) => s.flush(),
None => Err(io::standard_error(io::OtherIoError))
}
} | identifier_body |
conn.rs | use serialize::json;
use std::comm;
use std::io;
use std::io::{BufferedReader, LineBufferedWriter, Reader, Writer};
use std::io::net::addrinfo;
use std::io::net::tcp::TcpStream;
use std::io::net::ip::SocketAddr;
use std::io::process;
use std::io::stdio::StdWriter;
use rand;
use rand::Rng;
use std::str;
use term;
use ... | {
addr: SocketAddr,
host: ~str,
sock: Option<Sock>,
name: ~str,
term: term::Terminal<LineBufferedWriter<StdWriter>>
}
impl Connection {
pub fn new(name: ~str, host: ~str, port: u16) -> Result<Connection, ~str> {
// Resolve host
let addr = match addrinfo::get_host_addresses(hos... | Connection | identifier_name |
conn.rs | use serialize::json;
use std::comm;
use std::io;
use std::io::{BufferedReader, LineBufferedWriter, Reader, Writer};
use std::io::net::addrinfo;
use std::io::net::tcp::TcpStream;
use std::io::net::ip::SocketAddr;
use std::io::process;
use std::io::stdio::StdWriter;
use rand;
use rand::Rng;
use std::str;
use term;
use ... | "selectedProfile": "{}",
"serverId": "{}"
\}"#, token, profile, hash);
p.stdin = None;
// read response
let out = p.wait_with_output().output;
let out = str::from_utf8_owned(out.move_iter().collect()).unwrap();
debug!("Got - {}", out);... |
// write json to stdin and close it
write!(p.stdin.get_mut_ref() as &mut Writer, r#"
\{
"accessToken": "{}", | random_line_split |
prefix_code.rs | #![macro_escape]
use std::mem;
use std::intrinsics::ctlz32;
use std::cmp::max;
use std::iter::range_step;
static MAX_SUPPORTED_SYMS: u32 = 1024;
static MAX_EVER_CODE_SIZE: u32 = 34;
static MAX_EXPECTED_CODE_SIZE: uint = 16;
pub struct OrdFreq {
f: u16,
s: u16
}
impl OrdFreq {
pub fn new(sym: u32, freq: u32) -> O... |
}
}
for p in decoder_table.mut_iter() {
*p = 0xffff;
}
for i in range(0, sizes.len()) {
let s = sizes[i] as uint;
let code = next_code[s];
next_code[s] += 1;
let offset = (code as u16 + dec_first_offset[s]) as uint;
dec_offset_to_sym[offset] = i as u16;
let rev_code = reverse_u16(code) >> (16 ... | {
//return false; // Error, sizes don't add up
fail!("Code sizes don't add up");
} | conditional_block |
prefix_code.rs | #![macro_escape]
use std::mem;
use std::intrinsics::ctlz32;
use std::cmp::max;
use std::iter::range_step;
static MAX_SUPPORTED_SYMS: u32 = 1024;
static MAX_EVER_CODE_SIZE: u32 = 34;
static MAX_EXPECTED_CODE_SIZE: uint = 16;
pub struct OrdFreq {
f: u16,
s: u16
}
impl OrdFreq {
pub fn new(sym: u32, freq: u32) -> O... | (self) -> u16 {
self.s
}
}
pub fn sort_symbols2<'a>(mut first: &'a mut [OrdFreq], mut second: &'a mut [OrdFreq]) -> &'a mut [OrdFreq] {
let mut hist = [0u32,..256 * 2];
for &s in first.iter() {
let f = s.freq();
hist[ (f & 0xff) as uint] += 1;
hist[256 + ((f >> 8) & 0xff) as uint] += 1;
}
le... | sym | identifier_name |
prefix_code.rs | #![macro_escape]
use std::mem;
use std::intrinsics::ctlz32;
use std::cmp::max;
use std::iter::range_step;
static MAX_SUPPORTED_SYMS: u32 = 1024;
static MAX_EVER_CODE_SIZE: u32 = 34;
static MAX_EXPECTED_CODE_SIZE: uint = 16;
pub struct OrdFreq {
f: u16,
s: u16
}
impl OrdFreq {
pub fn new(sym: u32, freq: u32) -> O... |
let mut code = 0u32;
let mut offset = 0u32;
for i in range(1, MAX_EXPECTED_CODE_SIZE + 1) {
next_code[i] = code;
dec_first_offset[i] = offset as u16 - code as u16;
code += num_codes[i];
dec_max_code[i] = code << (16 - i);
code <<= 1;
offset += num_codes[i];
}
dec_max_code[17] = 0x10000;
if code!= (... | let mut next_code: [u32, ..MAX_EXPECTED_CODE_SIZE + 1] = [0, ..MAX_EXPECTED_CODE_SIZE + 1];
for &s in sizes.iter() {
num_codes[s as uint] += 1;
} | random_line_split |
main.rs | 5);
/// ```
pub fn diverges() ->! {
panic!("This function never returns!");
}
/// # Panics
fn test(){}
/// # Errors
fn test2(){}
/// # Safety
fn test3(){}
}
fn main() {
//variable
let (a,b) = (1,2);
println!("{} {}", a, b);
let x:i32 = 5;
println!("{}", x);
let mut x = "foo";
pri... | impl Circle {
fn area(&self) -> f64 {
std::f64::consts::PI * (self.radius * self.radius)
}
fn reference(&self) -> &Circle{
println!("taking self by reference!");
self
}
fn mutable_reference(&mut self) {
println!("taking self by mutable reference!");
}
... | random_line_split | |
main.rs | );
/// ```
pub fn diverges() ->! {
panic!("This function never returns!");
}
/// # Panics
fn test(){}
/// # Errors
fn test2(){}
/// # Safety
fn test3(){}
}
fn main() {
//variable
let (a,b) = (1,2);
println!("{} {}", a, b);
let x:i32 = 5;
println!("{}", x);
let mut x = "foo";
prin... | (&self) -> String { format!("string: {}", *self) }
}
fn do_something<T: FooBar>(x: T) {
x.method();
}
let x = 5u8;
let y = "Hello".to_string();
do_something(x);
do_something(y);
fn do_something2(x: &FooBar) {
x.method();
}
let x = 5u8;
//casting
do_something2(&x as &FooBar);
... | method | identifier_name |
main.rs | /// ```
pub fn diverges() ->! {
panic!("This function never returns!");
}
/// # Panics
fn test(){}
/// # Errors
fn test2(){}
/// # Safety
fn test3(){}
}
fn main() {
//variable
let (a,b) = (1,2);
println!("{} {}", a, b);
let x:i32 = 5;
println!("{}", x);
let mut x = "foo";
println... |
let graph = MyGraph;
let obj = Box::new(graph) as Box<Graph<N=Node, E=Edge>>;
struct FooUnsized<T:?Sized> {
f: T,
}
fn testUnsized(){
println!("unsized");
}
let mut fooUnsized = FooUnsized { f: testUnsized };
use std::ops::Add;
impl Add<i32> for Point {
type Output = f64;
fn add(self, r... | Vec::new()
}
}
| identifier_body |
reader.rs | use std::cmp::Reverse;
use std::sync::Arc;
use aexecutor::SearcherExecutorPool;
use anyhow::{Error, Result};
use serde::{Deserialize, Serialize};
use tantivy::collector::{Count, TopDocs};
use tantivy::fastfield::FastFieldReader;
use tantivy::query::{Query, TermQuery};
use tantivy::schema::{Field, FieldType, IndexRecor... |
#[derive(Debug, Serialize)]
pub struct QueryResults {
/// The retrieved documents.
pub(crate) hits: Vec<DocumentHit>,
/// The total amount of documents matching the search
count: usize,
/// The amount of time taken to search in seconds.
time_taken: f32,
}
impl QueryResults {
#[inline]
... | impl Default for Sort {
fn default() -> Self {
Self::Desc
}
} | random_line_split |
reader.rs | use std::cmp::Reverse;
use std::sync::Arc;
use aexecutor::SearcherExecutorPool;
use anyhow::{Error, Result};
use serde::{Deserialize, Serialize};
use tantivy::collector::{Count, TopDocs};
use tantivy::fastfield::FastFieldReader;
use tantivy::query::{Query, TermQuery};
use tantivy::schema::{Field, FieldType, IndexRecor... | ,
_ => Err(Error::msg("field is not a fast field")),
};
}
let out = match field_type {
FieldType::I64(_) => {
let collector =
collector.custom_score(move |segment_reader: &SegmentReader| {
let reader = segment_reader
... | {
let out: (Vec<(DateTime, DocAddress)>, usize) =
order_and_search(&searcher, field, query, collector, executor)?;
Ok((process_search(&searcher, schema, out.0)?, out.1))
} | conditional_block |
reader.rs | use std::cmp::Reverse;
use std::sync::Arc;
use aexecutor::SearcherExecutorPool;
use anyhow::{Error, Result};
use serde::{Deserialize, Serialize};
use tantivy::collector::{Count, TopDocs};
use tantivy::fastfield::FastFieldReader;
use tantivy::query::{Query, TermQuery};
use tantivy::schema::{Field, FieldType, IndexRecor... | (&self) -> Result<()> {
if self.max_concurrency == 0 {
return Err(Error::msg("max concurrency must be at least 1."));
}
Ok(())
}
}
impl ReaderContext {
fn default_reader_threads() -> usize {
1
}
}
/// A given query payload that describes how the reader should
/... | validate | identifier_name |
reader.rs | use std::cmp::Reverse;
use std::sync::Arc;
use aexecutor::SearcherExecutorPool;
use anyhow::{Error, Result};
use serde::{Deserialize, Serialize};
use tantivy::collector::{Count, TopDocs};
use tantivy::fastfield::FastFieldReader;
use tantivy::query::{Query, TermQuery};
use tantivy::schema::{Field, FieldType, IndexRecor... | }
let (_, addr) = results.remove(0);
let doc = searcher.doc(addr)?;
let schema = searcher.schema();
Ok(schema.to_named_doc(&doc))
})
.await??;
Ok(DocumentHit {
doc: document,
documen... | {
let id_field = self.query_handler.id_field();
let document = self
.pool
.spawn(move |searcher, executor| {
let qry = TermQuery::new(
Term::from_field_u64(id_field, id),
IndexRecordOption::Basic,
);
... | identifier_body |
lib.rs | _module::{self, Backend, DataId, FuncId, Linkage, Module};
use cranelift_object::{ObjectBackend, ObjectBuilder};
use saltwater_parser::arch::TARGET;
use saltwater_parser::{Opt, Program};
use saltwater_parser::data::{
hir::{Declaration, Initializer, Stmt, Symbol},
types::FunctionType,
StorageClass, *,
};
p... | (jit: bool) -> Box<dyn TargetIsa +'static> {
let mut flags_builder = cranelift::codegen::settings::builder();
// `simplejit` requires non-PIC code
if!jit {
// allow creating shared libraries
flags_builder
.enable("is_pic")
.expect("is_pic should be a valid option");
... | get_isa | identifier_name |
lib.rs | _module::{self, Backend, DataId, FuncId, Linkage, Module};
use cranelift_object::{ObjectBackend, ObjectBuilder};
use saltwater_parser::arch::TARGET;
use saltwater_parser::{Opt, Program};
use saltwater_parser::data::{
hir::{Declaration, Initializer, Stmt, Symbol},
types::FunctionType,
StorageClass, *,
};
p... |
// TODO: this is grossly inefficient, ask Cranelift devs if
// there's an easier way to make parameters modifiable.
fn store_stack_params(
&mut self,
params: &[Symbol],
func_start: Block,
location: &Location,
builder: &mut FunctionBuilder,
) -> CompileResult<()> ... | {
match init {
Initializer::Scalar(expr) => {
let val = self.compile_expr(*expr, builder)?;
// TODO: replace with `builder.ins().stack_store(val.ir_val, stack_slot, 0);`
// when Cranelift implements stack_store for i8 and i16
let addr =... | identifier_body |
lib.rs | lift_module::{self, Backend, DataId, FuncId, Linkage, Module};
use cranelift_object::{ObjectBackend, ObjectBuilder};
use saltwater_parser::arch::TARGET;
use saltwater_parser::{Opt, Program};
use saltwater_parser::data::{
hir::{Declaration, Initializer, Stmt, Symbol},
types::FunctionType,
StorageClass, *,
}... | // link the.o file using host linker
let status = Command::new("cc")
.args(&[&obj_file, Path::new("-o"), output])
.status()
.map_err(|err| {
if err.kind() == ErrorKind::NotFound {
Error::new(
ErrorKind::NotFound,
"could not... | use std::io::{Error, ErrorKind};
use std::process::Command;
| random_line_split |
tags.rs | use std::{str::FromStr, sync::Arc, time::Duration};
use eyre::Report;
use rand::RngCore;
use rosu_v2::model::GameMode;
use tokio::fs;
use tokio_stream::StreamExt;
use twilight_model::{channel::ReactionType, gateway::event::Event, http::attachment::Attachment};
use super::ReactionWrapper;
use crate::{
database::Ma... | &ctx, builder).await?;
break;
}
}
Ok(())
}
async fn get_random_image(mut mapsets: Vec<MapsetTagWrapper>, mode: GameMode) -> (u32, Vec<u8>) {
let mut path = CONFIG.get().unwrap().paths.backgrounds.clone();
match mode {
GameMode::Osu => path.push(OSU),
GameMode::Man... | let builder = MessageBuilder::new().content("Exiting loop :wave:");
msg.create_message( | conditional_block |
tags.rs | use std::{str::FromStr, sync::Arc, time::Duration};
use eyre::Report;
use rand::RngCore;
use rosu_v2::model::GameMode;
use tokio::fs;
use tokio_stream::StreamExt;
use twilight_model::{channel::ReactionType, gateway::event::Event, http::attachment::Attachment};
use super::ReactionWrapper;
use crate::{
database::Ma... | let mode = match args.next() {
Some(arg) => match arg.cow_to_ascii_lowercase().as_ref() {
"mna" | "mania" | "m" => GameMode::Mania,
"osu" | "std" | "standard" | "o" => GameMode::Osu,
_ => {
let content = "Could not parse first argument as mode. \
... | CommandData::Interaction { .. } => unreachable!(),
};
// Parse arguments as mode | random_line_split |
tags.rs | use std::{str::FromStr, sync::Arc, time::Duration};
use eyre::Report;
use rand::RngCore;
use rosu_v2::model::GameMode;
use tokio::fs;
use tokio_stream::StreamExt;
use twilight_model::{channel::ReactionType, gateway::event::Event, http::attachment::Attachment};
use super::ReactionWrapper;
use crate::{
database::Ma... | tch mode {
GameMode::Osu => path.push(OSU),
GameMode::Mania => path.push(MANIA),
_ => unreachable!(),
}
loop {
let random_idx = {
let mut rng = rand::thread_rng();
rng.next_u32() as usize % mapsets.len()
};
let mapset = mapsets.swap_remov... | clone();
ma | identifier_name |
tags.rs | use std::{str::FromStr, sync::Arc, time::Duration};
use eyre::Report;
use rand::RngCore;
use rosu_v2::model::GameMode;
use tokio::fs;
use tokio_stream::StreamExt;
use twilight_model::{channel::ReactionType, gateway::event::Event, http::attachment::Attachment};
use super::ReactionWrapper;
use crate::{
database::Ma... | let mut untagged = match ctx.psql().get_all_tags_mapset(mode).await {
Ok(tags) => tags.iter().any(|tag| tag.untagged()),
Err(err) => {
let _ = msg.error(&ctx, GENERAL_ISSUE).await;
return Err(err);
}
};
if!untagged {
let content = "All backgrounds ha... | let (msg, mut args) = match data {
CommandData::Message { msg, args, .. } => (msg, args),
CommandData::Interaction { .. } => unreachable!(),
};
// Parse arguments as mode
let mode = match args.next() {
Some(arg) => match arg.cow_to_ascii_lowercase().as_ref() {
"mna" | ... | identifier_body |
golem_renderer.rs | use crate::*;
use golem::*;
use std::cell::RefCell;
use std::collections::HashMap;
impl Renderer {
/// Constructs a new `Renderer` that will draw onto the given golem `Context` within the given
/// *initial_viewport*. Normally, only the *wrapper* should use this function.
pub fn new(context: Context, initi... | );
}
for int_counter in 1..= shader.description.num_ints {
let _result = shader_program.set_uniform(
&format!("int{}", int_counter),
UniformValue::Int(parameters.ints[int_counter as usize - 1])
... | UniformValue::Float(parameters.floats[float_counter as usize - 1]) | random_line_split |
golem_renderer.rs | use crate::*;
use golem::*;
use std::cell::RefCell;
use std::collections::HashMap;
impl Renderer {
/// Constructs a new `Renderer` that will draw onto the given golem `Context` within the given
/// *initial_viewport*. Normally, only the *wrapper* should use this function.
pub fn new(context: Context, initi... | (&self) -> &ElementBuffer {
&self.storage.quad_indices
}
/// Gets the number of indices in the `ElementBuffer` given by the `get_quad_indices`
/// method, in integers (which is just 6).
pub fn get_num_quad_indices(&self) -> usize {
6
}
/// Checks if the shader with the given *i... | get_quad_indices | identifier_name |
golem_renderer.rs | use crate::*;
use golem::*;
use std::cell::RefCell;
use std::collections::HashMap;
impl Renderer {
/// Constructs a new `Renderer` that will draw onto the given golem `Context` within the given
/// *initial_viewport*. Normally, only the *wrapper* should use this function.
pub fn new(context: Context, initi... |
// Now that we are sure we won't exceed the maximum number of shaders, we can insert the
// new shader, and return a reference to it.
let value = self.map.entry(id.clone()).or_insert(CachedShader {
last_used: self.current_time,
shader: create_shader()?,
});
... | {
let mut last_used_times: Vec<u64> = self
.map
.values()
.map(|cached_shader| cached_shader.last_used)
.collect();
last_used_times.sort();
let median = last_used_times[last_used_times.len() / 2];
// Remove ... | conditional_block |
repr.rs | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
//! Flattened Representation of an AssumeRole chain
//!
//! Assume Role credentials in profile files can chain together credentials from multiple
//! different providers with subsequent credentials bein... | {
AssumeRole {
role_arn: String,
external_id: Option<String>,
role_session_name: Option<String>,
},
AccessKey {
access_key_id: String,
secret_access_key: String,
session_token: Option<String>,
},
NamedSource... | Provider | identifier_name |
repr.rs | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
//! Flattened Representation of an AssumeRole chain
//!
//! Assume Role credentials in profile files can chain together credentials from multiple
//! different providers with subsequent credentials bein... |
/// Load static credentials from a profile
///
/// Example:
/// ```ini
/// [profile B]
/// aws_access_key_id = abc123
/// aws_secret_access_key = def456
/// ```
fn static_creds_from_profile(profile: &Profile) -> Result<Credentials, ProfileFileError> {
use static_credentials::*;
let access_key = profile.get(AW... | {
let session_name = profile.get(role::SESSION_NAME);
match (
profile.get(role::ROLE_ARN),
profile.get(web_identity_token::TOKEN_FILE),
) {
(Some(role_arn), Some(token_file)) => Some(Ok(BaseProvider::WebIdentityTokenRole {
role_arn,
web_identity_token_file: to... | identifier_body |
repr.rs | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
//! Flattened Representation of an AssumeRole chain
//!
//! Assume Role credentials in profile files can chain together credentials from multiple
//! different providers with subsequent credentials bein... | }
pub fn chain(&self) -> &[RoleArn<'a>] {
&self.chain.as_slice()
}
}
/// A base member of the profile chain
///
/// Base providers do not require input credentials to provide their own credentials,
/// eg. IMDS, ECS, Environment variables
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum BaseProv... | random_line_split | |
lib.rs | Mime without having to import so many enums.
///
/// # Example
///
/// ```
/// # #[macro_use] extern crate mime;
///
/// # fn main() {
/// let json = mime!(Application/Json);
/// let plain = mime!(Text/Plain; Charset=Utf8);
/// let text = mime!(Text/Html; Charset=("bar"), ("baz")=("quux"));
/// let img = mime!(Image/_... | #[test]
fn test_case_sensitive_values() {
assert_eq!(Mime::from_str("multipart/form-data; boundary=ABCDEFG").unwrap(), | random_line_split | |
lib.rs | !("matched json!"),
/// _ => ()
/// }
/// ```
#[derive(Clone, Debug, Eq, Hash, Ord, PartialOrd)]
pub struct Mime<T: AsRef<[Param]> = Vec<Param>>(pub TopLevel, pub SubLevel, pub T);
#[cfg(feature = "heapsize")]
impl<T: AsRef<[Param]> + heapsize::HeapSizeOf> heapsize::HeapSizeOf for Mime<T> {
fn heap_size_of_chi... | else if let TopLevel::Star = self.0 {
if let SubLevel::Star = self.1 {
let attrs = self.2.as_ref();
if attrs.len() == 0 {
return f.write_str("*/*");
}
}
}
// slower general purpose fmt
try!(fmt::Display... | {
if let SubLevel::Json = self.1 {
let attrs = self.2.as_ref();
if attrs.len() == 0 {
return f.write_str("application/json");
}
}
} | conditional_block |
lib.rs | !("matched json!"),
/// _ => ()
/// }
/// ```
#[derive(Clone, Debug, Eq, Hash, Ord, PartialOrd)]
pub struct Mime<T: AsRef<[Param]> = Vec<Param>>(pub TopLevel, pub SubLevel, pub T);
#[cfg(feature = "heapsize")]
impl<T: AsRef<[Param]> + heapsize::HeapSizeOf> heapsize::HeapSizeOf for Mime<T> {
fn heap_size_of_chi... | (c: char) -> bool {
if is_restricted_name_first_char(c) {
true
} else {
match c {
'!' |
'#' |
'$' |
'&' |
'-' |
'^' |
'.' |
'+' |
'_' => true,
_ => false
}
}
}
#[c... | is_restricted_name_char | identifier_name |
lib.rs | !("matched json!"),
/// _ => ()
/// }
/// ```
#[derive(Clone, Debug, Eq, Hash, Ord, PartialOrd)]
pub struct Mime<T: AsRef<[Param]> = Vec<Param>>(pub TopLevel, pub SubLevel, pub T);
#[cfg(feature = "heapsize")]
impl<T: AsRef<[Param]> + heapsize::HeapSizeOf> heapsize::HeapSizeOf for Mime<T> {
fn heap_size_of_chi... | } else if let TopLevel::Star = self.0 {
if let SubLevel::Star = self.1 {
let attrs = self.2.as_ref();
if attrs.len() == 0 {
return f.write_str("*/*");
}
}
}
// slower general purpose fmt
try!(fmt... | {
// It's much faster to write a single string, as opposed to push
// several parts through f.write_str(). So, check for the most common
// mime types, and fast track them.
if let TopLevel::Text = self.0 {
if let SubLevel::Plain = self.1 {
let attrs = self.2.a... | identifier_body |
shuf.rs | // This file is part of the uutils coreutils package.
//
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code.
// spell-checker:ignore (ToDO) cmdline evec seps rvec fdata
use clap::{crate_version, Arg, ArgAction, Command};
use memchr::memchr_ite... | .to_string(),
)
};
let options = Options {
head_count: {
let headcounts = matches
.get_many::<String>(options::HEAD_COUNT)
.unwrap_or_default()
.map(|s| s.to_owned())
.collect();
match parse_head_... | {
let args = args.collect_lossy();
let matches = uu_app().try_get_matches_from(args)?;
let mode = if let Some(args) = matches.get_many::<String>(options::ECHO) {
Mode::Echo(args.map(String::from).collect())
} else if let Some(range) = matches.get_one::<String>(options::INPUT_RANGE) {
m... | identifier_body |
shuf.rs | // This file is part of the uutils coreutils package.
//
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code.
// spell-checker:ignore (ToDO) cmdline evec seps rvec fdata
use clap::{crate_version, Arg, ArgAction, Command};
use memchr::memchr_ite... | (args: impl uucore::Args) -> UResult<()> {
let args = args.collect_lossy();
let matches = uu_app().try_get_matches_from(args)?;
let mode = if let Some(args) = matches.get_many::<String>(options::ECHO) {
Mode::Echo(args.map(String::from).collect())
} else if let Some(range) = matches.get_one::<... | uumain | identifier_name |
shuf.rs | // This file is part of the uutils coreutils package.
//
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code.
// spell-checker:ignore (ToDO) cmdline evec seps rvec fdata
use clap::{crate_version, Arg, ArgAction, Command};
use memchr::memchr_ite... | .override_usage(format_usage(USAGE))
.infer_long_args(true)
.args_override_self(true)
.arg(
Arg::new(options::ECHO)
.short('e')
.long(options::ECHO)
.value_name("ARG")
.help("treat each ARG as an input line")
... | .version(crate_version!()) | random_line_split |
lib.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | }
impl Sub for Indent {
type Output = Indent;
fn sub(self, rhs: Indent) -> Indent {
Indent::new(self.block_indent - rhs.block_indent,
self.alignment - rhs.alignment)
}
}
impl Add<usize> for Indent {
type Output = Indent;
fn add(self, rhs: usize) -> Indent {
In... | alignment: self.alignment + rhs.alignment,
}
} | random_line_split |
lib.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (&self) -> Span {
self.span
}
}
impl Spanned for ast::Pat {
fn span(&self) -> Span {
self.span
}
}
impl Spanned for ast::Ty {
fn span(&self) -> Span {
self.span
}
}
impl Spanned for ast::Arg {
fn span(&self) -> Span {
if items::is_named_arg(self) {
... | span | identifier_name |
aa_changes.rs | use crate::alphabet::aa::Aa;
use crate::alphabet::letter::Letter;
use crate::alphabet::letter::{serde_deserialize_seq, serde_serialize_seq};
use crate::alphabet::nuc::Nuc;
use crate::analyze::aa_del::AaDel;
use crate::analyze::aa_sub::AaSub;
use crate::analyze::nuc_del::NucDelRange;
use crate::analyze::nuc_sub::NucSub;... |
changes.aa_substitutions.sort();
changes.aa_deletions.sort();
changes.nuc_to_aa_muts.iter_mut().for_each(|(_, vals)| {
vals.sort();
vals.dedup();
});
Ok(changes)
}
/// Finds aminoacid substitutions and deletions in query peptides relative to reference peptides, in one gene
///
/// ## Precondition
... | {
let mut changes = qry_translation
.iter_cdses()
.map(|(qry_name, qry_cds_tr)| {
let ref_cds_tr = ref_translation.get_cds(qry_name)?;
let cds = gene_map.get_cds(&qry_cds_tr.name)?;
Ok(find_aa_changes_for_cds(
cds, qry_seq, ref_seq, ref_cds_tr, qry_cds_tr, nuc_subs, nuc_dels,
)... | identifier_body |
aa_changes.rs | use crate::alphabet::aa::Aa;
use crate::alphabet::letter::Letter;
use crate::alphabet::letter::{serde_deserialize_seq, serde_serialize_seq};
use crate::alphabet::nuc::Nuc;
use crate::analyze::aa_del::AaDel;
use crate::analyze::aa_sub::AaSub;
use crate::analyze::nuc_del::NucDelRange;
use crate::analyze::nuc_sub::NucSub;... | // then append to the group.
if codon <= prev.pos + 2 {
// If previous codon in the group is not exactly adjacent, there is 1 item in between,
// then cover the hole by inserting previous codon.
if codon == prev.pos + 2 && is_codon_sequenced(aa_alignment_ranges, c... | random_line_split | |
aa_changes.rs | use crate::alphabet::aa::Aa;
use crate::alphabet::letter::Letter;
use crate::alphabet::letter::{serde_deserialize_seq, serde_serialize_seq};
use crate::alphabet::nuc::Nuc;
use crate::analyze::aa_del::AaDel;
use crate::analyze::aa_sub::AaSub;
use crate::analyze::nuc_del::NucDelRange;
use crate::analyze::nuc_sub::NucSub;... |
// Current group is not empty
Some(prev) => {
// If previous codon in the group is adjacent or almost adjacent (there is 1 item in between),
// then append to the group.
if codon <= prev.pos + 2 {
// If previous codon in the group is not exactly adjacent, there... | {
if codon > 0 && is_codon_sequenced(aa_alignment_ranges, codon - 1) {
// Also prepend one codon to the left, for additional context, to start the group
curr_group.push(AaChangeWithContext::new(
cds,
codon - 1,
qry_seq,
ref_seq,
... | conditional_block |
aa_changes.rs | use crate::alphabet::aa::Aa;
use crate::alphabet::letter::Letter;
use crate::alphabet::letter::{serde_deserialize_seq, serde_serialize_seq};
use crate::alphabet::nuc::Nuc;
use crate::analyze::aa_del::AaDel;
use crate::analyze::aa_sub::AaSub;
use crate::analyze::nuc_del::NucDelRange;
use crate::analyze::nuc_sub::NucSub;... | {
pub cds_name: String,
pub pos: AaRefPosition,
pub ref_aa: Aa,
pub qry_aa: Aa,
pub nuc_pos: NucRefGlobalPosition,
#[schemars(with = "String")]
#[serde(serialize_with = "serde_serialize_seq")]
#[serde(deserialize_with = "serde_deserialize_seq")]
pub ref_triplet: Vec<Nuc>,
#[schemars(with = "Strin... | AaChangeWithContext | identifier_name |
lib.rs | #![cfg_attr(feature = "cargo-clippy", allow(clone_on_ref_ptr))]
#![cfg_attr(feature = "cargo-clippy", allow(new_without_default_derive))]
#![deny(warnings)]
extern crate bytes;
extern crate conduit_proxy_controller_grpc;
extern crate env_logger;
extern crate deflate;
#[macro_use]
extern crate futures;
extern crate fut... |
RouteError::NotRecognized => {
error!("turning route not recognized error into 500");
http::StatusCode::INTERNAL_SERVER_ERROR
}
RouteError::NoCapacity(capacity) => {
// TODO For H2 streams, we should probably si... | {
error!("turning {} into 500", i);
http::StatusCode::INTERNAL_SERVER_ERROR
} | conditional_block |
lib.rs | #![cfg_attr(feature = "cargo-clippy", allow(clone_on_ref_ptr))]
#![cfg_attr(feature = "cargo-clippy", allow(new_without_default_derive))]
#![deny(warnings)]
extern crate bytes;
extern crate conduit_proxy_controller_grpc;
extern crate env_logger;
extern crate deflate;
#[macro_use]
extern crate futures;
extern crate fut... | RouteError::NoCapacity(capacity) => {
// TODO For H2 streams, we should probably signal a protocol-level
// capacity change.
error!("router at capacity ({}); returning a 503", capacity);
http::StatusCode::SERVICE_UNAVAILABLE... | {
let stack = Arc::new(NewServiceFn::new(move || {
// Clone the router handle
let router = router.clone();
// Map errors to appropriate response error codes.
let map_err = MapErr::new(router, |e| {
match e {
RouteError::Route(r) => {
e... | identifier_body |
lib.rs | #![cfg_attr(feature = "cargo-clippy", allow(clone_on_ref_ptr))]
#![cfg_attr(feature = "cargo-clippy", allow(new_without_default_derive))]
#![deny(warnings)]
extern crate bytes;
extern crate conduit_proxy_controller_grpc;
extern crate env_logger;
extern crate deflate;
#[macro_use]
extern crate futures;
extern crate fut... | pub mod ctx;
mod dns;
mod drain;
pub mod fs_watch;
mod inbound;
mod logging;
mod map_err;
mod outbound;
pub mod stream;
pub mod task;
pub mod telemetry;
mod transparency;
mod transport;
pub mod timeout;
mod tower_fn; // TODO: move to tower-fn
mod watch_service; // TODO: move to tower
use bind::Bind;
use conditional::C... | pub mod control;
pub mod convert; | random_line_split |
lib.rs | #![cfg_attr(feature = "cargo-clippy", allow(clone_on_ref_ptr))]
#![cfg_attr(feature = "cargo-clippy", allow(new_without_default_derive))]
#![deny(warnings)]
extern crate bytes;
extern crate conduit_proxy_controller_grpc;
extern crate env_logger;
extern crate deflate;
#[macro_use]
extern crate futures;
extern crate fut... | (&self) -> SocketAddr {
self.inbound_listener.local_addr()
}
pub fn outbound_addr(&self) -> SocketAddr {
self.outbound_listener.local_addr()
}
pub fn metrics_addr(&self) -> SocketAddr {
self.metrics_listener.local_addr()
}
pub fn run_until<F>(self, shutdown_signal: F)
... | inbound_addr | identifier_name |
cht.rs | // This file is part of Substrate.
// Copyright (C) 2017-2020 Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the F... | <N>(cht_size: N, block_num: N) -> Option<N>
where
N: Clone + AtLeast32Bit,
{
let block_cht_num = block_to_cht_number(cht_size.clone(), block_num.clone())?;
let two = N::one() + N::one();
if block_cht_num < two {
return None
}
let cht_start = start_number(cht_size, block_cht_num.clone());
if cht_start!= block_n... | is_build_required | identifier_name |
cht.rs | // This file is part of Substrate.
// Copyright (C) 2017-2020 Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the F... |
/// Returns Some(cht_number) if CHT is need to be built when the block with given number is
/// canonized.
pub fn is_build_required<N>(cht_size: N, block_num: N) -> Option<N>
where
N: Clone + AtLeast32Bit,
{
let block_cht_num = block_to_cht_number(cht_size.clone(), block_num.clone())?;
let two = N::one() + N::one(... | {
SIZE.into()
} | identifier_body |
cht.rs | // This file is part of Substrate.
// Copyright (C) 2017-2020 Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the F... |
let cht_start = start_number(cht_size, block_cht_num.clone());
if cht_start!= block_num {
return None
}
Some(block_cht_num - two)
}
/// Returns Some(max_cht_number) if CHT has ever been built given maximal canonical block number.
pub fn max_cht_number<N>(cht_size: N, max_canonical_block: N) -> Option<N>
where
... | {
return None
} | conditional_block |
cht.rs | // This file is part of Substrate.
// Copyright (C) 2017-2020 Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the F... | /// SIZE items. The items are assumed to proceed sequentially from `start_number(cht_num)`.
/// Discards the trie's nodes.
pub fn compute_root<Header, Hasher, I>(
cht_size: Header::Number,
cht_num: Header::Number,
hashes: I,
) -> ClientResult<Hasher::Out>
where
Header: HeaderT,
Hasher: hash_db::Hasher,
Hasher::Ou... | /// Compute a CHT root from an iterator of block hashes. Fails if shorter than | random_line_split |
main.rs | Cow;
use std::cmp::min;
use std::fs::{rename, File, OpenOptions};
use std::io::{stdout, BufReader, Read, Write};
use std::net::IpAddr;
use structopt::StructOpt;
const PATH_HOSTSFILE: &str = "/etc/hosts";
const PATH_HOSTSFILE_NEW: &str = "/etc/hosts.new";
const PATH_CONFIG: &str = "/etc/hostsmod.yaml";
fn main() {
... |
}
panic!("found_post!= found_pre");
}
}
if opts.dry_run || opts.verbose {
println!("generated:\n>>>\n{}<<<", &buf_generate);
}
if opts.dry_run {
println!("DRY-RUN DRY-RUN DRY-RUN DRY-RUN DRY-RUN DRY-RUN DRY-RUN DRY-RUN DRY-RUN DRY-RUN DRY-RUN DRY-RUN");
... | {
eprintln!("Difference: {:?}", DONT_TOUCH[i])
} | conditional_block |
main.rs | Cow;
use std::cmp::min;
use std::fs::{rename, File, OpenOptions};
use std::io::{stdout, BufReader, Read, Write};
use std::net::IpAddr;
use structopt::StructOpt;
const PATH_HOSTSFILE: &str = "/etc/hosts";
const PATH_HOSTSFILE_NEW: &str = "/etc/hosts.new";
const PATH_CONFIG: &str = "/etc/hostsmod.yaml";
fn main() {
... | //opt_insert = None;
continue 'loop_actions;
}
if matches_hostname {
match part.get_family() {
Some(HostsPartFamily::IPv4) => {
if host_found_v4 || ... | {
'loop_actions: for action in &opts.actions {
match action {
Action::Define(ip, host) => {
if !config.whitelist.contains(host) {
return Err(format!("HOST {:?} not whitelisted!", host));
}
// eprintln!("defining additionally...:... | identifier_body |
main.rs | borrow::Cow;
use std::cmp::min;
use std::fs::{rename, File, OpenOptions};
use std::io::{stdout, BufReader, Read, Write};
use std::net::IpAddr;
use structopt::StructOpt;
const PATH_HOSTSFILE: &str = "/etc/hosts";
const PATH_HOSTSFILE_NEW: &str = "/etc/hosts.new";
const PATH_CONFIG: &str = "/etc/hostsmod.yaml";
fn mai... | // eprintln!("matching entry: {:?}", part);
let matches_hostname = part.matches_hostname(host);
if part.matches_ip(ip) && matches_hostname {
// eprintln!("already defined, NOP");
//opt_insert = None;
... | .enumerate()
.filter(|(_i, p)| p.matches_ip(ip) || p.matches_hostname(host))
{ | random_line_split |
main.rs |
let hostname_os_string = hostname::get().expect("unable to determine system hostname");
let hostname = hostname_os_string
.to_str()
.expect("system hostname is not a valid UTF-8 string");
let mut opts: opts::HostsArgs = {
let app: structopt::clap::App = opts::HostsArgs::clap();
... | render_entry | identifier_name | |
game.rs | use world::World;
use piston_window::*;
use camera::Camera;
use cgmath::{Vector2, vec3};
use cgmath::prelude::*;
use color::*;
use car::*;
use piston_window::Ellipse;
use bot::BoxRules;
use std::cell::RefCell;
use std::ops::DerefMut;
use std::time::Instant;
// `Game` contains every things to run the game
pub struct Ga... |
fn draw(&mut self, e: &Input) {
// Return a horizontal bar
macro_rules! bar {
($curr: expr, $full: expr) => {
[0.,
15.0,
self.config.screen_size.w as f64/2.*$curr/$full,
20.0,]
};
}
let jump_bar ... | {
match key {
Button::Keyboard(Key::A) => if let Turn::Left = self.state.turn {
self.state.turn = Turn::None;
},
Button::Keyboard(Key::D) => if let Turn::Right = self.state.turn {
self.state.turn = Turn::None;
},
Button:... | identifier_body |
game.rs | use world::World;
use piston_window::*;
use camera::Camera;
use cgmath::{Vector2, vec3};
use cgmath::prelude::*;
use color::*;
use car::*;
use piston_window::Ellipse;
use bot::BoxRules;
use std::cell::RefCell;
use std::ops::DerefMut;
use std::time::Instant;
// `Game` contains every things to run the game
pub struct Ga... | <T: Car>(config: &GameConfig, player: &T) -> Camera {
Camera::new(
config.screen_size.clone(),
vec3(0., config.camera_height, -config.camera_distance) + player.pos()
)
}
// Re-calculate fps
fn update_fps(&mut self) {
let d = self.state.last_frame.elapsed();
... | new_camera | identifier_name |
game.rs | use world::World;
use piston_window::*;
use camera::Camera;
use cgmath::{Vector2, vec3};
use cgmath::prelude::*;
use color::*;
use car::*;
use piston_window::Ellipse;
use bot::BoxRules;
use std::cell::RefCell;
use std::ops::DerefMut;
use std::time::Instant;
// `Game` contains every things to run the game
pub struct Ga... | self.world.player.speed += dt*self.config.sprint_factor;
}
} else if self.world.player.speed > self.config.player_speed.0 {
self.world.player.speed -= dt*self.config.sprint_factor;
}
self.state.spawn -= dt;
if self.state.spawn < 0. {
se... | }
if self.state.sprint {
if self.world.player.speed < self.config.player_speed.1 { | random_line_split |
graph.rs | use crate::{CommandEncoder, CommandEncoderOutput};
use generational_arena::Arena;
use moonwave_resources::{BindGroup, Buffer, ResourceRc, SampledTexture, TextureView};
use multimap::MultiMap;
use parking_lot::{RwLock, RwLockReadGuard};
use rayon::{prelude::*, ThreadPool};
use std::{
collections::HashMap,
fmt::{Debu... | optick::tag!("level", level as u32);
// Get rid of duplicated nodes.
let mut nodes_in_level = self.levels_map.get_vec_mut(&level).unwrap().clone();
nodes_in_level.sort_unstable_by_key(|x| x.index);
nodes_in_level.dedup_by_key(|x| x.index);
// Build cache for this level
... | optick::event!("FrameGraph::execute_level"); | random_line_split |
graph.rs | use crate::{CommandEncoder, CommandEncoderOutput};
use generational_arena::Arena;
use moonwave_resources::{BindGroup, Buffer, ResourceRc, SampledTexture, TextureView};
use multimap::MultiMap;
use parking_lot::{RwLock, RwLockReadGuard};
use rayon::{prelude::*, ThreadPool};
use std::{
collections::HashMap,
fmt::{Debu... | {
node_arena: RwLock<Arena<ConnectedNode>>,
edges_arena: RwLock<Arena<ConnectedEdges>>,
end_node: Index,
output_map: Vec<Vec<Option<FrameNodeValue>>>,
levels_map: MultiMap<usize, TraversedGraphNode>,
traversed_node_cache: HashMap<Index, usize>,
}
impl FrameGraph {
/// Creates a new empty graph.
pub fn... | FrameGraph | identifier_name |
graph.rs | use crate::{CommandEncoder, CommandEncoderOutput};
use generational_arena::Arena;
use moonwave_resources::{BindGroup, Buffer, ResourceRc, SampledTexture, TextureView};
use multimap::MultiMap;
use parking_lot::{RwLock, RwLockReadGuard};
use rayon::{prelude::*, ThreadPool};
use std::{
collections::HashMap,
fmt::{Debu... |
}
device_host.get_queue().submit(buffers);
}
}
}
// Reset
optick::event!("FrameGraph::reset");
self.reset();
}
}
#[derive(Clone)]
pub enum FrameNodeValue {
Buffer(ResourceRc<Buffer>),
BindGroup(ResourceRc<BindGroup>),
TextureView(ResourceRc<TextureView>),
S... | {
buffers.push(buffer);
} | conditional_block |
main.rs | use num_traits::PrimInt;
use pest::Parser;
use pest_derive::Parser;
use std::{
collections::HashMap,
error::Error,
fmt,
io::{self, Read},
str::FromStr,
};
#[cfg(debug_assertions)]
macro_rules! dbg_print {
($( $args:expr ),*) => { print!( $( $args ),* ); }
}
#[cfg(not(debug_assertions))]
macro_rules! dbg_... |
fn calc_hit(&self, enemy: &Group) -> u32 {
match (
self.immunity.to(enemy.attack),
self.weakness.to(enemy.attack),
) {
(false, false) => enemy.effective_power(),
(true, false) => 0,
(false, true) => enemy.effective_power() * 2,
(true, true) => unreachable!(),
}
}
... |
fn is_alive(&self) -> bool {
self.units > 0
} | random_line_split |
main.rs | use num_traits::PrimInt;
use pest::Parser;
use pest_derive::Parser;
use std::{
collections::HashMap,
error::Error,
fmt,
io::{self, Read},
str::FromStr,
};
#[cfg(debug_assertions)]
macro_rules! dbg_print {
($( $args:expr ),*) => { print!( $( $args ),* ); }
}
#[cfg(not(debug_assertions))]
macro_rules! dbg_... |
}
#[derive(Default, Clone)]
struct Army<'a> {
groups: Vec<Group>,
name: &'a str,
}
impl Army<'_> {
fn sort_for_attack(&self) -> Vec<u16> {
let mut ids: Vec<u16> = (0..self.groups.len() as u16).collect();
ids.sort_by_key(|i|
// descending sort
(
!self.groups[*i as usize].is_alive(),
... | {
let org_units = self.units;
let units_kill = points / self.hits;
self.units = self.units.saturating_sub(units_kill);
let units_lost = org_units - self.units;
dbg_print!("Units lost: {}\n", units_lost);
units_lost
} | identifier_body |
main.rs | use num_traits::PrimInt;
use pest::Parser;
use pest_derive::Parser;
use std::{
collections::HashMap,
error::Error,
fmt,
io::{self, Read},
str::FromStr,
};
#[cfg(debug_assertions)]
macro_rules! dbg_print {
($( $args:expr ),*) => { print!( $( $args ),* ); }
}
#[cfg(not(debug_assertions))]
macro_rules! dbg_... | (&self) -> u32 {
self.units * (self.damages as u32 + self.boost as u32)
}
fn is_alive(&self) -> bool {
self.units > 0
}
fn calc_hit(&self, enemy: &Group) -> u32 {
match (
self.immunity.to(enemy.attack),
self.weakness.to(enemy.attack),
) {
(false, false) => enemy.effective_pow... | effective_power | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.