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 |
|---|---|---|---|---|
universal.rs | use crate::{script, Tag, Face, GlyphInfo, Mask, Script};
use crate::buffer::{Buffer, BufferFlags};
use crate::ot::{feature, FeatureFlags};
use crate::plan::{ShapePlan, ShapePlanner};
use crate::unicode::{CharExt, GeneralCategoryExt};
use super::*;
use super::arabic::ArabicShapePlan;
pub const UNIVERSAL_SHAPER: Comple... | }
}
start = end;
end = buffer.next_syllable(start);
}
}
fn reorder(_: &ShapePlan, face: &Face, buffer: &mut Buffer) {
insert_dotted_circles(face, buffer);
let mut start = 0;
let mut end = buffer.next_syllable(0);
while start < buffer.len {
reorder_syll... | {
let universal_plan = plan.data::<UniversalShapePlan>();
let mask = universal_plan.rphf_mask;
if mask == 0 {
return;
}
let mut start = 0;
let mut end = buffer.next_syllable(0);
while start < buffer.len {
// Mark a substituted repha as USE_R.
for i in start..end {
... | identifier_body |
universal.rs | use crate::{script, Tag, Face, GlyphInfo, Mask, Script};
use crate::buffer::{Buffer, BufferFlags};
use crate::ot::{feature, FeatureFlags};
use crate::plan::{ShapePlan, ShapePlanner};
use crate::unicode::{CharExt, GeneralCategoryExt};
use super::*;
use super::arabic::ArabicShapePlan;
pub const UNIVERSAL_SHAPER: Comple... | buffer.next_glyph();
}
}
buffer.swap_buffers();
}
const fn category_flag(c: Category) -> u32 {
rb_flag(c as u32)
}
const fn category_flag64(c: Category) -> u64 {
rb_flag64(c as u32)
}
const BASE_FLAGS: u64 =
category_flag64(category::FM) |
category_flag64(category::FABV) ... | } else { | random_line_split |
universal.rs | use crate::{script, Tag, Face, GlyphInfo, Mask, Script};
use crate::buffer::{Buffer, BufferFlags};
use crate::ot::{feature, FeatureFlags};
use crate::plan::{ShapePlan, ShapePlanner};
use crate::unicode::{CharExt, GeneralCategoryExt};
use super::*;
use super::arabic::ArabicShapePlan;
pub const UNIVERSAL_SHAPER: Comple... | (face: &Face, buffer: &mut Buffer) {
use super::universal_machine::SyllableType;
if buffer.flags.contains(BufferFlags::DO_NOT_INSERT_DOTTED_CIRCLE) {
return;
}
// Note: This loop is extra overhead, but should not be measurable.
// TODO Use a buffer scratch flag to remove the loop.
let ... | insert_dotted_circles | identifier_name |
source.rs | //! Utils for extracting, inspecting or transforming source code
#![allow(clippy::module_name_repetitions)]
use crate::line_span;
use rustc_errors::Applicability;
use rustc_hir::{Expr, ExprKind};
use rustc_lint::{LateContext, LintContext};
use rustc_span::hygiene;
use rustc_span::{BytePos, Pos, Span, SyntaxContext};
... | else {
" ".repeat(indent - x) + l
}
})
.collect::<Vec<String>>()
.join("\n")
}
/// Converts a span to a code snippet if available, otherwise returns the default.
///
/// This is useful if you want to provide suggestions for your lint or more generally, if you want
///... | {
l.split_at(x - indent).1.to_owned()
} | conditional_block |
source.rs | //! Utils for extracting, inspecting or transforming source code
#![allow(clippy::module_name_repetitions)]
use crate::line_span;
use rustc_errors::Applicability;
use rustc_hir::{Expr, ExprKind};
use rustc_lint::{LateContext, LintContext};
use rustc_span::hygiene;
use rustc_span::{BytePos, Pos, Span, SyntaxContext};
... | /// Converts a span to a code snippet if available, otherwise returns the default.
///
/// This is useful if you want to provide suggestions for your lint or more generally, if you want
/// to convert a given `Span` to a `str`. To create suggestions consider using
/// [`snippet_with_applicability`] to ensure that the a... | }
| random_line_split |
source.rs | //! Utils for extracting, inspecting or transforming source code
#![allow(clippy::module_name_repetitions)]
use crate::line_span;
use rustc_errors::Applicability;
use rustc_hir::{Expr, ExprKind};
use rustc_lint::{LateContext, LintContext};
use rustc_span::hygiene;
use rustc_span::{BytePos, Pos, Span, SyntaxContext};
... | <'a, T: LintContext>(
cx: &T,
expr: &Expr<'_>,
option: Option<String>,
default: &'a str,
indent_relative_to: Option<Span>,
) -> Cow<'a, str> {
let code = snippet_block(cx, expr.span, default, indent_relative_to);
let string = option.unwrap_or_default();
if expr.span.from_expansion() {
... | expr_block | identifier_name |
source.rs | //! Utils for extracting, inspecting or transforming source code
#![allow(clippy::module_name_repetitions)]
use crate::line_span;
use rustc_errors::Applicability;
use rustc_hir::{Expr, ExprKind};
use rustc_lint::{LateContext, LintContext};
use rustc_span::hygiene;
use rustc_span::{BytePos, Pos, Span, SyntaxContext};
... |
/// Same as `snippet`, but should only be used when it's clear that the input span is
/// not a macro argument.
pub fn snippet_with_macro_callsite<'a, T: LintContext>(cx: &T, span: Span, default: &'a str) -> Cow<'a, str> {
snippet(cx, span.source_callsite(), default)
}
/// Converts a span to a code snippet. Retu... | {
if *applicability != Applicability::Unspecified && span.from_expansion() {
*applicability = Applicability::MaybeIncorrect;
}
snippet_opt(cx, span).map_or_else(
|| {
if *applicability == Applicability::MachineApplicable {
*applicability = Applicability::HasPlaceh... | identifier_body |
spi_host.rs | use crate::hil::spi_host::SpiHost;
use core::cell::Cell;
use core::cmp::min;
use kernel::common::cells::{OptionalCell, TakeCell};
use kernel::common::registers::{register_bitfields, register_structs, ReadOnly, ReadWrite, WriteOnly};
use kernel::common::StaticRef;
use kernel::hil::spi::{ClockPolarity, ClockPhase, SpiMas... | CSBSU OFFSET(2) NUMBITS(4) [],
/// CSB from SCK hold time in SCK cycles + 1 (defined with respect to
/// the last SCK edge)
CSBHLD OFFSET(6) NUMBITS(4) [],
/// SPI Clk Divider. Actual divider is IDIV+1. A value of 0 gives divide
/// by 1 clock, 1 gives divide by 2 etc.
... | /// CPOL setting
CPOL OFFSET(0) NUMBITS(1) [],
/// CPHA setting
CPHA OFFSET(1) NUMBITS(1) [],
/// CSB to SCK setup time in SCK cycles + 1.5 | random_line_split |
spi_host.rs | use crate::hil::spi_host::SpiHost;
use core::cell::Cell;
use core::cmp::min;
use kernel::common::cells::{OptionalCell, TakeCell};
use kernel::common::registers::{register_bitfields, register_structs, ReadOnly, ReadWrite, WriteOnly};
use kernel::common::StaticRef;
use kernel::hil::spi::{ClockPolarity, ClockPhase, SpiMas... |
fn get_rate(&self) -> u32 {
panic!("get_rate is not implemented");
}
fn set_clock(&self, _polarity: ClockPolarity) {
panic!("set_clock is not implemented");
}
fn get_clock(&self) -> ClockPolarity {
panic!("get_clock is not implemented");
}
fn set_phase(&self, _phase:... | {
panic!("set_rate is not implemented");
} | identifier_body |
spi_host.rs | use crate::hil::spi_host::SpiHost;
use core::cell::Cell;
use core::cmp::min;
use kernel::common::cells::{OptionalCell, TakeCell};
use kernel::common::registers::{register_bitfields, register_structs, ReadOnly, ReadWrite, WriteOnly};
use kernel::common::StaticRef;
use kernel::hil::spi::{ClockPolarity, ClockPhase, SpiMas... | (&self, _phase: ClockPhase) {
panic!("set_phase is not implemented");
}
fn get_phase(&self) -> ClockPhase {
panic!("get_phase is not implemented");
}
fn hold_low(&self) {
panic!("hold_low is not implemented");
}
fn release_low(&self) {
// Nothing to do, since thi... | set_phase | identifier_name |
spi_host.rs | use crate::hil::spi_host::SpiHost;
use core::cell::Cell;
use core::cmp::min;
use kernel::common::cells::{OptionalCell, TakeCell};
use kernel::common::registers::{register_bitfields, register_structs, ReadOnly, ReadWrite, WriteOnly};
use kernel::common::StaticRef;
use kernel::hil::spi::{ClockPolarity, ClockPhase, SpiMas... | );
}
fn wait_busy_clear_in_transactions(&self, enabled: bool) {
self.registers.xact.modify(
if enabled { XACT::RDY_POLL::SET } else { XACT::RDY_POLL::CLEAR });
}
}
impl SpiMaster for SpiHostHardware {
type ChipSelect = bool;
fn set_client(&self, client: &'static dyn kernel::hi... | { CTRL::ENPASSTHRU::CLEAR } | conditional_block |
adc.rs | MCU.
//!
//! ## Clocking
//!
//! The ADC requires a clock signal (ADCK), which is generated from the bus
//! clock, the bus clock divided by 2, the output of the OSC peripheral
//! (OSC_OUT), or an internal asynchronous clock, which, when selected,
//! operates in wait and stop modes. With any of these clock sources a... | (&mut self, inst: Analog<VrefH<Input>>) {
self.vref_h.replace(inst);
}
/// Try to grab an instance of the onchip Voltage Reference Low ([VrefL]) channel.
pub fn vref_l(&mut self) -> Result<Analog<VrefL<Input>>, Error> {
self.vref_l.take().ok_or(Error::Moved)
}
/// Return the instan... | return_vref_h | identifier_name |
adc.rs | the MCU.
//!
//! ## Clocking
//!
//! The ADC requires a clock signal (ADCK), which is generated from the bus
//! clock, the bus clock divided by 2, the output of the OSC peripheral
//! (OSC_OUT), or an internal asynchronous clock, which, when selected,
//! operates in wait and stop modes. With any of these clock sourc... |
// Bandgap. Grab directly, Currently the bandgap isn't implemented
// in [system::PMC]. We will eventually have to pass in the pmc
// peripheral handle as a variable.
unsafe { &(*pac::PMC::ptr()) }
.spmsc1
.modify(|_, w| w.bgbe()._1());
... | // Don't start a conversion (set channel to DummyDisable)
self.peripheral.sc1.modify(|_, w| w.adch()._11111()); | random_line_split |
adc.rs | MCU.
//!
//! ## Clocking
//!
//! The ADC requires a clock signal (ADCK), which is generated from the bus
//! clock, the bus clock divided by 2, the output of the OSC peripheral
//! (OSC_OUT), or an internal asynchronous clock, which, when selected,
//! operates in wait and stop modes. With any of these clock sources a... |
/// Try to grab an instance of the onchip Voltage Reference High ([VrefH]) channel.
pub fn vref_h(&mut self) -> Result<Analog<VrefH<Input>>, Error> {
self.vref_h.take().ok_or(Error::Moved)
}
/// Return the instance of [VrefH]
pub fn return_vref_h(&mut self, inst: Analog<VrefH<Input>>) {
... | {
self.bandgap.replace(inst);
} | identifier_body |
adc.rs | MCU.
//!
//! ## Clocking
//!
//! The ADC requires a clock signal (ADCK), which is generated from the bus
//! clock, the bus clock divided by 2, the output of the OSC peripheral
//! (OSC_OUT), or an internal asynchronous clock, which, when selected,
//! operates in wait and stop modes. With any of these clock sources a... |
}
/// Set ADC target channel.
///
/// In Single conversion mode (OneShot), setting the channel begins the conversion. In FIFO mode
/// the channel is added to the FIFO buffer.
///
/// Note: If the channel is changed while a conversion is in progress the
/// current conversion will be c... | {
None
} | conditional_block |
installed.rs | // Copyright (c) 2016 Google Inc (lewinb@google.com).
//
// Refer to the project root for licensing information.
//
extern crate serde_json;
extern crate url;
use std::borrow::BorrowMut;
use std::convert::AsRef;
use std::error::Error;
use std::io;
use std::io::Read;
use std::sync::Mutex;
use std::sync::mpsc::{channel,... |
_ => {
*rp.status_mut() = status::StatusCode::BadRequest;
let _ = rp.send("Invalid Request!".as_ref());
}
}
}
}
impl InstalledFlowHandler {
fn handle_url(&self, url: hyper::Url) {
// Google redirects to the specified localhost URL, append... | {
// We use a fake URL because the redirect goes to a URL, meaning we
// can't use the url form decode (because there's slashes and hashes and stuff in
// it).
let url = hyper::Url::parse(&format!("http://example.com{}", path));
if url.is_... | conditional_block |
installed.rs | // Copyright (c) 2016 Google Inc (lewinb@google.com).
//
// Refer to the project root for licensing information.
//
extern crate serde_json;
extern crate url;
use std::borrow::BorrowMut;
use std::convert::AsRef;
use std::error::Error;
use std::io;
use std::io::Read;
use std::sync::Mutex;
use std::sync::mpsc::{channel,... | impl server::Handler for InstalledFlowHandler {
fn handle(&self, rq: server::Request, mut rp: server::Response) {
match rq.uri {
uri::RequestUri::AbsolutePath(path) => {
// We use a fake URL because the redirect goes to a URL, meaning we
// can't use the url form ... | struct InstalledFlowHandler {
auth_code_snd: Mutex<Sender<String>>,
}
| random_line_split |
installed.rs | // Copyright (c) 2016 Google Inc (lewinb@google.com).
//
// Refer to the project root for licensing information.
//
extern crate serde_json;
extern crate url;
use std::borrow::BorrowMut;
use std::convert::AsRef;
use std::error::Error;
use std::io;
use std::io::Read;
use std::sync::Mutex;
use std::sync::mpsc::{channel,... |
match listening {
Result::Err(_) => default,
Result::Ok(listening) => {
InstalledFlow {
client: default.client,
server: Some(listening)... | {
let default = InstalledFlow {
client: client,
server: None,
port: None,
auth_code_rcv: None,
};
match method {
None => default,
Some(InstalledFlowReturnMethod::Interactive) => default,
// Start server on localh... | identifier_body |
installed.rs | // Copyright (c) 2016 Google Inc (lewinb@google.com).
//
// Refer to the project root for licensing information.
//
extern crate serde_json;
extern crate url;
use std::borrow::BorrowMut;
use std::convert::AsRef;
use std::error::Error;
use std::io;
use std::io::Read;
use std::sync::Mutex;
use std::sync::mpsc::{channel,... | {
/// Involves showing a URL to the user and asking to copy a code from their browser
/// (default)
Interactive,
/// Involves spinning up a local HTTP server and Google redirecting the browser to
/// the server with a URL containing the code (preferred, but not as reliable). The
/// parameter i... | InstalledFlowReturnMethod | identifier_name |
patterns.rs | use insta::assert_snapshot;
use test_utils::mark;
use super::{infer, infer_with_mismatches};
#[test]
fn infer_pattern() {
assert_snapshot!(
infer(r#"
fn test(x: &i32) {
let y = x;
let &z = x;
let a = z;
let (c, d) = (1, "hello");
for (e, f) in some_iter {
let g = e;
}
... | );
}
#[test]
fn infer_pattern_match_ergonomics() {
assert_snapshot!(
infer(r#"
struct A<T>(T);
fn test() {
let A(n) = &A(1);
let A(n) = &mut A(1);
}
"#),
@r###"
28..79 '{ ...(1); }': ()
38..42 'A(n)': A<i32>
40..41 'n': &i32
45..50 '&A(1)': &A<i32>
46..47 'A': A<i32... | {
assert_snapshot!(
infer_with_mismatches(r#"
fn test(x: &i32) {
if let 1..76 = 2u32 {}
if let 1..=76 = 2u32 {}
}
"#, true),
@r###"
9..10 'x': &i32
18..76 '{ ...2 {} }': ()
24..46 'if let...u32 {}': ()
31..36 '1..76': u32
39..43 '2u32': u32
44..46 '{}': ()
51.... | identifier_body |
patterns.rs | use insta::assert_snapshot;
use test_utils::mark;
use super::{infer, infer_with_mismatches};
#[test]
fn infer_pattern() {
assert_snapshot!(
infer(r#"
fn test(x: &i32) {
let y = x;
let &z = x;
let a = z;
let (c, d) = (1, "hello");
for (e, f) in some_iter {
let g = e;
}
... | () {
mark::check!(match_ergonomics_ref);
assert_snapshot!(
infer(r#"
fn test() {
let v = &(1, &2);
let (_, &w) = v;
}
"#),
@r###"
11..57 '{ ...= v; }': ()
21..22 'v': &(i32, &i32)
25..33 '&(1, &2)': &(i32, &i32)
26..33 '(1, &2)': (i32, &i32)
27..28 '1': i32
30..32 ... | infer_pattern_match_ergonomics_ref | identifier_name |
patterns.rs | use insta::assert_snapshot;
use test_utils::mark;
use super::{infer, infer_with_mismatches};
#[test]
fn infer_pattern() {
assert_snapshot!( | let (c, d) = (1, "hello");
for (e, f) in some_iter {
let g = e;
}
if let [val] = opt {
let h = val;
}
let lambda = |a: u64, b, c: i32| { a + b; c };
let ref ref_to_x = x;
let mut mut_x = x;
let ref mut mut_ref_to_x = x;
let k = mut_ref_to_x;
}
"#),
@r#... | infer(r#"
fn test(x: &i32) {
let y = x;
let &z = x;
let a = z; | random_line_split |
list_view.rs | use std::sync::Arc;
use crate::aliases::WinResult;
use crate::co;
use crate::funcs::{GetAsyncKeyState, GetCursorPos, PostQuitMessage};
use crate::gui::base::Base;
use crate::gui::events::ListViewEvents;
use crate::gui::native_controls::list_view_columns::ListViewColumns;
use crate::gui::native_controls::list_v... | match &self.0.opts_id {
OptsId::Wnd(opts) => {
let mut pos = opts.position;
let mut sz = opts.size;
multiply_dpi(Some(&mut pos), Some(&mut sz))?;
self.0.base.create_window( // may panic
"SysListView32", None, pos, sz,
opts.ctrl_id,
opts.window_ex_style,
opts... | || -> WinResult<()> {
| random_line_split |
list_view.rs | use std::sync::Arc;
use crate::aliases::WinResult;
use crate::co;
use crate::funcs::{GetAsyncKeyState, GetCursorPos, PostQuitMessage};
use crate::gui::base::Base;
use crate::gui::events::ListViewEvents;
use crate::gui::native_controls::list_view_columns::ListViewColumns;
use crate::gui::native_controls::list_v... | (&self, set: bool, ex_style: co::LVS_EX) {
self.hwnd().SendMessage(lvm::SetExtendedListViewStyle {
mask: ex_style,
style: if set { ex_style } else { co::LVS_EX::NoValue },
});
}
fn show_context_menu(&self,
follow_cursor: bool, has_ctrl: bool, has_shift: bool) -> WinResult<()>
{
let hmenu = m... | toggle_extended_style | identifier_name |
list_view.rs | use std::sync::Arc;
use crate::aliases::WinResult;
use crate::co;
use crate::funcs::{GetAsyncKeyState, GetCursorPos, PostQuitMessage};
use crate::gui::base::Base;
use crate::gui::events::ListViewEvents;
use crate::gui::native_controls::list_view_columns::ListViewColumns;
use crate::gui::native_controls::list_v... |
self
}
}
| {
self.ctrl_id = auto_ctrl_id();
} | conditional_block |
main.rs | //
extern crate bio;
extern crate itertools;
use std::collections::HashMap;
use std::cmp;
use std::env;
use std::error::Error;
use std::fs::File;
use std::io::prelude::*;
use bio::io::fastq;
use bio::alignment::pairwise::*;
use bio::alignment::AlignmentOperation;
// fn check(rec: &fastq::Record, read: &str) -> (u16, V... | () {
let args : Vec<String> = env::args().collect();
let file1 = fastq::Reader::from_file(&args[1]).unwrap();
let file2 = fastq::Reader::from_file(&args[2]).unwrap();
let mut num_records = 0;
let mut num_duplicates = 0;
let mut num_qual_skip = 0;
let mut results : HashMap<String, (String, ... | main | identifier_name |
main.rs | //
extern crate bio;
extern crate itertools;
use std::collections::HashMap;
use std::cmp;
use std::env;
use std::error::Error;
use std::fs::File;
use std::io::prelude::*;
use bio::io::fastq;
use bio::alignment::pairwise::*;
use bio::alignment::AlignmentOperation;
// fn check(rec: &fastq::Record, read: &str) -> (u16, V... | // distance += 1;
// }
// }
// else {
// distance += 1;
// }
// index += 1;
// }
// (distance, dif)
// }
fn hamming(seq1: &str, seq2: &str) -> u32 {
let mut score = 0;
for (i, j) in seq1.chars().zip(seq2.chars()) {
if i!= j... | // if i != j {
// dif.push((index, i, j)); | random_line_split |
main.rs | //
extern crate bio;
extern crate itertools;
use std::collections::HashMap;
use std::cmp;
use std::env;
use std::error::Error;
use std::fs::File;
use std::io::prelude::*;
use bio::io::fastq;
use bio::alignment::pairwise::*;
use bio::alignment::AlignmentOperation;
// fn check(rec: &fastq::Record, read: &str) -> (u16, V... |
fn ham_mutations(seq1: &str, seq2: &str) -> (u32, String) {
let mut score = 0;
let mut mutations = "".to_string();
let mut n = 1;
for (i, j) in seq1.chars().zip(seq2.chars()) {
if i!= j {
score += 1;
if score == 1 {
mutations = mutations + &format!("{}{... | {
let mut score = 0;
for (i, j) in seq1.chars().zip(seq2.chars()) {
if i != j {
score += 1;
}
}
score
} | identifier_body |
main.rs | #[macro_use]
extern crate microprofile;
//
use rand::{distributions as distr, distributions::Distribution};
use starframe::{
self as sf,
game::{self, Game},
graph, graphics as gx,
input::{Key, MouseButton},
math::{self as m, uv},
physics as phys,
};
mod mousegrab;
use mousegrab::MouseGrabber... | {
graph: graph::Graph,
l_pose: graph::Layer<m::Pose>,
l_collider: graph::Layer<phys::Collider>,
l_body: graph::Layer<phys::RigidBody>,
l_shape: graph::Layer<gx::Shape>,
l_player: graph::Layer<player::Player>,
l_evt_sink: sf::event::EventSinkLayer<MyGraph>,
}
impl MyGraph {
pub fn new() ... | MyGraph | identifier_name |
main.rs | #[macro_use]
extern crate microprofile;
//
use rand::{distributions as distr, distributions::Distribution};
use starframe::{
self as sf,
game::{self, Game},
graph, graphics as gx,
input::{Key, MouseButton},
math::{self as m, uv},
physics as phys,
};
mod mousegrab;
use mousegrab::MouseGrabber... | distr::Uniform::from(-5.0..5.0).sample(&mut rng),
distr::Uniform::from(-5.0..5.0).sample(&mut rng),
]
};
let mut rng = rand::thread_rng();
if game.input.is_key_pressed(Key::S, Some(0)) {
Recipe::DynamicBlock(recipes::Block {
... | let random_vel = || {
let mut rng = rand::thread_rng();
[ | random_line_split |
main.rs | {
#[clap(long)]
labels: bool,
#[clap(long)]
statement_counts: bool,
#[clap(short, long, default_value = "0")]
skip: u64,
#[clap(short, long)]
threads: Option<usize>,
#[clap(required = true)]
paths: Vec<String>,
}
#[derive(Debug, PartialEq, Eq, Copy, Clone)]
pub enum Extra<'a> {... | Opts | identifier_name | |
main.rs | String, u64>>,
}
lazy_static! {
static ref RE: Regex = Regex::new(
r#"(?x)
^
\s*
# subject
(?:
# IRI
(?:<([^>]*)>)
|
# Blank
(?:_:([^\s]+))
)
\s*
# predicate IRI
<([^>]*)>
\s*
... | }
},
_ => {
panic!("invalid escape {}{} at {} in {}", c, c2, idx, s);
}
});
continue;
}
};
}
res.push(c);
... | },
'U' => match parse_unicode(&mut chars, 8) {
Ok(c3) => c3,
Err(err) => {
panic!("invalid escape {}{} at {} in {}: {}", c, c2, idx, s, err); | random_line_split |
main.rs | static_include_str! {
PROPERTIES_DATA => "properties",
IDENTIFIER_PROPERTIES_DATA => "identifier-properties",
LANGUAGES_DATA => "languages",
LABELS_DATA => "labels",
}
lazy_static! {
static ref PROPERTIES: HashSet<&'static str> = line_set(&PROPERTIES_DATA);
}
lazy_static! {
static ref IDENTIFI... | {
let dir = env!("CARGO_MANIFEST_DIR");
let mut in_path = PathBuf::from(dir);
in_path.push("test.in.rdf");
let in_path = in_path.as_os_str().to_str().unwrap();
let mut out_path = PathBuf::from(dir);
out_path.push("test.out.rdf");
let out_path = out_path.as_os_st... | identifier_body | |
writer.rs |
call_locations: IndexSet<raw::SourceLocation>,
/// A map from code ranges to the [`raw::SourceLocation`]s they correspond to.
///
/// Only the starting address of a range is saved, the end address is given implicitly
/// by the start address of the next range.
ranges: BTreeMap<u32, raw::SourceL... | (&mut self, arch: Arch) {
self.arch = arch;
}
/// Sets the debug identifier of this SymCache.
pub fn set_debug_id(&mut self, debug_id: DebugId) {
self.debug_id = debug_id;
}
// Methods processing symbolic-debuginfo [`ObjectLike`] below:
// Feel free to move these to a separate ... | set_arch | identifier_name |
writer.rs |
call_locations: IndexSet<raw::SourceLocation>,
/// A map from code ranges to the [`raw::SourceLocation`]s they correspond to.
///
/// Only the starting address of a range is saved, the end address is given implicitly
/// by the start address of the next range.
ranges: BTreeMap<u32, raw::SourceL... | let num_ranges = self.ranges.len() as u32;
let string_bytes = self.string_table.into_bytes();
let header = raw::Header {
magic: raw::SYMCACHE_MAGIC,
version: crate::SYMCACHE_VERSION,
debug_id: self.debug_id,
arch: self.arch,
num_file... | let mut writer = Writer::new(writer);
// Insert a trailing sentinel source location in case we have a definite end addr
if let Some(last_addr) = self.last_addr {
// TODO: to be extra safe, we might check that `last_addr` is indeed larger than
// the largest range at some... | identifier_body |
writer.rs | `.
call_locations: IndexSet<raw::SourceLocation>,
/// A map from code ranges to the [`raw::SourceLocation`]s they correspond to.
///
/// Only the starting address of a range is saved, the end address is given implicitly
/// by the start address of the next range.
ranges: BTreeMap<u32, raw::Sourc... | let language = function.name.language();
let mut function = transform::Function {
name: function.name.as_str().into(),
comp_dir: comp_dir.map(Into::into),
};
for transformer in &mut self.transformers.0 {
function = transform... | } else {
function.address as u32
};
let function_idx = { | random_line_split |
sup.rs | use super::util::{CacheKeyPath,
RemoteSup};
use crate::VERSION;
use configopt::{ConfigOptDefaults,
ConfigOptToString,
Partial};
use habitat_common::{cli::{RING_ENVVAR,
RING_KEY_ENVVAR},
types::{AutomateAuthToken,
... | (#[serde(with = "serde_string")] NatsAddress);
impl fmt::Display for EventStreamAddress {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.0) }
}
impl FromStr for EventStreamAddress {
type Err = RantsError;
fn from_str(s: &str) -> Result<Self, Self::Err> { Ok(EventStreamAdd... | EventStreamAddress | identifier_name |
sup.rs | use super::util::{CacheKeyPath,
RemoteSup};
use crate::VERSION;
use configopt::{ConfigOptDefaults,
ConfigOptToString,
Partial};
use habitat_common::{cli::{RING_ENVVAR,
RING_KEY_ENVVAR},
types::{AutomateAuthToken,
... | /// run --ring myring)
#[structopt(name = "RING",
long = "ring",
short = "r",
env = RING_ENVVAR,
conflicts_with = "RING_KEY")]
ring: String,
/// The contents of the ring key when running with wire encryption. (Note: This option is
/// e... | #[structopt(flatten)]
cache_key_path: CacheKeyPath,
/// The name of the ring used by the Supervisor when running with wire encryption. (ex: hab sup | random_line_split |
texture.rs | use enum_dispatch::enum_dispatch;
use log::error;
use crate::textures::dots::DotsTexture;
use crate::textures::constant::ConstantTexture;
use crate::textures::scaled::ScaleTexture;
use crate::core::interaction::SurfaceInteraction;
use crate::textures::imagemap::{ ImageTextureFloat, ImageTextureRGB};
use crate::textures... | else { v })
}
fn noise_weight(t: Float) -> Float {
let t3 = t * t * t;
let t4 = t3 * t;
6.0 * t4 * t - 15.0 * t4 + 10.0 * t3
}
pub fn fbm(
p: &Point3f, dpdx: &Vector3f, dpdy: &Vector3f,
omega: Float, max_octaves: usize) -> Float {
// Compute number of octaves for antialiased FBm
let len2... | { -v } | conditional_block |
texture.rs | use enum_dispatch::enum_dispatch;
use log::error;
use crate::textures::dots::DotsTexture;
use crate::textures::constant::ConstantTexture;
use crate::textures::scaled::ScaleTexture;
use crate::core::interaction::SurfaceInteraction;
use crate::textures::imagemap::{ ImageTextureFloat, ImageTextureRGB};
use crate::textures... |
for _i in nint..max_octaves {
sum += o * 0.2;
o *= omega;
}
sum
}
fn smooth_step(min: Float, max: Float, value: Float) -> Float {
let v = clamp((value - min) / (max - min), 0.0, 1.0);
v * v * (-2.0 * v + 3.0)
}
pub fn get_mapping2d(t2w: &Transform, tp: &mut TextureParams) -> Tex... | smooth_step(0.3, 0.7, npartial),
0.2,
noisep(*p * lambda).abs()); | random_line_split |
texture.rs | use enum_dispatch::enum_dispatch;
use log::error;
use crate::textures::dots::DotsTexture;
use crate::textures::constant::ConstantTexture;
use crate::textures::scaled::ScaleTexture;
use crate::core::interaction::SurfaceInteraction;
use crate::textures::imagemap::{ ImageTextureFloat, ImageTextureRGB};
use crate::textures... | (vs: &Vector3f, vt: &Vector3f,
ds: Float, dt: Float) -> Self {
Self {
ds,
dt,
vs: *vs,
vt: *vt
}
}
}
impl TextureMapping2D for PlannarMapping2D {
fn map(&self, si: &SurfaceInteraction, dstdx: &mut Vector2f,
dstdy: &mut Ve... | new | identifier_name |
texture.rs | use enum_dispatch::enum_dispatch;
use log::error;
use crate::textures::dots::DotsTexture;
use crate::textures::constant::ConstantTexture;
use crate::textures::scaled::ScaleTexture;
use crate::core::interaction::SurfaceInteraction;
use crate::textures::imagemap::{ ImageTextureFloat, ImageTextureRGB};
use crate::textures... |
}
impl TextureMapping2D for UVMapping2D {
fn map(&self, si: &SurfaceInteraction,
dstdx: &mut Vector2f, dstdy: &mut Vector2f) -> Point2f {
// Compute texture differentials for sphere (u, v) mapping
*dstdx = Vector2f::new(self.su * si.dudx.get(), self.sv * si.dvdx.get());
*dstdy =... | {
Self { su, sv, du, dv }
} | identifier_body |
batches.rs | #[macro_use]
extern crate clap;
use clap::{Command, Arg, ArgAction};
use rusqlite as rs;
use std::path::Path;
use std::error::Error;
use std::vec::Vec;
use std::ffi::OsString;
use std::collections::HashSet;
use chrono::Local;
use chrono::DateTime;
use chrono::Datelike;
use glob::glob;
use count_write::CountWrite;
u... | (compact: &HashSet<OsString>, filename: &str) -> Result<(), Box<dyn Error>> {
let tarfile = OpenOptions::new()
.write(true)
.create_new(true)
.open(filename);
let mut tar = Builder::new(Encoder::new(tarfile?, 21)?.auto_finish());
for f in compact.iter() {
let mut file = File::... | compact | identifier_name |
batches.rs | #[macro_use]
extern crate clap;
use clap::{Command, Arg, ArgAction};
use rusqlite as rs;
use std::path::Path;
use std::error::Error;
use std::vec::Vec;
use std::ffi::OsString;
use std::collections::HashSet;
use chrono::Local;
use chrono::DateTime;
use chrono::Datelike;
use glob::glob;
use count_write::CountWrite;
u... |
fn delete_set(all: &HashSet<OsString>, keep: Vec<&HashSet<OsString>>) -> HashSet<OsString> {
let mut delete = all.clone();
for hs in keep {
let out = delete.difference(&hs).map(|e| e.clone()).collect();
delete = out;
}
delete
}
fn compact(compact: &HashSet<OsString>, filename: &str)... | {
glob(&(directory.to_string() + glob_str)).unwrap()
.flatten()
.map(|e| e.into_os_string())
.collect::<HashSet<OsString>>()
} | identifier_body |
batches.rs | #[macro_use]
extern crate clap;
use clap::{Command, Arg, ArgAction};
use rusqlite as rs;
use std::path::Path;
use std::error::Error;
use std::vec::Vec;
use std::ffi::OsString;
use std::collections::HashSet;
use chrono::Local;
use chrono::DateTime;
use chrono::Datelike;
use glob::glob;
use count_write::CountWrite;
u... | let delete = m.contains_id("delete");
run(filename, *min, delete)
},
Some(("prune", m)) => {
let directory = m.get_one::<String>("BACKUPS").unwrap();
let delete = m.contains_id("delete");
let skip = m.contains_id("skip");
prune(di... | let filename = m.get_one::<String>("FILE").unwrap();
let min = m.get_one::<u32>("min").unwrap(); | random_line_split |
batches.rs | #[macro_use]
extern crate clap;
use clap::{Command, Arg, ArgAction};
use rusqlite as rs;
use std::path::Path;
use std::error::Error;
use std::vec::Vec;
use std::ffi::OsString;
use std::collections::HashSet;
use chrono::Local;
use chrono::DateTime;
use chrono::Datelike;
use glob::glob;
use count_write::CountWrite;
u... |
}
Ok(())
}
| {
std::fs::remove_file(path)?;
} | conditional_block |
data_farmer.rs | use lazy_static::lazy_static;
/// In charge of cleaning, processing, and managing data. I couldn't think of
/// a better name for the file. Since I called data collection "harvesting",
/// then this is the farmer I guess.
///
/// Essentially the main goal is to shift the initial calculation and distribution
/// of jo... | else {
0.0
};
// In addition copy over latest data for easy reference
self.network_harvest = network.clone();
}
fn eat_cpu(&mut self, cpu: &[cpu::CpuData], new_entry: &mut TimedData) {
trace!("Eating CPU.");
// Note this only pre-calculates the data points ... | {
(network.tx as f64).log2()
} | conditional_block |
data_farmer.rs | use lazy_static::lazy_static;
/// In charge of cleaning, processing, and managing data. I couldn't think of
/// a better name for the file. Since I called data collection "harvesting",
/// then this is the farmer I guess.
///
/// Essentially the main goal is to shift the initial calculation and distribution
/// of jo... | fn default() -> Self {
DataCollection {
current_instant: Instant::now(),
frozen_instant: None,
timed_data_vec: Vec::default(),
network_harvest: network::NetworkHarvest::default(),
memory_harvest: mem::MemHarvest::default(),
swap_harvest... | }
impl Default for DataCollection { | random_line_split |
data_farmer.rs | use lazy_static::lazy_static;
/// In charge of cleaning, processing, and managing data. I couldn't think of
/// a better name for the file. Since I called data collection "harvesting",
/// then this is the farmer I guess.
///
/// Essentially the main goal is to shift the initial calculation and distribution
/// of jo... | {
pub rx_data: Value,
pub tx_data: Value,
pub cpu_data: Vec<Value>,
pub mem_data: Value,
pub swap_data: Value,
}
/// AppCollection represents the pooled data stored within the main app
/// thread. Basically stores a (occasionally cleaned) record of the data
/// collected, and what is needed to co... | TimedData | identifier_name |
data_farmer.rs | use lazy_static::lazy_static;
/// In charge of cleaning, processing, and managing data. I couldn't think of
/// a better name for the file. Since I called data collection "harvesting",
/// then this is the farmer I guess.
///
/// Essentially the main goal is to shift the initial calculation and distribution
/// of jo... |
pub fn set_frozen_time(&mut self) {
self.frozen_instant = Some(self.current_instant);
}
pub fn clean_data(&mut self, max_time_millis: u64) {
trace!("Cleaning data.");
let current_time = Instant::now();
let mut remove_index = 0;
for entry in &self.timed_data_vec {
... | {
self.timed_data_vec = Vec::default();
self.network_harvest = network::NetworkHarvest::default();
self.memory_harvest = mem::MemHarvest::default();
self.swap_harvest = mem::MemHarvest::default();
self.cpu_harvest = cpu::CpuHarvest::default();
self.process_harvest = Vec::... | identifier_body |
lib.rs | #![allow(non_snake_case)]
#![cfg_attr(test, feature(test))]
extern crate num_integer;
extern crate num_traits;
use num_integer::Integer;
use num_traits::{PrimInt,Signed,One,NumCast};
use ::std::collections::HashMap;
use ::std::hash::Hash;
#[cfg(test)] extern crate test;
#[cfg(test)] extern crate rand;
#[derive(Copy... | <X>(a: X, b: X) -> X where
X: PrimInt + Integer + Signed,
{
let GcdData { gcd,.. } = extended_gcd__inline(a, b);
gcd
}
/// Compute a least common multiple.
pub fn lcm<X>(a: X, b: X) -> X where
X: PrimInt + Integer + Signed,
{
let GcdData { lcm,.. } = extended_gcd__inline(a, b);
lcm
}
/// Compute a modular multi... | gcd | identifier_name |
lib.rs | #![allow(non_snake_case)]
#![cfg_attr(test, feature(test))]
extern crate num_integer;
extern crate num_traits;
use num_integer::Integer;
use num_traits::{PrimInt,Signed,One,NumCast};
use ::std::collections::HashMap;
use ::std::hash::Hash;
#[cfg(test)] extern crate test;
#[cfg(test)] extern crate rand;
#[derive(Copy... | else { Some(upper - One::one()) },
Upto(max) => if min > max { None } else { Some(max) },
}
}
}
#[test]
fn test_inclusive_limit_from() {
assert_eq!(Upto(4).inclusive_limit_from(3), Some(4));
assert_eq!(Upto(3).inclusive_limit_from(3), Some(3));
assert_eq!(Upto(2).inclusive_limit_from(3), None);
assert_eq... | { None } | conditional_block |
lib.rs | #![allow(non_snake_case)]
#![cfg_attr(test, feature(test))]
extern crate num_integer;
extern crate num_traits;
use num_integer::Integer;
use num_traits::{PrimInt,Signed,One,NumCast};
use ::std::collections::HashMap;
use ::std::hash::Hash;
#[cfg(test)] extern crate test;
#[cfg(test)] extern crate rand;
#[derive(Copy... |
/// Compute a least common multiple.
pub fn lcm<X>(a: X, b: X) -> X where
X: PrimInt + Integer + Signed,
{
let GcdData { lcm,.. } = extended_gcd__inline(a, b);
lcm
}
/// Compute a modular multiplicative inverse, if it exists.
///
/// This implementation uses the extended Gcd algorithm,
pub fn inverse_mod<X>(a: X,... | {
let GcdData { gcd, .. } = extended_gcd__inline(a, b);
gcd
} | identifier_body |
lib.rs | #![allow(non_snake_case)]
#![cfg_attr(test, feature(test))]
extern crate num_integer;
extern crate num_traits;
use num_integer::Integer;
use num_traits::{PrimInt,Signed,One,NumCast};
use ::std::collections::HashMap;
use ::std::hash::Hash;
#[cfg(test)] extern crate test;
#[cfg(test)] extern crate rand;
#[derive(Copy... | // not already reduced modulo n_i?
}
#[test]
fn test_inverse_mod() {
let solns15 = vec![
None, Some(1), Some(8), None, Some(4),
None, None, Some(13), Some(2), None,
None, Some(11), None, Some(7), Some(14),
];
for x in -15..30 {
assert_eq!(inverse_mod(x,15), solns15[x.mod_floor(&15... | random_line_split | |
main.rs | let [a, b, c] = self.0;
if a == b && b == c {
write!(f, "mono")
}
else {
let mut res = ['?'; 3];
res[a] = 'A';
res[b] = 'B';
res[c] = 'C';
let [l, r, c] = res;
write!(f, "{l}{c}{r}")
}
}
}
impl Def... |
fn print_current(last_secs: &mut u32, cur_secs: f32, total_secs: f32) {
let secs = cur_secs.trunc() as u32;
if *last_secs == secs {
return;
}
*last_secs = secs;
print!("\r");
print_time(secs);
print!(" -> ");
print_time((total_secs - cur_secs).trunc() as u32);
stdout().flus... | {
let hours = secs / 3600;
let minutes = (secs % 3600) / 60;
let secs = secs % 60;
if hours != 0 {
print!("{hours}:{minutes:02}:{secs:02}");
}
else {
print!("{minutes:02}:{secs:02}");
}
} | identifier_body |
main.rs | let [a, b, c] = self.0;
if a == b && b == c {
write!(f, "mono")
}
else {
let mut res = ['?'; 3];
res[a] = 'A';
res[b] = 'B';
res[c] = 'C';
let [l, r, c] = res;
write!(f, "{l}{c}{r}")
}
}
}
impl Def... | (mut s: &str) -> Result<StreamConfigHint, String> {
let mut config = StreamConfigHint::default();
if s == "*" {
return Ok(config);
}
const FORMATS: &[([&str;2], cpal::SampleFormat)] = &[
(["i8", "I8"], cpal::SampleFormat::I8),
(["u8", "U8"], cpal::SampleFormat::U8),
... | parse_stream_config | identifier_name |
main.rs | let [a, b, c] = self.0;
if a == b && b == c {
write!(f, "mono")
}
else {
let mut res = ['?'; 3];
res[a] = 'A';
res[b] = 'B';
res[c] = 'C';
let [l, r, c] = res;
write!(f, "{l}{c}{r}")
}
}
}
impl D... | })
}
fn parse_channels(s: &str) -> Result<ChannelMap, String> {
const ERROR_MSG: &str = "channel mapping should be a permutation of ABC characters";
if s.len()!= 3 {
return Err(ERROR_MSG.into());
}
let mut channels = [usize::MAX; 3];
// [A, B, C], where N -> 0: left, 1: right, 2: center... | ChannelMode::Channel(channel)
} | random_line_split |
mod.rs | mod light;
pub use light::*;
use crate::StandardMaterial;
use bevy_asset::{Assets, Handle};
use bevy_ecs::{prelude::*, system::SystemState};
use bevy_math::Mat4;
use bevy_render2::{
core_pipeline::Transparent3dPhase,
mesh::Mesh,
pipeline::*,
render_graph::{Node, NodeRunError, RenderGraphContext},
r... |
}
commands.insert_resource(ExtractedMeshes {
meshes: extracted_meshes,
});
}
#[derive(Default)]
pub struct MeshMeta {
transform_uniforms: DynamicUniformVec<Mat4>,
}
pub fn prepare_meshes(
render_resources: Res<RenderResources>,
mut mesh_meta: ResMut<MeshMeta>,
mut extracted_meshe... | {
if let Some(gpu_data) = &mesh.gpu_data() {
extracted_meshes.push(ExtractedMesh {
transform: transform.compute_matrix(),
vertex_buffer: gpu_data.vertex_buffer,
index_info: gpu_data.index_buffer.map(|i| IndexInfo {
... | conditional_block |
mod.rs | mod light;
pub use light::*;
use crate::StandardMaterial;
use bevy_asset::{Assets, Handle};
use bevy_ecs::{prelude::*, system::SystemState};
use bevy_math::Mat4;
use bevy_render2::{
core_pipeline::Transparent3dPhase,
mesh::Mesh,
pipeline::*,
render_graph::{Node, NodeRunError, RenderGraphContext},
r... |
}
impl Draw for DrawPbr {
fn draw(
&mut self,
world: &World,
pass: &mut TrackedRenderPass,
view: Entity,
draw_key: usize,
_sort_key: usize,
) {
let (pbr_shaders, extracted_meshes, views) = self.params.get(world);
let (view_uniforms, mesh_view_bin... | {
Self {
params: SystemState::new(world),
}
} | identifier_body |
mod.rs | mod light;
pub use light::*;
use crate::StandardMaterial;
use bevy_asset::{Assets, Handle};
use bevy_ecs::{prelude::*, system::SystemState};
use bevy_math::Mat4;
use bevy_render2::{
core_pipeline::Transparent3dPhase,
mesh::Mesh,
pipeline::*,
render_graph::{Node, NodeRunError, RenderGraphContext},
r... | _graph: &mut RenderGraphContext,
render_context: &mut dyn RenderContext,
world: &World,
) -> Result<(), NodeRunError> {
let mesh_meta = world.get_resource::<MeshMeta>().unwrap();
let light_meta = world.get_resource::<LightMeta>().unwrap();
mesh_meta
.transf... | fn run(
&self, | random_line_split |
mod.rs | mod light;
pub use light::*;
use crate::StandardMaterial;
use bevy_asset::{Assets, Handle};
use bevy_ecs::{prelude::*, system::SystemState};
use bevy_math::Mat4;
use bevy_render2::{
core_pipeline::Transparent3dPhase,
mesh::Mesh,
pipeline::*,
render_graph::{Node, NodeRunError, RenderGraphContext},
r... | (
&self,
_graph: &mut RenderGraphContext,
render_context: &mut dyn RenderContext,
world: &World,
) -> Result<(), NodeRunError> {
let mesh_meta = world.get_resource::<MeshMeta>().unwrap();
let light_meta = world.get_resource::<LightMeta>().unwrap();
mesh_meta
... | run | identifier_name |
mod.rs | //! Operating System backed readiness event queue.
//!
//! [`OsQueue`] provides an abstraction over platform specific Operating System
//! backed readiness event queues, such as kqueue or epoll.
//!
//! [`OsQueue`]: crate::os::OsQueue
//!
//! # Portability
//!
//! Using [`OsQueue`] provides a portable interface across ... | /// e.g. read or write.
///
/// To use this queue an [`Evented`] handle must first be registered using the
/// [`register`] method, supplying an associated id, readiness interests and
/// polling option. The [associated id] is used to associate a readiness event
/// with an `Evented` handle. The readiness [interests] d... | ///
/// This queue allows a program to monitor a large number of [`Evented`]
/// handles, waiting until one or more become "ready" for some class of
/// operations; e.g. [reading] or [writing]. An [`Evented`] type is considered
/// ready if it is possible to immediately perform a corresponding operation; | random_line_split |
mod.rs | //! Operating System backed readiness event queue.
//!
//! [`OsQueue`] provides an abstraction over platform specific Operating System
//! backed readiness event queues, such as kqueue or epoll.
//!
//! [`OsQueue`]: crate::os::OsQueue
//!
//! # Portability
//!
//! Using [`OsQueue`] provides a portable interface across ... |
}
impl<ES, E> event::Source<ES, E> for OsQueue
where ES: event::Sink,
E: From<io::Error>,
{
fn max_timeout(&self) -> Option<Duration> {
// Can't tell if an event is available.
None
}
fn poll(&mut self, event_sink: &mut ES) -> Result<(), E> {
self.blocking_poll(event_... | {
&self.selector
} | identifier_body |
mod.rs | //! Operating System backed readiness event queue.
//!
//! [`OsQueue`] provides an abstraction over platform specific Operating System
//! backed readiness event queues, such as kqueue or epoll.
//!
//! [`OsQueue`]: crate::os::OsQueue
//!
//! # Portability
//!
//! Using [`OsQueue`] provides a portable interface across ... | {
selector: sys::Selector,
}
impl OsQueue {
/// Create a new OS backed readiness event queue.
///
/// This function will make a syscall to the operating system to create the
/// system selector. If this syscall fails it will return the error.
///
/// # Examples
///
/// ```
/// ... | OsQueue | identifier_name |
room_model.rs | use crate::room::member::Member;
use crate::room::room::{MemberLeaveNoticeType, RoomState};
use crate::room::room::{Room, MEMBER_MAX};
use crate::task_timer::{Task, TaskCmd};
use crate::TEMPLATES;
use log::{error, info, warn};
use num_enum::IntoPrimitive;
use num_enum::TryFromPrimitive;
use protobuf::Message;
use rayon... | self.room_cache.remove(index as usize);
}
///快速加入
pub fn quickly_start(
&mut self,
member: Member,
sender: TcpSender,
task_sender: crossbeam::Sender<Task>,
) -> anyhow::Result<u32> {
let room_id: u32;
let user_id = member.user_id;
//如果房间缓存... | ex < 0 {
return;
}
| identifier_body |
room_model.rs | use crate::room::member::Member;
use crate::room::room::{MemberLeaveNoticeType, RoomState};
use crate::room::room::{Room, MEMBER_MAX};
use crate::task_timer::{Task, TaskCmd};
use crate::TEMPLATES;
use log::{error, info, warn};
use num_enum::IntoPrimitive;
use num_enum::TryFromPrimitive;
use protobuf::Message;
use rayon... | _id: u32;
let user_id = member.user_id;
//如果房间缓存里没有,则创建新房间
if self.room_cache.is_empty() {
//校验地图配置
let room_tmp_ref: &TileMapTempMgr = TEMPLATES.get_tile_map_temp_mgr_ref();
if room_tmp_ref.is_empty() {
anyhow::bail!("TileMapTempMgr is None")
... |
let room | identifier_name |
room_model.rs | use crate::room::member::Member;
use crate::room::room::{MemberLeaveNoticeType, RoomState};
use crate::room::room::{Room, MEMBER_MAX};
use crate::task_timer::{Task, TaskCmd};
use crate::TEMPLATES;
use log::{error, info, warn};
use num_enum::IntoPrimitive;
use num_enum::TryFromPrimitive;
use protobuf::Message;
use rayon... |
let room_cache = self.get_room_cache_mut(&room_id);
if room_cache.is_some() {
let rc = room_cache.unwrap();
rc.count -= 1;
//重新排序
self.room_cache.par_sort_by(|a, b| b.count.cmp(&a.count));
} else if room_cache.is_none() && need_add_cache {
... | } | random_line_split |
room_model.rs | use crate::room::member::Member;
use crate::room::room::{MemberLeaveNoticeType, RoomState};
use crate::room::room::{Room, MEMBER_MAX};
use crate::task_timer::{Task, TaskCmd};
use crate::TEMPLATES;
use log::{error, info, warn};
use num_enum::IntoPrimitive;
use num_enum::TryFromPrimitive;
use protobuf::Message;
use rayon... | leave(
&mut self,
battle_type: BattleType,
room_id: u32,
user_id: &u32,
) -> anyhow::Result<u32> {
let match_room = self.match_rooms.get_mut(&battle_type.into_u8());
if match_room.is_none() {
let str = format!("there is no battle_type:{:?}!", battle_type);... | _id);
}
}
///离开房间,离线也好,主动离开也好
pub fn | conditional_block |
main.rs | #[macro_use]
extern crate derive_new;
use std::fmt::{self, Debug, Display};
use serde::{Deserialize, Serialize};
const PROOF: &str = "0";
#[derive(Serialize, Deserialize, Debug, Clone, new)]
struct Block {
index: u64,
previus_hash: String,
timestamp: String,
data: Vec<Transaction>,
hash: String,... |
if y.reciver == wallet.pub_key {
let amount = y.amount as u128;
balance += amount;
}
}
}
println!("{}", balance);
balance
}
}
impl Display for Block {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::R... | {
let amount = y.amount as u128;
balance += amount;
} | conditional_block |
main.rs | #[macro_use]
extern crate derive_new;
use std::fmt::{self, Debug, Display};
use serde::{Deserialize, Serialize};
const PROOF: &str = "0";
#[derive(Serialize, Deserialize, Debug, Clone, new)]
struct Block {
index: u64,
previus_hash: String,
timestamp: String,
data: Vec<Transaction>,
hash: String,... | {
sender: String,
reciver: String,
amount: u64,
hash: Option<String>,
}
impl Transaction {
fn new(sender: Wallet, reciver: Wallet, amount: u64) -> Transaction {
let sender = sender.pub_key.clone();
let reciver = reciver.pub_key.clone();
let x = Transaction {
send... | Transaction | identifier_name |
main.rs | #[macro_use]
extern crate derive_new;
use std::fmt::{self, Debug, Display};
use serde::{Deserialize, Serialize};
const PROOF: &str = "0";
#[derive(Serialize, Deserialize, Debug, Clone, new)]
struct Block {
index: u64,
previus_hash: String,
timestamp: String,
data: Vec<Transaction>,
hash: String,... | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"{} {:?} {:?} {:?} {:?}",
self.index, self.previus_hash, self.timestamp, self.data, self.hash
)
}
}
fn calculate_hash_proof(
index: u64,
previus_hash: String,
timestamp: String,... | random_line_split | |
main.rs | #[macro_use]
extern crate derive_new;
use std::fmt::{self, Debug, Display};
use serde::{Deserialize, Serialize};
const PROOF: &str = "0";
#[derive(Serialize, Deserialize, Debug, Clone, new)]
struct Block {
index: u64,
previus_hash: String,
timestamp: String,
data: Vec<Transaction>,
hash: String,... |
}
trait Createblock {
fn new(
index: u64,
previus_hash: String,
timestamp: String,
data: Vec<Transaction>,
hash: String,
proof: u128,
) -> Self;
}
impl Createblock for Block {
fn new(
index: u64,
previus_hash: String,
timestamp: Strin... | {
write!(f, "{:?}-{:?}-{}", self.sender, self.reciver, self.amount)
} | identifier_body |
lib.rs | //! A fast, extensible, command-line arguments parser.
//!
//! This library is very new, so expect regular breaking changes. If you find a
//! bug or lacking documentation, don't hesitate to open an
//! [issue](https://github.com/Aloso/parkour/issues) or a pull request.
//!
//! This crate started as an experiment, so I... | //! # impl FromInput<'static> for Show {
//! # type Context = ();
//! # fn from_input(input: &mut ArgsInput, _: &()) -> parkour::Result<Self> {
//! # todo!()
//! # }
//! # }
//! #
//! struct Command {
//! color: Option<bool>,
//! show: Option<Show>,
//! }
//!
//! impl FromInput<'static> for ... | //! # color_space: ColorSpace,
//! # size: u8,
//! # } | random_line_split |
lib.rs | //! A fast, extensible, command-line arguments parser.
//!
//! This library is very new, so expect regular breaking changes. If you find a
//! bug or lacking documentation, don't hesitate to open an
//! [issue](https://github.com/Aloso/parkour/issues) or a pull request.
//!
//! This crate started as an experiment, so I... | () -> ArgsInput {
ArgsInput::from_args()
}
/// A prelude to make it easier to import all the needed types and traits. Use
/// it like this:
///
/// ```
/// use parkour::prelude::*;
/// ```
pub mod prelude {
pub use crate::actions::{
Action, Append, Dec, Inc, Reset, Set, SetOnce, SetPositional, SetSubco... | parser | identifier_name |
lib.rs | //! A fast, extensible, command-line arguments parser.
//!
//! This library is very new, so expect regular breaking changes. If you find a
//! bug or lacking documentation, don't hesitate to open an
//! [issue](https://github.com/Aloso/parkour/issues) or a pull request.
//!
//! This crate started as an experiment, so I... |
/// A prelude to make it easier to import all the needed types and traits. Use
/// it like this:
///
/// ```
/// use parkour::prelude::*;
/// ```
pub mod prelude {
pub use crate::actions::{
Action, Append, Dec, Inc, Reset, Set, SetOnce, SetPositional, SetSubcommand,
Unset,
};
pub use crate... | {
ArgsInput::from_args()
} | identifier_body |
gossip.rs | use crate::clock::{Clock, HybridTimestamp};
use crate::event_emitter::EventEmitter;
use crate::proto::gossip::*;
use crate::proto::gossip_grpc::*;
use crate::proto::PeerState;
use crate::rpc_client::RpcClient;
use failure::{err_msg, format_err, Error};
use futures::prelude::*;
use futures::sync::{mpsc, oneshot};
use gr... | (&self, address: &str) {
self.publish_event(GossipEvent::NewPeerDiscovered(address.to_string()));
}
fn update_meta_leader(&mut self, node_id: u64) {
self.current.set_meta_leader_id(node_id);
}
fn meta_leader_id(&self) -> Option<u64> {
if self.current.meta_leader_id!= 0 {
... | publish_peer_discovered | identifier_name |
gossip.rs | use crate::clock::{Clock, HybridTimestamp};
use crate::event_emitter::EventEmitter;
use crate::proto::gossip::*;
use crate::proto::gossip_grpc::*;
use crate::proto::PeerState;
use crate::rpc_client::RpcClient;
use failure::{err_msg, format_err, Error};
use futures::prelude::*;
use futures::sync::{mpsc, oneshot};
use gr... |
pub fn build_service(&self) -> Service {
create_gossip(self.clone())
}
pub fn state(&self) -> GossipState {
self.state.clone()
}
pub fn update_meta_leader(&self, id: u64) -> impl Future<Item = (), Error = ()> {
self.event(GossipEvent::MetaLeaderChanged(id))
}
pub... | {
let (sender, receiver) = mpsc::channel(32);
let state = GossipState::new(node_id, self_address, bootstrap, sender.clone(), clock);
run_gossip_event_handler(receiver, state.new_ref(), node_id);
GossipServer { state, sender }
} | identifier_body |
gossip.rs | use crate::clock::{Clock, HybridTimestamp};
use crate::event_emitter::EventEmitter;
use crate::proto::gossip::*;
use crate::proto::gossip_grpc::*;
use crate::proto::PeerState;
use crate::rpc_client::RpcClient;
use failure::{err_msg, format_err, Error};
use futures::prelude::*;
use futures::sync::{mpsc, oneshot};
use gr... |
gossip
.get_node_liveness()
.values()
.for_each(|peer| self.update_node_liveness(peer));
gossip
.get_peer_addresses()
.iter()
.filter(|(id, _)|!self.peers.contains_key(id))
.for_each(|(_, address)| self.publish_peer_discovere... | {
let address = gossip.get_address();
current_addrs.insert(peer_id, address.to_string());
self.publish_peer_discovered(address);
} | conditional_block |
gossip.rs | use crate::clock::{Clock, HybridTimestamp};
use crate::event_emitter::EventEmitter;
use crate::proto::gossip::*;
use crate::proto::gossip_grpc::*;
use crate::proto::PeerState;
use crate::rpc_client::RpcClient;
use failure::{err_msg, format_err, Error};
use futures::prelude::*;
use futures::sync::{mpsc, oneshot};
use gr... | peers: HashMap::new(),
};
inner.publish_peer_discovered(self_address);
bootstrap
.iter()
.for_each(|address| inner.publish_peer_discovered(address));
Self {
inner: Arc::new(RwLock::new(inner)),
}
}
fn get_current(&self) -> Go... | event_emitter,
clock,
connections: HashMap::new(),
clients: HashMap::new(), | random_line_split |
mod.rs | //! # Queueing Honey Badger
//!
//! This works exactly like Dynamic Honey Badger, but it has a transaction queue built in. Whenever
//! an epoch is output, it will automatically select a list of pending transactions and propose it
//! for the next one. The user can continuously add more pending transactions to the queu... | <R>(self, rng: R) -> QueueingHoneyBadgerWithStep<T, N, Q>
where
R:'static + Rng + Send + Sync,
{
self.build_with_transactions(None, rng)
.expect("building without transactions cannot fail")
}
/// Returns a new Queueing Honey Badger instance that starts with the given transact... | build | identifier_name |
mod.rs | //! # Queueing Honey Badger
//!
//! This works exactly like Dynamic Honey Badger, but it has a transaction queue built in. Whenever
//! an epoch is output, it will automatically select a list of pending transactions and propose it
//! for the next one. The user can continuously add more pending transactions to the queu... |
/// Returns a reference to the internal managed `DynamicHoneyBadger` instance.
pub fn dyn_hb(&self) -> &DynamicHoneyBadger<Vec<T>, N> {
&self.dyn_hb
}
/// Returns the information about the node IDs in the network, and the cryptographic keys.
pub fn netinfo(&self) -> &NetworkInfo<N> {
... | {
self.apply(|dyn_hb| dyn_hb.handle_message(sender_id, message))
} | identifier_body |
mod.rs | //! # Queueing Honey Badger
//!
//! This works exactly like Dynamic Honey Badger, but it has a transaction queue built in. Whenever
//! an epoch is output, it will automatically select a list of pending transactions and propose it
//! for the next one. The user can continuously add more pending transactions to the queu... | self.dyn_hb.our_id()
}
}
impl<T, N, Q> QueueingHoneyBadger<T, N, Q>
where
T: Contribution + Serialize + DeserializeOwned + Clone,
N: NodeIdT + Serialize + DeserializeOwned + Rand,
Q: TransactionQueue<T>,
{
/// Returns a new `QueueingHoneyBadgerBuilder` configured to use the node IDs and cry... | fn our_id(&self) -> &N { | random_line_split |
lib.rs | Enso are a very powerful mechanism and are used to transform group of tokens into
//! almost any statement. First, macros need to be discovered and registered. Currently, there is no
//! real macro discovery process, as there is no support for user-defined macros. Instead, there is
//! a set of hardcoded macros define... | (mut pattern: syntax::Tree) -> syntax::tree::ArgumentDefinition {
use syntax::tree::*;
let mut open1 = default();
let mut close1 = default();
if let box Variant::Group(Group { mut open, body: Some(mut body), close }) = pattern.variant {
*(if let Some(open) = open.as_mut() {
&mut open... | parse_argument_definition | identifier_name |
lib.rs | in Enso are a very powerful mechanism and are used to transform group of tokens into
//! almost any statement. First, macros need to be discovered and registered. Currently, there is no
//! real macro discovery process, as there is no support for user-defined macros. Instead, there is
//! a set of hardcoded macros def... | //! # Splitting the token stream by the macro segments.
//! The input token stream is being iterated and is being split based on the segments of the
//! registered macros. For example, for the input `if a b then c d else e f`, the token stream will
//! be split into three segments, `a b`, `c d`, and `e f`, which will b... | //! in case these segments were found. For example, let's consider two macros: `if ... then ...`,
//! and `if ... then ... else ...`. In such a case, the macro registry will contain only one entry,
//! "if", and two sets of possible resolution paths: ["then"], and ["then", "else"], each associated
//! with the correspo... | random_line_split |
lib.rs | Enso are a very powerful mechanism and are used to transform group of tokens into
//! almost any statement. First, macros need to be discovered and registered. Currently, there is no
//! real macro discovery process, as there is no support for user-defined macros. Instead, there is
//! a set of hardcoded macros define... |
str.push('x');
// Equal chance of the next line being interpreted as a body block or argument block
// line, if it is indented and doesn't match the operator-block syntax.
// The `=` operator is chosen to exercise the expression-to-statement conversion path.
... | {
str.push_str("* ");
} | conditional_block |
lib.rs | Enso are a very powerful mechanism and are used to transform group of tokens into
//! almost any statement. First, macros need to be discovered and registered. Currently, there is no
//! real macro discovery process, as there is no support for user-defined macros. Instead, there is
//! a set of hardcoded macros define... |
fn unroll_arguments<'s>(
mut tree: syntax::Tree<'s>,
args: &mut Vec<syntax::tree::ArgumentDefinition<'s>>,
) -> syntax::Tree<'s> {
while let Some(arg) = parse_argument_application(&mut tree) {
args.push(arg);
}
tree
}
/// Try to parse the expression as an application of a function to an `... | {
let mut args = vec![];
let first = unroll_arguments(tree, &mut args);
args.push(parse_argument_definition(first));
args.reverse();
args
} | identifier_body |
lib.rs | use counters::flavors::{Counter, CounterType};
use counters::Counters;
use crossbeam_queue::ArrayQueue;
use log::Logger;
use packet::BoxPkt;
use packet::PacketPool;
use perf::Perf;
use std::collections::HashMap;
use std::collections::VecDeque;
use std::sync::Arc;
// We preallocate space for these many graph nodes, of ... |
/// Queue one packet to another node
pub fn push(&mut self, node: usize, pkt: BoxPkt) -> bool {
let node = self.nodes[node];
if self.vectors[node].capacity() >= 1 {
self.vectors[node].push_back(pkt);
if node <= self.node {
self.work = true;
... | {
self.vectors[self.node].pop_front()
} | identifier_body |
lib.rs | use counters::flavors::{Counter, CounterType};
use counters::Counters;
use crossbeam_queue::ArrayQueue;
use log::Logger;
use packet::BoxPkt;
use packet::PacketPool;
use perf::Perf;
use std::collections::HashMap;
use std::collections::VecDeque;
use std::sync::Arc;
// We preallocate space for these many graph nodes, of ... | else {
self.work = true;
self.wakeup = wakeup;
}
}
}
/// The parameters each feature/client node needs to specify if it wants to be added
/// to the graph
pub struct GnodeInit {
/// A unique name for the node
pub name: String,
/// Names of all the nodes this node will h... | {
if wakeup < self.wakeup {
self.wakeup = wakeup;
}
} | conditional_block |
lib.rs | use counters::flavors::{Counter, CounterType};
use counters::Counters;
use crossbeam_queue::ArrayQueue;
use log::Logger;
use packet::BoxPkt;
use packet::PacketPool;
use perf::Perf;
use std::collections::HashMap;
use std::collections::VecDeque;
use std::sync::Arc;
// We preallocate space for these many graph nodes, of ... | <T> {
// The thread this graph belongs to
thread: usize,
// The graph nodes
nodes: Vec<Gnode<T>>,
// Graph node performance info
perf: Vec<Perf>,
// A per node packet queue, to hold packets from other nodes to this node
vectors: Vec<VecDeque<BoxPkt>>,
// Generic enq/deq/drop counters... | Graph | identifier_name |
lib.rs | use counters::flavors::{Counter, CounterType};
use counters::Counters;
use crossbeam_queue::ArrayQueue;
use log::Logger;
use packet::BoxPkt;
use packet::PacketPool;
use perf::Perf;
use std::collections::HashMap;
use std::collections::VecDeque;
use std::sync::Arc;
// We preallocate space for these many graph nodes, of ... | next_nodes: Vec::new(),
}
}
fn clone(&self, counters: &mut Counters, log: Arc<Logger>) -> Self {
Gnode {
client: self.client.clone(counters, log),
name: self.name.clone(),
next_names: self.next_names.clone(),
next_nodes: self.next_node... | random_line_split | |
claim_name.rs | use std::{ops::Deref, sync::Arc};
use aho_corasick::{AhoCorasick, AhoCorasickBuilder};
use bathbot_macros::SlashCommand;
use bathbot_model::{
rkyv_util::time::{DateRkyv, DateTimeRkyv},
rosu_v2::user::{ArchivedUser, User, UserHighestRank as UserHighestRankRkyv, UserStatistics},
};
use bathbot_util::{constants::... |
}
pub struct ClaimNameValidator;
impl ClaimNameValidator {
pub fn is_valid(prefix: &str) -> bool {
!VALIDATOR
.get_or_init(|| {
let needles = [
"qfqqz",
"dppljf{",
"difbu",
"ojhhfs",
... | {
match user {
RedisData::Original(user) => Self::from(user),
RedisData::Archive(user) => Self::from(user.deref()),
}
} | identifier_body |
claim_name.rs | use std::{ops::Deref, sync::Arc};
use aho_corasick::{AhoCorasick, AhoCorasickBuilder};
use bathbot_macros::SlashCommand;
use bathbot_model::{
rkyv_util::time::{DateRkyv, DateTimeRkyv},
rosu_v2::user::{ArchivedUser, User, UserHighestRank as UserHighestRankRkyv, UserStatistics},
};
use bathbot_util::{constants::... | (user: RedisData<User>) -> Self {
match user {
RedisData::Original(user) => Self::from(user),
RedisData::Archive(user) => Self::from(user.deref()),
}
}
}
pub struct ClaimNameValidator;
impl ClaimNameValidator {
pub fn is_valid(prefix: &str) -> bool {
!VALIDATOR
... | from | identifier_name |
claim_name.rs | use std::{ops::Deref, sync::Arc};
use aho_corasick::{AhoCorasick, AhoCorasickBuilder};
use bathbot_macros::SlashCommand;
use bathbot_model::{
rkyv_util::time::{DateRkyv, DateTimeRkyv},
rosu_v2::user::{ArchivedUser, User, UserHighestRank as UserHighestRankRkyv, UserStatistics},
};
use bathbot_util::{constants::... | pub user_id: u32,
}
impl From<User> for ClaimNameUser {
#[inline]
fn from(user: User) -> Self {
Self {
avatar_url: user.avatar_url,
country_code: user.country_code,
has_badges:!user.badges.is_empty(),
has_ranked_mapsets: user.ranked_mapset_count > 0,
... | pub username: Username, | random_line_split |
piston.rs | 4 v_Color;
uniform mat4 u_Projection;
uniform mat4 u_View;
uniform mat4 u_Model;
uniform vec4 u_Color;
uniform vec3 u_LightDirection;
void main() {
vec3 normal = normalize(vec3(u_Model * vec4(a_Normal, 0.0)));
float dot = max(dot(normal, u_LightDirection), 0.0);
v_Color... |
let (fx, fy) = point_to_coordinate(front);
let (x, y) = point_to_coordinate(pos.p);
let (dx, dy) = (fx - x, fy - y);
let how_much_ | self.player_pos = pos;
let front = pos.p + pos.dir; | random_line_split |
piston.rs | .0);
}
"
};
static FRAGMENT_SRC: gfx::ShaderSource<'static> = shaders! {
GLSL_150: b"
#version 150 core
smooth in vec4 v_Color;
out vec4 o_Color;
void main() {
o_Color = v_Color;
}
"
};
struct Renderer<C : device::draw::CommandBuffer, D: gfx::Device<C>> {
graphics: gfx::Graphics<... | date_movement(& | identifier_name | |
piston.rs | v_Color;
uniform mat4 u_Projection;
uniform mat4 u_View;
uniform mat4 u_Model;
uniform vec4 u_Color;
uniform vec3 u_LightDirection;
void main() {
vec3 normal = normalize(vec3(u_Model * vec4(a_Normal, 0.0)));
float dot = max(dot(normal, u_LightDirection), 0.0);
v_Color ... | pub fn finish_immediately(&mut self) {
self.current = self.destination.clone();
}
}
pub struct PistonUI {
renderer : Renderer<GlCommandBuffer, GlDevice>,
render_controller : RenderController,
input_controller: InputController,
}
pub struct RenderController {
player_pos: Position,
c... | self.destination = dest;
}
| identifier_body |
piston.rs | | {
vertex_data.push(v);
});
for o in obj.object_iter() {
for g in o.group_iter() {
for i in g.indices().iter() {
match i {
&genmesh::PolyTri(poly) => {
for i in vec!(poly.x, poly.y, poly.z)... | conditional_block | ||
context.rs | (&self) -> &Context {
self.0.as_ref()
}
}
impl std::borrow::Borrow<Context> for CtxRef {
fn borrow(&self) -> &Context {
self.0.borrow()
}
}
impl std::cmp::PartialEq for CtxRef {
fn eq(&self, other: &CtxRef) -> bool {
Arc::ptr_eq(&self.0, &other.0)
}
}
impl Default for CtxR... | as_ref | identifier_name | |
context.rs | }
impl Default for CtxRef {
fn default() -> Self {
Self(Arc::new(Context {
// Start with painting an extra frame to compensate for some widgets
// that take two frames before they "settle":
repaint_requests: AtomicU32::new(1),
..Context::default()
}))
... | random_line_split | ||
context.rs |
}
impl std::borrow::Borrow<Context> for CtxRef {
fn borrow(&self) -> &Context {
self.0.borrow()
}
}
impl std::cmp::PartialEq for CtxRef {
fn eq(&self, other: &CtxRef) -> bool {
Arc::ptr_eq(&self.0, &other.0)
}
}
impl Default for CtxRef {
fn default() -> Self {
Self(Arc::n... | {
self.0.as_ref()
} | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.