text stringlengths 1 2.12k | source dict |
|---|---|
c#, performance, ms-word
public bool HavePreferenceData { get { return preferenceFileRead; } }
public CPrintSavePreference.PrintSave PrintSaveOptions { get { return printSaveValue; } set { printSaveValue = value; } }
public string RentRosterFile { get; set; }
public string RentRosterSheet { get; set; }
public string DefaultSaveDirectory { get; set; }
public CUserPreferences()
{
printSavePreference = new CPrintSavePreference();
InitDictionaries();
SetValuesToUndefinedState();
}
public CUserPreferences(string PreferencesFileName)
{
printSavePreference = new CPrintSavePreference();
InitDictionaries();
preferenceFileExists = File.Exists(PreferencesFileName);
if (preferenceFileExists)
{
preferenceFileRead = ReadPreferenceFile(PreferencesFileName);
}
else
{
SetValuesToUndefinedState();
}
}
public bool SavePreferencesToFile(string preferencesFileName)
{
StreamWriter rentRosterPreferencesfile = new StreamWriter(preferencesFileName);
try
{
WritePreferencesToDisc(rentRosterPreferencesfile);
rentRosterPreferencesfile.Flush();
rentRosterPreferencesfile.Close();
preferenceFileExists = true;
preferenceFileRead = true;
return true;
}
catch (IOException)
{
MessageBox.Show("Unable to write to preferences file: " + preferencesFileName);
return false;
}
}
private void InitDictionaries()
{ | {
"domain": "codereview.stackexchange",
"id": 42715,
"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, ms-word",
"url": null
} |
c#, performance, ms-word
private void InitDictionaries()
{
FieldNameByIndex = new Dictionary<int, string>();
int fieldNameCount = fileValueIds.Length;
for (int i = 0; i < fieldNameCount; ++i)
{
FieldNameByIndex.Add(i, fileValueIds[i]);
}
IndexFromFieldName = new Dictionary<string, int>();
for (int i = 0; i < fieldNameCount; ++i)
{
IndexFromFieldName.Add(fileValueIds[i], i);
}
}
private void SetValuesToUndefinedState()
{
PrintSaveOptions = CPrintSavePreference.PrintSave.PrintOnly;
}
// These constants and variables are used when reading and writing
// the preferences to and from the preference file.
private const int fileVersionId = 0;
private const int printSaveOptionId = 1;
private const int defaultSaveDirId = 2;
private const int rentRosterFileId = 3;
private const int rentRosterSheetNameId = 4;
private string[] fileValueIds =
{
"FileVersion:",
"PrintSaveValue:",
"DefaultSaveDirectory:",
"RentRosterFile:",
"RentRosterSheet:"
};
private void WritePreferencesToDisc(StreamWriter preferenceFile)
{
preferenceFile.WriteLine(fileValueIds[fileVersionId] + " " + fileVersion.ToString());
preferenceFile.WriteLine(fileValueIds[printSaveOptionId] + " " +
printSavePreference.ConvertPrintSaveToString(printSaveValue));
preferenceFile.WriteLine(fileValueIds[defaultSaveDirId] + " " + DefaultSaveDirectory);
preferenceFile.WriteLine(fileValueIds[rentRosterFileId] + " " + RentRosterFile);
preferenceFile.WriteLine(fileValueIds[rentRosterSheetNameId] + " " + RentRosterSheet);
} | {
"domain": "codereview.stackexchange",
"id": 42715,
"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, ms-word",
"url": null
} |
c#, performance, ms-word
}
private void ConvertandTestFileVersion(string fileInput)
{
try
{
int testFileVersion = Int32.Parse(fileInput);
if (testFileVersion != fileVersion)
{
if (testFileVersion < fileVersion)
{
MessageBox.Show("Preference file version " + fileInput + " out of date, please edit preferences to add new field values.");
}
else
{
MessageBox.Show("This version of the Tenant Roster tool does not support all the features of the tool that generated the file.");
}
}
}
catch (FormatException e)
{
string eMsg = "Reading preferences File Version failed: " + e.Message;
MessageBox.Show(eMsg);
}
}
private bool ReadPreferenceFile(string fileName)
{
bool fileReadSucceeded = true;
string[] lines;
if (File.Exists(fileName))
{
try
{
lines = File.ReadAllLines(fileName);
fileReadSucceeded = GetPreferenceValues(lines);
}
catch (IOException)
{
fileReadSucceeded = false;
}
}
return fileReadSucceeded;
} | {
"domain": "codereview.stackexchange",
"id": 42715,
"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, ms-word",
"url": null
} |
c#, performance, ms-word
return fileReadSucceeded;
}
private bool GetPreferenceValues(string[] lines)
{
bool hasAllFields = false;
int requiredFieldCount = 0;
int lineCount = lines.Length;
for (int i = 0; i < lineCount; ++i)
{
string[] nameAndValue = lines[i].Split(' ');
int fieldIndex;
IndexFromFieldName.TryGetValue(nameAndValue[0], out fieldIndex);
switch (fieldIndex)
{
case fileVersionId:
ConvertandTestFileVersion(nameAndValue[1]);
requiredFieldCount++;
break;
case printSaveOptionId:
printSaveValue = printSavePreference.ConvertStringToPrintSave(nameAndValue[1]);
requiredFieldCount++;
break;
case defaultSaveDirId:
DefaultSaveDirectory = CorrectForMuliWordNames(nameAndValue);
requiredFieldCount++;
break;
case rentRosterFileId:
RentRosterFile = CorrectForMuliWordNames(nameAndValue);
requiredFieldCount++;
break;
case rentRosterSheetNameId:
RentRosterSheet = CorrectForMuliWordNames(nameAndValue);
requiredFieldCount++;
break;
default:
MessageBox.Show("Reading preference file: Unknown field identity");
return false;
}
}
if (requiredFieldCount == fileValueIds.Length)
{
hasAllFields = true;
}
return hasAllFields;
} | {
"domain": "codereview.stackexchange",
"id": 42715,
"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, ms-word",
"url": null
} |
c#, performance, ms-word
return hasAllFields;
}
private string CorrectForMuliWordNames(string[] lineValues)
{
string wholeName = lineValues[1];
for (int i = 2; i < lineValues.Length; i++)
{
wholeName += " " + lineValues[i];
}
return wholeName;
}
}
}
CPrintSavePreference.cs
using System.Collections.Generic;
namespace RentRosterAutomation
{
public class CPrintSavePreference
{
private Dictionary<PrintSave, string> PrintSaveToStringDic;
private Dictionary<string, PrintSave> StringToPrintSaveDic;
public enum PrintSave
{
PrintOnly,
PrintAndSave,
SaveOnly
}
public CPrintSavePreference()
{
InitDictionaries();
}
public string ConvertPrintSaveToString(PrintSave printSave)
{
string printSaveString;
PrintSaveToStringDic.TryGetValue(printSave, out printSaveString);
return printSaveString;
}
public PrintSave ConvertStringToPrintSave(string printSaveString)
{
PrintSave retValue;
StringToPrintSaveDic.TryGetValue(printSaveString, out retValue);
return retValue;
}
private void InitDictionaries()
{
PrintSaveToStringDic = new Dictionary<PrintSave, string>();
PrintSaveToStringDic.Add(PrintSave.PrintOnly, "Print_Only");
PrintSaveToStringDic.Add(PrintSave.PrintAndSave, "Print_and_Save");
PrintSaveToStringDic.Add(PrintSave.SaveOnly, "Save_Only");
StringToPrintSaveDic = new Dictionary<string, PrintSave>();
StringToPrintSaveDic.Add("Print_Only", PrintSave.PrintOnly);
StringToPrintSaveDic.Add("Print_and_Save", PrintSave.PrintAndSave);
StringToPrintSaveDic.Add("Save_Only", PrintSave.SaveOnly);
}
}
} | {
"domain": "codereview.stackexchange",
"id": 42715,
"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, ms-word",
"url": null
} |
c#, performance, ms-word
}
}
Form_PrintMailboxLists .cs
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace RentRosterAutomation
{
public partial class Form_PrintMailboxLists : Form
{
private readonly CUserPreferences preferences;
private CPrintSavePreference.PrintSave printSave;
private bool addDateToFileName = false;
private bool addDateToTitle = false;
private string selectedBuildings;
private CPropertyComplex propertyComplex;
private CWordInteropMethods wordInteropMethods;
public Form_PrintMailboxLists()
{
InitializeComponent();
preferences = Program.preferences;
propertyComplex = Program.excelInteropMethods.Complex;
wordInteropMethods = new CWordInteropMethods(preferences);
}
private void PrintMailboxLists_Form_Load(object sender, EventArgs e)
{
List<string> buildings = propertyComplex.BuildingAddressList;
foreach (string building in buildings)
{
SelectBuilding2Print_listBox.Items.Add(building);
}
SelectBuilding2Print_listBox.Items.Add("All Buildings");
if (preferences.HavePreferenceData)
{
printSave = preferences.PrintSaveOptions;
PrintSaveChange();
}
AddDateToFileName_CB.Checked = addDateToFileName;
AddDateUnderAddress_CB.Checked = addDateToTitle;
PML_SaveAndPrint_Button.Enabled = false;
}
private void AddDateToFileName_CB_CheckedChanged(object sender, EventArgs e)
{
addDateToFileName = !addDateToFileName;
}
private void AddDateUnderAddress_CB_CheckedChanged(object sender, EventArgs e)
{
addDateToTitle = !addDateToTitle;
} | {
"domain": "codereview.stackexchange",
"id": 42715,
"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, ms-word",
"url": null
} |
c#, performance, ms-word
private void PML_SaveAndPrint_Button_Click(object sender, EventArgs e)
{
if (String.Compare(selectedBuildings, "All Buildings") == 0)
{
List<int> StreetNumbers = propertyComplex.StreetNumbers;
foreach (int streetNumber in StreetNumbers)
{
printAndOrSaveMailList(streetNumber);
}
}
else
{
string streetAddress = selectedBuildings.Substring(0, 5);
printAndOrSaveMailList(streetAddress);
}
Close();
}
private void printAndOrSaveMailList(string streetAddress)
{
int iStreetNumber = 0;
if (Int32.TryParse(streetAddress, out iStreetNumber))
{
printAndOrSaveMailList(iStreetNumber);
}
else
{
MessageBox.Show("Non Numeric string passed into PrintMailboxLists_Form::printAndOrSaveMailList().");
}
}
private void PML_PrintOnly_RB_CheckedChanged(object sender, EventArgs e)
{
printSave = CPrintSavePreference.PrintSave.PrintOnly;
}
private void PML_SavelOnly_RB_CheckedChanged(object sender, EventArgs e)
{
printSave = CPrintSavePreference.PrintSave.SaveOnly;
}
private void PML_PrintAndSave_RB_CheckedChanged(object sender, EventArgs e)
{
printSave = CPrintSavePreference.PrintSave.PrintAndSave;
}
private void PrintSaveChange()
{
switch (printSave)
{
case CPrintSavePreference.PrintSave.PrintAndSave:
PML_PrintAndSave_RB.Checked = true;
break;
case CPrintSavePreference.PrintSave.SaveOnly:
PML_SavelOnly_RB.Checked = true;
break; | {
"domain": "codereview.stackexchange",
"id": 42715,
"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, ms-word",
"url": null
} |
c#, performance, ms-word
default:
PML_PrintOnly_RB.Checked = true;
break;
}
}
private void SelectBuilding2Print_listBox_SelectedIndexChanged(object sender, EventArgs e)
{
if (SelectBuilding2Print_listBox.SelectedItem != null)
{
selectedBuildings = SelectBuilding2Print_listBox.SelectedItem.ToString();
PML_SaveAndPrint_Button.Enabled = true;
}
}
private void printAndOrSaveMailList(int streetAddress)
{
bool save = ((printSave == CPrintSavePreference.PrintSave.PrintAndSave) ? true :
(printSave == CPrintSavePreference.PrintSave.SaveOnly) ? true : false);
bool print = ((printSave == CPrintSavePreference.PrintSave.PrintAndSave) ? true :
(printSave == CPrintSavePreference.PrintSave.PrintOnly) ? true : false);
string documentName = "MailboxList_" + streetAddress;
string statusMessage = (print && save) ? "Printing and Saving " :
(print) ? "Printing " : "Saving ";
statusMessage += "the mailbox list for " + streetAddress;
Form_CurrentProgressStatus psStatus = new Form_CurrentProgressStatus();
psStatus.MessageText = statusMessage;
psStatus.Show();
CBuilding building = propertyComplex.GetBuilding(streetAddress);
if (building != null)
{
CMailboxListData mailboxList = Program.excelInteropMethods.GetMailboxData(building);
if (mailboxList != null)
{
wordInteropMethods.CreateMailistPrintAndOrSave(documentName,
mailboxList, addDateToFileName, addDateToTitle, save, print);
}
}
psStatus.Close();
}
}
} | {
"domain": "codereview.stackexchange",
"id": 42715,
"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, ms-word",
"url": null
} |
c#, performance, ms-word
psStatus.Close();
}
}
}
Answer: Error Handling
Similar to the Excel part, an exception in the writing can cause an orphaned Word instance. Placing the Quit() in a finally block will help that
try
{
var wordDoc = wordApp.Documents.Add();
FormatDocMargins(ref wordDoc, wordApp);
AddTitleToMailBoxList(wordDoc, mailboxdata.AddressStreetNumber, addDateToTitle);
AddTenantTableToMailBoxList(wordDoc, mailboxdata, wordApp);
object DoNotSaveChanges = PrintAndOrSave(wordDoc, save, print, fullFilePathName);
wordDoc.Close(ref DoNotSaveChanges);
}
catch (Exception e)
{
string eMsg = "An error occurred while generating the Word Document for "
+ documentName + " : " + e.Message;
docGenerated = false;
MessageBox.Show(eMsg);
}
finally
{
wordApp.Quit();
}
NOTE:
Most of the Missing parameters are optional and can be omitted.
It is not necessary to use reference parameters when passing the document around. The only time that we would need the parameter to be ref is if we were creating the document in the method and wanted to return it in the parameter.
In the original code we create the document instance twice
Word.Document wordDoc = new Word.Document();
wordApp.Visible = false;
wordDoc = wordApp.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing);
only the second is needed (with the optional missing params omitted)
Word.Document wordDoc = wordApp.Documents.Add(); | {
"domain": "codereview.stackexchange",
"id": 42715,
"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, ms-word",
"url": null
} |
c#, performance, ms-word
Other
Under what conditions can the documentName be null or empty? This strikes me as a condition that should be handled long before we get to this method.
It is possible to not print or save (pass in false for each) and still have docGenerated be true. Is this intended?
As far as I can see the CUserPreferences and CPrintSavePreference are not used (we read the defaultSaveFolder from CUserPreferences in the ctor but that is it). Am I missing something?
It depends upon the full requirements but for some quick print/save preferences a Flags enum is useful
[Flags]
internal enum WriterTargets
{
None = 0,
Print = 1,
Save = 2
}
We can set them and parse them using the built in functionality
var targets = WriterTargets.Print;
Console.WriteLine(targets.ToString());
gives 'Print'
targets = WriterTargets.Save;
Console.WriteLine(targets.ToString());
gives 'Save'
targets = WriterTargets.Save | WriterTargets.Print;
Console.WriteLine(targets.ToString());
or
targets = (WriterTargets)Enum.Parse(typeof(WriterTargets), "Save, Print");
Console.WriteLine(targets.ToString());
gives 'Print, Save' | {
"domain": "codereview.stackexchange",
"id": 42715,
"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, ms-word",
"url": null
} |
c++, beginner, classes, coordinate-system
Title: C++ simple 2D vector
Question: I'm brand new to cpp and tried implementing a simple Vector class that supports abs(), equality and addition operators. I just wanted a quick set of eyes to tell me if I'm doing anything egregious in my constructor/operators and finally their usage.
Note: the [[nodiscard]] was recommended by the clion IDE.
#include <iostream>
#include <cmath>
class Vector {
public:
double x, y;
[[nodiscard]] double abs() const {return sqrt(x*x + y*y);}
// constructor
Vector(double x, double y) {
this->x = x;
this->y = y;
}
// add op
Vector operator+(const Vector& b) {
Vector vec(this->x, this->y);
vec.x += b.x;
vec.y += b.y;
return vec;
}
// eq op
bool operator==(const Vector& b) {
if (this->x == b.x && this->y == b.y) {
return true;
}
return false;
}
};
int main()
{
Vector vec = Vector(4, 8);
Vector vec2 = Vector(3.2, 5.5);
Vector vec3 = vec + vec2;
bool equal = vec == vec2;
bool equal2 = vec == Vector(4, 8);
std::cout << equal << std::endl;
std::cout << equal2 << std::endl;
std::cout << vec3.x << std::endl;
std::cout << vec.abs() << std::endl;
}
Answer: For the add operator, you're currently constructing a brand new vector when you do Vector vec(this->x, this->y), before manipulating the newly constructed vector's x and y values. If this is what you want to do, you can add the values in the constructor instead: return Vector(x+other.x, y+other.y). You may, however, also want to implement and use the incremental add operator +=, where you instead just could add to this->x and this->y and return *this. If you do this you should also return by reference, i.e.:
Vector& operator+=(const Vector& other) {
this->x += x;
this->y += y;
return *this;
} | {
"domain": "codereview.stackexchange",
"id": 42716,
"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++, beginner, classes, coordinate-system",
"url": null
} |
c++, beginner, classes, coordinate-system
You probably want your x and y members to be private and not public. And use member initialisation - your constructor can be changed to
Vector(double x, double y) : x(x), y(y) {}
Also consider that if (condition) return true else return false is the same as return condition, i.e. you can do
bool operator==(const Vector& other) {
return (this->x == other.x && this->y == other.y);
}
Finally, maybe have a look at some existing libraries that implement vectors (in 2 or 3 dimensions - shouldn't matter much). These should be able to give you some help or inspiration. | {
"domain": "codereview.stackexchange",
"id": 42716,
"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++, beginner, classes, coordinate-system",
"url": null
} |
console, rust, amazon-web-services
Title: Rust CLI tool to synchronize files to S3
Question: Learning Rust, I've written a small CLI tool which will
Fetch the existing data in S3
Iterate through local folders
Upload the files which don't exist in S3
I'd be keen to hear anything I might have done that doesn't follow Rust best practices.
use async_recursion::async_recursion;
use aws_sdk_s3::error::ListObjectsV2Error;
use aws_sdk_s3::model::{ServerSideEncryption, StorageClass};
use aws_sdk_s3::output::{ListObjectsV2Output, PutObjectOutput};
use aws_sdk_s3::{error::PutObjectError, ByteStream, Client, Region, SdkError};
use log::{debug, error, info, warn};
use shellexpand;
use std::collections::HashSet;
use std::fs;
use std::path::{Path, PathBuf};
use std::str::FromStr;
use structopt::StructOpt;
use thiserror::Error;
#[derive(Error, Debug)]
pub enum BackupError {
#[error("Could not parse path")]
InvalidPath,
#[error("Invalid storage class")]
InvalidStorageClass,
#[error("Invalid server side encryption")]
InvalidServerSideEncryption,
#[error("S3 upload failed")]
UploadFailed(#[from] SdkError<PutObjectError>),
#[error("Failed to retrieve data from server")]
FileFetchFailed(#[from] SdkError<ListObjectsV2Error>),
}
pub type BackupResult<T> = Result<T, BackupError>;
#[derive(Debug, StructOpt)]
struct Options {
/// Directory to backup
#[structopt(parse(from_os_str))]
path: std::path::PathBuf,
/// AWS region
#[structopt(default_value = "eu-west-2", short, long)]
region: String,
/// Bucket to store data in
#[structopt(short, long)]
bucket: String,
/// The storage class for the individual files
/// Accepted values:
/// ```
/// DEEP_ARCHIVE
/// GLACIER
/// GLACIER_IR
/// INTELLIGENT_TIERING
/// ONEZONE_IA
/// OUTPOSTS
/// REDUCED_REDUNDANCY
/// STANDARD
/// STANDARD_IA
/// ```
#[structopt(default_value = "DEEP_ARCHIVE", short, long)]
storage_class: String, | {
"domain": "codereview.stackexchange",
"id": 42717,
"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": "console, rust, amazon-web-services",
"url": null
} |
console, rust, amazon-web-services
/// The encryption used by the individual files
/// Accepted values:
/// ```
/// AES256
/// aws:kms
/// ```
#[structopt(default_value = "AES256", short, long)]
encryption: String,
}
#[tokio::main]
async fn main() {
env_logger::init_from_env(
env_logger::Env::default().filter_or(env_logger::DEFAULT_FILTER_ENV, "info"),
);
let args = Options::from_args();
let client = match S3Client::new(
&args.bucket,
args.region,
&args.storage_class,
&args.encryption,
)
.await
{
Ok(c) => c,
Err(err) => panic!("Unable to establish S3 client: {}", err),
};
let mut files_by_path = match fetch_existing_objects(&client).await {
Ok(files) => files,
Err(error) => panic!("Failed to fetch objects: {}", error),
};
info!("Found {} objects", files_by_path.len());
let root = match expand_path(args.path) {
Ok(p) => p,
Err(error) => panic!("Failed to read root path: {}", error),
};
let second = root.clone();
match traverse_directories(
&root,
&second,
&mut files_by_path,
&client,
&client.bucket,
&client.storage_class,
&client.encryption,
)
.await
{
Ok(()) => info!("All directories synced"),
Err(err) => error!("Failed to sync directories: {}", err),
}
}
async fn fetch_existing_objects(
client: &S3Client,
) -> Result<HashSet<Vec<String>>, Box<dyn std::error::Error>> {
let mut files_by_path = HashSet::<Vec<String>>::new();
let mut next_token: Option<String> = None;
loop {
let response = client.fetch_existing_objects(next_token).await?;
for object in response.contents().unwrap_or_default() {
let filename = match object.key() {
Some(name) => name.to_owned(),
None => panic!("No filename found!"),
}; | {
"domain": "codereview.stackexchange",
"id": 42717,
"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": "console, rust, amazon-web-services",
"url": null
} |
console, rust, amazon-web-services
let filename_pieces = split_filename(&filename);
files_by_path.insert(filename_pieces);
}
next_token = response.next_continuation_token().map(|t| t.to_string());
if !response.is_truncated() {
break;
}
}
Ok(files_by_path)
}
fn expand_path(input: PathBuf) -> BackupResult<PathBuf> {
let expanded_path: String = shellexpand::tilde::<String>(&parse_path(input)?).to_string();
return Ok(Path::new(&expanded_path).to_owned());
}
fn split_filename(filename: &str) -> Vec<String> {
return filename
.split(&['/', '\\'][..])
.map(|s| s.to_string())
.collect();
}
#[async_recursion]
async fn traverse_directories(
path: &Path,
root: &Path,
existing_files: &mut HashSet<Vec<String>>,
client: &S3Client,
bucket: &str,
storage_class: &StorageClass,
sse: &ServerSideEncryption,
) -> BackupResult<()> {
// We use metadata since path::is_file() coerces an error into false
let metadata = match fs::metadata(path) {
Ok(m) => m,
Err(err) => {
warn!("Unable to read the metadata for {:?}: {}", path, err);
return Ok(());
}
};
if metadata.is_file() {
debug!("Processing {:?}", path.file_name());
let stripped_path = match strip_path(path, &root) {
Some(p) => p,
None => return Ok(()),
};
let filename_segments = split_filename(&stripped_path);
if existing_files.contains(&filename_segments) {
info!("Skipping existing file: {}", stripped_path);
return Ok(());
}
info!("Uploading new file: {}", stripped_path);
existing_files.insert(filename_segments); | {
"domain": "codereview.stackexchange",
"id": 42717,
"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": "console, rust, amazon-web-services",
"url": null
} |
console, rust, amazon-web-services
let file_data = ByteStream::from_path(path).await;
match file_data {
Ok(data) => {
client.upload_file(data, stripped_path.as_ref()).await?;
}
Err(err) => {
error!("Failed to read file {:?}: {}", stripped_path, err);
}
}
return Ok(());
}
debug!("Diving into new directory: {:?}", path);
for entry in fs::read_dir(path).unwrap() {
let directory = entry.unwrap();
let directory_name = parse_path(directory.path())?;
info!("Evaluating {}", directory_name);
traverse_directories(
&directory.path(),
root,
existing_files,
&client,
bucket,
storage_class,
sse,
)
.await
.unwrap();
}
Ok(())
}
fn parse_path(path: PathBuf) -> BackupResult<String> {
return match path.into_os_string().into_string() {
Ok(parsed_path) => Ok(parsed_path),
Err(err) => Err(BackupError::InvalidPath),
};
}
fn strip_path(path: &Path, root: &Path) -> Option<String> {
let path = match path.strip_prefix(root) {
Ok(p) => match p.to_str() {
Some(p) => p,
None => {
error!("Failed to parse path: {:?}", path);
return None;
}
},
Err(err) => {
error!("Failed to parse path {:?}: {}", path, err);
return None;
}
};
return Some(path.to_owned());
}
pub struct S3Client {
s3_client: Client,
bucket: String,
storage_class: StorageClass,
encryption: ServerSideEncryption,
} | {
"domain": "codereview.stackexchange",
"id": 42717,
"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": "console, rust, amazon-web-services",
"url": null
} |
console, rust, amazon-web-services
impl S3Client {
pub async fn new(
bucket: &str,
region: String,
storage_class: &str,
sse: &str,
) -> BackupResult<S3Client> {
let region = Region::new(region);
let aws_config = aws_config::from_env().region(region).load().await;
let client = Client::new(&aws_config);
let storage_class = match StorageClass::from_str(storage_class) {
Ok(class) => class,
Err(err) => return Err(BackupError::InvalidStorageClass),
};
let sse = match ServerSideEncryption::from_str(sse) {
Ok(enc) => enc,
Err(err) => return Err(BackupError::InvalidStorageClass),
};
return Ok(S3Client {
s3_client: client,
bucket: bucket.to_owned(),
storage_class,
encryption: sse,
});
}
pub async fn upload_file(&self, data: ByteStream, key: &str) -> BackupResult<PutObjectOutput> {
let upload_response = self
.s3_client
.put_object()
.bucket(&self.bucket)
.key(key.replace("\\", "/"))
.body(data)
.set_storage_class(Some(self.storage_class.to_owned()))
.server_side_encryption(self.encryption.to_owned())
.send()
.await;
match upload_response {
Ok(output) => Ok(output),
Err(err) => Err(BackupError::UploadFailed(err)),
}
}
pub async fn fetch_existing_objects(
&self,
continuation_token: Option<String>,
) -> BackupResult<ListObjectsV2Output> {
let response = self
.s3_client
.list_objects_v2()
.bucket(&self.bucket)
.set_continuation_token(continuation_token.or(None))
.send()
.await;
match response {
Ok(output) => Ok(output),
Err(err) => Err(BackupError::FileFetchFailed(err)),
}
}
} | {
"domain": "codereview.stackexchange",
"id": 42717,
"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": "console, rust, amazon-web-services",
"url": null
} |
console, rust, amazon-web-services
If it is easier, you can also read the code on Github: https://github.com/Vannevelj/backup-rs
Answer: Your code looks good! You've used thiserror and clap (through structopt) which is nice.
I would also recommend using clippy to catch some of the most common mistakes and to suggest idiomatic improvements.
Here are my suggestions:
Remove use shellexpand; as it is not used.
All the cases where you match on a result and panic in the error arm can be replaced with unwrap_or_else.
Example
Before:
let mut files_by_path = match fetch_existing_objects(&client).await {
Ok(files) => files,
Err(error) => panic!("Failed to fetch objects: {}", error),
};
After:
let mut files_by_path = fetch_existing_objects(&client)
.await
.unwrap_or_else(|err| panic!("Failed to fetch objects: {}", err));
No need to use the return keyword when returning the last expression in a function.
Example
Before:
fn split_filename(filename: &str) -> Vec<String> {
return filename
.split(&['/', '\\'][..])
.map(|s| s.to_string())
.collect();
}
After:
fn split_filename(filename: &str) -> Vec<String> {
filename
.split(&['/', '\\'][..])
.map(|s| s.to_string())
.collect()
}
Avoid specifying types where they can be inferred.
Example
Before:
let expanded_path: String = shellexpand::tilde::<String>(&parse_path(input)?).to_string();
After:
let expanded_path = shellexpand::tilde(&parse_path(input)?).to_string();
Replace from_str with from where from_str has Infallible error type.
Example
Before:
let storage_class = match StorageClass::from_str(storage_class) {
Ok(class) => class,
Err(err) => return Err(BackupError::InvalidStorageClass),
};
let sse = match ServerSideEncryption::from_str(sse) {
Ok(enc) => enc,
Err(err) => return Err(BackupError::InvalidStorageClass),
};
After:
let storage_class = StorageClass::from(storage_class);
let sse = ServerSideEncryption::from(sse); | {
"domain": "codereview.stackexchange",
"id": 42717,
"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": "console, rust, amazon-web-services",
"url": null
} |
console, rust, amazon-web-services
Dynamic dispatch can be avoided here:
async fn fetch_existing_objects(
client: &S3Client,
) -> Result<HashSet<Vec<String>>, Box<dyn std::error::Error>>
because the function only returns one error type.
async fn fetch_existing_objects(client: &S3Client) -> BackupResult<HashSet<Vec<String>>>
Use map_err instead of matching if you want to transform errors.
Example
Before:
let response = self
.s3_client
.list_objects_v2()
.bucket(&self.bucket)
.set_continuation_token(continuation_token.or(None))
.send()
.await;
match response {
Ok(output) => Ok(output),
Err(err) => Err(BackupError::FileFetchFailed(err)),
}
After:
self.s3_client
.list_objects_v2()
.bucket(&self.bucket)
.set_continuation_token(continuation_token)
.send()
.await
.map_err(BackupError::FileFetchFailed)
The bucket parameter in the new method of the S3Client can also be of type String like the region parameter.
Use expect instead of match when you want to panic with a custom message if a result is error.
Before:
let filename = match object.key() {
Some(name) => name.to_owned(),
None => panic!("No filename found!"),
};
let filename_pieces = split_filename(&filename);
After:
let filename = object.key().expect("No filename found!");
let filename_pieces = split_filename(filename);
Also, there is no need to convert filename to String.
You can directly return from the loop inside the fetch_existing_objects(..) method instead of breaking.
Before:
if !response.is_truncated() {
break;
}
After:
if !response.is_truncated() {
return Ok(files_by_path);
}
Avoid unwraps, they should either panic with a meaningful message or return an error.
I would personally redesign the recursive asynchronous function to avoid the tail recursion.
Also bucket, storage_class and sse parameters in the traverse_directories() method are never used. | {
"domain": "codereview.stackexchange",
"id": 42717,
"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": "console, rust, amazon-web-services",
"url": null
} |
console, rust, amazon-web-services
Final Code (Not tested):
use aws_sdk_s3::error::ListObjectsV2Error;
use aws_sdk_s3::model::{ServerSideEncryption, StorageClass};
use aws_sdk_s3::output::{ListObjectsV2Output, PutObjectOutput};
use aws_sdk_s3::{error::PutObjectError, ByteStream, Client, Region, SdkError};
use log::{debug, error, info, warn};
use std::collections::HashSet;
use std::fs;
use std::path::{Path, PathBuf};
use structopt::StructOpt;
use thiserror::Error;
#[derive(Error, Debug)]
pub enum BackupError {
#[error("Could not parse path")]
InvalidPath,
#[error("Invalid storage class")]
InvalidStorageClass,
#[error("Invalid server side encryption")]
InvalidServerSideEncryption,
#[error("S3 upload failed")]
UploadFailed(#[from] SdkError<PutObjectError>),
#[error("Failed to retrieve data from server")]
FileFetchFailed(#[from] SdkError<ListObjectsV2Error>),
}
pub type BackupResult<T> = Result<T, BackupError>;
#[derive(Debug, StructOpt)]
struct Options {
/// Directory to backup
#[structopt(parse(from_os_str))]
path: std::path::PathBuf,
/// AWS region
#[structopt(default_value = "eu-west-2", short, long)]
region: String,
/// Bucket to store data in
#[structopt(short, long)]
bucket: String,
/// The storage class for the individual files
/// Accepted values:
/// ```
/// DEEP_ARCHIVE
/// GLACIER
/// GLACIER_IR
/// INTELLIGENT_TIERING
/// ONEZONE_IA
/// OUTPOSTS
/// REDUCED_REDUNDANCY
/// STANDARD
/// STANDARD_IA
/// ```
#[structopt(default_value = "DEEP_ARCHIVE", short, long)]
storage_class: String,
/// The encryption used by the individual files
/// Accepted values:
/// ```
/// AES256
/// aws:kms
/// ```
#[structopt(default_value = "AES256", short, long)]
encryption: String,
} | {
"domain": "codereview.stackexchange",
"id": 42717,
"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": "console, rust, amazon-web-services",
"url": null
} |
console, rust, amazon-web-services
#[tokio::main]
async fn main() {
env_logger::init_from_env(
env_logger::Env::default().filter_or(env_logger::DEFAULT_FILTER_ENV, "info"),
);
let args = Options::from_args();
let client = S3Client::new(
args.bucket,
args.region,
&args.storage_class,
&args.encryption,
)
.await
.unwrap_or_else(|err| panic!("Unable to establish S3 client: {}", err));
let mut files_by_path = fetch_existing_objects(&client)
.await
.unwrap_or_else(|err| panic!("Failed to fetch objects: {}", err));
info!("Found {} objects", files_by_path.len());
let root =
expand_path(args.path).unwrap_or_else(|err| panic!("Failed to read root path: {}", err));
match traverse_directories(&root, &mut files_by_path, &client).await {
Ok(()) => info!("All directories synced"),
Err(err) => error!("Failed to sync directories: {}", err),
}
}
async fn fetch_existing_objects(client: &S3Client) -> BackupResult<HashSet<Vec<String>>> {
let mut files_by_path = HashSet::new();
let mut next_token: Option<String> = None;
loop {
let response = client.fetch_existing_objects(next_token).await?;
for object in response.contents().unwrap_or_default() {
let filename = object.key().expect("No filename found!");
let filename_pieces = split_filename(filename);
files_by_path.insert(filename_pieces);
}
next_token = response.next_continuation_token().map(|t| t.to_string());
if !response.is_truncated() {
return Ok(files_by_path);
}
}
}
fn expand_path(input: PathBuf) -> BackupResult<PathBuf> {
let expanded_path = shellexpand::tilde(&parse_path(input)?).to_string();
Ok(Path::new(&expanded_path).to_owned())
}
fn split_filename(filename: &str) -> Vec<String> {
filename
.split(&['/', '\\'][..])
.map(|s| s.to_string())
.collect()
} | {
"domain": "codereview.stackexchange",
"id": 42717,
"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": "console, rust, amazon-web-services",
"url": null
} |
console, rust, amazon-web-services
async fn traverse_directories(
root: &Path,
existing_files: &mut HashSet<Vec<String>>,
client: &S3Client,
) -> BackupResult<()> {
let mut paths = vec![root.to_owned()];
while !paths.is_empty() {
let path = paths.remove(0);
debug!("Diving into directory: {:?}", path);
// We use metadata since path::is_file() coerces an error into false
let metadata = match fs::metadata(&path) {
Ok(m) => m,
Err(err) => {
warn!("Unable to read the metadata for {:?}: {}", &path, err);
continue;
}
};
if metadata.is_file() {
debug!("Processing {:?}", path.file_name());
let stripped_path = match strip_path(&path, root) {
Some(p) => p,
None => continue,
};
let filename_segments = split_filename(&stripped_path);
if existing_files.contains(&filename_segments) {
info!("Skipping existing file: {}", stripped_path);
continue;
}
info!("Uploading new file: {}", stripped_path);
existing_files.insert(filename_segments);
match ByteStream::from_path(path).await {
Ok(data) => {
client.upload_file(data, stripped_path.as_ref()).await?;
}
Err(err) => {
error!("Failed to read file {:?}: {}", stripped_path, err);
}
}
continue;
}
for entry in fs::read_dir(path).unwrap() {
let directory = entry.unwrap();
paths.push(directory.path())
}
}
Ok(())
}
fn parse_path(path: PathBuf) -> BackupResult<String> {
path.into_os_string()
.into_string()
.map_err(|_| BackupError::InvalidPath)
} | {
"domain": "codereview.stackexchange",
"id": 42717,
"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": "console, rust, amazon-web-services",
"url": null
} |
console, rust, amazon-web-services
fn strip_path(path: &Path, root: &Path) -> Option<String> {
let path = match path.strip_prefix(root) {
Ok(p) => match p.to_str() {
Some(p) => p,
None => {
error!("Failed to parse path: {:?}", path);
return None;
}
},
Err(err) => {
error!("Failed to parse path {:?}: {}", path, err);
return None;
}
};
Some(path.to_owned())
}
pub struct S3Client {
s3_client: Client,
bucket: String,
storage_class: StorageClass,
encryption: ServerSideEncryption,
}
impl S3Client {
pub async fn new(
bucket: String,
region: String,
storage_class: &str,
sse: &str,
) -> BackupResult<S3Client> {
let region = Region::new(region);
let aws_config = aws_config::from_env().region(region).load().await;
let client = Client::new(&aws_config);
let storage_class = StorageClass::from(storage_class);
let sse = ServerSideEncryption::from(sse);
Ok(S3Client {
s3_client: client,
bucket,
storage_class,
encryption: sse,
})
}
pub async fn upload_file(&self, data: ByteStream, key: &str) -> BackupResult<PutObjectOutput> {
let upload_response = self
.s3_client
.put_object()
.bucket(&self.bucket)
.key(key.replace("\\", "/"))
.body(data)
.set_storage_class(Some(self.storage_class.to_owned()))
.server_side_encryption(self.encryption.to_owned())
.send()
.await;
match upload_response {
Ok(output) => Ok(output),
Err(err) => Err(BackupError::UploadFailed(err)),
}
} | {
"domain": "codereview.stackexchange",
"id": 42717,
"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": "console, rust, amazon-web-services",
"url": null
} |
console, rust, amazon-web-services
pub async fn fetch_existing_objects(
&self,
continuation_token: Option<String>,
) -> BackupResult<ListObjectsV2Output> {
self.s3_client
.list_objects_v2()
.bucket(&self.bucket)
.set_continuation_token(continuation_token)
.send()
.await
.map_err(BackupError::FileFetchFailed)
}
} | {
"domain": "codereview.stackexchange",
"id": 42717,
"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": "console, rust, amazon-web-services",
"url": null
} |
vba, excel
Title: Verify items and prices in a large Excel sheet
Question: This code searches for a lookup value (Worksheet "Price", Column B13:B31) from the table array in (Worksheet "Sheet1", Column A4:Z10000).
Can this be done in a simpler or shorter way?
Please find my code below;
Sub Lookup1()
Dim r, i As Long, rngLU As Range, j As Long
Dim price, descr As String
i = 13
j = 14
k = 15
l = 16
m = 17
n = 18
o = 19
p = 20
q = 21
g = 22
s = 23
t = 24
u = 25
v = 26
w = 27
x = 28
y = 29
Z = 30
h = 31
Set rngLU = Sheet4.Range("A4:A120000")
With Sheet1
If .Range("B" & i).Value2 > 1 Then
r = Application.Match(.Range("B" & i).Value2, rngLU, 0)
If IsError(r) Then
descr = "Please write manually the Item Description in Column K -->"
price = "#N/A"
Else
descr = rngLU.Cells(r, 3) ' col C
price = rngLU.Cells(r, 4) ' col D
End If
End If
.Cells(i, "C") = descr
.Cells(i, "H") = price
End With
With Sheet1
If .Range("B" & j).Value2 > 1 Then
r = Application.Match(.Range("B" & j).Value2, rngLU, 0)
If IsError(r) Then
descr = "Please write manually the Item Description in Column K -->"
price = "#N/A"
Else
descr = rngLU.Cells(r, 3) ' col C
price = rngLU.Cells(r, 4) ' col D
End If
End If
.Cells(j, "C") = descr
.Cells(j, "H") = price
End With
With Sheet1
If .Range("B" & k).Value2 > 1 Then
r = Application.Match(.Range("B" & k).Value2, rngLU, 0)
If IsError(r) Then
descr = "Please write manually the Item Description in Column K -->"
price = "#N/A"
Else
descr = rngLU.Cells(r, 3) ' col C
price = rngLU.Cells(r, 4) ' col D
End If
End If
.Cells(k, "C") = descr
.Cells(k, "H") = price
End With
With Sheet1 | {
"domain": "codereview.stackexchange",
"id": 42718,
"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": "vba, excel",
"url": null
} |
vba, excel
.Cells(k, "C") = descr
.Cells(k, "H") = price
End With
With Sheet1
If .Range("B" & l).Value2 > 1 Then
r = Application.Match(.Range("B" & l).Value2, rngLU, 0)
If IsError(r) Then
descr = "Please write manually the Item Description in Column K -->"
price = "#N/A"
Else
descr = rngLU.Cells(r, 3) ' col C
price = rngLU.Cells(r, 4) ' col D
End If
End If
.Cells(l, "C") = descr
.Cells(l, "H") = price
End With
With Sheet1
If .Range("B" & m).Value2 > 1 Then
r = Application.Match(.Range("B" & m).Value2, rngLU, 0)
If IsError(r) Then
descr = "Please write manually the Item Description in Column K -->"
price = "#N/A"
Else
descr = rngLU.Cells(r, 3) ' col C
price = rngLU.Cells(r, 4) ' col D
End If
End If
.Cells(m, "C") = descr
.Cells(m, "H") = price
End With
With Sheet1
If .Range("B" & n).Value2 > 1 Then
r = Application.Match(.Range("B" & n).Value2, rngLU, 0)
If IsError(r) Then
descr = "Please write manually the Item Description in Column K -->"
price = "#N/A"
Else
descr = rngLU.Cells(r, 3) ' col C
price = rngLU.Cells(r, 4) ' col D
End If
End If
.Cells(n, "C") = descr
.Cells(n, "H") = price
End With
With Sheet1
If .Range("B" & o).Value2 > 1 Then
r = Application.Match(.Range("B" & o).Value2, rngLU, 0)
If IsError(r) Then
descr = "Please write manually the Item Description in Column K -->"
price = "#N/A"
Else
descr = rngLU.Cells(r, 3) ' col C
price = rngLU.Cells(r, 4) ' col D
End If
End If
.Cells(o, "C") = descr
.Cells(o, "H") = price
End With
With Sheet1
If .Range("B" & p).Value2 > 1 Then
r = Application.Match(.Range("B" & p).Value2, rngLU, 0)
If IsError(r) Then
descr = "Please write manually the Item Description in Column K -->"
price = "#N/A"
Else
descr = rngLU.Cells(r, 3) ' col C
price = rngLU.Cells(r, 4) ' col D
End If
End If | {
"domain": "codereview.stackexchange",
"id": 42718,
"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": "vba, excel",
"url": null
} |
vba, excel
.Cells(p, "C") = descr
.Cells(p, "H") = price
End With
With Sheet1
If .Range("B" & q).Value2 > 1 Then
r = Application.Match(.Range("B" & q).Value2, rngLU, 0)
If IsError(r) Then
descr = "Please write manually the Item Description in Column K -->"
price = "#N/A"
Else
descr = rngLU.Cells(r, 3) ' col C
price = rngLU.Cells(r, 4) ' col D
End If
End If
.Cells(q, "C") = descr
.Cells(q, "H") = price
End With
With Sheet1
If .Range("B" & g).Value2 > 1 Then
r = Application.Match(.Range("B" & g).Value2, rngLU, 0)
If IsError(r) Then
descr = "Please write manually the Item Description in Column K -->"
price = "#N/A"
Else
descr = rngLU.Cells(r, 3) ' col C
price = rngLU.Cells(r, 4) ' col D
End If
End If
.Cells(g, "C") = descr
.Cells(g, "H") = price
End With
With Sheet1
If .Range("B" & s).Value2 > 1 Then
r = Application.Match(.Range("B" & s).Value2, rngLU, 0)
If IsError(r) Then
descr = "Please write manually the Item Description in Column K -->"
price = "#N/A"
Else
descr = rngLU.Cells(r, 3) ' col C
price = rngLU.Cells(r, 4) ' col D
End If
End If
.Cells(s, "C") = descr
.Cells(s, "H") = price
End With
With Sheet1
If .Range("B" & t).Value2 > 1 Then
r = Application.Match(.Range("B" & t).Value2, rngLU, 0)
If IsError(r) Then
descr = "Please write manually the Item Description in Column K -->"
price = "#N/A"
Else
descr = rngLU.Cells(r, 3) ' col C
price = rngLU.Cells(r, 4) ' col D
End If
End If
.Cells(t, "C") = descr
.Cells(t, "H") = price
End With
With Sheet1
If .Range("B" & u).Value2 > 1 Then
r = Application.Match(.Range("B" & u).Value2, rngLU, 0)
If IsError(r) Then
descr = "Please write manually the Item Description in Column K -->"
price = "#N/A"
Else
descr = rngLU.Cells(r, 3) ' col C
price = rngLU.Cells(r, 4) ' col D
End If
End If | {
"domain": "codereview.stackexchange",
"id": 42718,
"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": "vba, excel",
"url": null
} |
vba, excel
.Cells(u, "C") = descr
.Cells(u, "H") = price
End With
With Sheet1
If .Range("B" & v).Value2 > 1 Then
r = Application.Match(.Range("B" & v).Value2, rngLU, 0)
If IsError(r) Then
descr = "Please write manually the Item Description in Column K -->"
price = "#N/A"
Else
descr = rngLU.Cells(r, 3) ' col C
price = rngLU.Cells(r, 4) ' col D
End If
End If
.Cells(v, "C") = descr
.Cells(v, "H") = price
End With
With Sheet1
If .Range("B" & w).Value2 > 1 Then
r = Application.Match(.Range("B" & w).Value2, rngLU, 0)
If IsError(r) Then
descr = "Please write manually the Item Description in Column K -->"
price = "#N/A"
Else
descr = rngLU.Cells(r, 3) ' col C
price = rngLU.Cells(r, 4) ' col D
End If
End If
.Cells(w, "C") = descr
.Cells(w, "H") = price
End With
With Sheet1
If .Range("B" & x).Value2 > 1 Then
r = Application.Match(.Range("B" & x).Value2, rngLU, 0)
If IsError(r) Then
descr = "Please write manually the Item Description in Column K -->"
price = "#N/A"
Else
descr = rngLU.Cells(r, 3) ' col C
price = rngLU.Cells(r, 4) ' col D
End If
End If
.Cells(x, "C") = descr
.Cells(x, "H") = price
End With
With Sheet1
If .Range("B" & y).Value2 > 1 Then
r = Application.Match(.Range("B" & y).Value2, rngLU, 0)
If IsError(r) Then
descr = "Please write manually the Item Description in Column K -->"
price = "#N/A"
Else
descr = rngLU.Cells(r, 3) ' col C
price = rngLU.Cells(r, 4) ' col D
End If
End If
.Cells(y, "C") = descr
.Cells(y, "H") = price
End With
With Sheet1
If .Range("B" & Z).Value2 > 1 Then
r = Application.Match(.Range("B" & Z).Value2, rngLU, 0)
If IsError(r) Then
descr = "Please write manually the Item Description in Column K -->"
price = "#N/A"
Else
descr = rngLU.Cells(r, 3) ' col C
price = rngLU.Cells(r, 4) ' col D
End If
End If | {
"domain": "codereview.stackexchange",
"id": 42718,
"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": "vba, excel",
"url": null
} |
vba, excel
.Cells(Z, "C") = descr
.Cells(Z, "H") = price
End With
With Sheet1
If .Range("B" & h).Value2 > 1 Then
r = Application.Match(.Range("B" & h).Value2, rngLU, 0)
If IsError(r) Then
descr = "Please write manually the Item Description in Column K -->"
price = "#N/A"
Else
descr = rngLU.Cells(r, 3) ' col C
price = rngLU.Cells(r, 4) ' col D
End If
End If
.Cells(h, "C") = descr
.Cells(h, "H") = price
End With
Call ClearRows
End Sub
Answer: You are correct that this code can be simplified. The posted code was almost certainly created using Copy-Paste (19 times) followed by changing a single variable within the block. When code is created this way, it is always time to stop and find a way to refactor the copied code blocks to execute within some type of loop.
Fortunately in this case, the single value changed in each code block appears to be a sequence of contiguous numbers. As a result, the entire subroutine can be executed within a single For loop.
Sub Lookup1UsingLoop()
Dim r, i As Long, rngLU As Range, j As Long
Dim price, descr As String
Set rngLU = Sheet4.Range("A4:A120000")
Dim rangeAddress As String
Dim rowNumber As Long
With Sheet1
For rowNumber = 13 To 31
rangeAddress = "B" & CStr(rowNumber)
If .Range(rangeAddress).Value2 > 1 Then
r = Application.Match(.Range(rangeAddress ).Value2, rngLU, 0)
If IsError(r) Then
descr = "Please write manually the Item Description in Column K -->"
price = "#N/A"
Else
descr = rngLU.Cells(r, 3) ' col C
price = rngLU.Cells(r, 4) ' col D
End If
End If
.Cells(rowNumber, "C") = descr
.Cells(rowNumber, "H") = price
Next
End With
Call ClearRows
End Sub | {
"domain": "codereview.stackexchange",
"id": 42718,
"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": "vba, excel",
"url": null
} |
c#, validation
Title: Input Data Validator (good practice)
Question: I work at an application that receives data from user and I try to write a validator function for it, but I'm not sure if this is the correct way to proceed.
Example: The user will input a number (as string, don't ask why I don't use an int, let it be a string), let's say "103", and I'will use this number inside a function, but first, at the beginning of that function I call a validator function:
private bool ValidateCommandCode(string code)
{
bool isValid = false;
byte commandByte = new byte();
if (byte.TryParse(code, out commandByte))
{
isValid = true;
}
else
{
Log.Error($"Command number {CommandCode} for the request is not valid!");
isValid = false;
}
return isValid;
}
private async void MainFunction()
{
if (ValidateCommandCode(CommandCode) == false)
return;
// ... do the magic with the CommandCode ...
}
in the same manner, I want to validate another field filled by the user: e.g of data: 000A000B
private bool ValidateRequestData(string data)
{
bool isValid = false;
if (!String.IsNullOrEmpty(Payload) && !String.IsNullOrWhiteSpace(Payload))
{
if (Payload.Trim().Replace(" ", "").Length % 2 != 0)
{
Log.Error($"Payload (Data) {Payload} for the request doesn't have an even number of bytes!");
isValid = false;
}
else
{
isValid = true;
}
}
else
{
isValid = true;
}
return isValid;
}
Is this a good way to proceed? Aren't so many flags "isValid" too confusing?
Answer: First off, in here
if (!String.IsNullOrEmpty(Payload) && !String.IsNullOrWhiteSpace(Payload))
You only need to do
if(!String.IsNullOrWhiteSpace(Payload)) | {
"domain": "codereview.stackexchange",
"id": 42719,
"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#, validation",
"url": null
} |
c#, validation
You only need to do
if(!String.IsNullOrWhiteSpace(Payload))
There is a lot of nesting going on and you can simplify your code to make it easier to read by doing this instead
private static bool ValidateRequestData(string data, string payload)
{
if (String.IsNullOrWhiteSpace(data)) return false; // or throw
if (String.IsNullOrWhiteSpace(payload)) return false;
if (payload.Trim().Replace(" ", "").Length % 2 != 0)
{
//Log.Error(...);
return false;
}
return true
}
If you also notice, we are passing in the payload as an argument and also make this a static method. This is generally a safer design as the state of your member Payload is likely not guaranteed to remain the same (or at least it's not obvious).
I would also recommend changing the method name from ValidateRequestData() to IsValidRequestData().
As an extra. We can also clean up you other method
private static bool ValidateCommandCode(string code)
{
if (!byte.TryParse(code, out byte commandByte))
{
//Log.Error(...);
return false;
}
return true;
}
Although, keep in mind the Parse could probably have happened somewhere else. It doesn't seem very efficient to do a parse only for the purpose of validation and not making any use of the result. | {
"domain": "codereview.stackexchange",
"id": 42719,
"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#, validation",
"url": null
} |
c++, template-meta-programming, c++20
Title: invocable_traits
Question: Update: there are new versions of this code: v3 is posted here and v4 is posted here
Goal: implement traits that for anything callable return its arity, return type and the argument types. Since pointers to data members are also callable, those should be handled (and be considered 0-arity).
Code below, try here. This is v2, after comments received here.
Besides the suggested changes, i have added support for function references, now also provide information about the class the invocable belongs to (if member function, or data member), and provide better error messages if you want try to get the traits on something not callable.
I decided not to put a ref to the class as the first argument type, but instead provide it separately. Testing if class_type is not void tells you if a ref to a class instance is needed. Indeed, for pointers to static member functions, class_type is void.
#pragma once
#include <cstddef>
#include <tuple>
#include <type_traits>
// derived and extended from https://github.com/kennytm/utils/blob/master/traits.hpp
// and https://stackoverflow.com/a/28213747
// This does not handle overloaded functions (which includes functors with
// overloaded operator()), because the compiler would not be able to resolve
// the overload without knowing the argument types and the cv- and noexcept-
// qualifications. If you do know those already and can thus specify the
// overload to the compiler, you do not need this class. The only remaining
// piece of information is the result type, which you can get with
// std::invoke_result.
namespace detail
{
template <std::size_t i, typename... Args>
struct invocable_traits_arg_impl
{
static_assert(i<sizeof...(Args), "Requested argument type out of bounds (function does not declare this many arguments)");
using type = std::tuple_element_t<i, std::tuple<Args...>>;
}; | {
"domain": "codereview.stackexchange",
"id": 42720,
"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++, template-meta-programming, c++20",
"url": null
} |
c++, template-meta-programming, c++20
using type = std::tuple_element_t<i, std::tuple<Args...>>;
};
template <typename R, typename C, bool IsVariadic, typename... Args>
struct invocable_traits_class
{
static constexpr std::size_t arity = sizeof...(Args);
static constexpr auto is_variadic = IsVariadic;
using result_type = R;
using class_type = C;
template <std::size_t i>
using arg = invocable_traits_arg_impl<i,Args...>::type;
};
template <typename R, bool IsVariadic, typename... Args>
struct invocable_traits_free : public invocable_traits_class<R, void, IsVariadic, Args...> {};
}
template <typename T>
struct invocable_traits; | {
"domain": "codereview.stackexchange",
"id": 42720,
"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++, template-meta-programming, c++20",
"url": null
} |
c++, template-meta-programming, c++20
#define INVOCABLE_TRAITS_SPEC(cv,...) \
/* handle functions, with all possible iterations of reference and noexcept */ \
template <typename R, typename... Args> \
struct invocable_traits<R(Args... __VA_OPT__(,) __VA_ARGS__) cv> \
: public detail::invocable_traits_free<R,0 __VA_OPT__(+1),Args...> {}; \
template <typename R, typename... Args> \
struct invocable_traits<R(Args...__VA_OPT__(,) __VA_ARGS__) cv &> \
: public detail::invocable_traits_free<R,0 __VA_OPT__(+1),Args...> {}; \
template <typename R, typename... Args> \
struct invocable_traits<R(Args...__VA_OPT__(,) __VA_ARGS__) cv &&> \
: public detail::invocable_traits_free<R,0 __VA_OPT__(+1),Args...> {}; \
template <typename R, typename... Args> \
struct invocable_traits<R(Args...__VA_OPT__(,) __VA_ARGS__) cv noexcept> \
: public detail::invocable_traits_free<R,0 __VA_OPT__(+1),Args...> {}; \
template <typename R, typename... Args> \
struct invocable_traits<R(Args...__VA_OPT__(,) __VA_ARGS__) cv & noexcept> \
: public detail::invocable_traits_free<R,0 __VA_OPT__(+1),Args...> {}; \
template <typename R, typename... Args> \
struct invocable_traits<R(Args...__VA_OPT__(,) __VA_ARGS__) cv && noexcept> \
: public detail::invocable_traits_free<R,0 __VA_OPT__(+1),Args...> {}; \
/* handle pointers to member functions (incl. iterations of reference and noexcept) */\
template <typename C, typename R, typename... Args> \
struct invocable_traits<R(C::*)(Args...__VA_OPT__(,) __VA_ARGS__) cv> \ | {
"domain": "codereview.stackexchange",
"id": 42720,
"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++, template-meta-programming, c++20",
"url": null
} |
c++, template-meta-programming, c++20
struct invocable_traits<R(C::*)(Args...__VA_OPT__(,) __VA_ARGS__) cv> \
: public detail::invocable_traits_class<R,C,0 __VA_OPT__(+1),Args...> {}; \
template <typename C, typename R, typename... Args> \
struct invocable_traits<R(C::*)(Args...__VA_OPT__(,) __VA_ARGS__) cv &> \
: public detail::invocable_traits_class<R,C,0 __VA_OPT__(+1),Args...> {}; \
template <typename C, typename R, typename... Args> \
struct invocable_traits<R(C::*)(Args...__VA_OPT__(,) __VA_ARGS__) cv &&> \
: public detail::invocable_traits_class<R,C,0 __VA_OPT__(+1),Args...> {}; \
template <typename C, typename R, typename... Args> \
struct invocable_traits<R(C::*)(Args...__VA_OPT__(,) __VA_ARGS__) cv noexcept> \
: public detail::invocable_traits_class<R,C,0 __VA_OPT__(+1),Args...> {}; \
template <typename C, typename R, typename... Args> \
struct invocable_traits<R(C::*)(Args...__VA_OPT__(,) __VA_ARGS__) cv & noexcept> \
: public detail::invocable_traits_class<R,C,0 __VA_OPT__(+1),Args...> {}; \
template <typename C, typename R, typename... Args> \
struct invocable_traits<R(C::*)(Args...__VA_OPT__(,) __VA_ARGS__) cv && noexcept> \
: public detail::invocable_traits_class<R,C,0 __VA_OPT__(+1),Args...> {}; \
/* handle pointers to data members */ \
__VA_OPT__( /* no variadic function version for data members, (inverted) skip */ \
template <typename C, typename R> \
struct invocable_traits<R C::* cv> \
: public detail::invocable_traits_class<R,C,false> {}; \
) /* end __VA_OPT___*/ | {
"domain": "codereview.stackexchange",
"id": 42720,
"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++, template-meta-programming, c++20",
"url": null
} |
c++, template-meta-programming, c++20
// cover all const and volatile permutations
INVOCABLE_TRAITS_SPEC(, )
INVOCABLE_TRAITS_SPEC(const, )
INVOCABLE_TRAITS_SPEC(volatile, )
INVOCABLE_TRAITS_SPEC(const volatile, )
// and also variadic function versions
INVOCABLE_TRAITS_SPEC(, ...)
INVOCABLE_TRAITS_SPEC(const, ...)
INVOCABLE_TRAITS_SPEC(volatile, ...)
INVOCABLE_TRAITS_SPEC(const volatile, ...)
#undef INVOCABLE_TRAITS_SPEC
// pointers to functions
template <typename R, typename... Args>
struct invocable_traits<R(*)(Args...)> : public invocable_traits<R(Args...)> {};
template <typename R, typename... Args>
struct invocable_traits<R(*)(Args...) noexcept> : public invocable_traits<R(Args...)> {};
template <typename R, typename... Args>
struct invocable_traits<R(*)(Args..., ...)> : public invocable_traits<R(Args..., ...)> {};
template <typename R, typename... Args>
struct invocable_traits<R(*)(Args..., ...) noexcept> : public invocable_traits<R(Args..., ...)> {};
// references to functions
template <typename R, typename... Args>
struct invocable_traits<R(&)(Args...)> : public invocable_traits<R(Args...)> {};
template <typename R, typename... Args>
struct invocable_traits<R(&)(Args...) noexcept> : public invocable_traits<R(Args...)> {};
template <typename R, typename... Args>
struct invocable_traits<R(&)(Args..., ...)> : public invocable_traits<R(Args..., ...)> {};
template <typename R, typename... Args>
struct invocable_traits<R(&)(Args..., ...) noexcept> : public invocable_traits<R(Args..., ...)> {};
// get at operator() of any struct/class defining it (this includes lambdas)
// bit of machinery for better error messages
namespace detail {
template <typename T>
concept HasCallOperator = requires(T)
{
std::declval<T>().operator();
};
template <typename T, bool isCallable>
struct invocable_traits_extract : invocable_traits<decltype(&T::operator())> {}; | {
"domain": "codereview.stackexchange",
"id": 42720,
"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++, template-meta-programming, c++20",
"url": null
} |
c++, template-meta-programming, c++20
template <typename T>
struct invocable_traits_extract<T, false>
{
static_assert(std::is_class_v<T>, "passed type is not a class, and thus cannot have an operator()");
static_assert(!std::is_class_v<T> || HasCallOperator<T>, "passed type is a class that doesn't have an operator()");
// to reduce excessive compiler error output
static constexpr std::size_t arity = 0;
static constexpr auto is_variadic = false;
using result_type = void;
using class_type = void;
template <size_t i> struct arg { using type = void; };
};
}
template <typename T>
struct invocable_traits : detail::invocable_traits_extract<std::decay_t<T>, detail::HasCallOperator<T>> {};
testing code:
#include <string>
void test(int)
{}
void test2(int) noexcept
{}
void testEllipsis(int,...)
{}
struct tester
{
void yolo(char)
{}
void yoloEllipsis(char, ...)
{}
static long yoloStatic(short)
{}
void operator()(int in_)
{}
std::string field;
};
int main()
{
auto lamb = [](const int& in_) {return "ret"; };
using traits = invocable_traits<decltype(lamb)>;
static_assert(std::is_same_v<const char*, traits::result_type>, "");
static_assert(std::is_same_v<const int&, traits::arg<0>>, "");
using traits2 = invocable_traits<decltype(&test)>;
static_assert(std::is_same_v<void, traits2::result_type>, "");
static_assert(std::is_same_v<int, traits2::arg<0>>, "");
using traits2b = invocable_traits<decltype(&test2)>;
static_assert(std::is_same_v<void, traits2b::result_type>, "");
static_assert(std::is_same_v<int, traits2b::arg<0>>, "");
static_assert(!traits2b::is_variadic, "");
using traits2c = invocable_traits<decltype(&testEllipsis)>;
static_assert(std::is_same_v<void, traits2c::result_type>, "");
static_assert(std::is_same_v<int, traits2c::arg<0>>, "");
static_assert(traits2c::is_variadic, ""); | {
"domain": "codereview.stackexchange",
"id": 42720,
"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++, template-meta-programming, c++20",
"url": null
} |
c++, template-meta-programming, c++20
using traits3 = invocable_traits<decltype(&tester::yolo)>;
static_assert(std::is_same_v<void, traits3::result_type>, "");
static_assert(std::is_same_v<char, traits3::arg<0>>, "");
using traits3b = invocable_traits<decltype(&tester::yoloEllipsis)>;
static_assert(std::is_same_v<void, traits3b::result_type>, "");
static_assert(std::is_same_v<tester, traits3b::class_type>, "");
static_assert(std::is_same_v<char, traits3b::arg<0>>, "");
static_assert(traits3b::is_variadic, "");
using traits3c = invocable_traits<decltype(&tester::yoloStatic)>;
static_assert(std::is_same_v<long, traits3c::result_type>, "");
static_assert(std::is_same_v<void, traits3c::class_type>, "");
static_assert(std::is_same_v<short, traits3c::arg<0>>, "");
static_assert(!traits3c::is_variadic, "");
using traits4 = invocable_traits<decltype(&tester::field)>;
static_assert(std::is_same_v<std::string, traits4::result_type>, "");
static_assert(traits4::arity==0, "");
using traits5 = invocable_traits<std::add_rvalue_reference_t<decltype(lamb)>>;
static_assert(std::is_same_v<const char*, traits5::result_type>, "");
static_assert(std::is_same_v<const int&, traits5::arg<0>>, "");
using traits6 = invocable_traits<std::add_lvalue_reference_t<decltype(lamb)>>;
static_assert(std::is_same_v<const char*, traits6::result_type>, "");
static_assert(std::is_same_v<decltype(lamb), traits6::class_type>, "");
static_assert(std::is_same_v<const int&, traits6::arg<0>>, "");
auto lamb2 = [](const int& in_, ...) mutable noexcept {return "ret"; };
// functor
using traits7 = invocable_traits<tester>;
static_assert(std::is_same_v<void, traits7::result_type>, "");
static_assert(std::is_same_v<int, traits7::arg<0>>, ""); | {
"domain": "codereview.stackexchange",
"id": 42720,
"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++, template-meta-programming, c++20",
"url": null
} |
c++, template-meta-programming, c++20
using traits8 = invocable_traits<decltype(lamb2)>;
static_assert(std::is_same_v<const char*, traits8::result_type>, "");
static_assert(std::is_same_v<const int&, traits8::arg<0>>, "");
static_assert(traits8::is_variadic, "");
/*using traits9 = invocable_traits<int>;
static_assert(std::is_same_v<const char*, traits9::result_type>, "");*/
return 0;
}
Answer: Be sure to #undef the macro after the use of it. It's for expanding inside the header, not for the user to call.
What does it do with overloaded functions? | {
"domain": "codereview.stackexchange",
"id": 42720,
"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++, template-meta-programming, c++20",
"url": null
} |
c++, regex
Title: Replace function for C++
Question: I'm learning regex for c++, and tried to make a simple function. It is very small but I'm satisfied, because this is the first time I managed to pass function as argument. This is a replace function. Please give me tips on how to improve:
std::string Replace(std::string text, std::regex reg, std::function<std::string(std::smatch)> func){
std::smatch matcher;
std::string result = "";
while (std::regex_search(text, matcher, reg))
{
result += matcher.prefix().str();
result += func(matcher);
text = matcher.suffix().str();
}
result += text;
return result;
}
Now here is a test, I pass a javascript like formatted string, with regex \\$\\{\\s*([a-zA-Z0-9]*?)\\s*\\} and I put my name and age into a variable.
int main(){
std::string name = "Ihsan";
std::string age = "13";
std::string text = "hello my name is ${name}, and im ${age} years old.";
std::regex pattern("\\$\\{\\s*([a-zA-Z0-9]*?)\\s*\\}");
std::cout << Replace(text, pattern, [name, age](auto matcher) -> std::string{
std::string str1 = matcher.str(1);
if(str1 == "name"){
return name;
}
if(str1 == "age"){
return age;
}
});
}
Output is:
hello my name is Ihsan, and im 13 years old. | {
"domain": "codereview.stackexchange",
"id": 42721,
"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++, regex",
"url": null
} |
c++, regex
}
Output is:
hello my name is Ihsan, and im 13 years old.
Answer: There are a lot easier ways to print your name and age, but I'll assume you know that :)
When you pass non-POD arguments into functions it is usually more efficient to pass them as references, because it means you don't create a copy of them. (POD => Plain Old Data: int, char, etc).
When you pass an argument by reference it can introduce confusion, is the argument being passed by reference, or is it going to be assigned a value within the function and used as an out variable? So it helps readers understand the code if you make you references const.
Of course adding comments to your code makes a big difference. You know what it is doing and WHY now, but give it 6 months time and you will think an alien wrote it.
You should always have a think about using literal values, i.e. name and age. OK in this case its not too much of an issue, but what about wrapping them up in a map with the replacement values? It would make your code shorter and more extendable? | {
"domain": "codereview.stackexchange",
"id": 42721,
"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++, regex",
"url": null
} |
c++, multithreading, callback, c++20
Title: c++ multithreaded message broadcaster with link lifetime management
Question: note: A version of this code without link lifetime management was previously reviewed. Adding lifetime management actually made the code simpler, and the class simpler to use.
I have written a class that handles listeners registering callbacks to receive messages. Link lifetime is managed. Code is multithreaded in that any thread can broadcast to the listeners, and any thread can add or remove listeners.
I have made a list of requirements for the class:
there may be zero, one or multiple listeners
listeners can be registered or deregistered from different threads
each listener should be called exactly once for each message
all listeners should receive all messages
messages may originate from multiple sources in different threads
each message should be forwarded to all listeners before the next message is processed (messages are not sent in parallel)
each listener should receive the messages in the same order, i.e., the order in which they are provided to the broadcaster (from the view of the broadcaster)
listeners can be removed
listeners are identified by a cookie whose validity state indicates if the listener is still listening
anyone with the cookie should be able to deregister the listener
listeners should never be called again when deregistration completes
listeners should be able to add a new listener when invoked, this listener will participate starting from the next message
listeners are noexcept, so code shouldn’t deal with exceptions thrown by listeners
adding and removing listeners happens much less frequently than broadcasting.
A further consideration that is not enforced in code:
Users are expected to read documentation that states which functions are safe to call from inside a listener, and which must not. | {
"domain": "codereview.stackexchange",
"id": 42722,
"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++, multithreading, callback, c++20",
"url": null
} |
c++, multithreading, callback, c++20
Link lifetime management is performed by wrapper each registered listener function in a shared_ptr that is held by the listener, and references as a weak pointer in the broadcaster class. Just before the listener is invoked, the weak pointer is converted to a shared pointer, which would fail if the listener released its end.
I am not sure if this method for lifetime management works, or if there is a race condition: broadcaster obtains shared pointer, but before it can invoke the callback, the listener just destructs. Link remains valid as shared pointer is acquired by broadcaster, but the listener that is about to be invoked no longer exists. That is a possible race, right? How to solve it?
A listener who owns a dangling link (no more broadcaster) is not a problem, as they can't do anything unsafe with their end of the link.
Implementation
#include <vector>
#include <iterator>
#include <mutex>
#include <memory>
#include <functional>
#include <type_traits>
// based on https://stackoverflow.com/a/47872677
// usage notes:
// 1. None of the member functions of this class may be called from
// inside an executing listener, except
// add_listener_from_inside_callback(). Calling them anyway
// will result in deadlock.
// 2. add_listener_from_inside_callback() may _only_ be called from
// inside an executing listener.
template <class... Message>
class Broadcaster
{
public:
using listener = std::function<void(Message...)>;
using cookieType = std::shared_ptr<void>;
// returns number of registered listeners
size_t num_listeners() noexcept
{
auto l = std::unique_lock(_mut);
// prune to reduce chance that we return
// having more listeners than we do
for (auto it = _targets.cbegin(); it != _targets.cend(); )
{
if (it->expired())
it = _targets.erase(it);
else
++it;
}
return _targets.size();
} | {
"domain": "codereview.stackexchange",
"id": 42722,
"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++, multithreading, callback, c++20",
"url": null
} |
c++, multithreading, callback, c++20
// clears all listeners
void clear() noexcept
{
auto l = std::unique_lock(_mut);
_targets.clear();
}
// should never be called from inside a running listener
template <class F> requires (std::is_nothrow_invocable_r_v<void, F, Message...>)
[[nodiscard]] cookieType add_listener(F&& r_)
{
auto l = std::unique_lock(_mut);
auto listenFunc = std::make_shared<listener>(std::forward<F>(r_));
_targets.push_back(listenFunc);
return listenFunc;
}
template <class F> requires (std::is_nothrow_invocable_r_v<void, F, Message...>)
[[nodiscard]] cookieType add_listener_from_inside_callback(F&& r_)
{
auto listenFunc = std::make_shared<listener>(std::forward<F>(r_));
// place into a holding pen, will be added to active listeners
// as soon as all currently registered callbacks have received
// the current message
_newTargets.push_back(listenFunc);
return listenFunc;
}
void notify_all(const Message&... msg_) noexcept
{
auto l = std::unique_lock(_mut);
// invoke all listeners with message, if still
// alive. else remove
for (auto it = _targets.cbegin(); it != _targets.cend(); )
{
auto targetPtr = it->lock();
if (!targetPtr)
it = _targets.erase(it);
else
{
targetPtr->operator()(msg_...);
++it;
}
}
// if any new listeners, move them into active listeners
// so they'll receive the next message
if (!_newTargets.empty())
{
_targets.insert(_targets.end(), std::make_move_iterator(_newTargets.begin()),
std::make_move_iterator(_newTargets.end()));
_newTargets.clear();
}
} | {
"domain": "codereview.stackexchange",
"id": 42722,
"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++, multithreading, callback, c++20",
"url": null
} |
c++, multithreading, callback, c++20
private:
mutable std::mutex _mut;
std::vector<std::weak_ptr<listener>> _targets;
std::vector<std::weak_ptr<listener>> _newTargets;
};
Example usage
#include <iostream>
#include <string>
#include <functional>
void freeTestFunction(std::string msg_) noexcept
{
std::cout << "from freeTestFunction: " << msg_ << std::endl;
}
struct test
{
using StringBroadcaster = Broadcaster<std::string>;
void simpleCallback(std::string msg_) noexcept
{
std::cout << "from simpleCallback: " << msg_ << std::endl;
}
void oneShotCallback(std::string msg_) noexcept
{
std::cout << "from oneShotCallback: " << msg_ << std::endl;
_cb_oneShot_cookie.reset();
}
void twoStepCallback_step1(std::string msg_) noexcept
{
std::cout << "from twoStepCallback_step1: " << msg_ << std::endl;
// replace callback
_cb_twostep_cookie = _broadcast.add_listener_from_inside_callback([&](auto fr_) noexcept { twoStepCallback_step2(fr_); });
}
void twoStepCallback_step2(std::string msg_) noexcept
{
std::cout << "from twoStepCallback_step2: " << msg_ << std::endl;
}
void runExample()
{
auto cb_simple_cookie = _broadcast.add_listener([&](auto fr_) noexcept { simpleCallback(fr_); });
_cb_oneShot_cookie = _broadcast.add_listener([&](auto fr_) noexcept { oneShotCallback(fr_); });
_cb_twostep_cookie = _broadcast.add_listener([&](auto fr_) noexcept { twoStepCallback_step1(fr_); });
auto free_func_cookie = _broadcast.add_listener(&freeTestFunction); | {
"domain": "codereview.stackexchange",
"id": 42722,
"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++, multithreading, callback, c++20",
"url": null
} |
c++, multithreading, callback, c++20
_broadcast.notify_all("message 1"); // should be received by simpleCallback, oneShotCallback, twoStepCallback_step1, freeTestFunction
free_func_cookie.reset();
_broadcast.notify_all("message 2"); // should be received by simpleCallback and twoStepCallback_step2
cb_simple_cookie.reset();
_broadcast.notify_all("message 3"); // should be received by twoStepCallback_step2
_cb_twostep_cookie.reset();
_broadcast.notify_all("message 4"); // should be received by none
}
StringBroadcaster _broadcast;
StringBroadcaster::cookieType _cb_oneShot_cookie;
StringBroadcaster::cookieType _cb_twostep_cookie;
};
int main(int argc, char **argv)
{
test t;
t.runExample();
return 0;
} | {
"domain": "codereview.stackexchange",
"id": 42722,
"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++, multithreading, callback, c++20",
"url": null
} |
c++, multithreading, callback, c++20
int main(int argc, char **argv)
{
test t;
t.runExample();
return 0;
}
Answer: Unnecessary use of mutable
Since none of the member functions are const, you can't call them on a const Broadcaster object, so making the mutex mutable does not do anything.
Making adding from inside the callback easier
The caller must remember to call add_listener_from_inside_callback() if it is inside the callback, otherwise a deadlock will occur. Also, calling add_listener_from_inside_callback() outside a callback might invalidate iterators. You can avoid the need for this function, and have add_listener() safely detect if it is called from inside a callback.
The first requirement is to use std::recursive_mutex instead of a regular mutex. This ensures calling add_listener() from inside the callback won't deadlock.
The remaining issue is to avoid iterator invalidation. You could consider adding a simple boolean flag _in_callback, which is set at the start of notify_all and cleared at the end, and if set when add_listener() is called, append to _newTargets instead of _targets. However, there are two
other options. The first is to always add to _newTargets, and to move the new targets into _targets at the start of notify_all(). The second is to use std::deque instead of std::vector, as it won't invalidate iterators if you insert at the front or back. You can't erase elements in the same loop anymore though, but you can defer that to after the main loop. It could look like:
template <class... Message>
class Broadcaster
{
...
void notify_all(const Message&... msg_) noexcept
{
auto l = std::unique_lock(_mut);
bool flush = false;
for (auto& target: _targets) {
if (auto targetPtr = target.lock())
targetPtr->operator()(msg_...);
else
flush = true;
} | {
"domain": "codereview.stackexchange",
"id": 42722,
"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++, multithreading, callback, c++20",
"url": null
} |
c++, multithreading, callback, c++20
if (flush)
std::erase_if(_targets, [](auto& target){return target.expired();});
}
...
private:
std::recursive_mutex _mut;
std::deque<std::weak_ptr<listener>> _targets;
};
A big drawback of the std::recursive_mutex is that it will now allow callbacks to also call num_listeners() and clear() without deadlocking, but instead invalidating iterators. You could avoid that again by adding an in_callback flag to detect recursion. | {
"domain": "codereview.stackexchange",
"id": 42722,
"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++, multithreading, callback, c++20",
"url": null
} |
python, performance, reinventing-the-wheel, quick-sort
Title: In place QuickSort algorithm in Python
Question: I have been searching for ways to make my algorithm more efficient but most answers told me to divide the array into two differente arrays one of less elements and one of greater elements and then merge it, but that would make the QuickSort a non in-place sort anymore.
So, if someone could tell me a way of improving the efficiency of my code and if it is well designed or not, without affecting the in-place characteristic of the algorithm.
def QuickSort(array, right, left):
left_original = left
right_original = right
pivot_pos = right
while True:
for right in reversed(range(pivot_pos, right+1)):
if (array[right] < array[pivot_pos]):
break
for left in range(left, pivot_pos+1):
if (array[left] > array[pivot_pos]):
break
if right == left:
break
if array[pivot_pos] == array[right]:
pivot_pos = left
elif array[pivot_pos] == array[left]:
pivot_pos = right
array[right], array[left] = array[left], array[right]
right = right_original
left = left_original
right1 = pivot_pos - 1
left1 = left_original
right2 = right_original
left2 = pivot_pos + 1
if (right1 > left1):
QuickSort(array, right1, left1)
if (right2 > left2):
QuickSort(array, right2, left2)
Answer: Fix your function signature. Most Python programmers use lowercase for function
names. Even more important, don't swap the order the left and right:
# No: why is "left" to the right of "right"?!?
def QuickSort(array, right, left):
...
# Yes: less chance for confusion.
def quicksort(array, left, right):
... | {
"domain": "codereview.stackexchange",
"id": 42723,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, reinventing-the-wheel, quick-sort",
"url": null
} |
python, performance, reinventing-the-wheel, quick-sort
# Yes: less chance for confusion.
def quicksort(array, left, right):
...
Don't make the caller know your implementation details. Forcing the caller
to pass values for left and right is not convenient for your users; it is
somewhat error prone (for example, in some cases you can pass the wrong
indexes, the function will complete without error, but the list won't be
sorted); and it's not needed because Python makes it easy to define a function
with optional arguments:
def quicksort(xs, left = 0, right = None):
if right is None:
right = len(xs) - 1
...
Ranges have a step value. If you are using range(), you don't need
reversed(). Use a negative step:
for right in range(right, pivot_pos - 1, -1):
...
What about empty sequences?. Currently your code raises an error. This
problem is related to the next point.
Enforce recursive termination in one spot, almost always at the beginning.
As a general rule for recursive functions, enforce the termination condition at
the outset -- and only there. Your code makes a very common mistake of trying to
look into the future: before making the recursive call, you check for
preconditions. I observed this mistake in many software engineering
interviews, and it almost always caused the applicants to become more
confused. The better approach is to be confident: just make the recursive call
and let the function handle its own preconditions. Here's that point
illustrated with a code comparison:
# If we try to look into the future, additional variables
# are spawned, increasing complexity.
def quicksort(array, left, right):
...
right1 = pivot_pos - 1
left1 = left_original
right2 = right_original
left2 = pivot_pos + 1
if (right1 > left1):
quicksort(array, left1, right1)
if (right2 > left2):
quicksort(array, left2, right2)
# Things are simpler if we blindly recurse, letting the function
# enforce preconditions in a natural manner. | {
"domain": "codereview.stackexchange",
"id": 42723,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, reinventing-the-wheel, quick-sort",
"url": null
} |
python, performance, reinventing-the-wheel, quick-sort
def quicksort(array, left, right):
if right <= left:
return
...
quicksort(array, left_original, pivot_pos - 1)
quicksort(array, pivot_pos + 1, right_original)
Using top-down implementation: an alternative to consider. Although your
current implementation appears to work correctly, I found it difficult to
reason about. For example, it seems like the main while-true loop might be
doing repetitive work, because on every iteration right and left are reset
to the original boundaries -- but perhaps I overlooked a detail. Either way,
the core idea of quicksort is very intuitive: we select a pivot value and make
the necessary swaps to enforce the quicksort invariant, namely small values < pivot value <= large values. But the implementation does not build on that
intuition or make it evident, either in code or in comments to guide the
reader. The implementation is additionally complex because several variables
are changing at once: right is being pushed downward, left pushed upward,
pivot_pos is sometimes altered based on those changes, then we swap a large
value and a small value, and then left and right are reset. I guess that
has a resemblance to quicksort (and is probably correct) but the alignment
between the code and the intuition not super obvious. Sometimes when struggling
to write an intuitive implementation (as distinct from a merely working one), I
will use a top-down approach. First we start with something clear and basic:
def quicksort(xs, i = 0, j = None):
# Set optional arguments.
if j is None:
j = len(xs) - 1
# Base case: do nothing if indexes have met or crossed.
if not i < j:
return
# Partition the sequence to enforce the quicksort invariant:
# "small values" < pivot value <= "large values". The function
# returns the index of the pivot value.
pi = partition(xs, i, j)
# Sort left side and right side.
quicksort(xs, i, pi - 1)
quicksort(xs, pi + 1, j) | {
"domain": "codereview.stackexchange",
"id": 42723,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, reinventing-the-wheel, quick-sort",
"url": null
} |
python, performance, reinventing-the-wheel, quick-sort
# Sort left side and right side.
quicksort(xs, i, pi - 1)
quicksort(xs, pi + 1, j)
Implement the functions that your top-level design omitted. So far, we
have simplicity and clarity, but only because we've deferred the trickiest
part: how to do the partitioning. But the top-down approach has a big benefit
in that we've reduced the size the problem considerably: instead of doing
sorting, we are merely partitioning; instead of build a user-facing function, we
are writing a utility function intended for use only by our quicksorter; and
instead of building a recursive function, we are building a regular function.
In my notes from various algorithm classes, I have a quicksort partitioning
function along the following lines. Note how some of its simplicity comes from
the fact that we are not modifying too many values: k which is just the
primary iteration variable, and pb which represents the current
partitioning boundary. Also note how additional simplicity comes from writing
another utility: the swap() function. If we were writing a mission-critical
sort function and cared about raw speed, we would not use that approach;
instead, we would do the swapping in line. However, in this case we are
focusing on algorithmic clarity. In that context, moving the grubby swapping
details elsewhere is a benefit.
def partition(xs, i, j):
# Get the pivot value and initialize the partition boundary.
pval = xs[i]
pb = i + 1
# Examine all values other than the pivot, swapping to enforce the
# invariant. Every swap moves an observed "small" value to the left of the
# boundary. "Large" values are left alone since they are already to the
# right of the boundary.
for k in range(pb, j + 1):
if xs[k] < pval:
swap(xs, k, pb)
pb += 1
# Put pivot value between the two sides of the partition,
# and return that location.
swap(xs, i, pb - 1)
return pb - 1
def swap(xs, i, j):
xs[i], xs[j] = xs[j], xs[i] | {
"domain": "codereview.stackexchange",
"id": 42723,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, reinventing-the-wheel, quick-sort",
"url": null
} |
c++, multithreading, callback, c++20
Title: c++ multithreaded message broadcaster with link lifetime management v2
Question: note: This is v2 of code that was previously reviewed.
I have written a class that handles listeners registering callbacks to receive messages. Link lifetime is managed (or is it?). Code is multithreaded in that any thread can broadcast to the listeners, and any thread can add or remove listeners.
I have two concerns:
I am not sure if this method for lifetime management works, or if there is a race condition. Is the following a possible race condition?
broadcaster obtains shared pointer;
before it can invoke the callback, the listener destructs (imaging its a ref to a class member function);
Listener is invoked, but points to an object that no longer exists.
It is possible that the broadcaster is destructed while another thread has invoked one of the member functions, and thus holds (or is trying to acquire) the mutex. That would crash?
Implementation
#include <vector>
#include <mutex>
#include <memory>
#include <functional>
#include <type_traits>
#include <numeric>
// based on https://stackoverflow.com/a/47872677
// usage notes:
// 1. It is safe to call any of the member functions
// from inside a listener invoked by this class.
// 2. Listeners added from inside listener callback
// will participate starting from the next message.
// 3. This class guarantees message ordering with
// multiple producer threads.
template <class... Message>
class Broadcaster
{
public:
using listener = std::function<void(Message...)>;
using cookieType = std::shared_ptr<void>;
// returns number of registered listeners
size_t num_listeners() const noexcept
{
auto l = std::unique_lock(_mut);
return std::accumulate(_targets.cbegin(), _targets.cend(), size_t{ 0 }, [](size_t cur, const auto& m) { return cur + !m.expired(); });
} | {
"domain": "codereview.stackexchange",
"id": 42724,
"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++, multithreading, callback, c++20",
"url": null
} |
c++, multithreading, callback, c++20
// clears all listeners
void clear() noexcept
{
auto l = std::unique_lock(_mut);
_targets.clear();
}
template <class F> requires (std::is_nothrow_invocable_r_v<void, F, Message...>)
[[nodiscard]] cookieType add_listener(F&& r_)
{
auto l = std::unique_lock(_mut);
auto listenFunc = std::make_shared<listener>(std::forward<F>(r_));
_targets.push_back(listenFunc);
return listenFunc;
}
void notify_all(const Message&... msg_) noexcept
{
auto lt = std::unique_lock(_mut);
auto ls = std::unique_lock(_sendMut);
// remove dead listeners
_targets.erase(
std::remove_if(_targets.begin(), _targets.end(),
[](const auto& ptr) { return ptr.expired(); }
),
_targets.end()
);
// take copy
auto tmp = _targets;
lt.unlock();
// 1. mutex unlocked, so new listeners can be added
// 2. sending mutex remains held so that message
// ordering is guaranteed.
// invoke all listeners with message
for (auto&& f : tmp)
{
if (auto targetPtr = f.lock(); targetPtr)
targetPtr->operator()(msg_...);
}
}
private:
mutable std::mutex _mut;
std::mutex _sendMut;
std::vector<std::weak_ptr<listener>> _targets;
};
Example usage
#include <iostream>
#include <string>
#include <functional>
void freeTestFunction(std::string msg_) noexcept
{
std::cout << "from freeTestFunction: " << msg_ << std::endl;
}
struct test
{
using StringBroadcaster = Broadcaster<std::string>; | {
"domain": "codereview.stackexchange",
"id": 42724,
"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++, multithreading, callback, c++20",
"url": null
} |
c++, multithreading, callback, c++20
void simpleCallback(std::string msg_) noexcept
{
std::cout << "from simpleCallback: " << msg_ << std::endl;
}
void oneShotCallback(std::string msg_) noexcept
{
std::cout << "from oneShotCallback: " << msg_ << std::endl;
_cb_oneShot_cookie.reset();
}
void twoStepCallback_step1(std::string msg_) noexcept
{
std::cout << "from twoStepCallback_step1: " << msg_ << std::endl;
// replace callback
_cb_twostep_cookie = _broadcast.add_listener([&](auto fr_) noexcept { twoStepCallback_step2(fr_); });
}
void twoStepCallback_step2(std::string msg_) noexcept
{
std::cout << "from twoStepCallback_step2: " << msg_ << std::endl;
}
void runExample()
{
auto cb_simple_cookie = _broadcast.add_listener([&](auto fr_) noexcept { simpleCallback(fr_); });
_cb_oneShot_cookie = _broadcast.add_listener([&](auto fr_) noexcept { oneShotCallback(fr_); });
_cb_twostep_cookie = _broadcast.add_listener([&](auto fr_) noexcept { twoStepCallback_step1(fr_); });
auto free_func_cookie = _broadcast.add_listener(&freeTestFunction);
_broadcast.notify_all("message 1"); // should be received by simpleCallback, oneShotCallback, twoStepCallback_step1, freeTestFunction
free_func_cookie.reset();
_broadcast.notify_all("message 2"); // should be received by simpleCallback and twoStepCallback_step2
cb_simple_cookie.reset();
_broadcast.notify_all("message 3"); // should be received by twoStepCallback_step2
_cb_twostep_cookie.reset();
_broadcast.notify_all("message 4"); // should be received by none
}
StringBroadcaster _broadcast;
StringBroadcaster::cookieType _cb_oneShot_cookie;
StringBroadcaster::cookieType _cb_twostep_cookie;
};
int main(int argc, char **argv)
{
test t;
t.runExample();
return 0;
} | {
"domain": "codereview.stackexchange",
"id": 42724,
"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++, multithreading, callback, c++20",
"url": null
} |
c++, multithreading, callback, c++20
int main(int argc, char **argv)
{
test t;
t.runExample();
return 0;
}
Answer: Use the right algorithms
Don't use std::accumulate() to count the number of elements that match a predicate, there is std::count_if() which is a much better match for what you are trying to do:
size_t num_listeners() const noexcept
{
auto l = std::unique_lock(_mut);
return std::count_if(_targets.cbegin(), _targets.cend(),
[](const auto& m) { return !m.expired(); });
}
Or even better, with C++20 ranges you can use:
return std::ranges::count_if(_targets, [](const auto& m) { return !m.expired(); });
The erase-remove idiom is no longer necessary in C++20 thanks to the much simpler std::erase_if:
// remove dead listeners
std::erase_if(_targets, [](const auto& ptr) { return ptr.expired(); });
Be careful when adding noexcept
It is great that you add noexcept to functions where possible. But be aware that exceptions come from a lot of places.
Theoretically, std::mutex::lock() might throw. However, this is extremely unlikely, and if it does, you probably won't be able to recover anyway. So for practical purposes, you can leave functions that take a lock noexcept. This means that if an exception is raised, the program will immediately terminate instead of unwinding the stack until the exception is caught.
Lock ordering
Never let locking of multiple mutexes have partial overlaps. In more complex situations this has a high chance of causing deadlocks. Avoid calling lock() and unlock() manually, and always use RAII lock guards. Use braces to limit the scope of a lock where necessary. For example:
void notify_all(const Message&... msg_)
{
auto ls = std::unique_lock(_sendMut);
decltype(_targets) tmp;
{
// remove dead listeners
auto lt = std::unique_lock(_mut);
std::erase_if(_targets, [](const auto& ptr) { return ptr.expired(); });
// take copy
tmp = _targets;
}
...
} | {
"domain": "codereview.stackexchange",
"id": 42724,
"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++, multithreading, callback, c++20",
"url": null
} |
c++, multithreading, callback, c++20
// take copy
tmp = _targets;
}
...
}
Cost of making copies
Making copies is a good way to avoid issues with multiple threads trying to modify _targets while you are still broadcasting a message. However, there is of course a cost. Copying a std::weak_ptr is not very cheap, because it needs to atomically increment the reference count of the control block associated with the std::shared_ptr it refers to. So with just a few listeners I think copying _targets will be more expensive than using a recursive mutex and a flag to detect listeners being added during the loop.
On the other hand, you are already calling lock() on every std::weak_ptr in tmp. That just creates a bunch of std::shared_ptrs. So you could do the lock()ing while making a copy:
void notify_all(const Message&... msg_)
{
auto ls = std::unique_lock(_sendMut);
std::vector<std::shared_ptr<listener>> tmp;
{
// remove dead listeners
auto lt = std::unique_lock(_mut);
std::erase_if(_targets, [](const auto& ptr) { return ptr.expired(); });
// take copy
for (auto& target: _targets)
tmp.push_back(target.lock());
}
for (auto& targetPtr: tmp)
if (targetPtr)
targetPtr->operator()(msg_...);
}
Alternatives
I think there is a big overhead coming from that fact that you use a std::shared_ptr for each individual listener. You could avoid that by having a std::shared_ptr for the whole vector of listeners. You could make your own RAII class that replaces the current cookieType, and which contains a std::weak_ptr to the vector of listeners, and a destructor which will erase the listener from that vector if it is still alive. | {
"domain": "codereview.stackexchange",
"id": 42724,
"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++, multithreading, callback, c++20",
"url": null
} |
c#
Title: A Custom Range Partitioner
Question: Terminology usage: I will use chunk, page, partition, or subrange interchangeably.
I frequently use and promote using the System.Collections.Concurrent.Partitioner class (see link). For my particular usage, I always use it for a full indexed collection, i.e. IList<T>. Sometimes I may use it for single-threaded processing lists with fixed range size per chunk, or I may process in parallel threads where I care more about the number of chunks rather than a specific range size.
Recently I posted an answer using Partitioner to this CR question. However, it caused me to think of ways I could enhance a partitioner customized more to my needs and preferred usage.
For starters, I wish the boring tuple property names of Item1 and Item2 had more descriptive names such as FromInclusive and ToExclusive.
For logging purposes, it would be nice sometimes to know what chunk number I am currently processing. There could be some other nice things to know such as how many total chunks there are or perhaps whether I am on the last chunk.
I almost always work with an item count, meaning the overall range is from 0 to item count – 1. But the manner in how those chunks are formed and how many chunks there will be depends upon whether I pass in a range size, or a desired chunk count. With Partitioner, if I want a specific chunk count, I must first use my desired chunk count to determine the applicable range size, which is what Partitioner is expecting.
CLASS PartitionedIndexRange
I am most interested in feedback or a review of this class.
public class PartitonedIndexRange
{
private PartitonedIndexRange(int fromInclusive, int toExclusive, int partitionIndex, int partitionsCount)
{
this.FromInclusive = fromInclusive;
this.ToExclusive = toExclusive;
this.PartitionIndex = partitionIndex;
this.PartitionsCount = partitionsCount;
} | {
"domain": "codereview.stackexchange",
"id": 42725,
"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#
public int FromInclusive { get; }
public int ToExclusive { get; } = -1;
public int PartitionIndex { get; } = -1;
public int PartitionsCount { get; }
public int LastPartitionIndex => PartitionsCount - 1;
public bool IsFirstPartition => PartitionIndex == 0;
public bool IsLastPartition => PartitionIndex == LastPartitionIndex;
public int Size => ToExclusive - FromInclusive;
public static void CheckCannotBeNegative(string name, int value)
{
if (value < 0)
{
throw new ArgumentOutOfRangeException(name, $"{name} cannot be negative.");
}
}
public static void CheckMustBePositive(string name, int value)
{
if (value <= 0)
{
throw new ArgumentOutOfRangeException(name, $"{name} must be greater than 0.");
}
}
public static void Check2CannotBeLessThan1(string name1, int value1, string name2, int value2)
{
if (value2 < value1)
{
throw new ArgumentOutOfRangeException(name2, $"{name2} cannot be less than {name1}.");
}
}
public static IEnumerable<PartitonedIndexRange> GetPartitionsByRangeSize(int itemCount, int rangeSize)
{
CheckCannotBeNegative(nameof(itemCount), itemCount);
CheckMustBePositive(nameof(rangeSize), rangeSize);
if (itemCount == 0)
{
yield break;
}
int partitionCount = GetChunkSize(itemCount, rangeSize);
foreach (var partition in GetPartitions(0, itemCount, partitionCount, rangeSize))
{
yield return partition;
}
} | {
"domain": "codereview.stackexchange",
"id": 42725,
"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#
public static IEnumerable<PartitonedIndexRange> GetPartitionsByRangeSize(int fromInclusive, int toExclusive, int rangeSize)
{
CheckCannotBeNegative(nameof(fromInclusive), fromInclusive);
Check2CannotBeLessThan1(nameof(fromInclusive), fromInclusive, nameof(toExclusive), toExclusive);
CheckMustBePositive(nameof(rangeSize), rangeSize);
if (toExclusive == fromInclusive)
{
yield break;
}
int partitionCount = GetChunkSize(toExclusive - fromInclusive, rangeSize);
foreach (var partition in GetPartitions(fromInclusive, toExclusive, partitionCount, rangeSize))
{
yield return partition;
}
}
public static IEnumerable<PartitonedIndexRange> GetPartitionsByPartitionCount(int itemCount, int partitionCount)
{
CheckCannotBeNegative(nameof(itemCount), itemCount);
CheckMustBePositive(nameof(partitionCount), partitionCount);
if (itemCount == 0)
{
yield break;
}
int rangeSize = GetChunkSize(itemCount, partitionCount);
foreach (var partition in GetPartitions(0, itemCount, partitionCount, rangeSize))
{
yield return partition;
}
}
public static IEnumerable<PartitonedIndexRange> GetPartitionsByPartitionCount(int fromInclusive, int toExclusive, int partitionCount)
{
CheckCannotBeNegative(nameof(fromInclusive), fromInclusive);
Check2CannotBeLessThan1(nameof(fromInclusive), fromInclusive, nameof(toExclusive), toExclusive);
CheckMustBePositive(nameof(partitionCount), partitionCount);
if (toExclusive == fromInclusive)
{
yield break;
}
int rangeSize = GetChunkSize(toExclusive - fromInclusive, partitionCount);
foreach (var partition in GetPartitions(fromInclusive, toExclusive, partitionCount, rangeSize))
{
yield return partition;
}
} | {
"domain": "codereview.stackexchange",
"id": 42725,
"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#
private static IEnumerable<PartitonedIndexRange> GetPartitions(int fromInclusive, int toExclusive, int partitionCount, int rangeSize)
{
int inclusiveStart = fromInclusive;
for (int partitionIndex = 0; partitionIndex < partitionCount; partitionIndex++)
{
bool isLast = (partitionIndex + 1) == partitionCount;
int exclusiveEnd = isLast ? toExclusive : inclusiveStart + rangeSize;
var partition = new PartitonedIndexRange(inclusiveStart, exclusiveEnd, partitionIndex, partitionCount);
yield return partition;
inclusiveStart = exclusiveEnd;
}
}
private static int GetChunkSize(int itemCount, int inputSize)
{
// <quote>Context means everything.</quote>
// If inputSize is a Range Size, then outputSize is the Partition Count
// If inputSize is a Partition Count, then outputSize is the Range Size
int outputSize = itemCount / inputSize;
return (itemCount % inputSize == 0) ? outputSize : 1 + outputSize;
}
public override string ToString()
{
return $"Partition[{PartitionIndex}] Range [{FromInclusive} - {ToExclusive}) Size {Size}";
}
}
I intentionally made the constructor private restricting usage to the static create methods: GetPartitionsByRangeSize and GetPartitionsByPartitionCount.
STATIC CLASS UsageExample
Note I am not interested in any feedback or review on the UsageExample class.
internal static class UsageExample
{
private static Random _random { get; } = new Random();
public static void RunSimple()
{
// Simple example does not need an actual collection.
// All we really need is to know the size of a collection.
Console.WriteLine();
Console.WriteLine("SIMPLE EXAMPLE using itemCount");
var itemCount = _random.Next(60_000, 200_000); | {
"domain": "codereview.stackexchange",
"id": 42725,
"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#
var rangeSize = 12_500;
var partitionsByRangeSize = PartitonedIndexRange.GetPartitionsByRangeSize(itemCount, rangeSize);
Console.WriteLine();
Console.WriteLine($"BY RANGE SIZE. ItemCount={itemCount} RangeSize={rangeSize}");
foreach (var partition in partitionsByRangeSize)
{
Console.WriteLine(partition);
}
var partitionCount = 9;
var partitionsByPartitionCount = PartitonedIndexRange.GetPartitionsByPartitionCount(itemCount, partitionCount);
Console.WriteLine();
Console.WriteLine($"BY PARTITION COUNT. ItemCount={itemCount} PartitionCount={partitionCount}");
foreach (var partition in partitionsByPartitionCount)
{
Console.WriteLine(partition);
}
}
public static void RunSimple2()
{
Console.WriteLine();
Console.WriteLine("SIMPLE EXAMPLE using toInclusive & fromExclusive");
var fromInclusive = 1_000;
var toExclusive = 12_500;
var rangeSize = 1_000;
var partitionsByRangeSize = PartitonedIndexRange.GetPartitionsByRangeSize(fromInclusive, toExclusive, rangeSize);
Console.WriteLine();
Console.WriteLine($"BY RANGE SIZE. FromInclusive={fromInclusive} ToExclusive={toExclusive} RangeSize={rangeSize}");
foreach (var partition in partitionsByRangeSize)
{
Console.WriteLine(partition);
}
var partitionCount = 10;
var partitionsByPartitionCount = PartitonedIndexRange.GetPartitionsByPartitionCount(fromInclusive, toExclusive, partitionCount);
Console.WriteLine();
Console.WriteLine($"BY PARTITION COUNT. FromInclusive={fromInclusive} ToExclusive={toExclusive} PartitionCount={partitionCount}");
foreach (var partition in partitionsByPartitionCount)
{
Console.WriteLine(partition);
}
} | {
"domain": "codereview.stackexchange",
"id": 42725,
"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#
public static void RunParallel()
{
Console.WriteLine();
Console.WriteLine("PARALLEL EXAMPLE");
var arraySize = _random.Next(88_888, 111_111);
var maxDegreeOfParallelism = Environment.ProcessorCount + 1;
var example = SumArray.Create(arraySize, maxDegreeOfParallelism);
Console.WriteLine();
Console.WriteLine($"Running multi-threaded for ArraySize={arraySize} MaxDegreeOfParallelism={maxDegreeOfParallelism}");
Console.WriteLine("Custom partitioner with guaranteed order will be called.");
Console.WriteLine("Parallel.ForEach order is NOT guaranteed.");
var elapsed = example.RunMultiThreaded();
Console.WriteLine($" Elapsed = {elapsed}");
}
private class SumArray
{
// Modified my answer from this original Code Review post:
// https://codereview.stackexchange.com/questions/270338/sum-of-2-arrays-using-multi-threading/270355#270355
public int[] ArrayA { get; private set; } = new int[0];
public int[] ArrayB { get; private set; } = new int[0];
public int[] ArrayC { get; private set; } = new int[0];
public int MaxDegreeOfParallelism { get; private set; } = 1;
public int ArraySize { get; private set; } = 0;
private SumArray(int size, int maxDegreeOfParallelism)
{
// There are probably more checks that could be done but here are the minimum.
if (size <= 0)
{
throw new ArgumentOutOfRangeException(nameof(size), "Array size must be greater than 0");
}
if (maxDegreeOfParallelism <= 0)
{
throw new ArgumentOutOfRangeException(nameof(maxDegreeOfParallelism), "MaxDegreeOfParallelism must be greater than 0");
} | {
"domain": "codereview.stackexchange",
"id": 42725,
"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#
// While I could call Initialize() here, my philosophy is that a constructor
// should do the BARE MINIMUM, which is only to set some properties and
// then return as quickly as possible.
// To that end, I mark the constructor as private, and require accessing
// it via the public Create().
this.ArraySize = size;
this.MaxDegreeOfParallelism = maxDegreeOfParallelism;
}
public static SumArray Create(int size, int maxDegreeOfParallelism)
{
var instance = new SumArray(size, maxDegreeOfParallelism);
// Initialize is intentionally run after construction.
instance.Initialize();
return instance;
}
private void Initialize()
{
ArrayA = new int[ArraySize];
ArrayB = new int[ArraySize];
ArrayC = new int[ArraySize];
// Magic number replacements.
// https://en.wikipedia.org/wiki/Magic_number_(programming)
// Consider increasing with bigger arrays.
// Consider making parameters or properties rather than constants.
const int minA = 1;
const int maxA = 9999;
const int minB = 100_000;
const int maxB = 900_000;
for (int i = 0; i < ArraySize; i++)
{
// Consider increasing the magic num
ArrayA[i] = _random.Next(minA, maxA);
ArrayB[i] = _random.Next(minB, maxB);
}
}
public TimeSpan RunSingleThreaded()
{
var watch = Stopwatch.StartNew();
for (int i = 0; i < ArraySize; i++)
{
ArrayC[i] = ArrayA[i] + ArrayB[i];
}
watch.Stop();
return watch.Elapsed;
}
public TimeSpan RunMultiThreaded()
{
var watch = Stopwatch.StartNew(); | {
"domain": "codereview.stackexchange",
"id": 42725,
"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#
public TimeSpan RunMultiThreaded()
{
var watch = Stopwatch.StartNew();
var options = new ParallelOptions() { MaxDegreeOfParallelism = MaxDegreeOfParallelism };
// CUSTOM PARTITIONER CALL HERE
var partitions = PartitonedIndexRange.GetPartitionsByPartitionCount(ArraySize, MaxDegreeOfParallelism);
// While the partitioner sends the partitions in order,
// the task scheduler is not guaranteed to process them in the same order.
Parallel.ForEach(partitions, options, partition =>
{
LockedWriteLine($" START {partition}");
for (var i = partition.FromInclusive; i < partition.ToExclusive; i++)
{
ArrayC[i] = ArrayA[i] + ArrayB[i];
}
LockedWriteLine($" END Partition[{partition.PartitionIndex}]");
});
watch.Stop();
return watch.Elapsed;
}
private object _lockObject = new object();
private void LockedWriteLine(string text)
{
// I know Console.WriteLine is supposed to be thread safe,
// but I am being extra cautious here to remove any doubt.
lock (_lockObject)
{
Console.WriteLine(text);
}
}
}
}
This requires using System.Diagnostics ; for the Stopwatch. There is a subclass named SumArray, which is a modified example of the answer I provided to this POST. The RunMultiThreaded method uses the custom partitioner. I included some Console.WriteLine to illustrate when a thread starts and ends, which can produce some very interesting results regarding ordering.
SAMPLE CONSOLE OUTPUT
SIMPLE EXAMPLE | {
"domain": "codereview.stackexchange",
"id": 42725,
"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#
BY RANGE SIZE. ItemCount=77032 RangeSize=12500
Partition[0] Range [0 - 12500) Size 12500
Partition[1] Range [12500 - 25000) Size 12500
Partition[2] Range [25000 - 37500) Size 12500
Partition[3] Range [37500 - 50000) Size 12500
Partition[4] Range [50000 - 62500) Size 12500
Partition[5] Range [62500 - 75000) Size 12500
Partition[6] Range [75000 - 77032) Size 2032
BY PARTITION COUNT. Item Count=77032 PartitionCount=9
Partition[0] Range [0 - 8560) Size 8560
Partition[1] Range [8560 - 17120) Size 8560
Partition[2] Range [17120 - 25680) Size 8560
Partition[3] Range [25680 - 34240) Size 8560
Partition[4] Range [34240 - 42800) Size 8560
Partition[5] Range [42800 - 51360) Size 8560
Partition[6] Range [51360 - 59920) Size 8560
Partition[7] Range [59920 - 68480) Size 8560
Partition[8] Range [68480 - 77032) Size 8552
PARALLEL EXAMPLE
Running multi-threaded for ArraySize=103493 MaxDegreeOfParallelism=7
Custom partitioner with guaranteed order will be called.
Parallel.ForEach order is NOT guaranteed.
START Partition[0] Range [0 - 14785) Size 14785
END Partition[0]
START Partition[1] Range [14785 - 29570) Size 14785
START Partition[4] Range [59140 - 73925) Size 14785
END Partition[4]
START Partition[2] Range [29570 - 44355) Size 14785
END Partition[1]
START Partition[6] Range [88710 - 103493) Size 14783
END Partition[6]
START Partition[3] Range [44355 - 59140) Size 14785
END Partition[3]
START Partition[5] Range [73925 - 88710) Size 14785
END Partition[5]
END Partition[2]
Elapsed = 00:00:00.0364611 | {
"domain": "codereview.stackexchange",
"id": 42725,
"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#
Simple Observations: notice the size of the last partition in the Simple example, chunking by Partition Count produces more balanced chunks than by Range Size.
Parallel Observations: although the custom partitioner creates the partitions in a very ordered, sequential manner, the Parallel.ForEach does not guarantee the order of processing. Note that # 2 starts after # 4 but before # 6, 3 and 5, and that # 2 also is the last to complete. Note as well that # 0 started and ended before the others began.
Granted that’s just from one sample run. I encourage you to run it several times since the results change. Here is output from another run.
SIMPLE EXAMPLE
BY RANGE SIZE. ItemCount=130810 RangeSize=12500
Partition[0] Range [0 - 12500) Size 12500
Partition[1] Range [12500 - 25000) Size 12500
Partition[2] Range [25000 - 37500) Size 12500
Partition[3] Range [37500 - 50000) Size 12500
Partition[4] Range [50000 - 62500) Size 12500
Partition[5] Range [62500 - 75000) Size 12500
Partition[6] Range [75000 - 87500) Size 12500
Partition[7] Range [87500 - 100000) Size 12500
Partition[8] Range [100000 - 112500) Size 12500
Partition[9] Range [112500 - 125000) Size 12500
Partition[10] Range [125000 - 130810) Size 5810
BY PARTITION COUNT. ItemCount=130810 PartitionCount=9
Partition[0] Range [0 - 14535) Size 14535
Partition[1] Range [14535 - 29070) Size 14535
Partition[2] Range [29070 - 43605) Size 14535
Partition[3] Range [43605 - 58140) Size 14535
Partition[4] Range [58140 - 72675) Size 14535
Partition[5] Range [72675 - 87210) Size 14535
Partition[6] Range [87210 - 101745) Size 14535
Partition[7] Range [101745 - 116280) Size 14535
Partition[8] Range [116280 - 130810) Size 14530
PARALLEL EXAMPLE | {
"domain": "codereview.stackexchange",
"id": 42725,
"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#
PARALLEL EXAMPLE
Running multi-threaded for ArraySize=98424 MaxDegreeOfParallelism=7
Custom partitioner with guaranteed order will be called.
Parallel.ForEach order is NOT guaranteed.
START Partition[1] Range [14061 - 28122) Size 14061
START Partition[0] Range [0 - 14061) Size 14061
START Partition[3] Range [42183 - 56244) Size 14061
END Partition[1]
START Partition[2] Range [28122 - 42183) Size 14061
END Partition[3]
START Partition[4] Range [56244 - 70305) Size 14061
END Partition[0]
START Partition[6] Range [84366 - 98424) Size 14058
END Partition[2]
END Partition[4]
END Partition[6]
START Partition[5] Range [70305 - 84366) Size 14061
END Partition[5]
Elapsed = 00:00:00.0644807
Here is another example of parallel usage where the last partition starts before the first one!
PARALLEL EXAMPLE
Running multi-threaded for ArraySize=93916 MaxDegreeOfParallelism=7
Custom partitioner with guaranteed order will be called.
Parallel.ForEach order is NOT guaranteed.
START Partition[1] Range [13417 - 26834) Size 13417
START Partition[6] Range [80502 - 93916) Size 13414
START Partition[3] Range [40251 - 53668) Size 13417
START Partition[2] Range [26834 - 40251) Size 13417
START Partition[5] Range [67085 - 80502) Size 13417
START Partition[4] Range [53668 - 67085) Size 13417
START Partition[0] Range [0 - 13417) Size 13417
END Partition[1]
END Partition[6]
END Partition[3]
END Partition[2]
END Partition[5]
END Partition[0]
END Partition[4]
Elapsed = 00:00:00.0346445 | {
"domain": "codereview.stackexchange",
"id": 42725,
"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#
CONCERNS
While I like UsageExample as a nice way of demonstrating the unpredictable order of parallel tasks, I have little concern about a review of its code. My primary concern is a review of the PartitionedIndexRange class. So far, I like it enough to have it find a welcome on my developer’s toolkit. Having meta data about the partition is nice from a logging perspective in my many applications, most of which are Console apps running unattended via Windows Task Scheduler.
I chose to use longer descriptive names for the meta data to clarify the context of the indices. There are the pair of FromInclusive and ToExclusive, which do not contain the word “Index” and save for the capitalization match the old partitioner names. For the meta properties, I could have gone with “Id” or “Index” but chose the longer “PartitionIndex” to be clear. Ditto for “PartitionCount” instead of “Count”. | {
"domain": "codereview.stackexchange",
"id": 42725,
"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#
Answer: I think your approach is simple and straight forward. The overall naming convention is good. Many parts of the class have descriptive naming, and that makes things much easier to understand the class.
The validations methods such as CheckCannotBeNegative, CheckMustBePositive ..etc. since the actual purpose is to test a value against condition and throw an exception if true, it would be more sensible to include Throw in the method's name, such as ThrowIfNegative as it would tell what to expect from this method. CheckMustBePositive can be also ThrowIfZeroOrNegative.
for the actual methods GetPartitionsByRangeSize and GetPartitionsByPartitionCount they have similar logic, the only difference I see are three values fromInclusive , partitionCount and rangeSize.
So basically, you have two strategies, one using a starting and ending indexes, and the second would be to use a chunk size (which is the ItemCount). So, instead of replicating 4 methods, we can do one private method, and recall it with the arguments needed from the public methods instead. This would mean extending GetChunkSize with a way to calculate the partitionCount and rangeSize based on the passed arguments that we did in the public methods.
My theory is to reduce code redundancy and add more maintainability and readibility, which would results with something like this :
public static IEnumerable<PartitonedIndexRange> GetPartitionsByPartitionCount(int itemCount, int partitionCount)
{
return GetPartitionsByPartitionCount(0, itemCount, partitionCount);
}
public static IEnumerable<PartitonedIndexRange> GetPartitionsByPartitionCount(int fromInclusive, int toExclusive, int partitionCount)
{
return InternalCreatePartitions(fromInclusive, toExclusive, partitionCount, 0);
}
public static IEnumerable<PartitonedIndexRange> GetPartitionsByRangeSize(int itemCount, int rangeSize)
{
return GetPartitionsByRangeSize(0, itemCount, rangeSize);
} | {
"domain": "codereview.stackexchange",
"id": 42725,
"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#
public static IEnumerable<PartitonedIndexRange> GetPartitionsByRangeSize(int fromInclusive, int toExclusive, int rangeSize)
{
return InternalCreatePartitions(fromInclusive, toExclusive, 0, rangeSize);
}
private static IEnumerable<PartitonedIndexRange> InternalCreatePartitions(int fromInclusive, int toExclusive, int partitionCount, int rangeSize)
{
// here we will put the combined logic of the GetPartitionsByRangeSize && GetPartitionsByPartitionCount
}
if you see that we passes 0 to some arguments, as a way to determine which part of the arguments should be calculated (or ignored) internally. For instance, if we pass a zero to rangeSize then it means we need to calculate the chunk size based on the partitionCount, thus, we will have the rangeSize calculated. While if we pass zero to the fromInclusive this would give us the ItemCount since itemCount = toExclusive.
based on that, the GetChunkSize would be extended to something like this :
private static (int PartitionCount, int RangeSize) InternalGetCalculatedChunkSize(int fromInclusive, int toExclusive, int partitionCount, int rangeSize)
{
int calculatedRangeSize = rangeSize;
int calculatedPartitionSize = partitionCount;
// if it's a Partition Count then the fromInclusive would be zero.
int itemCount = toExclusive - fromInclusive;
// since we passes a zero to one of the operhands (partitionCount OR rangeSize)
// this shall determines which non-zero part should be used as input size
int inputSize = Math.Max(calculatedPartitionSize, calculatedRangeSize);
int outputSize = itemCount / (inputSize == 0 ? 1 : inputSize); // extra insurance to prevent from DivideByZeroException
int chunkSize = (itemCount % inputSize == 0) ? outputSize : 1 + outputSize;
if (partitionCount == 0)
{
calculatedPartitionSize = chunkSize;
}
else
{
calculatedRangeSize = chunkSize;
} | {
"domain": "codereview.stackexchange",
"id": 42725,
"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#
// if for some reason the calculation resulted a zero or negative
ThrowIfZeroOrNegative(nameof(calculatedPartitionSize), calculatedPartitionSize);
ThrowIfZeroOrNegative(nameof(calculatedRangeSize), calculatedRangeSize);
return (PartitionCount: calculatedPartitionSize, RangeSize: calculatedRangeSize);
}
Now, we can do this :
private static IEnumerable<PartitonedIndexRangev2> InternalCreatePartitions(int fromInclusive, int toExclusive, int partitionCount, int rangeSize)
{
ThrowIfNegative(nameof(fromInclusive), fromInclusive);
ThrowIfNegative(nameof(toExclusive), toExclusive);
ThrowIfNegative(nameof(partitionCount), partitionCount);
ThrowIfNegative(nameof(rangeSize), rangeSize);
if (toExclusive < fromInclusive)
{
throw new ArgumentOutOfRangeException(nameof(toExclusive), $"{nameof(toExclusive)} cannot be less than {nameof(fromInclusive)}.");
}
// (fromInclusive + toExclusive) == 0 is equivalent to ItemCount == 0 since we passes a zero to fromInclusive.
if (fromInclusive == toExclusive || (fromInclusive + toExclusive) == 0)
{
yield break;
}
var chunkSize = InternalGetCalculatedChunkSize(fromInclusive, toExclusive, partitionCount, rangeSize);
foreach (var partition in InternalGetPartitionsIterator(fromInclusive, toExclusive, chunkSize.PartitionCount, chunkSize.RangeSize))
{
yield return partition;
}
}
private static IEnumerable<PartitonedIndexRange> InternalGetPartitionsIterator(int fromInclusive, int toExclusive, int partitionCount, int rangeSize)
{
int inclusiveStart = fromInclusive;
for (int partitionIndex = 0; partitionIndex < partitionCount; partitionIndex++)
{
bool isLast = (partitionIndex + 1) == partitionCount;
int exclusiveEnd = isLast ? toExclusive : inclusiveStart + rangeSize;
var partition = new PartitonedIndexRange(inclusiveStart, exclusiveEnd, partitionIndex, partitionCount); | {
"domain": "codereview.stackexchange",
"id": 42725,
"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#
yield return partition;
inclusiveStart = exclusiveEnd;
}
}
With that, the initial theory should work as expected.
The last thing to add, is using uint instead of int if possible. This would reduce the need of checking for negative integers. | {
"domain": "codereview.stackexchange",
"id": 42725,
"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
} |
beginner, c
Title: Can you criticise my Snake Game in C?
Question: This is my first year at university, and I'm trying to learn everything about fundamentals. I've coded a snake game recently in C.
This is a programming-challenge that I've given to myself to practice arrays and pointers. I don't need a solution to my code because it works the way I want. I create a snake and its body grows the more I eat the food.
The thing is, I want to improve how I code, as I feel like at some point it becomes a mess. I've tried to write my algorithm and what I plan to code on paper first.
My algorithm works this way: I create a snake head, then it moves with my input, and if body comes along the head, they follow each other. There are two arrays so that I can hold the coordinates and the "values on the board": 2 means a snake, 0 means an empty space, 1 means border and so on.
Also I don't know any framework yet and studying only C feels like I'm lacking. Is that a problem?
I feel like I've repeated myself sometimes and couldn't write the best way possible, so how can I write this code better?
Or are there any bugs I can't see or anything I can do better?
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <conio.h>
#include <unistd.h>
int row_f=0,column_f=0;// food variables
int board[25][64];
int snake[150][2];
int movement=0;
int body_count=0;
void follow(int body_count);
void create_snake(int *rowPtr,int *colPtr,int x,int movement,int body_count);
void print_board();
void create_food(int *rowPtr,int *colPtr,int x);
void pointerset(int *rowPtr,int *colPtr);
int main()
{
srand(time(NULL));
char direction;
//----------------Creating board--------------
for(int i=0;i<25;i++){
for(int a=0;a<64;a++){
if(i == 0 || i == 24){
board[i][a]=1;
}else if(a == 0 || a==63){
board[i][a]=1;
}else{
board[i][a]=0;
}
}
}
//----------------Creating board-------------- | {
"domain": "codereview.stackexchange",
"id": 42726,
"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, c",
"url": null
} |
beginner, c
create_food(&row_f,&column_f,3);
create_snake(&snake[0][0],&snake[0][1],2,movement,body_count);
print_board();
control(direction,&snake[0][0],&snake[0][1]);
}
void control(char wasd_2486,int *rowPtr,int *colPtr){
int food_eaten =0;
while(!kbhit()){
print_board();
if(movement == 2){
if(board[*rowPtr+1][*colPtr]==3){
food_eaten=1;
create_food(&row_f,&column_f,3);
body_count++;
create_snake(snake[body_count][0],snake[body_count][1],2,movement,body_count);
}
follow(body_count);
*rowPtr = *rowPtr+1;
board[*rowPtr][*colPtr]=2;
control(wasd_2486,rowPtr,colPtr);
}else if(movement == 4){
if(board[*rowPtr][*colPtr-1]==3){
food_eaten=1;
create_food(&row_f,&column_f,3);
body_count++;
create_snake(snake[body_count][0],snake[body_count][1],2,movement,body_count);
}
follow(body_count);
*colPtr = *colPtr-1;
board[*rowPtr][*colPtr]=2;
control(wasd_2486,rowPtr,colPtr);
}else if(movement == 8){
if(board[*rowPtr-1][*colPtr]==3){
food_eaten=1;
create_food(&row_f,&column_f,3);
body_count++;
create_snake(snake[body_count][0],snake[body_count][1],2,movement,body_count);
}
follow(body_count);
*rowPtr = *rowPtr-1;
board[*rowPtr][*colPtr]=2;
control(wasd_2486,rowPtr,colPtr);
}else if(movement == 6){ | {
"domain": "codereview.stackexchange",
"id": 42726,
"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, c",
"url": null
} |
beginner, c
control(wasd_2486,rowPtr,colPtr);
}else if(movement == 6){
if(board[*rowPtr][*colPtr+1]==3){
food_eaten=1;
create_food(&row_f,&column_f,3);
body_count++;
create_snake(snake[body_count][0],snake[body_count][1],2,movement,body_count);
}
follow(body_count);
*colPtr = *colPtr+1;
board[*rowPtr][*colPtr]=2;
control(wasd_2486,rowPtr,colPtr);
}
control(wasd_2486,rowPtr,colPtr);
while(kbhit()){
print_board();
wasd_2486=getch();
if(wasd_2486 == '4' || wasd_2486 == 'a'){
if(movement == 0 || movement != 6){
movement=4;
}
}else if(wasd_2486 == '6' || wasd_2486 == 'd'){
if(movement == 0 || movement != 4){
movement =6;
}
}else if(wasd_2486 == '2' || wasd_2486 == 's'){
if(movement == 0 || movement != 8){
movement =2;
}
}else if(wasd_2486 == '8' || wasd_2486 == 'w'){
if(movement == 0||movement !=2){
movement=8;
}
}
control(wasd_2486,rowPtr,colPtr);
}
}
}
void follow(int body_count){
if(body_count == 0){
board[snake[body_count][0]][snake[body_count][1]]=0;
}else{
for(int i=body_count;i>0;i--){
board[snake[body_count][0]][snake[body_count][1]]=0;
snake[i][0]=snake[i-1][0];
snake[i][1]=snake[i-1][1];
}
}
}
void create_snake(int *rowPtr,int *colPtr,int x,int movement,int body_count){
if(movement == 0){
pointerset(rowPtr,colPtr); | {
"domain": "codereview.stackexchange",
"id": 42726,
"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, c",
"url": null
} |
beginner, c
}else if(movement == 2){
snake[body_count][0]= snake[body_count-1][0]-1;
snake[body_count][1]= snake[body_count-1][1];
board[snake[body_count][0]][snake[body_count][1]]=2;
}else if(movement == 4){
snake[body_count][0]= snake[body_count-1][0];
snake[body_count][1]= snake[body_count-1][1]+1;
board[snake[body_count][0]][snake[body_count][1]]=2;
}else if(movement == 6){
snake[body_count][0]= snake[body_count-1][0];
snake[body_count][1]= snake[body_count-1][1]-1;
board[snake[body_count][0]][snake[body_count][1]]=2;
}else if(movement == 8){
snake[body_count][0]= snake[body_count-1][0]-1;
snake[body_count][1]= snake[body_count-1][1];
board[snake[body_count][0]][snake[body_count][1]]=2;
}
}
void create_food(int *rowPtr,int *colPtr,int x){
pointerset(rowPtr,colPtr);
if(board[*rowPtr][*colPtr]==1){
create_food(rowPtr,colPtr,x);
}else if(board[*rowPtr][*colPtr]==0){
board[*rowPtr][*colPtr]=x;
}else{
create_food(rowPtr,colPtr,x);
}
}
void pointerset(int *rowPtr,int *colPtr){
*rowPtr=rand()%25;
*colPtr=rand()%64;
}
void print_board(){
system("CLS");
for(int i=0;i<25;i++){
for(int a=0;a<64;a++){
if(board[i][a]==1){
printf("+");
}else if(board[i][a]==0){
printf(" ");
}else if(board[i][a]==2){
printf("o");
}else if(board[i][a]==3){
printf("*");
}
}
printf("\n");
}
printf("\n");printf("\n");printf("\n");printf("\n");
}
Answer: Overall
Aside from the atrocious format, very nice code for a learner.
Use an auto-formatter!
Avoid manual formatting, yet always run an auto-formatter before code review.
Ding, Ding, Ding!!!
No warnings, even with many enabled. Yeah!
Bug: direction never assigned before use.
char direction;
...
control(direction,&snake[0][0],&snake[0][1]); | {
"domain": "codereview.stackexchange",
"id": 42726,
"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, c",
"url": null
} |
beginner, c
Avoid naked magic numbers
//int board[25][64];
//for (int i = 0; i < 25; i++) {
// for (int a = 0; a < 64; a++) {
#define BOARD_ROWS 25
#define BOARD_COLS 64
int board[BOARD_ROWS][BOARD_COLS];
for (int i = 0; i < BOARD_ROWS; i++) {
for (int a = 0; a < BOARD_COLS; a++) {
// if(i == 0 || i == 24){
if(i == 0 || i == BOARD_ROWS - 1){
And many many other constants too.
Short on comments
I recommend at least a comment/function definition and some overall program comment. Your algorithm belongs in the top of code as a comment.
Alternative to calling rand() twice
// *rowPtr = rand() % 25;
// *colPtr = rand() % 64;
int r = rand() % (BOARD_ROWS * BOARD_COLS);
*rowPtr = r / BOARD_COLS;
*colPtr = r % BOARD_COLS;
Alternative printing
As board[i][a] should be only [0...3]
//if(board[i][a]==1){
// printf("+");
//}else if(board[i][a]==0){
// printf(" ");
//}else if(board[i][a]==2){
// printf("o");
//}else if(board[i][a]==3){
// printf("*");
// Table look up - in this case a string look up.
putchar(" +o*"[board[i][a] & 3]);
Initialize function
Consider putting Creating board code in its own function rather than main(). Better if initialization does not rely on global variable initial values and assigns them here.
Collapse repetitive code
// printf("\n");printf("\n");printf("\n");printf("\n");
printf("\n\n\n\n"); // or the like
Advanced: Global variables
As you advance, consider a struct to hold all the global data together and then pass around a pointer to that struct.
Minor: Incomplete prototype
Declaration void print_board(); still allows calls like print_board(42);. Use (void).
// void print_board();
void print_board(void);
C2x may change this and have void print_board(); same as void print_board(void);
Minor: Avoid type change warnings.
// srand(time(NULL));
srand((unsigned) time(NULL));
What is wasd_2486?
Comment or use a better name. | {
"domain": "codereview.stackexchange",
"id": 42726,
"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, c",
"url": null
} |
python, beginner, iterator
Title: Zipping two lists with an offset in Python
Question: Walking my first steps in Python from C, I find myself missing pointers from time to time.
In this case I want to go through a list processing two element at a time, where those elements are step places away. This is my initial approach, but I would be happy to learn a couple alternatives, and their advantages.
v = [0,1,2,3,4,5,6,7,8,9]
step = 3
for x, y in zip( v[:-step], v[step:] ) :
print("\nx={}, y={}".format(x, y))
I'm interested in what can be done with naked Python alone first. But alternatives from a module, are welcome as well. I want to know which approach is closer to pointer use in C (which was my intent with the code above) in terms of efficiency.
Answer: You're on the right track, but it can be simplified to the following.
Note also that the step variable name could add confusion because Python ranges and slices
have a step attribute -- but it's not what you are doing:
start = 3
for x, y in zip(v, v[start:]):
...
Also note that syntax like v[start:] creates a new list. If you are
dealing with large data volumes and want to avoid that, you can use
itertools.islice.
from itertools import islice
v = [0,1,2,3,4,5,6,7,8,9]
start = 3
for x, y in zip(v, islice(v, start, None)):
print(x, y) | {
"domain": "codereview.stackexchange",
"id": 42727,
"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, beginner, iterator",
"url": null
} |
java, json
Title: Remove elements from JSON
Question: This function removes a JSON element from a JSON file. In may case, the ID element. I am able to get the desired result. But the code looks very verbose; can it be written in a better way without hindering the performance?
The path for removal is provided from the root node:
/glossary/GlossDiv/GlossList/GlossEntry/ID
{
"glossary": {
"title": "example glossary",
"GlossDiv": {
"title": "S",
"GlossList": {
"GlossEntry": {
"ID": "SGML",
"SortAs": "SGML",
"GlossTerm": "Standard Generalized Markup Language",
"Acronym": "SGML",
"Abbrev": "ISO 8879:1986",
"GlossDef": {
"para": "A meta-markup language, used to create markup languages such as DocBook.",
"GlossSeeAlso": ["GML", "XML"]
},
"GlossSee": "markup"
}
}
}
}
}
The code to remove the element follows. As one can observe, it has two for loops and we are traversing to the parent of the element which needs to be removed and then removing the element. Is there a better way of writing the code?
public static JsonNode removeProperty(JsonNode node, List<String> removedField){
JsonNode modifiedNode = node;
for (String nodeToBeRemoved: removedField){
String[] array = nodeToBeRemoved.split("/");
for (int i =1;i<array.length-1;i++){
String name=array[i];
modifiedNode = modifiedNode.get(name);
}
((ObjectNode)modifiedNode).remove(array[array.length-1]);
}
return node;
} | {
"domain": "codereview.stackexchange",
"id": 42728,
"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": "java, json",
"url": null
} |
java, json
return node;
}
Answer: One thing I would suggest is to split this into a few functions with descriptive names and smaller scopes. First, since we can remove several fields with this function, I think it would be more clearly named removeProperties. (Also, is there a reason that the function name uses "property" and the parameter name uses "field"? It seems to me you could pick one or the other.)
If you split this into single responsibility functions, you get:
public static JsonNode removeProperties(JsonNode node, List<String> removedField){
JsonNode modifiedNode = node;
for (String nodeToBeRemoved: removedField){
modifiedNode = removeProperty(modifiedNode, nodeToBeRemoved);
}
return node;
}
A second observation is that it looks like ObjectNode.remove mutates the node. If that's correct, then why bother returning the modified node? Since it's changed in place, you could make this a void function. Or, if the intent is to avoid mutating the provided node, then you'd need to clone it before starting to operate on it. Even if you clone it, remove still changes the node in place, so there's no need for the inner function to return modifiedNode.
I suggest you include JavaDocs specifying whether this function will change the input node or not.
Thirdly, I suggest some renaming here:
String[] array = nodeToBeRemoved.split("/");
To me, this would me more clear as follows, since it makes sense to split a path but I don't know what it means to split a node. We already have a node in context, and its type is JsonNode. If we also call this string a node, then we have two things called "node" which have different types.
String[] pathParts = pathToBeRemoved.split("/");
On the topic of names, I think it would be helpful to extract a variable for the last element:
String keyToRemove = pathParts[pathParts.length - 1];
That way the remove line becomes more clear:
((ObjectNode) nodeToModify).remove(keyToRemove); | {
"domain": "codereview.stackexchange",
"id": 42728,
"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": "java, json",
"url": null
} |
javascript
Title: Filter an object array based on certain conditions
Question: How can I rewrite this in a cleaner way?
I have this function that takes a list of contacts of different types (are being called relationships.
If there are contacts of type A the list should be filtered to only include contacts of type A, otherwise, it should only include contacts of type B.
const getContactNames = () => {
let filteredContacts = contacts.filter(c => c.relationship === 'A')
if (!filteredContacts.length) {
filteredContacts = contacts.filter(
c => c.relationship === 'B'
)
}
return filteredContacts.map(contact => getContactName(contact))
}
The getContactName function:
const getContactName = contact =>
`${contact?.title || ''} ${contact?.firstName || ''} ${
contact?.lastName || ''
}`.trim()
contact object:
const contact = {title:"Mr", firstName:"test", lastName: "test", relationship: "B", address: "test", city:"NY", state:"NY"}
How can I rewrite the getContactNames function in a cleaner way?
Answer:
rewrite this in a cleaner way?
The contact object does all the work for itself: initializing properties, formatting name output. If some client code is doing something to an object's properties then it probably should be a method/function in that object.
function contact(fromJSON) {
title: fromJSON.title || "",
firstName: fromJSON.firstName || "",
lastName: fromJSON.lastName || "",
contactName: function() {
return `${ this.title } ${ this.firstName } ${ this.lastName }`.trim()
}
}
New contact objects are initialized with blank string. The chaining operator is not needed as there are no nested objects in contact | {
"domain": "codereview.stackexchange",
"id": 42729,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript",
"url": null
} |
javascript
Filtering for "A else B" types. The point is avoiding nesting when practical which naturally makes reading and understanding easier.
Yes, filtering for "B"s may sometimes be unnecessary but I don't care. I love how clean, simple, and clear the code feels. If performance might be an issue, well, that's what testing is for.
// if there are no type "A" contacts, give me type "B"s
const getContacts = () => {
let ContactsA = contacts.filter( c => c.relationship === 'A' )
let ContactsB = contacts.filter( c => c.relationship === 'B' )
return ContactsA.length ? ContactsA : ContactsB
}
Client code
const contacts = // array of contacts from JSON object
const AorBcontacts = getContacts()
AorBcontacts.forEach( x => console.log( x.contactName() )) | {
"domain": "codereview.stackexchange",
"id": 42729,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript",
"url": null
} |
php, mvc, laravel
Title: Laravel model and controller interaction
Question: I want to know if I'm going about creating and calling two functions from my model to my controller in the simplest and cleanest way.
Model:
public function getPosts()
{
$post = $this->paginate(4);
return $post;
}
public function getMonth($post)
{
$post->month = date('M', strtotime($this->created_at));
$post->month = strtoupper($post->month);
return $post->month;
}
public function getDay($post)
{
$post->day = date('d', strtotime($this->created_at));
return $post->day;
}
Controller:
public function index()
{
$post = $this->post->getPosts();
$post->month = $this->post->getMonth($post);
$post->day = $this->post->getDay($post);
return View::make('posts.index', compact('post'));
}
I am unsure about if my controller is acting in a strict MVC way, being that I thought it's only job is to direct traffic, but it's doing more by calling functions from my model. Is this the best way to go about this?
Answer: PHP is not my area of expertise, so just some generic notes:
4 is a magic number here:
$post = $this->paginate(4);
Why is it 4? What the purpose if this number? A named constant or local variable would be readable with a descriptive name.
public function getMonth($post)
{
$post->month = date('M', strtotime($this->created_at));
$post->month = strtoupper($post->month);
return $post->month;
}
Using a local variable with a proper name, like lowercase_month, in the first line would be readable and more descriptive.
These methods violates Command Query Separation since they return some data and modify the $post too.
Functions should either do something or answer something, but not both.
Source: Clean Code by Robert C. Martin, Chapter 3: Functions, Command Query Separation p45
$post->month = date('M', strtotime($this->created_at));
$post->month = strtoupper($post->month); | {
"domain": "codereview.stackexchange",
"id": 42730,
"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": "php, mvc, laravel",
"url": null
} |
php, mvc, laravel
$post->month = date('M', strtotime($this->created_at));
$post->month = strtoupper($post->month);
I'd consider moving these calls to the Post class since it seems data envy. (Pseudocode.)
class Post {
...
public void setMonth($created_at) {
$lowercase_month = date('M', strtotime($created_at));
$post->month = strtoupper($lowercase_month);
}
...
} | {
"domain": "codereview.stackexchange",
"id": 42730,
"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": "php, mvc, laravel",
"url": null
} |
java, object-oriented
Title: Is my Tic-Tac-Toe design clean?
Question: The following is an implementation of Tic-Tac-Toe game. I tried to incorporate S and O principles without violating L,I,D (hopefully) principles of SOLID. The main aim is to design in such a way that it is extensible so that any new feature additions in the future won't break the current architecture (Ex: If I Need to save Game info in DB in the future). I am mainly interested in how the components should be connected. Is my code clean? Any inputs are highly appreciated...
import java.util.Arrays;
import java.util.Scanner;
interface IPlayer {
int[] makeMove();
}
class Player implements IPlayer {
private InputReader mInputReader;
private BoardMovement mBoardMovement;
private char mStyle;
private String mName;
public Player(InputReader inputReader, BoardMovement movement, char ch, String name) {
mInputReader = inputReader;
mBoardMovement = movement;
mStyle = ch;
mName = name;
}
@Override
public int[] makeMove() {
int[] input = mInputReader.readInput();
mBoardMovement.onMove(input[0], input[1], mStyle);
return input;
}
public String getName() {
return mName;
}
}
interface InputReader {
int[] readInput();
}
class ConsoleInputReader implements InputReader {
private final Scanner SCANNER = new Scanner(System.in);
@Override
public int[] readInput() {
int[] move = new int[2];
move[0] = SCANNER.nextInt();
move[1] = SCANNER.nextInt();
return move;
}
}
interface BoardMovement {
void onMove(int x, int y, char ch);
}
public class Board implements BoardMovement {
protected final char[][] mBoard;
protected int mSize;
private final BoardMovement mListener = this;
public Board(int n) {
mBoard = new char[n][n];
mSize = n;
}
@Override
public void onMove(int x, int y, char ch) {
mBoard[x][y] = ch;
} | {
"domain": "codereview.stackexchange",
"id": 42731,
"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": "java, object-oriented",
"url": null
} |
java, object-oriented
@Override
public void onMove(int x, int y, char ch) {
mBoard[x][y] = ch;
}
public BoardMovement getBoardMovementListener() {
return mListener;
}
}
class GameState extends Board {
Player mCurrentPlayer;
Player playerOne, playerTwo;
boolean isGameEnded;
int winner;
int moves;
public GameState(int n) {
super(n);
moves = 0;
}
public void setPlayers(Player one, Player two) {
playerOne = one;
playerTwo = two;
mCurrentPlayer = playerOne;
}
public void play() {
int[] move = mCurrentPlayer.makeMove();
checkWinner(move);
moves++;
if (isGameEnded) {
winner = mCurrentPlayer == playerOne ? 1 : 2;
return;
}
if (moves == mSize * mSize) isGameEnded = true;
mCurrentPlayer = mCurrentPlayer == playerOne ? playerTwo : playerOne;
}
private void checkWinner(int[] move) {
if (checkRow(move)) return;
if (checkColumn(move)) return;
checkDiagonal(move);
}
private boolean checkRow(int[] move) {
int count = 0;
char current = mBoard[move[0]][move[1]];
for (int i = 0; i < mSize; i++) {
if (mBoard[i][move[1]] == current) count++;
}
if (count == mSize) {
isGameEnded = true;
return true;
}
return false;
}
private boolean checkColumn(int[] move) {
int count = 0;
char current = mBoard[move[0]][move[1]];
for (int i = 0; i < mSize; i++) {
if (mBoard[move[0]][i] == current) count++;
}
if (count == mSize) {
isGameEnded = true;
return true;
}
return false;
} | {
"domain": "codereview.stackexchange",
"id": 42731,
"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": "java, object-oriented",
"url": null
} |
java, object-oriented
private void checkDiagonal(int[] move) {
int diag = 0, rev_diag = 0;
char current = mBoard[move[0]][move[1]];
for (int i = 0; i < mSize; i++) {
if (mBoard[i][i] == current) diag++;
if (mBoard[i][mSize - 1 - i] == current) rev_diag++;
}
if (diag == mSize || rev_diag == mSize) {
isGameEnded = true;
}
}
public void print() {
for (char[] board : mBoard) {
System.out.println(Arrays.toString(board));
}
}
// 0 -> draw , 1 -> player 1 , 2 -> player 2
public int getWinner() {
return winner;
}
public String getWinnerName() {
return mCurrentPlayer.getName();
}
}
class GameManager {
GameState gameState;
public GameManager(GameState gameState) {
this.gameState = gameState;
}
public void startGame() {
while (!gameState.isGameEnded) {
gameState.play();
gameState.print();
}
int winner = gameState.getWinner();
if (winner == 0) System.out.println("The match is drawn");
else System.out.println("The Winner is " + gameState.getWinnerName());
}
}
Drive Code :
public class TicTacToe {
public static void main(String[] args) {
ConsoleInputReader consoleInputReader = new ConsoleInputReader();
GameState gameState = new GameState(3);
Player playerA = new Player(consoleInputReader, gameState.getBoardMovementListener(), 'X', "Player A");
Player playerB = new Player(consoleInputReader, gameState.getBoardMovementListener(), 'O', "Player B");
gameState.setPlayers(playerA, playerB);
GameManager gameManager = new GameManager(gameState);
gameManager.startGame();
}
} | {
"domain": "codereview.stackexchange",
"id": 42731,
"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": "java, object-oriented",
"url": null
} |
java, object-oriented
Answer: One thing that stands out to me is class GameState extends Board {.
When building for extensibility, you're imagining that all your classes get bigger and more complicated. Inheritance lets you spread the members of one class across multiple files. If all your files double in size, the complexity of GameState quadruples.
Here's an adaptation of your GameState that uses composition:
import java.util.Arrays;
import java.util.List;
public class GameState {
Player mCurrentPlayer;
Player playerOne, playerTwo;
boolean isGameEnded;
int winner;
int moves;
// GameState *has* a Board, but it *isn't* a board
// this means you aren't mixing Board state with GameState
private final Board board;
public GameState(int n) {
board = new Board(n);
moves = 0;
}
// unchanged
public void setPlayers(Player one, Player two) {
playerOne = one;
playerTwo = two;
mCurrentPlayer = playerOne;
}
public void play() {
int[] move = mCurrentPlayer.makeMove();
checkWinner(move);
moves++;
if (isGameEnded) {
winner = mCurrentPlayer == playerOne ? 1 : 2;
return;
}
// the logic of maximum possible moves is hidden behind a named method
// that means that this class can focus on the business rule (moves == max moves)
// and the board class can focus on implementation (max moves == width x height
if (moves == board.getMaximumPossibleMoves()) isGameEnded = true;
mCurrentPlayer = mCurrentPlayer == playerOne ? playerTwo : playerOne;
} | {
"domain": "codereview.stackexchange",
"id": 42731,
"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": "java, object-oriented",
"url": null
} |
java, object-oriented
// unchanged
// however, I would suggest that you make these check* methods static
// and set the isGameEnded value here
// because then you can move all the check methods into a separate file
// which is another way to keep things small and well contained as your
// classes grow
private void checkWinner(int[] move) {
if (checkRow(move)) return;
if (checkColumn(move)) return;
checkDiagonals(move);
}
private boolean checkRow(int[] move) {
// See https://refactoring.guru/smells/primitive-obsession
// for a discussion on primitives vs micro objects
Position position = Position.of(move);
// getMarkerAtPosition: abstraction provides two things:
// 1. a name that reveals the intention
// 2. hides the implementation so you don't care how the board is encoded
// Character: in addition to the primitive obsession points,
// using a boxed type here lets us use List instead of array
// List lets us use stream, filter, etc.
// which lets us write more concise code
Character marker = board.getMarkerAtPosition(position);
// I've split the for loop into two parts:
// 1. find the row (this lives in board)
// 2. check the row (stream/filter/etc.)
List<Character> row = board.getRow(position.y);
isGameEnded = row.stream().filter(x -> x.equals(marker)).count() == board.getBoardSize();
// you had "if isGameEnded return true else return false", which simplifies to:
return isGameEnded;
} | {
"domain": "codereview.stackexchange",
"id": 42731,
"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": "java, object-oriented",
"url": null
} |
java, object-oriented
// same comments as checkRow
// it's worth noting, though, that the checks now operate on lists of Characters
// so instead of checking row, column, and each diagonal, you could instead
// get row, column, and each diagonal
// and then for each of those four lists, check if any are complete
private boolean checkColumn(int[] move) {
Position position = Position.of(move);
Character marker = board.getMarkerAtPosition(position);
List<Character> column = board.getColumn(position.x);
isGameEnded = column.stream().filter(x -> x.equals(marker)).count() == board.getBoardSize();
return isGameEnded;
}
// same comments as rows/columns
private void checkDiagonals(int[] move) {
Position position = Position.of(move);
Character marker = board.getMarkerAtPosition(position);
// Previously, you iterated once. Now, this code iterates twice.
// Since the size of the grid is constant and quite small, I don't
// think this affects performance.
List<Character> upwardsDiagonal = board.getUpwardsDiagonal();
List<Character> downwardsDiagonal = board.getDownwardsDiagonal();
boolean isUpwardsDiagonalComplete = upwardsDiagonal.stream().filter(x -> x.equals(marker)).count() == board.getBoardSize();
boolean isDownwardsDiagonalComplete = downwardsDiagonal.stream().filter(x -> x.equals(marker)).count() == board.getBoardSize();
isGameEnded = isDownwardsDiagonalComplete || isUpwardsDiagonalComplete;
}
public void print() {
board.getRows().forEach(row -> {
System.out.println(Arrays.toString(row.toArray()));
});
}
// 0 -> draw , 1 -> player 1 , 2 -> player 2
public int getWinner() {
return winner;
}
public String getWinnerName() {
return mCurrentPlayer.getName();
}
} | {
"domain": "codereview.stackexchange",
"id": 42731,
"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": "java, object-oriented",
"url": null
} |
java, object-oriented
public String getWinnerName() {
return mCurrentPlayer.getName();
}
}
Board class with new methods:
public class Board implements BoardMovement {
// Although I've updated the methods to use Character instead of char
// I didn't change the type of mBoard
// You may find that storing the board as Character[][] makes things easier
protected final char[][] mBoard;
private int mSize;
private final BoardMovement mListener = this;
// unchanged
public Board(int n) {
mBoard = new char[n][n];
mSize = n;
}
// unchanged
@Override
public void onMove(int x, int y, char ch) {
mBoard[x][y] = ch;
}
// unchanged
public BoardMovement getBoardMovementListener() {
return mListener;
}
// the following are the new methods, extracted from GameState
int getBoardSize() {
return mSize;
}
int getMaximumPossibleMoves() {
return mSize * mSize;
}
Character getMarkerAtPosition(Position move) {
return Character.of(mBoard[move.x][move.y]);
}
List<Character> getColumn(int x) {
List<Character> result = new ArrayList<>();
for (int y = 0; y < mSize; y++) {
result.add(Character.of(mBoard[x][y]));
}
return result;
}
List<Character> getRow(int y) {
List<Character> result = new ArrayList<>();
for (int x = 0; x < mSize; x++) {
result.add(Character.of(mBoard[x][y]));
}
return result;
}
List<Character> getUpwardsDiagonal() {
List<Character> result = new ArrayList<>();
for (int i = 0; i < mSize; i++) {
result.add(Character.of(mBoard[i][mSize - 1 - i]));
}
return result;
} | {
"domain": "codereview.stackexchange",
"id": 42731,
"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": "java, object-oriented",
"url": null
} |
java, object-oriented
List<Character> getDownwardsDiagonal() {
List<Character> result = new ArrayList<>();
for (int i = 0; i < mSize; i++) {
result.add(Character.of(mBoard[i][i]));
}
return result;
}
List<List<Character>> getRows() {
List<List<Character>> rows = new ArrayList<>();
for (char[] board : mBoard) {
List<Character> row = new ArrayList<>();
for (char character : board) {
row.add(Character.of(character));
}
rows.add(row);
}
return rows;
}
}
Supporting classes:
class Character {
char value;
private Character(char value) {
this.value = value;
}
public static Character of(char value) {
return new Character(value);
}
@Override
public boolean equals(Object other) {
return other instanceof Character && this.value == ((Character) other).value;
}
@Override
public String toString() {
return java.lang.Character.toString(this.value);
}
}
class Position {
final int x;
final int y;
public static Position of(int[] moves) {
return new Position(moves[0], moves[1]);
}
public Position(int x, int y) {
this.x = x;
this.y = y;
}
} | {
"domain": "codereview.stackexchange",
"id": 42731,
"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": "java, object-oriented",
"url": null
} |
java, object-oriented
public Position(int x, int y) {
this.x = x;
this.y = y;
}
}
Previously, GameState relied on mBoard being char[][]. With this implementation, GameState relies on a few Board methods for accessing rows, columns, etc. You can implement those methods with any number of board formats. This lets the storage of the board vary independently of the game rules in GameState.
I think you can take this idea even further, working towards a version of your code where GameState reads almost like an English summary of the rules because the methods on Board are so expressive of the intent. The underlying principal is to increase the signal to noise ratio in the classes that have business rules. For you, that's GameState. Everything there that deals with implementation details like [i], for loops, etc. is noise, and everything that deals with the rules of tic tac toe is signal. For example:
int[] move = mCurrentPlayer.makeMove(); // signal
checkWinner(move); // signal
moves++; // noise
if (isGameEnded) { // signal..?
winner = mCurrentPlayer == playerOne ? 1 : 2; // noisy signal
return;
}
vs
makeMove(mCurrentPlayer);
if (boardStateDoesIndicateGameOver()) {
winner = getPlayerIdentifier(mCurrentPlayer);
return;
} | {
"domain": "codereview.stackexchange",
"id": 42731,
"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": "java, object-oriented",
"url": null
} |
java, design-patterns, spring, spring-mvc, abstract-factory
Title: Using Factory Design Pattern in Rest Controller of Spring
Question: I used factory design pattern to identify the service according to the enum that comes from the api uri as request param. Everything seems okay according to me but cannot be sure if I used it right.
@RestController
@RequestMapping(GA)
public class GaController {
@Autowired
private GaServiceFactory factory;
@PostMapping(value = INITIALIZE, produces = APPLICATION_JSON_VALUE)
public ResponseEntity<GaDTO> initialize(@RequestParam GaType gaType) {
return status(CREATED).body(factory.getInstance(gaType).initialize());
}
@GetMapping(value = FIND, produces = APPLICATION_JSON_VALUE)
public ResponseEntity<GaDTO> find(@PathVariable String id, @RequestParam GaType gaType) {
return status(FOUND).body(factory.getInstance(gaType).find(id));
}
@GetMapping(value = FIND_ALL, produces = APPLICATION_JSON_VALUE)
public ResponseEntity<List<GaDTO>> findAll(@RequestParam GaType gaType) {
return status(FOUND).body(factory.getInstance(gaType).findAll());
}
This is my factory;
@Service
public class GaServiceFactory {
@Autowired
private ApplicationContext appContext;
public IGaService getInstance(GaType type) {
if (MAN.equals(type)) {
return appContext.getBean(ManGaService.class);
}
throw new RuntimeException("No matching service could be created !");
}
} | {
"domain": "codereview.stackexchange",
"id": 42732,
"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": "java, design-patterns, spring, spring-mvc, abstract-factory",
"url": null
} |
java, design-patterns, spring, spring-mvc, abstract-factory
throw new RuntimeException("No matching service could be created !");
}
}
Answer: Welcome to CodeReview.
By the code you have shown, using the factory pattern may be overengineering. Unless you plan on adding more services, just use the ManGaService directly (to have less coupling, you could declare the variable of type IGaService).
But maybe, and more importantly, why would you have the desired service be specified as a query parameter? Doesn't it make more sense to define separate resources and URLs?
If you simply want to unify the way operations are handled for all resources, then you could make the GaType parameter a PathVariable, so that it is transparent to the user of your API.
For example, this could be a controller for the respurce handled by the ManGaService:
@RestController
@RequestMapping("/path/of/ga/man")
public class ManGaController {
// Using constructor autowiring allows to declare fields as final
private final IGaService manService;
@Autowired
private ManGaController(ManGaService manService) {
this.manService = manService;
}
@PostMapping
public ResponseEntity<GaDTO> initialize() {
// I prefer class imports instead of static method imports
return ResponseEntity.status(HttpStatus.CREATED)
.body(manService.initialize());
}
...
}
Then, there would be some other controllers for the other existing resources handled by IGaServices.
Lastly, as a comment, instead of creating a RuntimeException directly, either use a specialized subclass, or declare your own. If you were to keep using your factory pattern approach, IllegalArgumentException would be more suitable | {
"domain": "codereview.stackexchange",
"id": 42732,
"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": "java, design-patterns, spring, spring-mvc, abstract-factory",
"url": null
} |
c++, template-meta-programming, c++20
Title: invocable_traits v4
Question: Update: there is a new version of this code: v5 is posted here
Goal: implement traits that for anything callable return its arity, return type and the argument types. Since pointers to data members are also callable, those should be handled (and be considered 0-arity).
Code below, try here. This is v4 (v3 here), incorporating comments received on v2 and further enhancements:
the return type when using the invocable with std::invoke() may differ from the declared return type. Can now query both.
can now get more info about the function declaration, whether it is marked const, volatile and no_except
Did i cover all possible callables out there? Do i provide all potentially useful information about a callable (it covers my use cases, but if you can think of more that might be useful, let me know).
#pragma once
#include <cstddef>
#include <tuple>
#include <type_traits>
// inspired by https://github.com/kennytm/utils/blob/master/traits.hpp
// and https://stackoverflow.com/a/28213747
// This does not handle overloaded functions (which includes functors with
// overloaded operator()), because the compiler would not be able to resolve
// the overload without knowing the argument types and the cv- and noexcept-
// qualifications. If you do know those already and can thus specify the
// overload to the compiler, you do not need this class. The only remaining
// piece of information is the result type, which you can get with
// std::invoke_result.
namespace detail
{
template <std::size_t i, typename... Args>
struct invocable_traits_arg_impl
{
static_assert(i < sizeof...(Args), "Requested argument type out of bounds (function does not declare this many arguments)");
using type = std::tuple_element_t<i, std::tuple<Args...>>;
}; | {
"domain": "codereview.stackexchange",
"id": 42733,
"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++, template-meta-programming, c++20",
"url": null
} |
c++, template-meta-programming, c++20
using type = std::tuple_element_t<i, std::tuple<Args...>>;
};
template <
typename Rd, typename Ri, typename C,
bool IsConst, bool isVolatile, bool isNoexcept, bool IsVariadic,
typename... Args>
struct invocable_traits_class
{
static constexpr std::size_t arity = sizeof...(Args);
static constexpr auto is_const = IsConst;
static constexpr auto is_volatile = isVolatile;
static constexpr auto is_noexcept = isNoexcept;
static constexpr auto is_variadic = IsVariadic;
using declared_result_t = Rd; // return type as declared in function
using invoke_result_t = Ri; // return type of std::invoke() expression
using class_t = C;
template <std::size_t i>
using arg_t = typename invocable_traits_arg_impl<i, Args...>::type;
};
template <
typename Rd, typename Ri,
bool IsConst, bool isVolatile, bool isNoexcept, bool IsVariadic,
typename... Args>
struct invocable_traits_free : public invocable_traits_class<Rd, Ri, void, IsConst, isVolatile, isNoexcept, IsVariadic, Args...> {};
template <typename T>
struct invocable_traits_impl;
#define IS_NONEMPTY(...) 0 __VA_OPT__(+1) | {
"domain": "codereview.stackexchange",
"id": 42733,
"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++, template-meta-programming, c++20",
"url": null
} |
c++, template-meta-programming, c++20
#define INVOCABLE_TRAITS_SPEC(c,v,...) \
/* functions, including noexcept versions */ \
template <typename R, typename... Args> \
struct invocable_traits_impl<R(Args... __VA_OPT__(,) __VA_ARGS__) c v> \
: public invocable_traits_free< \
R, \
std::invoke_result_t<R(Args... __VA_OPT__(,) __VA_ARGS__) c v,Args...>, \
IS_NONEMPTY(c), \
IS_NONEMPTY(v), \
false, \
IS_NONEMPTY(__VA_ARGS__), \
Args...> {}; \
template <typename R, typename... Args> \
struct invocable_traits_impl<R(Args...__VA_OPT__(,) __VA_ARGS__) c v noexcept> \
: public invocable_traits_free< \
R, \
std::invoke_result_t<R(Args... __VA_OPT__(,) __VA_ARGS__) c v noexcept,Args...>,\
IS_NONEMPTY(c), \
IS_NONEMPTY(v), \
true, \
IS_NONEMPTY(__VA_ARGS__), \
Args...> {}; \ | {
"domain": "codereview.stackexchange",
"id": 42733,
"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++, template-meta-programming, c++20",
"url": null
} |
c++, template-meta-programming, c++20
Args...> {}; \
/* pointers to member functions, including noexcept versions) */ \
template <typename C, typename R, typename... Args> \
struct invocable_traits_impl<R(C::*)(Args...__VA_OPT__(,) __VA_ARGS__) c v> \
: public invocable_traits_class< \
R, \
std::invoke_result_t<R(C::*)(Args...__VA_OPT__(,) __VA_ARGS__) c v,C,Args...>, \
C, \
IS_NONEMPTY(c), \
IS_NONEMPTY(v), \
false, \
IS_NONEMPTY(__VA_ARGS__), \
Args...> {}; \
template <typename C, typename R, typename... Args> \
struct invocable_traits_impl<R(C::*)(Args...__VA_OPT__(,) __VA_ARGS__) c v noexcept>\
: public invocable_traits_class< \
R, \
std::invoke_result_t<R(C::*)(Args...__VA_OPT__(,) __VA_ARGS__) c v noexcept,C,Args...>, \
C, \
IS_NONEMPTY(c), \
IS_NONEMPTY(v), \
true, \ | {
"domain": "codereview.stackexchange",
"id": 42733,
"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++, template-meta-programming, c++20",
"url": null
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.