text
stringlengths
1
2.12k
source
dict
c++ char m = 'x'; char sq = 's'; char c = 'c'; char d = '/'; char s = '-'; if (operation == m) { result = multiply(number1, number2, operation); } else if (operation == sq) { result = square(number1, operation); } else if (operation == c) { result = cube(number1, operation); } else if (operation == d) { result = divide(number1, number2, operation); } else if (operation == s) { result = subtract(number1, number2, operation); } else { cout << "Wrong operator input. Try again" << endl; return 2; } // Outputing Result : cout << "The result is : " << result << endl; return 0; } // Function Definition int multiply(int firstnumber, int secondnumber, char operation) { return firstnumber * secondnumber; } int square(int firstnumber, char operation) { return firstnumber * firstnumber; } int cube(int firstnumber, char operation) { return firstnumber * firstnumber * firstnumber; } int divide(int firstnumber, int secondnumber, char operation) { return firstnumber / secondnumber; } int subtract(int firstnumber, int secondnumber, char operation) { return firstnumber - secondnumber; } Answer: Avoid using using namespace std; Find more details here why using namespace std; is considered bad practice Use '\n' for adding newline std::endl doesn't just add newline but it also flushes the stream. More details about it std::endl vs '\n' Refactor into functions Make a function for calculation. What if you'd want to calculate twice? By making it into a function you can simply call it as needed. Example: int calculate(...){ ... } int main(){ int result1 = calculate(2, 3, 'x'); int result2 = calculate(2, 'c'); } Leverage STL STL functional header has
{ "domain": "codereview.stackexchange", "id": 42693, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++", "url": null }
c++ Leverage STL STL functional header has std::divides for division. std::minus for subtraction. std::multiplies for multiplication. Example usage: std::minus<int>{}(10, 9) // -> 10 - 9 is performed std::divides<int>{}(3, 2) // -> 3 / 2 is performed Remove unnecessary parameters from the function. char operation parameter is never used. It doesn't serve any purpose and can be removed. switch-case You could use switch for mapping char to operation. And to avoid writing operation == /*op*/ for each operation in every if and elif. switch(op){ case 'x': return std::multiplies<int>{}(num1, num2); case '/': return std::divides<int>{}(num1, num2); case '-': return std::minus<int>{}(num1, num2); case 'c': return cube(num1); case 's': return sqaure(num1); default: /* Handle when `op` is other than [-, /, x, c, s] */ };,
{ "domain": "codereview.stackexchange", "id": 42693, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++", "url": null }
parsing, rust, lexical-analysis Title: Lexer for a Scheme-like language in rust Question: I was/am working on an interpreter for a scheme-like language. Just some time back I shifted my implementation from C++ to Rust, which I just started learning. I know there are parser libraries like LALRPROP and nom in Rust that could parse easily for me, but I wanted to try and write it in Rust from scratch. Any comments and help would be much appreciated so that I can write more idiomatic Rust. object.rs: has the definition of the AST and functions for display and conversion of the AST to strings. use crate::util; use std::fmt; #[derive(Debug)] pub enum Object { Integer(i64), Boolean(bool), Character(char), String(String), Symbol(String), Cons { car: Box<Object>, cdr: Box<Object> }, Nil, } pub type ObjectBox = Box<Object>; pub mod constants { use super::Object; pub const TRUE: Object = Object::Boolean(true); pub const FALSE: Object = Object::Boolean(false); pub const NIL: Object = Object::Nil; } impl Object { fn pair_to_string(&self) -> String { let mut result = String::from(""); if let Object::Cons { car, cdr } = &*self { result.push_str(&car.to_string()); match **cdr { Object::Cons { car: _, cdr: _ } => { result.push(' '); result.push_str(&cdr.pair_to_string()); } Object::Nil => result.push_str(""), _ => { result.push_str(" . "); result.push_str(&cdr.to_string()); } }; return result; } else { panic!("I shouldnt be here!"); } }
{ "domain": "codereview.stackexchange", "id": 42694, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "parsing, rust, lexical-analysis", "url": null }
parsing, rust, lexical-analysis pub fn to_string(&self) -> String { match &*self { Object::Integer(i) => i.to_string(), Object::Boolean(i) => { if *i { "#t".to_string() } else { "#f".to_string() } } Object::Character(i) => match i { '\n' => "$\\n".to_string(), '\t' => "$\\t".to_string(), '\r' => "$\\r".to_string(), '\0' => "$\\0".to_string(), '\\' => "$\\\\".to_string(), ' ' => "$space".to_string(), _ => format!("${}", i), }, Object::String(i) => format!("\"{}\"", util::raw_string(i)), Object::Symbol(i) => i.to_string(), cons @ Object::Cons { car: _, cdr: _ } => format!("({})", cons.pair_to_string()), Object::Nil => "()".to_string(), } } } impl fmt::Display for Object { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.to_string()) } } parser.rs: The parser, it tokenizes and parses at the same time. Meaningfull error messages still need to be added, I am planning on making a custom error type, so i can also pass the error position. use super::object::*; pub struct Parser<'a> { source: &'a str, start: usize, current: usize, } impl<'a> Parser<'a> { pub fn new(source: &'a str) -> Self { Parser { source: source, start: 0, current: 0, } } pub fn set_source(&mut self, new_source: &'a str) { self.source = new_source; } fn is_at_end(&self) -> bool { self.current - 1 == self.source.chars().count() } fn advance(&mut self) -> Option<char> { self.current += 1; self.source.chars().nth(self.current - 1) } fn peek(&self) -> Option<char> { self.source.chars().nth(self.current) }
{ "domain": "codereview.stackexchange", "id": 42694, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "parsing, rust, lexical-analysis", "url": null }
parsing, rust, lexical-analysis fn peek(&self) -> Option<char> { self.source.chars().nth(self.current) } fn is_delimiter(&self, ch: char) -> bool { ch.is_ascii_whitespace() || matches!(ch, '(' | ')' | ';' | '"' | '\'') || self.is_at_end() } fn peek_delimiter(&self) -> bool { if let Some(ch) = self.peek() { self.is_delimiter(ch) } else { true } } fn is_symbol_initial(&self, ch: char) -> bool { !matches!(ch, '(' | ')' | ';' | '$' | '#' | '"' | '-' | '\'') && !ch.is_ascii_digit() } fn is_symbol_character(&self, ch: char) -> bool { !matches!(ch, '(' | ')' | ';' | '\'') || ch.is_ascii_whitespace() } fn skip_whitespace(&mut self) { while let Some(ch) = self.peek() { if ch.is_whitespace() { self.advance(); continue; } else if ch == ';' { while let Some(ch) = self.advance() { if ch == '\n' { break; } } continue; } break; } } fn peek_number(&self, ch: char) -> bool { ch.is_ascii_digit() || (ch == '-' && self.peek().unwrap().is_ascii_digit()) } fn parse_number(&mut self) -> Result<ObjectBox, String> { while let Some(ch) = self.peek() { if ch.is_ascii_digit() { self.advance(); } else { break; } } Ok(ObjectBox::new(Object::Integer( self.source .chars() .skip(self.start) .take(self.current - self.start) .collect::<String>() .parse::<i64>() .unwrap(), ))) }
{ "domain": "codereview.stackexchange", "id": 42694, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "parsing, rust, lexical-analysis", "url": null }
parsing, rust, lexical-analysis fn parse_boolean(&mut self) -> Result<ObjectBox, String> { if let Some(ch) = self.advance() { match ch { 't' => Ok(ObjectBox::new(constants::TRUE)), 'f' => Ok(ObjectBox::new(constants::FALSE)), _ => Err(String::from("")), } } else { Err(String::from("")) } } fn parse_character(&mut self) -> Result<ObjectBox, String> { // TODO: Add $\x80 and $\d97 style characters if let Some(ch) = self.advance() { if ch == '\\' { if let Some(ch) = self.advance() { if !self.peek_delimiter() { return Err(String::from("")); } match ch { 'n' => return Ok(ObjectBox::new(Object::Character('\n'))), 'r' => return Ok(ObjectBox::new(Object::Character('\r'))), 't' => return Ok(ObjectBox::new(Object::Character('\t'))), '\\' => return Ok(ObjectBox::new(Object::Character('\\'))), '0' => return Ok(ObjectBox::new(Object::Character('\0'))), ' ' => return Ok(ObjectBox::new(Object::Character(' '))), _ => return Err(String::from("")), } } else { return Err(String::from("")); } } else { if !self.peek_delimiter() { return Err(String::from("")); } return Ok(ObjectBox::new(Object::Character(ch))); } } else { return Err(String::from("")); } } fn parse_string(&mut self) -> Result<ObjectBox, String> { let mut result = String::new(); while let Some(ch) = self.advance() { if self.is_at_end() { return Err(String::from("at end")); }
{ "domain": "codereview.stackexchange", "id": 42694, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "parsing, rust, lexical-analysis", "url": null }
parsing, rust, lexical-analysis if ch == '"' { return Ok(ObjectBox::new(Object::String(result))); } if ch == '\\' { if let Some(ch) = self.advance() { match ch { 'n' => result.push('\n'), 'r' => result.push('\r'), 't' => result.push('\t'), '\\' => result.push('\\'), '0' => result.push('\0'), _ => result.push(ch), } continue; } else { return Err(String::from("empty escape sequence")); } } result.push(ch); } Err(String::from("no ending quote")) } fn parse_pair(&mut self) -> Result<ObjectBox, String> { let car: ObjectBox; let cdr: ObjectBox; self.skip_whitespace(); if let Some(ch) = self.peek() { if ch == ')' { self.advance(); return Ok(ObjectBox::new(constants::NIL)); } match self.parse() { Ok(object_box) => car = object_box, a @ Err(_) => return a, } self.skip_whitespace(); if let Some(ch) = self.peek() { if ch == '.' { self.advance(); if !self.peek_delimiter() { return Err(String::from("")); } match self.parse() { Ok(object_box) => cdr = object_box, a @ Err(_) => return a, } self.skip_whitespace();
{ "domain": "codereview.stackexchange", "id": 42694, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "parsing, rust, lexical-analysis", "url": null }
parsing, rust, lexical-analysis self.skip_whitespace(); if let Some(ch) = self.advance() { if ch == ')' { return Ok(ObjectBox::new(Object::Cons { car, cdr })); } else { return Err(String::from("")); } } else { return Err(String::from("")); } } else { match self.parse_pair() { Ok(object_box) => cdr = object_box, a @ Err(_) => return a, } return Ok(ObjectBox::new(Object::Cons { car, cdr })); } } } Err(String::from("here")) } fn parse_symbol(&mut self) -> Result<ObjectBox, String> { while let Some(ch) = self.peek() { if self.is_symbol_character(ch) { self.advance(); } else { break; } } return Ok(ObjectBox::new(Object::Symbol( self.source .chars() .skip(self.start) .take(self.current - self.start) .collect::<String>(), ))); } pub fn parse(&mut self) -> Result<ObjectBox, String> { self.skip_whitespace(); self.start = self.current; let ch = self.advance().unwrap(); match ch { ch if self.peek_number(ch) => self.parse_number(), '#' => self.parse_boolean(), '$' => self.parse_character(), '"' => self.parse_string(), '(' => self.parse_pair(), ch if self.is_symbol_initial(ch) => self.parse_symbol(), _ => Err(String::from("Unknown Character")), } } }
{ "domain": "codereview.stackexchange", "id": 42694, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "parsing, rust, lexical-analysis", "url": null }
parsing, rust, lexical-analysis util.rs: a utility module, for now just has a function that converts strings like "Hello \n World!" to "Hello \\n World" pub fn raw_string(string: &str) -> String { let mut result = String::from(""); for ch in string.chars() { match ch { '\n' => result.push_str("\\n"), '\t' => result.push_str("\\t"), '\r' => result.push_str("\\r"), '\\' => result.push_str("\\\\"), '\0' => result.push_str("\\0"), _ => result.push(ch), } } result } main.rs: The driver code, for now I am hard coding the input, the plan is to make a interactive REPL. #![allow(dead_code)] mod core; mod util; use self::core::parser::*; fn main() { let mut scanner = Parser::new("\"Hello \\nWorld\""); match scanner.parse() { Ok(object) => println!("{}", object), Err(message) => println!("{}", message), } } Any tips to make the code more Rust-like will be very helpful! Answer: Clippy First, always, always run cargo clippy. Clippy gives you lots of helpful tips to make your code more idiomatic and simpler, and sometimes catches more serious missteps. From Clippy: Lots of unnecessary return statements. To return a value on the last line of a function (or the last line of each if branch), in Rust it is preferred to omit the return statement. In your case, the biggest offender is fn parse_character where Clippy finds that most of your returns can be omitted (however, I would note that this function honestly looks pretty gnarly regardless and should be broken up into simpler more understandable functions). In constructing a struct, you can use the field name directly if it matches the local variable name: Parser { source, start: 0, current: 0 }
{ "domain": "codereview.stackexchange", "id": 42694, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "parsing, rust, lexical-analysis", "url": null }
parsing, rust, lexical-analysis Finally, Clippy finds a potentially more serious problem, and links you to this page: the problem is that .to_string() is automatically implemented for any type that implements Display (via the ToString trait), so there are actually two definitions of .to_string() for your struct, one of them being overwritten. Easiest fix is to rename your public pub fn to_string(&self) -> String to a private function like fn to_string_core(&self) -> String and use it only internally. More idiomatic fix would be to put this logic directly in the Display implementation and omit to_string_core. That's all for Clippy fixes. Other than what Clippy finds, your code is generally pretty good, though a bit complicated in places (but this is maybe to be expected with parsing code). Additional comments In object.rs: The function fn pair_to_string is undesirable: it has an unstated precondition, namely that the object is a Cons case, and it panics if this is not satisfied. Additionally, everywhere this is used, you actually already know that the input is a cons, so the correct design is to take as input the branches of the cons directly. Here is the improved function: fn pair_to_string(&self, other: &Self) -> String { let mut result = self.to_string(); match other { Object::Cons { car, cdr } => { result.push(' '); result.push_str(&car.pair_to_string(&cdr)); } Object::Nil => result.push_str(""), _ => { result.push_str(" . "); result.push_str(&other.to_string()); } }; result }
{ "domain": "codereview.stackexchange", "id": 42694, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "parsing, rust, lexical-analysis", "url": null }
parsing, rust, lexical-analysis now the code is more self-explanatory (it's clear that it takes a pair of Objects and prints them), simpler, and doesn't have a hidden assumption. In general, the Cons object constructor and its usage should be documented and explained: a reader unfamiliar with Scheme is highly unlikely to know what this is used for (a list vs a tree, etc.) In main.rs: Blanket #![allow(dead_code)] statements are counterproductive. If you intend core as a public API, the easiest fix is to do pub mod core. If you just temporarily want to ignore the dead code warning on set_source, use a method-level annotation: #[allow(dead_code)] pub fn set_source(&mut self, new_source: &'a str) { In parser.rs: The use of self.source.chars().nth to keep getting the nth character is problematic. Note that .chars() will be a new iterator over the source string each time and nth will get the nth character; so you probably have a very inefficient algorithm (at least n^2) for parsing large strings. There are two possible fixes here. First, the easy way: Strings are a pain because character boundaries are of different lengths, making indexing into them difficult. So to completely avoid string issues, get rid of &str in the beginning and instead convert it to an array of characters: &[char]. Converting a string s to a vector of characters is easy: let char_vec: Vec<char> = s.chars().collect(). Then use &char_vec to get a &[char]. The harder way: to work with the string directly, what you "really" want is a pointer into the string, not an index. So start and current should really be iterators with lifetime &'a which are pointing into the string source. Like this: use std::str::Chars; pub struct ParserBetter<'a> { source: &'a str, start: Chars<'a>, current: Chars<'a>, }
{ "domain": "codereview.stackexchange", "id": 42694, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "parsing, rust, lexical-analysis", "url": null }
parsing, rust, lexical-analysis This will involve a more substantial code rewrite, but it might be a good learning exercise for how to properly work with strings. The takeaway message is don't index into strings with an integer. If you need to index, use a vector of characters. Indexing into strings is either highly inefficient (if done with .chars().nth(i)) or can fall in the middle of character boundaries (if done with [i]).
{ "domain": "codereview.stackexchange", "id": 42694, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "parsing, rust, lexical-analysis", "url": null }
c++, algorithm, template, c++20 Title: 3D Inverse Discrete Cosine Transformation Implementation in C++ Question: This is a follow-up question for 3D Discrete Cosine Transformation Implementation in C++. In this post, I am trying to follow user17732522's answer to update dct3_detail and dct3 template functions, and propose idct3_detail and idct3 template functions. The formula of 3D Inverse Discrete Cosine Transformation is as follows. The 3D inverse discrete cosine transformation $$x(n_{1}, n_{2}, n_{3})$$ of size $$N_{1} \times N_{2} \times N_{3}$$ is \begin{equation} \begin{split} {x(n_{1}, n_{2}, n_{3})} = \sum_{{k_1 = 0}}^{N_1 - 1} \sum_{{k_2 = 0}}^{N_2 - 1} \sum_{{k_3 = 0}}^{N_3 - 1} \epsilon_{k_{1}} \epsilon_{k_{2}} \epsilon_{k_{3}} X(k_{1}, k_{2}, k_{3}) \\ \times \cos({\frac {\pi}{2N_{1}} (2n_{1} + 1)k_{1}}) \\ \times \cos({\frac {\pi}{2N_{2}} (2n_{2} + 1)k_{2}}) \\ \times \cos({\frac {\pi}{2N_{3}} (2n_{3} + 1)k_{3}}) \end{split} \label{3DIDCTMainFormula} \end{equation} where \begin{equation} \begin{split} n_{1} = 0, 1, \dots, N_{1} - 1 \\ n_{2} = 0, 1, \dots, N_{2} - 1 \\ n_{3} = 0, 1, \dots, N_{3} - 1 \\ \epsilon_{k_{i}} = \begin{cases} \frac{1}{\sqrt{2}} & \text{for $k_{i} = 0$} \\ 1 & \text{otherwise} \end{cases} i = 1, 2, 3 \end{split} \label{3DIDCTMainFormulaDetail} \end{equation} The experimental implementation
{ "domain": "codereview.stackexchange", "id": 42695, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, template, c++20", "url": null }
c++, algorithm, template, c++20 non-static idct3_detail template function implementation: template<std::floating_point ElementT = double, std::floating_point OutputT = ElementT> Image<OutputT> idct3_detail(const std::vector<Image<ElementT>>& input, const std::size_t plane_index) { auto N1 = static_cast<OutputT>(input[0].getWidth()); auto N2 = static_cast<OutputT>(input[0].getHeight()); auto N3 = input.size(); auto output = Image<OutputT>(input[plane_index].getWidth(), input[plane_index].getHeight()); for (std::size_t y = 0; y < output.getHeight(); ++y) { for (std::size_t x = 0; x < output.getWidth(); ++x) { OutputT sum{}; for (std::size_t inner_z = 0; inner_z < N3; ++inner_z) { auto plane = input[inner_z]; for (std::size_t inner_y = 0; inner_y < plane.getHeight(); ++inner_y) { for (std::size_t inner_x = 0; inner_x < plane.getWidth(); ++inner_x) { auto l1 = (std::numbers::pi_v<OutputT> / (2 * N1) * (2 * x + 1) * static_cast<OutputT>(inner_x)); auto l2 = (std::numbers::pi_v<OutputT> / (2 * N2) * (2 * y + 1) * static_cast<OutputT>(inner_y)); auto l3 = (std::numbers::pi_v<OutputT> / (2 * static_cast<OutputT>(N3)) * (2 * static_cast<OutputT>(plane_index) + 1) * static_cast<OutputT>(inner_z)); OutputT alpha1 = (inner_x == 0) ? (std::numbers::sqrt2_v<OutputT> / 2) : (OutputT{1.0}); OutputT alpha2 = (inner_y == 0) ? (std::numbers::sqrt2_v<OutputT> / 2) : (OutputT{1.0}); OutputT alpha3 = (inner_z == 0) ? (std::numbers::sqrt2_v<OutputT> / 2) : (OutputT{1.0}); sum += alpha1 * alpha2 * alpha3 * static_cast<OutputT>(plane.at(inner_x, inner_y)) * std::cos(l1) * std::cos(l2) * std::cos(l3); } } }
{ "domain": "codereview.stackexchange", "id": 42695, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, template, c++20", "url": null }
c++, algorithm, template, c++20 } } } output.at(x, y) = sum; } } return output; }
{ "domain": "codereview.stackexchange", "id": 42695, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, template, c++20", "url": null }
c++, algorithm, template, c++20 non-static idct3 template function implementation: template<std::floating_point ElementT = double, std::floating_point OutputT = ElementT> std::vector<Image<OutputT>> idct3(const std::vector<Image<ElementT>>& input) { std::vector<Image<OutputT>> output; output.resize(input.size()); for (std::size_t i = 0; i < input.size(); ++i) { output[i] = idct3_detail<ElementT, OutputT>(input, i); } return output; } The updated version dct3_detail template function implementation: static keyword removed const std::size_t type plane_index parameter Update input parameter with type const std::vector<Image<ElementT>>&. Use OutputT template parameter in output type. Use std::numbers::pi_v<OutputT> instead of using std::numbers::pi About the suggestion of swapping ElementT and OutputT template parameters, I want to make OutputT follows the input ElementT if it isn't specified, i.e. std::floating_point OutputT = ElementT. This makes OutputT needs to be placed after ElementT. As far as I know, template<std::floating_point OutputT = ElementT, std::floating_point ElementT = double> this way doesn't work because ElementT hasn't been declared, it can't be assigned as the default value to OutputT. About the following suggestion: It seems that you don't really access input in dct3_detail except as input[plane_index]. The only exception is input[0].getWidth(), but it appears that the result is required to be independent of the index anyway, right? If so, don't pass input and plane_index to dct3_detail. Just pass the element you currently want to use as a reference: constexpr Image<OutputT> dct3_detail(const Image<ElementT>& input_element) { // input[plane_index] -> input_element // input[0] -> input_element } //... for (auto& input_element : input) { output.push_back(dct3_detail(input_element)); }
{ "domain": "codereview.stackexchange", "id": 42695, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, template, c++20", "url": null }
c++, algorithm, template, c++20 //... for (auto& input_element : input) { output.push_back(dct3_detail(input_element)); } As far as I know, for calculating each output element in 3D DCT cube, the full input 3D DCT cube would be used. From the mathematics aspect, as the formula presented: \begin{equation} \begin{split} {X(k_{1}, k_{2}, k_{3})} = {\frac {8}{N_{1} N_{2} N_{3}}} \epsilon_{k_{1}} \epsilon_{k_{2}} \epsilon_{k_{3}} \sum_{{n_1 = 0}}^{N_1 - 1} \sum_{{n_2 = 0}}^{N_2 - 1} \sum_{{n_3 = 0}}^{N_3 - 1} x(n_{1}, n_{2}, n_{3}) \\ \times \cos({\frac {\pi}{2N_{1}} (2n_{1} + 1)k_{1}}) \\ \times \cos({\frac {\pi}{2N_{2}} (2n_{2} + 1)k_{2}}) \\ \times \cos({\frac {\pi}{2N_{3}} (2n_{3} + 1)k_{3}}) \end{split} \label{eq:3DDCTMainFormula} \end{equation} The term $${X(k_{1}, k_{2}, k_{3})}$$ represents each element in the transformed output from 3D DCT calculation. From the aspect of programming, there is input[inner_z] used in the inner loops. The whole transformed output can be constructed by planes. dct3_detail template function plays the role of calculating each output plane. By the way, if the dimension of input DCT cube is large, dct3 may take long execution time. Instead of continuous computation, each plane can be calculated (saved) separately with dct3_detail function. If there is any misunderstanding, please let me know.
{ "domain": "codereview.stackexchange", "id": 42695, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, template, c++20", "url": null }
c++, algorithm, template, c++20 template<std::floating_point ElementT = double, std::floating_point OutputT = ElementT> Image<OutputT> dct3_detail(const std::vector<Image<ElementT>>& input, const std::size_t plane_index) { auto N1 = static_cast<OutputT>(input[0].getWidth()); auto N2 = static_cast<OutputT>(input[0].getHeight()); auto N3 = input.size(); auto alpha1 = (plane_index == 0) ? (std::numbers::sqrt2_v<OutputT> / 2) : (OutputT{1.0}); auto output = Image<OutputT>(input[plane_index].getWidth(), input[plane_index].getHeight()); for (std::size_t y = 0; y < output.getHeight(); ++y) { OutputT alpha2 = (y == 0) ? (std::numbers::sqrt2_v<OutputT> / 2) : (OutputT{1.0}); for (std::size_t x = 0; x < output.getWidth(); ++x) { OutputT sum{}; OutputT alpha3 = (x == 0) ? (std::numbers::sqrt2_v<OutputT> / 2) : (OutputT{1.0}); for (std::size_t inner_z = 0; inner_z < N3; ++inner_z) { auto plane = input[inner_z]; for (std::size_t inner_y = 0; inner_y < plane.getHeight(); ++inner_y) { for (std::size_t inner_x = 0; inner_x < plane.getWidth(); ++inner_x) { auto l1 = (std::numbers::pi_v<OutputT> / (2 * N1) * (2 * static_cast<OutputT>(inner_x) + 1) * x); auto l2 = (std::numbers::pi_v<OutputT> / (2 * N2) * (2 * static_cast<OutputT>(inner_y) + 1) * y); auto l3 = (std::numbers::pi_v<OutputT> / (2 * static_cast<OutputT>(N3)) * (2 * static_cast<OutputT>(inner_z) + 1) * static_cast<OutputT>(plane_index)); sum += static_cast<OutputT>(plane.at(inner_x, inner_y)) * std::cos(l1) * std::cos(l2) * std::cos(l3); } } } output.at(x, y) = 8 * alpha1 * alpha2 * alpha3 * sum / (N1 * N2 * N3); } } return output; }
{ "domain": "codereview.stackexchange", "id": 42695, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, template, c++20", "url": null }
c++, algorithm, template, c++20 The updated version dct3 template function implementation: static keyword removed Update input parameter with type const std::vector<Image<ElementT>>&. Use OutputT template parameter in output type. template<std::floating_point ElementT = double, std::floating_point OutputT = ElementT> std::vector<Image<OutputT>> dct3(const std::vector<Image<ElementT>>& input) { std::vector<Image<OutputT>> output; output.resize(input.size()); for (std::size_t i = 0; i < input.size(); ++i) { output[i] = dct3_detail<ElementT, OutputT>(input, i); } return output; } Full Testing Code The full tests for dct3 and idct3 template functions: #include <algorithm> #include <array> #include <cassert> #include <chrono> #include <cmath> #include <concepts> #include <exception> #include <execution> #include <fstream> #include <functional> #include <iostream> #include <iterator> #include <numbers> #include <numeric> #include <ranges> #include <string> #include <type_traits> #include <utility> #include <vector> using BYTE = unsigned char; struct RGB { BYTE channels[3]; }; using GrayScale = BYTE; namespace TinyDIP { #define is_size_same(x, y) {assert(x.getWidth() == y.getWidth()); assert(x.getHeight() == y.getHeight());} // Reference: https://stackoverflow.com/a/58067611/6667035 template <typename T> concept arithmetic = std::is_arithmetic_v<T>; // recursive_depth function implementation template<typename T> constexpr std::size_t recursive_depth() { return 0; } template<std::ranges::input_range Range> constexpr std::size_t recursive_depth() { return recursive_depth<std::ranges::range_value_t<Range>>() + 1; } // recursive_invoke_result_t implementation template<std::size_t, typename, typename> struct recursive_invoke_result { }; template<typename T, typename F> struct recursive_invoke_result<0, F, T> { using type = std::invoke_result_t<F, T>; };
{ "domain": "codereview.stackexchange", "id": 42695, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, template, c++20", "url": null }
c++, algorithm, template, c++20 template<std::size_t unwrap_level, typename F, template<typename...> typename Container, typename... Ts> requires (std::ranges::input_range<Container<Ts...>> && requires { typename recursive_invoke_result<unwrap_level - 1, F, std::ranges::range_value_t<Container<Ts...>>>::type; }) struct recursive_invoke_result<unwrap_level, F, Container<Ts...>> { using type = Container<typename recursive_invoke_result<unwrap_level - 1, F, std::ranges::range_value_t<Container<Ts...>>>::type>; }; template<std::size_t unwrap_level, typename F, typename T> using recursive_invoke_result_t = typename recursive_invoke_result<unwrap_level, F, T>::type; // recursive_variadic_invoke_result_t implementation template<std::size_t, typename, typename, typename...> struct recursive_variadic_invoke_result { }; template<typename F, class...Ts1, template<class...>class Container1, typename... Ts> struct recursive_variadic_invoke_result<1, F, Container1<Ts1...>, Ts...> { using type = Container1<std::invoke_result_t<F, std::ranges::range_value_t<Container1<Ts1...>>, std::ranges::range_value_t<Ts>...>>; };
{ "domain": "codereview.stackexchange", "id": 42695, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, template, c++20", "url": null }
c++, algorithm, template, c++20 template<std::size_t unwrap_level, typename F, class...Ts1, template<class...>class Container1, typename... Ts> requires ( std::ranges::input_range<Container1<Ts1...>> && requires { typename recursive_variadic_invoke_result< unwrap_level - 1, F, std::ranges::range_value_t<Container1<Ts1...>>, std::ranges::range_value_t<Ts>...>::type; }) // The rest arguments are ranges struct recursive_variadic_invoke_result<unwrap_level, F, Container1<Ts1...>, Ts...> { using type = Container1< typename recursive_variadic_invoke_result< unwrap_level - 1, F, std::ranges::range_value_t<Container1<Ts1...>>, std::ranges::range_value_t<Ts>... >::type>; }; template<std::size_t unwrap_level, typename F, typename T1, typename... Ts> using recursive_variadic_invoke_result_t = typename recursive_variadic_invoke_result<unwrap_level, F, T1, Ts...>::type; template<typename OutputIt, typename NAryOperation, typename InputIt, typename... InputIts> OutputIt transform(OutputIt d_first, NAryOperation op, InputIt first, InputIt last, InputIts... rest) { while (first != last) { *d_first++ = op(*first++, (*rest++)...); } return d_first; }
{ "domain": "codereview.stackexchange", "id": 42695, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, template, c++20", "url": null }
c++, algorithm, template, c++20 // recursive_transform for the multiple parameters cases (the version with unwrap_level) template<std::size_t unwrap_level = 1, class F, class Arg1, class... Args> constexpr auto recursive_transform(const F& f, const Arg1& arg1, const Args&... args) { if constexpr (unwrap_level > 0) { static_assert(unwrap_level <= recursive_depth<Arg1>(), "unwrap level higher than recursion depth of input"); recursive_variadic_invoke_result_t<unwrap_level, F, Arg1, Args...> output{}; transform( std::inserter(output, std::ranges::end(output)), [&f](auto&& element1, auto&&... elements) { return recursive_transform<unwrap_level - 1>(f, element1, elements...); }, std::ranges::cbegin(arg1), std::ranges::cend(arg1), std::ranges::cbegin(args)... ); return output; } else { return f(arg1, args...); } } template <typename ElementT> class Image { public: Image() = default; Image(const std::size_t width, const std::size_t height): width(width), height(height), image_data(width * height) { } Image(const std::size_t width, const std::size_t height, const ElementT initVal): width(width), height(height), image_data(width * height, initVal) {} Image(std::vector<ElementT> input, std::size_t newWidth, std::size_t newHeight): width(newWidth), height(newHeight) { if (input.size() != newWidth * newHeight) { throw std::runtime_error("Image data input and the given size are mismatched!"); } image_data = std::move(input); }
{ "domain": "codereview.stackexchange", "id": 42695, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, template, c++20", "url": null }
c++, algorithm, template, c++20 constexpr ElementT& at(const unsigned int x, const unsigned int y) { checkBoundary(x, y); return image_data[y * width + x]; } constexpr ElementT const& at(const unsigned int x, const unsigned int y) const { checkBoundary(x, y); return image_data[y * width + x]; } constexpr std::size_t getWidth() const { return width; } constexpr std::size_t getHeight() const noexcept { return height; } constexpr auto getSize() noexcept { return std::make_tuple(width, height); } std::vector<ElementT> const& getImageData() const { return image_data; } // expose the internal data void print(std::string separator = "\t", std::ostream& os = std::cout) const { for (std::size_t y = 0; y < height; ++y) { for (std::size_t x = 0; x < width; ++x) { // Ref: https://isocpp.org/wiki/faq/input-output#print-char-or-ptr-as-number os << +at(x, y) << separator; } os << "\n"; } os << "\n"; return; }
{ "domain": "codereview.stackexchange", "id": 42695, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, template, c++20", "url": null }
c++, algorithm, template, c++20 // Enable this function if ElementT = RGB void print(std::string separator = "\t", std::ostream& os = std::cout) const requires(std::same_as<ElementT, RGB>) { for (std::size_t y = 0; y < height; ++y) { for (std::size_t x = 0; x < width; ++x) { os << "( "; for (std::size_t channel_index = 0; channel_index < 3; ++channel_index) { // Ref: https://isocpp.org/wiki/faq/input-output#print-char-or-ptr-as-number os << +at(x, y).channels[channel_index] << separator; } os << ")" << separator; } os << "\n"; } os << "\n"; return; } friend std::ostream& operator<<(std::ostream& os, const Image<ElementT>& rhs) { const std::string separator = "\t"; for (std::size_t y = 0; y < rhs.height; ++y) { for (std::size_t x = 0; x < rhs.width; ++x) { // Ref: https://isocpp.org/wiki/faq/input-output#print-char-or-ptr-as-number os << +rhs.at(x, y) << separator; } os << "\n"; } os << "\n"; return os; } Image<ElementT>& operator+=(const Image<ElementT>& rhs) { assert(rhs.width == this->width); assert(rhs.height == this->height); std::transform(std::ranges::cbegin(image_data), std::ranges::cend(image_data), std::ranges::cbegin(rhs.image_data), std::ranges::begin(image_data), std::plus<>{}); return *this; }
{ "domain": "codereview.stackexchange", "id": 42695, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, template, c++20", "url": null }
c++, algorithm, template, c++20 Image<ElementT>& operator-=(const Image<ElementT>& rhs) { assert(rhs.width == this->width); assert(rhs.height == this->height); std::transform(std::ranges::cbegin(image_data), std::ranges::cend(image_data), std::ranges::cbegin(rhs.image_data), std::ranges::begin(image_data), std::minus<>{}); return *this; } Image<ElementT>& operator*=(const Image<ElementT>& rhs) { assert(rhs.width == this->width); assert(rhs.height == this->height); std::transform(std::ranges::cbegin(image_data), std::ranges::cend(image_data), std::ranges::cbegin(rhs.image_data), std::ranges::begin(image_data), std::multiplies<>{}); return *this; } Image<ElementT>& operator/=(const Image<ElementT>& rhs) { assert(rhs.width == this->width); assert(rhs.height == this->height); std::transform(std::ranges::cbegin(image_data), std::ranges::cend(image_data), std::ranges::cbegin(rhs.image_data), std::ranges::begin(image_data), std::divides<>{}); return *this; } friend bool operator==(Image<ElementT> const&, Image<ElementT> const&) = default; friend bool operator!=(Image<ElementT> const&, Image<ElementT> const&) = default; friend Image<ElementT> operator+(Image<ElementT> input1, const Image<ElementT>& input2) { return input1 += input2; } friend Image<ElementT> operator-(Image<ElementT> input1, const Image<ElementT>& input2) { return input1 -= input2; } Image<ElementT>& operator=(Image<ElementT> const& input) = default; // Copy Assign Image<ElementT>& operator=(Image<ElementT>&& other) = default; // Move Assign Image(const Image<ElementT> &input) = default; // Copy Constructor
{ "domain": "codereview.stackexchange", "id": 42695, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, template, c++20", "url": null }
c++, algorithm, template, c++20 Image(const Image<ElementT> &input) = default; // Copy Constructor Image(Image<ElementT> &&input) = default; // Move Constructor private: std::size_t width; std::size_t height; std::vector<ElementT> image_data; void checkBoundary(const size_t x, const size_t y) const { assert(x < width); assert(y < height); } };
{ "domain": "codereview.stackexchange", "id": 42695, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, template, c++20", "url": null }
c++, algorithm, template, c++20 template<std::floating_point ElementT = double, std::floating_point OutputT = ElementT> Image<OutputT> dct3_detail(const std::vector<Image<ElementT>>& input, const std::size_t plane_index) { auto N1 = static_cast<OutputT>(input[0].getWidth()); auto N2 = static_cast<OutputT>(input[0].getHeight()); auto N3 = input.size(); auto alpha1 = (plane_index == 0) ? (std::numbers::sqrt2_v<OutputT> / 2) : (OutputT{1.0}); auto output = Image<OutputT>(input[plane_index].getWidth(), input[plane_index].getHeight()); for (std::size_t y = 0; y < output.getHeight(); ++y) { OutputT alpha2 = (y == 0) ? (std::numbers::sqrt2_v<OutputT> / 2) : (OutputT{1.0}); for (std::size_t x = 0; x < output.getWidth(); ++x) { OutputT sum{}; OutputT alpha3 = (x == 0) ? (std::numbers::sqrt2_v<OutputT> / 2) : (OutputT{1.0}); for (std::size_t inner_z = 0; inner_z < N3; ++inner_z) { auto plane = input[inner_z]; for (std::size_t inner_y = 0; inner_y < plane.getHeight(); ++inner_y) { for (std::size_t inner_x = 0; inner_x < plane.getWidth(); ++inner_x) { auto l1 = (std::numbers::pi_v<OutputT> / (2 * N1) * (2 * static_cast<OutputT>(inner_x) + 1) * x); auto l2 = (std::numbers::pi_v<OutputT> / (2 * N2) * (2 * static_cast<OutputT>(inner_y) + 1) * y); auto l3 = (std::numbers::pi_v<OutputT> / (2 * static_cast<OutputT>(N3)) * (2 * static_cast<OutputT>(inner_z) + 1) * static_cast<OutputT>(plane_index)); sum += static_cast<OutputT>(plane.at(inner_x, inner_y)) * std::cos(l1) * std::cos(l2) * std::cos(l3); } } }
{ "domain": "codereview.stackexchange", "id": 42695, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, template, c++20", "url": null }
c++, algorithm, template, c++20 } } } output.at(x, y) = 8 * alpha1 * alpha2 * alpha3 * sum / (N1 * N2 * N3); } } return output; }
{ "domain": "codereview.stackexchange", "id": 42695, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, template, c++20", "url": null }
c++, algorithm, template, c++20 template<std::floating_point ElementT = double, std::floating_point OutputT = ElementT> std::vector<Image<OutputT>> dct3(const std::vector<Image<ElementT>>& input) { std::vector<Image<OutputT>> output; output.resize(input.size()); for (std::size_t i = 0; i < input.size(); ++i) { output[i] = dct3_detail<ElementT, OutputT>(input, i); } return output; }
{ "domain": "codereview.stackexchange", "id": 42695, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, template, c++20", "url": null }
c++, algorithm, template, c++20 template<std::floating_point ElementT = double, std::floating_point OutputT = ElementT> Image<OutputT> idct3_detail(const std::vector<Image<ElementT>>& input, const std::size_t plane_index) { auto N1 = static_cast<OutputT>(input[0].getWidth()); auto N2 = static_cast<OutputT>(input[0].getHeight()); auto N3 = input.size(); auto output = Image<OutputT>(input[plane_index].getWidth(), input[plane_index].getHeight()); for (std::size_t y = 0; y < output.getHeight(); ++y) { for (std::size_t x = 0; x < output.getWidth(); ++x) { OutputT sum{}; for (std::size_t inner_z = 0; inner_z < N3; ++inner_z) { auto plane = input[inner_z]; for (std::size_t inner_y = 0; inner_y < plane.getHeight(); ++inner_y) { for (std::size_t inner_x = 0; inner_x < plane.getWidth(); ++inner_x) { auto l1 = (std::numbers::pi_v<OutputT> / (2 * N1) * (2 * x + 1) * static_cast<OutputT>(inner_x)); auto l2 = (std::numbers::pi_v<OutputT> / (2 * N2) * (2 * y + 1) * static_cast<OutputT>(inner_y)); auto l3 = (std::numbers::pi_v<OutputT> / (2 * static_cast<OutputT>(N3)) * (2 * static_cast<OutputT>(plane_index) + 1) * static_cast<OutputT>(inner_z)); OutputT alpha1 = (inner_x == 0) ? (std::numbers::sqrt2_v<OutputT> / 2) : (OutputT{1.0}); OutputT alpha2 = (inner_y == 0) ? (std::numbers::sqrt2_v<OutputT> / 2) : (OutputT{1.0}); OutputT alpha3 = (inner_z == 0) ? (std::numbers::sqrt2_v<OutputT> / 2) : (OutputT{1.0}); sum += alpha1 * alpha2 * alpha3 * static_cast<OutputT>(plane.at(inner_x, inner_y)) * std::cos(l1) * std::cos(l2) * std::cos(l3);
{ "domain": "codereview.stackexchange", "id": 42695, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, template, c++20", "url": null }
c++, algorithm, template, c++20 std::cos(l1) * std::cos(l2) * std::cos(l3); } } } output.at(x, y) = sum; } } return output; }
{ "domain": "codereview.stackexchange", "id": 42695, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, template, c++20", "url": null }
c++, algorithm, template, c++20 template<std::floating_point ElementT = double, std::floating_point OutputT = ElementT> std::vector<Image<OutputT>> idct3(const std::vector<Image<ElementT>>& input) { std::vector<Image<OutputT>> output; output.resize(input.size()); for (std::size_t i = 0; i < input.size(); ++i) { output[i] = idct3_detail<ElementT, OutputT>(input, i); } return output; } } template<typename ElementT> void print3(std::vector<TinyDIP::Image<ElementT>> input) { for (std::size_t i = 0; i < input.size(); i++) { input[i].print(); std::cout << "*******************\n"; } } void idct3Test() { std::size_t N1 = 10, N2 = 10, N3 = 10; std::vector<TinyDIP::Image<double>> test_input; for (std::size_t z = 0; z < N3; z++) { test_input.push_back(TinyDIP::Image<double>(N1, N2)); } for (std::size_t z = 1; z <= N3; z++) { for (std::size_t y = 1; y <= N2; y++) { for (std::size_t x = 1; x <= N1; x++) { test_input[z - 1].at(y - 1, x - 1) = x * 100 + y * 10 + z; } } } print3(test_input); auto dct3_output = TinyDIP::dct3(test_input); print3(dct3_output); auto idct3_output = TinyDIP::idct3(dct3_output); print3(TinyDIP::recursive_transform( [](auto&& input1, auto&& input2) { return input1 - input2; }, idct3_output, test_input)); } int main() { auto start = std::chrono::system_clock::now(); idct3Test(); auto end = std::chrono::system_clock::now(); std::chrono::duration<double> elapsed_seconds = end - start; std::time_t end_time = std::chrono::system_clock::to_time_t(end); std::cout << "Computation finished at " << std::ctime(&end_time) << "elapsed time: " << elapsed_seconds.count() << '\n'; return 0; }
{ "domain": "codereview.stackexchange", "id": 42695, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, template, c++20", "url": null }
c++, algorithm, template, c++20 The output of the testing code above: 111 121 131 141 151 161 171 181 191 201 211 221 231 241 251 261 271 281 291 301 311 321 331 341 351 361 371 381 391 401 411 421 431 441 451 461 471 481 491 501 511 521 531 541 551 561 571 581 591 601 611 621 631 641 651 661 671 681 691 701 711 721 731 741 751 761 771 781 791 801 811 821 831 841 851 861 871 881 891 901 911 921 931 941 951 961 971 981 991 1001 1011 1021 1031 1041 1051 1061 1071 1081 1091 1101 ******************* 112 122 132 142 152 162 172 182 192 202 212 222 232 242 252 262 272 282 292 302 312 322 332 342 352 362 372 382 392 402 412 422 432 442 452 462 472 482 492 502 512 522 532 542 552 562 572 582 592 602 612 622 632 642 652 662 672 682 692 702 712 722 732 742 752 762 772 782 792 802 812 822 832 842 852 862 872 882 892 902 912 922 932 942 952 962 972 982 992 1002 1012 1022 1032 1042 1052 1062 1072 1082 1092 1102 ******************* 113 123 133 143 153 163 173 183 193 203 213 223 233 243 253 263 273 283 293 303 313 323 333 343 353 363 373 383 393 403 413 423 433 443 453 463 473 483 493 503 513 523 533 543 553 563 573 583 593 603 613 623 633 643 653 663 673 683 693 703 713 723 733 743 753 763 773 783 793 803 813 823 833 843 853 863 873 883 893 903 913 923 933 943 953 963 973 983 993 1003 1013 1023 1033 1043 1053 1063 1073 1083 1093 1103 ******************* 114 124 134 144 154 164 174 184 194 204 214 224 234 244 254 264 274 284 294 304 314 324 334 344 354 364 374 384 394 404 414 424 434 444 454 464 474 484 494 504 514 524 534 544 554 564 574 584 594 604 614 624 634 644 654 664 674 684 694 704 714 724 734 744 754 764 774 784 794 804 814 824 834 844 854 864 874 884 894 904 914 924 934 944 954 964 974 984 994 1004 1014 1024 1034 1044 1054 1064 1074 1084 1094 1104
{ "domain": "codereview.stackexchange", "id": 42695, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, template, c++20", "url": null }
c++, algorithm, template, c++20 ******************* 115 125 135 145 155 165 175 185 195 205 215 225 235 245 255 265 275 285 295 305 315 325 335 345 355 365 375 385 395 405 415 425 435 445 455 465 475 485 495 505 515 525 535 545 555 565 575 585 595 605 615 625 635 645 655 665 675 685 695 705 715 725 735 745 755 765 775 785 795 805 815 825 835 845 855 865 875 885 895 905 915 925 935 945 955 965 975 985 995 1005 1015 1025 1035 1045 1055 1065 1075 1085 1095 1105 ******************* 116 126 136 146 156 166 176 186 196 206 216 226 236 246 256 266 276 286 296 306 316 326 336 346 356 366 376 386 396 406 416 426 436 446 456 466 476 486 496 506 516 526 536 546 556 566 576 586 596 606 616 626 636 646 656 666 676 686 696 706 716 726 736 746 756 766 776 786 796 806 816 826 836 846 856 866 876 886 896 906 916 926 936 946 956 966 976 986 996 1006 1016 1026 1036 1046 1056 1066 1076 1086 1096 1106 ******************* 117 127 137 147 157 167 177 187 197 207 217 227 237 247 257 267 277 287 297 307 317 327 337 347 357 367 377 387 397 407 417 427 437 447 457 467 477 487 497 507 517 527 537 547 557 567 577 587 597 607 617 627 637 647 657 667 677 687 697 707 717 727 737 747 757 767 777 787 797 807 817 827 837 847 857 867 877 887 897 907 917 927 937 947 957 967 977 987 997 1007 1017 1027 1037 1047 1057 1067 1077 1087 1097 1107 ******************* 118 128 138 148 158 168 178 188 198 208 218 228 238 248 258 268 278 288 298 308 318 328 338 348 358 368 378 388 398 408 418 428 438 448 458 468 478 488 498 508 518 528 538 548 558 568 578 588 598 608 618 628 638 648 658 668 678 688 698 708 718 728 738 748 758 768 778 788 798 808 818 828 838 848 858 868 878 888 898 908 918 928 938 948 958 968 978 988 998 1008 1018 1028 1038 1048 1058 1068 1078 1088 1098 1108
{ "domain": "codereview.stackexchange", "id": 42695, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, template, c++20", "url": null }
c++, algorithm, template, c++20 ******************* 119 129 139 149 159 169 179 189 199 209 219 229 239 249 259 269 279 289 299 309 319 329 339 349 359 369 379 389 399 409 419 429 439 449 459 469 479 489 499 509 519 529 539 549 559 569 579 589 599 609 619 629 639 649 659 669 679 689 699 709 719 729 739 749 759 769 779 789 799 809 819 829 839 849 859 869 879 889 899 909 919 929 939 949 959 969 979 989 999 1009 1019 1029 1039 1049 1059 1069 1079 1089 1099 1109 ******************* 120 130 140 150 160 170 180 190 200 210 220 230 240 250 260 270 280 290 300 310 320 330 340 350 360 370 380 390 400 410 420 430 440 450 460 470 480 490 500 510 520 530 540 550 560 570 580 590 600 610 620 630 640 650 660 670 680 690 700 710 720 730 740 750 760 770 780 790 800 810 820 830 840 850 860 870 880 890 900 910 920 930 940 950 960 970 980 990 1000 1010 1020 1030 1040 1050 1060 1070 1080 1090 1100 1110
{ "domain": "codereview.stackexchange", "id": 42695, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, template, c++20", "url": null }
c++, algorithm, template, c++20 ******************* 1726.75 -80.7207 2.5284e-13 -8.64604 -7.77618e-14 -2.82843 1.59162e-13 -1.14371 -1.43473e-13 -0.320717 -807.207 2.57244e-14 -1.24763e-13 -1.00325e-13 4.82332e-14 -7.91025e-14 -9.83958e-14 1.62707e-13 5.91661e-14 6.73658e-14 3.81988e-13 -1.54346e-14 -1.28622e-14 -1.92933e-15 1.41484e-14 -3.85866e-15 -1.28622e-15 3.21555e-15 -5.46643e-15 8.84276e-15 -86.4604 -1.22191e-14 -4.50177e-15 -8.36043e-15 5.14488e-15 1.92933e-15 7.07421e-15 7.71732e-15 2.57244e-15 -2.41166e-15 -5.54792e-14 6.4311e-15 1.92933e-15 -1.28622e-15 -2.57244e-15 3.85866e-15 -4.50177e-15 7.71732e-15 -3.21555e-15 -2.21873e-14 -28.2843 -5.14488e-15 1.28622e-15 -4.50177e-15 3.21555e-15 -5.78799e-15 -7.39576e-15 9.9682e-15 -1.28622e-15 9.64665e-15 1.64164e-13 -7.71732e-15 4.50177e-15 2.57244e-14 -6.4311e-16 3.21555e-16 -1.28622e-15 3.85866e-15 -4.50177e-15 -3.85866e-15 -11.4371 2.18657e-14 -1.57562e-14 -3.21555e-15 1.60777e-15 1.70424e-14 -3.21555e-16 -4.66255e-15 -1.60777e-15 -9.56626e-15 -3.77668e-13 8.68198e-15 1.28622e-15 -5.78799e-15 -1.92933e-15 -1.447e-15 -5.14488e-15 2.73322e-15 2.81361e-15 1.00888e-14 -3.20717 5.30566e-15 8.03887e-16 5.30566e-15 -1.68816e-14 -3.5371e-15 -1.63993e-14 7.39576e-15 1.2822e-14 1.18171e-14
{ "domain": "codereview.stackexchange", "id": 42695, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, template, c++20", "url": null }
c++, algorithm, template, c++20 ******************* -8.07207 2.3152e-14 -7.71732e-15 -5.14488e-15 1.92933e-15 -6.4311e-16 -3.85866e-15 1.02898e-14 4.50177e-15 4.82332e-16 -2.4824e-13 5.45697e-15 -5.45697e-15 1.18234e-14 -9.09495e-16 8.18545e-15 0 -4.54747e-15 4.09273e-15 -3.86535e-15 -4.50177e-14 3.63798e-15 -1.81899e-15 6.36646e-15 1.81899e-15 6.36646e-15 3.63798e-15 -4.54747e-15 -4.54747e-15 -2.27374e-16 6.4311e-15 -9.09495e-16 0 1.81899e-15 -9.09495e-16 0 -8.18545e-15 1.81899e-15 -4.54747e-15 4.09273e-15 -1.54346e-14 -8.18545e-15 -1.81899e-15 -1.81899e-15 6.36646e-15 4.54747e-15 7.27596e-15 -1.81899e-15 -2.27374e-15 2.27374e-15 -6.4311e-16 4.54747e-15 -3.63798e-15 -2.72848e-15 8.18545e-15 4.54747e-15 -5.91172e-15 -2.27374e-15 -6.13909e-15 -5.00222e-15 1.02898e-14 6.36646e-15 1.81899e-15 -9.09495e-16 4.54747e-15 5.00222e-15 4.09273e-15 9.09495e-16 -2.27374e-16 8.6402e-15 -1.31838e-14 -9.09495e-16 5.45697e-15 -1.36424e-15 -9.09495e-16 -2.72848e-15 -5.91172e-15 5.68434e-15 6.13909e-15 -8.18545e-15 1.86502e-14 -5.00222e-15 -9.09495e-16 -4.54747e-16 -9.54969e-15 -4.77485e-15 -4.54747e-16 -9.09495e-16 5.00222e-15 3.41061e-15 1.63993e-14 5.68434e-15 -6.82121e-15 -9.09495e-16 -9.77707e-15 -7.04858e-15 2.95586e-15 2.95586e-15 1.02318e-15 1.39266e-15
{ "domain": "codereview.stackexchange", "id": 42695, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, template, c++20", "url": null }
c++, algorithm, template, c++20 ******************* 3.31056e-13 -5.14488e-15 -1.41484e-14 -9.64665e-15 1.28622e-14 -6.4311e-15 6.4311e-15 3.21555e-15 -4.18021e-15 1.12544e-15 -1.06756e-13 -1.09139e-14 -1.81899e-15 -9.09495e-16 -7.27596e-15 -9.09495e-16 -1.81899e-15 -4.54747e-15 4.54747e-15 -7.50333e-15 -4.1159e-14 5.45697e-15 -3.63798e-15 -1.81899e-15 -5.45697e-15 -4.54747e-15 2.72848e-15 -2.27374e-15 9.09495e-16 -2.72848e-15 -5.14488e-15 -1.45519e-14 -7.27596e-15 -9.09495e-16 -2.72848e-15 9.09495e-15 0 -2.72848e-15 -9.09495e-16 -1.11413e-14 -3.21555e-15 3.63798e-15 1.00044e-14 -3.63798e-15 -4.54747e-15 -8.18545e-15 -4.54747e-15 -3.18323e-15 3.18323e-15 -5.22959e-15 -1.41484e-14 6.36646e-15 0 9.09495e-16 -1.81899e-15 -8.18545e-15 -2.27374e-15 -7.7307e-15 1.59162e-15 -8.6402e-15 1.92933e-14 1.81899e-15 -2.72848e-15 -1.81899e-15 2.27374e-15 -7.27596e-15 -2.72848e-15 2.27374e-15 1.81899e-15 3.18323e-15 1.60777e-15 -9.09495e-16 4.54747e-15 2.27374e-15 0 5.91172e-15 -2.72848e-15 2.04636e-15 3.18323e-15 -5.91172e-15 -1.54346e-14 3.18323e-15 -1.36424e-15 4.54747e-16 1.22782e-14 -4.3201e-15 8.41283e-15 0 -1.13687e-15 6.82121e-16 -6.27032e-15 -4.54747e-16 6.82121e-16 -4.54747e-16 2.27374e-16 -2.38742e-15 -1.13687e-15 2.04636e-15 -6.82121e-16 -6.16751e-15
{ "domain": "codereview.stackexchange", "id": 42695, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, template, c++20", "url": null }
c++, algorithm, template, c++20 ******************* -0.864604 -9.64665e-15 6.4311e-16 7.07421e-15 0 -7.07421e-15 1.35053e-14 -3.85866e-15 -6.4311e-16 -2.41166e-15 -2.71392e-13 -8.18545e-15 -3.63798e-15 3.63798e-15 -8.18545e-15 -1.09139e-14 2.72848e-15 -3.63798e-15 -9.09495e-16 7.7307e-15 -5.14488e-15 0 -9.09495e-15 -4.54747e-15 -2.72848e-15 -5.45697e-15 -2.72848e-15 -3.63798e-15 -6.36646e-15 -2.27374e-16 -4.6947e-14 0 5.45697e-15 -4.54747e-15 -9.09495e-16 2.72848e-15 -4.54747e-15 -1.36424e-15 6.36646e-15 -1.18234e-14 1.09329e-14 -8.18545e-15 5.45697e-15 -2.72848e-15 9.09495e-16 8.18545e-15 -1.09139e-14 3.18323e-15 2.27374e-15 5.45697e-15 1.54346e-14 -1.81899e-15 -9.09495e-16 2.72848e-15 4.54747e-15 -2.72848e-15 -6.36646e-15 3.63798e-15 9.09495e-16 3.86535e-15 5.78799e-15 -9.09495e-15 -7.27596e-15 -9.09495e-16 -3.63798e-15 4.54747e-15 1.22782e-14 -1.36424e-15 -2.27374e-16 5.68434e-16 -1.28622e-14 5.45697e-15 5.91172e-15 6.82121e-15 -6.36646e-15 2.27374e-15 -2.27374e-15 1.36424e-15 3.86535e-15 2.6148e-15 -5.46643e-15 2.72848e-15 -4.54747e-15 4.54747e-15 -2.04636e-15 -1.81899e-15 3.86535e-15 2.72848e-15 1.13687e-15 -1.47793e-15 -1.78463e-14 8.6402e-15 -2.04636e-15 -2.27374e-15 1.28466e-14 2.38742e-15 -3.41061e-16 -1.02318e-15 -2.04636e-15 -9.37916e-16
{ "domain": "codereview.stackexchange", "id": 42695, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, template, c++20", "url": null }
c++, algorithm, template, c++20 ******************* -4.09273e-14 1.1576e-14 1.09329e-14 3.85866e-15 -3.85866e-15 3.85866e-15 6.4311e-15 1.1576e-14 -5.14488e-15 -9.32509e-15 -5.14488e-15 -6.36646e-15 -1.81899e-15 0 -4.54747e-15 -4.54747e-15 0 -5.45697e-15 -5.00222e-15 2.27374e-15 -2.37951e-14 0 9.09495e-16 -3.63798e-15 -1.00044e-14 -9.09495e-16 3.63798e-15 5.91172e-15 5.00222e-15 -1.25056e-14 6.4311e-16 9.09495e-16 7.27596e-15 -9.09495e-16 4.54747e-15 8.18545e-15 -1.63709e-14 5.00222e-15 -4.54747e-16 1.81899e-15 -1.02898e-14 -4.54747e-15 -5.45697e-15 3.63798e-15 2.72848e-15 -1.81899e-15 1.09139e-14 -8.18545e-15 4.3201e-15 5.22959e-15 -2.25088e-14 -1.81899e-15 -8.18545e-15 0 1.81899e-15 1.81899e-15 1.36424e-15 1.81899e-15 9.09495e-16 1.13687e-15 1.80071e-14 -3.63798e-15 -5.00222e-15 9.09495e-16 5.45697e-15 6.82121e-15 -4.54747e-15 -9.54969e-15 3.86535e-15 -2.27374e-15 -1.38269e-14 9.09495e-16 -3.63798e-15 -2.72848e-15 -1.81899e-15 2.72848e-15 -3.86535e-15 -1.81899e-15 -3.29692e-15 -7.56017e-15 -2.95831e-14 5.45697e-15 -2.27374e-15 2.50111e-15 -1.36424e-15 1.11413e-14 9.54969e-15 5.34328e-15 -1.02318e-15 -1.04023e-14 -1.09329e-14 -1.59162e-15 -9.09495e-16 -1.10276e-14 4.20641e-15 6.36646e-15 3.86535e-15 1.59162e-15 -7.04858e-15 1.29319e-14
{ "domain": "codereview.stackexchange", "id": 42695, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, template, c++20", "url": null }
c++, algorithm, template, c++20 ******************* -0.282843 -9.00354e-15 -7.71732e-15 -3.21555e-15 9.64665e-15 -5.78799e-15 2.25088e-15 3.5371e-15 -1.92933e-15 4.50177e-15 -1.08686e-13 2.72848e-15 -5.45697e-15 8.18545e-15 8.18545e-15 9.09495e-16 -4.54747e-16 3.18323e-15 -5.22959e-15 4.54747e-16 4.75901e-14 -4.54747e-15 3.63798e-15 -9.09495e-16 0 -6.36646e-15 8.6402e-15 -1.81899e-15 -2.95586e-15 -8.6402e-15 -3.08693e-14 -1.81899e-15 2.72848e-15 -9.09495e-16 1.00044e-14 0 6.36646e-15 -9.09495e-16 -1.36424e-15 1.29603e-14 3.21555e-15 -1.81899e-15 2.72848e-15 1.81899e-15 3.63798e-15 0 2.27374e-15 -3.63798e-15 0 -6.13909e-15 -3.47279e-14 -1.81899e-15 -5.45697e-15 0 9.09495e-16 5.00222e-15 4.54747e-16 1.13687e-15 -5.22959e-15 2.16005e-15 -2.57244e-15 -2.27374e-15 5.00222e-15 5.45697e-15 2.27374e-15 7.27596e-15 9.09495e-16 -8.6402e-15 -9.09495e-16 -1.20508e-14 -1.41484e-14 3.18323e-15 -5.91172e-15 4.54747e-16 8.18545e-15 -3.18323e-15 -2.27374e-16 -4.3201e-15 3.29692e-15 -1.81899e-15 4.82332e-16 2.72848e-15 -1.13687e-14 5.22959e-15 6.13909e-15 4.09273e-15 5.00222e-15 -1.7053e-15 -2.38742e-15 1.47793e-15 6.4311e-15 7.61702e-15 2.16005e-15 -4.54747e-16 2.27374e-16 -6.36646e-15 2.95586e-15 0 3.9222e-15 9.6918e-15
{ "domain": "codereview.stackexchange", "id": 42695, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, template, c++20", "url": null }
c++, algorithm, template, c++20 ******************* 1.64164e-13 -1.54346e-14 3.21555e-15 1.41484e-14 -3.21555e-15 5.46643e-15 -5.14488e-15 -1.28622e-15 -7.07421e-15 0 -1.02898e-14 1.00044e-14 5.45697e-15 0 -7.27596e-15 -7.7307e-15 4.09273e-15 -4.54747e-15 2.95586e-15 1.59162e-14 3.85866e-15 1.09139e-14 6.36646e-15 9.09495e-16 4.09273e-15 -3.63798e-15 9.09495e-16 4.54747e-16 9.09495e-16 1.36424e-15 2.12226e-14 -3.63798e-15 1.81899e-15 -3.63798e-15 -1.00044e-14 -2.72848e-15 5.91172e-15 -3.63798e-15 5.68434e-15 1.87583e-14 -4.88764e-14 3.63798e-15 -7.7307e-15 -5.45697e-15 -1.09139e-14 -9.54969e-15 -2.72848e-15 -7.7307e-15 9.32232e-15 -4.09273e-15 -7.71732e-15 8.6402e-15 -9.54969e-15 -3.63798e-15 -8.6402e-15 -9.09495e-16 -9.09495e-16 -2.27374e-16 3.18323e-15 -4.77485e-15 -2.57244e-15 5.91172e-15 -7.7307e-15 2.27374e-15 -5.91172e-15 5.91172e-15 -2.04636e-15 1.81899e-15 4.20641e-15 -5.85487e-15 -2.89399e-15 -1.36424e-15 5.91172e-15 -7.7307e-15 7.50333e-15 -1.13687e-15 4.54747e-16 -1.81899e-15 6.36646e-15 -1.20508e-14 -5.94877e-15 1.13687e-15 -6.82121e-16 9.54969e-15 2.72848e-15 5.91172e-15 -3.86535e-15 7.95808e-16 -2.04636e-15 -4.20641e-15 -2.06599e-14 -6.48015e-15 4.3201e-15 3.97904e-15 2.72848e-15 -3.63798e-15 7.7307e-15 -5.68434e-17 2.70006e-15 6.96332e-15
{ "domain": "codereview.stackexchange", "id": 42695, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, template, c++20", "url": null }
c++, algorithm, template, c++20 ******************* -0.114371 2.44382e-14 -3.21555e-16 -8.36043e-15 7.39576e-15 8.68198e-15 -4.50177e-15 -1.60777e-16 -1.92933e-15 -1.21387e-14 2.08046e-13 -1.00044e-14 1.81899e-15 2.27374e-15 1.81899e-15 -4.54747e-15 -4.54747e-15 5.68434e-15 7.04858e-15 1.00044e-14 -4.9841e-14 -2.72848e-15 9.09495e-15 9.09495e-16 -6.36646e-15 4.54747e-16 5.45697e-15 1.81899e-15 4.54747e-16 8.6402e-15 3.85866e-14 5.45697e-15 -4.54747e-16 -4.09273e-15 -3.63798e-15 2.27374e-15 -5.00222e-15 -9.09495e-16 1.13687e-15 -1.37561e-14 6.75265e-15 -2.72848e-15 -3.63798e-15 3.63798e-15 -9.09495e-16 -9.09495e-16 -2.04636e-15 1.13687e-15 2.6148e-15 1.53477e-15 1.1576e-14 -4.09273e-15 -7.7307e-15 5.45697e-15 3.63798e-15 9.09495e-16 -2.95586e-15 2.50111e-15 -2.16005e-15 -1.00044e-14 -1.06113e-14 5.91172e-15 6.82121e-15 -9.54969e-15 3.86535e-15 -1.13687e-15 9.09495e-15 -3.86535e-15 8.6402e-15 5.22959e-15 -8.52121e-15 3.63798e-15 2.04636e-15 4.77485e-15 -3.18323e-15 1.59162e-15 -2.72848e-15 7.04858e-15 -5.22959e-15 1.33014e-14 8.03887e-15 -5.22959e-15 5.00222e-15 -1.13687e-15 -2.72848e-15 1.19371e-14 -4.66116e-15 -7.95808e-16 7.21911e-15 -6.39488e-15 -8.03887e-16 -8.07177e-15 2.27374e-15 5.68434e-16 -3.63798e-15 6.13909e-15 -9.09495e-16 8.69704e-15 -2.84217e-15 8.14282e-15
{ "domain": "codereview.stackexchange", "id": 42695, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, template, c++20", "url": null }
c++, algorithm, template, c++20 ******************* -6.29825e-14 8.03887e-15 -8.36043e-15 -3.5371e-15 -6.4311e-15 4.34099e-15 -1.02898e-14 -6.4311e-16 -3.45672e-15 2.23079e-14 6.75265e-14 7.7307e-15 -9.09495e-16 4.54747e-16 5.91172e-15 3.86535e-15 -8.6402e-15 6.82121e-15 -9.09495e-16 6.13909e-15 -4.1159e-14 3.18323e-15 2.27374e-15 -2.27374e-15 9.54969e-15 -1.59162e-15 -4.3201e-15 2.50111e-15 1.36424e-15 5.22959e-15 2.25088e-15 -1.00044e-14 -4.54747e-15 2.72848e-15 5.22959e-15 -7.27596e-15 9.32232e-15 -1.13687e-15 4.54747e-16 -1.47793e-15 -1.67209e-14 -2.72848e-15 1.81899e-15 2.50111e-15 6.82121e-15 5.68434e-15 -1.59162e-15 1.93268e-15 -2.16005e-15 -1.67688e-14 -4.66255e-15 6.36646e-15 4.54747e-15 1.59162e-15 7.95808e-15 -4.54747e-15 4.54747e-16 -2.50111e-15 -3.41061e-16 -9.43601e-15 -7.23499e-15 7.04858e-15 9.32232e-15 -4.54747e-16 6.36646e-15 -1.04592e-14 7.50333e-15 8.07177e-15 -6.59384e-15 1.25056e-15 2.47597e-14 1.38698e-14 -5.45697e-15 2.50111e-15 -6.82121e-16 1.28466e-14 -1.47793e-15 -3.75167e-15 3.12639e-15 -1.84741e-15 1.96952e-14 -5.45697e-15 -3.75167e-15 -1.09139e-14 -3.63798e-15 -3.18323e-15 -1.00613e-14 -4.77485e-15 2.04636e-15 1.6172e-14 9.36529e-15 9.09495e-16 3.52429e-15 4.66116e-15 -1.3415e-14 -1.02318e-14 -3.78009e-15 1.90425e-15 7.24754e-15 -1.09424e-14
{ "domain": "codereview.stackexchange", "id": 42695, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, template, c++20", "url": null }
c++, algorithm, template, c++20 ******************* -0.0320717 1.43092e-14 4.34099e-15 6.27032e-15 -9.80743e-15 8.36043e-15 -5.94877e-15 -4.90371e-15 1.25004e-14 1.95345e-14 5.75583e-14 -7.04858e-15 4.54747e-16 4.54747e-15 3.86535e-15 -1.13687e-14 6.59384e-15 2.95586e-15 -9.09495e-16 4.83169e-16 1.94541e-14 -1.81899e-15 -5.22959e-15 0 3.41061e-15 -3.97904e-15 -3.18323e-15 -1.59162e-15 4.54747e-16 -6.62226e-15 -1.12544e-15 -2.27374e-15 -2.95586e-15 5.00222e-15 3.97904e-15 -1.02318e-15 1.7053e-15 -4.20641e-15 -1.36424e-15 3.60956e-15 1.92933e-15 -1.13687e-15 9.09495e-16 -1.93268e-15 9.89075e-15 -1.31877e-14 1.13687e-15 6.82121e-15 -7.50333e-15 -1.02602e-14 -9.00354e-15 4.20641e-15 8.98126e-15 -4.09273e-15 -1.13687e-15 2.04636e-15 1.81899e-15 4.54747e-15 -1.53477e-15 8.78231e-15 -1.80875e-14 -4.20641e-15 5.91172e-15 6.25278e-15 8.18545e-15 6.82121e-16 3.97904e-15 -2.84217e-16 -8.78231e-15 4.23483e-15 -1.17368e-14 4.66116e-15 5.45697e-15 -6.0254e-15 -1.36424e-15 2.50111e-15 6.82121e-16 5.74119e-15 1.93268e-15 4.50484e-15 4.22041e-15 1.93268e-15 -6.82121e-16 1.93268e-15 1.13687e-16 4.54747e-16 1.98952e-16 -5.3717e-15 1.15676e-14 -2.07478e-15 9.305e-15 -1.19371e-15 4.66116e-15 4.74643e-15 3.32534e-15 3.35376e-15 6.79279e-15 3.90799e-15 -1.8332e-15 -3.41061e-16
{ "domain": "codereview.stackexchange", "id": 42695, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, template, c++20", "url": null }
c++, algorithm, template, c++20 ******************* 1.16529e-12 1.1795e-12 9.66338e-13 1.22213e-12 1.08002e-12 1.19371e-12 1.16529e-12 1.02318e-12 1.25056e-12 1.02318e-12 1.3074e-12 1.27898e-12 1.08002e-12 1.27898e-12 1.10845e-12 1.25056e-12 1.19371e-12 1.02318e-12 1.13687e-12 1.08002e-12 5.11591e-13 5.68434e-13 2.27374e-13 5.11591e-13 3.97904e-13 3.97904e-13 5.11591e-13 4.54747e-13 4.54747e-13 2.84217e-13 1.42109e-12 1.42109e-12 9.66338e-13 1.42109e-12 1.19371e-12 1.3074e-12 1.42109e-12 1.3074e-12 1.3074e-12 1.19371e-12 1.02318e-12 1.13687e-12 4.54747e-13 9.09495e-13 6.82121e-13 6.82121e-13 9.09495e-13 9.09495e-13 9.09495e-13 9.09495e-13 1.13687e-12 1.13687e-12 5.68434e-13 1.02318e-12 7.95808e-13 7.95808e-13 1.02318e-12 1.02318e-12 9.09495e-13 9.09495e-13 1.93268e-12 1.93268e-12 1.25056e-12 1.81899e-12 1.59162e-12 1.59162e-12 1.81899e-12 1.93268e-12 1.7053e-12 1.7053e-12 1.7053e-12 1.59162e-12 7.95808e-13 1.36424e-12 1.13687e-12 9.09495e-13 1.36424e-12 1.47793e-12 1.36424e-12 1.47793e-12 1.81899e-12 1.81899e-12 1.02318e-12 1.59162e-12 1.36424e-12 1.13687e-12 1.59162e-12 1.7053e-12 1.36424e-12 1.59162e-12 1.81899e-12 2.16005e-12 1.13687e-12 1.81899e-12 1.59162e-12 1.36424e-12 1.81899e-12 2.04636e-12 1.81899e-12 2.04636e-12
{ "domain": "codereview.stackexchange", "id": 42695, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, template, c++20", "url": null }
c++, algorithm, template, c++20 ******************* 1.16529e-12 1.15108e-12 8.81073e-13 1.08002e-12 8.81073e-13 1.10845e-12 1.08002e-12 8.2423e-13 1.08002e-12 9.37916e-13 1.10845e-12 1.08002e-12 9.37916e-13 1.08002e-12 9.37916e-13 1.19371e-12 1.13687e-12 9.66338e-13 1.08002e-12 1.02318e-12 3.41061e-13 3.97904e-13 5.68434e-14 3.41061e-13 2.27374e-13 2.27374e-13 3.41061e-13 2.84217e-13 2.84217e-13 1.13687e-13 1.19371e-12 1.19371e-12 7.38964e-13 1.19371e-12 9.66338e-13 1.08002e-12 1.19371e-12 1.08002e-12 1.08002e-12 9.66338e-13 6.82121e-13 1.02318e-12 3.41061e-13 7.95808e-13 5.68434e-13 5.68434e-13 7.95808e-13 7.95808e-13 7.95808e-13 7.95808e-13 1.02318e-12 1.02318e-12 4.54747e-13 9.09495e-13 6.82121e-13 6.82121e-13 9.09495e-13 9.09495e-13 7.95808e-13 7.95808e-13 1.81899e-12 1.81899e-12 1.13687e-12 1.7053e-12 1.47793e-12 1.47793e-12 1.7053e-12 1.81899e-12 1.59162e-12 1.59162e-12 1.59162e-12 1.47793e-12 6.82121e-13 1.25056e-12 1.02318e-12 7.95808e-13 1.25056e-12 1.36424e-12 1.25056e-12 1.36424e-12 1.7053e-12 1.7053e-12 9.09495e-13 1.47793e-12 1.25056e-12 1.02318e-12 1.47793e-12 1.59162e-12 1.25056e-12 1.47793e-12 1.59162e-12 1.93268e-12 9.09495e-13 1.59162e-12 1.36424e-12 1.13687e-12 1.59162e-12 1.81899e-12 1.59162e-12 1.81899e-12
{ "domain": "codereview.stackexchange", "id": 42695, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, template, c++20", "url": null }
c++, algorithm, template, c++20 ******************* 1.16529e-12 1.03739e-12 8.2423e-13 1.13687e-12 9.66338e-13 1.02318e-12 1.08002e-12 8.81073e-13 1.02318e-12 9.66338e-13 8.52651e-13 8.81073e-13 6.25278e-13 8.81073e-13 7.38964e-13 9.66338e-13 9.09495e-13 7.38964e-13 8.52651e-13 7.95808e-13 5.68434e-14 1.13687e-13 -2.27374e-13 5.68434e-14 -5.68434e-14 -5.68434e-14 5.68434e-14 0 0 -1.7053e-13 6.25278e-13 6.25278e-13 1.7053e-13 6.25278e-13 3.97904e-13 5.11591e-13 6.25278e-13 5.11591e-13 5.11591e-13 3.97904e-13 2.27374e-13 3.41061e-13 -3.41061e-13 1.13687e-13 -1.13687e-13 -1.13687e-13 1.13687e-13 1.13687e-13 1.13687e-13 1.13687e-13 3.41061e-13 3.41061e-13 -2.27374e-13 2.27374e-13 0 0 2.27374e-13 2.27374e-13 1.13687e-13 1.13687e-13 7.95808e-13 7.95808e-13 1.13687e-13 6.82121e-13 4.54747e-13 4.54747e-13 6.82121e-13 7.95808e-13 5.68434e-13 5.68434e-13 5.68434e-13 4.54747e-13 -3.41061e-13 2.27374e-13 0 -2.27374e-13 2.27374e-13 3.41061e-13 2.27374e-13 3.41061e-13 6.82121e-13 6.82121e-13 -1.13687e-13 4.54747e-13 2.27374e-13 0 4.54747e-13 5.68434e-13 2.27374e-13 4.54747e-13 5.68434e-13 9.09495e-13 -4.54747e-13 2.27374e-13 0 -2.27374e-13 2.27374e-13 4.54747e-13 2.27374e-13 4.54747e-13
{ "domain": "codereview.stackexchange", "id": 42695, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, template, c++20", "url": null }
c++, algorithm, template, c++20 ******************* 1.20792e-12 1.15108e-12 9.37916e-13 1.27898e-12 1.13687e-12 1.13687e-12 1.16529e-12 1.0516e-12 1.16529e-12 1.10845e-12 1.0516e-12 1.08002e-12 8.2423e-13 1.10845e-12 9.09495e-13 9.66338e-13 9.09495e-13 7.38964e-13 8.52651e-13 7.95808e-13 2.27374e-13 2.84217e-13 -5.68434e-14 2.27374e-13 1.13687e-13 1.13687e-13 2.27374e-13 1.7053e-13 1.7053e-13 0 7.95808e-13 7.95808e-13 3.41061e-13 7.95808e-13 5.68434e-13 6.82121e-13 7.95808e-13 6.82121e-13 6.82121e-13 5.68434e-13 4.54747e-13 5.68434e-13 -1.13687e-13 3.41061e-13 1.13687e-13 1.13687e-13 3.41061e-13 3.41061e-13 3.41061e-13 3.41061e-13 5.68434e-13 5.68434e-13 0 4.54747e-13 2.27374e-13 2.27374e-13 4.54747e-13 4.54747e-13 3.41061e-13 3.41061e-13 1.02318e-12 1.02318e-12 3.41061e-13 9.09495e-13 6.82121e-13 6.82121e-13 9.09495e-13 1.02318e-12 7.95808e-13 7.95808e-13 7.95808e-13 6.82121e-13 -1.13687e-13 4.54747e-13 2.27374e-13 0 4.54747e-13 5.68434e-13 4.54747e-13 5.68434e-13 1.02318e-12 1.02318e-12 2.27374e-13 7.95808e-13 5.68434e-13 3.41061e-13 7.95808e-13 9.09495e-13 5.68434e-13 7.95808e-13 7.95808e-13 1.13687e-12 -4.54747e-13 2.27374e-13 0 -2.27374e-13 2.27374e-13 4.54747e-13 2.27374e-13 4.54747e-13
{ "domain": "codereview.stackexchange", "id": 42695, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, template, c++20", "url": null }
c++, algorithm, template, c++20 ******************* 7.81597e-13 6.96332e-13 5.40012e-13 7.10543e-13 6.25278e-13 7.38964e-13 7.67386e-13 5.40012e-13 7.38964e-13 6.25278e-13 6.82121e-13 7.10543e-13 4.83169e-13 6.82121e-13 5.40012e-13 7.95808e-13 7.38964e-13 5.68434e-13 6.82121e-13 6.25278e-13 -5.68434e-14 0 -3.41061e-13 -5.68434e-14 -1.7053e-13 -1.7053e-13 -5.68434e-14 -1.13687e-13 -1.13687e-13 -2.84217e-13 6.82121e-13 6.82121e-13 2.27374e-13 6.82121e-13 4.54747e-13 5.68434e-13 6.82121e-13 5.68434e-13 5.68434e-13 4.54747e-13 2.27374e-13 3.41061e-13 -3.41061e-13 1.13687e-13 -1.13687e-13 -1.13687e-13 1.13687e-13 1.13687e-13 1.13687e-13 1.13687e-13 3.41061e-13 3.41061e-13 -2.27374e-13 2.27374e-13 0 0 2.27374e-13 2.27374e-13 1.13687e-13 1.13687e-13 1.02318e-12 1.02318e-12 3.41061e-13 9.09495e-13 6.82121e-13 6.82121e-13 9.09495e-13 1.02318e-12 7.95808e-13 7.95808e-13 6.82121e-13 5.68434e-13 -2.27374e-13 3.41061e-13 1.13687e-13 -1.13687e-13 3.41061e-13 4.54747e-13 3.41061e-13 4.54747e-13 6.82121e-13 6.82121e-13 -1.13687e-13 4.54747e-13 2.27374e-13 0 4.54747e-13 5.68434e-13 2.27374e-13 4.54747e-13 5.68434e-13 9.09495e-13 -2.27374e-13 4.54747e-13 2.27374e-13 0 4.54747e-13 6.82121e-13 4.54747e-13 6.82121e-13
{ "domain": "codereview.stackexchange", "id": 42695, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, template, c++20", "url": null }
c++, algorithm, template, c++20 ******************* 6.53699e-13 4.54747e-13 3.69482e-13 6.53699e-13 4.54747e-13 5.68434e-13 4.83169e-13 3.69482e-13 5.68434e-13 4.54747e-13 4.54747e-13 4.83169e-13 2.55795e-13 5.11591e-13 2.27374e-13 4.54747e-13 3.97904e-13 2.27374e-13 3.41061e-13 2.84217e-13 -3.97904e-13 -3.41061e-13 -6.82121e-13 -3.97904e-13 -5.11591e-13 -5.11591e-13 -3.97904e-13 -4.54747e-13 -4.54747e-13 -6.25278e-13 2.27374e-13 2.27374e-13 -2.27374e-13 2.27374e-13 0 1.13687e-13 2.27374e-13 1.13687e-13 1.13687e-13 0 -2.27374e-13 -1.13687e-13 -7.95808e-13 -3.41061e-13 -5.68434e-13 -5.68434e-13 -3.41061e-13 -3.41061e-13 -3.41061e-13 -3.41061e-13 -1.13687e-13 -1.13687e-13 -6.82121e-13 -2.27374e-13 -4.54747e-13 -4.54747e-13 -2.27374e-13 -2.27374e-13 -3.41061e-13 -3.41061e-13 3.41061e-13 3.41061e-13 -3.41061e-13 2.27374e-13 0 0 2.27374e-13 3.41061e-13 1.13687e-13 1.13687e-13 2.27374e-13 1.13687e-13 -6.82121e-13 -1.13687e-13 -3.41061e-13 -5.68434e-13 -1.13687e-13 0 -1.13687e-13 0 2.27374e-13 2.27374e-13 -5.68434e-13 0 -2.27374e-13 -4.54747e-13 0 1.13687e-13 -2.27374e-13 0 1.13687e-13 4.54747e-13 -6.82121e-13 0 -2.27374e-13 -4.54747e-13 0 2.27374e-13 0 2.27374e-13
{ "domain": "codereview.stackexchange", "id": 42695, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, template, c++20", "url": null }
c++, algorithm, template, c++20 ******************* 6.11067e-13 6.39488e-13 2.55795e-13 5.40012e-13 4.54747e-13 4.54747e-13 5.40012e-13 3.69482e-13 4.83169e-13 3.69482e-13 5.40012e-13 5.68434e-13 2.55795e-13 4.83169e-13 3.41061e-13 5.11591e-13 4.54747e-13 2.84217e-13 3.97904e-13 3.41061e-13 -2.27374e-13 -1.7053e-13 -5.11591e-13 -2.27374e-13 -3.41061e-13 -3.41061e-13 -2.27374e-13 -2.84217e-13 -2.84217e-13 -4.54747e-13 3.41061e-13 3.41061e-13 -1.13687e-13 3.41061e-13 1.13687e-13 2.27374e-13 3.41061e-13 2.27374e-13 2.27374e-13 1.13687e-13 -2.27374e-13 -1.13687e-13 -7.95808e-13 -3.41061e-13 -5.68434e-13 -5.68434e-13 -3.41061e-13 -3.41061e-13 -3.41061e-13 -3.41061e-13 -1.13687e-13 -1.13687e-13 -6.82121e-13 -2.27374e-13 -4.54747e-13 -4.54747e-13 -2.27374e-13 -2.27374e-13 -3.41061e-13 -3.41061e-13 5.68434e-13 5.68434e-13 -1.13687e-13 4.54747e-13 2.27374e-13 2.27374e-13 4.54747e-13 5.68434e-13 3.41061e-13 3.41061e-13 3.41061e-13 2.27374e-13 -5.68434e-13 0 -2.27374e-13 -4.54747e-13 0 1.13687e-13 0 1.13687e-13 3.41061e-13 3.41061e-13 -4.54747e-13 1.13687e-13 -1.13687e-13 -3.41061e-13 1.13687e-13 2.27374e-13 -1.13687e-13 1.13687e-13 3.41061e-13 1.13687e-12 0 6.82121e-13 4.54747e-13 2.27374e-13 6.82121e-13 9.09495e-13 6.82121e-13 9.09495e-13
{ "domain": "codereview.stackexchange", "id": 42695, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, template, c++20", "url": null }
c++, algorithm, template, c++20 ******************* 5.68434e-13 5.96856e-13 3.69482e-13 6.82121e-13 5.11591e-13 5.68434e-13 6.25278e-13 4.26326e-13 5.68434e-13 5.11591e-13 5.11591e-13 5.40012e-13 2.84217e-13 5.40012e-13 3.97904e-13 6.25278e-13 5.68434e-13 3.97904e-13 5.11591e-13 4.54747e-13 -1.7053e-13 -1.13687e-13 -4.54747e-13 -1.7053e-13 -2.84217e-13 -2.84217e-13 -1.7053e-13 -2.27374e-13 -2.27374e-13 -3.97904e-13 5.11591e-13 5.11591e-13 5.68434e-14 5.11591e-13 2.84217e-13 3.97904e-13 5.11591e-13 3.97904e-13 3.97904e-13 2.84217e-13 0 1.13687e-13 -5.68434e-13 -1.13687e-13 -3.41061e-13 -3.41061e-13 -1.13687e-13 -1.13687e-13 -1.13687e-13 -1.13687e-13 1.13687e-13 1.13687e-13 -4.54747e-13 0 -2.27374e-13 -2.27374e-13 0 0 -1.13687e-13 -1.13687e-13 7.95808e-13 7.95808e-13 1.13687e-13 6.82121e-13 4.54747e-13 4.54747e-13 6.82121e-13 7.95808e-13 5.68434e-13 5.68434e-13 5.68434e-13 4.54747e-13 -3.41061e-13 2.27374e-13 0 -2.27374e-13 2.27374e-13 3.41061e-13 2.27374e-13 3.41061e-13 6.82121e-13 6.82121e-13 -1.13687e-13 4.54747e-13 2.27374e-13 0 4.54747e-13 5.68434e-13 2.27374e-13 4.54747e-13 5.68434e-13 1.13687e-12 0 6.82121e-13 4.54747e-13 2.27374e-13 6.82121e-13 9.09495e-13 6.82121e-13 9.09495e-13
{ "domain": "codereview.stackexchange", "id": 42695, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, template, c++20", "url": null }
c++, algorithm, template, c++20 ******************* 4.83169e-13 4.54747e-13 1.98952e-13 5.11591e-13 2.55795e-13 4.83169e-13 3.97904e-13 2.55795e-13 4.54747e-13 3.12639e-13 3.69482e-13 3.41061e-13 1.42109e-13 3.97904e-13 5.68434e-14 2.84217e-13 2.27374e-13 5.68434e-14 1.7053e-13 1.13687e-13 -5.68434e-13 -5.11591e-13 -8.52651e-13 -5.68434e-13 -6.82121e-13 -6.82121e-13 -5.68434e-13 -6.25278e-13 -6.25278e-13 -7.95808e-13 1.7053e-13 1.7053e-13 -2.84217e-13 1.7053e-13 -5.68434e-14 5.68434e-14 1.7053e-13 5.68434e-14 5.68434e-14 -5.68434e-14 -6.82121e-13 -5.68434e-13 -1.25056e-12 -7.95808e-13 -1.02318e-12 -1.02318e-12 -7.95808e-13 -7.95808e-13 -7.95808e-13 -7.95808e-13 -5.68434e-13 -5.68434e-13 -1.13687e-12 -6.82121e-13 -9.09495e-13 -9.09495e-13 -6.82121e-13 -6.82121e-13 -7.95808e-13 -7.95808e-13 -2.27374e-13 -2.27374e-13 -9.09495e-13 -3.41061e-13 -5.68434e-13 -5.68434e-13 -3.41061e-13 -2.27374e-13 -4.54747e-13 -4.54747e-13 -4.54747e-13 -5.68434e-13 -1.36424e-12 -7.95808e-13 -1.02318e-12 -1.25056e-12 -7.95808e-13 -6.82121e-13 -7.95808e-13 -6.82121e-13 -3.41061e-13 -3.41061e-13 -1.13687e-12 -5.68434e-13 -7.95808e-13 -1.02318e-12 -5.68434e-13 -4.54747e-13 -7.95808e-13 -5.68434e-13 -4.54747e-13 -2.27374e-13 -1.36424e-12 -6.82121e-13 -9.09495e-13 -1.13687e-12 -6.82121e-13 -4.54747e-13 -6.82121e-13 -4.54747e-13
{ "domain": "codereview.stackexchange", "id": 42695, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, template, c++20", "url": null }
c++, algorithm, template, c++20 ******************* 5.68434e-13 6.25278e-13 2.84217e-13 5.96856e-13 4.54747e-13 5.68434e-13 5.40012e-13 4.54747e-13 6.25278e-13 5.11591e-13 3.97904e-13 4.83169e-13 2.27374e-13 4.83169e-13 4.54747e-13 6.82121e-13 6.25278e-13 4.54747e-13 5.68434e-13 5.11591e-13 -2.84217e-13 -2.27374e-13 -5.68434e-13 -2.84217e-13 -3.97904e-13 -3.97904e-13 -2.84217e-13 -3.41061e-13 -3.41061e-13 -5.11591e-13 1.7053e-13 1.7053e-13 -2.84217e-13 1.7053e-13 -5.68434e-14 5.68434e-14 1.7053e-13 5.68434e-14 5.68434e-14 -5.68434e-14 -5.68434e-13 -4.54747e-13 -1.13687e-12 -6.82121e-13 -9.09495e-13 -9.09495e-13 -6.82121e-13 -6.82121e-13 -6.82121e-13 -6.82121e-13 -4.54747e-13 -4.54747e-13 -1.02318e-12 -5.68434e-13 -7.95808e-13 -7.95808e-13 -5.68434e-13 -5.68434e-13 -6.82121e-13 -6.82121e-13 -1.13687e-13 -1.13687e-13 -7.95808e-13 -2.27374e-13 -4.54747e-13 -4.54747e-13 -2.27374e-13 -1.13687e-13 -3.41061e-13 -3.41061e-13 -3.41061e-13 -4.54747e-13 -1.25056e-12 -6.82121e-13 -9.09495e-13 -1.13687e-12 -6.82121e-13 -5.68434e-13 -6.82121e-13 -5.68434e-13 0 0 -7.95808e-13 -2.27374e-13 -4.54747e-13 -6.82121e-13 -2.27374e-13 -1.13687e-13 -4.54747e-13 -2.27374e-13 -2.27374e-13 0 -1.13687e-12 -4.54747e-13 -6.82121e-13 -9.09495e-13 -4.54747e-13 -2.27374e-13 -4.54747e-13 -2.27374e-13 ******************* Computation finished at Sun Jan 2 08:55:02 2022 elapsed time: 0.0323257 A Godbolt link is here. TinyDIP on GitHub All suggestions are welcome. The summary information: Which question it is a follow-up to? 3D Discrete Cosine Transformation Implementation in C++ What changes has been made in the code since last question? Update dct3_detail and dct3 template functions Propose idct3_detail and idct3 template functions implementation.
{ "domain": "codereview.stackexchange", "id": 42695, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, template, c++20", "url": null }
c++, algorithm, template, c++20 Propose idct3_detail and idct3 template functions implementation. Why a new review is being asked for? If there is any possible improvement, please let me know. Answer: Use std::uint8_t instead of BYTE I see you are declaring a type alias BYTE. However, I think that is a bad idea. If you really wanted to talk about an opaque byte, then since C++17 there is std::byte. However, you cannot do any arithmetic with std::bytes. Instead, you want to treat bytes as 8 bit integers. There is already a perfect type for this: std::uint8_t. I recommend you use that instead of declaring your own type alias, as it is less confusing for someone who doesn't know what you mean by BYTE without looking up how it is declared. Avoid macros There is no reason to make is_size_same() a macro, you can just make it a function: constexpr void assert_size_same(const auto& x, const auto& y) { assert(x.getWidth() == y.getWidth()); assert(x.getHeight() == y.getHeight()); } The drawback of that function is that if it triggers, it will print the line number of the assert() statements inside assert_size_same(), not the line where assert_size_same() itself is called. If you enable coredumps, the backtrace will contain the desired information. Possible workarounds are to make is_size_same() return a boolean: constexpr bool is_size_same(const auto& x, const auto& y) { return x.getWidth() == y.getWidth() && x.getHeight() == y.getHeight(); }
{ "domain": "codereview.stackexchange", "id": 42695, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, template, c++20", "url": null }
c++, algorithm, template, c++20 Then you can call assert(is_size_same(x, y)). The drawback of that is that it won't tell you if it is the width or height that was not the same, but I don't think that is that important in this case. throw vs assert() You are mixing both exceptions and assertions in your code. This can be OK, but you have to be sure when to use exceptions and when to use assertions. assert() helps you as the developer catch bugs early. It will always terminate the program when triggered (except if NDEBUG is defined), so there is no way to recover from assertions. In constrast, exceptions can be handled by the caller by using a try-catch block. Exceptions should be used for things that are exceptional but can happen, assertions should be used for things that are programming bugs and should never happen. It is sometimes hard to decide between the two, but we can look at how things are done in the standard library for some guidance. For example, STL containers have a member function at(), and this one throws when you are out of bounds. So your checkBoundary() function should also throw a std::out_of_range exception. Also be consistent. Is it a programmer bug if someone tries to construct an image with a given std::vector<ElementT> that is not exactly newWidth * newHeight long? Is this similar to trying to add two Images with different sizes? I think so, so I would recommend to choose either to throw in both cases or to assert() in both cases. Avoid passing vectors by value The constructor of Image that takes a vector as parameter takes it by value. This means a copy will be made by the caller. Consider creating a version instead that takes image as a const reference. This does not avoid a copy, but it does avoid the move (which is very fast, but still not free). You can also add a constructor that takes image by rvalue reference; this allows the caller to move an existing vector into an Image, avoid all copies. Printing Images
{ "domain": "codereview.stackexchange", "id": 42695, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, template, c++20", "url": null }
c++, algorithm, template, c++20 Printing Images Your operator<<() duplicates the code of print(). The simple solution is to have operator<<() call print(). As a bonus, it will then also be able to print RGB images using <<. However, consider whether adding printing functions to an Image class is a good idea. It adds responsibilities to the class. Also, it's not very flexible; what if I want to have the values printed in hex? Or I want an ASCII-art representation of the image? Or I want it in JSON? What if I add a struct RGBA and make an image out of that? Instead, callers can access the image data themselves and print however they like it. Create a namespace detail Instead of having a function dct3_detail() in the same namespace as dct3(), consider creating a namespace detail and putting it in there. This is a common technique to indicate that this is a "private" function. If it is meant to be called by the user, then I wouldn't call it dct3_detail(), but rather dct3_one_plane() or something similar. Consider using FFTW You have implemented a naive DCT algorithm that runs in \$O(N^2)\$ time, where N = width * height * planes. Similar to the discrete Fourier transform (DFT), you can do a fast cosine transform in only \$O(N \log N)\$ time. However, instead of implementing it yourself, I strongly recommend you use the FFTW library to do most of the work for you.
{ "domain": "codereview.stackexchange", "id": 42695, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, template, c++20", "url": null }
go, io, compression Title: Decompress tar.gz file in Go Question: I want to extract tar.gz file and store the contents in the same directory. I got below method which does the job but I wanted to see if there is any way to improve below code if there is any efficient way? func ExtractTarGz(gzipStream io.Reader, logger log.Logger) (err error) { uncompressedStream, err := gzip.NewReader(gzipStream) if err != nil { return err } tarReader := tar.NewReader(uncompressedStream) for true { header, err := tarReader.Next() if err == io.EOF { break } if err != nil { return fmt.Errorf("ExtractTarGz: Next() failed: %s", err.Error()) } switch header.Typeflag { case tar.TypeDir: if err := os.Mkdir(header.Name, 0755); err != nil { return fmt.Errorf("ExtractTarGz: Mkdir() failed: %s", err.Error()) } case tar.TypeReg: outFile, err := os.Create(header.Name) if err != nil { return fmt.Errorf("ExtractTarGz: Create() failed: %s", err.Error()) } defer outFile.Close() if _, err := io.Copy(outFile, tarReader); err != nil { return fmt.Errorf("ExtractTarGz: Copy() failed: %s", err.Error()) } default: return fmt.Errorf("ExtractTarGz: uknown type: %s in %s", header.Typeflag, header.Name) } } return nil } I am seeing possible resource leak on defer outFile.Close() line. Not sure how should I fix that. Is the way I am returning error from this method looks good here or something that can be improved here? I will be running this code in production so if there are any other improvements that can be done in the above code then I would like to make those before I run it in prod so opting for code review.
{ "domain": "codereview.stackexchange", "id": 42696, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "go, io, compression", "url": null }
go, io, compression Answer: func ExtractTarGz(gzipStream io.Reader) error { uncompressedStream, err := gzip.NewReader(gzipStream) if err != nil { return err } tarReader := tar.NewReader(uncompressedStream) var header *tar.Header for header, err = tarReader.Next(); err == nil; header, err = tarReader.Next() { switch header.Typeflag { case tar.TypeDir: if err := os.Mkdir(header.Name, 0755); err != nil { return fmt.Errorf("ExtractTarGz: Mkdir() failed: %w", err) } case tar.TypeReg: outFile, err := os.Create(header.Name) if err != nil { return fmt.Errorf("ExtractTarGz: Create() failed: %w", err) } if _, err := io.Copy(outFile, tarReader); err != nil { // outFile.Close error omitted as Copy error is more interesting at this point outFile.Close() return fmt.Errorf("ExtractTarGz: Copy() failed: %w", err) } if err := outFile.Close(); err != nil { return fmt.Errorf("ExtractTarGz: Close() failed: %w", err) } default: return fmt.Errorf("ExtractTarGz: uknown type: %b in %s", header.Typeflag, header.Name) } } if err != io.EOF { return fmt.Errorf("ExtractTarGz: Next() failed: %w", err) } return nil } So few things changed:
{ "domain": "codereview.stackexchange", "id": 42696, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "go, io, compression", "url": null }
go, io, compression So few things changed: We're iterating over reader till there is an error (we're doing 1 error check less on each iteration) with the same functionality as before (we're checking the io.EOF at the end now). I've changed returning the errors with error wrapping "%w", with that you can later on use errors.Is() if you would need that in any case. I've added the error check for closing the file - a common thing to overlook. Removed defer for the Close function. In the case of many files, you would end up with a lot of files opened till all of them are copied. Better just to close it after copy. The functionality will be changed as in the edge case of failing on closing the file, the decompressing will change. Changed error formating of type flag - linter is shouting that it is not string so "%s" should not be used. Removed logger from function arguments - unused variable. Regarding the returning errors. I would not use the prefix of the function name, as you know in the code that you're using certain function. I would remove it here and put it in the in the place where you invoke this function. So if err := ExtractTarGz(gzipStream); err != nil { return fmt.Errorf("ExtractTarGz failed: %w", err) }
{ "domain": "codereview.stackexchange", "id": 42696, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "go, io, compression", "url": null }
c#, .net, .net-core Title: Using a IEnumerable where we have mostly only one item Question: I have a project where I publish and subscribe some data packages. Mostly those data packages are just one package, but sometimes (1 in 100) there could be more packages at one time (a lot more, like 100.000 at the same time) I have a class PacketTransport which only has a IDataPacket property in it. I do this so I can serialize and deserialize it with JSON.net and the JsonSerializerSettings with TypeNameHandling = TypeNameHandling.Auto so the deserializer will know which kind of type it is. I think about making IDataPacket to an IEnumerable<IDataPacket> so I will always enumerate eventhough there is just one data packet inside because when sometimes 100.000 Data Packages at a time are coming, my MQTT is overloaded with 100.000 PacketTransport packages and for the next minutes nothing else can pass. But as those 100.000 packets are mostly very small, I would like to pack it in one PacketTransport message. So my question is: Is it bad to use an IEnumerable where most of the time only one item is inside it? Is the overhead that much or can I ignore it? public class PacketTransport { //Serialize with: //JsonConvert.SerializeObject(packetTransport, new() { TypeNameHandling = TypeNameHandling.Auto }); public IEnumerable<IDataPacket> DataPackets { get; } public PacketTransport(IDataPacket dataPacket) { if (dataPacket is null) throw new ArgumentNullException(nameof(dataPacket)); DataPackets = new[] { dataPacket }; //Is this the most efficient way? } public PacketTransport(IEnumerable<IDataPacket> dataPackets) { if (dataPackets is null) throw new ArgumentNullException(nameof(dataPackets)); DataPackets = dataPackets.ToArray(); //Copy the original dataPackets } } public interface IDataPacket { int Id { get; } } p.s.: I know, that my main bottleneck is probably the JSON serialization, I will go with protobuf in the future
{ "domain": "codereview.stackexchange", "id": 42697, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, .net, .net-core", "url": null }
c#, .net, .net-core Answer: Is it bad to use an IEnumerable where most of the time only one item is inside it? This is perfectly fine. Checking for element counts and using either a collection or another variable would cause you more headaches and overhead than sticking to enumerables. Is the overhead that much or can I ignore it? You can ignore it... unless the profiler tells you otherwise. DataPackets = new[] { dataPacket }; //Is this the most efficient way? When you are looking for a materialized collection then I'm pretty sure it is and also the most elegant one. You could use linq like that but mhmm... I wouldn't: Enumerable.Repeat(dataPacket , 1)
{ "domain": "codereview.stackexchange", "id": 42697, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, .net, .net-core", "url": null }
postscript Title: An enhanced syntax for defining functions in PostScript Question: This file enhances PostScript with a few new syntactic niceties for defining functions with named arguments and even type-checking. block The first part of the enhancement consists of a new control structure called a "block". A block is a list of pairs which will be collected as key/value pairs into a dictionary and then the special key main gets called. This much allows us to elide the 'def' for all functions and data, and also the / decorations on all the function names. { main { f g h } f { } g { } h { } } block This code defines a main function and 3 functions that main calls. When block executes, all 4 functions are defined in a dictionary and then main gets called. Importantly, it lets you put main at the top to aid top-down coding. Alternatively, there is a function pairs-begin which can be used with this same array of pairs as an upgrade to the traditional << ... >> begin construct. func Another enhancement is the func syntax. A function can be created to accept named arguments by calling func with the array of argument names and the array of the body of the function. To do this within the block construct where normally the contents of the block are not executed but just collected, you can force execution by prefixing the @ sign to func. Any name can be executed "at compile time" with this @ prefix, but only at the top-level. Using func you can give names to the arguments of functions by enclosing them in curly braces before the function body: { main{ 3 f 4 5 g } f {x}{ 1 x div sin } @func g {x y}{ x log y log mul } @func } block
{ "domain": "codereview.stackexchange", "id": 42698, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "postscript", "url": null }
postscript This code creates a function f of one argument x, and a function g of two arguments x and y. The function body is augmented with code which takes these 2 objects from the stack and defines them in a new local dictionary created and begined for this invocation of the function, coupled with an end at the end. For some use cases like implementing control structures, it is useful to place the end more strategically. The fortuple function illustrates this by using @func-begin which does not add end at the end. It then places the end earlier, before calling back to the p argument. A function can also declare the types that its arguments must have by enclosing them in parentheses and using executable names for the argument names and literal names for the types: { main { 3 4 p } p (x/integer y/integer){ x y add } @func } block
{ "domain": "codereview.stackexchange", "id": 42698, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "postscript", "url": null }
postscript This augments the function body with code which checks that there are indeed enough objects on the stack, or else it triggers a stackunderflow error. Then it checks that all of the arguments have the expected type, or else it triggers a typecheck error. The types here are written without the letters type at the end; these are added automatically. You can omit the type name with the parenthesized syntax and it will allow any type for that argument. If you omit all the type names you still get the stackunderflow checking. With any of these errors the name of the user function is reported in the error message for easier debugging. Implementation Implementation-wise, the foundation is the pairs construct which is an array which gets traversed with forall. Any name beginning with @ gets the @ stripped off and the remainder gets executed. The results are enclosed in << and >> to create a dictionary. The first dictionary defines everything to do with pairs including pairs-def which adds the key/value pairs into the current dictionary rather than begin a new dictionary. The next two sections add their functions to this same dictionary. This justifies (somewhat) the cuddled style of bracing. The whole implementation is split into 3 layers but the result is only 1 dictionary on the dictstack with all of these functions in it. The middle section defines block and func and all of the functionality for the simple-func style of defining functions. The third section implements two looping control structures which use the simple-func style. These looping functions are then used by the more complex typed-func style. Many of the functions used to implement all of this are useful in their own right so they are also supplied to the user, like curry compose reduce.
{ "domain": "codereview.stackexchange", "id": 42698, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "postscript", "url": null }
postscript There is some simplistic testing code at the bottom guarded by /debug where. So if this file is simply run from another file, it will skip the testing code. But if the key debug is defined somewhere on the dictstack, then the testing code will execute. So with ghostscript, testing can be invoked with gs -ddebug struct2.ps. The testing code itself illustrates the overhead of the code added by func. For type checking, it adds a fair amount of code. %! % struct2.ps An enhanced PostScript syntax for defining functions with named, % type-checked arguments. Using @func within a block or other construct that uses % 'pairs' accomplishes a sort of compile-time macro expansion of the shorthand function description. << /pairs-begin { pairs begin } /pairs-def { pairs {def} forall } /pairs { << exch explode >> } /explode { { @exec } forall } /@exec { dup type /nametype eq { exec-if-@ } if } /exec-if-@ { dup dup length string cvs dup first (@) first eq { exec@ }{ pop } ifelse } /first { 0 get } /exec@ { exch pop rest cvn cvx exec } /rest { 1 1 index length 1 sub getinterval } >> begin { block { pairs-begin main end } func { 1 index type /stringtype eq { typed-func }{ simple-func } ifelse } simple-func { func-begin { end } compose } typed-func { exch args-and-types reverse { make-type-name } map check-stack 3 1 roll exch simple-func compose } func-begin { exch reverse /args-begin load curry exch compose } args-begin { dup length dict begin { exch def } forall } args-and-types { /was_x false def [ exch { each-specifier } fortokens fix-last ] dup args exch types } each-specifier { dup xcheck /is_x exch def is_x was_x and { null exch } if /was_x is_x def } fix-last { counttomark 2 mod 1 eq { null } if } check-stack { {pop} 4 index cvlit { cvx /stackunderflow signalerror } curry compose
{ "domain": "codereview.stackexchange", "id": 42698, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "postscript", "url": null }
postscript check-stack { {pop} 4 index cvlit { cvx /stackunderflow signalerror } curry compose /if cvx 2 array astore cvx {check-count} exch compose curry 3 index cvlit { cvx /typecheck signalerror } curry /if cvx 2 array astore cvx {check-types} exch compose compose } check-count { dup length count 2 sub gt } check-types { dup length 1 add copy true exch { check-type and } forall exch pop not } check-type { dup null eq { 3 -1 roll pop pop true }{ 3 -1 roll type eq } ifelse } make-type-name { dup type /nametype eq { dup length 4 add string dup dup 4 2 roll cvs 2 copy 0 exch putinterval length (type) putinterval cvn } if } args { [ exch 2 { 0 get } fortuple ] } types { [ exch 2 { 1 get } fortuple ] } map { 1 index xcheck 3 1 roll [ 3 1 roll forall ] exch {cvx} if } reduce { exch dup first exch rest 3 -1 roll forall } rreduce { exch aload length 1 sub dup 3 add -1 roll repeat } curry { [ 3 1 roll {} forall ] cvx } @pop { dup length 1 add array dup 0 5 -1 roll put dup 1 4 -1 roll putinterval cvx } compose { 2 array astore cvx { {} forall } map } @pop { 1 index length 1 index length add array dup 0 4 index putinterval dup 4 -1 roll length 4 -1 roll putinterval cvx } reverse { [ exch dup length 1 sub -1 0 { 2 copy get 3 1 roll pop } for pop ] } } pairs-def { fortokens {src proc}{ { src token {exch /src exch store}{exit}ifelse proc } loop } @func fortuple {a n p}{ 0 n /a load length 1 sub { /a exch /n getinterval /p exec } {load-if-literal-name} map end for } @func-begin load-if-literal-name { dup type /nametype eq 1 index xcheck not and { load } if } } pairs-def
{ "domain": "codereview.stackexchange", "id": 42698, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "postscript", "url": null }
postscript /debug where{pop}{currentfile flushfile}ifelse { - sub + add * mul %:= {exch def} += {dup load 3 -1 roll + store} var 2 3 @add f {x y z}{ x y z + * } @func f' {x y z}{ x y z + * end } @func-begin f'' { {z y x}args-begin x y z + * end } g(x/integer y/integer z/real){ x y z + * } @func g' { [/realtype/integertype/integertype] check-count { pop /g cvx /stackunderflow signalerror } if check-types { /g cvx /typecheck signalerror } if {z y x}args-begin x y z + * end } h(x y z){ x y z + * } @func %@dup @== h' { [null null null] check-count { pop /h cvx /stackunderflow signalerror } if check-types { /h cvx /typecheck signalerror } if {z y x}args-begin x y z + * end } main { var == [ 1 2 3 4 5 ] { - } rreduce == / = 3 4 5 f == 3 4 5 f' == 3 4 5 f'' == / = 3 4 5.0 g = 3 4 5.0 g' = { 3 4 5 g = } stopped { $error /errorname get =only ( in ) print $error /command get = } if / = clear { 3 4 h = } stopped { $error /errorname get =only ( in ) print $error /command get = } if clear 3 4 5 h = { 3.0 4.0 5.0 h = } stopped { $error /errorname get =only ( in ) print $error /command get = } if { 3.0 4.0 5.0 h' = } stopped { $error /errorname get =only ( in ) print $error /command get = } if quit } } block The output from the testing code: $ gsnd -q -ddebug struct2.ps 5 3 27 27 27 27.0 27.0 typecheck in g stackunderflow in h 27 27.0 27.0
{ "domain": "codereview.stackexchange", "id": 42698, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "postscript", "url": null }
postscript 27 27 27 27.0 27.0 typecheck in g stackunderflow in h 27 27.0 27.0 Are there improvements to make to the implementation or the behavior? Currently the simple-func style does not check that there are enough arguments but just tries to define them assuming that they're there. Would it be better to add this checking, or is it better to have this low-overhead version which does not add (possibly wasteful) checks? Answer: This function check-stack { {pop} 4 index cvlit { cvx /stackunderflow signalerror } curry compose /if cvx 2 array astore cvx {check-count} exch compose curry 3 index cvlit { cvx /typecheck signalerror } curry /if cvx 2 array astore cvx {check-types} exch compose compose } is a mess. It would probably be better written in a template instantiation style. check-stack { % types -> stack-checker-proc-for-types {_types _args _body _name} args-begin /_name load /_name 1 index cvlit def /_body load /_args load ({ //_types check-count { pop //_name cvx /stackunderflow signalerror } if check-types { //_name cvx /typecheck signalerror } if }) cvx exec end }
{ "domain": "codereview.stackexchange", "id": 42698, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "postscript", "url": null }
python, performance, matrix Title: Python: Create submatrices from long/narrow table and save in HDF5 Question: Hello dear StackExchange Community, I have written a small program which is doing the following. In short: it reads in a table in narrow format creates submatrices from it saves it in HDF5 format The long table is actually representing a huge matrix and the data has the following shape (example not real): POS1 POS2 VALUE 146000 146000 42 146000 147000 69 147000 147000 13 . . . . . . . . .
{ "domain": "codereview.stackexchange", "id": 42699, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, matrix", "url": null }
python, performance, matrix The data comes from experimental measurements and is not formatted user friendly. POS 1 and POS 2 represent coordinates of a small cluster on a big grid(matrix) and VALUE is a representing how strong these are associated. It's quite similar to a correlation matrix. The distance between positions is evenly sized and always has a distance of 1k (they represent bins). The goal is to compare every coordinate/bin vs all others. so if have n bins we get a matrix with n x n Values. Unfortunately not all comparisons are in the table. Some are missing. For my project I need to subset this big matrix into smaller ones, while keeping track of the coordinates, so I can process them individually. I decided to go for 128x128 matrices. Also I needed a solution how I can store the data efficiently to able to access it in a fast way for different ML applications. I decided to go for HDF5 using the h5py library. For every 128x128 submatrix I create a dataset in the HDF5 file with the name of POS1-POS2. This way I have the coordinates stored as the dataset name, which makes them easy to track, since all of them represent 1k bins. While my code actually runs, it runs pretty slow. I could rewrite it in c++ using the eigen lib or try Rust, since I am currently learning it, but I thought I stick to Python and try to optimize it. Maybe someone here could help? Maybe numba or pypy could help here? Until now I did not make that much of a good experience with numba regarding more complicated code where one does not just crunch numbers (where it really shines). Any suggestions and optimization are welcome! Many thanks in advance! I separated the matrix class I wrote into another file: from typing import List, Tuple import numpy as np import pandas as pd class ImageMatrix: """ Class to store and fill 128x128 Image from long table """ def __init__(self, x_axis_start: int = 0, y_axis_start: int = 0, mat_dims: Tuple[int, int] = (128, 128)):
{ "domain": "codereview.stackexchange", "id": 42699, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, matrix", "url": null }
python, performance, matrix # axis' to know where submatrix belongs to in "whole" matrix self.x_axis: List[int] = [i for i in range(x_axis_start, x_axis_start + mat_dims[0] * 1_000, 1000)] self.y_axis: List[int] = [j for j in range(y_axis_start, y_axis_start + mat_dims[1] * 1_000, 1000)] self.mat_dims: Tuple[int, int] = mat_dims # create empty mat to fill up self.image_matrix: np.ndarray = np.zeros(mat_dims).astype(int) def __str__(self) -> str: return(f"Matrix of size: {self.mat_dims}\n" f"coordinates starting for x: {self.x_axis[0]} and y: {self.y_axis[0]}.") def print_matrix(self) -> None: """Print Matrix to the screen""" print(self.image_matrix) def add_value(self, value:int , x_coordinate:int, y_coordinate:int) -> None: """Adds a value to the matrix at given coordinates (x: column, y: row)""" self.image_matrix[self.y_axis.index(y_coordinate)][self.x_axis.index(x_coordinate)] = value def fill_from_pandas(self, pandas_df: pd.DataFrame) -> None: """ Fills up the matrix from a pandas long table assuming the table has following structure: BIN1 BIN2 VALUE """ for i in range(0,len(pandas_df)): self.add_value(pandas_df.iloc[i,:][2], pandas_df.iloc[i,:][0], pandas_df.iloc[i,:][1] ) def fill_from_pandas_symmetric(self, pandas_df: pd.DataFrame) -> None: """ Fills up the matrix and makes it symetric from a pandas long table assuming the table has following structure: BIN1 BIN2 VALUE """ self.fill_from_pandas(pandas_df) tmp = np.tril(self.image_matrix) + np.triu(self.image_matrix.T,1) self.image_matrix = tmp Here's the main script: import argparse from time import time import h5py import numpy as np import pandas as pd from termcolor import colored import imagematrix
{ "domain": "codereview.stackexchange", "id": 42699, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, matrix", "url": null }
python, performance, matrix import h5py import numpy as np import pandas as pd from termcolor import colored import imagematrix def load_hic_from_csv(path_to_file: str) -> pd.DataFrame: """ Input: path to T/CSV file Outout: pandas dataframe Expects t/csv to have the following format and no header: COL 1 COL 2 COL 3 """ return pd.read_csv(path_to_file, header=None, delim_whitespace=True, names=["POS1","POS2","VALUE"]) def create_hdf5_dataset(long_table: pd.DataFrame, file_name: str) -> None: """ Input: - a pandas dataframe containing the hi-C counts - file name to write hdf5 file to - name of dataset group Output: None. Creates an HDF5 File in specified dir """ # get first and last bin start = long_table['POS1'].min() end = long_table['POS2'].max() n_iters = int((end -start)/128_000) hf = h5py.File(file_name, 'a') # loop throug main matrix in 128k steps for counter, i in enumerate(range(start, end, 128_000)): # print steps every 10 steps if(counter % 10 == 0): print(f"[{counter}/{n_iters}]") # loop throug main matrix in 128k steps for j in range(start, end, 128_000): # select subregion from matrix local_region = long_table[(long_table['POS1'] >= i) & (long_table['POS1'] <= i + 127_000 )&\ (long_table['POS2'] >= j) & (long_table['POS2'] <= j + 127_000 )] # instantiate the matrix My_matrix = imagematrix.ImageMatrix(x_axis_start=i, y_axis_start= j) # mirror matrix if it's symmetric -> long table does not contain that values if(i == j): My_matrix.fill_from_pandas_symmetric(local_region) else: My_matrix.fill_from_pandas(local_region) hf.create_dataset(f"{i}-{j}", data=My_matrix.image_matrix, compression="lzf")
{ "domain": "codereview.stackexchange", "id": 42699, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, matrix", "url": null }
python, performance, matrix hf.create_dataset(f"{i}-{j}", data=My_matrix.image_matrix, compression="lzf") # close file hf.close() print(colored(f"Done processing: {file_name}!", 'green')) def main() -> None: argsParser = argparse.ArgumentParser(description = "Write diagonal sub matrices to hdf5 file in 128 x 128 ") argsParser.add_argument('--input_file', '-i', type = str, required = True, help="Long table containing POS1, POS2 and VALUES") argsParser.add_argument('--output_file', '-o', type = str, required= True, help="A string with the path to the output file") # parse arguments args =argsParser.parse_args() DF = load_hic_from_csv(args.input_file) create_hdf5_dataset(DF, args.output_file) if __name__ == "__main__": main()
{ "domain": "codereview.stackexchange", "id": 42699, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, matrix", "url": null }
python, performance, matrix Here's a longer example input file. The ones I am currently working with are actually tab separated and not csvs anymore. Furthermore maybe i should mention that these files can get quite big - a few GB. 7320000 17351000 3.0 17321000 17351000 1.0 17322000 17351000 2.0 17323000 17351000 2.0 17324000 17351000 4.0 17325000 17351000 4.0 17326000 17351000 1.0 17327000 17351000 1.0 17328000 17351000 2.0 17329000 17351000 1.0 17332000 17351000 1.0 17333000 17351000 5.0 17340000 17351000 4.0 17341000 17351000 6.0 17342000 17351000 6.0 17343000 17351000 5.0 17344000 17351000 3.0 17345000 17351000 4.0 17346000 17351000 4.0 17347000 17351000 9.0 17348000 17351000 1.0 17349000 17351000 4.0 17350000 17351000 77.0 17351000 17351000 48.0 16848000 17352000 1.0 16864000 17352000 1.0 16865000 17352000 1.0 16874000 17352000 1.0 16877000 17352000 1.0 16884000 17352000 4.0 16895000 17352000 1.0 16900000 17352000 1.0 16910000 17352000 1.0 16913000 17352000 1.0 16928000 17352000 1.0 16936000 17352000 1.0 16939000 17352000 1.0 16943000 17352000 2.0 16946000 17352000 1.0 16954000 17352000 1.0 17003000 17352000 1.0 17008000 17352000 1.0 17013000 17352000 1.0 17018000 17352000 1.0 17024000 17352000 1.0 17030000 17352000 1.0 17031000 17352000 1.0 17034000 17352000 1.0 17035000 17352000 2.0
{ "domain": "codereview.stackexchange", "id": 42699, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, matrix", "url": null }
python, performance, matrix 17034000 17352000 1.0 17035000 17352000 2.0 17037000 17352000 1.0 17042000 17352000 1.0 17055000 17352000 1.0 17062000 17352000 1.0 17064000 17352000 1.0 17065000 17352000 1.0 17066000 17352000 1.0 17068000 17352000 1.0 17072000 17352000 1.0 17076000 17352000 2.0 17078000 17352000 1.0 17079000 17352000 1.0 17085000 17352000 1.0 17086000 17352000 1.0 17089000 17352000 1.0 17091000 17352000 2.0 17092000 17352000 1.0 17094000 17352000 3.0
{ "domain": "codereview.stackexchange", "id": 42699, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, matrix", "url": null }
python, performance, matrix Answer: POS 1 and POS 2 represent coordinates of a small cluster on a big grid (matrix) Unfortunately not all comparisons are in the table. Some are missing. This is a job for sparse matrices. The selection of which sparse matrix format to use is non-trivial but BSR lends itself well to direct construction from your data. I'd cut out Pandas and use Numpy file loading directly; loadtxt is trivially easy for processing your format. I assume that your third column is all int; if not, you can use a struct-dtype. Divide out the factor of 1000 from your coordinates. Consider ejecting HDF5 and using standard Numpy npz. Think: you had already been loading the entire dataframe of coordinates into memory all at once, which means that it's reasonable to assume you should be able to do the same for a sparse matrix which scales in the same way. You can save and load this sparse matrix in one shot, and when you load it and do (mystery) processing, you can slice it for segmentation then. The slicing operation will be much easier in the sparse representation and you can lose most of your code. Suggested import argparse import numpy as np import scipy.sparse from scipy.sparse import spmatrix def load_hic(path: str) -> np.ndarray: return np.loadtxt(fname=path, dtype=int) def create_dataset(long_table: np.ndarray) -> spmatrix: data = long_table[:, 2] ij = long_table[:, :2].T // 1_000 return scipy.sparse.bsr_matrix((data, ij)) def parse_args() -> argparse.Namespace: args_parser = argparse.ArgumentParser( description="Convert a coordinate-list file to a sparse NPZ file") args_parser.add_argument('--input-file', '-i', type=str, required=True, help="Long table containing POS1, POS2 and VALUES") args_parser.add_argument('--output-file', '-o', type=str, required=True, help="A string with the path to the output file") return args_parser.parse_args()
{ "domain": "codereview.stackexchange", "id": 42699, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, matrix", "url": null }
python, performance, matrix def main() -> None: args = parse_args() array = load_hic(args.input_file) sparse = create_dataset(array) scipy.sparse.save_npz(args.output_file, sparse) if __name__ == "__main__": main()
{ "domain": "codereview.stackexchange", "id": 42699, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, matrix", "url": null }
c#, performance, asp.net-core, entity-framework-core Title: Finding items involving a particular category Question: I have a Item Service that is Called from an Asp.Net Core API Controller. The query gets all items in a particular category for display on an eCommerce web site (reactjs). The controller only returns json: public async Task<IEnumerable<EcommerceItemDto>> GetAllItemsAsync(string customerNumber, string category = "All", int page = 0, int pageSize = 9999) { IQueryable<Category> categories; if (category == "All") { categories = _context.Categories .Include(c => c.Children) .Include(p => p.Parent) .AsNoTrackingWithIdentityResolution(); } else { categories = _context.Categories .Where(n => n.Name == category) .Include(c => c.Children) .Include(p => p.Parent) .AsNoTrackingWithIdentityResolution(); } var items = await _context.EcommerceItems .FromSqlInterpolated($"SELECT * FROM [cp].[GetEcommerceItemsView] WHERE [CustomerNumber] = {customerNumber}") .Include(x => x.Category) .Include(i => i.Images.OrderByDescending(d => d.Default)) .OrderBy(i => i.ItemNumber) .Where(c => categories.Any(x => x.Children.Contains(c.Category)) || categories.Contains(c.Category)) .Skip(page * pageSize) .Take(pageSize) .AsNoTracking() .ToListAsync(); var dto = _mapper.Map<IEnumerable<EcommerceItemDto>>(items); return dto; }
{ "domain": "codereview.stackexchange", "id": 42700, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, performance, asp.net-core, entity-framework-core", "url": null }
c#, performance, asp.net-core, entity-framework-core var dto = _mapper.Map<IEnumerable<EcommerceItemDto>>(items); return dto; } I can show my Controller Action, [cp].[GetEcommerceItemsView] View, EcommerceItem Class, EcommerceItemDto Class, Category Class and Images Class if anyone thinks that will help. I have run Tuning on my Sql Database and applied the recommendations. I have bench-marked this using _mapper.Map as well as .ProjectTo and mapper.Map is faster by a hair. In my test Database, I only have about 65 Items with Images. But this request is taking about 1000 to 1500 ms. UPDATE As Per requested by @iSR5... public class EcommerceItem : INotifyPropertyChanged { [Key] public string ItemNumber { get; set; } public string ItemDescription { get; set; } [Column(TypeName = "text")] public string ExtendedDesc { get; set; } public bool Featured { get; set; } public string CategoryName { get; set; } public Category Category { get; set; } [Column(TypeName = "numeric(19, 5)")] public decimal Price { get; set; } [Column(TypeName = "numeric(19, 5)")] public decimal QtyOnHand { get; set; } public bool? Metadata1Active { get; set; } [StringLength(50)] public string Metadata1Name { get; set; } [StringLength(50)] public string Metadata1 { get; set; } ... // I have Twenty Matadata Groups public bool? Metadata20Active { get; set; } [StringLength(50)] public string Metadata20Name { get; set; } [StringLength(50)] public string Metadata20 { get; set; } public ICollection<EcommerceItemImages> Images { get; set; } public event PropertyChangedEventHandler PropertyChanged; [NotifyPropertyChangedInvocator] protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } }
{ "domain": "codereview.stackexchange", "id": 42700, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, performance, asp.net-core, entity-framework-core", "url": null }
c#, performance, asp.net-core, entity-framework-core My EcommerceItemDto: public class EcommerceItemDto { [Key] public string ItemNumber { get; set; } public string ItemDescription { get; set; } [Column(TypeName = "text")] public string ExtendedDesc { get; set; } public bool Featured { get; set; } public string CategoryName { get; set; } [Column(TypeName = "numeric(19, 5)")] public decimal Price { get; set; } [Column(TypeName = "numeric(19, 5)")] public decimal QtyOnHand { get; set; } public bool? Metadata1Active { get; set; } [StringLength(50)] public string Metadata1Name { get; set; } [StringLength(50)] public string Metadata1 { get; set; } ... // Same as EcommerceItem I have twenty Metadata groups public bool? Metadata20Active { get; set; } [StringLength(50)] public string Metadata20Name { get; set; } [StringLength(50)] public string Metadata20 { get; set; } public ICollection<EcommerceItemImagesDto> Images { get; set; } } My Category Model: [Table("bma_ec_categories")] public class Category : INotifyPropertyChanged { [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)] [Column("category_id")] public int CategoryId { get; set; } [Column("parent_category_id")] public int? ParentId { get; set; } [Required] [Column("category_name")] [StringLength(50)] public string Name { get; set; } public Category Parent { get; set; } public ICollection<Category> Children { get; set; } [Column("title")] [StringLength(150)] public string Title { get; set; } [Column("description")] [StringLength(250)] public string Description { get; set; } [Column("keywords")] [StringLength(250)] public string Keywords { get; set; } [Column("page_content", TypeName = "text")] public string PageContent { get; set; } [Column("banner_group_id")] public int? BannerGroupId { get; set; }
{ "domain": "codereview.stackexchange", "id": 42700, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, performance, asp.net-core, entity-framework-core", "url": null }
c#, performance, asp.net-core, entity-framework-core [Column("banner_group_id")] public int? BannerGroupId { get; set; } [Column("inactive")] public byte? Inactive { get; set; } [Column("issitecategory")] public byte Issitecategory { get; set; } [Column("metadata1_active")] public byte Metadata1Active { get; set; } [Column("metadata1_name")] [StringLength(50)] public string Metadata1Name { get; set; } ... [Column("metadata20_active")] public byte? Metadata20Active { get; set; } [Column("metadata20_name")] [StringLength(50)] public string Metadata20Name { get; set; } [Column("sort_order")] public int? SortOrder { get; set; } public ICollection<EcommerceItem> Items { get; set; } public event PropertyChangedEventHandler PropertyChanged; [NotifyPropertyChangedInvocator] protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } Just to be complete, my View, it gets the calculated Price for the logged in user and flattens the category and item Metadata: SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO
{ "domain": "codereview.stackexchange", "id": 42700, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, performance, asp.net-core, entity-framework-core", "url": null }
c#, performance, asp.net-core, entity-framework-core SET QUOTED_IDENTIFIER ON GO ALTER VIEW [cp].[GetEcommerceItemsView] AS SELECT RTRIM(LTRIM(IV.ITEMNMBR)) AS ItemNumber ,RTRIM(LTRIM(IM.ITEMDESC)) AS ItemDescription ,ecItems.[extended_desc] AS ExtendedDesc ,CAST(ecItems.Featured AS BIT) AS Featured ,cat.category_name AS CategoryName ,CASE IM.PRICMTHD WHEN 1 THEN IV.UOMPRICE WHEN 2 THEN IV.UOMPRICE * IC.LISTPRCE / 100 WHEN 3 THEN (IM.CURRCOST) * (1 + (IV.UOMPRICE / 100)) WHEN 4 THEN (IM.STNDCOST) * (1 + (IV.UOMPRICE / 100)) WHEN 5 THEN (IM.CURRCOST) / (1 - (IV.UOMPRICE / 100)) WHEN 6 THEN (IM.STNDCOST) / (1 - (IV.UOMPRICE / 100)) ELSE 0 END AS Price ,IQ.QTYONHND AS QtyOnHand ,CAST(cat.[metadata1_active] AS BIT) AS [Metadata1Active] ,cat.[metadata1_name] AS [Metadata1Name] ,ecItems.[metadata1] AS [Metadata1] ... ,CAST(cat.[metadata20_active] AS BIT) AS [Metadata20Active] ,cat.[metadata20_name] AS [Metadata20Name] ,ecItems.[Metadata20] AS [Metadata20] ,C.CUSTNMBR AS CustomerNumber FROM dbo.RM00101 AS C LEFT OUTER JOIN dbo.IV00108 AS IV ON C.PRCLEVEL = IV.PRCLEVEL LEFT OUTER JOIN dbo.IV00101 AS IM ON IM.ITEMNMBR = IV.ITEMNMBR LEFT OUTER JOIN dbo.IV00102 AS IQ ON IQ.ITEMNMBR = IV.ITEMNMBR AND IQ.RCRDTYPE = 1 LEFT OUTER JOIN dbo.IV00105 AS IC ON IC.ITEMNMBR = IV.ITEMNMBR AND IV.CURNCYID = IC.CURNCYID LEFT OUTER JOIN dbo.bma_ec_items AS ecItems ON ecItems.ITEMNMBR = IV.ITEMNMBR LEFT OUTER JOIN dbo.bma_ec_item_category AS icat ON icat.ITEMNMBR = IV.ITEMNMBR LEFT OUTER JOIN dbo.bma_ec_categories AS cat ON cat.category_id = icat.category_id WHERE (IM.ITEMNMBR IN (SELECT ITEMNMBR FROM dbo.bma_ec_items WHERE (display_on_ecommerce = 1)) ) GO
{ "domain": "codereview.stackexchange", "id": 42700, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, performance, asp.net-core, entity-framework-core", "url": null }
c#, performance, asp.net-core, entity-framework-core Special Note: I am using Newtonsoft Json Serializer in my controller. I know There are faster Serializers out there. UPDATE 2 As requested, Test Results follows: BenchmarkDotNet=v0.13.0, OS=Windows 10.0.19043.1110 (21H1/May2021Update) Intel Core i7-7700 CPU 3.60GHz (Kaby Lake), 1 CPU, 8 logical and 4 physical cores .NET SDK=5.0.302 [Host] : .NET 5.0.8 (5.0.821.31504), X64 RyuJIT [AttachedDebugger] DefaultJob : .NET 5.0.8 (5.0.821.31504), X64 RyuJIT Method IterationCount Mean Error StdDev Min Max Ratio RatioSD GetItems 50 228.2 ms 8.15 ms 23.65 ms 119.7 ms 265.6 ms 1.00 0.00 GetItemsWithChanges 50 231.0 ms 4.60 ms 10.66 ms 211.3 ms 253.1 ms 1.04 0.22 GetItems 100 455.8 ms 9.04 ms 24.29 ms 414.9 ms 522.0 ms 1.00 0.00 GetItemsWithChanges 100 453.8 ms 9.00 ms 20.32 ms 421.0 ms 502.2 ms 1.00 0.08 UPDATE 3 Test without categories: Method IterationCount Mean Error StdDev Min Max Ratio RatioSD GetItems 50 231.1 ms 6.06 ms 17.88 ms 140.4 ms 259.7 ms 1.00 0.00 GetItemsWithChangesWithoutCategories 50 230.9 ms 4.61 ms 10.69 ms 214.0 ms 255.4 ms 1.01 0.15 GetItems 100 450.2 ms 8.99 ms 22.40 ms 416.6 ms 510.1 ms 1.00 0.00 GetItemsWithChangesWithoutCategories 100 452.5 ms 9.01 ms 23.10 ms 417.3 ms 515.9 ms 1.01 0.08 Answer: I followed all the recommendations from RedGate's Sql Prompt (Modified my view to the one recommended change): SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO
{ "domain": "codereview.stackexchange", "id": 42700, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, performance, asp.net-core, entity-framework-core", "url": null }
c#, performance, asp.net-core, entity-framework-core SET QUOTED_IDENTIFIER ON GO ALTER VIEW [cp].[GetEcommerceItemsView] AS SELECT RTRIM(LTRIM(IV.ITEMNMBR)) AS ItemNumber ,RTRIM(LTRIM(IM.ITEMDESC)) AS ItemDescription ,ecItems.[extended_desc] AS ExtendedDesc ,CAST(ecItems.Featured AS BIT) AS Featured ,cat.category_name AS CategoryName ,CASE IM.PRICMTHD WHEN 1 THEN IV.UOMPRICE WHEN 2 THEN IV.UOMPRICE * IC.LISTPRCE / 100 WHEN 3 THEN (IM.CURRCOST) * (1 + (IV.UOMPRICE / 100)) WHEN 4 THEN (IM.STNDCOST) * (1 + (IV.UOMPRICE / 100)) WHEN 5 THEN (IM.CURRCOST) / (1 - (IV.UOMPRICE / 100)) WHEN 6 THEN (IM.STNDCOST) / (1 - (IV.UOMPRICE / 100)) ELSE 0 END AS Price ,IQ.QTYONHND AS QtyOnHand ,CAST(cat.[metadata1_active] AS BIT) AS [Metadata1Active] ,cat.[metadata1_name] AS [Metadata1Name] ,ecItems.[metadata1] AS [Metadata1] ... ,CAST(cat.[metadata20_active] AS BIT) AS [Metadata20Active] ,cat.[metadata20_name] AS [Metadata20Name] ,ecItems.[Metadata20] AS [Metadata20] ,C.CUSTNMBR AS CustomerNumber FROM dbo.RM00101 AS C LEFT OUTER JOIN dbo.IV00108 AS IV ON C.PRCLEVEL = IV.PRCLEVEL LEFT OUTER JOIN dbo.IV00101 AS IM ON IM.ITEMNMBR = IV.ITEMNMBR LEFT OUTER JOIN dbo.IV00102 AS IQ ON IQ.ITEMNMBR = IV.ITEMNMBR AND IQ.RCRDTYPE = 1 LEFT OUTER JOIN dbo.IV00105 AS IC ON IC.ITEMNMBR = IV.ITEMNMBR AND IV.CURNCYID = IC.CURNCYID LEFT OUTER JOIN dbo.bma_ec_items AS ecItems ON ecItems.ITEMNMBR = IV.ITEMNMBR AND ecItems.display_on_ecommerce = 1 LEFT OUTER JOIN dbo.bma_ec_item_category AS icat ON icat.ITEMNMBR = IV.ITEMNMBR LEFT OUTER JOIN dbo.bma_ec_categories AS cat ON cat.category_id = icat.category_id GO Re-Ran the the tuning advisor and applied those Index creations. Then I switched to System.Text.Json from Newtonsoft.Json as my serializer in the Asp.net Core project. Re-Ran my Bench-Mark test: Method IterationCount Mean Error StdDev Min Max Ratio RatioSD
{ "domain": "codereview.stackexchange", "id": 42700, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, performance, asp.net-core, entity-framework-core", "url": null }
c#, performance, asp.net-core, entity-framework-core Method IterationCount Mean Error StdDev Min Max Ratio RatioSD GetItems 50 225.5 ms 4.89 ms 14.26 ms 134.77 ms 250.5 ms 1.00 0.00 GetItemsWithChangesWithoutCategories 50 225.4 ms 6.86 ms 20.23 ms 98.31 ms 254.2 ms 1.01 0.13 GetItems 100 434.6 ms 7.65 ms 11.21 ms 415.40 ms 460.2 ms 1.00 0.00 GetItemsWithChangesWithoutCategories 100 442.1 ms 8.78 ms 16.50 ms 418.91 ms 478.6 ms 1.02 0.05 I guess this is optimized as it gets, unless I switch to Dapper. UPDATE To be fair to @iSR5, I discovered I had a typo in my username I was using to get the Authorization Token. I corrected it and re-ran the test: Method IterationCount Mean Error StdDev Min Max Ratio GetItems 50 6.260 s 0.1213 s 0.1490 s 6.012 s 6.598 s 1.00 GetItemsWithChangesWithoutCategories 50 2.036 s 0.0407 s 0.0543 s 1.948 s 2.162 s 0.32 GetItems 100 12.521 s 0.2439 s 0.2281 s 12.048 s 12.932 s 1.00 GetItemsWithChangesWithoutCategories 100 4.135 s 0.0790 s 0.0739 s 4.031 s 4.242 s 0.33
{ "domain": "codereview.stackexchange", "id": 42700, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, performance, asp.net-core, entity-framework-core", "url": null }
python, python-3.x, machine-learning Title: Linear Regression in Scikit_learn Question: I have 2 datasets (one for training and the other for testing) containing information about days temperature and humidity; My programm should process the training dataset and find a relation between both, and then predicts humidity values from test dataset, after processing temperature values. My training dataset has almost 97.000 rows of examples, but I only got 42% of accuracy. Maybe because weather is so complex to measure, or it's the program. Any tips for improvement are very welcome. Training Dataset: https://drive.google.com/file/d/1d-jGkFlM6_Wf01UUZGH1mDbDAEyypgnL/view?usp=sharing Testing Dataset: https://drive.google.com/file/d/1wRb-rufT046q7hR83l2IKcCB-raZYhLW/view?usp=sharing import numpy as np import pandas as pd import sklearn as sk from sklearn import linear_model df_train = pd.read_csv("path\\weather_train.csv") df_test = pd.read_csv("path\\weather_test.csv") x_train = np.array(df_train['Temperature (C)']).reshape(-1, 1) y_train = np.array(df_train['Humidity']).reshape(-1, 1) x_test = np.array(df_test['Temperature (C)']).reshape(-1, 1) y_test = np.array(df_test['Humidity']).reshape(-1, 1) #The Model algorithm = linear_model.LinearRegression() algorithm.fit(x_train,y_train) #Here it will predict humidity (Y values) from Temperature (X values) of test dataset and get precision% print(algorithm.predict(x_test)) accu = algorithm.score(x_test, y_test) print("==============================") print(f"Accuracy: {accu * 100}%") print("==============================")
{ "domain": "codereview.stackexchange", "id": 42701, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, machine-learning", "url": null }
python, python-3.x, machine-learning Answer: To test whether the libraries do what you would expect simply create a very simple dataset (e.g. y = 2x + normalerror) which OLS should deal with without any issues. From my understanding of the documentation, what you call "accuracy" here (sklearn.linear_model.LinearRegression score method) is R2 calculated using data out of the training set. With this in mind, it would be worth thinking about what R2 should you expect. R2 = 0.42 for regressing stock returns on information from previous time period is incredible and would make you a billionaire in no time. R2 = 0.42 for regressing Force on Acceleration given some object of fixed mass is questionable and there is something wrong either with your data or model. Is there a linear relationship between temperature and humidity? From some very light googling I found a claim that they are inversely proportional (although the source seems questionable). If that's true then OLS cannot capture their relationship (unless you transform them). Given that you have only one regressor, you can plot your data using scatterplot to gain some intuition about their relationship.
{ "domain": "codereview.stackexchange", "id": 42701, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, machine-learning", "url": null }
c#, object-oriented, design-patterns, .net, memory-management Title: Implement IDisposable correctly using object composition principle Question: Update at the end Is it possible to implement IDisposable pattern correctly while using object composition principle to promote code-reuse, reduce code duplication and hide verbose "official" implementation? Rational Composition over inheritance is a good principle Implementing IDisposable correctly and thoroughly is very verbose and cumbersome Proposal Delegate the dispose logic to a dedicated class: public class DisposeManager { public Action Managed { get; set; } public Action Unmanaged { get; set; } protected virtual void Dispose(bool disposing) { // only dispose once if (disposed) return; if (disposing) { Managed?.Invoke(); } Unmanaged?.Invoke(); disposed = true; } public void DisposeObject(object o) { Dispose(disposing: true); GC.SuppressFinalize(o); } public void FinalizeObject() { Dispose(disposing: false); } private bool disposed; } Implement IDisposable in user class in the following way: public class DisposeUser : IDisposable { public DisposeUser() { // using lambda disposeManager.Managed = () => { // [...] }; // or using member method disposeManager.Unmanaged = DisposeUnmanaged; } ~DisposeUser() { disposeManager.FinalizeObject(); } public void Dispose() { disposeManager.DisposeObject(this); } private void DisposeUnmanaged() { // [...] } private readonly DisposeManager disposeManager = new DisposeManager(); } Benefits much simpler to implement for user classes more explicit (managed, unmanaged) use composition remove the needs for multiple base classes all implementing the dispose pattern and creating code duplication Questions
{ "domain": "codereview.stackexchange", "id": 42702, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, object-oriented, design-patterns, .net, memory-management", "url": null }
c#, object-oriented, design-patterns, .net, memory-management Questions Is it ever a good idea or more of a programmer fancy "improvement" idea ? I've made a decent number of research on the dispose pattern and implementation but never found someone suggesting such idea, any reason why? Any potential problems around hard refs, especially with Action capturing members, etc. that would prevent the actual user class to be collected correctly? Other thought? Thanks! Update Drawbacks mention in answers Mainly the drawbacks that were pointed in the answers are: probably overkill for most case because it's rare to have unmanaged resources to dispose doesn't cover IAsyncDisposable performance impact (delegates) Managed and Unmanaged action properties can re-set later Loose the well-known pattern knowledge for other developers Not much simpler/reducing code New version After using this base version in a project, I've made some improvements that may address some of the drawbacks mentioned. However this new version also accentuates some of them. Changes expose list of actions to allow child class to easily add dispose logic add extensions methods to ease the add of disposable child(s) extension method to register to an event and unregister on dispose in one line Those changes doesn't address much of the drawbacks mentioned, but I think it starts to bring enough benefits for the developer on a daily-basis usage to be worth it. Of course it's the case only if performance is not a concern and you need to dispose stuff in various places.
{ "domain": "codereview.stackexchange", "id": 42702, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, object-oriented, design-patterns, .net, memory-management", "url": null }
c#, object-oriented, design-patterns, .net, memory-management Answer: I think there is nothing wrong with your code, however I am unsure if it provides a significant benefit. What you are doing here is replacing one pattern with another, which is for sure simpler, but only marginally. So instead of one if and one SupressFinalize you need a FinalizeObject, DisposeObject a lambda. Not convinced this is a huge improvement, that might be the reason why you don't see it anywhere, although some kind of a dispose-helper is a frequent sight in many codebases. The problem with the new patterns is of course is that they are not known to people, so between a well-known pattern and a new pattern which is marginally better, I think the old pattern is preferable. Let's address your list of questions and benefits: Benefits much simpler to implement for user classes As discussed, simpler, but not much simpler. more explicit (managed, unmanaged) True, however since there is no compile-time difference between the callbacks, my guess that after a while you will find that they are mixed up in the code base. use composition This is not a benefit. True, composition preferred to inheritance in most cases, but there is a reason for that, we should not just do composition for it's own sake. remove the needs for multiple base classes all implementing the dispose pattern and creating code duplication True, but then again, it has nearly as much code as before. Questions Is it ever a good idea or more of a programmer fancy "improvement" idea ? Might be both. I don't see anything wring with using it, but forcing it on the codebase would be unwise. I've made a decent number of research on the dispose pattern and implementation but never found someone suggesting such idea, any reason why? Probably for the reasons above
{ "domain": "codereview.stackexchange", "id": 42702, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, object-oriented, design-patterns, .net, memory-management", "url": null }
c#, object-oriented, design-patterns, .net, memory-management Any potential problems around hard refs, especially with Action capturing members, etc. that would prevent the actual user class to be collected correctly? I don't thinks so. There might be an issue with disposable ref-structs, but you would not want to use your code for them anyway. In some high-perf scenarios creating a bunch of new objects is a no-go, but it is rare.
{ "domain": "codereview.stackexchange", "id": 42702, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, object-oriented, design-patterns, .net, memory-management", "url": null }
python, python-3.x, parsing, security Title: Boolean expression evaluation for user input using evil eval Question: The following code is a module that evaluates boolean expressions, which are entered through an unauthorized web API. The exposed function of the library being used is evaluate(). Its positional argument string is a string of a pythonic boolean expression that is entered by the user and thusly untrustworthy (so it's potentially any string). I implemented some basic checks to ensure that arbitrary code execution is mitigated. Most of the security is outsourced to the callback function used to evaluate the boolness of user-defined tokens. I'd appreciate a review with focus on security, but also appreciate general feedback. """Boolean evaluation.""" from typing import Callable, Iterator __all__ = ['SecurityError', 'evaluate'] PARENTHESES = frozenset({'(', ')'}) KEYWORDS = frozenset({'and', 'or', 'not'}) class SecurityError(Exception): """Indicates a possible security breach in parsing boolean statements. """ def bool_val(token: str, callback: Callable[[str], bool]) -> str: """Evaluates the given statement into a boolean value.""" callback_result = callback(token) if isinstance(callback_result, bool): return str(callback_result) raise SecurityError('Callback method did not return a boolean value.') def tokenize(word: str) -> Iterator[str]: """Yields tokens of a string.""" for index, char in enumerate(word): if char in PARENTHESES: yield word[:index] yield char yield from tokenize(word[index+1:]) break else: yield word def boolexpr(string: str, callback: Callable[[str], bool]) -> Iterator[str]: """Yields boolean expression elements for python."""
{ "domain": "codereview.stackexchange", "id": 42703, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, parsing, security", "url": null }
python, python-3.x, parsing, security for word in string.strip().split(): for token in filter(None, tokenize(word)): if token in KEYWORDS or token in PARENTHESES: yield token else: yield bool_val(token, callback) def evaluate( string: str, *, callback: Callable[[str], bool] = lambda s: s.casefold() == 'true' ) -> bool: """Safely evaluates a boolean string.""" return bool(eval(' '.join(boolexpr(string, callback)))) Update This library is used in one place only, namely a real estates filtering API, where web applications can retrieve real estates from a database. By using boolean expressions parsed by this library code, the web applications can filter the retrieved real estates. The actual matching is done in the callback function passed to evaluate, which matches common filtering properties on the respective real estates and then uses evaluate() to assert whether the requested combination of properties is met. E.g. id in [1, 2, 3] and (sales_type == "rent" or price < 250000) which, depending on the real estate, evaluates the matching to True and ( False or True ) which is then passed to eval(). Answer: I mean to say this in the gentlest possible way, but from top to bottom this is a bad idea. It would take a more detailed explanation of why this creature exists to convince me otherwise. Your default callback produces some pretty crazy results: ^ and 1 both evaluate to False, for instance. A critical step in security is to limit DOS potential by constraining the possible expression input length. I would replace your PARENTHESES and KEYWORDS with an AST-walk that is very strict on node types. Your eval uses all-defaults, which means: A code object will be immediately compiled, without being able to examine the AST first Any future-features available to the calling scope are implicitly passed into the compiled scope Just... read this and tell me that it's a good idea:
{ "domain": "codereview.stackexchange", "id": 42703, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, parsing, security", "url": null }
python, python-3.x, parsing, security If both [global and local] dictionaries are omitted, the expression is executed with the globals and locals in the environment where eval() is called. I would also rethink your callback. If the idea is to have a small collection of names that evaluate to booleans, just pass these in as locals and call it a day. Anything more complicated expands the potential for misuse. If this needs to exist at all, I would suggest something like """Boolean evaluation.""" import ast from types import CodeType from typing import Union EXPR_LIMIT = 100 class SecurityError(Exception): """Indicates a possible security breach in parsing boolean statements. """ def compile_isolated( source: Union[str, ast.Expression], flags: int, ) -> Union[ast.Expression, CodeType]: return compile( source=source, filename='<untrusted_expr>', mode='eval', flags=flags, dont_inherit=1, # no future features, isolated flags optimize=2, # cut asserts and docstrings ) def evaluate(string: str, **bool_locals: bool) -> bool: if len(string) > EXPR_LIMIT: raise SecurityError('Expression too long') expr: ast.Expression = compile_isolated( source=string, flags=ast.PyCF_ONLY_AST, # no await, no pep484, defer compilation ) if not isinstance(expr, ast.Expression): raise SecurityError('Invalid parent node') top_op, = ast.iter_child_nodes(expr) for node in ast.walk(top_op): if isinstance(node, ( ast.UnaryOp, ast.Not, ast.BoolOp, ast.boolop, ast.Name, ast.Load, )): continue if isinstance(node, ast.Constant): literal = ast.literal_eval(node) if not isinstance(literal, bool): raise SecurityError('Invalid literal') else: raise SecurityError('Invalid node') code_object: CodeType = compile_isolated(source=expr, flags=0) isolated_globals = {'__builtins__': {}}
{ "domain": "codereview.stackexchange", "id": 42703, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, parsing, security", "url": null }
python, python-3.x, parsing, security isolated_globals = {'__builtins__': {}} for v in bool_locals.values(): if not isinstance(v, bool): raise ValueError('Invalid value for bool_locals') result = eval(code_object, isolated_globals, bool_locals) if not isinstance(result, bool): raise SecurityError('Unexpected non-boolean output') return result def test() -> None: assert evaluate('not (a and False) or True', a=True) is True assert evaluate('not False') is True assert evaluate('a and (b or c)', a=True, b=True, c=False) is True for bad in ( '__loader__ or True', 'exit', 'quit', 'eval and False', ): try: evaluate(bad) raise AssertionError('Should have failed') except NameError: pass for bad in ( '1 or False', 'int(False)', 'False * True', 'exit()', 'dos'*40, ): try: evaluate(bad) raise AssertionError('Should have failed') except SecurityError: pass if __name__ == '__main__': test()
{ "domain": "codereview.stackexchange", "id": 42703, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, parsing, security", "url": null }
javascript Title: An if statment which check access to a specific feature based on specific cases Question: In my React application, I had to add an if statement to check for specific access requirements to a specific feature. This access is determined by the roles, actions, and features. I created an if the functionality that covers my scenarios but trying to find a better way to write it. The scenario I'm covering is as described: We have 4 roles as ['study_manager', 'system_admin', 'sponsor_admin', 'sponsor_user'], Those who have access to the feature ANALYTYCS_FEATURE The ANALYTICS_FEATURE can be turned on/off from a panel but only if RECRUITMENT_FEATURE is on Scenario to be covered: If we have RECRUITMENT_FEATURE active but ANALYTYCS_FEATURE not active only 'study_manager', 'system_admin' can access it If we have both active then 'sponsor_admin', 'sponsor_user'] can also see it No active RECRUITMENT_FEATURE no one sees it I was able to cover this scenario by the following if functionality but I believe is very ugly const accessRequirements = checkAccess => { if (checkAccess({ features: [RECRUITMENT_FEATURE] })) { console.log('RECRUITMENT_FEATURE IS ON !!!!!!!!!!!!!!'); if ( checkAccess({ roles: ['study_manager', 'system_admin'], actions: ['analytics:show'], }) ) { console.log('SHOWING FOR THE ROLES BUT ANALYTICS is OFF'); return true; } if ( checkAccess({ actions: ['analytics:show', 'analytics.candidates:get'], features: [ANALYTICS_FEATURE], }) ) { console.log('ANALYTICS_FEATURE IS ON!!!!!!!!!!!!'); return true; } }
{ "domain": "codereview.stackexchange", "id": 42704, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript", "url": null }
javascript I was trying to change this to something like checkAccess({ features: [RECRUITMENT_FEATURE] }) && (checkAccess({ roles: ['study_manager', 'system_admin'], actions: ['analytics:show'], }) || (checkAccess({ actions: ['analytics:show', 'analytics.candidates:get'], }) && checkAccess({ features: [ANALYTICS_FEATURE] }))); But this last doesn't work as expected Answer: if is never ugly There is nothing wrong with nested if statements. Generally they are easier to understand than complex statement clauses. If you remove the noise (console logs and split statement lines) from your first working example we get. Assuming that the return is false if end of function is reached. const accessRequirements = checkAccess => { if (checkAccess({ features: [RECRUITMENT_FEATURE] })) { if (checkAccess({roles: ['study_manager', 'system_admin'], actions: ['analytics:show']})) { return true; } if (checkAccess({ actions: ['analytics:show', 'analytics.candidates:get'], features: [ANALYTICS_FEATURE]})) { return true; } } return false; } I would recommend that you use the above version as the following can easily get confused if you are not careful with the placement of brackets (, {, }, ). Removing the statements You can then reduce that. First the inner statements can be a single statement using logical or || const accessRequirements = checkAccess => { if (checkAccess({ features: [RECRUITMENT_FEATURE] })) { if (checkAccess({roles: ['study_manager', 'system_admin'], actions: ['analytics:show']}) || checkAccess({ actions: ['analytics:show', 'analytics.candidates:get'], features: [ANALYTICS_FEATURE]})) { return true; } } return false; }
{ "domain": "codereview.stackexchange", "id": 42704, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript", "url": null }
javascript Then link the outer statement using logical and && const accessRequirements = checkAccess => { if (checkAccess({ features: [RECRUITMENT_FEATURE] }) && ( checkAccess({roles: ['study_manager', 'system_admin'], actions: ['analytics:show']}) || checkAccess({ actions: ['analytics:show', 'analytics.candidates:get'], features: [ANALYTICS_FEATURE]})) { return true; } return false; } As the return is a boolean you can just return the result of the statement clause... const accessRequirements = checkAccess => { return checkAccess({ features: [RECRUITMENT_FEATURE] }) && ( checkAccess({roles: ['study_manager', 'system_admin'], actions: ['analytics:show']}) || checkAccess({actions: ['analytics:show', 'analytics.candidates:get'], features: [ANALYTICS_FEATURE]}) ); } What was wrong? What you did wrong in the second example is separate the checkAccess call.. You had two calls to checkAccess || (checkAccess({ actions: ['analytics:show', 'analytics.candidates:get'], }) && checkAccess({ features: [ANALYTICS_FEATURE] }))) But the working example only has one || checkAccess({ actions: ['analytics:show', 'analytics.candidates:get'], features: [ANALYTICS_FEATURE] });
{ "domain": "codereview.stackexchange", "id": 42704, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript", "url": null }