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 |
|---|---|---|---|---|
row.rs | //! This module contains definition of table rows stuff
use std::io::{Error, Write};
use std::iter::FromIterator;
use std::slice::{Iter, IterMut};
// use std::vec::IntoIter;
use std::ops::{Index, IndexMut};
use super::Terminal;
use super::format::{ColumnPosition, TableFormat};
use super::utils::NEWLINE;
use super::Ce... |
}
impl Default for Row {
fn default() -> Row {
Row::empty()
}
}
impl Index<usize> for Row {
type Output = Cell;
fn index(&self, idx: usize) -> &Self::Output {
&self.cells[idx]
}
}
impl IndexMut<usize> for Row {
fn index_mut(&mut self, idx: usize) -> &mut Self::Output {
... | {
let mut printed_columns = 0;
for cell in self.iter() {
printed_columns += cell.print_html(out)?;
}
// Pad with empty cells, if target width is not reached
for _ in 0..col_num - printed_columns {
Cell::default().print_html(out)?;
}
Ok(())
... | identifier_body |
row.rs | //! This module contains definition of table rows stuff
use std::io::{Error, Write};
use std::iter::FromIterator;
use std::slice::{Iter, IterMut};
// use std::vec::IntoIter;
use std::ops::{Index, IndexMut};
use super::Terminal;
use super::format::{ColumnPosition, TableFormat};
use super::utils::NEWLINE;
use super::Ce... | (&self) -> Iter<Cell> {
self.cells.iter()
}
/// Returns an mutable iterator over cells
pub fn iter_mut(&mut self) -> IterMut<Cell> {
self.cells.iter_mut()
}
/// Internal only
fn __print<T: Write +?Sized, F>(
&self,
out: &mut T,
format: &TableFormat,
... | iter | identifier_name |
row.rs | //! This module contains definition of table rows stuff
use std::io::{Error, Write};
use std::iter::FromIterator;
use std::slice::{Iter, IterMut};
// use std::vec::IntoIter;
use std::ops::{Index, IndexMut};
use super::Terminal;
use super::format::{ColumnPosition, TableFormat};
use super::utils::NEWLINE;
use super::Ce... | pub(crate) fn get_column_width(&self, column: usize, format: &TableFormat) -> usize {
let mut i = 0;
for c in &self.cells {
if i + c.get_hspan() > column {
if c.get_hspan() == 1 {
return c.get_width();
}
let (lp, rp) = f... | /// Get the minimum width required by the cell in the column `column`.
/// Return 0 if the cell does not exist in this row
// #[deprecated(since="0.8.0", note="Will become private in future release. See [issue #87](https://github.com/phsym/prettytable-rs/issues/87)")] | random_line_split |
codegen.rs | use grammar::{Grammar, NontermName, Rule, Sym, TermName};
pub fn codegen<B:BackendText>(back: &mut B) -> String where
// IMO these should not be necessary, see Rust issue #29143
B::Block: RenderIndent
{
let mut s = String::new();
s = s + &back.prefix();
let indent = back.rule_indent_preference();
... | / Given alpha = x1 x2.. x_f, shorthand for
///
/// code(x1 .. x_f, j, A)
/// code( x2.. x_f, j, A)
/// ...
/// code( x_f, j, A)
///
/// Each `code` maps to a command and (potentially) a trailing label;
/// therefore concatenating the codes results in a leading command
... | // FIXME: the infrastructure should be revised to allow me to
// inline a sequence of terminals (since they do not need to
// be encoded into separate labelled blocks).
assert!(alpha.len() > 0);
let (s_0, alpha) = alpha.split_at(1);
match s_0[0] {
Sym::T(t) =>
... | identifier_body |
codegen.rs | use grammar::{Grammar, NontermName, Rule, Sym, TermName};
pub fn codegen<B:BackendText>(back: &mut B) -> String where
// IMO these should not be necessary, see Rust issue #29143
B::Block: RenderIndent
{
let mut s = String::new();
s = s + &back.prefix();
let indent = back.rule_indent_preference();
... | f, a: TermName) -> C::Command {
let b = &self.backend;
let matches = b.curr_matches_term(a);
let next_j = b.increment_curr();
let goto_l0 = b.goto_l0();
b.if_else(matches, next_j, goto_l0)
}
/// code(A_kα, j, X) =
/// if test(I[j], X, A_k α) {
/// c_u := c... | rm(&sel | identifier_name |
codegen.rs | use grammar::{Grammar, NontermName, Rule, Sym, TermName};
pub fn codegen<B:BackendText>(back: &mut B) -> String where
// IMO these should not be necessary, see Rust issue #29143
B::Block: RenderIndent
{
let mut s = String::new();
s = s + &back.prefix();
let indent = back.rule_indent_preference();
... | let l_a_i = b.alternate_label((a, i));
let add_l_a_i = b.add(l_a_i);
let c2 = b.if_(test, add_l_a_i);
c = b.seq(c, c2);
}
let goto_l0 = b.goto_l0();
c = b.seq(c, goto_l0);
c
};
// each call t... | let mut c = b.no_op();
for (i, alpha) in alphas.iter().enumerate() {
let test = b.test(a, (None, alpha)); | random_line_split |
mod.rs | use std::{
convert::TryInto,
io::SeekFrom,
mem::size_of,
path::{Path, PathBuf},
};
use bincode::{deserialize, serialize_into, serialized_size};
use cfg_if::cfg_if;
use once_cell::sync::OnceCell;
use serde::{de::DeserializeOwned, Serialize};
use tokio::{
fs::{create_dir, remove_file, OpenOptions},
... |
/// Append single event to `source` log file (usually queue name)
pub async fn persist_event<P>(
&self,
event: &Event<'_>,
source: P,
) -> Result<(), PersistenceError>
where
P: AsRef<Path>,
{
self.append(event, source.as_ref().join(QUEUE_FILE)).await
}
... | {
let path = self.config.path.join(source);
debug!("Loading from {}", path.display());
let mut file = OpenOptions::new()
.read(true)
.open(path)
.await
.map_err(PersistenceError::from)?;
Self::parse_log(&mut file).await
} | identifier_body |
mod.rs | use std::{
convert::TryInto,
io::SeekFrom,
mem::size_of,
path::{Path, PathBuf},
};
use bincode::{deserialize, serialize_into, serialized_size};
use cfg_if::cfg_if;
use once_cell::sync::OnceCell;
use serde::{de::DeserializeOwned, Serialize};
use tokio::{
fs::{create_dir, remove_file, OpenOptions},
... | () {
let mut entries = Vec::new();
entries.append(&mut Log::make_log_entry(&vec![1u32, 2, 3]).unwrap());
entries.append(&mut Log::make_log_entry(&vec![4, 5, 6]).unwrap());
entries.append(&mut Log::make_log_entry(&vec![7, 8, 9]).unwrap());
let parsed = Log::parse_log::<Vec<u32>, _... | test_multiple_log_entries | identifier_name |
mod.rs | use std::{
convert::TryInto,
io::SeekFrom,
mem::size_of,
path::{Path, PathBuf},
};
use bincode::{deserialize, serialize_into, serialized_size};
use cfg_if::cfg_if;
use once_cell::sync::OnceCell;
use serde::{de::DeserializeOwned, Serialize};
use tokio::{
fs::{create_dir, remove_file, OpenOptions},
... | debug!("Log entry size: {}", size);
buf.reserve(size.try_into().map_err(PersistenceError::LogEntryTooBig)?);
source
.take(size)
.read_buf(&mut buf)
.await
.map_err(PersistenceError::from)?;
entries.push(deseri... | {
let size = source.read_u64_le().await.map_err(PersistenceError::from)?;
| random_line_split |
critical_cliques.rs | cliques.push(clique);
}
let mut crit_graph = Graph::new(cliques.len());
for c1 in 0..cliques.len() {
for c2 in 0..cliques.len() {
if c1 == c2 {
continue;
}
if should_be_neighbors(g, &cliques[c1], &cliques[c2]) {
crit_grap... | {
// This is the example from "Guo: A more effective linear kernelization for cluster
// editing, 2009", Fig. 1
let mut graph = Graph::new(9);
graph.set(0, 1, Weight::ONE);
graph.set(0, 2, Weight::ONE);
graph.set(1, 2, Weight::ONE);
graph.set(2, 3, Weight::ONE);
... | identifier_body | |
critical_cliques.rs | in (u + 1)..self.graph.size() {
if self.graph.get(u, v) > Weight::ZERO {
pg.add_edge(NodeIndex::new(u), NodeIndex::new(v), 0);
}
}
}
pg
}
}
pub fn build_crit_clique_graph(g: &Graph<Weight>) -> CritCliqueGraph {
let mut cliques = ... |
visited[u] = true;
let mut clique = CritClique::default();
clique.vertices.push(u);
for v in g.nodes() {
if visited[v] {
continue;
}
// TODO: Is it maybe worth storing neighbor sets instead of recomputing them?
if g.clo... | {
continue;
} | conditional_block |
critical_cliques.rs | (&self) -> petgraph::Graph<String, u8, petgraph::Undirected, u32> {
use petgraph::prelude::NodeIndex;
let mut pg = petgraph::Graph::with_capacity(self.graph.size(), 0);
for u in 0..self.graph.size() {
pg.add_node(
self.cliques[u]
.vertices
... | to_petgraph | identifier_name | |
critical_cliques.rs | v in (u + 1)..self.graph.size() {
if self.graph.get(u, v) > Weight::ZERO {
pg.add_edge(NodeIndex::new(u), NodeIndex::new(v), 0);
}
}
}
pg
}
}
pub fn build_crit_clique_graph(g: &Graph<Weight>) -> CritCliqueGraph {
let mut cliques ... | // Now mark the clique and its neighbors as "removed" from the graph, so future reduction and
// algorithm steps ignore it. (It is now a disjoint clique, i.e. already done.)
for &u in clique_neighbors {
g.set_present(u, false);
}
for &u in &clique.vertices {
g.set_present(u, false);
... | *k -= *uv;
Edit::delete(edits, &imap, u, v);
*uv = f32::NEG_INFINITY;
}
| random_line_split |
config_diff.rs | use std::num::NonZeroU32;
use merge::Merge;
use schemars::JsonSchema;
use segment::types::{HnswConfig, ProductQuantization, ScalarQuantization};
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use validator::{Validate, ValidationErrors};
use crate::config::{CollectionParam... |
}
#[derive(
Debug,
Default,
Deserialize,
Serialize,
JsonSchema,
Validate,
Copy,
Clone,
PartialEq,
Eq,
Merge,
Hash,
)]
#[serde(rename_all = "snake_case")]
pub struct HnswConfigDiff {
/// Number of edges per node in the index graph. Larger the value - more accurate th... | {
from_full(full)
} | identifier_body |
config_diff.rs | use std::num::NonZeroU32;
use merge::Merge;
use schemars::JsonSchema;
use segment::types::{HnswConfig, ProductQuantization, ScalarQuantization};
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use validator::{Validate, ValidationErrors};
use crate::config::{CollectionParam... | /// result: {"a": 1, "b": 2}
fn merge_level_0(base: &mut Value, diff: Value) {
match (base, diff) {
(base @ &mut Value::Object(_), Value::Object(diff)) => {
let base = base.as_object_mut().unwrap();
for (k, v) in diff {
if!v.is_null() {
base.insert... | /// diff: {"a": null} | random_line_split |
config_diff.rs | use std::num::NonZeroU32;
use merge::Merge;
use schemars::JsonSchema;
use segment::types::{HnswConfig, ProductQuantization, ScalarQuantization};
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use validator::{Validate, ValidationErrors};
use crate::config::{CollectionParam... | () -> Self {
QuantizationConfigDiff::Disabled(Disabled::Disabled)
}
}
impl Validate for QuantizationConfigDiff {
fn validate(&self) -> Result<(), ValidationErrors> {
match self {
QuantizationConfigDiff::Scalar(scalar) => scalar.validate(),
QuantizationConfigDiff::Product... | new_disabled | identifier_name |
runtime.rs | last_changed_revision(&self, d: Durability) -> Revision {
self.shared_state.revisions[d.index()].load()
}
/// Read current value of the revision counter.
#[inline]
pub(crate) fn pending_revision(&self) -> Revision {
self.shared_state.pending_revision.load()
}
#[cold]
pub(c... | }
} | random_line_split | |
runtime.rs | Runtime {
id: RuntimeId { counter: 0 },
revision_guard: None,
shared_state: Default::default(),
local_state: Default::default(),
}
}
}
impl std::fmt::Debug for Runtime {
fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
... | (&self) {
self.local_state
.report_untracked_read(self.current_revision());
}
/// Acts as though the current query had read an input with the given durability; this will force the current query's durability to be at most `durability`.
///
/// This is mostly useful to control the dura... | report_untracked_read | identifier_name |
runtime.rs | Runtime {
id: RuntimeId { counter: 0 },
revision_guard: None,
shared_state: Default::default(),
local_state: Default::default(),
}
}
}
impl std::fmt::Debug for Runtime {
fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
... |
}
pub(crate) fn permits_increment(&self) -> bool {
self.revision_guard.is_none() &&!self.local_state.query_in_progress()
}
#[inline]
pub(crate) fn push_query(&self, database_key_index: DatabaseKeyIndex) -> ActiveQueryGuard<'_> {
self.local_state.push_query(database_key_index)
... | {
for rev in &self.shared_state.revisions[1..=d.index()] {
rev.store(new_revision);
}
} | conditional_block |
runtime.rs | Runtime {
id: RuntimeId { counter: 0 },
revision_guard: None,
shared_state: Default::default(),
local_state: Default::default(),
}
}
}
impl std::fmt::Debug for Runtime {
fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
... |
/// Reports that the query depends on some state unknown to salsa.
///
/// Queries which report untracked reads will be re-executed in the next
/// revision.
pub fn report_untracked_read(&self) {
self.local_state
.report_untracked_read(self.current_revision());
}
/// Ac... | {
self.local_state
.report_query_read_and_unwind_if_cycle_resulted(input, durability, changed_at);
} | identifier_body |
scanner.rs | use crate::file::{FileContent, FileSet};
use crate::metadata::Metadata;
use std::cell::RefCell;
use std::cmp;
use std::collections::btree_map::Entry as BTreeEntry;
use std::collections::hash_map::Entry as HashEntry;
use std::collections::BTreeMap;
use std::collections::BinaryHeap;
use std::collections::HashMap;
use std... | self.stats.added += 1;
if let Some(fileset) = self.new_fileset(&path, metadata) {
self.dedupe_by_content(fileset, path, metadata)?;
} else {
self.stats.hardlinks += 1;
self.stats.bytes_saved_by_hardlinks += metadata.size() as usize;
}
Ok(())
... | random_line_split | |
scanner.rs | use crate::file::{FileContent, FileSet};
use crate::metadata::Metadata;
use std::cell::RefCell;
use std::cmp;
use std::collections::btree_map::Entry as BTreeEntry;
use std::collections::hash_map::Entry as HashEntry;
use std::collections::BTreeMap;
use std::collections::BinaryHeap;
use std::collections::HashMap;
use std... | ,
HashEntry::Occupied(mut e) => {
// This case may require a deferred deduping later,
// if the new link belongs to an old fileset that has already been deduped.
let mut t = e.get_mut().borrow_mut();
t.push(path);
None
... | {
let fileset = Rc::new(RefCell::new(FileSet::new(path, metadata.nlink())));
e.insert(Rc::clone(&fileset)); // clone just bumps a refcount here
Some(fileset)
} | conditional_block |
scanner.rs | use crate::file::{FileContent, FileSet};
use crate::metadata::Metadata;
use std::cell::RefCell;
use std::cmp;
use std::collections::btree_map::Entry as BTreeEntry;
use std::collections::hash_map::Entry as HashEntry;
use std::collections::BTreeMap;
use std::collections::BinaryHeap;
use std::collections::HashMap;
use std... | Ok(())
}
fn add(&mut self, path: Box<Path>, metadata: &fs::Metadata) -> io::Result<()> {
self.scan_listener.file_scanned(&path, &self.stats);
let ty = metadata.file_type();
if ty.is_dir() {
// Inode is truncated to group scanning of roughly close inodes together,
... | {
// Errors are ignored here, since it's super common to find permission denied and unreadable symlinks,
// and it'd be annoying if that aborted the whole operation.
// FIXME: store the errors somehow to report them in a controlled manner
for entry in fs::read_dir(path)?.filter_map(|p| p... | identifier_body |
scanner.rs | use crate::file::{FileContent, FileSet};
use crate::metadata::Metadata;
use std::cell::RefCell;
use std::cmp;
use std::collections::btree_map::Entry as BTreeEntry;
use std::collections::hash_map::Entry as HashEntry;
use std::collections::BTreeMap;
use std::collections::BinaryHeap;
use std::collections::HashMap;
use std... | (&mut self, fileset: RcFileSet, path: Box<Path>, metadata: &fs::Metadata) -> io::Result<()> {
let mut deferred = false;
match self.by_content.entry(FileContent::new(path, Metadata::new(metadata))) {
BTreeEntry::Vacant(e) => {
// Seems unique so far
e.insert(ve... | dedupe_by_content | identifier_name |
server.rs | extern crate hashbrown;
extern crate rand;
use crate::command;
use self::ServerError::*;
use command::{Command, CommandHandler};
use hashbrown::HashMap;
use rand::Rng;
use std::convert::TryFrom;
use std::fmt;
use std::io;
use std::io::prelude::*;
use std::net::TcpListener;
use std::net::TcpStream;
use std::sync::m... | (&self) -> Vec<usize> {
use self::FinishedStatus::*;
use self::HandlerAsync::*;
self.handlers
.iter()
.filter(|(id, handler)| {
if let Finished(status) = handler.check_status() {
match status {
TimedOut => {
... | check_handlers | identifier_name |
server.rs | extern crate hashbrown;
extern crate rand;
use crate::command;
use self::ServerError::*;
use command::{Command, CommandHandler};
use hashbrown::HashMap;
use rand::Rng;
use std::convert::TryFrom;
use std::fmt;
use std::io;
use std::io::prelude::*;
use std::net::TcpListener;
use std::net::TcpStream;
use std::sync::m... | msg_sender,
msg_recver,
handlers,
cmd_handler,
})
}
#[allow(unused)]
pub fn from_cfg() -> Result<Server, &'static str> {
unimplemented!();
}
pub fn cmd<C: Command +'static>(mut self, name: &'static str, command: C) -> Self {
l... | Ok(Server {
size, | random_line_split |
main.rs |
format: wgpu::VertexFormat::Float4,
},
wgpu::VertexAttributeDescriptor {
offset: mem::size_of::<[f32; 8]>() as wgpu::BufferAddress,
shader_location: 7,
format: wgpu::VertexFormat::Float4,
},
wgpu::VertexAttr... | (
device: &wgpu::Device,
layout: &wgpu::PipelineLayout,
color_format: wgpu::TextureFormat,
depth_format: Option<wgpu::TextureFormat>,
vertex_descs: &[wgpu::VertexBufferDescriptor],
vs_src: wgpu::ShaderModuleSource,
fs_src: wgpu::ShaderModuleSource,
) -> wgpu::RenderPipeline {
// Create S... | create_render_pipeline | identifier_name |
main.rs | swap_chain: wgpu::SwapChain,
render_pipeline: wgpu::RenderPipeline,
obj_model: model::Model,
camera: camera::Camera,
camera_controller: camera::CameraController,
projection: camera::Projection,
uniforms: Uniforms,
uniform_buffer: wgpu::Buffer,
uniform_bind_group: wgpu::BindGroup,
in... | state.resize(physical_size)
},
WindowEvent::ScaleFactorChanged {new_inner_size, ../*scale_factor*/ } => {
state.resize(*new_inner_size)
}, | random_line_split | |
main.rs |
format: wgpu::VertexFormat::Float4,
},
wgpu::VertexAttributeDescriptor {
offset: mem::size_of::<[f32; 8]>() as wgpu::BufferAddress,
shader_location: 7,
format: wgpu::VertexFormat::Float4,
},
wgpu::VertexAttr... |
DeviceEvent::Button {
button: 1, // Left Mouse Button
state,
} => {
self.mouse_pressed = *state == ElementState::Pressed;
true
}
DeviceEvent::MouseMotion { delta } => {
if self.mouse_pressed ... | {
self.camera_controller.process_scroll(delta);
true
} | conditional_block |
lib.rs | #![recursion_limit = "256"]
extern crate proc_macro;
use proc_macro::TokenStream;
use proc_macro2;
use quote::quote;
use regex::Regex;
use std::collections::HashSet;
use syn::{parse_macro_input, DeriveInput};
#[derive(Debug, PartialEq)]
enum RouteToRegexError {
MissingLeadingForwardSlash,
NonAsciiChars,
InvalidIde... | st_route_to_regex_characters_after_wildcard() {
let regex = route_to_regex("/p/:project_id/exams/:exam*ID/submissions_expired");
assert_eq!(
regex,
Err(RouteToRegexError::CharactersAfterWildcard)
);
}
#[test]
fn test_route_to_regex_invalid_ending() {
let regex = route_to_regex("/p/:project_id/exams/:exam_id/su... | route_to_regex("/p/:project_id/exams/:_exam_id/submissions_expired");
assert_eq!(
regex,
Err(RouteToRegexError::InvalidIdentifier("_exam_id".to_string()))
);
}
#[test]
fn te | identifier_body |
lib.rs | #![recursion_limit = "256"]
extern crate proc_macro;
use proc_macro::TokenStream;
use proc_macro2;
use quote::quote;
use regex::Regex;
use std::collections::HashSet;
use syn::{parse_macro_input, DeriveInput};
#[derive(Debug, PartialEq)]
enum RouteToRegexError {
MissingLeadingForwardSlash,
NonAsciiChars,
InvalidIde... | }
query_string
});
Ok(#struct_constructor)
}
}
};
let impl_wrapper = syn::Ident::new(
&format!("_IMPL_APPROUTE_FOR_{}", name.to_string()),
proc_macro2::Span::call_site(),
);
let out = quote! {
const #impl_wrapper: () = {
extern crate app_route;
#app_route_impl
};
};
out.i... |
if query_string.starts_with('?') {
query_string = &query_string[1..]; | random_line_split |
lib.rs | #![recursion_limit = "256"]
extern crate proc_macro;
use proc_macro::TokenStream;
use proc_macro2;
use quote::quote;
use regex::Regex;
use std::collections::HashSet;
use syn::{parse_macro_input, DeriveInput};
#[derive(Debug, PartialEq)]
enum RouteToRegexError {
MissingLeadingForwardSlash,
NonAsciiChars,
InvalidIde... | ta) -> Vec<syn::Field> {
match data {
syn::Data::Struct(data_struct) => match data_struct.fields {
syn::Fields::Named(ref named_fields) => named_fields.named.iter().cloned().collect(),
_ => panic!("Struct fields must be named"),
},
_ => panic!("AppRoute derive is only supported for structs"),
}
}
fn fiel... | ds(data: &syn::Da | identifier_name |
lib.rs | #![recursion_limit = "256"]
extern crate proc_macro;
use proc_macro::TokenStream;
use proc_macro2;
use quote::quote;
use regex::Regex;
use std::collections::HashSet;
use syn::{parse_macro_input, DeriveInput};
#[derive(Debug, PartialEq)]
enum RouteToRegexError {
MissingLeadingForwardSlash,
NonAsciiChars,
InvalidIde... |
regex += &format!("(?P<{}>[^/]+)/", name);
format_str += &format!("{}}}/", name);
parse_state = ParseState::Static;
} else if byte == '*' {
// Found a wildcard - add the var name to the regex
// Validate 'name' as a Rust identifier
if!ident_regex.is_match(&name) {
return Err(R... | {
return Err(RouteToRegexError::InvalidIdentifier(name));
} | conditional_block |
partition.rs | use arrow_deps::{
arrow::record_batch::RecordBatch, datafusion::logical_plan::Expr,
datafusion::logical_plan::Operator, datafusion::optimizer::utils::expr_to_column_names,
datafusion::scalar::ScalarValue,
};
use generated_types::wal as wb;
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use wa... |
Expr::BinaryExpr { op,.. } => {
match op {
Operator::Eq
| Operator::Lt
| Operator::LtEq
| Operator::Gt
| Operator::GtEq
| Operator::Plus
| Operator::Mi... | {} | conditional_block |
partition.rs | use arrow_deps::{
arrow::record_batch::RecordBatch, datafusion::logical_plan::Expr,
datafusion::logical_plan::Operator, datafusion::optimizer::utils::expr_to_column_names,
datafusion::scalar::ScalarValue,
};
use generated_types::wal as wb;
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use wa... |
/// Return true if this column is the time column
pub fn is_time_column(&self, id: u32) -> bool {
self.time_column_id == id
}
/// Creates a DataFusion predicate for appliying a timestamp range:
///
/// range.start <= time and time < range.end`
fn make_timestamp_predicate_expr(&sel... | {
match &self.field_restriction {
None => true,
Some(field_restriction) => field_restriction.contains(&field_id),
}
} | identifier_body |
partition.rs | use arrow_deps::{
arrow::record_batch::RecordBatch, datafusion::logical_plan::Expr,
datafusion::logical_plan::Operator, datafusion::optimizer::utils::expr_to_column_names,
datafusion::scalar::ScalarValue,
};
use generated_types::wal as wb;
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use wa... | /// of this dictionary. If there are no matching Strings in the
/// partitions dictionary, those strings are ignored and a
/// (potentially empty) set is returned.
fn compile_string_list(&self, names: Option<&BTreeSet<String>>) -> Option<BTreeSet<u32>> {
names.map(|names| {
names
... | range,
})
}
/// Converts a potential set of strings into a set of ids in terms | random_line_split |
partition.rs | use arrow_deps::{
arrow::record_batch::RecordBatch, datafusion::logical_plan::Expr,
datafusion::logical_plan::Operator, datafusion::optimizer::utils::expr_to_column_names,
datafusion::scalar::ScalarValue,
};
use generated_types::wal as wb;
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use wa... | {
/// At least one of the strings was not present in the partitions'
/// dictionary.
///
/// This is important when testing for the presence of all ids in
/// a set, as we know they can not all be present
AtLeastOneMissing,
/// All strings existed in this partition's dictionary
Present... | PartitionIdSet | identifier_name |
mod.rs |
ToTaskNum(usize),
AllHistory,
}
impl From<&usize> for ResponseType {
fn from(u: &usize) -> Self {
ResponseType::ToTaskNum(*u)
}
}
// :shrug:
impl From<&ResponseType> for ResponseType {
fn from(r: &ResponseType) -> Self {
*r
}
}
/// Given identifiers for a workflow/run, and a t... | num_expected_fails,
mock_gateway: MockServerGatewayApis::new(),
expect_fail_wft_matcher: Box::new(|_, _, _| true),
}
}
pub fn from_resp_batches(
wf_id: &str,
t: TestHistoryBuilder,
resps: impl IntoIterator<Item = impl Into<ResponseType>>,
... | num_expected_fails: Option<usize>,
) -> Self {
Self {
hists,
enforce_correct_number_of_polls, | random_line_split |
mod.rs | ToTaskNum(usize),
AllHistory,
}
impl From<&usize> for ResponseType {
fn from(u: &usize) -> Self {
ResponseType::ToTaskNum(*u)
}
}
// :shrug:
impl From<&ResponseType> for ResponseType {
fn from(r: &ResponseType) -> Self {
*r
}
}
/// Given identifiers for a workflow/run, and a tes... | else {
Some(Err(tonic::Status::out_of_range(
"Ran out of mock responses!",
)))
}
});
Box::new(mock_poller) as BoxedPoller<T>
}
pub fn mock_poller<T>() -> MockPoller<T>
where
T: Send + Sync +'static,
{
let mut mock_poller = MockPoller::new();
mock_pol... | {
Some(Ok(t))
} | conditional_block |
mod.rs | ToTaskNum(usize),
AllHistory,
}
impl From<&usize> for ResponseType {
fn from(u: &usize) -> Self {
ResponseType::ToTaskNum(*u)
}
}
// :shrug:
impl From<&ResponseType> for ResponseType {
fn from(r: &ResponseType) -> Self {
*r
}
}
/// Given identifiers for a workflow/run, and a tes... | (mut cfg: MockPollCfg) -> MocksHolder<MockServerGatewayApis> {
// Maps task queues to maps of wfid -> responses
let mut task_queues_to_resps: HashMap<String, BTreeMap<String, VecDeque<_>>> = HashMap::new();
let outstanding_wf_task_tokens = Arc::new(RwLock::new(BiMap::new()));
let mut correct_num_polls =... | build_mock_pollers | identifier_name |
mod.rs | ToTaskNum(usize),
AllHistory,
}
impl From<&usize> for ResponseType {
fn from(u: &usize) -> Self {
ResponseType::ToTaskNum(*u)
}
}
// :shrug:
impl From<&ResponseType> for ResponseType {
fn from(r: &ResponseType) -> Self {
*r
}
}
/// Given identifiers for a workflow/run, and a tes... | let mut res = core.poll_workflow_activation(TEST_Q).await.unwrap();
let contains_eviction = res.eviction_index();
if let Some(eviction_job_ix) = contains_eviction {
// If the job list has an eviction, make sure it was the last item in the list
// then... | {
let mut evictions = 0;
let expected_evictions = expect_and_reply.len() - 1;
let mut executed_failures = HashSet::new();
let expected_fail_count = expect_and_reply
.iter()
.filter(|(_, reply)| !reply.is_success())
.count();
'outer: loop {
let expect_iter = expect_an... | identifier_body |
main.rs | #[macro_use] extern crate clap;
extern crate curl;
extern crate formdata;
extern crate hex;
extern crate hmac;
extern crate hyper;
#[macro_use] extern crate log;
extern crate pipe;
extern crate rand;
extern crate sha_1;
#[macro_use] extern crate serde_json;
#[macro_use] extern crate serde_derive;
extern crate stderrlog... | use std::io::{BufReader, BufWriter, Read};
use std::str;
use std::thread::spawn;
use url::Url;
use curl::easy::{Easy, List};
const FORM_MAX_FILE_SIZE: u64 = 1099511627776;
const FORM_MAX_FILE_COUNT: usize = 1048576;
const FORM_EXPIRES: u64 = 4102444800;
#[derive(Debug)]
struct OpenStackConfig {
auth_url: String,
... | use std::fs::File;
use std::path::Path; | random_line_split |
main.rs | #[macro_use] extern crate clap;
extern crate curl;
extern crate formdata;
extern crate hex;
extern crate hmac;
extern crate hyper;
#[macro_use] extern crate log;
extern crate pipe;
extern crate rand;
extern crate sha_1;
#[macro_use] extern crate serde_json;
#[macro_use] extern crate serde_derive;
extern crate stderrlog... | {
url: String,
redirect: String,
max_file_size: u64,
max_file_count: usize,
expires: u64,
signature: String
}
#[derive(Debug)]
struct MissingToken;
impl fmt::Display for MissingToken {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Token not found in Keystone response headers")
... | FormTemplate | identifier_name |
interpolation.rs | /*
* Copyright 2018 The Starlark in Rust Authors.
* Copyright (c) Facebook, Inc. and its affiliates.
*
* 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
*
* https://www.apache.org/lic... |
NamedOrPositional::Named(..) => {
result.named_count += 1;
}
}
result
.parameters
.push((named_or_positional, format, String::new()));
}
}
Ok(result)
}
... | {
result.positional_count += 1;
} | conditional_block |
interpolation.rs | /*
* Copyright 2018 The Starlark in Rust Authors.
* Copyright (c) Facebook, Inc. and its affiliates.
*
* 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
*
* https://www.apache.org/lic... | {
Named(String),
Positional,
}
/// Implement Python `%` format strings.
pub struct Interpolation {
/// String before first parameter
init: String,
/// Number of positional arguments
positional_count: usize,
/// Number of named arguments
named_count: usize,
/// Arguments followed by... | NamedOrPositional | identifier_name |
interpolation.rs | /*
* Copyright 2018 The Starlark in Rust Authors.
* Copyright (c) Facebook, Inc. and its affiliates.
*
* 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
*
* https://www.apache.org/lic... | box owned_tuple.iter()
}
None => box iter::once(argument),
}
};
for (named_or_positional, format, tail) in self.parameters {
let arg = match named_or_positional {
NamedOrPositional::Positional... | random_line_split | |
interpolation.rs | /*
* Copyright 2018 The Starlark in Rust Authors.
* Copyright (c) Facebook, Inc. and its affiliates.
*
* 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
*
* https://www.apache.org/lic... | return Err(
StringInterpolationError::UnexpectedEOFClosingParen.into()
);
}
Some(')') => {
break;
}
... | {
let mut result = Self {
init: String::new(),
positional_count: 0,
named_count: 0,
parameters: Vec::new(),
};
let mut chars = format.chars();
while let Some(c) = chars.next() {
if c != '%' {
result.append_litera... | identifier_body |
loading.rs | extern crate quicksilver;
extern crate json;
use quicksilver::prelude::*;
use std::collections::HashMap;
use itertools::Itertools;
use std::iter;
use crate::game_logic::{BoardState};
use crate::game_control::*;
use crate::game_objects::*;
use crate::ai::AI;
use crate::automaton::{AutomatonState, GameEvent};
use std::m... | (json: &serde_json::value::Value, node_name: &str, card_factory: &CardFactory) -> Deck {
let deck_node = {
json.get(node_name)
.expect(format!("Deck node \"{}\" not found", node_name).as_str())
.clone()
};
let data: HashMap<String, usize> = serde_json::from_value(deck_node)
... | parse_deck | identifier_name |
loading.rs | extern crate quicksilver;
extern crate json;
use quicksilver::prelude::*;
use std::collections::HashMap;
use itertools::Itertools;
use std::iter;
use crate::game_logic::{BoardState};
use crate::game_control::*;
use crate::game_objects::*;
use crate::ai::AI;
use crate::automaton::{AutomatonState, GameEvent};
use std::m... |
match game_type.to_lowercase().as_str() {
"vs" => {
assert_eq!(players.len(), 2, "For VS game, only 2 players are possible");
players[0].opponent_idx = 1;
players[1].opponent_idx = 0;
},
_ => panic!("Unknown game type")
}
players
}
pub fn lo... | .expect("game type not specified")
.as_str()
.expect("game type not string"); | random_line_split |
loading.rs | extern crate quicksilver;
extern crate json;
use quicksilver::prelude::*;
use std::collections::HashMap;
use itertools::Itertools;
use std::iter;
use crate::game_logic::{BoardState};
use crate::game_control::*;
use crate::game_objects::*;
use crate::ai::AI;
use crate::automaton::{AutomatonState, GameEvent};
use std::m... | PlayerControl::Human => None,
PlayerControl::AI => Some(AI::new())
};
println!("Loading done");
BoardState {
player: player,
turn: 1,
hand: Box::new(hand),
deck: Box::new(draw_deck),
globals: NumberMap::new(),
stores: Box::new(vec!(build_stor... | {
let store_node = "build_store";
let trade_row = "kaiju_store";
let hand_size = 5;
let draw_deck = parse_deck(&json, &player.starting_deck, card_factory);
//let bs_node = { json.get("build_store").expect("build_store node not found").clone() };
let build_store = parse_store(BoardZone::BuildSt... | identifier_body |
episode.rs | use std::cmp;
use std::path::Path;
use std::u32;
use byteorder::{ByteOrder, BE};
use fst::{self, IntoStreamer, Streamer};
use crate::error::{Error, Result};
use crate::index::csv_file;
use crate::record::Episode;
use crate::util::{IMDB_EPISODE, fst_set_builder_file, fst_set_file};
/// The name of the episode index f... | Err(err) => bug!("episode id invalid UTF-8: {}", err),
Ok(tvshow_id) => tvshow_id,
};
let mut i = nul + 1;
let season = from_optional_u32(&bytes[i..]);
i += 4;
let epnum = from_optional_u32(&bytes[i..]);
i += 4;
let tvshow_id = match String::from_utf8(bytes[i..].to_vec()) ... | None => bug!("could not find nul byte"),
};
let id = match String::from_utf8(bytes[..nul].to_vec()) { | random_line_split |
episode.rs | use std::cmp;
use std::path::Path;
use std::u32;
use byteorder::{ByteOrder, BE};
use fst::{self, IntoStreamer, Streamer};
use crate::error::{Error, Result};
use crate::index::csv_file;
use crate::record::Episode;
use crate::util::{IMDB_EPISODE, fst_set_builder_file, fst_set_file};
/// The name of the episode index f... |
}
| {
let ctx = TestContext::new("small");
let idx = Index::create(ctx.data_dir(), ctx.index_dir()).unwrap();
let ep = idx.episode(b"tt0701063").unwrap().unwrap();
assert_eq!(ep.tvshow_id, "tt0096697");
} | identifier_body |
episode.rs | use std::cmp;
use std::path::Path;
use std::u32;
use byteorder::{ByteOrder, BE};
use fst::{self, IntoStreamer, Streamer};
use crate::error::{Error, Result};
use crate::index::csv_file;
use crate::record::Episode;
use crate::util::{IMDB_EPISODE, fst_set_builder_file, fst_set_file};
/// The name of the episode index f... | (ep: &Episode) -> Result<u32> {
match ep.episode {
None => Ok(u32::MAX),
Some(x) => {
if x == u32::MAX {
bug!("unsupported episode number {} for {:?}", x, ep);
}
Ok(x)
}
}
}
fn u32_to_bytes(n: u32) -> [u8; 4] {
let mut buf = [0u8; ... | to_optional_epnum | identifier_name |
main.rs | extern crate docopt;
#[macro_use]
extern crate serde_derive;
use docopt::Docopt;
#[macro_use]
extern crate log;
use log::{Level, LevelFilter, Metadata, Record};
use std::collections::{HashMap, HashSet};
use std::fs::File;
use std::io::{BufRead, BufReader, Seek, SeekFrom};
use std::path::Path;
static MY_LOGGER: Simp... | (&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(
f,
"{} {} {:?}",
self.file_path.display(),
self.delimiter,
self.quote
)
}
}
fn parse_args<'a>(
path_arg: &'a String,
delimiter_arg: &'a String,
quote_arg: &'a S... | fmt | identifier_name |
main.rs | extern crate docopt;
#[macro_use]
extern crate serde_derive;
use docopt::Docopt;
#[macro_use]
extern crate log;
use log::{Level, LevelFilter, Metadata, Record};
use std::collections::{HashMap, HashSet};
use std::fs::File;
use std::io::{BufRead, BufReader, Seek, SeekFrom};
use std::path::Path;
static MY_LOGGER: Simp... |
}
struct CsvDesc<'a> {
file_path: &'a Path,
delimiter: char,
quote: Option<char>,
}
impl<'a> std::fmt::Display for CsvDesc<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(
f,
"{} {} {:?}",
self.file_path.display(),
... | {} | identifier_body |
main.rs | extern crate docopt;
#[macro_use]
extern crate serde_derive;
use docopt::Docopt;
#[macro_use]
extern crate log;
use log::{Level, LevelFilter, Metadata, Record};
use std::collections::{HashMap, HashSet};
use std::fs::File;
use std::io::{BufRead, BufReader, Seek, SeekFrom};
use std::path::Path;
static MY_LOGGER: Simp... | Err(e) => panic!("failed getting csv row #2: {}", e),
};
info!("comparing {}:", row_key);
info!("line #1: {:?}", row_1);
info!("line #2: {:?}", row_2);
for col in &cols_to_compare {
let col_index_1 = *csv_col_index_1.get(*col).unwrap();
let c... | let row_2 = match get_csv_row(&csv_desc_2, index_2) {
Ok(row) => row, | random_line_split |
verify.rs | use std::ffi::OsStr;
use std::fmt::Write as _;
use std::fs::File;
use std::path::{Path, PathBuf};
use crate::cache::caches::RegistrySuperCache;
use crate::cache::*;
use crate::remove::remove_file;
use flate2::read::GzDecoder;
use rayon::iter::*;
use tar::Archive;
use walkdir::WalkDir;
#[derive(Debug, Clone, PartialE... |
dir.push(&comp1_with_crate_ext); // bytes-0.4.12.crate
dir.into_iter().collect::<PathBuf>()
}
/// look into the.gz archive and get all the contained files+sizes
fn sizes_of_archive_files(path: &Path) -> Vec<FileWithSize> {
let tar_gz = File::open(path).unwrap();
// extract the tar
let tar = GzDe... | {
// for each directory, find the path to the corresponding .crate archive
// .cargo/registry/src/github.com-1ecc6299db9ec823/bytes-0.4.12
// corresponds to
// .cargo/registry/cache/github.com-1ecc6299db9ec823/bytes-0.4.12.crate
// reverse, and "pop" the front components
let mut dir = src_path.... | identifier_body |
verify.rs | use std::ffi::OsStr;
use std::fmt::Write as _;
use std::fs::File;
use std::path::{Path, PathBuf};
use crate::cache::caches::RegistrySuperCache;
use crate::cache::*;
use crate::remove::remove_file;
use flate2::read::GzDecoder;
use rayon::iter::*;
use tar::Archive;
use walkdir::WalkDir;
#[derive(Debug, Clone, PartialE... | diff.files_size_difference.push(FileSizeDifference {
path: fws.path.clone(),
size_archive: archive_file.size,
size_source: fws.size,
});
}
}
... | {
Some(fws) => {
if fws.size != archive_file.size { | random_line_split |
verify.rs | use std::ffi::OsStr;
use std::fmt::Write as _;
use std::fs::File;
use std::path::{Path, PathBuf};
use crate::cache::caches::RegistrySuperCache;
use crate::cache::*;
use crate::remove::remove_file;
use flate2::read::GzDecoder;
use rayon::iter::*;
use tar::Archive;
use walkdir::WalkDir;
#[derive(Debug, Clone, PartialE... |
None => unreachable!(), // we already checked this
};
}
}
let files_of_archive: Vec<&PathBuf> = files_of_archive.iter().map(|fws| &fws.path).collect();
for source_file in files_of_source_paths
.iter()
.filter(|path| path.file_name().unwrap()!= ".cargo-ok")
... | {
if fws.size != archive_file.size {
diff.files_size_difference.push(FileSizeDifference {
path: fws.path.clone(),
size_archive: archive_file.size,
size_source: fws.size,
... | conditional_block |
verify.rs | use std::ffi::OsStr;
use std::fmt::Write as _;
use std::fs::File;
use std::path::{Path, PathBuf};
use crate::cache::caches::RegistrySuperCache;
use crate::cache::*;
use crate::remove::remove_file;
use flate2::read::GzDecoder;
use rayon::iter::*;
use tar::Archive;
use walkdir::WalkDir;
#[derive(Debug, Clone, PartialE... | (src_path: &Path) -> PathBuf {
// for each directory, find the path to the corresponding.crate archive
//.cargo/registry/src/github.com-1ecc6299db9ec823/bytes-0.4.12
// corresponds to
//.cargo/registry/cache/github.com-1ecc6299db9ec823/bytes-0.4.12.crate
// reverse, and "pop" the front components
... | map_src_path_to_cache_path | identifier_name |
load.rs | : Instant,
}
impl MasterCommitCache {
/// Download the master-branch Rust commit list
pub async fn download() -> anyhow::Result<Self> {
let commits = collector::master_commits().await?;
Ok(Self {
commits,
updated: Instant::now(),
})
}
}
/// Site context obje... | let mut finished = 0;
while finished < unordered_queue.len() {
// The next level is those elements in the unordered queue which
// are ready to be benchmarked (i.e., those with parent in done or no
// parent).
let level_len = partition_in_place(unordered_queue[finished..].iter_mu... | // A topological sort, where each "level" is additionally altered such that
// try commits come first, and then sorted by PR # (as a rough heuristic for
// earlier requests).
| random_line_split |
load.rs | Instant,
}
impl MasterCommitCache {
/// Download the master-branch Rust commit list
pub async fn download() -> anyhow::Result<Self> {
let commits = collector::master_commits().await?;
Ok(Self {
commits,
updated: Instant::now(),
})
}
}
/// Site context objec... |
}
}
let mut already_tested = all_commits.clone();
let mut i = 0;
while i!= queue.len() {
if!already_tested.insert(queue[i].0.sha.clone()) {
queue.remove(i);
} else {
i += 1;
}
}
sort_queue(all_commits.clone(), queue)
}
fn sort_queue(
... | {
// do nothing, for now, though eventually we'll want an artifact queue
} | conditional_block |
load.rs | one is done, we will download the data twice, but that's it
match MasterCommitCache::download().await {
Ok(commits) => master_commits.store(Arc::new(commits)),
Err(e) => {
// couldn't get the data, keep serving cached results for now
... | {
assert_eq!(
parse_published_artifact_tag(
"static.rust-lang.org/dist/2022-08-15/channel-rust-beta.toml"
),
Some("beta-2022-08-15".to_string())
);
} | identifier_body | |
load.rs | {
pub sha: String,
pub parent_sha: String,
}
impl TryCommit {
pub fn sha(&self) -> &str {
self.sha.as_str()
}
pub fn comparison_url(&self) -> String {
format!(
"https://perf.rust-lang.org/compare.html?start={}&end={}",
self.parent_sha, self.sha
)
... | TryCommit | identifier_name | |
iso_spec.rs | //! This module contains implementation of specification, its segments and associated operations
//!
use std::collections::HashMap;
use std::fmt::{Display, Formatter};
use std::io::Cursor;
use crate::iso8583::{bitmap, IsoError};
use crate::iso8583::field::{Field, ParseError};
use crate::iso8583::yaml_de::YMessageSegme... |
impl Spec {
/// Returns a IsoMsg after parsing data or an ParseError on failure
pub fn parse(&'static self, data: &mut Vec<u8>) -> Result<IsoMsg, ParseError> {
let msg = self.get_msg_segment(data);
if msg.is_err() {
return Err(ParseError { msg: msg.err().unwrap().msg });
}
... | {
IsoMsg {
spec,
msg: seg,
fd_map: HashMap::new(),
bmp: Bitmap::new(0, 0, 0),
}
} | identifier_body |
iso_spec.rs | //! This module contains implementation of specification, its segments and associated operations
//!
use std::collections::HashMap;
use std::fmt::{Display, Formatter};
use std::io::Cursor;
use crate::iso8583::{bitmap, IsoError};
use crate::iso8583::field::{Field, ParseError};
use crate::iso8583::yaml_de::YMessageSegme... | }
/// Sets F64 or F128 based on algo, padding and key provided via cfg
pub fn set_mac(&mut self, cfg: &Config) -> Result<(), IsoError> {
if cfg.get_mac_algo().is_none() || cfg.get_mac_padding().is_none() || cfg.get_mac_key().is_none() {
return Err(IsoError { msg: format!("missing mac_al... | } | random_line_split |
iso_spec.rs | //! This module contains implementation of specification, its segments and associated operations
//!
use std::collections::HashMap;
use std::fmt::{Display, Formatter};
use std::io::Cursor;
use crate::iso8583::{bitmap, IsoError};
use crate::iso8583::field::{Field, ParseError};
use crate::iso8583::yaml_de::YMessageSegme... |
match generate_pin_block(&cfg.get_pin_fmt().as_ref().unwrap(), pin, pan, &hex::decode(cfg.get_pin_key().as_ref().unwrap().as_str()).unwrap()) {
Ok(v) => {
self.set_on(52, hex::encode(v).as_str())
}
Err(e) => {
Err(IsoError { msg: e.msg })
... | {
return Err(IsoError { msg: format!("missing pin_format or key in call to set_pin") });
} | conditional_block |
iso_spec.rs | //! This module contains implementation of specification, its segments and associated operations
//!
use std::collections::HashMap;
use std::fmt::{Display, Formatter};
use std::io::Cursor;
use crate::iso8583::{bitmap, IsoError};
use crate::iso8583::field::{Field, ParseError};
use crate::iso8583::yaml_de::YMessageSegme... | (_name: &str) -> &'static Spec {
//TODO:: handle case of multiple specs, for now just return the first
ALL_SPECS.iter().find_map(|(_k, v)| Some(v)).unwrap()
}
/// Returns a empty IsoMsg that can be used to create a message
pub fn new_msg(spec: &'static Spec, seg: &'static MessageSegment) -> IsoMsg {
IsoMsg... | spec | identifier_name |
spatial.rs | use inle_alloc::temp::*;
use inle_app::app::Engine_State;
use inle_ecs::ecs_world::{Ecs_World, Entity, Evt_Entity_Destroyed};
use inle_events::evt_register::{with_cb_data, wrap_cb_data, Event_Callback_Data};
use inle_math::vector::Vec2f;
use inle_physics::collider::C_Collider;
use inle_physics::phys_world::{Collider_Ha... |
}
pub struct World_Chunks {
chunks: HashMap<Chunk_Coords, World_Chunk>,
to_destroy: Event_Callback_Data,
}
#[derive(Default, Debug)]
pub struct World_Chunk {
pub colliders: Vec<Collider_Handle>,
}
impl World_Chunks {
pub fn new() -> Self {
Self {
chunks: HashMap::new(),
... | {
Vec2f {
x: self.x as f32 * CHUNK_WIDTH,
y: self.y as f32 * CHUNK_HEIGHT,
}
} | identifier_body |
spatial.rs | use inle_alloc::temp::*;
use inle_app::app::Engine_State;
use inle_ecs::ecs_world::{Ecs_World, Entity, Evt_Entity_Destroyed};
use inle_events::evt_register::{with_cb_data, wrap_cb_data, Event_Callback_Data};
use inle_math::vector::Vec2f;
use inle_physics::collider::C_Collider;
use inle_physics::phys_world::{Collider_Ha... | pub fn to_world_pos(self) -> Vec2f {
Vec2f {
x: self.x as f32 * CHUNK_WIDTH,
y: self.y as f32 * CHUNK_HEIGHT,
}
}
}
pub struct World_Chunks {
chunks: HashMap<Chunk_Coords, World_Chunk>,
to_destroy: Event_Callback_Data,
}
#[derive(Default, Debug)]
pub struct Worl... | x: (pos.x / CHUNK_WIDTH).floor() as i32,
y: (pos.y / CHUNK_HEIGHT).floor() as i32,
}
}
| random_line_split |
spatial.rs | use inle_alloc::temp::*;
use inle_app::app::Engine_State;
use inle_ecs::ecs_world::{Ecs_World, Entity, Evt_Entity_Destroyed};
use inle_events::evt_register::{with_cb_data, wrap_cb_data, Event_Callback_Data};
use inle_math::vector::Vec2f;
use inle_physics::collider::C_Collider;
use inle_physics::phys_world::{Collider_Ha... | (&self) -> usize {
self.chunks.len()
}
pub fn add_collider(&mut self, cld_handle: Collider_Handle, pos: Vec2f, extent: Vec2f) {
let mut chunks = vec![];
self.get_all_chunks_containing(pos, extent, &mut chunks);
for coords in chunks {
self.add_collider_coords(cld_hand... | n_chunks | identifier_name |
main.rs | /*
--- Day 4: Passport Processing ---
You arrive at the airport only to realize that you grabbed your North Pole Credentials instead of your passport. While these documents are extremely similar, North Pole Credentials aren't issued by a country and therefore aren't actually valid documentation for travel in most of t... | ;
}
valid_passports_total
}
fn validate_passport(passport: &HashMap<String, String>) -> bool {
let mut result = true;
// Birth year
if let Some(byr) = passport.get("byr") {
result = result && validate_byr(byr);
} else {
result = false;
}
// Issue Year
if let Some(... | { 0 } | conditional_block |
main.rs | /*
--- Day 4: Passport Processing ---
You arrive at the airport only to realize that you grabbed your North Pole Credentials instead of your passport. While these documents are extremely similar, North Pole Credentials aren't issued by a country and therefore aren't actually valid documentation for travel in most of t... | (passport: &HashMap<String, String>) -> bool {
let mut result = true;
// Birth year
if let Some(byr) = passport.get("byr") {
result = result && validate_byr(byr);
} else {
result = false;
}
// Issue Year
if let Some(iyr) = passport.get("iyr") {
result = result && va... | validate_passport | identifier_name |
main.rs | /*
--- Day 4: Passport Processing ---
You arrive at the airport only to realize that you grabbed your North Pole Credentials instead of your passport. While these documents are extremely similar, North Pole Credentials aren't issued by a country and therefore aren't actually valid documentation for travel in most of t... |
ecl valid: brn
ecl invalid: wat
pid valid: 000000001
pid invalid: 0123456789
Here are some invalid passports:
eyr:1972 cid:100
hcl:#18171d ecl:amb hgt:170 pid:186cm iyr:2018 byr:1926
iyr:2019
hcl:#602927 eyr:1967 hgt:170cm
ecl:grn pid:012533040 byr:1946
hcl:dab227 iyr:2012
ecl:brn hgt:182cm pid:021572410 eyr:... |
hcl valid: #123abc
hcl invalid: #123abz
hcl invalid: 123abc | random_line_split |
main.rs | /*
--- Day 4: Passport Processing ---
You arrive at the airport only to realize that you grabbed your North Pole Credentials instead of your passport. While these documents are extremely similar, North Pole Credentials aren't issued by a country and therefore aren't actually valid documentation for travel in most of t... | for item in lin.split_whitespace() {
let mut pair = item.split(':');
let key = String::from(pair.next().unwrap());
let value = String::from(pair.next().unwrap());
entry.insert(key, value);
}
line = lines.next();
... | {
let mut passports: Vec< HashMap<String, String> > = Vec::new();
let file = File::open(filename).unwrap();
let reader = BufReader::new(file);
let mut lines = reader.lines();
// iterate over lines until end of file
loop {
let mut line = lines.next();
if line.is_none() {
... | identifier_body |
reader.rs | },
/// The padding header at the end of the packet, if present, specifies the number of padding
/// bytes, including itself, and therefore cannot be less than `1`, or greater than the
/// available space.
PaddingLengthInvalid(u8),
}
impl<'a> RtpReader<'a> {
/// An RTP packet header is no fewer ... | (b: &'a [u8]) -> Result<RtpReader<'_>, RtpReaderError> {
if b.len() < Self::MIN_HEADER_LEN {
return Err(RtpReaderError::BufferTooShort(b.len()));
}
let r = RtpReader { buf: b };
if r.version()!= 2 {
return Err(RtpReaderError::UnsupportedVersion(r.version()));
... | new | identifier_name |
reader.rs | },
/// The padding header at the end of the packet, if present, specifies the number of padding
/// bytes, including itself, and therefore cannot be less than `1`, or greater than the
/// available space.
PaddingLengthInvalid(u8),
}
impl<'a> RtpReader<'a> {
/// An RTP packet header is no fewer ... |
#[test]
fn padding_too_large() {
// 'padding' header-flag is on, and padding length (255) in final byte is larger than the
// buffer length. (Test data created by fuzzing.)
let data = [
0xa2, 0xa2, 0xa2, 0xa2, 0xa2, 0x90, 0x0, 0x0, 0x1, 0x0, 0xff, 0xa2, 0xa2, 0xa2, 0xa2,
... | {
let reader = RtpReader::new(&TEST_RTP_PACKET_WITH_EXTENSION).unwrap();
assert_eq!(2, reader.version());
assert!(reader.padding().is_none());
assert!(reader.extension().is_some());
assert_eq!(0, reader.csrc_count());
assert_eq!(111, reader.payload_type());
} | identifier_body |
reader.rs | },
/// The padding header at the end of the packet, if present, specifies the number of padding
/// bytes, including itself, and therefore cannot be less than `1`, or greater than the
/// available space.
PaddingLengthInvalid(u8),
}
impl<'a> RtpReader<'a> {
/// An RTP packet header is no fewer ... | else {
None
}
}
/// Create a `RtpPacketBuilder` from this packet. **Note** that padding from the original
/// packet will not be used by default, and must be defined on the resulting `RtpPacketBuilder`
/// if required.
///
/// The padding is not copied from the original si... | {
let offset = self.csrc_end();
let id = (self.buf[offset] as u16) << 8 | (self.buf[offset + 1] as u16);
let start = offset + 4;
Some((id, &self.buf[start..start + self.extension_len()]))
} | conditional_block |
reader.rs |
},
/// The padding header at the end of the packet, if present, specifies the number of padding
/// bytes, including itself, and therefore cannot be less than `1`, or greater than the
/// available space.
PaddingLengthInvalid(u8),
}
impl<'a> RtpReader<'a> {
/// An RTP packet header is no fewer... | }
#[test]
fn padding_too_large() {
// 'padding' header-flag is on, and padding length (255) in final byte is larger than the
// buffer length. (Test data created by fuzzing.)
let data = [
0xa2, 0xa2, 0xa2, 0xa2, 0xa2, 0x90, 0x0, 0x0, 0x1, 0x0, 0xff, 0xa2, 0xa2, 0xa2, 0xa... | assert!(reader.padding().is_none());
assert!(reader.extension().is_some());
assert_eq!(0, reader.csrc_count());
assert_eq!(111, reader.payload_type()); | random_line_split |
lib.rs | //! Linear regression
//!
//! `linreg` calculates linear regressions for two dimensional measurements, also known as
//! [simple linear regression](https://en.wikipedia.org/wiki/Simple_linear_regression).
//!
//! Base for all calculations of linear regression is the simple model found in
//! https://en.wikipedia.org/wi... |
let x_sum: F = xs.iter().cloned().map(Into::into).sum();
let n = F::from(xs.len()).ok_or(Error::Mean)?;
let x_mean = x_sum / n;
let y_sum: F = ys.iter().cloned().map(Into::into).sum();
let y_mean = y_sum / n;
lin_reg(
xs.iter()
.map(|i| i.clone().into())
.zip(ys.i... | {
return Err(Error::Mean);
} | conditional_block |
lib.rs | //! Linear regression
//!
//! `linreg` calculates linear regressions for two dimensional measurements, also known as
//! [simple linear regression](https://en.wikipedia.org/wiki/Simple_linear_regression).
//!
//! Base for all calculations of linear regression is the simple model found in
//! https://en.wikipedia.org/wi... |
pub fn parts(mut self) -> Result<(F, F, F, F), Error> {
self.normalize()?;
let Self {
x_mean,
y_mean,
x_mul_y_mean,
x_squared_mean,
..
} = self;
Ok((x_mean, y_mean, x_mul_y_mean, x_sq... | {
match self.n {
1 => return Ok(()),
0 => return Err(Error::NoElements),
_ => {}
}
let n = F::from(self.n).ok_or(Error::Mean)?;
self.n = 1;
self.x_mean = self.x_mean / n;
self.y_mean = self.y_mean / n... | identifier_body |
lib.rs | //! Linear regression
//!
//! `linreg` calculates linear regressions for two dimensional measurements, also known as
//! [simple linear regression](https://en.wikipedia.org/wiki/Simple_linear_regression).
//!
//! Base for all calculations of linear regression is the simple model found in
//! https://en.wikipedia.org/wi... | <F: FloatCore> {
x_mean: F,
y_mean: F,
x_mul_y_mean: F,
x_squared_mean: F,
n: usize,
}
impl<F: FloatCore> Default for Accumulator<F> {
fn default() -> Self {
Self::new()
}
}
impl<F: FloatCore> Accumulator<F> {
pub fn new() -> ... | Accumulator | identifier_name |
lib.rs | //! Linear regression
//!
//! `linreg` calculates linear regressions for two dimensional measurements, also known as
//! [simple linear regression](https://en.wikipedia.org/wiki/Simple_linear_regression).
//!
//! Base for all calculations of linear regression is the simple model found in
//! https://en.wikipedia.org/wi... | .fold((F::zero(), F::zero()), |(sx, sy), (x, y)| {
(sx + x.into(), sy + y.into())
});
let x_mean = x_sum / n;
let y_mean = y_sum / n;
lin_reg(
xys.iter()
.map(|(x, y)| (x.clone().into(), y.clone().into())),
x_mean,
y_mean,
)
}
#[cfg(test)]
... | // If we ran the generic impl on each tuple field, that would be very cache inefficient
let n = F::from(xys.len()).ok_or(Error::Mean)?;
let (x_sum, y_sum) = xys
.iter()
.cloned() | random_line_split |
mod.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
use core::mem::transmute;
use core::mem::MaybeUninit;
use core::ptr;
use core::sync::atomic::fence;... |
/// Register the given sigaction as the default. Optionally an override function
/// can be passed in that will us to change the default handler for an action
fn insert_action(
sigaction: libc::sigaction,
override_default_handler: Option<libc::sighandler_t>,
) -> SlotKey {
HANDLER_SLOT_MAP.insert(Some(Sig... | {
if action.sa_flags & libc::SA_SIGINFO > 0 {
let to_run: extern "C" fn(libc::c_int, *const libc::siginfo_t, *const libc::c_void) =
transmute(action.sa_sigaction as *const libc::c_void);
to_run(
signal_val,
&sig_info as *const libc::siginfo_t,
ptr::nul... | identifier_body |
mod.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
use core::mem::transmute;
use core::mem::MaybeUninit;
use core::ptr;
use core::sync::atomic::fence;... | /// treatment of function pointers in signal handlers (instead of checking for)
///specific values of sighandler_t before calling
pub extern "C" fn default_ignore_handler<T: ToolGlobal>(
_signal_value: libc::c_int,
_siginfo: *const libc::siginfo_t,
_ctx: *const libc::c_void,
) {
}
/// This is our replaceme... |
/// This is our replacement for default handlers where
/// `libc::sighandler_t = libc::SIG_IGN` which is the default handler
/// value for lots of signals. This function does nothing, but allows uniform | random_line_split |
mod.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
use core::mem::transmute;
use core::mem::MaybeUninit;
use core::ptr;
use core::sync::atomic::fence;... | (original: libc::sigaction, override_handler: Option<libc::sighandler_t>) -> Self {
let mut internal_action = original.clone();
// This is safe because it is only reading from a mut static that is
// guaranteed to have been completely set before this function
// is called
intern... | new | identifier_name |
set1.rs | => ((extended[1] & 0x0F) << 2) | ((extended[2] & 0xC0) >> 6),
3 => ((extended[2] & 0x3F) << 0),
_ => return Err("too many groups!"),
};
let symbol: char = match sextet {
c @ 0...25 => char::from(0x41 + c),
c @ 26...51 => char::fro... | (plaintext: &[u8], key: &[u8]) -> Vec<u8> {
let result = plaintext
.iter()
.zip(key.iter().cycle())
.map(|pair| match pair {
(&aa, &bb) => aa ^ bb,
})
.collect::<Vec<u8>>();
return result;
}
use std::collections::BTreeMap;
pub fn char_freq_score(text: &[u8]) ->... | xor_repeat | identifier_name |
set1.rs | => ((extended[1] & 0x0F) << 2) | ((extended[2] & 0xC0) >> 6),
3 => ((extended[2] & 0x3F) << 0),
_ => return Err("too many groups!"),
};
let symbol: char = match sextet {
c @ 0...25 => char::from(0x41 + c),
c @ 26...51 => char::fro... |
#[test]
fn hamming_distance() {
assert_eq!(
set1::hamming_distance("this is a test".as_bytes(), "wokka wokka!!!".as_bytes())
.unwrap(),
37
);
}
#[test]
fn break_repeating_key_xor() {
let mut f = File::open("challenge-data/6.txt").unwr... | {
let plaintext = "Burning 'em, if you ain't quick and nimble\n\
I go crazy when I hear a cymbal";
let key = "ICE";
let plaintext = plaintext.as_bytes();
let key = key.as_bytes();
let ciphertext = set1::xor_repeat(&plaintext, &key);
let ciphert... | identifier_body |
set1.rs | 2 => ((extended[1] & 0x0F) << 2) | ((extended[2] & 0xC0) >> 6),
3 => ((extended[2] & 0x3F) << 0),
_ => return Err("too many groups!"),
};
let symbol: char = match sextet {
c @ 0...25 => char::from(0x41 + c),
c @ 26...51 => char::f... | #[test]
fn xor() {
let a = "1c0111001f010100061a024b53535009181c";
let b = "686974207468652062756c6c277320657965";
let res = "746865206b696420646f6e277420706c6179";
let a_bytes = Vec::from_hex(a).unwrap();
let b_bytes = Vec::from_hex(b).unwrap();
let res_bytes = ... | }
}
| random_line_split |
main.rs | #[macro_use]
extern crate colored_print;
extern crate atty;
use colored_print::color::ConsoleColor;
use colored_print::color::ConsoleColor::*;
use std::env;
use std::ffi::OsStr;
use std::fmt;
use std::fmt::Display;
use std::fs;
use std::fs::File;
use std::io;
use std::io::prelude::*;
use std::path::{Path, PathBuf};
u... |
fn print_output(retval: Option<i32>, output: &str) {
colored_print!{
colorize();
Reset, "{}", output;
}
if let Some(code) = retval {
colored_println!{
colorize();
Cyan, "return code";
Reset, ": {}", code;
}
}
}
fn print_stderr(stderr... | {
colored_println!{
colorize();
color, "{} ", heading;
}
} | identifier_body |
main.rs | #[macro_use]
extern crate colored_print;
extern crate atty;
use colored_print::color::ConsoleColor;
use colored_print::color::ConsoleColor::*;
use std::env;
use std::ffi::OsStr;
use std::fmt;
use std::fmt::Display;
use std::fs;
use std::fs::File;
use std::io;
use std::io::prelude::*;
use std::path::{Path, PathBuf};
u... | .arg("-emit-llvm")
.arg("-o")
.arg(ir_path.display().to_string())
.arg(src_path.display().to_string())
.output()?;
let cc_output = String::from_utf8_lossy(&output.stderr).into_owned();
if!ir_path.exists() {
return Ok(CompilationResult::Failure { cc_output });
}
... | let output = Command::new("clang")
.arg("-O0")
.arg("-S") | random_line_split |
main.rs | #[macro_use]
extern crate colored_print;
extern crate atty;
use colored_print::color::ConsoleColor;
use colored_print::color::ConsoleColor::*;
use std::env;
use std::ffi::OsStr;
use std::fmt;
use std::fmt::Display;
use std::fs;
use std::fs::File;
use std::io;
use std::io::prelude::*;
use std::path::{Path, PathBuf};
u... | {
compilation: CompilationResult,
assembly: AssemblyResult,
execution: ExecutionResult,
}
fn do_for(version: Version, path: &Path) -> io::Result<Results> {
let (compilation, assembly, execution);
// explicitly denote borrowing region
{
compilation = (version.get_compiler_func())(&path... | Results | identifier_name |
cylinder.rs | //! Construct cylinders that are curved sheets, not volumes.
use surface::{Sheet, LatticeType};
use coord::{Coord, Direction, Translate,
rotate_coords, rotate_planar_coords_to_alignment};
use describe::{unwrap_name, Describe};
use error::Result;
use iterator::{ResidueIter, ResidueIterOut};
use system::*;
use std... | }
#[cfg(test)]
mod tests {
use super::*;
use surface::LatticeType::*;
fn setup_cylinder(radius: f64, height: f64, lattice: &LatticeType) -> Cylinder {
Cylinder {
name: None,
residue: None,
lattice: lattice.clone(),
alignment: Direction::Z,
... |
fn describe_short(&self) -> String {
format!("{} (Cylinder)", unwrap_name(&self.name))
} | random_line_split |
cylinder.rs | //! Construct cylinders that are curved sheets, not volumes.
use surface::{Sheet, LatticeType};
use coord::{Coord, Direction, Translate,
rotate_coords, rotate_planar_coords_to_alignment};
use describe::{unwrap_name, Describe};
use error::Result;
use iterator::{ResidueIter, ResidueIterOut};
use system::*;
use std... | () {
let lattice = PoissonDisc { density: 10.0 };
assert!(setup_cylinder(-1.0, 1.0, &lattice).construct().is_err());
assert!(setup_cylinder(1.0, -1.0, &lattice).construct().is_err());
assert!(setup_cylinder(1.0, 1.0, &lattice).construct().is_ok());
}
#[test]
fn add_caps_to_... | constructing_cylinder_with_negative_radius_or_height_returns_error | identifier_name |
lib.rs | #[macro_use]
extern crate log;
use io_partition::Partition;
use std::fmt;
use std::io;
use std::io::{Read, Seek, SeekFrom};
fn get_bit(byte: u8, id: usize) -> Option<bool> {
if id < 8 {
Some((byte >> (7 - id) << 7) >= 1)
} else {
None
}
}
#[derive(Debug)]
pub enum PXError {
IOError(io:... | <F: Read + Seek>(file: &mut F) -> Result<bool, PXError> {
if file.seek(SeekFrom::End(0))? < 4 {
return Ok(false);
};
file.seek(SeekFrom::Start(0))?;
let mut header_5 = [0; 5];
file.read_exact(&mut header_5)?;
if &header_5 == b"PKDPX" {
return Ok(true);
};
if &header_5 ... | is_px | identifier_name |
lib.rs | #[macro_use]
extern crate log;
use io_partition::Partition;
use std::fmt;
use std::io;
use std::io::{Read, Seek, SeekFrom};
fn get_bit(byte: u8, id: usize) -> Option<bool> {
if id < 8 {
Some((byte >> (7 - id) << 7) >= 1)
} else {
None
}
}
#[derive(Debug)]
pub enum PXError {
IOError(io:... | }
None => {
let new_byte = px_read_u8(&mut raw_file)?;
let offset_rel: i16 =
-0x1000 + (((nb_low as i16) * 256) + (new_byte as i16));
let offset = (offset_rel as i32) + (result.len... | random_line_split | |
lib.rs | #[macro_use]
extern crate log;
use io_partition::Partition;
use std::fmt;
use std::io;
use std::io::{Read, Seek, SeekFrom};
fn get_bit(byte: u8, id: usize) -> Option<bool> {
if id < 8 {
Some((byte >> (7 - id) << 7) >= 1)
} else {
None
}
}
#[derive(Debug)]
pub enum PXError {
IOError(io:... | )?)
} else if &header_5 == b"AT4PX" {
let decompressed_lenght = px_read_u16(&mut file)? as u32;
Ok(decompress_px_raw(
file,
control_flags,
decompressed_lenght,
container_lenght,
18,
)?)
} else {
Err(PXError::Inva... | {
debug!("decompressing a px-compressed file file");
file.seek(SeekFrom::Start(0))?;
let mut header_5 = [0; 5];
file.read_exact(&mut header_5)?;
let container_lenght = px_read_u16(&mut file)?;
let mut control_flags_buffer = [0; 9];
file.read_exact(&mut control_flags_buffer)?;
let contr... | identifier_body |
film.rs | use crate::core::geometry::point::{Point2i, Point2f};
use crate::core::spectrum::{Spectrum, xyz_to_rgb};
use crate::core::pbrt::{Float, Options, clamp, INFINITY};
use crate::core::filter::{Filters, Filter};
use crate::core::geometry::bounds::{Bounds2i, Bounds2f};
use crate::core::parallel::AtomicFloat;
use std::sync::R... |
let pi = Point2i::from(p.floor());
if!self.cropped_pixel_bounds.inside_exclusive(&pi) { return; }
if v.y() > self.max_sample_luminance {
v *= self.max_sample_luminance / v.y();
}
let mut pixels = self.pixels.write().unwrap();
let xyz = v.to_xyz();
... | {
error!("Ignoring slatted spectrum with infinite luminance at ({}, {})", p.x, p.y);
return;
} | conditional_block |
film.rs | use crate::core::geometry::point::{Point2i, Point2f};
use crate::core::spectrum::{Spectrum, xyz_to_rgb};
use crate::core::pbrt::{Float, Options, clamp, INFINITY};
use crate::core::filter::{Filters, Filter};
use crate::core::geometry::bounds::{Bounds2i, Bounds2f};
use crate::core::parallel::AtomicFloat;
use std::sync::R... | (&self, p: &Point2f, mut v: Spectrum) {
// TODO: ProfilePhase
if v.has_nans() {
error!("Ignoring splatted spectrum with NaN values at ({}, {})", p.x, p.y);
return;
} else if v.y() < 0.0 {
error!("Ignoring splatted spectrum with negative luminance {} at ({}, {}... | add_splat | identifier_name |
film.rs | use crate::core::geometry::point::{Point2i, Point2f};
use crate::core::spectrum::{Spectrum, xyz_to_rgb};
use crate::core::pbrt::{Float, Options, clamp, INFINITY};
use crate::core::filter::{Filters, Filter};
use crate::core::geometry::bounds::{Bounds2i, Bounds2f};
use crate::core::parallel::AtomicFloat;
use std::sync::R... | let p = Point2f::new(
(x as Float + 0.5) * filt.radius().x / FILTER_TABLE_WIDTH as Float,
(y as Float + 0.5) * filt.radius().y / FILTER_TABLE_WIDTH as Float
);
filter_table[offset] = filt.evaluate(&p);
offset += 1;
... | let mut offset = 0;
let mut filter_table = [0.0; FILTER_TABLE_WIDTH * FILTER_TABLE_WIDTH];
for y in 0..FILTER_TABLE_WIDTH {
for x in 0..FILTER_TABLE_WIDTH { | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.