text
stringlengths
1
2.12k
source
dict
c #endif source: #include "calibrate.h" /** * compare mpu->self-test for current mpu to the self-test results * in mpu_st_list. if matched, the self-test can serve as a * fingerprint to set the mpu->id. * * ID must be 1-based to allow zero-initialized struct to set default. */ uint8_t get_id_from_factory_st (mpu_t *mpu) { int nids = get_mpu_st_list_sz(), nelem = NAXIS * 2; const uint8_t mpuid[6] = { mpu->accel_st.x, mpu->accel_st.y, mpu->accel_st.z, mpu->gyro_st.x, mpu->gyro_st.y, mpu->gyro_st.z }; int i = 0; for (; i < nids; i++) { /* loop over each known id */ bool found = true; /* initialize flag true */ for (int j = 0; j < nelem; j++) { /* loop over each st value */ if (mpuid[j] != mpu->st_data[i][j]) { /* if any fails to match */ found = false; /* set found flag false */ break; } } if (found) { /* if self-test data matched */ return (mpu->id = i + 1); /* return one-based index for mpu */ } } return 0; } The primary MPU config header: #ifndef mpu_h #define mpu_h 1 #include <stddef.h> #include <stdint.h> #include <stdbool.h> #define NAXIS 3 /* No. axis */ #define RWBUFSZ 16 /* for general 16-byte buffer size */ /** * vector typdefs for common types */ typedef union { uint8_t arr[NAXIS]; struct { uint8_t x, y, z; }; } vect_uint8_t; typedef union { uint16_t arr[NAXIS]; struct { uint16_t x, y, z; }; } vect_uint16_t; typedef union { float arr[NAXIS]; struct { float x, y, z; }; } vect_float_t; /** * main configuration for mpu */ typedef struct mpu_t {
{ "domain": "codereview.stackexchange", "id": 45603, "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 /** * main configuration for mpu */ typedef struct mpu_t { uint8_t addr, id; /* mpu I2C address and individual chip-ID */ vect_uint8_t accel_st, gyro_st; /* factory self-test values */ const uint8_t (*st_data)[NAXIS*2]; /* pointer to array of stored st values */ } mpu_t; /** * Initialize mpu */ void mpuinit (mpu_t *mpu); #endif and source: #include "mpu.h" #include "caldata.h" /** * Initialize mpu */ void mpuinit (mpu_t *mpu) { mpu->st_data = mpu_st_data; } A short test program: #include <stdio.h> #include "mpu.h" #include "caldata.h" #include "calibrate.h" int main (void) { /* declare/initialize struct */ mpu_t mpu = { 0x68, 0, {{ 94, 95, 120 }}, {{ 198, 215, 219 }}, NULL }; mpuinit (&mpu); /* initialize mpu */ if (mpu.st_data) { /* check if data if table */ get_id_from_factory_st (&mpu); /* set id from self-test vals */ } printf ("mpu.id: %hhu\n", mpu.id); /* output result */ } And finally a Makefile to build. Allowing make BLDOPT=-DCHECKNULL to check the case where the pointer is initialize 0: TARGET = mpucaldata CC = gcc BIN = bin SRC = src OBJ = obj SRCS = $(wildcard $(SRC)/*.c) OBJS = $(patsubst $(SRC)%.c, $(OBJ)/%.o, $(SRCS)) BLDOPT = CFLAGS += -Wall -Wextra -pedantic -Wshadow -Werror -std=c11 CFLAGS += -Iinclude CFLAGS += $(BLDOPT) LDFLAGS += # clean before build and create directories all: clean setup $(TARGET) setup: @mkdir -p $(BIN) @mkdir -p $(OBJ) # build executable $(TARGET): $(OBJS) $(CC) $(CFLAGS) $(LDFLAGS) -o $(BIN)/$(TARGET) $^ # compile objects $(OBJ)/%.o: $(SRC)/%.c $(CC) -c $(CFLAGS) $< -o $@ # clean clean: @rm -rvf $(OBJ) @rm -rvf $(BIN)
{ "domain": "codereview.stackexchange", "id": 45603, "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 # clean clean: @rm -rvf $(OBJ) @rm -rvf $(BIN) (note: If you use the Makefile put all sources in a src subdirectory and all headers in an include subdirectory. The Makefile puts the objects in the ./obj directory and the executable in ./bin) Anything look amiss? Answer: Are self-test values unique enough? It's tempting to look at the self-test values of a small number of MPUs, and from seeing that they are all different, conclude that they are therefore unique. But are they really? If you add a new MPU, can you be confident it too will have a unique set of self-test values? Looking at the spread in the values, I would say you get about 3 to 4 bits of entropy from each of the 6 bytes. Lets go with 3 bits to be conservative, that means you have about \$2^{3\cdot 6}\$ = 262144 possible combinations of self-test values. Assuming that they are all equally likely, the birthday paradox then says that if you have a set of 512 MPUs, the chance that at least two of them will have exactly the same self-test values is approximately 50%. So, if you have much less than 512 MPUs to worry about, it's probably fine. Use memcmp() You can greatly simplify get_id_from_factory_st() by using memcmp(): uint8_t get_id_from_factory_st (mpu_t *mpu) { const uint8_t mpuid[6] = {mpu->accel_st.x, mpu->accel_st.y, mpu->accel_st.z, mpu->gyro_st.x, mpu->gyro_st.y, mpu->gyro_st.z}; for (uint8_t i = 0; i < get_mpu_st_list_sz(); i++) { if (memcmp(mpu->st_data[i], mpuid, sizeof mpuid) == 0) { return (mpu->id = i + 1); /* return one-based index for mpu */ } } return 0; }
{ "domain": "codereview.stackexchange", "id": 45603, "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 }
batch Title: Simple fool-proof Minecraft installer Question: I am making a simple, (hopefully) fool-proof Minecraft installer for my friends, some of whom can't comprehend folders and zip files in addition to running a school-provided device, thus lacking certain functionalities (e.g., they can't install Java using the installer and must therefore fiddle around with zip files and environment variables if they were to do everything the installer would've done for them). This started off with me listing some QoL mods I used, then helping them install those mods, then helping them to install a launcher to easily install those mods, and so on, gradually helping with the entire "pipeline". That was tiring and slow, so here I am. I've set up an archive containing Java 17 and Prism Launcher pre-installed and pre-configured with the various QoL mods, and I now need to somehow get it to their device. I would've preferred Bash, but this needs to run on a stock Windows 10 device, potentially school-provided ones with policies that prevent normal installation of stuff, thus the use of archive files. Having them install Cygwin / WSL / Python / whatever would've defeated the entire purpose of this automation, since if they can figure that out, then they wouldn't have problems figuring out the "can't install Java" and "how do I download and install the mods" problems. With Bash I have shellcheck, but I'm not sure what I can do about Batch other than trial and error. This did run in a Windows Sandbox environment (I did have to install vcruntime140, but I assume on a real device it would already be installed), but it was a lot of trial and error, given my unfamiliarity with the language (this is literally the first time I'm writing any Batch). Would love some feedback about how I did in general, and what I can do to improve the script - best practices, etc. run.bat: @echo off setlocal echo( set original_dir="%~dp0"
{ "domain": "codereview.stackexchange", "id": 45604, "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": "batch", "url": null }
batch echo( set original_dir="%~dp0" set /p "target_dir=Select an install location (Desktop=1, Documents=2, Downloads=3): " if "%target_dir%"=="1" ( set target_dir="%USERPROFILE%\Desktop" ) else if "%target_dir%"=="2" ( set target_dir="%USERPROFILE%\Documents" ) else if "%target_dir%"=="3" ( set target_dir="%USERPROFILE%\Downloads" ) else ( echo Invalid option exit /b ) move mc.tar.xz %target_dir% cd %target_dir% "%WINDIR%\System32\tar.exe" -xf mc.tar.xz del mc.tar.xz cd mc cd PrismLauncher echo( >> prismlauncher.cfg hostname > tempfile set /p temphostname=<tempfile del tempfile echo LastHostname=%temphostname% >> prismlauncher.cfg set target_dir=%target_dir:\=/% set target_dir=%target_dir:"=% echo JavaPath=%target_dir%/mc/jdk-17.0.9+9/bin/javaw.exe >> prismlauncher.cfg cd %original_dir% start /b "" cmd.exe /c "del %~f0 & exit /b" Answer: Review context: Both Author and Reviewer are not expert at batch. My intent is that some new engineer, also not expert at batch, should be able to come along in a few months and maintain this. creating the .tar I've set up an archive containing Java 17 and Prism Launcher pre-installed and pre-configured with the various QoL mods There is hopefully another script, not part of the submission, which downloads these assets and builds the .tar from scratch. Things change, java moves on to version 22, bugs get fixed. You will want to be able to easily reproduce all the build steps when one of them changes. This is a software life cycle process issue.
{ "domain": "codereview.stackexchange", "id": 45604, "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": "batch", "url": null }
batch problem statement, approach The OP very helpfully includes some Review Context explaining the motivation and the technical approach taken. A summary of this should appear at the top as REMarks. Or at least mention the URL of a ReadMe file. End user should understand what will change and what things (like a giant minecraft.tar plus this script) will be deleted. I initially found the deletion surprising, but then it made sense. With any luck deletion will only happen after successful install. (hopefully) fool-proof Minecraft installer Excellent, I'm glad to see this philosophic perspective. I didn't exactly see it in an explicit way in the code. Some install scripts are divided into two phases: readonly: gather / prepare / verify execute That is, we're going to need some assets, maybe we verify their SHA3 hash, we will need a writable install location that has space available, and so on. Knowing we have that in hand, then we can go do destructive things like spam new folders onto the Desktop or delete a downloaded asset. IDK, maybe I'm being too paranoid, maybe this source code does do that, and all that's missing is the occasional REMark describing how things would unfold in the error case. move mc.tar.xz %target_dir% This seems to be the first place where things can go south. In bash we might first verify the target is a -w writable -d directory -- LBYL. Here we forge ahead -- EAFP. My review concern is whether we have bash set -e behavior here. Will a move failure bail out? Or will the script continue, nuking the .tar file and this script? I'm not sure, and don't have a test system available, but I have to believe that Author's Intent was immediate bailout.
{ "domain": "codereview.stackexchange", "id": 45604, "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": "batch", "url": null }
batch idempotency The primary use case is a student encounters a computer with no minecraft, runs the installer, and we're happy. They visit the same computer the next day and they're still happy. Suppose the following day they believe they're on a new computer, but it turns out they're on the same one. Maybe they forgot whether Downloads or Documents holds the game. So they run the installer. What happens? Would installing to Downloads twice yield a working game? Would installing to Downloads and then to Documents similarly work? Would it leave us with two copies, and is that undesirable? Maybe before prompting {1,2,3} the script should look around for evidence of a previous install? If Alice installs to Downloads, could Bob subsequently install to his own Downloads on same machine? previous java In a similar vein, do we care if a computer winds up with both java 17 + java 19 installed? Or three or four versions? Could the script maybe look around and notice there's a usable version already installed? Yeah, yeah, I know, it's getting too complex, and out-of-scope. downloading assets Rather than expecting a .tar in same directory as the .bat, should this script perhaps have one or two hard-coded URLs and obtain assets from internet as needed? blank line I think this is equivalent to /usr/bin/printf "\n": echo( I don't have a CMD.exe available to test that. It appears to exploit a peculiarity in batch command parsing, one the vendor makes no explicit mention of. Larry Wall asserts "there's more than one way to skin a cat!", but not all developers agree with the Let a thousand flowers bloom philosophy. Be boring. Following conventions is a good thing, it makes software more maintainable. Of the different variant approaches for emitting a newline, the recommended one appears to be: echo. The vendor docs explain: Don't include a space before the period. Otherwise, the period appears instead of a blank line. BTW, those docs also mention items like
{ "domain": "codereview.stackexchange", "id": 45604, "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": "batch", "url": null }
batch BTW, those docs also mention items like Applies To: Windows Vista, Windows Server 2008, Windows Server 2012, Windows 8 which is something you might put in a REMark, telling us the one or two OS versions you have tested against. arcane invocations set original_dir="%~dp0" Experienced batch hackers would recognize this immediately. For everyone else, consider calling this run_bat_dir or perhaps drive_path_dir. set target_dir=%target_dir:\=/% set target_dir=%target_dir:"=% I bet something really cool happened there, something essential. I don't know what it is, and R / APL / batch punctuation is notoriously difficult to google for. Please show us REM foo"bar" --> foobar, or a better example of what this pair of lines is intended to do. ... %~f0 ... Consider assigning that to batch_file_path and using that, just for its documentation value. names Using a slightly obscure directory name of mc/ is perhaps deliberate, so as not to attract too much attention from adults. If not, prefer minecraft/ and minecraft.tar.xz. Consider incorporating a version number in the .tar file's name. setting LastHostname hostname > tempfile set /p temphostname=<tempfile del tempfile This seems more painful than necessary. Is it possible to echo without a trailing CRLF ? Alternatively, if we tacked on a trailing \ backwhack with echo LastHostname=\, would PrismLauncher accept a multiline config option? If so, we could just finish up with hostname >> prismlauncher.cfg uninstaller Perhaps we want one? Or manual directions for uninstalling? test suite Consider putting some of those arcane invocations into one-line unit tests, which know the correct answer and so can display a Green bar. Consider writing an idempotency integration test which abuses some poor computer in ways I suggested above, with multiple attempted installs and then some automated verification that all is well. Such tests will come in handy when the school upgrades to a future windows release.
{ "domain": "codereview.stackexchange", "id": 45604, "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": "batch", "url": null }
batch This script achieves its design goals. I would be willing to delegate maintenance tasks on it to an engineer who is well versed in Batch and has test systems available running the targeted operating system(s). After some of the proposed enhancements have been incorporated, I would be willing to delegate maintenance tasks to a junior dev who has test systems available.
{ "domain": "codereview.stackexchange", "id": 45604, "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": "batch", "url": null }
rust, tcp, redis Title: Simple Redis implementation in Rust Question: This is a very tiny implementation of Rust that uses redis serialization protocol (RESP). I implemented it as one of code crafters challenges. I have less than a few month experience in Rust, so it may not seems to be a very advanced Rust program. But I appreciate any feedback to improve my implementation and also to make my Rust code more advanced. use std::io::{Read, Write}; use std::net::{TcpListener, TcpStream}; use std::{ collections, sync::{Arc, Mutex}, thread, time, }; fn main() { let listener = TcpListener::bind("127.0.0.1:6379").unwrap(); let data_storage = Arc::new(Mutex::new(collections::HashMap::< String, (Option<time::Instant>, Vec<u8>), >::new())); for stream in listener.incoming() { match stream { Ok(s) => { let cloned_storage = data_storage.clone(); thread::spawn(move || handle(s, cloned_storage)); } Err(e) => { println!("error: {}", e); } } } }
{ "domain": "codereview.stackexchange", "id": 45605, "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": "rust, tcp, redis", "url": null }
rust, tcp, redis fn handle( mut stream: TcpStream, storage: Arc<Mutex<collections::HashMap<String, (Option<time::Instant>, Vec<u8>)>>>, ) { let mut buf = [0u8; 64]; loop { let read_count = stream.read(&mut buf).expect("Could not read from client"); if read_count == 0 { return; } let mut new_buf = Vec::new(); for i in 0..read_count { new_buf.push(buf[i]); } match Command::from_buffer(&new_buf.as_slice()) { Ok(Command::Ping) => { stream.write_all(b"+PONG\r\n"); } Ok(Command::Echo(s)) => { let out = serialize_to_bulk_string(s.as_bytes()); stream.write_all(out.as_slice()); } Ok(Command::Set(key, value, expiry)) => { let mut storage = storage.lock().unwrap(); let expiry = expiry.map(|t| time::Instant::now() + time::Duration::from_millis(t as u64)); storage.insert(key, (expiry, value)); let out = serialize_to_simple_string("OK".as_bytes()); stream.write_all(out.as_slice()); } Ok(Command::Get(key)) => { let mut storage = storage.lock().unwrap(); match storage.get(&key) { Some((expiry, v)) => { if let Some(expiry) = expiry { if time::Instant::now() >= *expiry { stream.write_all(b"$-1\r\n"); } else { let out = serialize_to_bulk_string(v); stream.write_all(out.as_slice()); } } else { let out = serialize_to_bulk_string(v); stream.write_all(out.as_slice()); } } None => {
{ "domain": "codereview.stackexchange", "id": 45605, "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": "rust, tcp, redis", "url": null }
rust, tcp, redis } } None => { stream.write_all(b"$-1\r\n"); } } } Err(_) => { stream.write_all(b"-Error\r\n"); } } } }
{ "domain": "codereview.stackexchange", "id": 45605, "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": "rust, tcp, redis", "url": null }
rust, tcp, redis fn serialize_to_simple_string(s: &[u8]) -> Vec<u8> { [b"+", s, b"\r\n"].concat() } fn serialize_to_bulk_string(s: &[u8]) -> Vec<u8> { [b"$", format!("{}", s.len()).as_bytes(), b"\r\n", s, b"\r\n"].concat() } #[derive(Debug)] enum Command { Ping, Echo(String), Set(String, Vec<u8>, Option<u64>), Get(String), } enum DataType { SimpleString, SimpleErr, Integer, BulkString, Array, } impl DataType { fn from_byte(b: u8) -> Self { match b { b'+' => Self::SimpleString, b'-' => Self::SimpleErr, b':' => Self::Integer, b'$' => Self::BulkString, b'*' => Self::Array, _ => unimplemented!(), } } } #[derive(Debug)] enum RedisObject { SimpleString(String), SimpleErr(String), Integer(i32), BulkString(usize, String), Array(Vec<RedisObject>), } struct Parser<'a> { stream: &'a [u8], } impl<'a> Parser<'a> { fn new(stream: &'a [u8]) -> Self { Self { stream } } fn parse(&mut self) -> Result<RedisObject, ()> { match Self::parse_object(self.stream) { Ok((Some(object), _)) => Ok(object), Ok(_) => Err(()), Err(_) => Err(()), } }
{ "domain": "codereview.stackexchange", "id": 45605, "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": "rust, tcp, redis", "url": null }
rust, tcp, redis fn parse_object(stream: &[u8]) -> Result<(Option<RedisObject>, usize), ()> { if stream[0..2] == *b"\r\n" { return Ok((None, 2)); } match DataType::from_byte(stream[0]) { DataType::Array => Parser::parse_array(&stream[1..]), DataType::SimpleString => { let parts = split_by_line(&stream[1..]); Ok(( Some(RedisObject::SimpleString( String::from_utf8(parts[0].clone()).unwrap(), )), parts[0].len(), )) } DataType::Integer => { let parts = split_by_line(&stream[1..]); Ok(( Some(RedisObject::Integer( String::from_utf8(parts[0].clone()) .unwrap() .parse::<i32>() .unwrap(), )), parts[0].len(), )) } DataType::BulkString => { let parts = split_by_line(&stream[1..]); let Ok(size) = String::from_utf8(parts[0].clone()) .unwrap() .parse::<usize>() else { panic!("invalid string"); }; let string = String::from_utf8(parts[1].clone()).unwrap(); assert!(string.len() == size as usize); Ok(( Some(RedisObject::BulkString(size, string)), parts[0].len() + parts[1].len() + 3, )) } _ => unimplemented!("type not implemented"), } }
{ "domain": "codereview.stackexchange", "id": 45605, "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": "rust, tcp, redis", "url": null }
rust, tcp, redis fn parse_array(stream: &[u8]) -> Result<(Option<RedisObject>, usize), ()> { let parts = split_by_line(stream); let _size = String::from_utf8(parts[0].clone()) .expect("invalid string") .parse::<usize>() .expect("invalid string"); let mut objects = vec![]; let mut pos: usize = parts[0].len() + 2; loop { match Parser::parse_object(&stream[pos..]) { Ok((Some(object), consumed)) => { objects.push(object); pos += consumed; if pos > stream.len() { break; } } Ok((None, consumed)) => { pos += consumed; if pos >= stream.len() { break; } } Err(_) => { return Err(()); } } } println!("{objects:?}"); Ok((Some(RedisObject::Array(objects)), pos)) } } fn split_by_line(stream: &[u8]) -> Vec<Vec<u8>> { let line_positions = stream .windows(2) .enumerate() .filter(|(_, w)| w == b"\r\n") .map(|(i, _)| i) .collect::<Vec<_>>(); let mut lines = vec![stream[..line_positions[0]].to_vec()]; lines.extend( line_positions .windows(2) .map(|i| stream[i[0] + 2..i[1]].to_vec()) .collect::<Vec<_>>(), ); lines.push(stream[*line_positions.last().unwrap() + 2..].to_vec()); lines .into_iter() .filter(|l| !l.is_empty()) .collect::<Vec<_>>() }
{ "domain": "codereview.stackexchange", "id": 45605, "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": "rust, tcp, redis", "url": null }
rust, tcp, redis impl Command { fn from_buffer(buf: &[u8]) -> Result<Self, ()> { let mut p = Parser::new(buf); match p.parse() { Ok(object) => match object { RedisObject::Array(arr) => match arr.as_slice() { [RedisObject::BulkString(4, s)] => { if s.to_uppercase() == "PING".to_string() { Ok(Command::Ping) } else { Err(()) } } [RedisObject::BulkString(4, s), RedisObject::BulkString(_, o)] => { if s.to_uppercase() == "ECHO".to_string() { Ok(Command::Echo(o.to_string())) } else { Err(()) } } [RedisObject::BulkString(3, s), RedisObject::BulkString(_, key)] => { if s.to_uppercase() == "GET".to_string() { Ok(Command::Get(key.to_string())) } else { Err(()) } } [RedisObject::BulkString(3, s), RedisObject::BulkString(_, key), RedisObject::BulkString(_, value), RedisObject::BulkString(2, ex), RedisObject::BulkString(_, duration)] => { if s.to_uppercase() == "SET".to_string() && ex.to_uppercase() == "PX" && duration.parse::<u64>().is_ok() { Ok(Command::Set( key.to_string(), value.as_bytes().to_vec(), Some(duration.parse::<u64>().unwrap()), )) } else { Err(()) } }
{ "domain": "codereview.stackexchange", "id": 45605, "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": "rust, tcp, redis", "url": null }
rust, tcp, redis Err(()) } } [RedisObject::BulkString(3, s), RedisObject::BulkString(_, key), RedisObject::BulkString(_, value)] => { if s.to_uppercase() == "SET".to_string() { Ok(Command::Set( key.to_string(), value.as_bytes().to_vec(), None, )) } else { Err(()) } } _ => Err(()), }, _ => Err(()), }, Err(_) => Err(()), } } }
{ "domain": "codereview.stackexchange", "id": 45605, "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": "rust, tcp, redis", "url": null }
rust, tcp, redis Answer: Don’t Panic! (On Runtime Errors) I admit I’ve sometimes put an .expect() or .unwrap() in my code examples, for simplicity. But I’m mostly on the side that believes end users should never see a runtime panic. Those should only be used for logic errors, or debugging. But a network error, especially, is something that often happens in the real world, so a program really ought to handle it more gracefully than panicking. In general, you might want to have each function on a stream that could fail, return a value wrapped in a std::io::Result. Computations that shouldn’t have to worry or know about TCP and errors should be called on the unwrapped values, with syntax sugar like the ? operator. Or you can use railway-style with calls like and_then. Let’s see what happens when we change main to return a std::io::result, allowing it to short-circuit and return the first Err: fn main() -> std::io::Result<()> { let listener = TcpListener::bind("127.0.0.1:6379")?; let data_storage = Arc::new(Mutex::new(collections::HashMap::< String, (Option<time::Instant>, Vec<u8>), >::new())); for stream in listener.incoming() { let s = stream?; let cloned_storage = data_storage.clone(); thread::spawn(move || handle(s, cloned_storage)); } Ok(()) } This error-handling is still bare-bones: any I/O error that gets returned from main makes the program print an error message and return with an exit status of 1. In this implementation, the error message is something like: Error: Os { code: 98, kind: AddrInUse, message: "Address already in use" }
{ "domain": "codereview.stackexchange", "id": 45605, "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": "rust, tcp, redis", "url": null }
rust, tcp, redis Unlike the default panic message from Result::expect, this doesn’t have any explanation of where the error happened or what you were trying to do (or the ability to get a backtrace). You might rename main to run and write a new main that inspects the return value of run, and handles it, for example by logging the error and trying again to listen on the port if possible. For an alternative that lets you add some context to the error, explaining where it happened and what you were doing, you might look at the error_chain crate. Refactor to Remove False Dependencies And to Reduce Cyclomatic Complexity You have a large match block in handle, currently, which is a good candidate for refactoring. It really takes a line of input and a shared database (by mutable reference), and returns some output. It doesn’t really need to know about sockets. This means it doesn’t need to know about, or handle, errors: we can check for them in one place, when we write the output string we returned. If we move this block into a helper function, we get (Warning: untested!): fn execute( s: &str, storage: &mut Arc<Mutex<collections::HashMap<String, (Option<time::Instant>, String)>>>, ) -> String { match Command::from_buffer(s.as_bytes()) { Ok(Command::Ping) => "+PONG\r\n".to_string(), Ok(Command::Echo(cmd)) => "$".to_string() + &cmd + "\r\n", Ok(Command::Set(key, value, expiry)) => { let mut storage = storage.lock().unwrap(); let expiry = expiry.map(|t| time::Instant::now() + time::Duration::from_millis(t as u64)); storage.insert(key, (expiry, value)); "+OK\r\n".to_string() } Ok(Command::Get(key)) => { let storage = storage.lock().unwrap(); match storage.get(&key) { Some((expiry, v)) => { if let Some(expiry) = expiry { if time::Instant::now() >= *expiry {
{ "domain": "codereview.stackexchange", "id": 45605, "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": "rust, tcp, redis", "url": null }
rust, tcp, redis if time::Instant::now() >= *expiry { "$-1\r\n".to_string() } else { "$".to_string() + &v + "\r\n" } } else { "$".to_string() + &v + "\r\n" } } None => "$-1\r\n".to_string(), } // end match } Err(_) => "-Error\r\n".to_string(), } // end match }
{ "domain": "codereview.stackexchange", "id": 45605, "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": "rust, tcp, redis", "url": null }
rust, tcp, redis This fixes one minor bug (the locked storage in the Get branch was mut when it didn’t need to be) and almost certainly introduces several more. This also simplifies the next piece: Use a BufReader to Split Lines You currently have some complex code to SplitByLine, SerializeToSimpleString, SerializeToBulkString, etc. While I haven’t checked the requirements or tested to see if what I’m about to recommend works robustly for your use case, it looks like you could be reinventing the wheel. There’s already a class in the standard library that turns anything with the Read trait into a buffered reader. The BufRead::lines method turns an input stream into an iterator over its lines. (More precisely, an iterator over std::io::Result objects which hold either a line of input, or a std::io::Error.) This is how I’d split into lines whenever possible. There’s also a more-general split method to delimit buffered input at an arbitrary byte. A wrinkle here is that a BufReader can’t be written to, nor can our stream be mutably borrowed twice, so we actually need to wrap a clone of the TcpStream for buffered reading, and use the original for writing. fn handle( mut stream: TcpStream, mut storage: Arc<Mutex<collections::HashMap<String, (Option<time::Instant>, String)>>>, ) { let buffered_stream = BufReader::new(stream.try_clone().expect("Cloning socket")); for line in buffered_stream.lines() { match line { Ok(s) => { if let Err(e) = stream.write_all(execute(&s, &mut storage).as_bytes()) { let _ = std::io::stdout().flush(); // Don't cross the streams! eprintln!("Network write error: {e}\n"); let _ = std::io::stderr().flush(); // Could be writing from multiple threads. return; } } Err(e) => { let _ = std::io::stdout().flush(); // Don't cross the streams!
{ "domain": "codereview.stackexchange", "id": 45605, "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": "rust, tcp, redis", "url": null }
rust, tcp, redis let _ = std::io::stdout().flush(); // Don't cross the streams! eprintln!("Network read error: {e}\n"); let _ = std::io::stderr().flush(); // Could be writing from multiple threads. return; } } } }
{ "domain": "codereview.stackexchange", "id": 45605, "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": "rust, tcp, redis", "url": null }
rust, tcp, redis You’ll notice a bit of hypocrisy in how I handled errors. Cloning the network socket, to get separate unbuffered writer and buffered reader streams, should “always” work, so I fell back to expect for error handling. (Don’t quote me on that: some OS might run out of file descriptors, or something.) Other errors are handled by printing a message to standard error and terminating the thread (which closes the network connection). I flush the standard output and error streams, and ignore the error conditions. (If printing an error message failed, there’s no point trying to print an error message about it!) This reduces the odds that a bunch of threads will garble their error messages together when they all crash at once, but if you want a robust solution, factor this code out into a locked critical section. Putting it All Together Because a lot of little changes were needed to get this tweaked version to compile, here's a full listing. There’s plenty of work left to do. You’ll notice for example that it still calls split_by_line even though the lines have already been split. use std::io::{BufRead, BufReader, Write}; use std::net::{TcpListener, TcpStream}; use std::{ collections, sync::{Arc, Mutex}, thread, time, }; fn main() -> std::io::Result<()> { let listener = TcpListener::bind("127.0.0.1:6379")?; let data_storage = Arc::new(Mutex::new(collections::HashMap::< String, (Option<time::Instant>, String), >::new())); for stream in listener.incoming() { let s = stream?; let cloned_storage = data_storage.clone(); thread::spawn(move || handle(s, cloned_storage)); } Ok(()) }
{ "domain": "codereview.stackexchange", "id": 45605, "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": "rust, tcp, redis", "url": null }
rust, tcp, redis fn handle( mut stream: TcpStream, mut storage: Arc<Mutex<collections::HashMap<String, (Option<time::Instant>, String)>>>, ) { let buffered_stream = BufReader::new(stream.try_clone().expect("Cloning socket")); for line in buffered_stream.lines() { match line { Ok(s) => { if let Err(e) = stream.write_all(execute(&s, &mut storage).as_bytes()) { let _ = std::io::stdout().flush(); // Don't cross the streams! eprintln!("Network write error: {e}\n"); let _ = std::io::stderr().flush(); // Could be writing from multiple threads. return; } } Err(e) => { let _ = std::io::stdout().flush(); // Don't cross the streams! eprintln!("Network read error: {e}\n"); let _ = std::io::stderr().flush(); // Could be writing from multiple threads. return; } } } }
{ "domain": "codereview.stackexchange", "id": 45605, "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": "rust, tcp, redis", "url": null }
rust, tcp, redis fn execute( s: &str, storage: &mut Arc<Mutex<collections::HashMap<String, (Option<time::Instant>, String)>>>, ) -> String { match Command::from_buffer(s.as_bytes()) { Ok(Command::Ping) => "+PONG\r\n".to_string(), Ok(Command::Echo(cmd)) => "$".to_string() + &cmd + "\r\n", Ok(Command::Set(key, value, expiry)) => { let mut storage = storage.lock().unwrap(); let expiry = expiry.map(|t| time::Instant::now() + time::Duration::from_millis(t as u64)); storage.insert(key, (expiry, value)); "+OK\r\n".to_string() } Ok(Command::Get(key)) => { let storage = storage.lock().unwrap(); match storage.get(&key) { Some((expiry, v)) => { if let Some(expiry) = expiry { if time::Instant::now() >= *expiry { "$-1\r\n".to_string() } else { "$".to_string() + &v + "\r\n" } } else { "$".to_string() + &v + "\r\n" } } None => "$-1\r\n".to_string(), } // end match } Err(_) => "-Error\r\n".to_string(), } // end match } /* fn serialize_to_simple_string(s: &[u8]) -> Vec<u8> { [b"+", s, b"\r\n"].concat() } fn serialize_to_bulk_string(s: &[u8]) -> Vec<u8> { [b"$", format!("{}", s.len()).as_bytes(), b"\r\n", s, b"\r\n"].concat() } */ #[derive(Debug)] enum Command { Ping, Echo(String), Set(String, String, Option<u64>), Get(String), } enum DataType { SimpleString, SimpleErr, Integer, BulkString, Array, }
{ "domain": "codereview.stackexchange", "id": 45605, "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": "rust, tcp, redis", "url": null }
rust, tcp, redis enum DataType { SimpleString, SimpleErr, Integer, BulkString, Array, } impl DataType { fn from_byte(b: u8) -> Self { match b { b'+' => Self::SimpleString, b'-' => Self::SimpleErr, b':' => Self::Integer, b'$' => Self::BulkString, b'*' => Self::Array, _ => unimplemented!(), } } } #[derive(Debug)] enum RedisObject { SimpleString(String), SimpleErr(String), Integer(i32), BulkString(usize, String), Array(Vec<RedisObject>), } struct Parser<'a> { stream: &'a [u8], } impl<'a> Parser<'a> { fn new(stream: &'a [u8]) -> Self { Self { stream } } fn parse(&mut self) -> Result<RedisObject, ()> { match Self::parse_object(self.stream) { Ok((Some(object), _)) => Ok(object), Ok(_) => Err(()), Err(_) => Err(()), } }
{ "domain": "codereview.stackexchange", "id": 45605, "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": "rust, tcp, redis", "url": null }
rust, tcp, redis fn parse_object(stream: &[u8]) -> Result<(Option<RedisObject>, usize), ()> { if stream[0..2] == *b"\r\n" { return Ok((None, 2)); } match DataType::from_byte(stream[0]) { DataType::Array => Parser::parse_array(&stream[1..]), DataType::SimpleString => { let parts = split_by_line(&stream[1..]); Ok(( Some(RedisObject::SimpleString( String::from_utf8(parts[0].clone()).unwrap(), )), parts[0].len(), )) } DataType::Integer => { let parts = split_by_line(&stream[1..]); Ok(( Some(RedisObject::Integer( String::from_utf8(parts[0].clone()) .unwrap() .parse::<i32>() .unwrap(), )), parts[0].len(), )) } DataType::BulkString => { let parts = split_by_line(&stream[1..]); let Ok(size) = String::from_utf8(parts[0].clone()) .unwrap() .parse::<usize>() else { panic!("invalid string"); }; let string = String::from_utf8(parts[1].clone()).unwrap(); assert!(string.len() == size as usize); Ok(( Some(RedisObject::BulkString(size, string)), parts[0].len() + parts[1].len() + 3, )) } _ => unimplemented!("type not implemented"), } }
{ "domain": "codereview.stackexchange", "id": 45605, "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": "rust, tcp, redis", "url": null }
rust, tcp, redis fn parse_array(stream: &[u8]) -> Result<(Option<RedisObject>, usize), ()> { let parts = split_by_line(stream); let _size = String::from_utf8(parts[0].clone()) .expect("invalid string") .parse::<usize>() .expect("invalid string"); let mut objects = vec![]; let mut pos: usize = parts[0].len() + 2; loop { match Parser::parse_object(&stream[pos..]) { Ok((Some(object), consumed)) => { objects.push(object); pos += consumed; if pos > stream.len() { break; } } Ok((None, consumed)) => { pos += consumed; if pos >= stream.len() { break; } } Err(_) => { return Err(()); } } } println!("{objects:?}"); Ok((Some(RedisObject::Array(objects)), pos)) } } fn split_by_line(stream: &[u8]) -> Vec<Vec<u8>> { let line_positions = stream .windows(2) .enumerate() .filter(|(_, w)| w == b"\r\n") .map(|(i, _)| i) .collect::<Vec<_>>(); let mut lines = vec![stream[..line_positions[0]].to_vec()]; lines.extend( line_positions .windows(2) .map(|i| stream[i[0] + 2..i[1]].to_vec()) .collect::<Vec<_>>(), ); lines.push(stream[*line_positions.last().unwrap() + 2..].to_vec()); lines .into_iter() .filter(|l| !l.is_empty()) .collect::<Vec<_>>() }
{ "domain": "codereview.stackexchange", "id": 45605, "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": "rust, tcp, redis", "url": null }
rust, tcp, redis impl Command { fn from_buffer(buf: &[u8]) -> Result<Self, ()> { let mut p = Parser::new(buf); match p.parse() { Ok(object) => match object { RedisObject::Array(arr) => match arr.as_slice() { [RedisObject::BulkString(4, s)] => { if s.to_uppercase() == "PING".to_string() { Ok(Command::Ping) } else { Err(()) } } [RedisObject::BulkString(4, s), RedisObject::BulkString(_, o)] => { if s.to_uppercase() == "ECHO".to_string() { Ok(Command::Echo(o.to_string())) } else { Err(()) } } [RedisObject::BulkString(3, s), RedisObject::BulkString(_, key)] => { if s.to_uppercase() == "GET".to_string() { Ok(Command::Get(key.to_string())) } else { Err(()) } } [RedisObject::BulkString(3, s), RedisObject::BulkString(_, key), RedisObject::BulkString(_, value), RedisObject::BulkString(2, ex), RedisObject::BulkString(_, duration)] => { if s.to_uppercase() == "SET".to_string() && ex.to_uppercase() == "PX" && duration.parse::<u64>().is_ok() { Ok(Command::Set( key.to_string(), value.to_string(), Some(duration.parse::<u64>().unwrap()), )) } else { Err(()) } }
{ "domain": "codereview.stackexchange", "id": 45605, "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": "rust, tcp, redis", "url": null }
rust, tcp, redis Err(()) } } [RedisObject::BulkString(3, s), RedisObject::BulkString(_, key), RedisObject::BulkString(_, value)] => { if s.to_uppercase() == "SET".to_string() { Ok(Command::Set(key.to_string(), value.to_string(), None)) } else { Err(()) } } _ => Err(()), }, _ => Err(()), }, Err(_) => Err(()), } } }
{ "domain": "codereview.stackexchange", "id": 45605, "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": "rust, tcp, redis", "url": null }
c++, algorithm, image, matrix, c++20 Title: Image Rotation and Transpose Functions Implementation in C++ Question: This is a follow-up question for Gaussian Fisheye Image Generator Implementation in C++ and An Updated Multi-dimensional Image Data Structure with Variadic Template Functions in C++. I am trying to implement image rotation function in this post. The example output: Image Input Output The experimental implementation rotate, rotate_detail and rotate_degree template functions implementation (in file image_operations.h) rotate_detail template function performs image rotation operation between 0° to 90°. namespace TinyDIP { // rotate_detail template function implementation // rotate_detail template function performs image rotation between 0° to 90° template<arithmetic ElementT, std::floating_point FloatingType = double> constexpr static auto rotate_detail(const Image<ElementT>& input, FloatingType radians) { if (input.getDimensionality()!=2) { throw std::runtime_error("Unsupported dimension!"); } // if 0° rotation case if (radians == 0) { return input; } // if 90° rotation case if(radians == std::numbers::pi_v<long double> / 2.0) { Image<ElementT> output(input.getHeight(), input.getWidth()); for (std::size_t y = 0; y < input.getHeight(); ++y) { for (std::size_t x = 0; x < input.getWidth(); ++x) { output.at(input.getHeight() - y - 1, x) = input.at(x, y); } } return output; }
{ "domain": "codereview.stackexchange", "id": 45606, "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, image, matrix, c++20", "url": null }
c++, algorithm, image, matrix, c++20 FloatingType half_width = static_cast<FloatingType>(input.getWidth()) / 2.0; FloatingType half_height = static_cast<FloatingType>(input.getHeight()) / 2.0; FloatingType new_width = 2 * std::hypot(half_width, half_height) * std::abs(std::sin(std::atan2(half_width, half_height) + radians)); FloatingType new_height = 2 * std::hypot(half_width, half_height) * std::abs(std::sin(std::atan2(half_height, half_width) + radians)); Image<ElementT> output(input.getWidth(), input.getHeight()); for (std::size_t y = 0; y < input.getHeight(); ++y) { for (std::size_t x = 0; x < input.getWidth(); ++x) { FloatingType distance_x = x - half_width; FloatingType distance_y = y - half_height; FloatingType distance = std::hypot(distance_x, distance_y); FloatingType angle = std::atan2(distance_y, distance_x) + radians; FloatingType width_ratio = new_width / static_cast<FloatingType>(input.getWidth()); FloatingType height_ratio = new_height / static_cast<FloatingType>(input.getHeight()); FloatingType distance_weight = (input.getWidth() > input.getHeight())?(1 / height_ratio):(1 / width_ratio); FloatingType new_distance = distance * distance_weight; FloatingType new_distance_x = new_distance * std::cos(angle); FloatingType new_distance_y = new_distance * std::sin(angle); output.at( static_cast<std::size_t>(new_distance_x + half_width), static_cast<std::size_t>(new_distance_y + half_height)) = input.at(x, y); } } return output; }
{ "domain": "codereview.stackexchange", "id": 45606, "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, image, matrix, c++20", "url": null }
c++, algorithm, image, matrix, c++20 // rotate template function implementation template<arithmetic ElementT, std::floating_point FloatingType = double> constexpr static auto rotate(const Image<ElementT>& input, FloatingType radians) { if (input.getDimensionality()!=2) { throw std::runtime_error("Unsupported dimension!"); } auto output = input; while(radians >= 2 * std::numbers::pi_v<long double>) { radians = radians - 2 * std::numbers::pi_v<long double>; } while(radians > std::numbers::pi_v<long double> / 2.0) { output = rotate_detail(output, std::numbers::pi_v<long double> / 2.0); radians-=(std::numbers::pi_v<long double> / 2.0); } output = rotate_detail(output, radians); return output; } // rotate template function implementation template<typename ElementT, class FloatingType = double> requires ((std::same_as<ElementT, RGB>) || (std::same_as<ElementT, HSV>)) constexpr static auto rotate(const Image<ElementT>& input, FloatingType radians) { if (input.getDimensionality()!=2) { throw std::runtime_error("Unsupported dimension!"); } return apply_each(input, [&](auto&& planes) { return rotate(planes, radians); }); } // rotate template function implementation template<arithmetic ElementT, std::integral T = int> constexpr static auto rotate(const Image<ElementT>& input, T radians) { if (input.getDimensionality()!=2) { throw std::runtime_error("Unsupported dimension!"); } return rotate(input, static_cast<double>(radians)); }
{ "domain": "codereview.stackexchange", "id": 45606, "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, image, matrix, c++20", "url": null }
c++, algorithm, image, matrix, c++20 // rotate_degree template function implementation template<typename ElementT, class T = double> constexpr static auto rotate_degree(const Image<ElementT>& input, T degrees) { if (input.getDimensionality()!=2) { throw std::runtime_error("Unsupported dimension!"); } return rotate(input, static_cast<double>(degrees) * std::numbers::pi_v<long double> / 180.0); } } transpose template function implementation (in file image_operations.h) namespace TinyDIP { // transpose template function implementation template<typename ElementT> constexpr static auto transpose(const Image<ElementT>& input) { if (input.getDimensionality()!=2) { throw std::runtime_error("Unsupported dimension!"); } Image<ElementT> output(input.getHeight(), input.getWidth()); for (std::size_t y = 0; y < input.getHeight(); ++y) { for (std::size_t x = 0; x < input.getWidth(); ++x) { output.at(y, x) = input.at(x, y); } } return output; } } Image class implementation (in file image.h) namespace TinyDIP { template <typename ElementT> class Image { public: Image() = default; template<std::same_as<std::size_t>... Sizes> Image(Sizes... sizes): size{sizes...}, image_data((1 * ... * sizes)) {} template<std::same_as<int>... Sizes> Image(Sizes... sizes) { size.reserve(sizeof...(sizes)); (size.push_back(sizes), ...); image_data.resize( std::reduce( std::ranges::cbegin(size), std::ranges::cend(size), std::size_t{1}, std::multiplies<>() ) ); }
{ "domain": "codereview.stackexchange", "id": 45606, "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, image, matrix, c++20", "url": null }
c++, algorithm, image, matrix, c++20 template<std::ranges::input_range Range, std::same_as<std::size_t>... Sizes> Image(const Range& input, Sizes... sizes): size{sizes...}, image_data(begin(input), end(input)) { if (image_data.size() != (1 * ... * sizes)) { throw std::runtime_error("Image data input and the given size are mismatched!"); } } Image(std::vector<ElementT>&& input, std::size_t newWidth, std::size_t newHeight) { size.reserve(2); size.emplace_back(newWidth); size.emplace_back(newHeight); if (input.size() != newWidth * newHeight) { throw std::runtime_error("Image data input and the given size are mismatched!"); } image_data = std::move(input); // Reference: https://stackoverflow.com/a/51706522/6667035 } Image(const std::vector<std::vector<ElementT>>& input) { size.reserve(2); size.emplace_back(input[0].size()); size.emplace_back(input.size()); for (auto& rows : input) { image_data.insert(image_data.end(), std::ranges::begin(input), std::ranges::end(input)); // flatten } return; } // at template function implementation template<typename... Args> constexpr ElementT& at(const Args... indexInput) { return const_cast<ElementT&>(static_cast<const Image &>(*this).at(indexInput...)); }
{ "domain": "codereview.stackexchange", "id": 45606, "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, image, matrix, c++20", "url": null }
c++, algorithm, image, matrix, c++20 // at template function implementation // Reference: https://codereview.stackexchange.com/a/288736/231235 template<typename... Args> constexpr ElementT const& at(const Args... indexInput) const { checkBoundary(indexInput...); constexpr std::size_t n = sizeof...(Args); if(n != size.size()) { throw std::runtime_error("Dimensionality mismatched!"); } std::size_t i = 0; std::size_t stride = 1; std::size_t position = 0; auto update_position = [&](auto index) { position += index * stride; stride *= size[i++]; }; (update_position(indexInput), ...); return image_data[position]; } constexpr std::size_t count() const noexcept { return std::reduce(std::ranges::cbegin(size), std::ranges::cend(size), 1, std::multiplies()); } constexpr std::size_t getDimensionality() const noexcept { return size.size(); } constexpr std::size_t getWidth() const noexcept { return size[0]; } constexpr std::size_t getHeight() const noexcept { return size[1]; } constexpr auto getSize() noexcept { return size; } std::vector<ElementT> const& getImageData() const noexcept { return image_data; } // expose the internal data
{ "domain": "codereview.stackexchange", "id": 45606, "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, image, matrix, c++20", "url": null }
c++, algorithm, image, matrix, c++20 void print(std::string separator = "\t", std::ostream& os = std::cout) const { if(size.size() == 1) { for(std::size_t x = 0; x < size[0]; ++x) { // Ref: https://isocpp.org/wiki/faq/input-output#print-char-or-ptr-as-number os << +at(x) << separator; } os << "\n"; } else if(size.size() == 2) { for (std::size_t y = 0; y < size[1]; ++y) { for (std::size_t x = 0; x < size[0]; ++x) { // Ref: https://isocpp.org/wiki/faq/input-output#print-char-or-ptr-as-number os << +at(x, y) << separator; } os << "\n"; } os << "\n"; } else if (size.size() == 3) { for(std::size_t z = 0; z < size[2]; ++z) { for (std::size_t y = 0; y < size[1]; ++y) { for (std::size_t x = 0; x < size[0]; ++x) { // Ref: https://isocpp.org/wiki/faq/input-output#print-char-or-ptr-as-number os << +at(x, y, z) << separator; } os << "\n"; } os << "\n"; } os << "\n"; } }
{ "domain": "codereview.stackexchange", "id": 45606, "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, image, matrix, c++20", "url": null }
c++, algorithm, image, matrix, 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 < size[1]; ++y) { for (std::size_t x = 0; x < size[0]; ++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; } Image<ElementT>& setAllValue(const ElementT input) { std::fill(std::ranges::begin(image_data), std::ranges::end(image_data), input); return *this; } friend std::ostream& operator<<(std::ostream& os, const Image<ElementT>& rhs) { const std::string separator = "\t"; rhs.print(separator, os); return os; } Image<ElementT>& operator+=(const Image<ElementT>& rhs) { check_size_same(rhs, *this); 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; } Image<ElementT>& operator-=(const Image<ElementT>& rhs) { check_size_same(rhs, *this); 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; }
{ "domain": "codereview.stackexchange", "id": 45606, "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, image, matrix, c++20", "url": null }
c++, algorithm, image, matrix, c++20 Image<ElementT>& operator*=(const Image<ElementT>& rhs) { check_size_same(rhs, *this); 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) { check_size_same(rhs, *this); 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; } friend Image<ElementT> operator*(Image<ElementT> input1, ElementT input2) { return multiplies(input1, input2); } friend Image<ElementT> operator*(ElementT input1, Image<ElementT> input2) { return multiplies(input2, input1); } #ifdef USE_BOOST_SERIALIZATION
{ "domain": "codereview.stackexchange", "id": 45606, "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, image, matrix, c++20", "url": null }
c++, algorithm, image, matrix, c++20 #ifdef USE_BOOST_SERIALIZATION void Save(std::string filename) { const std::string filename_with_extension = filename + ".dat"; // Reference: https://stackoverflow.com/questions/523872/how-do-you-serialize-an-object-in-c std::ofstream ofs(filename_with_extension, std::ios::binary); boost::archive::binary_oarchive ArchiveOut(ofs); // write class instance to archive ArchiveOut << *this; // archive and stream closed when destructors are called ofs.close(); } #endif private: std::vector<std::size_t> size; std::vector<ElementT> image_data; template<typename... Args> void checkBoundary(const Args... indexInput) const { constexpr std::size_t n = sizeof...(Args); if(n != size.size()) { throw std::runtime_error("Dimensionality mismatched!"); } std::size_t parameter_pack_index = 0; auto function = [&](auto index) { if (index >= size[parameter_pack_index]) throw std::out_of_range("Given index out of range!"); parameter_pack_index = parameter_pack_index + 1; }; (function(indexInput), ...); } #ifdef USE_BOOST_SERIALIZATION friend class boost::serialization::access; template<class Archive> void serialize(Archive& ar, const unsigned int version) { ar& size; ar& image_data; } #endif }; template<typename T, typename ElementT> concept is_Image = std::is_same_v<T, Image<ElementT>>; } #endif The usage of rotate function: std::string file_path = "InputImages/1"; auto bmp1 = TinyDIP::bmp_read(file_path.c_str(), false); bmp1 = rotate(bmp1, 1.0); TinyDIP::bmp_write("test", bmp1);
{ "domain": "codereview.stackexchange", "id": 45606, "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, image, matrix, c++20", "url": null }
c++, algorithm, image, matrix, c++20 The usage transpose function: template<typename ElementT> void transposeTest(const size_t size = 5) { std::cout << "Test with 2D image:\n"; auto image2d = TinyDIP::Image<ElementT>(size, size); image2d.setAllValue(1); image2d.at(0, 1) = 3; image2d.print(); TinyDIP::transpose(image2d).print(); return; } Godbolt link is here. TinyDIP on GitHub All suggestions are welcome. The summary information: Which question it is a follow-up to? Gaussian Fisheye Image Generator Implementation in C++ and An Updated Multi-dimensional Image Data Structure with Variadic Template Functions in C++ What changes has been made in the code since last question? I am trying to implement image rotation and transpose function in this post. Why a new review is being asked for? Please review the implementation of rotate and transpose template functions.
{ "domain": "codereview.stackexchange", "id": 45606, "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, image, matrix, c++20", "url": null }
c++, algorithm, image, matrix, c++20 Answer: Avoid trigonometric functions where possible Trigonometric functions like atan2(), sin() and cos() are very slow. You do three of those operations per pixel, which is going to be the major performance issue with your code. There is a way to avoid doing any per-pixel trigonometry though, and that is by decomposing the rotation into three shear operations, like for example shown in this StackOverflow question. Loop over the output pixels You loop over the input pixels, and remap their coordinates to the output. However, you will then have a risk that you miss some output pixels, as some might be skipped due to floating point rounding. Maybe you get lucky most of the time, but to avoid the problem, loop over the output pixels, and remap their coordinates to the input to find out which color to copy. Even better, if you use the shearing technique then you can avoid this issue completely. Handle negative rotation angles rotate() seems to only check for radians being too large in the positive direction, but doesn't check for potentially large negative values. I also recommend you use std::fmod() or something similar to truncate the angle here, instead of using a while-loop. Avoid rotating up to four times If the angle is between \$1\frac{1}{2} \pi\$ and \$2 \pi\$, you are performing four rotations. You should be able to rotate everything in one go (or if you use shear operations, using not more than 3 shears). If your algorithm really can't handle rotations larger than 90 degrees, then at least implement a fast algorithm to do 90, 180 and 270 degree rotations, as these are trivial to implement.
{ "domain": "codereview.stackexchange", "id": 45606, "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, image, matrix, c++20", "url": null }
python, ai, neural-network, pytorch Title: One-layer linear neural network to solve a regression problem in PyTorch Question: Good morning everyone, I am trying to figure out how deep learning works. My approach is mainly theoretical but I have decided to code a few deep learning projects to get a better feel of the kind of work involved. Most courses and textbooks out there recommend that your first project as an aspiring AI engineer should be a linear neural network that solves some simple problem. So, I have coded one such network with a single layer and I have trained it to solve a linear regression problem. I have used Dive into deep learning as a reference, but I have decided against developing the whole network from scratch as they do because I don't want to get bogged down in the details, and I'd much rather have a bird's-eye view of the field for the time being. Thus, I tried to use the high level abstract tools provided by the Pytorch library. I hope you can tell me whether I have put such tools to good use or not. In particular, I would like to get feedback on the general architecture of the program and the OOP aspects of it. All advice is welcome, though. The project is divided into 4 files. model.py defines the model architecture: """One layer linear neural network model to solve regression problems.""" import torch from torch import nn class LinearRegressionModel(nn.Module): """Linear neural network model used to solve linear regression problems.""" def __init__(self, number_of_features: int): """ Constructor for LinearRegressionModel. :param number_of_features: number of features used to compute a label. """ super().__init__() # Randomly initialize as many weights as there are feature and randomly initialize a bias. self.weights = nn.Parameter(torch.rand(number_of_features), requires_grad=True) self.bias = nn.Parameter(torch.rand(1), requires_grad=True)
{ "domain": "codereview.stackexchange", "id": 45607, "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, ai, neural-network, pytorch", "url": null }
python, ai, neural-network, pytorch def forward(self, instances: torch.Tensor) -> torch.Tensor: """Forward function for the neural network. Pass the input instances through a linear layer: return 'instances*weights + bias'. """ return torch.matmul(instances, self.weights) + self.bias data.py handles the synthetic data to train the model (I am using synthetic data for simplicity's sake): """Synthetic linear data generation.""" import torch class SyntheticLinearDataset(torch.utils.data.Dataset): """Create synthetic linear data polluted by noise according to a normal distribution.""" def __init__(self, weights: torch.Tensor, bias: torch.Tensor, noise: float, number_of_instances: int): """ Constructor for SyntheticLinearDataset. Store weights, bias, and noise as attributes. Generate the linear data and pollute it with noise. :param weights: True weights used to generate linear data. 'weights.size(0)' will be taken as the number of features in the generated data. :param bias: True bias used to generate linear data. :param noise: Standard deviation of the noise. :param number_of_instances: number of instances that are to be generated. """ # Store the parameters. self.weights = weights.unsqueeze(-1) self.bias = bias self.noise = noise # Generate the linear data and pollute it with noise. self.instances = torch.rand(number_of_instances, self.weights.size(0)) self.labels = torch.matmul(self.instances, self.weights) + self.bias self.labels += (torch.randn(number_of_instances, self.weights.size(0))*self.noise) def __getitem__(self, item): """Overload indexing to allow DataLoader to retrieve the data.""" return self.instances[item], self.labels[item] def __len__(self): """Return the length of the dataset.""" return len(self.instances)
{ "domain": "codereview.stackexchange", "id": 45607, "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, ai, neural-network, pytorch", "url": null }
python, ai, neural-network, pytorch visualization.py contains a function that allows me to draw a scatter plot to visualize the model's predictions: """Visualization tools to compare actual data with neural network predictions.""" import matplotlib.pyplot as plt import torch from torch import nn from torch.utils.data import DataLoader def plot_predictions(model: nn.Module, dataloader: DataLoader, title: str = None): """Take a random batch of data and plot the model-predicted labels against the actual labels. :param model: neural network. :param dataloader: dataloader used to load the random batch. :param title: title of the plot. :returns: None """ instances, labels = next(iter(dataloader)) with torch.inference_mode(): predictions = model(instances) plt.figure() plt.title(title) plt.scatter(instances, labels, c='b', s=4, label="Actual data") plt.scatter(instances, predictions, c='r', s=4, label="Model predictions") plt.legend() plt.show() main.py uses the classes and functions defined in the other files to actually generate the data, create the model, specify the hyperparameters, train the model, and finally plot the data: """Create a one layer linear neural network and train it to solve a linear regression problem with synthetic data.""" import torch from torch import nn from torch.utils.data import DataLoader, random_split from data import SyntheticLinearDataset from model import LinearRegressionModel from visualization import plot_predictions def training_loop(model: nn.Module, dataloader: DataLoader, number_of_epochs: int, loss_function, optimizer): """raining loop for LinearRegressionModel. Train the model using backpropagation and minibatch stochastic gradient descent (MSGD).
{ "domain": "codereview.stackexchange", "id": 45607, "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, ai, neural-network, pytorch", "url": null }
python, ai, neural-network, pytorch Train the model using backpropagation and minibatch stochastic gradient descent (MSGD). :param model: model to be trained. :param dataloader: dataloader for the training data. :param number_of_epochs: number of training epochs. :param loss_function: loss function. :param optimizer: optimizer. :returns: None """ for epoch in range(number_of_epochs): # Apply MSGD for instances, labels in dataloader: model.train() predictions = model(instances).unsqueeze(-1) loss = loss_function(predictions, labels) optimizer.zero_grad() loss.backward() optimizer.step() # Create and split dataset. Use an 80% vs 20% split for training data vs testing data. number_of_features = 1 number_of_instances = 10000 weights = torch.rand(number_of_features) bias = torch.rand(1) noise = 0.01 dataset = SyntheticLinearDataset(weights, bias, noise, number_of_instances) training_length = int(number_of_instances*0.8) testing_length = number_of_instances - training_length training_dataset, testing_dataset = random_split(dataset, [training_length, testing_length]) # Create model. regression_model = LinearRegressionModel(number_of_features) # Create hyperparameters. learning_rate = 0.1 batch_size = 100 num_epochs = 100 # Create optimizer and loss function. mse_loss_function = nn.MSELoss() sgd_optimizer = torch.optim.SGD(params=regression_model.parameters(), lr=learning_rate) # Create data loaders. training_dataloader = DataLoader(training_dataset, batch_size, shuffle=True) testing_dataloader = DataLoader(testing_dataset, batch_size, shuffle=True) # Visualize predictions before training. plot_predictions(regression_model, testing_dataloader, title="Before training") # Execute training loop. training_loop(regression_model, training_dataloader, num_epochs, mse_loss_function, sgd_optimizer)
{ "domain": "codereview.stackexchange", "id": 45607, "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, ai, neural-network, pytorch", "url": null }
python, ai, neural-network, pytorch # Visualize predictions after training. plot_predictions(regression_model, testing_dataloader, title="After training") A couple of questions that come to mind are: Should I import torch and its submodules in every file? Is it good practice to import a library so many times? Should I create a class to train my model, or is having a training_loop function a good approach? Once again, thank you all for your priceless advice. As a self-learning student of programming, this forum is helping me so much! I hope I can get good enough to be in a position where I'm able to give back to this community. Answer: Should I import torch and its submodules in every file? Is it good practice to import a library so many times? Yes. Yes. If you need it, import it. Don't worry, there's zero cost if you already imported it somewhere else in this process -- you'll just get a cache hit. Should I create a class to train my model, or is having a training_loop function a good approach? I feel you're asking the wrong question. Better to ask: Is training_loop() sufficient for our business needs? Looks like the answer is "yes!" So we're done. OTOH we might have needed several collaborating functions, which turn out to be passing (x,y,z), and (x,y,z), and always (x,y,z) around amongst themselves. Which suggests that those three parameters should perhaps be lumped together as a single object. Or perhaps we'd like to have a class whose objects can conveniently have methods refer to self.x self.y self.z
{ "domain": "codereview.stackexchange", "id": 45607, "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, ai, neural-network, pytorch", "url": null }
python, ai, neural-network, pytorch self.x self.y self.z main.py Your main module defines nearly twenty global variables before it gets around to invoking training_loop(). Humans can maybe hold seven or nine items in their head at once, fewer if the items are on the abstract side. It would be useful to bury that code within def main():, if only so the local variables disappear once we return and then they will go out of scope. Having done that, you might see opportunities to Extract Helper functions. Three dozen lines of source fits in a screenful and is not necessarily Too Long. But as written, the narrative is not very clear, it wanders between high- and low-level details, it does not remain at a single level of abstraction. What I'm looking for is a business problem to be solved, steps to accomplish that, and then decompositions into smaller problems that eventually are so trivial they are one-liners. Often the way to get to that is to read each # comment, and decide whether it suggests that several lines should be bundled up as some def _helper function.
{ "domain": "codereview.stackexchange", "id": 45607, "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, ai, neural-network, pytorch", "url": null }
python, object-oriented, api, rest, fastapi Title: Users CRUD in fastapi using pymongo Question: I am building users API with CRUD operation in fastapi and i'd love to hear feedback about it. I have been exploring fastapi in the past weeks and im trying to create API with best practice (scalable - no pagination yet, robust, effective and efficient) route.py from fastapi import APIRouter, Depends from users.serializer import User from users.schema import UserUpdate, UserResponse, UserCreate, UserFilter user_router = APIRouter( prefix="/users", tags= ["Users"] ) @user_router.get("/",response_model=list[UserResponse]) def get_users(): return User.get_all() @user_router.get("/filter", response_model=list[UserResponse]) def filter_user(query: UserFilter = Depends()): filter = User.filter(dict(query)) return filter @user_router.get("/{id}", response_model=UserResponse) def get_user(id: str): user = User.get(id) return user @user_router.post("/", response_model=UserResponse) def save_user(user: UserCreate): new_user = User(dict(user)) return new_user.create() @user_router.put("/{id}", response_model=UserResponse) def update_user(id: str, updated_user: UserUpdate): user = User(updated_user) return user.update(id) @user_router.delete("/{id}") def delete_user(id: str): user = User.delete(id) return user schema.py from typing import Optional from pydantic import BaseModel, EmailStr, model_validator from datetime import datetime class UserCreate(BaseModel): username: str email: EmailStr password: str first_name: str last_name: str role: str status: str created_at: Optional[datetime] = datetime.now() updated_at: Optional[datetime] = datetime.now() class Config: orm_mode: True
{ "domain": "codereview.stackexchange", "id": 45608, "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, object-oriented, api, rest, fastapi", "url": null }
python, object-oriented, api, rest, fastapi class Config: orm_mode: True class UserUpdate(BaseModel): username: str email: EmailStr first_name: str last_name: str role: str status: str created_at: Optional[datetime] = datetime.now() updated_at: Optional[datetime] = datetime.now() class Config: orm_mode: True class UserResponse(BaseModel): id: str username: str email: EmailStr first_name: str last_name: str role: str status: str created_at: Optional[datetime] = datetime.now() updated_at: Optional[datetime] = datetime.now() class UserLogin(BaseModel): username: str password: str class UserFilter(BaseModel): username: Optional[str] = None email: Optional[EmailStr] = None first_name: Optional[str] = None last_name: Optional[str] = None role: Optional[str] = None status: Optional[str] = None serializer.py from utils.passwords import PasswordHandler from gateways.database import DatabaseGateway from fastapi import HTTPException, status collection_name = "users" class User: def __init__(self, data) -> None: self.data = data def create(self): password_handler = PasswordHandler() self.data["password"] = password_handler.hash(self.data["password"]) user = DatabaseGateway(collection_name) return user_serializer(user.save_document(self.data)) def update(self, id): del self.data.created_at user = DatabaseGateway(collection_name) return user_serializer(user.update_document(id, self.data)) def delete(id): user = DatabaseGateway(collection_name) result = user.delete_document(id) if result: return user_serializer(result) raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="user not found!") def filter(filter): clean_filter = {k: v for k, v in filter.items() if v is not None}
{ "domain": "codereview.stackexchange", "id": 45608, "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, object-oriented, api, rest, fastapi", "url": null }
python, object-oriented, api, rest, fastapi users = DatabaseGateway(collection_name) filtered_document = users.filter_document(clean_filter) serialized_users = serialize_list(filtered_document) if serialized_users: return serialized_users raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="user not found!") def get_all(): users = DatabaseGateway(collection_name) serialized_users = serialize_list(users.get_collection()) if serialized_users: return serialized_users raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="users not found!") def get(id): user = DatabaseGateway(collection_name) result = user.get_document(id) if result: return user_serializer(result) raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="user not found!") def user_serializer(data) -> dict: user = { "id": str(data["_id"]), "username": data["username"], "email": data["email"], "first_name": data["first_name"], "last_name": data["last_name"], "role": data["role"], "status": data["status"], "created_at": data["created_at"], "updated_at": data["updated_at"] } return user def serialize_list(users) -> list: return [user_serializer(user) for user in users] gateway/database.py from config.database import Database from bson import ObjectId from fastapi import HTTPException class DatabaseGateway: def __init__(self, collection_name): self.collection_name = collection_name def save_document(self, data): document = Database.collection(self.collection_name).insert_one(dict(data)) data["_id"] = str(document.inserted_id) return data def get_collection(self): return Database.collection(self.collection_name).find()
{ "domain": "codereview.stackexchange", "id": 45608, "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, object-oriented, api, rest, fastapi", "url": null }
python, object-oriented, api, rest, fastapi def get_document(self, id:str): vba = ObjectId.is_valid(id) if vba: return Database.collection(self.collection_name).find_one({"_id": ObjectId(id)}) def update_document(self, id, data:dict): document = Database.collection(self.collection_name) return document.find_one_and_update({"_id": ObjectId(id)}, {"$set": dict(data)}, return_document=True) def delete_document(self, id:str): vba = ObjectId.is_valid(id) if vba: return Database.collection(self.collection_name).find_one_and_delete({"_id": ObjectId(id)}) def filter_document(self, filter): return Database.collection(self.collection_name).find(filter) config/database.py client = MongoClient(config("db_client")) db = client.fms # list of modules/collection (users, author, books) collections = { "users": db['users'] } class Database: def collection(collection: str): if collection in collections: return collections[collection] I'd love your review or opinion on this, small or big. Thanks a lot! Answer: test suite There isn't one. love your review or opinion on this I don't quite know which way I should approach this. We have a big blob of code, with no def test_foo, def main, or other obvious entrypoint for exercising the target code. I imagine there's a way to run it, but it is not yet obvious to me what way that would be. So, ok, I will just read sequentially, and we'll see what comes of it. lint Run this through black, please? The random whitespace variations are just distracting. Thank you. May as well tack on isort whilst you're at it. Oh, and thank you kindly for the type annotations, they're lovely. mutable default def filter_user(query: UserFilter = Depends()):
{ "domain": "codereview.stackexchange", "id": 45608, "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, object-oriented, api, rest, fastapi", "url": null }
python, object-oriented, api, rest, fastapi I don't know exactly what's going on with Depends(). But it makes me nervous, since a great many python programmers have been tripped up by mutable parameter defaults, for example def foo(d: dict = {'a': 1, 'b': 2}): The gotcha is that d is given a default value just once, when we define foo, rather than being given N new dict's for N calls to foo(). This surprises some folks, since updates to that single d value will persist over a great many calls. tl;dr: Have the signature default to None, and then within the function assign query = query or Depends() to compute a new Depends instance on each call, when needed. credentials class UserCreate(BaseModel): username: str email: EmailStr password: str I don't understand that last line. In the sense that, I don't understand why anyone would store a cleartext password in a database. Data breaches happen. At most, an attacker should only be able to harvest hashes, preferably produced by argon2id. There is maybe some confusion in this codebase between "password" and "hash"? Also, if a per-user "salt" is being stored, I haven't seen that explicitly called out by the code. optional I dislike these: created_at: Optional[datetime] = datetime.now() updated_at: Optional[datetime] = datetime.now() Surely it is trivial to impose a NOT NULL constraint on those, right? How hard could it be to ask the DB to fill those in on every INSERT and UPDATE? I have routinely worked with such constraints, across several backend RDBMS vendors. Similarly for the other tables. It's just too easy to always fill in these timestamps, and they really will prove useful. nuke created def update(self, id): del self.data.created_at I don't understand what's going on there. This may relate to the whole "non-NULL created constraint" mentioned above. This record was created at a certain timestamp, that fact is immutable, and I don't get why we'd want to change that. shadowing "id": str(data["_id"]),
{ "domain": "codereview.stackexchange", "id": 45608, "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, object-oriented, api, rest, fastapi", "url": null }
python, object-oriented, api, rest, fastapi It's not obvious to me what's going on here. Many methods take an id parameter, which shadows the id builtin function, but I bit my tongue on those, it didn't seem troubling. The prefix _ convention is for a _private helper or variable. The suffix _ convention is to distinguish our id_ from the builtin id(). Those don't seem very relevant to dict key names, but I am happy to be enlightened. In user_serializer() I am a little sad that we didn't have enough uniformity to enable just looping over a bunch of key names. In DatabaseGateway, I confess I have no idea what the TLA vba denotes. We find no helpful # comments. type stability In {get,delete}_document, we either return a DB row or None. I find it troubling that we just fall off the end of the function; please replace that with an explicit return None. Please add docstrings to these methods, or ...) -> None: type annotations, which explain to the caller they will optionally get a DB row. Additionally, delete_document() really needs a docstring explaining what comes back, since the name suggests a "void" routine one would evaluate just for side effects.
{ "domain": "codereview.stackexchange", "id": 45608, "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, object-oriented, api, rest, fastapi", "url": null }
beginner, rust, console Title: Rust: Command line menu in ASCII table Question: Specific areas in which I'd love to get feedback: Is it good to have the Command struct own the Strings (description field)? Or since these strings aren't really meant to change, should I rather have them as &'static strs? I initially used String but then switched to &'static str, and then I saw this SO post and switched back to String. Within the print_table function, am I complicating the code by having the max_lengths (for two fields of the Command struct) as a tuple instead of using two separate scalar variables? Also, is there a more idiomatic way of finding the maximum of lengths of a String field in array of structs? I've seen imports being placed at the top (e.g., use std::cmp::max) before the functions are used (max(1, 2)). I know that this keeps the code terse. However, I'm also a fan of qualified naming (e.g., in Python, it's encouraged to do import math; math.pow(x, y) instead of from math import pow; pow(x, y)). This way, to readers, there's no confusion about the source of a function. What's the general consensus of Rust community? Up to each dev? fn main() { let commands: [Command; 3] = [ Command {code: '1', description: String::from("Start your instance")}, Command {code: '2', description: String::from("Stop your instance")}, Command {code: 'q', description: String::from("Quit")}, ]; print_table(&commands); for cmd in commands.iter() { match cmd.code { '1' => println!("Starting instance"), '2' => println!("Stopping instance"), 'q' => println!("Quitting"), _ => println!("Invalid option"), } } }
{ "domain": "codereview.stackexchange", "id": 45609, "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": "beginner, rust, console", "url": null }
beginner, rust, console fn print_table(commands: &[Command; 3]) { const BUFFER: usize = 2; const HEADING: (&str, &str) = ("Code", "Description"); const VERTICAL_BAR: &str = "│"; const HORIZONTAL_SEP: &str = "─"; std::process::Command::new("clear").status().unwrap(); let mut max_lengths: (usize, usize) = (0, 0); for cmd in commands.iter() { max_lengths.0 = std::cmp::max(max_lengths.0, cmd.code.len_utf8()); max_lengths.1 = std::cmp::max(max_lengths.1, cmd.description.len()); } max_lengths.0 = std::cmp::max(max_lengths.0, HEADING.0.len()); max_lengths.1 = std::cmp::max(max_lengths.1, HEADING.1.len()); let horizontal_lines: (&str, &str) = ( &HORIZONTAL_SEP.repeat(max_lengths.0 + BUFFER), &HORIZONTAL_SEP.repeat(max_lengths.1 + BUFFER), ); println!("╭{}┬{}╮", horizontal_lines.0, horizontal_lines.1); println!("{VERTICAL_BAR}{:^w1$}{VERTICAL_BAR} {:^w2$}{VERTICAL_BAR}", HEADING.0, HEADING.1, w1=max_lengths.0+BUFFER, w2=max_lengths.1+BUFFER-1); println!("├{}┼{}┤", horizontal_lines.0, horizontal_lines.1); for cmd in commands.iter() { println!("{VERTICAL_BAR}{:^w1$}{VERTICAL_BAR} {:<w2$}{VERTICAL_BAR}", cmd.code, cmd.description, w1=max_lengths.0+BUFFER, w2=max_lengths.1+BUFFER-1); } println!("╰{}┴{}╯", horizontal_lines.0, horizontal_lines.1); } struct Command { code: char, description: String, }
{ "domain": "codereview.stackexchange", "id": 45609, "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": "beginner, rust, console", "url": null }
beginner, rust, console struct Command { code: char, description: String, } Answer: I tend to favor &'static str when I can just for readability and for the same reason I declare things immutable when I can. The 'static lifetime is effectively the longest possible lifetime and for your code, so it doesn't invite the same lifetime issues for shorter-lived equivalents. Since you can freely replace one or the other and these strings are constants, I don't see a major advantage either way. The big thing with String is mutability, which you've said you don't need. I think you're duplicating some code in your print_table as well as juggling parallel structures. I also usually reserve tuples for cases where I know the length of the concept I'm representing is always fixed. For this I think a vector might be more appropriate (or at least something that can be extended and iterated over quickly). I would consolidate the information of a heading together. struct Heading { name: &'static str, length_fn: fn(&Command) -> usize } This will also make things more extensible if you ever add another column. I like to make extensive use of map to pipeline these types of calculations. I also chained some iterators here so you're not repeating max in the code. I would usually break these down into their own functions and move the Heading vec! declarations to elsewhere to clean it up, but I left that aside for conciseness. Examples follow let headings: Vec<Heading> = vec![ Heading { name: "Code", length_fn: |cmd| cmd.code.len_utf8(), }, Heading { name: "Description", length_fn: |cmd| cmd.description.len(), }, ];
{ "domain": "codereview.stackexchange", "id": 45609, "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": "beginner, rust, console", "url": null }
beginner, rust, console let buffer_lengths: Vec<usize> = headings.iter() .map(|heading| commands.iter() .map(|command| { (heading.length_fn)(&command) }).into_iter() .chain(std::iter::once(heading.name.len())) .max().unwrap_or(0) + BUFFER // Do your own error case ).collect(); let horizontal_lines: Vec<String> = buffer_lengths.iter() .map(|&len| HORIZONTAL_SEP.repeat(len)).collect(); then reference stuff like println!("╭{}┬{}╮", horizontal_lines[0], horizontal_lines[1]); println!("{VERTICAL_BAR}{:^w1$}{VERTICAL_BAR} {:^w2$}{VERTICAL_BAR}", headings[0].name, headings[1].name, w1 = buffer_lengths[0], w2 = buffer_lengths[1] - 1); I recognize the horizontal_lines is also a parallel structure to headings and you can probably do more consolidation refactoring how the text is printed. For two headings I might leave it for now. Thinking more on it, I'd also probably end up adding moving these into Heading itself and a new that takes the name, length closure, and the commands which does this calculation. Then Heading can be responsible for that data. That would do away with the obviously nested map. The important thing, though, is to move into iterators to streamline things. For imports, I think it's up to you on how and I've seen both ways. Clarity and readability are the important things. If it's a one-off I might leave the full one in for clarity unless I feel it's very obvious, but if it's repeated I usually do the import. I feel like in Python this is more important because of how it was cobbled together. What gets exported in Python libraries can become pretty big due to how namespacing (or, really, lack thereof) is done. You will find counterexamples of this in both languages, of course. I personally tend to write many shorter pieces of code rather than fewer and longer, so name collisions on imports aren't something I run across frequently. Salt and pepper to taste.
{ "domain": "codereview.stackexchange", "id": 45609, "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": "beginner, rust, console", "url": null }
c++, performance, concurrency Title: Multi Threaded High Performance txt file parsing Question: EDIT A port of Björn's answer to C++ with further improvements at bottom achieving up to 2.4GB/s on the reference machine. Text file parsing and processing continues to be a common task. Often it's slow, and can become a performance bottleneck if data is large or many files need to be processed. Background This is the next stage on from this question. As before the "Yahtzee" programming challenge shall serve as an illustrative example. Follow that link for full details, but the task is basically: Read ~1MB file with about ~100,000 newline separated ints (we are using that file repeated x1,000 because we got too fast => ~900MB; see below). Group them by hash map. We are using the 3rd party, ska::bytell_hash_map, instead of std::unordered_map, because it is about 2.5x faster. Find the group with the largest sum and return that sum. In the first code review I focused on: How to read the file efficiently => conclusion mmap (linux specific, see the other question for details and alternatives). How to parse efficiently => once we are efficiently reading the file, parsing becomes the bottleneck. The other question progressively moved to stripping the parsing right down to a tight loop incrementing a pointer over the mmap file with minimal checking / branching.
{ "domain": "codereview.stackexchange", "id": 45610, "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, concurrency", "url": null }
c++, performance, concurrency The file format here is very simple. One integer per line terminated with '\n'. We are assuming the data is in ASCII and no illegal characters exist; only [0-9]. The test file we used initially is this repeated a 1,000 times with: for i in {1..1000}; do cat yahtzee-upper-1.txt >> yahtzee-upper-big.txt ; done. This produces a file about 900MB in size, but with a very low cardinality (only 791 unique integers), which means the hashmap part of the algorithm is not too much of a bottleneck. See below for the second part of the challenge with a file with higher cardinality. With such stripped down code and mmap we were able to achieve ~540MB/s (1.7seconds for this file) using a single thread. (All timings are for a i7-2600 Sandy Bridge processor with 16GB of DDR3-1600 and a 500MB/s SSD, but note that we ensure that the file is OS cached so already in RAM. Hence the 500MB/s is not really relevant.) The next level In order to go faster still this question / code review focuses on going multi-threaded for the parsing. It turns out that the algorithm is Embarrassingly parallel if we chunk the mmap and just let each thread build its own hashmap and then combine them at the end. This last step is not significant (certainly not for the yahtzee-upper-big.txt file due to the low cardinality). Code is at bottom. It can achieve < 400ms for the full (cached)read, parse, hashmap and combine using 8 threads (that CPU has 4 cores + HT). (Note the os::fs::MemoryMappedFile class is my own RAII convenience wrapper for mmap). Scaling is not bad to 8 threads, but it visibly tails off. (Note that a tight single threaded loop spinning a pointer through the mmap takes ~140ms). 1 thread: ~1700ms 4 threads: ~680ms 6 threads: ~437ms 8 threads: ~390ms
{ "domain": "codereview.stackexchange", "id": 45610, "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, concurrency", "url": null }
c++, performance, concurrency This is quite good, although I would welcome feedback on the concurrency coding / style. The real challenge for this approach comes when we use a file with a higher cardinality (ie more unique integers and therefore a much bigger hashmap with more entries). Here is a small utility to generate a more challenging file: #include <iostream> #include <random> #include <fstream> #include <iomanip> int main(int argc, char* argv[]) { if (argc < 2) return 1; auto gen = std::mt19937{std::random_device{}()}; std::uniform_int_distribution<unsigned> dist(1'000'000, 2'000'000); auto file = std::ofstream{argv[1]}; // NOLINT for (std::size_t i = 0; i < 100'000'000; ++i) { file << dist(gen) << '\n'; } return 0; } run like this to make ~800MB file with cardinality 1,000,001. ./build/bin/yahtzee_gen yahtzee-upper-big2.txt The performance of this file, despite being slightly smaller, is much slower: ~2.1s on 8 threads. The single threaded performance is: 4.7seconds showing poor scalability. perf stat reports this: Performance counter stats for 'build/bin/yahtzee_mthr yahtzee-upper-big2.txt':
{ "domain": "codereview.stackexchange", "id": 45610, "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, concurrency", "url": null }
c++, performance, concurrency 14,159.77 msec task-clock # 6.044 CPUs utilized 2,789 context-switches # 0.197 K/sec 8 cpu-migrations # 0.001 K/sec 169,114 page-faults # 0.012 M/sec 49,300,366,303 cycles # 3.482 GHz (83.26%) 44,125,329,192 stalled-cycles-frontend # 89.50% frontend cycles idle (83.26%) 39,070,916,691 stalled-cycles-backend # 79.25% backend cycles idle (66.68%) 16,818,483,760 instructions # 0.34 insn per cycle # 2.62 stalled cycles per insn (83.36%) 2,613,261,878 branches # 184.555 M/sec (83.47%) 24,712,823 branch-misses # 0.95% of all branches (83.33%) 2.342779054 seconds time elapsed 13.755426000 seconds user 0.412222000 seconds sys Note the front and back-end idle cycles. I suspect that this kind of poor scalability can be typical where we are iterating through a large file whilst building up a significant size data structure from the input. A common use case? Note: We attempted CPU pinning (before switching from std::thread to std::async / std::future), but that made little difference. Feedback / Ideas Wanted Coding style and technique for the concurrent implementation. Ideas / code / tuning suggestions for helping improve the multi-threaded performance of the high cardinality file. And finally here is the code: #include "flat_hash_map/bytell_hash_map.hpp" #include "os/fs.hpp" #include <cstdint> #include <future> #include <iostream> #include <string> #include <string_view> #include <vector> using uint64 = std::uint64_t; using map_t = ska::bytell_hash_map<uint64, uint64>;
{ "domain": "codereview.stackexchange", "id": 45610, "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, concurrency", "url": null }
c++, performance, concurrency using uint64 = std::uint64_t; using map_t = ska::bytell_hash_map<uint64, uint64>; std::pair<const char* const, const char* const> from_sv(std::string_view sv) { return std::make_pair(sv.data(), sv.data() + sv.size()); } std::string_view to_sv(const char* const begin, const char* const end) { return std::string_view{begin, static_cast<std::size_t>(end - begin)}; } map_t parse(std::string_view buf) { auto map = map_t{}; auto [begin, end] = from_sv(buf); const char* curr = begin; uint64 val = 0; while (curr != end) { if (*curr == '\n') { map[val] += val; val = 0; } else { val = val * 10 + (*curr - '0'); } ++curr; // NOLINT } return map; } std::vector<std::string_view> chunk(std::string_view whole, int n_chunks, char delim = '\n') { auto [whole_begin, whole_end] = from_sv(whole); auto chunk_size = std::ptrdiff_t{(whole_end - whole_begin) / n_chunks}; auto chunks = std::vector<std::string_view>{}; const char* end = whole_begin; for (int i = 0; end != whole_end && i < n_chunks; ++i) { const char* begin = end; if (i == n_chunks - 1) { end = whole_end; // always ensure last chunk goes to the end } else { end = std::min(begin + chunk_size, whole_end); // NOLINT std::min for OOB check while (end != whole_end && *end != delim) ++end; // NOLINT ensure we have a whole line if (end != whole_end) ++end; // NOLINT one past the end } chunks.push_back(to_sv(begin, end)); } return chunks; } uint64 yahtzee_upper(const std::string& filename) { auto mfile = os::fs::MemoryMappedFile{filename}; unsigned n_threads = std::thread::hardware_concurrency(); auto fut_maps = std::vector<std::future<map_t>>{}; for (std::string_view chunk: chunk(mfile.get_buffer(), n_threads)) { // NOLINT fut_maps.push_back(std::async(std::launch::async, parse, chunk)); }
{ "domain": "codereview.stackexchange", "id": 45610, "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, concurrency", "url": null }
c++, performance, concurrency uint64 max_total = 0; auto final_map = map_t{}; for (auto&& fut_map: fut_maps) { map_t map = fut_map.get(); for (auto pair: map) { uint64 total = final_map[pair.first] += pair.second; if (total > max_total) max_total = total; } } std::cout << final_map.size() << "\n"; return max_total; } int main(int argc, char* argv[]) { if (argc < 2) return 1; std::cout << yahtzee_upper(argv[1]) << '\n'; // NOLINT return 0; } Answer: I hope you don't mind a pure C solution. For me it is easier to optimize code without C++ abstractions. But it should be straightforward to convert it to idiomatic C++ code. #include <assert.h> #include <math.h> #include <stdbool.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #ifdef _WIN32 #include <windows.h> #else #include <fcntl.h> #include <pthread.h> #include <sys/mman.h> #include <sys/stat.h> #endif ////////////////////////////////////////////////////////////////////////////// // Range of numbers, number of numbers and number of parser threads. ////////////////////////////////////////////////////////////////////////////// #define MIN_VALUE (1 * 1000 * 1000) #define MAX_VALUE (2 * 1000 * 1000) #define N_VALUES 400 * 1000 * 1000 #define N_THREADS 8 ////////////////////////////////////////////////////////////////////////////// // Timing functions. ////////////////////////////////////////////////////////////////////////////// #define NS_TO_S(x) ((double)(x) / 1000 / 1000 / 1000) uint64_t nano_count() { #ifdef _WIN32 static double scale_factor; static uint64_t hi = 0; static uint64_t lo = 0;
{ "domain": "codereview.stackexchange", "id": 45610, "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, concurrency", "url": null }
c++, performance, concurrency LARGE_INTEGER count; BOOL ret = QueryPerformanceCounter(&count); if (ret == 0) { printf("QueryPerformanceCounter failed.\n"); abort(); } if (scale_factor == 0.0) { LARGE_INTEGER frequency; BOOL ret = QueryPerformanceFrequency(&frequency); if (ret == 0) { printf("QueryPerformanceFrequency failed.\n"); abort(); } scale_factor = (1000000000.0 / frequency.QuadPart); } #ifdef CPU_64 hi = count.HighPart; #else if (lo > count.LowPart) { hi++; } #endif lo = count.LowPart; return (uint64_t)(((hi << 32) | lo) * scale_factor); #else struct timespec t; int ret = clock_gettime(CLOCK_MONOTONIC, &t); if (ret != 0) { printf("clock_gettime failed.\n"); abort(); } return (uint64_t)t.tv_sec * 1000000000 + t.tv_nsec; #endif } ////////////////////////////////////////////////////////////////////////////// // Generate the data file. ////////////////////////////////////////////////////////////////////////////// static int rand_in_range(int lo, int hi) { int range = hi - lo; int val = (rand() & 0xff) << 16 | (rand() & 0xff) << 8 | (rand() & 0xff); return (val % range) + lo; } static void run_generate(const char *path) { srand(1234); FILE *f = fopen(path, "wb"); for (int i = 0; i < N_VALUES; i++) { fprintf(f, "%d\n", rand_in_range(MIN_VALUE, MAX_VALUE)); } fclose(f); }
{ "domain": "codereview.stackexchange", "id": 45610, "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, concurrency", "url": null }
c++, performance, concurrency ////////////////////////////////////////////////////////////////////////////// // Fast number parser using loop unrolling macros. ////////////////////////////////////////////////////////////////////////////// #define PARSE_FIRST_DIGIT \ if (*at >= '0') { \ val = *at++ - '0'; \ } else { \ goto done; \ } #define PARSE_NEXT_DIGIT \ if (*at >= '0') { \ val = val*10 + *at++ - '0'; \ } else { \ goto done; \ } static void parse_chunk(char *at, const char *end, size_t *accum) { uint64_t val = 0; while (at < end) { // Parse up to 7 digits. PARSE_FIRST_DIGIT; PARSE_NEXT_DIGIT; PARSE_NEXT_DIGIT; PARSE_NEXT_DIGIT; PARSE_NEXT_DIGIT; PARSE_NEXT_DIGIT; PARSE_NEXT_DIGIT; done: #ifdef _WIN32 InterlockedExchangeAdd64(&accum[val], val); #else __sync_fetch_and_add(&accum[val], val); #endif // Skip newline character. at++; } } ////////////////////////////////////////////////////////////////////////////// // Thread definition ////////////////////////////////////////////////////////////////////////////// typedef struct { char *chunk_start; char *chunk_end; uint64_t *accum; } parse_chunk_thread_args; #ifdef _WIN32 static DWORD WINAPI parse_chunk_thread(LPVOID args) { parse_chunk_thread_args *a = (parse_chunk_thread_args *)args; parse_chunk(a->chunk_start, a->chunk_end, a->accum); return 0; } #else static void* parse_chunk_thread(void *args) { parse_chunk_thread_args *a = (parse_chunk_thread_args *)args; parse_chunk(a->chunk_start, a->chunk_end, a->accum); return NULL; } #endif
{ "domain": "codereview.stackexchange", "id": 45610, "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, concurrency", "url": null }
c++, performance, concurrency ////////////////////////////////////////////////////////////////////////////// // Parse the whole file. ////////////////////////////////////////////////////////////////////////////// static bool run_test(const char *path) { uint64_t time_start = nano_count(); #ifdef _WIN32 FILE *f = fopen(path, "rb"); fseek(f, 0, SEEK_END); uint64_t n_bytes = ftell(f); fseek(f, 0, SEEK_SET); char *buf_start = (char *)malloc(sizeof(char) * n_bytes); char *buf_end = buf_start + n_bytes; assert(fread(buf_start, 1, n_bytes, f) == n_bytes); fclose(f); #else int fd = open(path, O_RDONLY); if (fd == -1) { return false; } struct stat sb; if (fstat(fd, &sb) == -1) { return false; } uint64_t n_bytes = sb.st_size; char *buf_start = mmap(NULL, n_bytes, PROT_READ, MAP_PRIVATE, fd, 0); char *buf_end = buf_start + n_bytes; #endif uint64_t time_read = nano_count(); char *chunks[N_THREADS]; for (int i = 0; i < N_THREADS; i++) { chunks[i] = buf_start + (n_bytes / N_THREADS) * i; if (i > 0) { // Adjust the chunks starting points until they reach past // a newline. while (*chunks[i] != '\n') { chunks[i]++; } chunks[i]++; } } uint64_t *accum = calloc(MAX_VALUE, sizeof(uint64_t));
{ "domain": "codereview.stackexchange", "id": 45610, "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, concurrency", "url": null }
c++, performance, concurrency #if _WIN32 HANDLE threads[N_THREADS]; #else pthread_t threads[N_THREADS]; #endif parse_chunk_thread_args args[N_THREADS]; for (int i = 0; i < N_THREADS; i++) { char *chunk_start = chunks[i]; char *chunk_end = buf_end; if (i < N_THREADS - 1) { chunk_end = chunks[i + 1]; } args[i].chunk_start = chunk_start; args[i].chunk_end = chunk_end; args[i].accum = accum; #if _WIN32 threads[i] = CreateThread(NULL, 0, parse_chunk_thread, &args[i], 0, NULL); #else pthread_create(&threads[i], NULL, parse_chunk_thread, &args[i]); #endif } for (int i = 0; i < N_THREADS; i++) { #if _WIN32 WaitForSingleObject(threads[i], INFINITE); #else pthread_join(threads[i], NULL); #endif } uint64_t max = 0; for (int i = 0; i < MAX_VALUE; i++) { uint64_t val = accum[i]; if (val > max) { max = val; } } uint64_t time_parsed = nano_count(); free(accum); #if _WIN32 free(buf_start); #else if (munmap(buf_start, n_bytes) == -1) { return false; } #endif // Print timings. double read_secs = NS_TO_S(time_read - time_start); double parse_secs = NS_TO_S(time_parsed - time_read); double total_secs = NS_TO_S(time_parsed - time_start); printf("Read : %.3f seconds\n", read_secs); printf("Parse : %.3f seconds\n", parse_secs); printf("Total : %.3f seconds\n", total_secs); printf("-- Max: %zu\n", max); return true; }
{ "domain": "codereview.stackexchange", "id": 45610, "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, concurrency", "url": null }
c++, performance, concurrency int main(int argc, char *argv[]) { if (argc != 3) { printf("%s: [generate|test] path\n", argv[0]); return EXIT_FAILURE; } char *cmd = argv[1]; if (strcmp(cmd, "generate") == 0) { run_generate(argv[2]); } else if (strcmp(cmd, "test") == 0) { if (!run_test(argv[2])) { printf("Test run failed!\n"); return EXIT_FAILURE; } } else { printf("%s: [generate|test] path\n", argv[0]); return EXIT_FAILURE; } return EXIT_SUCCESS; } On my i7-6700 CPU desktop with 32 GB RAM, my code parses a 3.2 GB file in about 1.62 seconds and your code takes about eight seconds. I compile both programs with -march=native -mtune=native -O3 The main difference is that I'm using an array shared by all threads while you are using a hashmap for each thread. That is inefficient since the range of possible values is only one million. A hashmap would have the advantage over an array if the range of values was much larger than the number of values but that is not the case in your scenario. The array can be concurrently modified by all threads by using locking compiler intrinsics: #ifdef _WIN32 InterlockedExchangeAdd64(&accum[val], val); #else __sync_fetch_and_add(&accum[val], val); #endif
{ "domain": "codereview.stackexchange", "id": 45610, "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, concurrency", "url": null }
c++, performance, concurrency The intrinsics ensure that the updates are atomic and that threads don't interfere with each other. The last difference is #define PARSE_FIRST_DIGIT \ if (*at >= '0') { \ val = *at++ - '0'; \ } else { \ goto done; \ } #define PARSE_NEXT_DIGIT \ if (*at >= '0') { \ val = val*10 + *at++ - '0'; \ } else { \ goto done; \ } while (buf < end) { // Parse up to 7 digits. PARSE_FIRST_DIGIT; PARSE_NEXT_DIGIT; PARSE_NEXT_DIGIT; PARSE_NEXT_DIGIT; PARSE_NEXT_DIGIT; PARSE_NEXT_DIGIT; PARSE_NEXT_DIGIT; done: Here I have manually unrolled the parsing loop using macros. It improves performance by about 100 ms over your formulation when compiling with gcc. Linux vs. Windows On my laptop, the code runs a lot faster on Linux than on Windows. On Windows with an 1 600 MB file and 4 threads: Read : 1.170 seconds Parse : 3.119 seconds Total : 4.289 seconds -- Max: 498631000 Same setup on Linux: Read : 0.000 seconds Parse : 2.814 seconds Total : 2.814 seconds -- Max: 498631000
{ "domain": "codereview.stackexchange", "id": 45610, "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, concurrency", "url": null }
performance, beginner, algorithm, perl, bioinformatics Title: Highly nested bioinformatics processing Question: I have a script for parsing BAM files. The script's input thus is lines like E00489:44:HNNVYCCXX:3:1101:24890:5616 99 22 16052014 150M E00489:44:HNNVYCCXX:1:1110:21704:27345 99 22 16052044 150M E00489:44:HNNVYCCXX:1:1217:2372:69519 163 22 16052044 150M E00489:44:HNNVYCCXX:3:2123:8948:16779 99 22 16052044 150M E00489:44:HNNVYCCXX:2:2213:2920:25534 147 22 16052054 146M4S E00489:44:HNNVYCCXX:2:2206:5020:71717 83 22 16052055 145M5S E00489:44:HNNVYCCXX:4:2206:12642:40829 99 22 16052056 144M6S (The BAM file is actually run through cut -f1-4,6 before input to this script so this is only a subset of fields.) The first column is a kind of unique ID. The second is a bitwise flag. The third and fourth describe a chromosome and position in the human genome. The fifth is a CIGAR string, which is mostly what the script parses. I rarely use Perl, but it seems highly inefficient. It does work as intended, but it's slow. I'd like to speed it up and also make it more readable and easy-to-follow, if possible. #!/bin/perl #initialize hashes my %softhash; my %IDhash; my $file1Name = $ARGV[0] . 'all_sc_positions.txt'; my $file2Name = $ARGV[0] . 'edge_sc_positions.txt'; open(my $fh_all, '>', $file1Name); open(my $fh_edge, '>', $file2Name); #for each line while (my $line = <STDIN>) { #read in line and parse chomp($line); my @a = split("\t", $line); my $start = $a[3]; my $cigar = $a[4]; my @b = split(/[A-Z]/, $cigar);# keeps track of numbers my @c = split(/[0-9]*/, $cigar); #keeps track of letters my $loc = $start; #distance from start of read my $var_start; my $var_end; #loop over type of alignment in cigar string, build hashes of candidate locations for (my $i = 0; $i <= $#c; $i++) {
{ "domain": "codereview.stackexchange", "id": 45611, "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": "performance, beginner, algorithm, perl, bioinformatics", "url": null }
performance, beginner, algorithm, perl, bioinformatics #if there is softclipping or an indel, find the location and store in hash if ($c[$i] eq "S" || $c[$i] eq "I" || $c[$i] eq "D") { #find softclipping location if ($i == 1) { $var_start = $start - $b[0]; $var_end = $start; if ($c[$i] eq "S") { for (my $pos = $var_start; $pos < $var_end; $pos++) { $softhash{$a[2]}{$pos}++; } $var_start = $var_end - 1; $var_end = $var_start; } } else { for (my $j = $i-2; $j >= 0; $j--) {# subtract 2 from i, because the first value from c will always be empty $loc = $loc + $b[$j]; } $var_start = $loc; $var_end = $loc + $b[($i-1)]; if ($c[$i] eq "S") { for (my $pos=$var_start; $pos<$var_end; $pos++) { $softhash{$a[2]}{$pos}++; } $var_end = $var_start; } } $IDhash{$a[2]}{$var_start}{$var_end}{$c[$i]}++; } } } #write out edge features foreach my $key_chr (sort(keys %IDhash)) { foreach my $key_start (sort { $a <=> $b } (keys %{ $IDhash{$key_chr} })) { foreach my $key_end (sort { $a <=> $b } (keys %{ $IDhash{$key_chr}{$key_start} })){ print $fh_edge "$key_chr\t$key_start\t$key_end\t"; my $sum = $IDhash{$key_chr}{$key_start}{$key_end}{I} + $IDhash{$key_chr}{$key_start}{$key_end}{D} + $IDhash{$key_chr}{$key_start}{$key_end}{S}; print $fh_edge "$sum,"; for my $l ('S','I','D') {
{ "domain": "codereview.stackexchange", "id": 45611, "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": "performance, beginner, algorithm, perl, bioinformatics", "url": null }
performance, beginner, algorithm, perl, bioinformatics for my $l ('S','I','D') { if (defined($IDhash{$key_chr}{$key_start}{$key_end}{$l})) { print $fh_edge "$IDhash{$key_chr}{$key_start}{$key_end}{$l},"; } else { print $fh_edge "0,"; } } print $fh_edge "\n"; } } } #write out "all" features foreach my $key_chr (sort(keys %softhash)) { foreach my $key_pos (sort { $a <=> $b } (keys %{ $softhash{$key_chr} })) { print $fh_all "$key_chr\t$key_pos\t"; print $fh_all "$softhash{$key_chr}{$key_pos}\n"; } } Gist! Answer: Non-code / very-high-level considerations. The first thing you can do to speed up the performance would be to get a better computer. My computer is several years old, but it runs the unmodified code on the 100000-line example in less than one second, whereas you say it takes you a minute. (Of course, it's still worth remembering that better algorithms amplify the performance benefit of better hardware, so I will look at the hardware too). My experience in bioinformatics is very limited, and I've never worked with this particular format before. I have only looked briefly at the docs. However, following your link to a description of the CIGAR string, and then another link from that page to https://samtools.github.io/hts-specs/SAMv1.pdf , I observe the statement S may only have H operations between them and the ends of the CIGAR string However, 1368 lines of the 100000-line example violate that restriction. I suggest that you review the code to check that it doesn't rely on it, since you're the domain expert and have better understanding of what the codes mean than most if not all of us. And I think it is worth pointing out with respect to your observation that I rarely use Perl, but it seems highly inefficient.
{ "domain": "codereview.stackexchange", "id": 45611, "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": "performance, beginner, algorithm, perl, bioinformatics", "url": null }
performance, beginner, algorithm, perl, bioinformatics I rarely use Perl, but it seems highly inefficient. There's not much code here. Perhaps you should consider porting it to a language which you know better and is more efficient? (I would guess that Python run with PyPy or Cython would be faster, and Python knowledge seems to be common enough in your field that you wouldn't be creating problems for whoever later inherits it from you). Code considerations Possible bugs? my $loc = $start; #distance from start of read ... for (my $i = 0; $i <= $#c; $i++) { if ($c[$i] eq "S" || $c[$i] eq "I" || $c[$i] eq "D") { ... #find softclipping location if ($i == 1) { ... } else { for (my $j = $i-2; $j >= 0; $j--) {# subtract 2 from i, because the first value from c will always be empty $loc = $loc + $b[$j]; } ... } ... } } If I'm correctly interpreting things, shouldn't $loc = $start be just before the loop over $j? Otherwise a CIGAR string with several I/D/S will be double-counting some of the $b[$j]. In addition, I really can't understand how I and D can be treated identically. Shouldn't one of them cause $var_start to go down? Note: since the example too fast for me to get much useful profiling information out, this is based on common sense. Speed optimisation often defies common sense. I advise testing the suggestions one by one to see which work and which don't on large datasets. The most obvious optimisation relates to softhash, and in particular the loop for (my $pos = $var_start; $pos < $var_end; $pos++) { $softhash{$a[2]}{$pos}++; }
{ "domain": "codereview.stackexchange", "id": 45611, "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": "performance, beginner, algorithm, perl, bioinformatics", "url": null }
performance, beginner, algorithm, perl, bioinformatics If the ranges tend to be moderately wide then this is doing a lot of work and is ripe for optimisation. Specifically, you can replace that loop with $softhash{$a[2]}{$var_start}++; $softhash{$a[2]}{$var_end}--; and then modify the output loop at the end to foreach my $key_chr (sort(keys %softhash)) { my $accum = 0; my $prev_pos = -1; foreach my $key_pos (sort { $a <=> $b } (keys %{ $softhash{$key_chr} })) { if ($accum > 0) { for (my $i = $prev_pos; $i < $key_pos; $i++) { print $fh_all "$key_chr\t$i\t$accum\n"; } } $accum += $softhash{$key_chr}{$key_pos}; $prev_pos = $key_pos; } The main processing should be much faster than before, and the output loop should be slightly faster because (keys %{ $softhash{$key_chr} }) has fewer items to sort. If I'm right about $loc above, it might be worth eliminating the loop over $j and replacing it with an unconditional update of $var_start and $var_end. This probably won't help performance, but it might make the code more readable. The other things I'd do for readability mainly relate to names. I think it would be helpful to pull out $chromosome = $a[2]; I wonder whether $var_start and $var_end might be better as $range_start and $range_end; and I'm pretty sure that the key_ prefix doesn't convey much useful information. Reusing $chromosome instead of $key_chr, for example. One other readability issue: I was puzzled by the loop for (my $i = 0; $i <= $#c; $i++) because it clearly runs one time too many. Either start the iteration at 1 or find some way to make the indexing start at 0. If you implement the suggestion about updating the range unconditionally I think you cease to need to reference old values of $b and might be able to replace the loop with while ($cigar =~ /([0-9]+)([A-Z])/g) or something similar. (Not tested).
{ "domain": "codereview.stackexchange", "id": 45611, "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": "performance, beginner, algorithm, perl, bioinformatics", "url": null }
beginner, game, bash, console, tic-tac-toe Title: Text based tic-tac-toe in bash Question: I wrote this two player tic-tac-toe program in bash. To make a move you enter a number between 0 and 8 which corresponds to the square: 0|1|2 3|4|5 6|7|8 This is my code: #!/usr/bin/env bash declare -r BOARD_SIZE=9 declare -r DEFAULT_SQUARE_VALUE=- declare -ra PLAYERS=(O X) draw_board() { for i in {1..3} do echo "${1:- }|${2:- }|${3:- }" shift 3 done } get_placement() { while : do echo "Please enter a valid move (0-$((BOARD_SIZE - 1)))" read n echo digit_pattern="^[0-$((BOARD_SIZE-1))]\$" args=("$@") if [[ $n =~ $digit_pattern ]] && [[ ${args[$n]} == $DEFAULT_SQUARE_VALUE ]] then placement=$n return fi done } # sets $ended to whether the game has ended and $winner to the winner get_winner() { ended=1 possible_draw=1 # check for draw for square in $@ do if [[ $square == $DEFAULT_SQUARE_VALUE ]] then possible_draw=0 break fi done # check for winners if [[ ${PLAYERS[*]} =~ "$1" ]] && [[ ${PLAYERS[*]} =~ "$5" ]] && [[ ${PLAYERS[*]} =~ "$9" ]] then if [[ "$1" == "$5" ]] && [[ "$5" == "$9" ]] then winner=$1 return fi fi if [[ ${PLAYERS[*]} =~ "$3" ]] && [[ ${PLAYERS[*]} =~ "$5" ]] && [[ ${PLAYERS[*]} =~ "$7" ]] then if [[ "$3" == "$5" ]] && [[ "$5" == "$7" ]] then winner=$3 return fi fi for i in {1..3} do if [[ ${PLAYERS[*]} =~ "$1" ]] && [[ ${PLAYERS[*]} =~ "$2" ]] && [[ ${PLAYERS[*]} =~ "$3" ]] then if [[ "$1" == "$2" ]] && [[ "$2" == "$3" ]] then winner=$1 return fi fi
{ "domain": "codereview.stackexchange", "id": 45612, "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": "beginner, game, bash, console, tic-tac-toe", "url": null }
beginner, game, bash, console, tic-tac-toe if [[ ${PLAYERS[*]} =~ "$1" ]] && [[ ${PLAYERS[*]} =~ "$4" ]] && [[ ${PLAYERS[*]} =~ "$7" ]] then if [[ "$1" == "$4" ]] && [[ "$4" == "$7" ]] then winner=$1 return fi fi shift 3 done winner='' if [[ $possible_draw == 1 ]] then return fi ended=0 } board=( $(for i in $(seq 1 $BOARD_SIZE); do echo "$DEFAULT_SQUARE_VALUE"; done) ) current_turn="O" while : do draw_board ${board[@]} get_placement ${board[@]} board[$placement]=$current_turn get_winner ${board[@]} if [[ "$ended" == 1 ]] then if [ -n "$winner" ] then echo "$winner has won!" echo draw_board ${board[@]} else echo "Draw!" echo draw_board ${board[@]} fi exit fi [[ $current_turn == ${PLAYERS[0]} ]] && current_turn=${PLAYERS[1]} || current_turn=${PLAYERS[0]} echo -en "\n\n\n" done Example game: -|-|- -|-|- -|-|- Please enter a valid move (0-8) 0 O|-|- -|-|- -|-|- Please enter a valid move (0-8) 8 O|-|- -|-|- -|-|X Please enter a valid move (0-8) 6 O|-|- -|-|- O|-|X Please enter a valid move (0-8) 3 O|-|- X|-|- O|-|X Please enter a valid move (0-8) 2 O|-|O X|-|- O|-|X Please enter a valid move (0-8) 4 O|-|O X|X|- O|-|X Please enter a valid move (0-8) 1 O has won! O|O|O X|X|- O|-|X I do not know much about bash, so any feedback would be much appreciated. Answer: The intent here is that an engineer who is not a Bash expert should be able to readily maintain the code some months down the road. I do not know much about bash You might be that future maintenance engineer. Be kind to your future self. And thank you for that nice shebang. true get_placement() { while :
{ "domain": "codereview.stackexchange", "id": 45612, "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": "beginner, game, bash, console, tic-tac-toe", "url": null }
beginner, game, bash, console, tic-tac-toe Please don't do that. The Bourne shell has a long and sordid history which involves various (almost) work-alikes. The special builtin : colon operator used to be important when writing scripts. Nowadays, please just write while true. It's not like we're going to fork off a /usr/bin/true child. The shebang explained that we're targeting a shell, bash, which according to $ type true offers true as a shell builtin. Using arcane punctuation makes it harder for engineers to google for relevant technical advice. Using words (true) lets polyglot engineers leverage their knowledge from other environments into this one. shellcheck Code review submissions should lint clean before being submitted. When writing shell code it is easy to produce a result, but it is a minor challenge to make the script correct, due to quoting concerns and other minutiae. Lint this code, and follow the linter's advice, so it lints clean. 'Nuff said. spurious default I don't understand this line: draw_board() { ... echo "${1:- }|${2:- }|${3:- }" That is, why are we defaulting to SPACE? It seems that only [XO-] will ever be passed in. I am reluctant to support defaulting which is never used, out of concern that it may "paper over" some code defect that may be injected in future. char vs int; magic constant digit_pattern="^[0-$((BOARD_SIZE-1))]\$"
{ "domain": "codereview.stackexchange", "id": 45612, "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": "beginner, game, bash, console, tic-tac-toe", "url": null }
beginner, game, bash, console, tic-tac-toe One can play tic-tac-toe on boards of various sizes, including 2×2, 3×3, 4×4, .... The BOARD_SIZE constant is lovely and I thank you for it. Here, the digit_pattern expression is tightly coupled to the ... = 9 assignment. It precludes using a larger board, as then we'd need to worry about multi-digit labels for the squares. The key difficulty is that we're validating against string (really char) values, instead of against integer values. I am sad that we don't exit with an error code if this line encounters a "large" board size. zero- vs one- origin The review context showed a board with squares labeled 0 .. 8, which is very helpful. I'm surprised the game never displays that to the player. Consider using 1 .. 9 instead, even if that means allocating storage for an unused zeroth square. Then interpreting a bash expression like $8 would be more straightforward, it would have a more obvious correspondence to a certain square. side effect comments # sets $ended to whether the game has ended and $winner to the winner get_winner() { Thank you for explaining a non-obvious part of the contract, it's very helpful. This function is Too Long, as one cannot read all of it at once, it needs vertical scrolling to review it. You could e.g. easily Extract Helper by writing a check_for_winner function. On which topic, the check is entirely too tedious. Better to (roughly) loop over 159 357 123 147. Also, the vertical check is incorrect, leading to prompts like this: -|O|X -|O|X -|O|X Please enter a valid move (0-8)
{ "domain": "codereview.stackexchange", "id": 45612, "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": "beginner, game, bash, console, tic-tac-toe", "url": null }
beginner, game, bash, console, tic-tac-toe The shift 3 doesn't interact with the column check as you wanted it to. The row check works fine. test suite There isn't one, and you clearly need it, given the column check code defect. Write down some example move sequences, and the expected winner outcome and board state. Automating this will allow you to view Green bar before each commit. decomposition I will point out that this is just beautiful: do draw_board ${board[@]} get_placement ${board[@]} board[$placement]=$current_turn get_winner ${board[@]} Nice names, very clear narrative, looks great. UX I found it a bit surprising that the prompt doesn't mention whether it's currently the turn of O or X. It's not necessarily obvious, since an invalid input of e.g. 9 keeps current player the same. I was surprised that CTRL/D didn't exit the game due to EOF. An interactive player can always resort to CTRL/C. But automated unit tests may want to use redirection from an example game transcript file, and so reliably terminating on EOF might become an important requirement. This code only achieves a subset of its design goals. I would not be willing to delegate or accept maintenance tasks on it in its current form.
{ "domain": "codereview.stackexchange", "id": 45612, "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": "beginner, game, bash, console, tic-tac-toe", "url": null }
html, css Title: Basic static HTML page with applied accessibility Question: I'm following the FreeCodeCamp "Build a Tribute Page" project. I'm sure I forced some flexboxes where they didn't need to be. Tried to apply some accessibility topics that were discussed in earlier lessons. Overall its a very plain static page, but I'm trying to get the basics down in terms of structuring my html page correct before moving on to more complicated topics. I'm looking mostly for tips on how I'm structuring/nesting the HTML, as well as adding accessibility, and if my CSS structurally makes sense. Solution Note: this was wrote in Codepen so head/body tags are missing. HTML: <main id="main"> <h1 id="title">Philip Drury Dawson</h1> <div id="img-div"> <img id="image" src="http://media.cleveland.com/shaw_impact/photo/dawson-tiphelmet-2012-ccjpg-ad91451e0875bce2.jpg" alt="Phil Dawson greeting fans in First Energy Stadium"> <p id="img-caption"><em>Phil greeting his fans</em></p> </div> <!-- END img id="image" --> <div id="tribute-info"> <p>Phil was the best. <a href="https://www.reddit.com/r/Browns" target="_blank" id="tribute-link">We love him.</a> </p>
{ "domain": "codereview.stackexchange", "id": 45613, "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": "html, css", "url": null }
html, css <article> <h2>Cleveland Browns</h2> <p>The Cleveland Browns signed him as a free agent in March 1999, and he remained with the team for 14 years until he was signed by the San Francisco 49ers on March 19, 2013. (He was the only player left from the 1999 Browns squad). Dawson holds the Browns record for most consecutive field goals made (29) and most field goals in a game (6). Dawson is currently the 7th most accurate kicker in the NFL. On October 10, 2010, Dawson tied Lou Groza for the Browns' career field-goal record with 234. The two are tied for 35th in NFL history. Dawson scored the first points in the history of the "new" Cleveland Browns in 1999. On October 10 of that year, he scored the only touchdown of his career on a fake field goal against the Bengals in an 18-17 loss. His official career long was a 56-yard field goal on November 17, 2008, which would prove to be the game-winner against the Buffalo Bills on Monday Night Football. However, he did hit a 59-yard field goal in an August 14, 2010 preseason game. Dawson would have become an unrestricted free agent at the end of the 2010 season, but he was given the franchise tag on February 22, keeping him for the 2011 season. </p> </article> <article> <h2>The Phil Dawson Rule</h2> <p>Dawson had a rule named after him after a missed call by referees. On November 18, 2007, Dawson attempted a 51-yard field goal in the closing seconds of the fourth quarter to tie the game against the Baltimore Ravens. The kick carried through the air and hit the left upright and then the rear curved support post (stanchion), which bounced the football over the crossbar and into the end zone, in front of the goalpost. The kick was originally ruled no good. Under NFL rules, the play was not reviewable.
{ "domain": "codereview.stackexchange", "id": 45613, "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": "html, css", "url": null }
html, css not reviewable. <a href=#references><sup>[1]</sup></a> Officials discussed the play among themselves for several minutes and decided that, since the ball had indeed crossed the crossbar within the goal, whatever happened afterward to the ball did not matter. The kick was considered good, as announced by referee Pete Morelli. However, as the play is not technically reviewable, referee Pete Morelli announced that the play was reversed "after discussion," as opposed to "after further review," as is usually stated. At this point the Ravens, already celebrating in the locker room (they would have won 30-27 if the field goal was no good), were called back out onto the field to proceed to an overtime period. The Browns went on to win the game, 33-30 in overtime, as Dawson came through again with a more visible 33-yard field goal. Dawson finished 4 for 5 in FGs whereas fellow Lake Highlands High School alumnus Matt Stover finished 3 for 3 in FGs for the Ravens.<a href=#references><sup>[2]</sup></a> Notably, later in the season on December 16, in driving snow and wind gusts up to 40 mph, Dawson kicked another field goal, an improbable 49-yarder, that hit the same center support post. This field goal helped the Browns achieve an 8-0 win over the Buffalo Bills in blizzard conditions. Hitting this same structure twice in the same season has led some members of the Cleveland press to begin referring to the support post as "The Dawson Bar."<a href=#references><sup>[3]</sup></a> Prior to the 2008 season, the rule was changed to allow field goal and extra point attempts that hit the uprights or crossbar to be reviewed. This new rule is dubbed the "Phil Dawson Rule." </p> </article> </div> <!-- END div id="tribute-info" -->
{ "domain": "codereview.stackexchange", "id": 45613, "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": "html, css", "url": null }
html, css </main> <footer> <div id="references"> <h2>References</h2> <ol> <li> <a href="http://www.espn.com/nfl/columns/story?columnist=sando_mike&id=3120230">http://www.espn.com/nfl/columns/story?columnist=sando_mike&id=3120230</a> </li> <li> <a href="http://www.espn.com/nfl/boxscore?gameId=271118033">http://www.espn.com/nfl/boxscore?gameId=271118033</a> </li> <li> <a href="https://halftimeadjustments.wordpress.com/2007/12/20/the-dawson-bar/">https://halftimeadjustments.wordpress.com/2007/12/20/the-dawson-bar/</a> </li> </ol> </div> </footer> <script src="https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js"></script> CSS: html, body { font-family: verdana, arial, helvetica, sans-serif; } body { background-color: #444; } #main { color: #efefef; display: flex; flex-direction: column; align-items: center; margin: 0px 5%; } #img-div { background-color: #ff3c00; display: flex; flex-direction: column; justify-conent: flex-end; align-items: center; padding: 0px 0px 0px; } #image { max-width: 100%; height: auto; } #tribute-info { color: #222; background-color: #efefef; margin: 30px 0px; padding: 10px 5%; text-align: center; } #tribute-info h2 { border-bottom: 1px solid rgb(2, 2, 2, 0.2); padding-bottom: 10px; margin: 10px 0px; font-size: 1.5em; } p { font-size: 0.88em; line-height: 1.5; } sup { vertical-align: top; line-height: 1; font-size: 75%; } footer { color: #efefef; display: flex; flex-direction: column; align-items: center; margin: 0px 5%; } footer h2 { border-bottom: 1px solid rgb(239, 239, 239, 0.2); padding-bottom: 10px; margin: 10px 0px; font-size: 1.5em; text-align: center; } footer ol { columns: 2; column-width: 15em; font-size: 0.84em; list-style-position: inside; } footer a { color: #efefef; font-style: italic; }
{ "domain": "codereview.stackexchange", "id": 45613, "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": "html, css", "url": null }
html, css footer a { color: #efefef; font-style: italic; } Answer: HTML semantics The following snippet: <img id="image" src="http://media.cleveland.com/shaw_impact/photo/dawson-tiphelmet-2012-ccjpg-ad91451e0875bce2.jpg" alt="Phil Dawson greeting fans in First Energy Stadium"> <p id="img-caption"><em>Phil greeting his fans</em></p> Looks like an ideal candidate for <figure> and <figcaption>. Beyond semantics, It would visually simplify the markup, too. The figure element represents some flow content, optionally with a caption, that is self-contained and is typically referenced as single unit from the main flow of the document. <figure> <img src=“…”> <figcaption>Phil greeting his fans</figcaption> </figure> target=“_blank” Every place you use these should be accompanied by the following attribute: rel="noopener external” This is a plus for security and performance. More on that here. The footer This is more of a design opinion, so feel free to ignore it. I think this area of the page looks jumbled and could use some love. CSS The unit is not necessary if the value is 0. So 0px could just as well be 0 If you don’t need to support IE, some native CSS variables would help organize repeating styles For example: :root { —gray: #efefef; } #main { color: var(—grey); } #tribute-info { background-color: var(—grey); } General comments The number of ids seems unnecessary Some of the names of the ids are too general (“image”) and could be a problem if the HTML volume scales I hope this helps!
{ "domain": "codereview.stackexchange", "id": 45613, "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": "html, css", "url": null }
c++, design-patterns, observer-pattern Title: My C++ Implementation of the Observer Pattern Question: I have written my own basic implementation of the Observer pattern. Please code review it as you feel. This is a one file implementation, and any feedback no matter how small is appreciated. One sticky point is I was unsure on the implementation of RemoveObserver, so this may not be optimal. Could I have used Ranges here to modernise? #include <iostream> #include <chrono> #include <algorithm> #include <thread> using std::chrono::high_resolution_clock; using std::chrono::duration_cast; using std::chrono::duration; using std::chrono::milliseconds; class TimeObserver { public: virtual void Update(std::chrono::steady_clock::time_point time, std::chrono::steady_clock::time_point startTime) = 0; }; class Clock : public TimeObserver { virtual void Update(std::chrono::steady_clock::time_point time, std::chrono::steady_clock::time_point startTime) { duration<double, std::milli> ms_double = time - startTime; std::cout << ms_double.count() << "ms\n"; } }; class TimeManager { public: void RegisterObserver(TimeObserver* Observer) { observerList.push_back(Observer); }; void RemoveObserver(TimeObserver* Observer) { std::vector<TimeObserver*>::iterator position = std::find(observerList.begin(), observerList.end(), Observer); if (position != observerList.end()) observerList.erase(position); }; void NotifyObservers() { for (auto& observer : observerList) { observer->Update(time, startTime); } } void UpdateTime() { time = high_resolution_clock::now(); NotifyObservers(); } private: std::vector<TimeObserver*> observerList; std::chrono::steady_clock::time_point time = high_resolution_clock::now(); std::chrono::steady_clock::time_point startTime = high_resolution_clock::now(); };
{ "domain": "codereview.stackexchange", "id": 45614, "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++, design-patterns, observer-pattern", "url": null }
c++, design-patterns, observer-pattern int main() { TimeManager timeManager{}; TimeObserver* clockObserver = new Clock(); TimeObserver* clockObserver2 = new Clock(); timeManager.RegisterObserver(clockObserver); // Print initial time reading timeManager.UpdateTime(); // sleep for 1s std::this_thread::sleep_for(std::chrono::milliseconds(1000)); // register a second observer timeManager.RegisterObserver(clockObserver2); // This should print twice as we have 2 observers, should be ~1000ms timeManager.UpdateTime(); // Remove both observers timeManager.RemoveObserver(clockObserver); timeManager.RemoveObserver(clockObserver2); // nothing should print as we have no observers timeManager.UpdateTime(); delete clockObserver; delete clockObserver2; } Answer: About the observer design pattern The design patterns from the "Gang of Four" focus heavily on solving problems using classes. However, in modern C++, there are other ways to solve the problem that might have some benefits. Consider that you had to create two classes for the observer pattern here: an abstract base class TimeObserver, and a concrete class Clock. If you need to observe something else, or want to have an time observer that does something different than printing the time, you have to add more classes. But you are not interested in the classes, you only are interested in the function Update(). So instead you could use std::function to store observer function: class TimeManager { using Clock = std::chrono::steady_clock; using TimePoint = Clock::time_point; using Observer = std::function<void(TimePoint, TimePoint)>; public: void RegisterObserver(Observer observer) { observers.push_back(observer); } … void NotifyObservers() { for (auto& observer: observers) { observer(time, startTime); } } … private: std::vector<Observer> observers; … };
{ "domain": "codereview.stackexchange", "id": 45614, "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++, design-patterns, observer-pattern", "url": null }
c++, design-patterns, observer-pattern And then you could use it like so: int main() { TimeManager timeManager; timeManager.RegisterObserver([](auto time, auto startTime) { std::cout << duration<double, std::milli>{time - startTime}.count() << "ms\n"; }); … } This is slightly more efficient as well, since with virtual functions, two pointer indirections are necessary to call the actual function, whereas with std::function<> there is only a single indirection. One drawback though is that you no longer have a pointer to an object that you can use as a handle to deregister the observer. However, that brings me to: Deregistering issues Your example code is correct. However, what if you had forgotten to delete the observers? Or worse, what if you deleted the observers after registering them but before calling UpdateTime()? What if you register the same observer object twice? There are several ways in which you can avoid these issues: Use std::function as shown above. Use std::shared_ptr<TimeObserver> to manage the lifetime of the observer objects. Use std::unique_ptr<TimeObserver> and std::move() it when calling RegisterObserver(). All of these types will help manage the lifetime of observer objects in a safe way. They each have their pros and cons. Use std::erase() to remove items Instead of calling std::find() and then observerList.erase(…), you can use std::erase() since C++20. This simplifies the code and also handles erasing duplicates: void RemoveObserver(TimeObserver* observer) { std::erase(observerList, observer); }
{ "domain": "codereview.stackexchange", "id": 45614, "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++, design-patterns, observer-pattern", "url": null }
c++, design-patterns, observer-pattern Avoid std::chrono::high_resolution_clock Unfortunately, it's not well-defined what std::chrono::high_resolution_clock is. You are almost always better of using another clock. For example, std::chrono::system_clock if you care about wall clock time, something which you can compare with system clocks on other machines. Or if you want a clock that is not affected by NTP updates, leap seconds and so on, use std::chrono::steady_clock. Note that the latter is almost always a high resolution clock. Also, avoid storing the result of std::chrono::high_resolution_clock::now() into a std::chrono::steady_clock::time_point. What would it even mean?
{ "domain": "codereview.stackexchange", "id": 45614, "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++, design-patterns, observer-pattern", "url": null }
c++, recursion, template, c++20, constrained-templates Title: A recursive_copy_if Template Function Implementation with Unwrap Level Implementation in C++ Question: This is a follow-up question for A recursive_copy_if Template Function Implementation in C++ and recursive_invocable and recursive_project_invocable Concept Implementation in C++. I am trying to implement recursive_copy_if template function with unwrap level in this post. The experimental implementation recursive_copy_if Template Function // recursive_copy_if function implementation with unwrap level template <std::size_t unwrap_level, std::ranges::input_range Range, class UnaryPredicate> requires(recursive_invocable<unwrap_level, UnaryPredicate, Range>) constexpr auto recursive_copy_if(const Range& input, const UnaryPredicate& unary_predicate) { if constexpr(unwrap_level > 1) { Range output{}; std::ranges::transform( std::ranges::cbegin(input), std::ranges::cend(input), std::inserter(output, std::ranges::end(output)), [&unary_predicate](auto&& element) { return recursive_copy_if<unwrap_level - 1>(element, unary_predicate); } ); return output; } else { Range output{}; std::ranges::copy_if(std::ranges::cbegin(input), std::ranges::cend(input), std::inserter(output, std::ranges::end(output)), unary_predicate); return output; } } The used recursive_invocable concept // is_recursive_invocable template function implementation template<std::size_t unwrap_level, class F, class... T> requires(unwrap_level <= recursive_depth<T...>()) static constexpr bool is_recursive_invocable() { if constexpr (unwrap_level == 0) { return std::invocable<F, T...>; } else { return is_recursive_invocable< unwrap_level - 1, F, std::ranges::range_value_t<T>...>(); } }
{ "domain": "codereview.stackexchange", "id": 45615, "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++, recursion, template, c++20, constrained-templates", "url": null }
c++, recursion, template, c++20, constrained-templates // recursive_invocable concept template<std::size_t unwrap_level, class F, class... T> concept recursive_invocable = is_recursive_invocable<unwrap_level, F, T...>(); Full Testing Code The full testing code: // A recursive_copy_if Template Function Implementation with Unwrap Level Implementation in C++ #include <algorithm> #include <array> #include <cassert> #include <chrono> #include <complex> #include <concepts> #include <deque> #include <exception> #include <execution> #include <functional> #include <iostream> #include <iterator> #include <list> #include <ranges> #include <stdexcept> #include <string> #include <type_traits> #include <utility> #include <vector> template<typename T> concept is_inserterable = requires(T x) { std::inserter(x, std::ranges::end(x)); }; #ifdef USE_BOOST_MULTIDIMENSIONAL_ARRAY template<typename T> concept is_multi_array = requires(T x) { x.num_dimensions(); x.shape(); boost::multi_array(x); }; #endif // recursive_depth function implementation template<typename T> constexpr std::size_t recursive_depth() { return std::size_t{0}; } template<std::ranges::input_range Range> constexpr std::size_t recursive_depth() { return recursive_depth<std::ranges::range_value_t<Range>>() + std::size_t{1}; } // recursive_depth template function implementation with target type template<typename T_Base, typename T> constexpr std::size_t recursive_depth() { return std::size_t{0}; } template<typename T_Base, std::ranges::input_range Range> requires (!std::same_as<Range, T_Base>) constexpr std::size_t recursive_depth() { return recursive_depth<T_Base, std::ranges::range_value_t<Range>>() + std::size_t{1}; }
{ "domain": "codereview.stackexchange", "id": 45615, "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++, recursion, template, c++20, constrained-templates", "url": null }
c++, recursion, template, c++20, constrained-templates // is_recursive_invocable template function implementation template<std::size_t unwrap_level, class F, class... T> requires(unwrap_level <= recursive_depth<T...>()) static constexpr bool is_recursive_invocable() { if constexpr (unwrap_level == 0) { return std::invocable<F, T...>; } else { return is_recursive_invocable< unwrap_level - 1, F, std::ranges::range_value_t<T>...>(); } } // recursive_invocable concept template<std::size_t unwrap_level, class F, class... T> concept recursive_invocable = is_recursive_invocable<unwrap_level, F, T...>(); // is_recursive_project_invocable template function implementation template<std::size_t unwrap_level, class Proj, class F, class... T> requires(unwrap_level <= recursive_depth<T...>() && recursive_invocable<unwrap_level, Proj, T...>) static constexpr bool is_recursive_project_invocable() { if constexpr (unwrap_level == 0) { return std::invocable<F, std::invoke_result_t<Proj, T...>>; } else { return is_recursive_project_invocable< unwrap_level - 1, Proj, F, std::ranges::range_value_t<T>...>(); } } // recursive_project_invocable concept template<std::size_t unwrap_level, class Proj, class F, class... T> concept recursive_project_invocable = is_recursive_project_invocable<unwrap_level, Proj, F, T...>();
{ "domain": "codereview.stackexchange", "id": 45615, "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++, recursion, template, c++20, constrained-templates", "url": null }
c++, recursion, template, c++20, constrained-templates // recursive_copy_if function implementation with unwrap level template <std::size_t unwrap_level, std::ranges::input_range Range, class UnaryPredicate> requires(recursive_invocable<unwrap_level, UnaryPredicate, Range>) constexpr auto recursive_copy_if(const Range& input, const UnaryPredicate& unary_predicate) { if constexpr(unwrap_level > 1) { Range output{}; std::ranges::transform( std::ranges::cbegin(input), std::ranges::cend(input), std::inserter(output, std::ranges::end(output)), [&unary_predicate](auto&& element) { return recursive_copy_if<unwrap_level - 1>(element, unary_predicate); } ); return output; } else { Range output{}; std::ranges::copy_if(std::ranges::cbegin(input), std::ranges::cend(input), std::inserter(output, std::ranges::end(output)), unary_predicate); return output; } } // recursive_print implementation template<std::ranges::input_range Range> constexpr auto recursive_print(const Range& input, const int level = 0) { auto output = input; std::cout << std::string(level, ' ') << "Level " << level << ":" << std::endl; std::ranges::transform(std::ranges::cbegin(input), std::ranges::cend(input), std::ranges::begin(output), [level](auto&& x) { std::cout << std::string(level, ' ') << x << std::endl; return x; } ); return output; }
{ "domain": "codereview.stackexchange", "id": 45615, "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++, recursion, template, c++20, constrained-templates", "url": null }
c++, recursion, template, c++20, constrained-templates template<std::ranges::input_range Range> requires (std::ranges::input_range<std::ranges::range_value_t<Range>>) constexpr auto recursive_print(const Range& input, const int level = 0) { auto output = input; std::cout << std::string(level, ' ') << "Level " << level << ":" << std::endl; std::ranges::transform(std::ranges::cbegin(input), std::ranges::cend(input), std::ranges::begin(output), [level](auto&& element) { return recursive_print(element, level + 1); } ); return output; } // recursive_invoke_result_t implementation // from https://stackoverflow.com/a/65504127/6667035 template<typename, typename> struct recursive_invoke_result { }; template<typename T, std::invocable<T> F> struct recursive_invoke_result<F, T> { using type = std::invoke_result_t<F, T>; }; template<typename F, template<typename...> typename Container, typename... Ts> requires ( !std::invocable<F, Container<Ts...>> && std::ranges::input_range<Container<Ts...>> && requires { typename recursive_invoke_result<F, std::ranges::range_value_t<Container<Ts...>>>::type; }) struct recursive_invoke_result<F, Container<Ts...>> { using type = Container<typename recursive_invoke_result<F, std::ranges::range_value_t<Container<Ts...>>>::type>; }; template<typename F, typename T> using recursive_invoke_result_t = typename recursive_invoke_result<F, T>::type; template <std::ranges::range Range> constexpr auto get_output_iterator(Range& output) { return std::inserter(output, std::ranges::end(output)); } template<std::size_t dim, class T> constexpr auto n_dim_vector_generator(T input, std::size_t times) { if constexpr (dim == 0) { return input; } else { auto element = n_dim_vector_generator<dim - 1>(input, times); std::vector<decltype(element)> output(times, element); return output; } }
{ "domain": "codereview.stackexchange", "id": 45615, "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++, recursion, template, c++20, constrained-templates", "url": null }
c++, recursion, template, c++20, constrained-templates template<std::size_t dim, std::size_t times, class T> constexpr auto n_dim_array_generator(T input) { if constexpr (dim == 0) { return input; } else { auto element = n_dim_array_generator<dim - 1, times>(input); std::array<decltype(element), times> output; std::fill(std::begin(output), std::end(output), element); return output; } } template<std::size_t dim, class T> constexpr auto n_dim_deque_generator(T input, std::size_t times) { if constexpr (dim == 0) { return input; } else { auto element = n_dim_deque_generator<dim - 1>(input, times); std::deque<decltype(element)> output(times, element); return output; } } template<std::size_t dim, class T> constexpr auto n_dim_list_generator(T input, std::size_t times) { if constexpr (dim == 0) { return input; } else { auto element = n_dim_list_generator<dim - 1>(input, times); std::list<decltype(element)> output(times, element); return output; } } template<std::size_t dim, template<class...> class Container = std::vector, class T> constexpr auto n_dim_container_generator(T input, std::size_t times) { if constexpr (dim == 0) { return input; } else { return Container(times, n_dim_container_generator<dim - 1, Container, T>(input, times)); } } // Copy from https://stackoverflow.com/a/37264642/6667035 #ifndef NDEBUG # define M_Assert(Expr, Msg) \ __M_Assert(#Expr, Expr, __FILE__, __LINE__, Msg) #else # define M_Assert(Expr, Msg) ; #endif void __M_Assert(const char* expr_str, bool expr, const char* file, int line, const char* msg) { if (!expr) { std::cerr << "Assert failed:\t" << msg << "\n" << "Expected:\t" << expr_str << "\n" << "Source:\t\t" << file << ", line " << line << "\n"; abort(); } }
{ "domain": "codereview.stackexchange", "id": 45615, "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++, recursion, template, c++20, constrained-templates", "url": null }
c++, recursion, template, c++20, constrained-templates void recursive_copy_if_tests() { // std::vector<int> test case std::vector<int> test_vector_1 = { 1, 2, 3, 4, 5, 6 }; std::vector<int> expected_result_1 = { 2, 4, 6 }; M_Assert( recursive_copy_if<1>(test_vector_1, [](auto&& x) { return (x % 2) == 0; }) == expected_result_1, "std::vector<int> test case failed"); // std::vector<std::vector<int>> test case std::vector<decltype(test_vector_1)> test_vector_2 = { test_vector_1, test_vector_1, test_vector_1 }; std::vector<std::vector<int>> expected_result_2 = { expected_result_1, expected_result_1, expected_result_1 }; M_Assert( recursive_copy_if<2>(test_vector_2, [](auto&& x) { return (x % 2) == 0; }) == expected_result_2, "std::vector<std::vector<int>> test case failed"); // std::vector<std::string> test case std::vector<std::string> test_vector_3 = { "1", "2", "3", "4", "5", "6" }; std::vector<std::string> expected_result_3 = { "1" }; M_Assert( recursive_copy_if<1>(test_vector_3, [](auto&& x) { return (x == "1"); }) == expected_result_3, "std::vector<std::string> test case failed"); // std::vector<std::vector<std::string>> test case std::vector<std::vector<std::string>> test_vector_4 = { test_vector_3, test_vector_3, test_vector_3 }; std::vector<std::vector<std::string>> expected_result_4 = { expected_result_3, expected_result_3, expected_result_3 }; M_Assert( recursive_copy_if<2>(test_vector_4, [](auto&& x) { return (x == "1"); }) == expected_result_4, "std::vector<std::vector<std::string>> test case failed");
{ "domain": "codereview.stackexchange", "id": 45615, "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++, recursion, template, c++20, constrained-templates", "url": null }
c++, recursion, template, c++20, constrained-templates // std::deque<int> test case std::deque<int> test_deque_1; test_deque_1.push_back(1); test_deque_1.push_back(2); test_deque_1.push_back(3); test_deque_1.push_back(4); test_deque_1.push_back(5); test_deque_1.push_back(6); std::deque<int> expected_result_5; expected_result_5.push_back(1); M_Assert( recursive_copy_if<1>(test_deque_1, [](auto&& x) { return (x == 1); }) == expected_result_5, "std::deque<int> test case failed" ); // std::deque<std::deque<int>> test case std::deque<decltype(test_deque_1)> test_deque_2; test_deque_2.push_back(test_deque_1); test_deque_2.push_back(test_deque_1); test_deque_2.push_back(test_deque_1); std::deque<decltype(expected_result_5)> expected_result_6; expected_result_6.push_back(expected_result_5); expected_result_6.push_back(expected_result_5); expected_result_6.push_back(expected_result_5); M_Assert( recursive_copy_if<2>(test_deque_2, [](auto&& x) { return (x == 1); }) == expected_result_6, "std::deque<std::deque<int>> test case failed" ); // std::list<int> test case std::list<int> test_list_1 = { 1, 2, 3, 4, 5, 6 }; std::list<int> expected_result_7 = {2, 4, 6}; M_Assert( recursive_copy_if<1>(test_list_1, [](int x) { return (x % 2) == 0; }) == expected_result_7, "std::list<int> test case failed" ); // std::list<std::list<int>> test case std::list<std::list<int>> test_list_2 = { test_list_1, test_list_1, test_list_1, test_list_1 }; std::list<std::list<int>> expected_result_8 = { expected_result_7, expected_result_7, expected_result_7, expected_result_7 }; M_Assert( recursive_copy_if<2>(test_list_2, [](int x) { return (x % 2) == 0; }) == expected_result_8, "std::list<std::list<int>> test case failed" ); std::cout << "All tests passed!\n"; }
{ "domain": "codereview.stackexchange", "id": 45615, "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++, recursion, template, c++20, constrained-templates", "url": null }
c++, recursion, template, c++20, constrained-templates int main() { auto start = std::chrono::system_clock::now(); recursive_copy_if_tests(); 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; } The output of the test code above: All tests passed! Computation finished at Fri Mar 29 07:36:41 2024 elapsed time: 0.00130443 Godbolt link is here. All suggestions are welcome. The summary information: Which question it is a follow-up to? A recursive_copy_if Template Function Implementation in C++ and recursive_invocable and recursive_project_invocable Concept Implementation in C++ What changes has been made in the code since last question? I am trying to implement recursive_copy_if template function with unwrap level in this post. Why a new review is being asked for? Please review the implementation of recursive_copy_if template function and its tests. Answer: Range is not just an input range This is something I missed in my reviews of your previous questions. The parameter input is clearly an input range, so it's natural to restrict its type to std::ranges::input_range. However, Range is also used to create a new object that is used as an output range. So clearly, the constraint it wrong. You also require that it is a range that you can use std::inserter() on. What if unwrap_level == 0? From your code I can see that you intend unwrap_level to be at least 1. However, what if the caller passes in 0? I would add a static_assert() to catch this case.
{ "domain": "codereview.stackexchange", "id": 45615, "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++, recursion, template, c++20, constrained-templates", "url": null }
react.js, user-interface, state Title: How to manage array of states effectively? Question: I have a working code to have 2 search bars with dropdown suggestions, selectable by both mouse and arrow keys in TypeScript and Fresh/Preact. In there I have to explicitly declare individual hooks for different lists: const list1 = ['rabbits', 'raccoons', 'reindeer', 'red pandas', 'rhinoceroses', 'river otters', 'rattlesnakes', 'roosters'] as const const list2 = ['jacaranda', 'jacarta', 'jack-o-lantern orange', 'jackpot', 'jade', 'jade green', 'jade rosin', 'jaffa']; export default function SearchBar() { const [resultList1, setResultList1] = useState<null | (typeof list1[number])[]>(null); const [cursor1, setCursor1] = useState<Cursor>(0); const [selectedItem1, setSelectedItem1] = useState<null | typeof list1[number]>(null); // State to track selected item for list 1 const [resultList2, setResultList2] = useState<null | (typeof list2[number])[]>(null); const [cursor2, setCursor2] = useState<null | number>(0); // State to track selected item for list 2 const [selectedItem2, setSelectedItem2] = useState<null | typeof list2[number]>(null); // State to track selected item for list 2 /** activeList is used to determine whether the suggestion list should be popup or not */ const [activeList, setActiveList] = useState<null | '1' | '2'>(null); // State to track active list
{ "domain": "codereview.stackexchange", "id": 45616, "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": "react.js, user-interface, state", "url": null }
react.js, user-interface, state And explicitly return individual divs for different lists. <div id='search-div-1' className="search-bar-container" > <input type="text" placeholder={'Search list 1'} onInput={(e) => { setResultList1(list1.filter(item => item.includes((e.target as HTMLTextAreaElement).value))); }} onFocus={() => setActiveList('1')} onKeyDown={(e) => handleKeyDown(e)} /> <br /> {resultList1 && activeList === '1' ? SuggestedList() : null} Cursor: {cursor1}<br /> Selected item: <span id="Item 1">{selectedItem1}</span><br /> </div> <div id='search-div-2' className="search-bar-container" > <input type="text" placeholder={'Search list 2'} onInput={(e) => { setResultList2(list2.filter(item => item.includes((e.target as HTMLTextAreaElement).value))); }} onFocus={() => setActiveList('2')} onKeyDown={(e) => handleKeyDown(e)} /> <br /> {resultList2 && activeList === '2' ? SuggestedList() : null} Full code here. I wonder if this is a good approach or not. My next step for this is to have the suggested lists disappear when they are unfocused by integrating it with Detect click outside multiple components.
{ "domain": "codereview.stackexchange", "id": 45616, "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": "react.js, user-interface, state", "url": null }