text stringlengths 1 2.12k | source dict |
|---|---|
c++, performance
Title: Evaluating math terms as nested lambdas instead of expression tree
Question: I need to store some math terms. Originally I would use a tree to do it, especially if parsing strings was involved. However, since the expressions are built within the code and need not be parsed, I thought of doing it with nested lambdas and overloaded operators instead.
Since these expressions will probably be run a few thousand times (possibly up to 100k), I wonder if I should expect any problems (e.g. call stack too full) or what other thoughts you have on this approach. I expect no math term to contain more than 100 operators (in f+g*h I count 2 operators, for that matter).
Run it on godbolt
#include <functional>
#include <iostream>
using Func = std::function<double(double)>;
class Cube{
public:
double operator()(double x) const{
return x*x*x;
}
};
Func operator+(Func lhs, Func rhs){
return [lhs, rhs](double x){
return lhs(x) + rhs(x);
};
}
Func operator-(Func lhs, Func rhs){
return [lhs, rhs](double x){
return lhs(x) - rhs(x);
};
}
Func operator*(Func lhs, Func rhs){
return [lhs, rhs](double x){
return lhs(x) * rhs(x);
};
}
Func operator/(Func lhs, Func rhs){
return [lhs, rhs](double x){
return lhs(x) / rhs(x);
};
}
int main(){
std::function<double(double)> square = [](double x){
return x*x;
};
Cube c;
auto result1 = square + c;
auto result2 = square - c;
auto result3 = square * c;
auto result4 = c / square;
auto result5 = result1 + result2 - result3 * result4;
double x = 3.5;
std::cout << "result1: " << result1(x) << "\n";
std::cout << "result2: " << result2(x) << "\n";
std::cout << "result3: " << result3(x) << "\n";
std::cout << "result4: " << result4(x) << "\n";
std::cout << "result5: " << result5(x) << "\n";
}
```` | {
"domain": "codereview.stackexchange",
"id": 43547,
"lm_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",
"url": null
} |
c++, performance
Answer: I don't see any major problems with this approach, in fact it strikes me as quite elegant! However, I notice your Cube callable/functor and your square function are not composable with the rest of your operators, and this is trivially fixable by making them also functions returning lambdas:
Func square(Func op) {
return [op](double x) {
auto r = op(x);
return r*r;
};
}
And similarly for cube. Note how I cache the result - this way if op has side effects, they only happen once, as most consumers of the library might expect.
What I mean by composable is that you can now do stuff like:
Func complicatedOperation = square(cube(cube + square));
The way these would get composed is by having a small helper function, id:
double id(double x) {
return x;
}
id or "identity", a function which just returns its argument, provides a simple way of saying "value goes here" when the tree is being constructed.
and if you want to start the expression tree with the square or cube functions, define these:
liftedSquare = square(id);
liftedCube = cube(id);
Now, there's an easier way here - what about just having:
#include <cmath>
...
Func operator^(const Func& lhs, const Func& rhs){
return [lhs, rhs](const double x){
return std::pow(lhs(x), rhs(x));
};
}
No need for separate square and cube anymore! square becomes auto square = id ^ lift(2);. lift is this function which is basically just a lazy version of id, it takes a value and returns a function returning that value.
Then just chuck everything into a namespace so it doesn't interfere with other operator overloads, and you have this:
#include <functional>
#include <cmath>
#include <iostream>
namespace LazyOps {
using Func = std::function<double(double)>;
namespace {
double _id(const double x) {
return x;
}
}
Func id = _id; | {
"domain": "codereview.stackexchange",
"id": 43547,
"lm_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",
"url": null
} |
c++, performance
Func lift(const double x) {
return [x](const double _) {
return x;
};
}
Func cube(const Func& op) {
return [op](const double x) {
auto r = op(x);
return r*r*r;
};
}
Func square(const Func& op) {
return [op](const double x) {
auto r = op(x);
return r*r;
};
}
Func operator+(const Func& lhs, const Func& rhs){
return [lhs, rhs](const double x){
return lhs(x) + rhs(x);
};
}
Func operator-(const Func& lhs, const Func& rhs){
return [lhs, rhs](const double x){
return lhs(x) - rhs(x);
};
}
Func operator*(const Func& lhs, const Func& rhs){
return [lhs, rhs](const double x){
return lhs(x) * rhs(x);
};
}
Func operator/(const Func& lhs, const Func& rhs){
return [lhs, rhs](const double x){
return lhs(x) / rhs(x);
};
}
Func operator^(const Func& lhs, const Func& rhs){
return [lhs, rhs](const double x){
return std::pow(lhs(x), rhs(x));
};
}
}
int main(){
using namespace LazyOps;
auto liftedSquare = square(id);
auto liftedCube = cube(id);
auto result1 = liftedSquare + liftedCube;
auto result2 = liftedSquare - liftedCube;
auto result3 = liftedSquare * liftedCube;
auto result4 = liftedCube / liftedSquare;
auto newSquare = id ^ lift(2);
auto result5 = result1 + result2 - result3 * result4;
auto result6 = cube(square(liftedCube / liftedSquare));
auto result7 = id ^ id;
double x = 4.0; | {
"domain": "codereview.stackexchange",
"id": 43547,
"lm_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",
"url": null
} |
c++, performance
double x = 4.0;
std::cout << "result1: " << result1(x) << "\n";
std::cout << "result2: " << result2(x) << "\n";
std::cout << "result3: " << result3(x) << "\n";
std::cout << "result4: " << result4(x) << "\n";
std::cout << "result5: " << result5(x) << "\n";
std::cout << "result6: " << result6(x) << "\n";
std::cout << "result7: " << result7(x) << "\n";
std::cout << "square(" << x << "): " << newSquare(x) << "\n";
}
Unfortunately, the compiler isn't great with compiling auto result = id ^ id; just like that, therefore I had to put in a type deduction hint by putting the actual _id function in a private anonymous namespace and defining an alias Func id = _id; in the actual LazyOps namespace.
As for whether this will blow up your stack, I can't really say, but hopefully accepting the Func arguments as const references can help with that. Make a small script to generate some huge expression tree and see how it goes! | {
"domain": "codereview.stackexchange",
"id": 43547,
"lm_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",
"url": null
} |
c, windows, gui, winapi
Title: Code for setting all child controls to the default message font on Windows
Question: If you aren't aware, if you hand-code a GUI with the Windows API you will find your controls look quite ugly by default due to their font. Running this code:
#include <Windows.h>
#include <windowsx.h>
#include <CommCtrl.h>
#include <strsafe.h>
#include <sal.h>
#pragma comment(lib, "comctl32.lib")
#if defined _M_IX86
#pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='x86' publicKeyToken='6595b64144ccf1df' language='*'\"")
#elif defined _M_IA64
#pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='ia64' publicKeyToken='6595b64144ccf1df' language='*'\"")
#elif defined _M_X64
#pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='amd64' publicKeyToken='6595b64144ccf1df' language='*'\"")
#else
#pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"")
#endif
CONST WCHAR g_wszClassName[] = L"FONT_DEMO_WINDOW";
VOID WINAPI OnClose(
HWND hWnd
)
{
DestroyWindow(hWnd);
}
VOID WINAPI OnCommand(
HWND hWnd,
INT nID,
HWND hwSource,
UINT uNotify
)
{
HWND hButton = FindWindowExW(hWnd, NULL, L"Button", NULL);
if (hButton == hwSource)
{
WCHAR *wszBuffer = NULL;
HWND hEdit = FindWindowExW(hWnd, NULL, L"Edit", NULL);
HWND hStatic = FindWindowExW(hWnd, NULL, L"Static", NULL);
HANDLE hHeap = GetProcessHeap();
INT nLen = GetWindowTextLengthW(hEdit) + 1; | {
"domain": "codereview.stackexchange",
"id": 43548,
"lm_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, windows, gui, winapi",
"url": null
} |
c, windows, gui, winapi
wszBuffer = (WCHAR *) HeapAlloc(hHeap, HEAP_ZERO_MEMORY, nLen * sizeof(WCHAR));
if (NULL == wszBuffer)
{
MessageBoxW(NULL, L"Out of memory", L"Error", MB_OK | MB_ICONSTOP);
ExitProcess(ERROR_OUTOFMEMORY);
}
GetWindowTextW(hEdit, wszBuffer, nLen);
SetWindowTextW(hStatic, wszBuffer);
HeapFree(hHeap, 0, wszBuffer);
wszBuffer = NULL;
}
}
BOOL WINAPI OnCreate(
HWND hWnd,
LPCREATESTRUCTW lpCreateStruct
)
{
INITCOMMONCONTROLSEX iccx;
HINSTANCE hInstance = lpCreateStruct->hInstance;
iccx.dwICC = ICC_STANDARD_CLASSES;
iccx.dwSize = sizeof(INITCOMMONCONTROLSEX);
InitCommonControlsEx(&iccx);
CreateWindowW(L"Button", L"Click Me", WS_VISIBLE | WS_CHILD, 205, 210, 90, 30, hWnd, NULL, hInstance, NULL);
CreateWindowW(L"Static", L"", WS_VISIBLE | WS_CHILD, 10, 100, 490, 20, hWnd, NULL, hInstance, NULL);
CreateWindowW(L"Edit", L"Type something in here", WS_VISIBLE | WS_CHILD, 10, 10, 470, 20, hWnd, NULL, hInstance, NULL);
return TRUE;
}
VOID WINAPI OnDestroy(
HWND hWnd
)
{
PostQuitMessage(ERROR_SUCCESS);
}
VOID WINAPI OnPaint(
HWND hWnd
)
{
PAINTSTRUCT ps;
BeginPaint(hWnd, &ps);
EndPaint(hWnd, &ps);
}
LRESULT CALLBACK WindowProc(
HWND hWnd,
UINT Msg,
WPARAM wParam,
LPARAM lParam
)
{
switch (Msg)
{
HANDLE_MSG(hWnd, WM_CLOSE, OnClose);
HANDLE_MSG(hWnd, WM_CREATE, OnCreate);
HANDLE_MSG(hWnd, WM_COMMAND, OnCommand);
HANDLE_MSG(hWnd, WM_DESTROY, OnDestroy);
HANDLE_MSG(hWnd, WM_PAINT, OnPaint);
default:
return DefWindowProcW(hWnd, Msg, wParam, lParam);
}
return 0;
}
ATOM WINAPI RegisterWCEX(
HINSTANCE hInstance
)
{
WNDCLASSEXW wcex;
ZeroMemory(&wcex, sizeof(WNDCLASSEXW)); | {
"domain": "codereview.stackexchange",
"id": 43548,
"lm_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, windows, gui, winapi",
"url": null
} |
c, windows, gui, winapi
wcex.cbSize = sizeof(WNDCLASSEXW);
wcex.hInstance = hInstance;
wcex.lpszClassName = g_wszClassName;
wcex.hbrBackground = (HBRUSH) COLOR_WINDOW;
wcex.hCursor = LoadCursorW(NULL, IDC_ARROW);
wcex.hIcon = wcex.hIconSm = LoadIconW(NULL, IDI_APPLICATION);
wcex.lpfnWndProc = WindowProc;
return RegisterClassExW(&wcex);
}
INT APIENTRY wWinMain(
_In_ HINSTANCE hInstance,
_In_opt_ HINSTANCE hPrevInstance,
_In_ LPWSTR lpCmdLine,
_In_ INT nShowCmd
)
{
HWND hWnd;
MSG Msg;
if (RegisterWCEX(hInstance) == 0)
{
MessageBoxW(NULL, L"Window registration failed", L"Error", MB_OK | MB_ICONSTOP);
return -1;
}
hWnd = CreateWindowExW(WS_EX_OVERLAPPEDWINDOW, g_wszClassName, L"Windows Font Demo", WS_VISIBLE | WS_SYSMENU, 100, 100, 500, 350, NULL, NULL, hInstance, NULL);
if (NULL == hWnd)
{
MessageBoxW(NULL, L"Window creation failed", L"Error", MB_OK | MB_ICONSTOP);
return -1;
}
ShowWindow(hWnd, nShowCmd);
UpdateWindow(hWnd);
while (GetMessageW(&Msg, NULL, 0, 0) > 0)
{
TranslateMessage(&Msg);
DispatchMessageW(&Msg);
}
return Msg.wParam;
}
Will give us the following window:
I therefore make the following addition to any GUI project I code (key changes: the EnumChildProc function, the SystemsParameterInfoW and EnumChildWindows calls in wWinMain):
#include <Windows.h>
#include <windowsx.h>
#include <CommCtrl.h>
#include <strsafe.h>
#include <sal.h>
#pragma comment(lib, "comctl32.lib") | {
"domain": "codereview.stackexchange",
"id": 43548,
"lm_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, windows, gui, winapi",
"url": null
} |
c, windows, gui, winapi
#pragma comment(lib, "comctl32.lib")
#if defined _M_IX86
#pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='x86' publicKeyToken='6595b64144ccf1df' language='*'\"")
#elif defined _M_IA64
#pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='ia64' publicKeyToken='6595b64144ccf1df' language='*'\"")
#elif defined _M_X64
#pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='amd64' publicKeyToken='6595b64144ccf1df' language='*'\"")
#else
#pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"")
#endif
CONST WCHAR g_wszClassName[] = L"FONT_DEMO_WINDOW";
BOOL CALLBACK EnumChildProc(
HWND hWnd,
LPARAM lParam
)
{
HFONT hfDefault = *(HFONT *) lParam;
SendMessageW(hWnd, WM_SETFONT, (WPARAM) hfDefault, MAKELPARAM(TRUE, 0));
return TRUE;
}
VOID WINAPI OnClose(
HWND hWnd
)
{
DestroyWindow(hWnd);
}
VOID WINAPI OnCommand(
HWND hWnd,
INT nID,
HWND hwSource,
UINT uNotify
)
{
HWND hButton = FindWindowExW(hWnd, NULL, L"Button", NULL);
if (hButton == hwSource)
{
WCHAR *wszBuffer = NULL;
HWND hEdit = FindWindowExW(hWnd, NULL, L"Edit", NULL);
HWND hStatic = FindWindowExW(hWnd, NULL, L"Static", NULL);
HANDLE hHeap = GetProcessHeap();
INT nLen = GetWindowTextLengthW(hEdit) + 1;
wszBuffer = (WCHAR *) HeapAlloc(hHeap, HEAP_ZERO_MEMORY, nLen * sizeof(WCHAR));
if (NULL == wszBuffer)
{
MessageBoxW(NULL, L"Out of memory", L"Error", MB_OK | MB_ICONSTOP);
ExitProcess(ERROR_OUTOFMEMORY);
} | {
"domain": "codereview.stackexchange",
"id": 43548,
"lm_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, windows, gui, winapi",
"url": null
} |
c, windows, gui, winapi
GetWindowTextW(hEdit, wszBuffer, nLen);
SetWindowTextW(hStatic, wszBuffer);
HeapFree(hHeap, 0, wszBuffer);
wszBuffer = NULL;
}
}
BOOL WINAPI OnCreate(
HWND hWnd,
LPCREATESTRUCTW lpCreateStruct
)
{
INITCOMMONCONTROLSEX iccx;
HINSTANCE hInstance = lpCreateStruct->hInstance;
iccx.dwICC = ICC_STANDARD_CLASSES;
iccx.dwSize = sizeof(INITCOMMONCONTROLSEX);
InitCommonControlsEx(&iccx);
CreateWindowW(L"Button", L"Click Me", WS_VISIBLE | WS_CHILD, 205, 210, 90, 30, hWnd, NULL, hInstance, NULL);
CreateWindowW(L"Static", L"", WS_VISIBLE | WS_CHILD, 10, 100, 490, 20, hWnd, NULL, hInstance, NULL);
CreateWindowW(L"Edit", L"Type something in here", WS_VISIBLE | WS_CHILD, 10, 10, 470, 20, hWnd, NULL, hInstance, NULL);
return TRUE;
}
VOID WINAPI OnDestroy(
HWND hWnd
)
{
PostQuitMessage(ERROR_SUCCESS);
}
VOID WINAPI OnPaint(
HWND hWnd
)
{
PAINTSTRUCT ps;
BeginPaint(hWnd, &ps);
EndPaint(hWnd, &ps);
}
LRESULT CALLBACK WindowProc(
HWND hWnd,
UINT Msg,
WPARAM wParam,
LPARAM lParam
)
{
switch (Msg)
{
HANDLE_MSG(hWnd, WM_CLOSE, OnClose);
HANDLE_MSG(hWnd, WM_CREATE, OnCreate);
HANDLE_MSG(hWnd, WM_COMMAND, OnCommand);
HANDLE_MSG(hWnd, WM_DESTROY, OnDestroy);
HANDLE_MSG(hWnd, WM_PAINT, OnPaint);
default:
return DefWindowProcW(hWnd, Msg, wParam, lParam);
}
return 0;
}
ATOM WINAPI RegisterWCEX(
HINSTANCE hInstance
)
{
WNDCLASSEXW wcex;
ZeroMemory(&wcex, sizeof(WNDCLASSEXW));
wcex.cbSize = sizeof(WNDCLASSEXW);
wcex.hInstance = hInstance;
wcex.lpszClassName = g_wszClassName;
wcex.hbrBackground = (HBRUSH) COLOR_WINDOW;
wcex.hCursor = LoadCursorW(NULL, IDC_ARROW);
wcex.hIcon = wcex.hIconSm = LoadIconW(NULL, IDI_APPLICATION);
wcex.lpfnWndProc = WindowProc;
return RegisterClassExW(&wcex);
} | {
"domain": "codereview.stackexchange",
"id": 43548,
"lm_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, windows, gui, winapi",
"url": null
} |
c, windows, gui, winapi
return RegisterClassExW(&wcex);
}
INT APIENTRY wWinMain(
_In_ HINSTANCE hInstance,
_In_opt_ HINSTANCE hPrevInstance,
_In_ LPWSTR lpCmdLine,
_In_ INT nShowCmd
)
{
HWND hWnd;
MSG Msg;
NONCLIENTMETRICSW ncm;
HFONT hfDefault;
ZeroMemory(&ncm, sizeof(NONCLIENTMETRICSW));
ncm.cbSize = sizeof(NONCLIENTMETRICSW);
SystemParametersInfoW(SPI_GETNONCLIENTMETRICS, sizeof(NONCLIENTMETRICSW), &ncm, FALSE);
hfDefault = CreateFontIndirectW(&ncm.lfMessageFont);
if (RegisterWCEX(hInstance) == 0)
{
MessageBoxW(NULL, L"Window registration failed", L"Error", MB_OK | MB_ICONSTOP);
return -1;
}
hWnd = CreateWindowExW(WS_EX_OVERLAPPEDWINDOW, g_wszClassName, L"Windows Font Demo", WS_VISIBLE | WS_SYSMENU, 100, 100, 500, 350, NULL, NULL, hInstance, NULL);
if (NULL == hWnd)
{
MessageBoxW(NULL, L"Window creation failed", L"Error", MB_OK | MB_ICONSTOP);
return -1;
}
ShowWindow(hWnd, nShowCmd);
EnumChildWindows(hWnd, EnumChildProc, (LPARAM) &hfDefault);
UpdateWindow(hWnd);
while (GetMessageW(&Msg, NULL, 0, 0) > 0)
{
TranslateMessage(&Msg);
DispatchMessageW(&Msg);
}
return Msg.wParam;
}
Which gives us the much more aesthetically pleasing window:
Is this an advisable, efficient, and correct solution to this problem? | {
"domain": "codereview.stackexchange",
"id": 43548,
"lm_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, windows, gui, winapi",
"url": null
} |
c, windows, gui, winapi
Is this an advisable, efficient, and correct solution to this problem?
Answer: Came over from the SO question because admittedly I never look in here.
Firstly, it's not DPI aware. This is fine if you didn't intend it to be.
Not applicable here, but if it were a dialog, MSDN suggests doing it in WM_INITDIALOG.
What you programmed is what needs to happen in the end to change the font (as in it would be free of bugs as far as I can tell), but I would note that the way you programmed it increases the API surface area of the window class.
I'm not exactly sure what kind of answer you're looking for. If you want to know whether this correct and efficient in the context of the application that you posted, then yes, and I have nothing to add.
Otherwise, under specific circumstances (which might totally not be relevant to you), this approach might not scale well with growing complexity and use cases.
This depends a little on how you view things. Either you believe that the window's font is inherent to the window (that's most windows I would say), or you believe that the window is completely agnostic to which font is used, and expects the application to set it.
In the former case, there is no reason why it would be necessary for the application code (i.e. what you've written in wWinMain) to bother with the font - it could happen "automatically". This can for example be done by putting it in WM_CREATE. This is closer to what you would expect from a typical dialog created from a typical dialog template.
In the latter case, it would be possible to reduce the API surface to a single action that the application must take in addition to creating the window. This could be implemented in many different ways, such as implementing the child window enumeration in WM_SETFONT recursively. This is closer to having a reusable child control that integrates well with existing windows. | {
"domain": "codereview.stackexchange",
"id": 43548,
"lm_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, windows, gui, winapi",
"url": null
} |
javascript, performance, error-handling, google-apps-script
Title: Google App Script Automation for User Onboarding | {
"domain": "codereview.stackexchange",
"id": 43549,
"lm_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, performance, error-handling, google-apps-script",
"url": null
} |
javascript, performance, error-handling, google-apps-script
Question: Background
I am a relatively new developer(> 2 years coding) working as an intern for a smaller company, as part of a now 4 person team. We had two other team members, one our system admin and the other our IT manager, fired less than a month after I was hired on. I was hoping to use our IT manager as a resource for reviewing and talking about code with me, as we do not have any other team members with coding knowledge/experience, however now that he has been removed from his position I wanted to reach out to this community to see if I could collaborate with other like-minded people on the code I am writing.
Code Explanation
When I was first hired, I was tasked with creating an automation for our new user onboarding process. We are currently a Google shop, thus we are using Google Workspace for our enterprise suite. To leverage some of the resources available and reduce time/effort needed to make a web application, I am using a Google Form to collect information from our HR team about new hires. The Google Form responses are linked to a Google Sheet (Form Responses), which is used to house the data about our new employees. Once the data is received by the Google Sheet, I am using a Zapier integration with Google Sheets to detect a new spreadsheet row and alert our IT team via Slack that a new employee needs to be "approved" by our team.(Circumstantially, not all users will need accounts within our organization. Thus the need for "approval" of new users).
I have a Google App Script project tied to the Google Sheet containing the Form Responses that appends a Checkbox to new rows added to the sheet with the following code (If the checkbox is checked, the user is approved and accounts should be created):
Form Response Code
function FormSubmit(e){
var ss = SpreadsheetApp.getActive();
ss.getSheetByName("Form Responses").appendRow(e.values);
var lastRow = ss.getSheetByName("Form Responses").getLastRow(); | {
"domain": "codereview.stackexchange",
"id": 43549,
"lm_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, performance, error-handling, google-apps-script",
"url": null
} |
javascript, performance, error-handling, google-apps-script
var lastRow = ss.getSheetByName("Form Responses").getLastRow();
var lastColumn = ss.getSheetByName("Form Responses").getLastColumn(); | {
"domain": "codereview.stackexchange",
"id": 43549,
"lm_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, performance, error-handling, google-apps-script",
"url": null
} |
javascript, performance, error-handling, google-apps-script
var endCell = ss.getSheetByName("Form Responses").getRange(lastRow,lastColumn);
endCell.insertCheckboxes();
}
From here, a member of our team would open the Form Responses Google Sheet, click the checkbox to "approve" the creation of accounts for the user, and click a button embedded on the Form Responses Google Sheet to automate the creation of their Google Account. When the Google Account is created, the new account will also be added to all of the groups they need to be a member of, along with the Shared Drives they need access to.
Image of button/checkbox
In order to have the right information needed to create Windows AD and LastPass accounts inside of our organization, the button not only creates the new employees Google account, but also sends formatted data obtained from the Form Responses Google Sheet over to another Google Sheet(New Users) to store the data for future use. Error logging for the automation is stored on a Google Doc, that I am appending the "logs" to after the script runs.
Code for Button
function MoveRows() {
//Get the values of the current spreadsheet
var spreadSheet = SpreadsheetApp.getActiveSpreadsheet();
var sourceSheet = spreadSheet.getSheetByName("Form Responses");
var sourceRange = sourceSheet.getDataRange();
var sourceValues = sourceRange.getValues(); | {
"domain": "codereview.stackexchange",
"id": 43549,
"lm_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, performance, error-handling, google-apps-script",
"url": null
} |
javascript, performance, error-handling, google-apps-script
//Loops through the rows of the SpreadSheet
for(i = 1; i < sourceValues.length; i++ )
{
//If the user was checked, proceed
if(sourceValues[i][16] == true){
//Assign values to Users
var firstName = sourceValues[i][2];
var lastName = sourceValues[i][3];
var userName = firstName.substring(0,1) + lastName;
var email = firstName + "." + lastName + sourceValues[i][11];
var streetAddress = "###";
var city = "###";
var zipCode = "###";
var state = "###";
var country = "###";
var costCenter = sourceValues[i][8];
var password = "###";
var orgUnitPath;
//If there is no department for our User(user not in Appleton)
//then their "department" is going to be the location of the store they are working at
if(sourceValues[i][7] == "###"){
var department = sourceValues[i][10];
var location = sourceValues[i][7];
}else{
department = location = sourceValues[i][7];
}
//Switch used to decide OrgUnit Path, 'Location' column is used to identify which OrgUnit the User belongs to
switch(location){
case "Philippines - Listings":
case "Philippines - Pricing":
case "Phillipines - OCC/Other":
orgUnitPath = "/People - Philippines"
break;
case "###":
orgUnitPath = "###"
break;
default:
orgUnitPath = "/People - Retail"
break;
}
//Batch object that contains the new user to be added to our workspace
var user = {
"primaryEmail": email,
"password": password,
"orgUnitPath": orgUnitPath,
"organizations": [{
"costCenter": costCenter,
"department": department
}],
"name" : {
"familyName": lastName,
"givenName": firstName
}
}
var errorLog; | {
"domain": "codereview.stackexchange",
"id": 43549,
"lm_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, performance, error-handling, google-apps-script",
"url": null
} |
javascript, performance, error-handling, google-apps-script
try{
//API call to add the new user to our Google Workspace
AdminDirectory.Users.insert(user)
}catch(error){
errorLog += '{ERROR Google}: The Google Account was not able to be created: Message ' + error.Message;
}
//Switch for assigning role based groups and shared drives
switch(ssValues[i][9]){
case "Accounting":
AdminDirectory.Members.insert(groupMember, "###");
AdminDirectory.Members.insert(groupMember, "###");
AdminDirectory.Members.insert(groupMember, "###");
AdminDirectory.Members.insert(groupMember, "###");
DriveApp.getFolderById("###").addEditor(email);
break;
//...repetitive switch code, can include if necessary
}
//Create a row to hold the new values
var targetValues = [firstName,lastName,userName,email,streetAddress,city,zipCode,state,country,department,location,costCenter];
//Get the sheet to move the row to
var targetSheet = SpreadsheetApp.openById("###");
//Append the data to the rows
targetSheet.appendRow(targetValues);
}else{
continue;
}
} | {
"domain": "codereview.stackexchange",
"id": 43549,
"lm_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, performance, error-handling, google-apps-script",
"url": null
} |
javascript, performance, error-handling, google-apps-script
//Used to grab the Google Doc that is holding the logs for error handling
var logDoc = Docs.Documents.get("###");
/*Batch object that is used to make an API call to the Google Docs API
Object holds the text that is set to be added to the log
This object is the purpose behind grabbing the Google Doc before posting information to it
Revision ID is needed to keep all of the current data from the log
*/
var updateObject={
"requests":[
{
"insertText":{
"text": "\n" + errorLog.toString(),
"endOfSegmentLocation":{
"segmentId": ""
}
}
}
],
"writeControl":{
"requiredRevisionId":logDoc.revisionId
}
}
//This API call is used to add the batch object to the Google Doc(Onboard Automation Logs)
Docs.Documents.batchUpdate(updateObject, "###");
//Delete the rows of data that were moved to "New Users"
sourceSheet.deleteRows(2,sourceValues.length);
}
Where can I improve my error handling on script/ do I need more error handling? Can I improve on the use of best practice anywhere in this code? Any performance concerns?
I have included a ### everywhere that might be containing some sensitive information about our organization. If there is any information that appears to be missing and is vital for reviewing this code please let me know. If there are too many questions/questions are too vague, please let me know and I will revise accordingly. Any other suggested advice, even if it is not related to the questions I asked, is more than welcomed.
Answer: You could leverage a more object orient approach to create an instance of a user
const sourceValues = [
[null, "John", "Doe"],
[null,"Bill", "Nye"]
]
class User{
constructor(_,firstName, lastName, ...args ) {
this.firstName = firstName;
this.lastName = lastName
}
userEmail(){
return this.firstName + "." + this.lastName // + sourceValues[i][11];
}
} | {
"domain": "codereview.stackexchange",
"id": 43549,
"lm_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, performance, error-handling, google-apps-script",
"url": null
} |
javascript, performance, error-handling, google-apps-script
userList = sourceValues.map(args=>new User(...args))
or use a a zip like function to map the user info to the name of the column.
const COLUMN_NAMES = ["Unknown", "firstName", "lastName"]
function zip(columnNames, userArr){
return userArr.map(userData=>{
let out = {}
for (var i = 0; i < columnNames.length; i++) {
out = { ...out, [columnNames[i]]: userData[i] }
}
return out
})
}
zip(COLUMN_NAMES,sourceValues)
Either one of these approaches would make your code much more understandable to another developer. | {
"domain": "codereview.stackexchange",
"id": 43549,
"lm_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, performance, error-handling, google-apps-script",
"url": null
} |
performance, strings, nim
Title: How to speed up truncating text to specific word count in nim?
Question: I have a web application, as part of it I regularly have to send out "overviews" of records in a database, which contain shortened excerpts of a description-text of that record.
What the code is supposed to do:
Take an HTML string
Remove the HTML brackets so that only text remains
cut it down to SHORT_DESCRIPTION_WORD_COUNT words
if there are more than SHORT_DESCRIPTION_WORD_COUNT words, add "..." at the end
My current implementation looks like this:
import std/[strutils, strformat, htmlparser, xmltree, enumerate]
const SHORT_DESCRIPTION_WORD_COUNT: int = 40
proc truncate*(text: string): string =
let cleanedString = text.parseHtml().innerText
let splitString = cleanedString.split(" ")
if splitString.len() <= SHORT_DESCRIPTION_WORD_COUNT:
result = cleanedString
else:
result.add(splitString[0..SHORT_DESCRIPTION_WORD_COUNT-1].join(" "))
result.add("...")
Looking at some valgrind data, I determined that this proc takes up a sizeable chunk of time and would benefit from being speed-performance optimized a bit.
I'm mostly wondering how to do that though. I believe the intensive steps here are the cleaning up of the HTML and then splitting the string, I'm not sure how to avoid those.
Answer: After consulting with Yardanico in nim's discord for a bit, there is 1 significant improvement that can be made here and a couple minor ones:
Main Improvement: Use the split iterator
I use the split proc and assign the seq of strings into a variable to iterate over.
That is wasteful, when you can use the split iterator instead.
Since you still need to track which word you're at to know when you hit SHORT_DESCRIPTION_WORD_COUNT, you can use std/enumerate, which is sugar over writing var i=0 and manually incrementing that within the loop.
proc truncate_breakfor_enumerate*(text: string): string =
let cleanedString = text.parseHtml().innerText | {
"domain": "codereview.stackexchange",
"id": 43550,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, strings, nim",
"url": null
} |
performance, strings, nim
for i, str in enumerate(cleanedString.split(" ")):
result.add(" " & str)
if i >= SHORT_DESCRIPTION_WORD_COUNT:
result.add("...")
break
Minor Improvement: Pre-allocate the string
This matters mostly for scenarios in which you add longer strings. Having the string pre-allocated to roughly the correct size can reduce the number of memory allocations needed overall. That is, because if the string outgrows its size as you add substrings to it, it will need to be copied elsewhere. You can do this with newStringOfCap.
This will only even start to matter if you start having a fairly sizeable amount of text (>5000 chars) and even then the improvements are somewhat marginal.
proc truncate_breakformemoryalloc*(text: string): string =
let cleanedString = text.parseHtml().innerText
result = newStringOfCap(400) # <-- The important bit
for i, str in enumerate(cleanedString.split(" ")):
result.add(" " & str)
if i >= SHORT_DESCRIPTION_WORD_COUNT:
result.add("...")
break
Running these over a benchmark with one of normal text and another more artificial one with regularly words above 50 characters, these are my results:
name ......................................... min time avg time std dv runs
truncate classic ............................. 0.046 ms 0.053 ms ±0.004 x1000
truncate_breakfor_enumerate................... 0.021 ms 0.023 ms ±0.001 x1000
truncate_breakfor_enumerate_memoryalloc ...... 0.021 ms 0.025 ms ±0.004 x1000
truncate classic long ........................ 0.050 ms 0.082 ms ±0.019 x1000
truncate_breakfor_enumerate long ............. 0.036 ms 0.040 ms ±0.007 x1000
truncate_breakfor_enumerate_memoryalloc long ..0.035 ms 0.038 ms ±0.004 x1000
Both of these versions should do perfectly fine for any purposes. | {
"domain": "codereview.stackexchange",
"id": 43550,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, strings, nim",
"url": null
} |
python
Title: Find the column number in a spreadsheet according to the letter that identifies it
Question: Google Sheets maintains an identity for each column that follows this pattern:
col 1 = A
col 26 = Z
col 27 = AA
col 52 = AZ
To know the column number according to the id I do it like this:
import itertools
import string
col_values = 'AA'
def col_letter_to_num(col, col_abs=False) -> int:
col_num = col
if col_num < 0:
return None
col_num += 1
col_str = ''
col_abs = '$' if col_abs else ''
while col_num:
remainder = col_num % 26
if remainder == 0:
remainder = 26
col_letter = chr(ord('A') + remainder - 1)
col_str = col_letter + col_str
col_num = int((col_num - 1) / 26)
return col_abs + col_str
if isinstance(col_values, int):
col_num = col_values
elif isinstance(col_values, str) and not any(x in col_values for x in list(string.digits)):
for i in itertools.count(start=0):
if col_letter_to_num(i) == col_values:
col_num = i+1
break
else:
col_num = 'ERROR'
print(col_num)
I brought the code for review in order to learn to discover the most correct and professional methods to reach the same result. | {
"domain": "codereview.stackexchange",
"id": 43551,
"lm_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",
"url": null
} |
python
Answer: Your first -> int is inaccurate since you sometimes return None; so that should be -> Optional[int]. However: don't return None. Raise a ValueError.
col_letter_to_num, first of all, has a lie as its name. It doesn't convert column letters to a column number; it does the opposite. As written it's backwards and should entirely go away, and rather than your for i in count() that attempts every index until there's a match, just find the index directly by doing math on the given string.
Producing the string 'ERROR' is a bad idea. Raise an exception if there's a data problem.
The behaviour of using isinstance(int) to default to a no-op suggests a problem elsewhere in the code where you don't actually know what kind of variable you're holding. This is a hidden problem and a code smell. Do not apply this default. Elsewhere in the code, it should be well-defined enough that you always know that you're holding a string when you need one. In your function, require that the argument is a string.
Your not any validation can be greatly simplified: instead of looping through a generator and checking each character's membership in digits, just check for isalpha() on the entire string.
Suggested
def col_letter_to_num(col_values: str) -> int:
if not isinstance(col_values, str):
raise TypeError(f'col_values must be a str, got {type(col_values).__name__}')
if not col_values.isalpha():
raise ValueError(f'col_values must be alphabetic, got {col_values}')
col_num = 0
for c in col_values:
col_num = col_num*26 + 1 + ord(c.upper()) - ord('A')
return col_num
def main() -> None:
for example in (
'A', 'Z', 'AA', 'AZ', 'ba', 'BIG',
):
print(f'col {col_letter_to_num(example)} = {example}')
for bad in ('A5', 83):
try:
col_letter_to_num(bad)
except Exception as e:
print(e)
if __name__ == '__main__':
main() | {
"domain": "codereview.stackexchange",
"id": 43551,
"lm_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",
"url": null
} |
python
if __name__ == '__main__':
main()
Output
col 1 = A
col 26 = Z
col 27 = AA
col 52 = AZ
col 53 = ba
col 1593 = BIG
col_values must be alphabetic, got A5
col_values must be a str, got int | {
"domain": "codereview.stackexchange",
"id": 43551,
"lm_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",
"url": null
} |
python, performance, image, object-detection
Title: Matching corresponding masks of objects between 2 images
Question: Here is a program that processes 2 grayscale images. Both represent the position of objects, in the form of multiple masks per image. Each mask is a shape with one color delimiting it, with 0 (or black) for the background. Each object uses the color available in order when created, so if there are n object, the color from 1 to n are used.
The first image is the result of an AI prediction, while the second is estimated by a user. I want to match objetcs between the 2 images, since numbering is not done in the same order in both. I thus matched the objects, in one of three categories :
no match
exactly one match
more than one match
This is done by first extracting a boolean image of the position for each mask, storing them in 2 lists, and summing (equivalent to and in bool) each combinaition to see if they overlap. I don't have multiple matches in this exemple, but there are in other cases. For exactly 1-1 match, I do the numbering again for img_2, by matching it with what is stored in one.
The code is working as intended, but it is a bit slow when the image size gets bigger, and especially when the number of objects gets higher. The matching part is the main culprit, since its complexity is O(n²). It takes about 2min for images with 250 objects (is it possible to share those? I can't create them in the code as I did here), and it is most likely the upper bound of what I'll encounter.
My question is : is it possible to reduce the complexity of the matching part of my code ?
Any feedback on the rest of code is also welcomed, although not my main concern.
import numpy as np
import matplotlib.pyplot as plt | {
"domain": "codereview.stackexchange",
"id": 43552,
"lm_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, image, object-detection",
"url": null
} |
python, performance, image, object-detection
### Creating both sample images
img_1 = np.array([[0]*27+[1]*22+[0]*10,
[0]*27+[1]*22+[0]*10,
[0]*27+[1]*22+[0]*10,
[0]*28+[1]*20+[0]*11,
[0]*28+[1]*20+[0]*11,
[0]*29+[1]*18+[0]*12,
[0]*29+[1]*18+[0]*12,
[0]*30+[1]*16+[0]*13,
[0]*12+[3]*2+[0]*18+[1]*12+[0]*15,
[0]*11+[3]*4+[0]*19+[1]*8+[0]*17,
[0]*10+[3]*6+[0]*43,
[0]*10+[3]*6+[0]*43,
[0]*10+[3]*6+[0]*43,
[0]*11+[3]*4+[0]*44,
[0]*59,
[0]*59,
[0]*59,
[0]*59,
[0]*59,
[0]*59,
[0]*59,
[0]*59,
[0]*59,
[0]*59,
[0]*59,
[0]*59,
[0]*59,
[0]*59,
[0]*59,
[0]*12+[2]*2+[0]*45,
[0]*10+[2]*6+[0]*43,
[0]*8+[2]*10+[0]*41,
[0]*7+[2]*12+[0]*40,
[0]*5+[2]*16+[0]*38,
[0]*4+[2]*18+[0]*37,
[0]*3+[2]*20+[0]*36,
[0]*3+[2]*20+[0]*36,
[0]*3+[2]*20+[0]*36,
[0]*3+[2]*20+[0]*36,
[0]*3+[2]*20+[0]*36,
[0]*3+[2]*20+[0]*36,
[0]*3+[2]*20+[0]*36,
[0]*3+[2]*20+[0]*36,
[0]*3+[2]*20+[0]*36,
[0]*3+[2]*20+[0]*36,
[0]*3+[2]*20+[0]*36,
[0]*3+[2]*20+[0]*36,
[0]*4+[2]*18+[0]*37,
[0]*5+[2]*16+[0]*38,
[0]*7+[2]*12+[0]*40,
[0]*8+[2]*10+[0]*41,
[0]*10+[2]*6+[0]*43,
[0]*11+[2]*4+[0]*44,
[0]*59, | {
"domain": "codereview.stackexchange",
"id": 43552,
"lm_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, image, object-detection",
"url": null
} |
python, performance, image, object-detection
[0]*11+[2]*4+[0]*44,
[0]*59,
[0]*59],dtype=np.int32) | {
"domain": "codereview.stackexchange",
"id": 43552,
"lm_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, image, object-detection",
"url": null
} |
python, performance, image, object-detection
img_2 = np.array([[0]*24+[3]*23+[0]*12,
[0]*23+[3]*25+[0]*11,
[0]*23+[3]*25+[0]*11,
[0]*21+[2]*2+[3]*25+[0]*11,
[0]*20+[2]*3+[3]*25+[0]*11,
[0]*19+[2]*4+[3]*25+[0]*11,
[0]*18+[2]*5+[3]*25+[0]*11,
[0]*18+[2]*6+[3]*23+[0]*12,
[0]*18+[2]*6+[3]*23+[0]*12,
[0]*18+[2]*7+[3]*21+[0]*13,
[0]*19+[2]*7+[3]*19+[0]*14,
[0]*20+[2]*7+[3]*17+[0]*15,
[0]*21+[2]*5+[0]*3+[3]*13+[0]*17,
[0]*32+[3]*7+[0]*20,
[0]*59,
[0]*59,
[0]*59,
[0]*59,
[0]*59,
[0]*59,
[0]*59,
[0]*59,
[0]*59,
[0]*59,
[0]*13+[1]*3+[0]*43,
[0]*11+[1]*6+[0]*42,
[0]*9+[1]*10+[0]*40,
[0]*8+[1]*12+[0]*39,
[0]*6+[1]*16+[0]*37,
[0]*4+[1]*20+[0]*35,
[0]*3+[1]*22+[0]*34,
[0]*2+[1]*24+[0]*33,
[0]*2+[1]*24+[0]*33,
[0]*2+[1]*24+[0]*33,
[0]*2+[1]*24+[0]*33,
[0]*2+[1]*24+[0]*33,
[0]*2+[1]*24+[0]*33,
[0]*2+[1]*24+[0]*33,
[0]*2+[1]*24+[0]*33,
[0]*2+[1]*24+[0]*33,
[0]*2+[1]*24+[0]*33,
[0]*2+[1]*24+[0]*33,
[0]*2+[1]*24+[0]*33,
[0]*2+[1]*24+[0]*33,
[0]*2+[1]*24+[0]*33,
[0]*3+[1]*22+[0]*34,
[0]*4+[1]*20+[0]*35,
[0]*6+[1]*16+[0]*37,
[0]*7+[1]*14+[0]*38,
[0]*9+[1]*10+[0]*40,
[0]*11+[1]*6+[0]*42,
[0]*12+[1]*4+[0]*43, | {
"domain": "codereview.stackexchange",
"id": 43552,
"lm_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, image, object-detection",
"url": null
} |
python, performance, image, object-detection
[0]*11+[1]*6+[0]*42,
[0]*12+[1]*4+[0]*43,
[0]*59,
[0]*59,
[0]*59],dtype=np.int32) | {
"domain": "codereview.stackexchange",
"id": 43552,
"lm_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, image, object-detection",
"url": null
} |
python, performance, image, object-detection
### Side to side images
print("Number of items predicted in img_1 :",len(np.unique(img_1)))
print("Number of items in ground-truth, img_2 :",len(np.unique(img_2)))
plt.figure(0)
plt.subplot(1,2,1), plt.imshow(img_1)
plt.axis("off")
plt.subplot(1,2,2), plt.imshow(img_2)
plt.axis("off")
### Creating one boolean image for each mask
masks_1 = []
masks_2 = []
leng = max(len(np.unique(img_1)), len(np.unique(img_2)))
for k in range(1,leng):
mask_1 = img_1==k
masks_1.append(mask_1)
mask_2 = img_2==k
masks_2.append(mask_2)
### Each possible combination, from img_1 compared to img_2, and the opposite
zero=[] # No match from img_1 to img_2
one={} # Exactly one match from img_1 to img_2
more={} # More than one match from img_1 to img_2
zero_2=[] # Same as zero but from img_2 to img_1
one_2={} # Same as one but from img_2 to img_1
more_2={} # Same as more but from img_2 to img_1
for i in range(leng-1):
number_match = 0
number_match_2 = 0
index_match = []
index_match_2 = []
### Checks if there are pixels in common in both images, and the total number
for j in range(leng-1):
if not (sum(sum(masks_1[i]*masks_2[j]))==0):
number_match += 1
index_match.append(j)
if not (sum(sum(masks_2[i]*masks_1[j]))==0):
number_match_2 += 1
index_match_2.append(j)
### Sorts each index depending on the number of match
if number_match==0:
zero.append(i)
elif number_match>1:
more[i] = index_match
elif number_match==1:
one[i] = index_match[0]
if number_match_2==0:
zero_2.append(i)
elif number_match_2>1:
more_2[i] = index_match_2
elif number_match_2==1:
one_2[i] = index_match_2[0] | {
"domain": "codereview.stackexchange",
"id": 43552,
"lm_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, image, object-detection",
"url": null
} |
python, performance, image, object-detection
### Remove pairs if it's not a 1-1 match
temp = []
for m in one.keys():
if one_2.get(one[m]) is None:
if more_2.get(one[m]) is None:
zero_2.append(one[m])
zero.append(m)
temp.append(m)
else:
more.update({m:one[m]})
temp.append(m)
for k in range(len(temp)):
del one[temp[k]]
temp = []
for n in one_2.keys():
if one.get(one_2[n]) is None:
if more.get(one_2[n]) is None:
zero.append(one_2[n])
zero_2.append(n)
temp.append(n)
else:
more_2.update({n:one_2[n]})
temp.append(n)
for k in range(len(temp)):
del one_2[temp[k]]
### Second pair of image, with all 1-1 match
xSize, ySize = np.shape(img_1)
img_1 = np.zeros((xSize,ySize),dtype=np.int32)
img_2 = np.zeros((xSize,ySize),dtype=np.int32)
if bool(one):
lis = list(one.keys())
for m in range(len(lis)):
img_1 = img_1+(masks_1[lis[m]])*(lis[m]+1)
if bool(one_2):
lis2 = list(one_2.keys())
for n in range(len(lis2)):
img_2 = img_2+(masks_2[lis2[n]])*(one_2[lis2[n]]+1)
plt.figure(1)
plt.subplot(1,2,1), plt.imshow(img_1)
plt.axis("off")
plt.subplot(1,2,2), plt.imshow(img_2)
plt.axis("off")
Answer: This:
summing (equivalent to and in bool)
is untrue. "And" is equivalent to multiplication.
As for your code:
Move all of your code out of the global namespace into functions, and hint their signatures with PEP484 types.
Increase vectorisation by holding your images in one array with an outer dimension of 2.
These prints:
print("Number of items predicted in img_1 :", len(np.unique(img_1)))
print("Number of items in ground-truth, img_2 :", len(np.unique(img_2))) | {
"domain": "codereview.stackexchange",
"id": 43552,
"lm_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, image, object-detection",
"url": null
} |
python, performance, image, object-detection
do not seem accurate, because you include the background (0). You should probably exclude this.
Rather than implicit axis references with plt., prefer explicit axis object references, such as ax.imshow().
Do not hold masks_x as lists; instead hold them as one np.ndarray.
Combine zero and zero_2 into one tuple of two lists, and similar for one and more.
This loop:
for i in range(leng - 1):
though it doesn't say so due to a poor variable name, is actually looping through colours ("items" in your parlance). But why are you using a range? Why not actually iterate through the colour values themselves? This will relieve your code from needing to assume that your colours are contiguous integers.
Don't not sum(sum(x * y)) == 0. This is really just an np.any() on an np.logical_and over the proper dimensions.
Change this loop:
for m in one.keys():
so that it's calling .items() instead of .keys(), so that you can use the value from it instead of re(re-re-re)-writing one[m].
Do not write if one_2.get(one[m]) is None; instead write if one[m] not in one_2.
Have you tested this?
for k in range(len(temp)):
del one[temp[k]]
Your current test data do not exercise this path, and I believe it will fail because you're deleting by index from front to back, when you need to delete from back to front. Also don't iterate over a range; just iterate over the values of temp.
if bool(one): and similar can be entirely deleted because your later for loop, if one is empty, will already be a no-op. Even if you didn't delete it, bool() is unnecessary because the collection is already truthy.
You should really add titles to your figures.
Suggested
Basically equivalent in my limited testing.
import numpy as np
import matplotlib.pyplot as plt
def make_samples() -> np.ndarray: # 2x55x59
samples = np.empty((2, 55, 59), dtype=np.int32) | {
"domain": "codereview.stackexchange",
"id": 43552,
"lm_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, image, object-detection",
"url": null
} |
python, performance, image, object-detection
samples[0, ...] = [[0] * 27 + [1] * 22 + [0] * 10,
[0] * 27 + [1] * 22 + [0] * 10,
[0] * 27 + [1] * 22 + [0] * 10,
[0] * 28 + [1] * 20 + [0] * 11,
[0] * 28 + [1] * 20 + [0] * 11,
[0] * 29 + [1] * 18 + [0] * 12,
[0] * 29 + [1] * 18 + [0] * 12,
[0] * 30 + [1] * 16 + [0] * 13,
[0] * 12 + [3] * 2 + [0] * 18 + [1] * 12 + [0] * 15,
[0] * 11 + [3] * 4 + [0] * 19 + [1] * 8 + [0] * 17,
[0] * 10 + [3] * 6 + [0] * 43,
[0] * 10 + [3] * 6 + [0] * 43,
[0] * 10 + [3] * 6 + [0] * 43,
[0] * 11 + [3] * 4 + [0] * 44,
[0] * 59,
[0] * 59,
[0] * 59,
[0] * 59,
[0] * 59,
[0] * 59,
[0] * 59,
[0] * 59,
[0] * 59,
[0] * 59,
[0] * 59,
[0] * 59,
[0] * 59,
[0] * 59,
[0] * 59,
[0] * 12 + [2] * 2 + [0] * 45,
[0] * 10 + [2] * 6 + [0] * 43,
[0] * 8 + [2] * 10 + [0] * 41,
[0] * 7 + [2] * 12 + [0] * 40,
[0] * 5 + [2] * 16 + [0] * 38,
[0] * 4 + [2] * 18 + [0] * 37,
[0] * 3 + [2] * 20 + [0] * 36,
[0] * 3 + [2] * 20 + [0] * 36,
[0] * 3 + [2] * 20 + [0] * 36,
[0] * 3 + [2] * 20 + [0] * 36,
[0] * 3 + [2] * 20 + [0] * 36,
[0] * 3 + [2] * 20 + [0] * 36,
[0] * 3 + [2] * 20 + [0] * 36, | {
"domain": "codereview.stackexchange",
"id": 43552,
"lm_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, image, object-detection",
"url": null
} |
python, performance, image, object-detection
[0] * 3 + [2] * 20 + [0] * 36,
[0] * 3 + [2] * 20 + [0] * 36,
[0] * 3 + [2] * 20 + [0] * 36,
[0] * 3 + [2] * 20 + [0] * 36,
[0] * 3 + [2] * 20 + [0] * 36,
[0] * 3 + [2] * 20 + [0] * 36,
[0] * 4 + [2] * 18 + [0] * 37,
[0] * 5 + [2] * 16 + [0] * 38,
[0] * 7 + [2] * 12 + [0] * 40,
[0] * 8 + [2] * 10 + [0] * 41,
[0] * 10 + [2] * 6 + [0] * 43,
[0] * 11 + [2] * 4 + [0] * 44,
[0] * 59,
[0] * 59] | {
"domain": "codereview.stackexchange",
"id": 43552,
"lm_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, image, object-detection",
"url": null
} |
python, performance, image, object-detection
samples[1, ...] = [[0] * 24 + [3] * 23 + [0] * 12,
[0] * 23 + [3] * 25 + [0] * 11,
[0] * 23 + [3] * 25 + [0] * 11,
[0] * 21 + [2] * 2 + [3] * 25 + [0] * 11,
[0] * 20 + [2] * 3 + [3] * 25 + [0] * 11,
[0] * 19 + [2] * 4 + [3] * 25 + [0] * 11,
[0] * 18 + [2] * 5 + [3] * 25 + [0] * 11,
[0] * 18 + [2] * 6 + [3] * 23 + [0] * 12,
[0] * 18 + [2] * 6 + [3] * 23 + [0] * 12,
[0] * 18 + [2] * 7 + [3] * 21 + [0] * 13,
[0] * 19 + [2] * 7 + [3] * 19 + [0] * 14,
[0] * 20 + [2] * 7 + [3] * 17 + [0] * 15,
[0] * 21 + [2] * 5 + [0] * 3 + [3] * 13 + [0] * 17,
[0] * 32 + [3] * 7 + [0] * 20,
[0] * 59,
[0] * 59,
[0] * 59,
[0] * 59,
[0] * 59,
[0] * 59,
[0] * 59,
[0] * 59,
[0] * 59,
[0] * 59,
[0] * 13 + [1] * 3 + [0] * 43,
[0] * 11 + [1] * 6 + [0] * 42,
[0] * 9 + [1] * 10 + [0] * 40,
[0] * 8 + [1] * 12 + [0] * 39,
[0] * 6 + [1] * 16 + [0] * 37,
[0] * 4 + [1] * 20 + [0] * 35,
[0] * 3 + [1] * 22 + [0] * 34,
[0] * 2 + [1] * 24 + [0] * 33,
[0] * 2 + [1] * 24 + [0] * 33,
[0] * 2 + [1] * 24 + [0] * 33,
[0] * 2 + [1] * 24 + [0] * 33,
[0] * 2 + [1] * 24 + [0] * 33,
[0] * 2 + [1] * 24 + [0] * 33,
[0] * 2 + [1] * 24 + [0] * 33,
[0] * 2 + [1] * 24 + [0] * 33, | {
"domain": "codereview.stackexchange",
"id": 43552,
"lm_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, image, object-detection",
"url": null
} |
python, performance, image, object-detection
[0] * 2 + [1] * 24 + [0] * 33,
[0] * 2 + [1] * 24 + [0] * 33,
[0] * 2 + [1] * 24 + [0] * 33,
[0] * 2 + [1] * 24 + [0] * 33,
[0] * 2 + [1] * 24 + [0] * 33,
[0] * 2 + [1] * 24 + [0] * 33,
[0] * 2 + [1] * 24 + [0] * 33,
[0] * 3 + [1] * 22 + [0] * 34,
[0] * 4 + [1] * 20 + [0] * 35,
[0] * 6 + [1] * 16 + [0] * 37,
[0] * 7 + [1] * 14 + [0] * 38,
[0] * 9 + [1] * 10 + [0] * 40,
[0] * 11 + [1] * 6 + [0] * 42,
[0] * 12 + [1] * 4 + [0] * 43,
[0] * 59,
[0] * 59,
[0] * 59] | {
"domain": "codereview.stackexchange",
"id": 43552,
"lm_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, image, object-detection",
"url": null
} |
python, performance, image, object-detection
return samples
def get_unique(before_images: np.ndarray) -> np.ndarray: # one-dimensional (3)
img_1, img_2 = before_images
items_1 = np.unique(img_1)
items_2 = np.unique(img_2)
items = np.unique(before_images)
# exclude background
items_1 = items_1[items_1.nonzero()]
items_2 = items_2[items_2.nonzero()]
items = items[items.nonzero()]
print('Number of items:')
print(" img_1, predicted:", items_1.size)
print(" img_2, ground-truth:", items_2.size)
print(" shared:", items.size)
return items
def make_masks(
before_images: np.ndarray, # 2 x 55 x 59
items: np.ndarray, # one-dimensional (3)
) -> np.ndarray: # 3 x 2 x 55 x 59
"""Creating one boolean image for each mask"""
# item * left/right * height * width
k = np.expand_dims(items, (1, 2, 3))
return before_images[np.newaxis, ...] == k
def make_combinations(
items: np.ndarray, # one-dimensional (3)
masks: np.ndarray, # 3 x 2 x 55 x 59
) -> tuple[
tuple[list[int], ...], # zeros
tuple[dict[int, int], ...], # ones
tuple[dict, ...], # more
]:
"""Each possible combination, from img_1 compared to img_2, and the opposite"""
zeros = [], [] # No match from image to image
ones = {}, {} # Exactly one match from image to image
mores = {}, {} # More than one match from image to image
for masks_a, item_a in zip(masks, items):
for i_image, (zero, one, more) in enumerate(zip(
zeros, ones, mores,
)):
number_match = 0
index_match = []
# Checks if there are pixels in common in both images, and the total number
for masks_b, item_b in zip(masks, items):
if np.any(np.logical_and(masks_a[i_image, ...], masks_b[1 - i_image, ...])):
number_match += 1
index_match.append(item_b) | {
"domain": "codereview.stackexchange",
"id": 43552,
"lm_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, image, object-detection",
"url": null
} |
python, performance, image, object-detection
# Sorts each index depending on the number of match
if number_match == 0:
zero.append(item_a)
elif number_match == 1:
one[item_a] = index_match[0]
elif number_match > 1:
more[item_a] = index_match
return zeros, ones, mores
def remove_pairs(
zeros: tuple[list[int], ...],
ones: tuple[dict[int, int], ...],
more: tuple[dict, ...],
) -> None:
"""Remove pairs if it's not a 1-1 match"""
for direction in (1, -1):
this_zero, other_zero = zeros[::direction]
this_one, other_one = ones[::direction]
this_more, other_more = more[::direction]
to_remove = []
for one_key, one_val in this_one.items():
if one_val not in other_one:
if one_val in other_more:
this_more[one_key] = one_val
else:
other_zero.append(one_val)
this_zero.append(one_key)
to_remove.append(one_key)
for t in sorted(to_remove, reverse=True):
del this_one[t]
def make_new_pair(
ones: tuple[dict[int, int], ...],
items: np.ndarray,
masks: np.ndarray,
) -> np.ndarray:
"""Second pair of image, with all 1-1 match"""
item_indices = dict(np.stack((items, np.arange(items.size))).T)
coefficients = np.zeros((*masks.shape[:2], 1, 1), dtype=np.int32) # 3x2x1x1
one, one_2 = ones
for item in one.keys():
coefficients[item_indices[item], 0, ...] = 1 + item
for item, count in one_2.items():
coefficients[item_indices[item], 1, ...] = 1 + count
return (masks*coefficients).sum(axis=0)
def show(images: np.ndarray, title: str) -> plt.Figure:
"""Side to side images"""
fig, axes = plt.subplots(nrows=1, ncols=images.shape[0])
fig.suptitle(title)
for axis, image in zip(axes, images):
axis.imshow(image)
axis.axis('off')
return fig | {
"domain": "codereview.stackexchange",
"id": 43552,
"lm_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, image, object-detection",
"url": null
} |
python, performance, image, object-detection
return fig
def main() -> None:
before_images = make_samples()
show(before_images, 'Before matching')
items = get_unique(before_images)
masks = make_masks(before_images, items)
zeros, ones, more = make_combinations(items, masks)
remove_pairs(zeros, ones, more)
after_images = make_new_pair(ones, items, masks)
show(after_images, 'After matching')
plt.show()
if __name__ == '__main__':
main()
Output
Number of items:
img_1, predicted: 3
img_2, ground-truth: 3
shared: 3
Simplification
is it possible to reduce the complexity of the matching part of my code ?
Yes, extremely. I think the algorithm may have been overthought. For example, you go through the trouble of building a zero collection but then never use it. This really boils down to
find the subset of pixel coordinates for which both the left and right images have foreground (are non-zero);
reduce to a map from left value to right value at those coordinates;
apply the map; and
demote to background anything not in the map.
The results are the same:
def main() -> None:
images = make_samples()
show(images, 'Before matching')
both_foreground = np.logical_and.reduce(images, axis=0)
mapping = np.unique(images[:, both_foreground], axis=1)
# Substitution routine loosely inspired by https://stackoverflow.com/questions/3403973
v, k = mapping
sparse_map = np.zeros(k.max() + 1, dtype=np.int32)
sparse_map[k] = v
images[1, ...] = sparse_map[images[1, ...]]
images[~np.isin(images, mapping[0, :])] = 0
show(images, 'After matching')
plt.show() | {
"domain": "codereview.stackexchange",
"id": 43552,
"lm_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, image, object-detection",
"url": null
} |
php, pdo
Title: Is this PDO query okay to use in PHP OOP?
Question: Do you think this code is good if I want to do a simple SQL query? Is it safe to use? Or am I doing something wrong?
class DBconnection {
private $dbusername = "testtest";
private $dbpassword = "testtest";
protected $conn;
public function __construct(){
try {
$this->conn = new PDO("mysql:host=localhost;dbname=yxy_user;charset=utf8", $this->dbusername, $this->dbpassword);
// set the PDO error mode to exception
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
error_log("Failed to connect to database!", 0);
}
}
}
class Query extends DBconnection {
public function FetchQuery($query, $params) {
$stmt = $this->conn->prepare($query);
$stmt->execute($params);
$result_query_fetch = $stmt->fetch(PDO::FETCH_ASSOC);
if($result_query_fetch) {
return $result_query_fetch;
}
else {
return false;
}
}
}
$Query_Class = new Query;
$myResult = $Query_Class->FetchQuery("SELECT name
FROM customers
WHERE id =:id",
array(":id" => "12345"));
if($myResult){
print_r ($myResult);
}
else {
echo "No results!";
}
Answer: Nope, this "PDO query" is NOT okay, especially "to use in PHP OOP".
The Database class does nothing useful, and shouldn't exist.
The Query class should never extend the Database class, because a query is not a database.
The code at whole is just an attempt to create a single procedure FetchQuery() - so you have to do exactly that:
db_credentials.php
<?php
$dbhost = 'localhost';
$dbname = 'yxy_user';
$dbusername = '';
$dbpassword = ''; | {
"domain": "codereview.stackexchange",
"id": 43553,
"lm_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, pdo",
"url": null
} |
php, pdo
db.php
<?php
require 'db_credentials.php';
$pdo = new PDO("mysql:host=$dbhost;dbname=$dbname;charset=utf8mb4", $dbusername, $dbpassword);
// set the PDO error mode to exception
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
function pdo($pdo, $sql, $args = NULL)
{
$stmt = $pdo->prepare($sql);
$stmt->execute($args);
return $stmt;
}
and then use it elsewhere
<?php
require 'db.php';
$sql = "SELECT name FROM customers WHERE id =:id";
$myResult = pdo($sql,[":id" => "12345"])->fetch(PDO::FETCH_ASSOC);
if($myResult){
print_r ($myResult);
}
else {
echo "No results!";
}
Note that this function returns the PDOStatement instance, which makes it extremely convenient and universal, you can see usage examples in this answer.
As of OOP, it is not an easy topic. There is a lot to learn. But above all, there must be a clear purpose for the class. For the moment I just don't see any use for the classes provided. But if you have other ideas or use cases for your database classes, you can post another question. | {
"domain": "codereview.stackexchange",
"id": 43553,
"lm_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, pdo",
"url": null
} |
javascript, datetime, validation
Title: JS function to check if a date is in the correct format
Question: I wrote the following JS function to check if a date comes in the right format and can be used further down in the application
const getInvalidDay = day => {
const date = new Date(day);
const dateToMoments = [date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds(), date.getUTCMilliseconds()];
return dateToMoments.some(moment => moment !== 0);
};
An example snippet to see how it works
const getInvalidDay = day => {
const date = new Date(day);
const dateToMoments = [date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds(), date.getUTCMilliseconds()];
return dateToMoments.some(moment => moment !== 0);
};
console.log('Should be true - not valid::: ', getInvalidDay('2021-03-16T09:00:00.000Z'));
console.log('Should be false - is valid::: ', getInvalidDay('2021-03-16'));
When we have all moments as 0 means the date is valid so we return false
instead, if some have !==0 then it is true and the date is not valid
I was wondering if there is another way to achieve the same result
Answer: An invalid date will be recognized by the Date object, as you can see here.
console.log('invalid date: ', new Date('hello world').toString());
console.log('valid date: ', new Date('2022-07-03T12:55:10.176Z').toString());
MDN documentation states:
Calling new Date() (the Date() constructor) returns a Date object. If called with an invalid date string, or if the date to be constructed will have a UNIX timestamp less than -8,640,000,000,000,000 or greater than 8,640,000,000,000,000 milliseconds, it returns a Date object whose toString() method returns the literal string Invalid Date.
So by definition you could check if a date is invalid by simply doing:
console.log(new Date('hello world').toString() === "Invalid Date")
Another option is to check the date instance passed to isNaN as indicated in this SO answer. | {
"domain": "codereview.stackexchange",
"id": 43554,
"lm_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, datetime, validation",
"url": null
} |
javascript, datetime, validation
Another option is to check the date instance passed to isNaN as indicated in this SO answer.
console.log('is valid: ', !isNaN(new Date('hello world')));
console.log('is valid: ', !isNaN(new Date())); | {
"domain": "codereview.stackexchange",
"id": 43554,
"lm_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, datetime, validation",
"url": null
} |
python, pandas, multiprocessing
Title: Treat a list by generating a dataframe and sending the data to function via multiprocessing
Question: To collect the list with the data from an API, I need to do these steps:
trading = betfairlightweight.APIClient(
'email',
'password',
app_key='app_key',
cert_files=('./certs/bf.pem'),
session=requests.Session()
)
trading.login()
hours_limit = 12
limit_hour = (datetime.datetime.utcnow() + datetime.timedelta(hours=hours_limit))
market_filter = betfairlightweight.filters.market_filter(
event_type_ids=['1'],
market_type_codes = [
'MATCH_ODDS',
'OVER_UNDER_25'
],
market_start_time={
'to': limit_hour.strftime("%Y-%m-%dT%H:%M:%SZ")
}
)
soccer_events = trading.betting.list_events(
filter=market_filter
)
Output soccer_events:
[<EventResult>, <EventResult>, ...]
Using:
def pretty_print(clas, indent=0):
print(' ' * indent + type(clas).__name__ + ':')
indent += 4
for k,v in clas.__dict__.items():
if '__dict__' in dir(v):
pretty_print(v,indent)
else:
print(' ' * indent + k + ': ' + str(v))
The output pretty_print(soccer_events[0]):
EventResult:
elapsed_time: 0.3472568988800049
_datetime_created: 2022-07-03 16:01:07.401756
_datetime_updated: 2022-07-03 16:01:07.401756
_data: {'event': {'id': '31569381', 'name': 'Bayamon FC v Puerto Rico Sol FC', 'countryCode': 'GB', 'timezone': 'GMT', 'openDate': '2022-07-03T23:30:00.000Z'}, 'marketCount': 2}
market_count: 2
Event:
id: 31569381
open_date: 2022-07-03 23:30:00
time_zone: GMT
country_code: GB
name: Bayamon FC v Puerto Rico Sol FC
venue: None | {
"domain": "codereview.stackexchange",
"id": 43555,
"lm_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, pandas, multiprocessing",
"url": null
} |
python, pandas, multiprocessing
With this list produced I generate a DataFrame to handle this data:
soccer_events_df = pd.DataFrame({
'event_name': [obj_event.event.name for obj_event in soccer_events],
'event_id': [obj_event.event.id for obj_event in soccer_events],
'event_venue': [obj_event.event.venue for obj_event in soccer_events],
'country_code': [obj_event.event.country_code for obj_event in soccer_events],
'time_zone': [obj_event.event.time_zone for obj_event in soccer_events],
'open_date': [obj_event.event.open_date for obj_event in soccer_events],
'market_count': [obj_event.market_count for obj_event in soccer_events],
'open_local_date': [obj_event.event.open_date.replace(tzinfo=datetime.timezone.utc).astimezone(tz=None)
for obj_event in soccer_events]
}) | {
"domain": "codereview.stackexchange",
"id": 43555,
"lm_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, pandas, multiprocessing",
"url": null
} |
python, pandas, multiprocessing
Output:
event_name event_id event_venue country_code time_zone open_date market_count open_local_date
0 FC LaPa v PKK-U 31566562 None FI GMT 2022-07-03 13:00:00 2 2022-07-03 10:00:00-03:00
1 BFA Vilnius v FK Banga II 31566818 None LT GMT 2022-07-03 14:00:00 2 2022-07-03 11:00:00-03:00
2 Varbergs BoIS v Varnamo 31540709 None SE GMT 2022-07-03 13:00:00 2 2022-07-03 10:00:00-03:00
3 Bayamon FC v Puerto Rico Sol FC 31569381 None GB GMT 2022-07-03 23:30:00 2 2022-07-03 20:30:00-03:00
4 Norrkoping v Sirius 31540708 None SE GMT 2022-07-03 15:30:00 2 2022-07-03 12:30:00-03:00
.. ... ... ... ... ... ... ... ...
175 Werder Bremen v Karlsruhe 31566873 None None GMT 2022-07-03 13:30:00 2 2022-07-03 10:30:00-03:00
176 San Martin de Formosa v CA Douglas Haig 31566616 None AR GMT 2022-07-03 19:00:00 2 2022-07-03 16:00:00-03:00
177 Club Defensores de P v Sarmiento de Resistencia 31566619 None AR GMT 2022-07-03 18:00:00 2 2022-07-03 15:00:00-03:00
178 Sportivo AC Las Parejas v CD Juventud Unida (G) 31566621 None AR GMT 2022-07-03 19:30:00 2 2022-07-03 16:30:00-03:00
179 CA Liniers v Camioneros 31566623 None AR GMT 2022-07-03 18:00:00 2 2022-07-03 15:00:00-03:00 | {
"domain": "codereview.stackexchange",
"id": 43555,
"lm_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, pandas, multiprocessing",
"url": null
} |
python, pandas, multiprocessing
As there are many games listed, to do what I need with each of them, I need multiprocessing, which before starting them I go through some filters:
events_bf = soccer_events_df.reset_index()
if len(events_bf) == 0:
trading.logout()
sys.exit()
events_bf = events_bf[events_bf['event_name'].str.contains(" v ")]
data_for_compare = (datetime.datetime.utcnow()).strftime("%Y-%m-%d %H:%M")
events_bf = events_bf[events_bf['open_date'] >= data_for_compare]
events_bf = events_bf[events_bf['open_date'] <= limit_hour.strftime("%Y-%m-%d %H:%M")]
try:
max_process = multiprocessing.cpu_count()-1 or 1
pool = multiprocessing.Pool(max_process)
list_pool = pool.map(data_event, zip(repeat(trading), events_bf.iterrows()))
finally:
pool.close()
pool.join()
This is the function used in multiprocessing:
def data_event(event_bf) -> list:
try:
trading = event_bf[0]
_, event_bf = event_bf[1]
event_name = event_bf['event_name']
event_id = event_bf['event_id']
filter_catalog_markets = betfairlightweight.filters.market_filter(
event_ids=[event_id],
market_type_codes = [
'MATCH_ODDS',
'OVER_UNDER_25'
]
)
catalog_markets = trading.betting.list_market_catalogue(
filter=filter_catalog_markets,
max_results='100',
sort='FIRST_TO_START',
market_projection=['RUNNER_METADATA']
) | {
"domain": "codereview.stackexchange",
"id": 43555,
"lm_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, pandas, multiprocessing",
"url": null
} |
python, pandas, multiprocessing
markets_df = pd.DataFrame({
'market_name': [market_cat_object.market_name for market_cat_object in catalog_markets],
'market_id': [market_cat_object.market_id for market_cat_object in catalog_markets],
'total_matched': [market_cat_object.total_matched for market_cat_object in catalog_markets],
'Home' : [market_cat_object.runners[0].runner_name if len(market_cat_object.runners) > 0 else '' for market_cat_object in catalog_markets],
'Home_id' : [market_cat_object.runners[0].selection_id if len(market_cat_object.runners) > 0 else 0 for market_cat_object in catalog_markets],
'Away' : [market_cat_object.runners[1].runner_name if len(market_cat_object.runners) > 1 else '' for market_cat_object in catalog_markets],
'Away_id' : [market_cat_object.runners[1].selection_id if len(market_cat_object.runners) > 1 else 0 for market_cat_object in catalog_markets],
'Draw' : [market_cat_object.runners[2].runner_name if len(market_cat_object.runners) > 2 else '' for market_cat_object in catalog_markets],
'Draw_id' : [market_cat_object.runners[2].selection_id if len(market_cat_object.runners) > 2 else 0 for market_cat_object in catalog_markets]
})
match_odds_list = []
Over_Under_list = []
ids_list = []
events_bf_markets = markets_df.reset_index()
for index, event_bf_market in events_bf_markets.iterrows():
if (event_bf_market['market_name'] == 'Match Odds'):
order_filter = betfairlightweight.filters.ex_best_offers_overrides(
best_prices_depth=3
) | {
"domain": "codereview.stackexchange",
"id": 43555,
"lm_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, pandas, multiprocessing",
"url": null
} |
python, pandas, multiprocessing
price_filter = betfairlightweight.filters.price_projection(
price_data=['EX_BEST_OFFERS'],
ex_best_offers_overrides=order_filter
)
market_books = trading.betting.list_market_book(
market_ids=[event_bf_market['market_id']],
price_projection=price_filter
)
runners = market_books[0].runners
back = []
try:
back.append([runner_book.last_price_traded
if runner_book.last_price_traded
else '-'
for runner_book
in runners])
except:
back.append(['-',"-"])
match_start = event_bf['open_date']
match_start_2 = pd.to_datetime(str(match_start))
match_odds_list.append(match_start_2.strftime('%Y-%m-%dT%H:%M:%SZ'))
match_start_local = event_bf['open_local_date']
match_start_local_2 = pd.to_datetime(str(match_start_local))
match_odds_list.append(match_start_local_2.strftime('%Y-%m-%dT%H:%M:%SZ'))
match_odds_list.append(event_bf_market['Home'] + ' v ' + event_bf_market['Away'])
match_odds_list.append(event_bf_market['Home'])
match_odds_list.append(event_bf_market['Away'])
match_odds_list.append(back[0][0])
match_odds_list.append(back[0][1])
match_odds_list.append(back[0][2])
ids_list.append(event_bf_market['Home_id'])
ids_list.append(event_bf_market['Away_id'])
ids_list.append(event_id) | {
"domain": "codereview.stackexchange",
"id": 43555,
"lm_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, pandas, multiprocessing",
"url": null
} |
python, pandas, multiprocessing
elif (event_bf_market['market_name'] == 'Over/Under 2.5 Goals'):
order_filter = betfairlightweight.filters.ex_best_offers_overrides(
best_prices_depth=3
)
price_filter = betfairlightweight.filters.price_projection(
price_data=['EX_BEST_OFFERS'],
ex_best_offers_overrides=order_filter
)
market_books = trading.betting.list_market_book(
market_ids=[event_bf_market['market_id']],
price_projection=price_filter
)
runners = market_books[0].runners
back = []
try:
back.append([runner_book.last_price_traded
if runner_book.last_price_traded
else '-'
for runner_book
in runners])
except:
back.append(['-'])
Over_Under_list.append(back[0][0])
Over_Under_list.append(back[0][1])
if (len(match_odds_list) >= 1):
return match_odds_list + Over_Under_list + ids_list
else:
return ['off']
except Exception as e:
print(e)
return ['off']
I would like a review on the methods used to treat this list as well as so many list comprehensions together to be able to generate the DataFrame and if the multiprocessing model I'm using is really the most appropriate for such data type.
Answer:
I need multiprocessing | {
"domain": "codereview.stackexchange",
"id": 43555,
"lm_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, pandas, multiprocessing",
"url": null
} |
python, pandas, multiprocessing
Answer:
I need multiprocessing
Do you actually? What is the runtime like with and without it? How many rows are you processing? If this takes (say) less than a second with a reasonable Pandas implementation and no parallel processing, I'd call the added complexity of the multiprocessing call to potentially be a higher cost than the benefit. Perhaps it's necessary due to the list_market_catalogue inner API call.
The field types of EventResult are unclear. Hopefully obj_event.event.open_date is a real datetime and not a string. If it is a string, you need to be telling Pandas to parse that to a datetime.
This is not a good idea:
data_for_compare = (datetime.datetime.utcnow()).strftime("%Y-%m-%d %H:%M")
as you should not be comparing strings when they're actually dates. Again, if open_date has been properly parsed, then you will be comparing datetimes directly instead of as strings.
This:
for index, event_bf_market in events_bf_markets.iterrows():
doesn't take enough advantage of Pandas vectorisation. For instance, within that loop, this if:
if (event_bf_market['market_name'] == 'Match Odds'):
can be split out so that you select that subframe in a vectorised manner, as in
match_odds = event_bf_market[event_bf_market.market_name == 'Match Odds']
# ... operate on this subframe unconditionally
data_event is too long. You should pull out some subroutines. It's also incomplete in its typehints: event_bf needs a type, and list needs a list[contained type].
You call out
so many list comprehensions together to be able to generate the DataFrame
and are right to do so. A certain amount of looping is inevitable because your target leaves are at different depths of the obj_event tree. Consider instead one loop that builds up an intermediate list of flat dictionaries and then call DataFrame.from_records. | {
"domain": "codereview.stackexchange",
"id": 43555,
"lm_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, pandas, multiprocessing",
"url": null
} |
javascript
Title: How to implement a daily streak counter in JavaScript?
Question: I want to implement this in a SQL database schema, but am doing it in JavaScript first to make sure I have the logic right. Basically, I would like to track "actions" a user performs. If they perform a certain amount of actions within a period (a day for now), then they hit the goal for that day. Then if they do this for multiple days in a row, they get a streak. If they skip a day, they lose the streak.
Do I have this implemented correctly? It appears to be working as expected, but I am not 100% sure this is how this type of thing should be implemented. Any suggestions on how to improve the implementation?
const { shiftTimeBy } = require('time-fast-forward')
const dayjs = require('dayjs')
const utc = require('dayjs/plugin/utc')
dayjs.extend(utc)
// 20 days ago
shiftTimeBy(-1 * 20 * 24 * 60 * 60 * 1000);
let startOfDay = dayjs.utc().startOf('day').toDate()
let startOfPreviousDay = dayjs.utc().startOf('day').subtract(1, 'day').toDate()
const actionTrackers = {}
// do action 22 times in a day, but daily goal is only 10
let i = 0
while (i < 22) {
trackAction({ actionId: 'vote', userId: 'bar' })
i++
}
// jump ahead to the next day
shiftTimeBy((1 * 24 * 60 * 60 * 1000) + 220);
startOfDay = dayjs.utc().startOf('day').toDate()
startOfPreviousDay = dayjs.utc().startOf('day').subtract(1, 'day').toDate()
// do action 22 times in a day again, but daily goal is only 10
i = 0
while (i < 22) {
trackAction({ actionId: 'vote', userId: 'bar' })
i++
}
// jump ahead 3 days
shiftTimeBy((3 * 24 * 60 * 60 * 1000) + 220);
startOfDay = dayjs.utc().startOf('day').toDate()
startOfPreviousDay = dayjs.utc().startOf('day').subtract(1, 'day').toDate()
// do action 22 times in a day again, but daily goal is only 10
i = 0
while (i < 22) {
trackAction({ actionId: 'vote', userId: 'bar' })
i++
} | {
"domain": "codereview.stackexchange",
"id": 43556,
"lm_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
function trackAction({ actionId, userId, dailyGoal = 10 }) {
const actionUsersTracker = actionTrackers[actionId] = actionTrackers[actionId] ?? {}
const actionUserTracker = actionUsersTracker[userId] = actionUsersTracker[userId] ?? {}
if (!actionUserTracker.lastDate) {
actionUserTracker.lastDate = new Date
actionUserTracker.actionCount = 1
actionUserTracker.streakCount = 0
} else {
if (actionUserTracker.lastDate < startOfDay) {
if (actionUserTracker.lastDate < startOfPreviousDay) {
actionUserTracker.streakCount = 0
}
actionUserTracker.lastDate = new Date
actionUserTracker.actionCount = 1
} else {
// within same day
actionUserTracker.actionCount++
if (actionUserTracker.actionCount === dailyGoal) {
actionUserTracker.streakCount++
}
}
}
console.log(actionUserTracker)
}
The time manipulation library is there to simulate a test where time passes and we perform the action at different points in time.
Answer: First of all, I would separate the code from the actual tracker and the testing code.
Your code would also benefit from avoiding the use of
"Magic Numbers".
I would also just save the date of action for every time a user is
making an action.
You should note that I haven't tested the code, and wrote it to make an example of
how I would create the basic logic. It probably won't work without modifying it to suit your needs.
First, let's create some objects that may represent our DB and basic insert logic:
const usersDB = [
{
uid: "uid_1",
username: "Chris",
email: "chris@g.com"
}
]; | {
"domain": "codereview.stackexchange",
"id": 43556,
"lm_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
const actionsDB = [
{
actionName: "clickButton",
uid: "uid_1",
counts: [
{
date: "1/1/2022",
count: 7,
},
{
date: "1/2/2022",
count: 7,
},
{
date: "1/3/2022",
count: 7,
},
]
}
];
const insertAction = (uid, actionName, date) => {
const userActionRecord = actionsDB.find(action => action.actionName === actionName && action.uid === uid);
const userDailyCount = userActionRecord.counts.find(dailyCount => dailyCount.date === date);
if (userDailyCount) {
userDailyCount.count += 1;
} else {
userActionRecord.counts.push({date: date, count: 1})
}
}
This way, we can populate the object with whichever data we want to test our logic.
Now, let's create the streak counting function and the tracking of making an action function:
const DAILY_GOAL_COUNT = 10;
const STREAK_COUNT = 7;
const ONE_DAY = <object that represents a day in your context>
const getStreaks = (daysWithGoals) => {
if (daysWithGoals < STREAK_COUNT) {
return;
}
streaks = [[daysWithGoals[0].date]];
currStreakIndex = 0;
for (let i = 1; i < daysWithGoals.Length; i++) {
if (daysWithGoals[i].date - daysWithGoals[i - 1] === ONE_DAY) {
streaks[currStreakIndex].push(daysWithGoals[i]);
} else {
streaks.push([daysWithGoals[i].date])
currStreakIndex++;
}
}
return streaks
.filter(streak => streak.Length >= STREAK_COUNT)
.map((streak) => {
return {start: streak[0], end: streak[streak.Length - 1]}
})
}
const makeActionAndTrack = (uid, actionName) => {
insertAction(uid, actionName, Date()); | {
"domain": "codereview.stackexchange",
"id": 43556,
"lm_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
const makeActionAndTrack = (uid, actionName) => {
insertAction(uid, actionName, Date());
const daysWithGoals = actionsDB
.filter(action => action.uid === uid && action.actionName === actionName)
.map(action => action.counts.filter(dailyCount => dailyCount.count >= DAILY_GOAL_COUNT))
const streaks = getStreaks(daysWithGoals);
if (streaks) {
streaks.forEach(streak => console.log(streak.start, streak.end))
}
}
This way we made our functions more atomic (probably could be improved a lot by separating to even smaller functions, and maybe creating a util to help with the dates like you did :) ).
I would also separate the insert and the tracking (in my example I just
wanted to make an example of a trigger to the tracking function - an
insertion of an action, but it could be a scheduled event or any event).
and so we'd be able to implement @kemicofa ghost answer without modifying
the code too much. | {
"domain": "codereview.stackexchange",
"id": 43556,
"lm_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
} |
java, algorithm, file, edit-distance
Title: Simple diff utility in Java
Question: (See the next and second iteration here.)
I have this toy implementation of the diff utility in Java:
com.github.coderodde.diff.Diff.java
package com.github.coderodde.diff;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class Diff {
private static final String NL = "\n";
public static void main(String[] args) {
if (args.length != 2) {
return;
}
File oldSourceFile = new File(args[0]);
File newSourceFile = new File(args[1]);
BufferedReader oldSourceBufferedReader = null;
BufferedReader newSourceBufferedReader = null;
try {
oldSourceBufferedReader =
new BufferedReader(new FileReader(oldSourceFile));
newSourceBufferedReader =
new BufferedReader(new FileReader(newSourceFile));
} catch (IOException ex) {
System.err.println("I/O failed: " + ex.getMessage());
System.exit(1);
}
List<String> oldSourceLines = new ArrayList<>();
List<String> newSourceLines = new ArrayList<>();
String oldSourceLine;
String newSourceLine;
try {
while ((oldSourceLine = oldSourceBufferedReader.readLine()) != null) {
oldSourceLines.add(oldSourceLine);
}
while ((newSourceLine = newSourceBufferedReader.readLine()) != null) {
newSourceLines.add(newSourceLine);
}
} catch (IOException ex) {
System.err.println("I/O failed: " + ex.getMessage());
System.exit(1);
}
System.out.println(computeDiff(oldSourceLines, newSourceLines));
} | {
"domain": "codereview.stackexchange",
"id": 43557,
"lm_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, algorithm, file, edit-distance",
"url": null
} |
java, algorithm, file, edit-distance
System.out.println(computeDiff(oldSourceLines, newSourceLines));
}
private static String computeDiff(List<String> oldSourceLines,
List<String> newSourceLines) {
int[][] matrix = computeLongestCommonSubsequenceData(oldSourceLines,
newSourceLines);
return printDiff(matrix, oldSourceLines, newSourceLines);
}
private static int[][] computeLongestCommonSubsequenceData(
List<String> oldSourceLines,
List<String> newSourceLines) {
int[][] matrix = new int[oldSourceLines.size() + 1]
[newSourceLines.size() + 1];
for (int i = 1; i <= oldSourceLines.size(); ++i) {
for (int j = 1; j <= newSourceLines.size(); ++j) {
if (oldSourceLines.get(i - 1)
.equals(newSourceLines.get(j - 1))) {
matrix[i][j] = matrix[i - 1][j - 1] + 1;
} else {
matrix[i][j] = Math.max(matrix[i - 1][j], matrix[i][j - 1]);
}
}
}
return matrix;
}
private static String printDiff(int[][] matrix,
List<String> oldSourceLines,
List<String> newSourceLines) {
StringBuilder stringBuilder = new StringBuilder();
printDiff(stringBuilder,
matrix,
oldSourceLines,
newSourceLines,
oldSourceLines.size() - 1,
newSourceLines.size() - 1);
return stringBuilder.toString();
} | {
"domain": "codereview.stackexchange",
"id": 43557,
"lm_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, algorithm, file, edit-distance",
"url": null
} |
java, algorithm, file, edit-distance
return stringBuilder.toString();
}
private static void printDiff(StringBuilder stringBuilder,
int[][] matrix,
List<String> oldSourceLines,
List<String> newSourceLines,
int i,
int j) {
if (i >= 0
&& j >= 0
&& oldSourceLines.get(i).equals(newSourceLines.get(j))) {
printDiff(stringBuilder,
matrix,
oldSourceLines,
newSourceLines,
i - 1,
j - 1);
stringBuilder.append(" ").append(oldSourceLines.get(i)).append(NL);
} else if (j > 0 && (i == 0 || matrix[i][j - 1] >= matrix[i - 1][j])) {
printDiff(stringBuilder,
matrix,
oldSourceLines,
newSourceLines,
i,
j - 1);
stringBuilder.append("+ ").append(newSourceLines.get(j)).append(NL);
} else if (i > 0 && (j == 0 || matrix[i][j - 1] < matrix[i - 1][j])) {
printDiff(stringBuilder,
matrix,
oldSourceLines,
newSourceLines,
i - 1,
j);
stringBuilder.append("- ").append(oldSourceLines.get(i)).append(NL);
}
}
}
Critique request
What do you think? Would it be better to hide the diff process into a class, for instance?
Answer: private static final String NL = "\n";
I don't think that NL is a particularly good name. Generally it is not needed either. For a system utility, I'd go for System.lineSeparator().
public static void main(String[] args) { | {
"domain": "codereview.stackexchange",
"id": 43557,
"lm_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, algorithm, file, edit-distance",
"url": null
} |
java, algorithm, file, edit-distance
There is a lot of duplicate code in the main method because reading the files is parallelized. Reading the files can be separated out into a a single method so that the duplicate code is not required (in this case just calling readLines would do the same thing I suppose).
if (args.length != 2) {
return;
}
I'd at least return a message to the user what kind of arguments are required, and then use System.exit() with a return/status code. You do this later on, strangely enough, so symmetry is also missing.
BufferedReader oldSourceBufferedReader = null;
BufferedReader newSourceBufferedReader = null;
try {
oldSourceBufferedReader =
new BufferedReader(new FileReader(oldSourceFile));
I'd expect try-with-resources to be used here, it would remove a lot of unnecessary code, and would avoid any null handling.
return printDiff(matrix, oldSourceLines, newSourceLines);
printDiff is a bad name, as the method doesn't actually print anything.
int[][] matrix = new int[oldSourceLines.size() + 1]
[newSourceLines.size() + 1];
Here you can see clearly what happens, but it is unclear from the code why the matrix has the calculated size. Whenever that happens you need code comments.
Furthermore, it seems your matrix is over-dimensioned in both directions by one, as you only index i - 1 and j - 1.
for (int i = 1; i <= oldSourceLines.size(); ++i) {
Nah, you should always try and use zero based indexing. Whenever you need one more, you can add it when needed. Subtraction always confuses things.
The same goes for ++i. Sometimes people things that ++i is faster, but it is no different than i++ and less clear.
private static void printDiff(StringBuilder stringBuilder,
int[][] matrix,
List<String> oldSourceLines,
List<String> newSourceLines,
int i,
int j) { | {
"domain": "codereview.stackexchange",
"id": 43557,
"lm_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, algorithm, file, edit-distance",
"url": null
} |
java, algorithm, file, edit-distance
This is a recursive method, and recursive methods should always be documented. Furthermore, for recursive methods, it is pretty important to make it very clear when the end is reached. I would recommend to check for a negative i and j to quickly return. Also, to make the method more readable, you could simply change i and / or j and then perform the recursion at the end.
Design. Yes, you always need a specific class that you instantiate, so that you can use it from other code without having to use main.
Currently the used algorithm is not described. This is vital for maintainability. Always document the algorithm and / or provide a reference to the method used.
When creating a diff I would strongly suggest to make sure that you don't need to read entire files in memory. Files can be huge after all. Otherwise you may want to limit the file size | {
"domain": "codereview.stackexchange",
"id": 43557,
"lm_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, algorithm, file, edit-distance",
"url": null
} |
python, beginner, python-3.x, mathematics
Title: Find perfect squares within a given range
Question: I managed to make this work without breaking the program if you enter some weird numbers in the range. The thing is I know this could have been done simpler and smarter. I can't really see how right now so I'm hoping you'll enlighten me. Thanks
print("Perfect Square Finder!")
print("Enter a range to find perfect squares")
square = 1
odd = 3
valid = False
while valid == False:
low = int(round(float(input("Low End: "))))
high = int(round(float(input("High End: "))))
if low > high or high < 0:
valid = False
print("Not a valid range")
else:
valid = True
while square <= high:
if square >= low:
present = True
print(str(int(square ** 0.5)) + "^2 = " + str(square))
else:
present = False
square = square + odd
odd = odd + 2
if present == False:
print("No perfect squares in the range")
Answer: Organization
Blank lines between sections of code would make your code a little easier to read. Add a blank line before both while loops as wall as the final if statement.
Move you perfect square finder into a function. This would allow you reuse the function multiple times, and even write test code to make sure it works.
Bugs
You function will not find the perfect square zero (0² == 0). | {
"domain": "codereview.stackexchange",
"id": 43558,
"lm_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, python-3.x, mathematics",
"url": null
} |
python, beginner, python-3.x, mathematics
If asked for a perfect square between 81129638414606699710187514626000 and 81129638414606699710187514626100, it can report:
9007199254740992^2 = 81129638414606699710187514626049
which is obviously wrong, since an even number squared will not be odd. The issue is int(square ** 0.5), which uses inexact floating point math to determine the square root. Using math.isqrt(square) does the calculation entirely using integer math, and is exact.
Bizarre validation
You use int(round(float(input(...)))) to get the low and high limits. Why are you using float() and round()? Are you allowing the user to enter in floating point limits, like 1.25 to 5.8? If not, you could simply have int(input(...)).
Efficiency
Your algorithm of computing perfect squares by summing odd integers is not the most efficient algorithm. But let's assume you wanted to do it that way anyway.
The code is not as efficient as it could be.
Every step until you reach a square >= low, you repeatedly set present = False. When searching for the perfect square 81129638414606699710187514626049, this ends up happening 9007199254740992 times, which is a bit excessive. You could simply set it present = False once before the loop starts.
The statements square = square + odd and odd = odd + 2 are not efficient, due to vulgarities of the Python interpreter. (It must look up the variable in the dictionary each time it is mentioned in the statement!) Using square += odd and odd += 2 eliminates one variable lookup each, so will be faster.
Reworked code
The following code uses f-strings to simplify the print statements. It also further reworks the perfect square finding loop into two separate loops for additional efficiency eliminating the present variable altogether. It further uses a "main guard", allowing the code to be imported without being executed. Finally, all code has been moved inside of functions, eliminating the global variables.
from math import isqrt
def print_perfect_squares_in_range(low, high): | {
"domain": "codereview.stackexchange",
"id": 43558,
"lm_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, python-3.x, mathematics",
"url": null
} |
python, beginner, python-3.x, mathematics
def print_perfect_squares_in_range(low, high):
square = 0 # Since zero is a perfect square,
odd = 1 # we need to start the search 1 step earlier
# Skip over all perfect square below lower limit
while square < low:
square += odd
odd += 2
# If the next perfect square has not exceeded the upper limit ...
if square <= high:
# ... then there are perfect squares in the given range
while square <= high:
print(f"{isqrt(square)}^2 = {square}")
square += odd
odd += 2
else:
# ... otherwise, there are not any.
print("No perfect squares in range")
def main():
valid = False
while not valid:
low = int(input("Low End: "))
high = int(input("High End: "))
if low > high or high < 0:
print("Not a valid range")
else:
valid = True
print_perfect_squares_in_range(low, high)
if __name__ == '__main__':
main() | {
"domain": "codereview.stackexchange",
"id": 43558,
"lm_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, python-3.x, mathematics",
"url": null
} |
javascript, node.js, library
Title: the mini js tool library
Question: I am a newbie js "developer" and for practice, I created a tiny (8 methods) JavaScript library. I need you to give me feedback "should I keep expanding my library or switch to something else" and how do I improve the code quality?
full code:
function isObject(val) {
if (val === null) { return false;}
return ( (typeof val === 'function') || (typeof val === 'object') );
}
function isDate(value) {
switch (typeof value) {
case 'number':
return true;
case 'string':
return !isNaN(Date.parse(value));
case 'object':
if (value instanceof Date) {
return !isNaN(value.getTime());
}
default:
return false;
}
}
function isEmptyOrOnlySpacesString(str) {
return (!str || /^\s*$/.test(str));
}
function getTimeZone() {
return Intl.DateTimeFormat().resolvedOptions().timeZone;
}
function doesObjectHaveEmptyProperties(obj) {
let emptyKeys = [];
for(let key in obj) {
if(obj[key] === "") {
emptyKeys.push(key + " is empty.\n");
}
}
return emptyKeys.join('') + ' others keys are filled';
}
function isSorted (arr){
return arr.every((a,b,c) => !b || c[b-1] <= a);
}
function shuffleArray (arr){
let len = arr.length;
while (len) {
const i = Math.floor(Math.random() * len--);
[arr[len], arr[i]] = [arr[i], arr[len]];
}
return arr;
}
function generateRandomIntArr(len, upTo){
return Array.from({ length: len }, () => Math.floor(Math.random() * upTo));
}
Also you can visit my github repo
thanks in advance
Answer: From a short review;
You may want to check out the lodash library, the implementation of isObject there is
function isObject(value) {
var type = typeof value;
return value != null && (type == 'object' || type == 'function');
} | {
"domain": "codereview.stackexchange",
"id": 43559,
"lm_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, node.js, library",
"url": null
} |
javascript, node.js, library
It does spell out completely value, which is better for readability
It does not repeat typeof value, but stores it in a temp value (would have gone for const here though)
It has one exit statement which seems cleaner
isDate returns true for 37, it feels wrong. I would try to parse numbers as well. Furthermore the functional name lies a bit, it does not check whether value is a date, but whether it can be converted to a date.
I prefer list more than arr, it reads better as a whole word
arr.every((a,b,c) -> those variable names are not good. every is not that common. I would if you insist on 1 letter variables go for v,i,l/a (value, index, list/array)
I would expect shuffleArray to create a new shuffled list, not to shuffle in place.
let emptyKeys could be const | {
"domain": "codereview.stackexchange",
"id": 43559,
"lm_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, node.js, library",
"url": null
} |
c#, performance, .net, memory-optimization
Title: Improving multiple FirstOrDefault statements on same collection
Question: I'm having multiple FirstOrDefault() statements, in this case 2, on a collection.
var id = data.Col.FirstOrDefault(x => x.Type == Types.Id)?.Value;
var email = data.Col.FirstOrDefault(x => x.Type == Types.Email)?.Value;
In the worst scenario this will loop 2 times over my entire collection.
I'm searching for a way to only loop over my collection once (and if possible break early when all has been found).
Is this a proper way of doing it or could it be written better?:
string id = null;
string email = null;
bool foundIdType = false;
bool foundEmailType = false;
foreach (var item in data.Col)
{
if (!foundIdType && item.Type == Types.Id)
{
foundIdType = true;
id = item.Value;
if (foundIdType && foundEmailType)
break;
}
if (!foundEmailType && item.Type == Types.Email)
{
foundEmailType = true;
email = item.Value;
if (foundIdType && foundEmailType)
break;
}
}
Answer: Your method is quite correct.
However, it can be simplified by getting rid of Boolean variables.
string id = null;
string email = null;
foreach (var item in data.Col)
{
if (id == null && item.Type == Types.Id)
id = item.Value;
if (email == null && item.Type == Types.Email)
email = item.Value;
if (id != null && email != null)
break;
} | {
"domain": "codereview.stackexchange",
"id": 43560,
"lm_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, .net, memory-optimization",
"url": null
} |
c#, performance, .net, memory-optimization
if (id != null && email != null)
break;
}
What type does the Col collection have?
If performance is critically important to you, then you can look at ways to increase it, such as Loop unrolling and the Sentinel value.
You can also cache values. When inserting data into a collection, save their very first values to the id and email variables, and the search is no longer needed. | {
"domain": "codereview.stackexchange",
"id": 43560,
"lm_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, .net, memory-optimization",
"url": null
} |
c++, library, benchmarking
Title: I wrote a simple time measurement library in C++
Question: welcome everybody
I wrote a simple code to measure time easily
Features
Easy include and just call timeit()
Fast It just calculates the average time in the loop
Light No lots of code, just one function is written
CrossPlatform It doesn't using any third party libraries, so it should work anywhere
Syntax
timeit(name, count, function, args).unit();
Example
#include "timeit.hpp"
void func(int a, int b){ /* do something */ }
timeit("test1", 1000, func, 5, 5).microseconds();
result
[TIMEIT] [test1]: 500192[µs]
Units
seconds
milliseconds
microseconds
Source Code
/**
* @file timeit.hpp
* @brief A simple measure time way
* @version 0.1
*
* Copyright (c) 2022 Maysara Elshewehy (xeerx.com) (maysara.elshewehy@gmail.com)
*
* Distributed under the MIT License (MIT)
*/
#pragma once
#include <iostream>
#include <vector>
#include <string>
#include <functional>
#include <numeric>
#include <chrono>
// DON'T USE IT, IT JUST HELPER FOR THE FUNCTION timeit()
class __timeit
{
private:
// name of test
std::string name;
// average result between all test results
size_t result = 0;
// storing test results
std::vector<size_t> results;
public:
// constructor: init name
__timeit(std::string n) : name{n} {}
// print result in seconds
void seconds() { std::cout << name << result / 1000 / 1000 << "[" << "s" << "]" << std::endl; }
// print result in milliseconds
void milliseconds() { std::cout << name << result / 1000 << "[" << "ms" << "]" << std::endl; }
// print result in microseconds
void microseconds() { std::cout << name << result << "[" << "µs" << "]" << std::endl; }
// get average result between all test results and set `result`
void get() { result = std::reduce(results.begin(), results.end()) / results.size(); }
// push test `result` to `results`
void set(size_t val){ results.push_back(val); }
}; | {
"domain": "codereview.stackexchange",
"id": 43561,
"lm_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++, library, benchmarking",
"url": null
} |
c++, library, benchmarking
// USE IT WITH ANY TYPE OF FUNCTIONS AND ANY NUMBER/TYPE OF PARAMETERS
template <class F, typename ...A>
__timeit timeit(std::string name, int count, F func, A&& ...args)
{
// create `__timeit` class and set name
__timeit clss("[TIMEIT] [" + name + "]: ");
// loop
for (size_t i = 0; i < count; i++)
{
// get time at beginning
std::chrono::steady_clock::time_point begin = std::chrono::steady_clock::now();
// execute function
func(std::forward<A>(args)...);
// get time at finishing
std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now();
// call `set()` function to push result to results vector
clss.set(std::chrono::duration_cast<std::chrono::microseconds>(end - begin).count());
}
// now call `get()` function to get average result between all test results and set `result`
clss.get();
// return to class object, so we can call units functions like: timeit(...).second(); easy right? :]
return clss;
}
Questions
Is there a better way?
Are there errors?
Any tips?
GitHub Repository | {
"domain": "codereview.stackexchange",
"id": 43561,
"lm_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++, library, benchmarking",
"url": null
} |
c++, library, benchmarking
Questions
Is there a better way?
Are there errors?
Any tips?
GitHub Repository
Answer: Don't do any time conversions yourself
By storing the elapsed time in microseconds, and doing integer divisions when asking for the elapsed time in seconds, you lose precision. Also, what if you want the time in nanoseconds or minutes? The best you can do is actually not do time conversions at all. Just keep durations stored as std::chrono::duration, and return that to the user, and they can cast it to whatever type they want themselves.
Don't store intermediate results longer than necessary
There is no need to have a class __timeit with a member variable results where intermediate results are stored in indefinitely. You only need this vector inside timeit() itself. Or even better, don't store them at all if you just need the sum:
template <class F, typename ...A>
auto timeit(int count, F func, A&& ...args)
{
using clock = std::chrono::steady_clock;
clock::duration total_duration = {};
for (size_t i = 0; i < count; i++)
{
auto begin = clock::now();
func(std::forward<A>(args)...);
auto end = clock::now();
total_duration += end - begin;
}
return total_duration / count;
} | {
"domain": "codereview.stackexchange",
"id": 43561,
"lm_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++, library, benchmarking",
"url": null
} |
c++, library, benchmarking
Don't use double underscores
Some uses of underscores in names are reserved. In particular, double underscores are always reserved, and you should not use them yourself.
Warm-up, autoscaling, errors
Your way of measuring the time a function takes is unfortunately a bit naive. The first time a function is called it might take a very different time to run than a subsequent time it is called, because of caches, branch predictors and memory not having been "warmed up" to the function you are calling. It sometimes takes a surprisingly large number of calls before everything has settled. If you are going to call a function a million times, doing a hundred thousand calls to warm up everything before is a small price to pay.
It's hard to know up front how long a function will take, and humans are usually not very patient. So it would be nice if autoscaling was implemented, so it will run for a fixed amount of time (say, a few seconds by default).
The individual time measurements will contain errors. This is because computers are typically non-deterministic, having to deal with interrupts, frequency scaling, and other things that will influence how fast things are running. The function you are calling itself might be non-deterministic. If you are going to record individual time measurements, consider doing some statistics on them. For example, either the minimum time or the median time or is probably more relevant than the average. You might also want to make the standard deviation available to the user, and maybe the maximum and 95th percentile values as well.
Finally, measuring time costs time itself. The cost of one call to clock::now() will be included in each time measurement. Ideally, you want to subtract that. A good way to do this would be to also measure the time it takes calling a no-op function, and subtract that time from your results.
Comparison with Python's timeit module | {
"domain": "codereview.stackexchange",
"id": 43561,
"lm_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++, library, benchmarking",
"url": null
} |
c++, library, benchmarking
Comparison with Python's timeit module
Python's timeit module not only has the timeit() function, but also a repeat() function and a Timer class. While not all the functionality in the timeit module is useful for C++, if you want to provide something that is familiar to a Python user, then it might be nice to implement Timer and repeat() at least.
Also note that Python's timeit() returns the total time for all iterations of the function, not just the average time for a single function call. | {
"domain": "codereview.stackexchange",
"id": 43561,
"lm_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++, library, benchmarking",
"url": null
} |
java, algorithm, file, edit-distance
Title: Simple diff utility in Java using OOP
Question: (Previous and initial iteration lives here.)
(The next iteration is here.)
Now I was able to spare some lines by putting diff related state in an object. Also, I relied on Files.readAllLines, as advised.
com.github.coderodde.diff.Diff.java:
package com.github.coderodde.diff;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.List;
import java.util.Objects;
public class Diff {
private static final String NL = System.lineSeparator();
private static final String HELP_MESSAGE =
"java -jar Diff.jar OLD_FILE NEW_FILE";
private final List<String> oldSourceLines;
private final List<String> newSourceLines;
private final int[][] matrix;
public Diff(List<String> oldSourceLines, List<String> newSourceLines) {
this.oldSourceLines = Objects.requireNonNull(oldSourceLines);
this.newSourceLines = Objects.requireNonNull(newSourceLines);
this.matrix = new int[oldSourceLines.size() + 1]
[newSourceLines.size() + 1];
}
public String compute() {
computeLongestCommonSubsequenceMatrix();
return buildDiff();
}
public static void main(String[] args) {
if (args.length != 2) {
System.out.println(HELP_MESSAGE);
System.exit(0);
}
try {
List<String> oldSourceLines = readFile(new File(args[0]));
List<String> newSourceLines = readFile(new File(args[1]));
Diff diff = new Diff(oldSourceLines, newSourceLines);
System.out.println(diff.compute());
} catch (IOException ex) {
System.err.println("I/O failed: " + ex.getMessage());
System.exit(1);
}
} | {
"domain": "codereview.stackexchange",
"id": 43562,
"lm_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, algorithm, file, edit-distance",
"url": null
} |
java, algorithm, file, edit-distance
// Reads all the file lines into a list and returns the list in question.
private static List<String> readFile(File file) throws IOException {
return Files.readAllLines(file.toPath());
}
// This algorithm solves the Longest Common Subsequence problem. The
// alphabet is not assumed to be a cuatomary alphabet, but rather all
// possible strings over a simple alphabet.
private void computeLongestCommonSubsequenceMatrix() {
for (int i = 1; i <= oldSourceLines.size(); ++i) {
for (int j = 1; j <= newSourceLines.size(); ++j) {
if (oldSourceLines.get(i - 1)
.equals(newSourceLines.get(j - 1))) {
matrix[i][j] = matrix[i - 1][j - 1] + 1;
} else {
matrix[i][j] = Math.max(matrix[i - 1][j],
matrix[i][j - 1]);
}
}
}
}
// The entry ponit for the algorithm that reconstructs the LCS from the
// matrix.
private String buildDiff() {
StringBuilder stringBuilder = new StringBuilder();
buildDiff(stringBuilder,
oldSourceLines.size() - 1,
newSourceLines.size() - 1);
return stringBuilder.toString();
}
// Reconstructs the diff ocntent from the LCS matrix.
private void buildDiff(StringBuilder stringBuilder,
int i,
int j) {
if (i >= 0
&& j >= 0
&& oldSourceLines.get(i).equals(newSourceLines.get(j))) {
buildDiff(stringBuilder,
i - 1,
j - 1);
stringBuilder.append(" ").append(oldSourceLines.get(i)).append(NL);
} else if (j > 0 && (i == 0 || matrix[i][j - 1] >= matrix[i - 1][j])) {
buildDiff(stringBuilder,
i,
j - 1); | {
"domain": "codereview.stackexchange",
"id": 43562,
"lm_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, algorithm, file, edit-distance",
"url": null
} |
java, algorithm, file, edit-distance
stringBuilder.append("+ ").append(newSourceLines.get(j)).append(NL);
} else if (i > 0 && (j == 0 || matrix[i][j - 1] < matrix[i - 1][j])) {
buildDiff(stringBuilder,
i - 1,
j);
stringBuilder.append("- ").append(oldSourceLines.get(i)).append(NL);
}
}
}
Critique request
As always, please, tell me anything that comes to mind. Am I improving my toy diff? | {
"domain": "codereview.stackexchange",
"id": 43562,
"lm_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, algorithm, file, edit-distance",
"url": null
} |
java, algorithm, file, edit-distance
Answer: This is a clear improvement from the first version, but there is still room for improvement.
Return a specific Object
However the result would benefit from being another object, or at least a list of the diff lines. Why? Because you input two lists of String and get a single String in return that people will have to parse to properly understand. This will allow you to decouple the formatting of the answer from the result itself.
I personally would return a List<Difference> where Difference contains two fields: the operation to go from oldLines to newLines (EQUAL, INSERT, DELETE) and the text. Then I would create a separate method that does only the formatting.
Use 0-index when possible
computeLongestCommonSubsequenceMatrix is one code that when you read it, you barely understand anything because everything is i-1 or j-1. The cognition of using i-1 is way higher than i+1. Okay you have some indices that are i or j, but it's more idiomatic to use for (i = 0; i < ...; i++) than for (i = 1; i <= ...; i++) because Java is always 0-based.
Also, your matrix is too big: its first row and its first column are always nothing but zeroes. So it's probably much better to revise the algorithm to remove those, and use 0-based index, I'm quite sure that the result will be more readable, as no one will then wonder why the size is +1 and why the loop starts at 1.
Use Javadoc comments to explain what the method does.
Javadoc has the Javadoc comments, /** ... */, use it, especially when your comment is explaining what the method does; and even when the method is private.
Plus, re-read your comments as they're full of typos.
Sanitize the inputs | {
"domain": "codereview.stackexchange",
"id": 43562,
"lm_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, algorithm, file, edit-distance",
"url": null
} |
java, algorithm, file, edit-distance
Plus, re-read your comments as they're full of typos.
Sanitize the inputs
Objects.requireNonNull() is nice, but List.copyOf() (Java 9+) also checks the content and makes sure that no element of the list is null. If any user provides null as a list element, it's only when compute is invoked that the NullPointerException is thrown. With List.copyOf(), it happens as soon as the list is provided and indicates that the class is null-hostile (which it implicitly is).
Store data in local variables
The method buildDiff is hard to understand for several reasons. One of which is because you keep repeating "oldSourceLines.get(i)" and "newSourceLines.get(j)". Those .get(x) get in the way of an easy reading, so create new variables in order to remove that cognition from the reader. Also, if the algorithm mixed sometimes i and j, there might be a reason to keep as you wrote, but in this case, it's always old->i and new->j, more reason to externalize.
It also happens that Files.readAllLines returns a RandomAccess List in the OpenJDK, but the specification is totally vague about it. If it returned a LinkedList or something similar, the implementation would be drastically slower.
Document recursion
The other reason why buildDiff is hard to understand is because it is recursive. Recursion is hard, and changing anything can break it very easily. So it's always better to make sure that recursion is properly documented.
Use Path.of()
The code currently mixes java.io and java.nio code. Try to be consistent and use only one. From your previous iteration, you chose to switch to Files.readAllLines(), meaning that you want to go towards java.nio.
Using Path.of(args[0]) (in Java 11) or Paths.get(args[1]) (Java 7+) is the way to go, now because the API is much smoother.
Also, readFile is useless as reading the lines is quite straightforward with the method you used:
List<String> oldSourceLines = Files.readAllLines(Path.of(args[0])); | {
"domain": "codereview.stackexchange",
"id": 43562,
"lm_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, algorithm, file, edit-distance",
"url": null
} |
java, algorithm, file, edit-distance
List<String> oldSourceLines = Files.readAllLines(Path.of(args[0]));
List<String> newSourceLines = Files.readAllLines(Path.of(args[1])); | {
"domain": "codereview.stackexchange",
"id": 43562,
"lm_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, algorithm, file, edit-distance",
"url": null
} |
java, algorithm, file, edit-distance
Rename variables
The word source in the variable name adds nothing, and even confuses the reader as they can ask "which source?". Since you lose nothing by naming the variables oldLines and newLines, it's shorter but still entirely meaningful and takes less place both in the code and the mind of the reader.
However i and j as parameters of the buildDiff recursive method are unreadable. i and j should be used in a for-loop and nowhere else. Use meaningful name here, such as oldLineIndex and newLineIndex, for instance. Ok your code will be longer, but it's more meaningful and the reader will know that you decrement an index when you -1 it: currently they don't. | {
"domain": "codereview.stackexchange",
"id": 43562,
"lm_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, algorithm, file, edit-distance",
"url": null
} |
c, array, c-preprocessor
Title: C generic dynamic array (using preprocessor)
Question: I wrote a generic dynamic array using the preprocessor. My use case for it is a compiler I'm writing that uses dynamic arrays a lot, and my current void pointer implementation is becoming a bit hard to use as I have to remember the type each array stores when using it.
I'm wondering if this is a good readable implementation and interface.
I'm aware that using an existing library would most likely be better, but as this is for learning purposes, I want to implement all the data structures I use.
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#define ARRAY_INITIAL_CAPACITY 8
#define Array(type) type *
// [capacity][used][data]...
#define initArray(array) do { \
size_t *data = malloc(2 * sizeof(size_t) + ARRAY_INITIAL_CAPACITY * sizeof(*(array))); \
data[0] = ARRAY_INITIAL_CAPACITY; \
data[1] = 0; \
(array) = (typeof(*(array)) *)&data[2]; \
} while(0)
#define freeArray(array) free((size_t *)(array)-2)
#define arrayCapacity(array) ((array) ? *((size_t *)(array)-2) : 0lu)
#define arrayUsed(array) ((array) ? *((size_t *)(array)-1) : 0lu)
#define arrayEmpty(array) (arrayUsed(array) == 0)
#define arrayPush(array, value) do { \
if(arrayUsed(array) + 1lu >= arrayCapacity(array)) { \
size_t *data = ((size_t *)(array)-2); \
size_t newCap = arrayCapacity(array) * 2 + 2 * sizeof(size_t); \
data = realloc(data, newCap); \
(array) = (typeof(*(array)) *)&data[2]; \
} \
size_t *used = ((size_t *)(array) - 1); \
(array)[(*used)++] = (value); \
} while(0)
#define arrayPop(array) (assert(arrayUsed(array) > 0), (array)[--*((size_t *)(array) - 1)])
#define arrayGet(array, idx) (assert((idx) < arrayUsed(array)), (array)[(idx)]) | {
"domain": "codereview.stackexchange",
"id": 43563,
"lm_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, array, c-preprocessor",
"url": null
} |
c, array, c-preprocessor
// callback type has to be void (*)(T, U)
// where T is the type of the items in the array,
// and U is the type of the user_data argument.
#define arrayMap(array, callback, user_data) do { \
for(size_t i = 0; i < arrayUsed(array); ++i) {\
callback(array[i], (user_data)); \
} \
} while(0)
#define arrayCopy(dest, src) do { \
for(size_t i = 0; i < arrayUsed(src); ++i) { \
arrayPush((dest), (src)[i]); \
} \
} while(0)
Example usage:
static void callback(int item, void *user_data) {
printf("%d\n", item);
}
int main(void) {
Array(int) nums = NULL;
initArray(nums);
arrayPush(nums, 1);
arrayPush(nums, 2);
printf("capacity: %lu, used: %lu\n", arrayCapacity(nums), arrayUsed(nums));
// Iterating
for(int i = 0; i < arrayUsed(nums); ++i) {
printf("%d\n", arrayGet(nums, i));
}
// Iterating in reverse
for(int i = arrayUsed(nums)-1; i >= 0; --i) {
printf("%d\n", nums[i]);
}
Array(int) nums2 = NULL;
initArray(nums2);
arrayCopy(nums2, nums);
while(!arrayEmpty(nums)) {
printf("%d\n", arrayPop(nums));
}
arrayMap(nums2, callback, NULL);
freeArray(nums2);
freeArray(nums);
return 0;
} | {
"domain": "codereview.stackexchange",
"id": 43563,
"lm_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, array, c-preprocessor",
"url": null
} |
c, array, c-preprocessor
Answer: General Observations
I think this is a great learning project, and asking for a review is a great idea.
The keyword typeof is not part of the current C Programming Standard and that means the code isn't portable, it can only be compiled by compilers that have provided the extension.
Generally hiding memory allocation is a bad idea, it makes the code very hard to debug and maintain.
Expecting a function such as callback() to be defined in a macro can be problematic.
While using macros in C can sometimes greatly reduce the amount of code written, it is very difficult to maintain code written this way, writing, debugging and maintaining such code is very difficult and needs to be heavily documented.
Alternate Implementation
Possibly a better way to implement this is to have a struct that contains the current capacity, the current size of the array in use and a void pointer that points to the data. Allocating the array would be a 2 step process, first allocate the struct and then allocate the data portion. Have a header file that defines the struct and function prototypes that operate on the struct. Have a C file that contains the functions that operate on the struct.
Test for Possible Memory Allocation Errors
In modern high-level languages such as C++, memory allocation errors throw an exception that the programmer can catch. This is not the case in the C programming language. While it is rare in modern computers because there is so much memory, memory allocation can fail, especially if the code is working in a limited memory application such as embedded control systems. In the C programming language when memory allocation fails, the functions malloc(), calloc() and realloc() return NULL. Referencing any memory address through a NULL pointer results in undefined behavior (UB). | {
"domain": "codereview.stackexchange",
"id": 43563,
"lm_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, array, c-preprocessor",
"url": null
} |
c, array, c-preprocessor
Possible unknown behavior in this case can be a memory page error (in Unix this would be call Segmentation Violation), corrupted data in the program and in very old computers it could even cause the computer to reboot (corruption of the stack pointer).
To prevent this undefined behavior a best practice is to always follow the memory allocation statement with a test that the pointer that was returned is not NULL. | {
"domain": "codereview.stackexchange",
"id": 43563,
"lm_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, array, c-preprocessor",
"url": null
} |
unit-testing, react.js, dom, jsx, state
Title: Unit test for a React click-counting component
Question: Take this basic component using state:
export const InputChild = () => {
const [count, setCount] = useState(0);
const updateCount = () => setCount((prev) => prev + 1);
return (
<>
<h1>Count: </h1>
<h2>{count}</h2>
<button onClick={updateCount}>Click</button>
</>
);
};
And this test that just ensures the count increases after clicking the button:
it('should increment', () => {
act(() => {
render(<InputChild />);
});
let h2 = screen.getByRole('heading', { level: 2 });
let count = Number(h2.innerHTML);
const button = screen.getByText('Click');
expect(count).toBe(0);
expect(button).toBeInTheDocument();
// fireEvent.click(button); // also works
act(() => {
button.dispatchEvent(new MouseEvent('click', { bubbles: true }));
});
// count = Number(h2.innerHTML); // then use count below
expect(Number(h2.innerHTML)).toBe(1);
fireEvent.click(button);
expect(Number(h2.innerHTML)).toBe(2);
fireEvent.click(button);
expect(Number(h2.innerHTML)).toBe(3);
});
It’s annoying that I have to use Number(h2.innerHTML) in here in order to get the latest count value. Alternatively I could redefine count whenever clicking the button to get the latest innerHTML value (as the state changes):
count = Number(h2.innerHTML);
expect(count).toBe(1);
fireEvent.click(button);
count = Number(h2.innerHTML);
expect(count).toBe(2);
fireEvent.click(button);
count = Number(h2.innerHTML);
expect(count).toBe(3);
But this seems too verbose.
Is there not a better way of doing this other than something like Number(h2.innerHTML)? I am new to unit testing and am trying to not write bad code, and the above just doesn’t feel right to me and I assume someone will have a better way of doing it.
Answer: Use const instead of let
let h2 = screen.getByRole('heading', { level: 2 }); | {
"domain": "codereview.stackexchange",
"id": 43564,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "unit-testing, react.js, dom, jsx, state",
"url": null
} |
unit-testing, react.js, dom, jsx, state
Answer: Use const instead of let
let h2 = screen.getByRole('heading', { level: 2 });
Good that you're using screen and ByRole, but use const unless you plan to reassign the variable (and don't plan to reassign variables if you can possibly help it).
You could try getByRole for const button = screen.getByText('Click'); too. If you change the text here or introduce another element that has the text Click, that can cause the test to fail when it shouldn't.
Use fireEvent rather than native DOM events
// fireEvent.click(button); // also works
act(() => {
button.dispatchEvent(new MouseEvent('click', { bubbles: true }));
});
I'd prefer using fireEvent unless you have a specific reason not to. It's already wrapped in act so you don't need to worry about that. Same goes for render, which should probably be broken out into a beforeEach block.
Use .toHaveTextContent() rather than .innerHTML
Instead of h2.innerHTML, you can use expect(h2).toHaveTextContent() brought to you by jest-dom. See Common mistakes with React Testing Library: Using the wrong assertion.
In general, the philosophy of RTL is not to be dipping into native DOM elements unless you have to.
I'd write expect(Number(h2.innerHTML)).toBe(1) as expect(h2.innerHTML).toBe("1"). If the assertion fails, you'll get a much clearer error that compares .innerHTML against the string, rather than whatever weird value Number() might have returned, like NaN. (but using toHaveTextContent() as described above avoids the problem altogether)
Minor points
expect(button).toBeInTheDocument(); is OK, but keep in mind that getBy will throw if it fails, so it's basically an always-pass. Kent recommends keeping the explicit assertion anyway but I figured I'd point it out.
I'd probably keep the assertion right after the variable assignment rather than interleaving them. For example,
let count = Number(h2.innerHTML);
const button = screen.getByText('Click');
expect(count).toBe(0);
expect(button).toBeInTheDocument(); | {
"domain": "codereview.stackexchange",
"id": 43564,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "unit-testing, react.js, dom, jsx, state",
"url": null
} |
unit-testing, react.js, dom, jsx, state
expect(count).toBe(0);
expect(button).toBeInTheDocument();
would be:
const count = Number(h2.innerHTML);
expect(count).toBe(0);
const button = screen.getByText('Click');
expect(button).toBeInTheDocument();
or with jest-dom and other suggestions:
expect(h2).toHaveTextContent("0");
const button = screen.getByRole('Button');
expect(button).toBeInTheDocument(); | {
"domain": "codereview.stackexchange",
"id": 43564,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "unit-testing, react.js, dom, jsx, state",
"url": null
} |
c++, performance, game, asynchronous, io
Title: Game loop using Future.wait_for to check for input
Question: I started writing this game from scratch yesterday, and I wasn't completely new to C++'s future library.
I only use the std::async class to launch asynchronously the conio.h defined getch function, to get user's input without stopping the execution of the rest, which has to update the screen each 0.1s (I did it with chrono).
char choice;
while (choice != 'q') {
auto input = std::async(std::launch::async, getch);
while (input.wait_for(std::chrono::milliseconds(FRAME_DURATION)) != std::future_status::ready) {
if (game::status == PAUSED) // if the game is paused, do nothing
continue; // just wait for the next char
moveAllBullets(); // move all bullets
updateField(); // update the field
printField(); // print the field
for (auto& enemy: game::enemies) {
if (!enemy.alive)
continue;
if (rand()%5 == 0) {
enemy.turn();
enemy.fireBullet();
} else if (rand()%2 == 0) {
enemy.movePlayer(game::random::directionalChar());
}
}
if (rand()%50 == 0)
game::random::addEnemy(rand()%48+1, rand()%18+1);
if (game::player.auto_fire)
game::player.fireBullet();
game::player.points++;
}
printField(); // print the field | {
"domain": "codereview.stackexchange",
"id": 43565,
"lm_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, game, asynchronous, io",
"url": null
} |
c++, performance, game, asynchronous, io
choice = input.get();
switch (choice) {
case 'q': case 'Q':
return;
case 'p': case 'P':
game::status = PAUSED;
break;
case 'r': case 'R':
game::status = PLAYING;
break;
case 'w': case 'W': case 'a': case 'A': case 's': case 'S': case 'd': case 'D':
if (game::status == PLAYING)
game::player.movePlayer(choice);
break;
case 'f': case 'F':
if (game::status == PLAYING && game::player.ammunitions > 0 && !game::player.auto_fire)
game::player.fireBullet();
break;
case 'x': case 'X':
game::player.auto_fire = !game::player.auto_fire;
break;
}
}
This is the content of the function mainloop, which gets called at the beginning of the program.
My doubts were about this two lines:
auto input = std::async(std::launch::async, getch);
while (input.wait_for(std::chrono::milliseconds(FRAME_DURATION)) != std::future_status::ready)
The refresh is quite slow for a 20x50 matrix, so I was wondering if the problem could be that input.wait_for, since I know that sometimes listening for an event may affect the performance. Also I don't know if it depends on the code or if printing 20×50=1000 characters is slow.
Is wait_for the "problem"? In this case is there any alternative to wait_for?
Edit
Would the use of multithreading instead of asynchronous functions improve the performance? Is there any difference in terms of what happens to the I/O?
Edit (1)
The most effective changes were (in this order):
Inserting std::ios_base::sync_with_stdio(false) at the beginning of the program
Replacing all the system("cls") as suggested by G. Sliepen
Replacing std::endl with '\n' (just once, in the printField function, I don't need to flush in that case, right?) | {
"domain": "codereview.stackexchange",
"id": 43565,
"lm_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, game, asynchronous, io",
"url": null
} |
c++, performance, game, asynchronous, io
I'll anyway follow some of your other suggestions, starting from that ones about multithreading and curses libraries, that I'm sure will be very useful.
Thank you so much, I'm new to this community and I've never recieved such acceptance in a SE community, and I've never learned so much with a single question too.
Answer: Don't call system()
The refresh is quite slow for a 20x50 matrix, so I was wondering if the problem could be that input.wait_for(), since I know that sometimes listening for an event may affect the performance. Also I don't know if it depends on the code or if printing 20×50=1000 characters is slow.
It's impossible to see from the code you posted, but taking a peek at your GitHub repository, the problem seems to be mainly because you clear the screen by calling system("cls"). This is horribly inefficient because system() creates a new shell process, which in turn has to parse the string "cls", and then execute the code to clear the screen. Apart from being slow, it is also not portable: doing this will prevent your code from running on Linux or macOS for example.
A much better way would be to print the ANSI escape code for clearing the screen. This is much more efficient and more portable:
std::cout << "\33[2J\33[H"; | {
"domain": "codereview.stackexchange",
"id": 43565,
"lm_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, game, asynchronous, io",
"url": null
} |
c++, performance, game, asynchronous, io
That actually prints two ANSI escape codes; one to clear the screen and another to move the cursor to the top left of the screen.
Use '\n' instead of std::endl
Prefer using '\n' instead of std::endl; the latter is equivalent to the former, but also forces the output to be flushed, which can negatively impact performance. If you need to flush the output, I recommend you do this explicitly by using std::flush.
Consider using a curses library
Using std::async() to do getch() with a timeout is a kludge. It might work in this simple program, but it doesn't scale. What if you need to wait for two different things? There is unfortunately no simple way to wait_for() two futures at the same time.
Instead of trying to solve this problem yourself, I strongly recommend you use a library that takes care of this for you. If you want a pure text console game, then you should use a curses library. These all have a standard interface, so it's easy to swap one for another. For DOS and Windows, I recommend you use PDCurses. | {
"domain": "codereview.stackexchange",
"id": 43565,
"lm_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, game, asynchronous, io",
"url": null
} |
assembly, rags-to-riches, x86
Title: Hack assembler/disassembler in x86_64 assembly language
Question: Starting from this answer I thought I would show a fully worked example of how to create a data-driven version of the assembler for the Hack assembly language. As I noted in that answer, having things data driven also provides the opportunity to create a disassembler using the same data structure. This code implements both. I had intended to create some test code in C++ to exercise parts of this, but ran out of time to do so, so there may be some remaining bugs. This is the reason that some of the functions are declared as global and begin with an underscore. Here's a sample input file:
source.hack
@16
M=1
@17
M=0
@16
D=M
@0
D=D-M
@18
D;JGT
@16
D=M
@17
M=D+M
@16
M=M+1
@4
0;JMP
@17
D=M
Example of use:
hack input.hack > input.bin
hack input.bin d > reconstructed.hack
Note that to specify either operation (assemble/disassemble) we need to supply a file name. To specify disassembly, an additional command line argument is given. The contents of it are not used; just the presence of an additional argument is what triggers disassembly.
It also makes no effort to diagnose or even detect malformed or invalid input lines.
hack.asm
BUFFSIZE equ 16384
; some character constants
NEWLINE equ 10
SPACE equ 32
TAB equ 9
; some syscall constants
SYSREAD equ 0
SYSWRITE equ 1
SYSOPEN equ 2
; default file handles
STDIN equ 0
STDOUT equ 1
STDERR equ 2
; exit takes an exit error code
%macro exit 1
mov edi, %1
mov eax, 60
syscall
%endmacro
; openfile takes an ASCIIZ filename
%macro openfile 1
mov rdi, %1
xor esi, esi ; read only
xor edx, edx ; no create
mov eax, SYSOPEN
syscall
%endmacro
; readfile takes a file descriptor, buffer pointer, and buffer size
%macro readfile 3
mov rdi, %1
mov rsi, %2
mov rdx, %3
mov eax, SYSREAD
syscall
%endmacro | {
"domain": "codereview.stackexchange",
"id": 43566,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "assembly, rags-to-riches, x86",
"url": null
} |
assembly, rags-to-riches, x86
; print takes the file handle, a pointer to the string, and a length
%macro print 3
mov rdi, %1 ; print to passed file handle
mov rsi, %2 ; pointer to buffer
mov rdx, %3 ; length of buffer
mov eax, SYSWRITE
syscall
%endmacro
; takes mask, and pointer to table as arguments
; ENTRY:
; rax : current opcode to be decoded
; rdi : pointer to current output
; EXIT:
; rdi : updated current output pointer
; TRASHED:
; rbx
; rcx
; rsi
; r10
%macro decodeOpcodePart 2
mov eax, ebx
and eax, %1
mov r10, %2
call _reverseTableLookup
jc %%nextpart
xor rcx,rcx
mov cx, word [r10 + Operation.strlen]
lea esi, [r10 + Operation.string]
rep movsb
%%nextpart:
%endmacro
; takes mask, and pointer to table as arguments
; ENTRY:
; rax : current partially encoded opcode
; EXIT:
; rax : updated opcode
; TRASHED:
; rdi
%macro encodeOpcodePart 1
mov edi, %1
call _tableLookup
or ax, word[edi + Operation.value]
%endmacro
section .bss
buffer resb BUFFSIZE
outbuf resw BUFFSIZE/2
line resb 10
section .data
err_no_args db "Error: no input filename given on command line", 10
err_no_args_len equ $ - err_no_args
err_open db "Error: could not open file",10
err_open_len equ $ - err_open
err_read db "Error: could not read from file", 10
err_read_len equ $ - err_read
err_zero db "Error: read zero words from file", 10
err_zero_len equ $ - err_zero
err_write db "Error: could not write to output",10
err_write_len equ $ - err_write
section .text
global _start
global _tableLookup
global _stringToNumber | {
"domain": "codereview.stackexchange",
"id": 43566,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "assembly, rags-to-riches, x86",
"url": null
} |
assembly, rags-to-riches, x86
section .text
global _start
global _tableLookup
global _stringToNumber
; look up a string token in a table and return the corresponding value
;
; ENTRY:
; esi : points to strz token
; edi : points to Operation table
; EXIT:
; cy : set if not found in table
; edi : points to matching entry if found
; esi : points to one char after matched token if found
; TRASHED:
; rbx
_tableLookup:
mov rbx, rsi ; save original pointer to token
.looptop:
movzx ecx, word [edi + Operation.strlen]
push rdi
repe cmpsb
pop rdi
je .found
add edi, Operation_size
cmp word [edi + Operation.strlen],0
mov rsi,rbx
jne .looptop
stc
.found:
ret
; look up a a value and construct the corresponding string
;
; ENTRY:
; eax : binary value to search for
; r10 : points to Operation table
; EXIT:
; cy : set if not found in table
; r10 : points to matching entry if found
; TRASHED:
_reverseTableLookup:
.looptop:
cmp ax, word [r10 + Operation.value]
je .found
add r10, Operation_size
cmp word [r10 + Operation.strlen],0
jne .looptop
stc
.found:
ret | {
"domain": "codereview.stackexchange",
"id": 43566,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "assembly, rags-to-riches, x86",
"url": null
} |
assembly, rags-to-riches, x86
; given a pointer to a decimal number string, convert to the value in eax
; ENTRY:
; esi : points to strz decimal number string
; EXIT:
; eax : contains converted value
; esi : points to one past ending character
; TRASHED:
; ebx, ecx
_stringToNumber:
push rbx
push rcx
xor eax, eax
xor ebx, ebx
xor ecx, ecx
inc ecx ; default multiplier is +1
lodsb
cmp al, '-' ; is it a leading - sign?
jnz .numeric
dec ecx
dec ecx
.numeric:
sub al, '0'
jb .done
cmp al, 10
jnb .done
imul ebx, 10
add ebx, eax
lodsb
jmp .numeric
.done:
imul ebx, ecx
mov eax, ebx
pop rcx
pop rbx
ret
; given a 16-bit number in ax, convert to string in line
; ENTRY:
; rax : number to convert (high 48 bits must be zero)
; rdi : points to destination buffer
;
; EXIT:
; rdi : points to one past end of written string
; TRASHES:
; rbx
;
_numberToString:
push rsi
push rcx
mov rsi, rdi
mov bx,10
add rdi,5
.loopy:
dec rdi
xor edx,edx
div bx
add dl, '0'
mov byte [rdi],dl
test rax,rax
jnz .loopy
; compute 5 - (rdi - rsi) = rsi - rdi + 5 = rsi + 5 - rdi
lea rcx, [rsi + 5]
sub rcx, rdi
xchg rsi, rdi
rep movsb
pop rcx
pop rsi
ret | {
"domain": "codereview.stackexchange",
"id": 43566,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "assembly, rags-to-riches, x86",
"url": null
} |
assembly, rags-to-riches, x86
; copy just one assembly line from source to dest buffer, omitting whitespace
; ENTRY:
; esi : pointer to source
; edi : pointer to destination
; eax : number of bytes in source
; EXIT:
; esi : points to start of next line in source (if any)
; edi : points one past end of copied line
; eax : bytes remaining in source
; TRASHED:
; none
getline:
push rcx
mov ecx, eax
.top:
lodsb
cmp al, NEWLINE
jz .done
cmp al, SPACE ; skip spaces
jz .skipws
cmp al, TAB ; skip tabs, too
jz .skipws
stosb ; neither of those, so store it
.skipws:
loop .top
jmp .exit
.done:
xor eax,eax ; write terminating NUL char
stosb
dec ecx
.exit:
mov eax, ecx
pop rcx
ret
_start:
mov rax, [rsp] ; load argc into rax
mov edx, err_no_args
mov ebx, err_no_args_len
cmp eax, 2 ; have to have at least one argument
js error_exit
openfile [rsp+16] ; try opening the file named in the argument
mov edx, err_open
mov ebx, err_open_len
cmp eax,0
js error_exit
readfile rax, buffer, BUFFSIZE ; read the entire file into memory
mov edx, err_read
mov ebx, err_read_len
cmp eax,0
js error_exit
je no_bytes | {
"domain": "codereview.stackexchange",
"id": 43566,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "assembly, rags-to-riches, x86",
"url": null
} |
assembly, rags-to-riches, x86
main:
mov rdi, outbuf ; rdi points to current output buffer
cmp qword [rsp], 3 ; if there are two arguments, we are disassembling
jne assemble
mov ecx, eax
shr rcx, 1 ; convert from num bytes to num words
jz no_bytes
disassemble:
; ecx = number of remaining bytes in source
; esi = pointer to source buffer
; rdi = current pointer to output buffer
lodsw ; get the next word to disassemble
push rsi
push rcx ; remember updated count and pointer
test ah, 0x80 ; is this a type A instruction?
jnz .decode_c
mov byte [rdi], '@' ; it's a type A which is "@nnnn"
inc rdi
call _numberToString
jmp .emitLine
; it's a type C instruction of the form "dest=comp;jmp"
.decode_c:
mov ebx, eax ; save opcode in ebx
decodeOpcodePart DESTMASK, hackdest
decodeOpcodePart COMPMASK, hackcomp
decodeOpcodePart JUMPMASK, hackjump
; at this point we expect rcx (input len) and rsi (input ptr) on the stack,
; rdi : points to current end of output buffer
.emitLine:
pop rcx
pop rsi
mov al,NEWLINE
stosb
dec rcx
jnz disassemble
jmp write_output | {
"domain": "codereview.stackexchange",
"id": 43566,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "assembly, rags-to-riches, x86",
"url": null
} |
assembly, rags-to-riches, x86
assemble:
; eax = number of remaining bytes in source
; esi = pointer to source buffer
; rdi = current pointer to output buffer
mov r10, rdi ; temporarily save output pointer
mov edi, line
call getline ; copy a line, omitting whitespace
push rax
push rsi
mov rsi, line
cmp byte [rsi], '@' ; is this a type A instruction?
jnz .c_instruction ; if not, assume it's type C
inc rsi
call _stringToNumber
jmp .storeOpcode
.c_instruction:
; it's a C instruction
; rsi is already pointing to line
xor eax, eax
encodeOpcodePart hackdest
encodeOpcodePart hackcomp
encodeOpcodePart hackjump
.storeOpcode:
mov rdi, r10 ; restore output pointer
stosw
pop rsi
pop rax
test rax,rax
jne assemble
write_output:
; rdi = current pointer to output buffer
mov rdx, rdi
sub rdx, outbuf
print STDOUT, outbuf, rdx
mov edx, err_write
mov ebx, err_write_len
cmp eax,0
js error_exit
exit 0
no_bytes:
mov edx, err_zero ; if the file was empty, it's an error
mov ebx, err_zero_len
; fall through to error_exit
error_exit:
print STDERR, rdx, rbx
exit 1
section .data
struc Operation
.string: resb 8
.strlen: resw 1
.value: resw 1
endstruc
; opcode "string", value
%macro opcode 2
istruc Operation
at Operation.string, db %1
%strlen len %1
%rep 8 - len
db 0
%endrep
at Operation.strlen, dw len
at Operation.value, dw %2
iend
%endmacro
DESTMASK equ 0x38
COMPMASK equ 0xffc0
JUMPMASK equ 0x07 | {
"domain": "codereview.stackexchange",
"id": 43566,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "assembly, rags-to-riches, x86",
"url": null
} |
assembly, rags-to-riches, x86
DESTMASK equ 0x38
COMPMASK equ 0xffc0
JUMPMASK equ 0x07
hackdest:
opcode "AMD=", 0x38
opcode "AD=", 0x30
opcode "AM=", 0x28
opcode "MD=", 0x18
opcode "M=", 0x08
opcode "D=", 0x10
opcode "A=", 0x20
opcode "", 0
hackcomp:
opcode "D+1", 0xe7c0
opcode "A+1", 0xedc0
opcode "M+1", 0xfdc0
opcode "D-1", 0xe380
opcode "A-1", 0xec80
opcode "M-1", 0xfc80
opcode "D+A", 0xe080
opcode "D+M", 0xf080
opcode "D-A", 0xe4c0
opcode "D-M", 0xf4c0
opcode "A-D", 0xe1c0
opcode "M-D", 0xf1c0
opcode "D&A", 0xe000
opcode "D&M", 0xf000
opcode "D|A", 0xe540
opcode "D|M", 0xf540
opcode "-1", 0xee80
opcode "!D", 0xe340
opcode "!A", 0xec40
opcode "!M", 0xfc40
opcode "-D", 0xe3c0
opcode "-A", 0xecc0
opcode "-M", 0xfcc0
opcode "0", 0xea80
opcode "1", 0xefc0
opcode "D", 0xe300
opcode "A", 0xec00
opcode "M", 0xfc00
opcode "", 0
hackjump:
opcode ";JGT", 0x1
opcode ";JEQ", 0x2
opcode ";JGE", 0x3
opcode ";JLT", 0x4
opcode ";JNE", 0x5
opcode ";JLE", 0x6
opcode ";JMP", 0x7
opcode "", 0
```
Answer: Commenting is good
There are a number of inaccuracies though in the documentation, several of these are probably related to copy-pasting: | {
"domain": "codereview.stackexchange",
"id": 43566,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "assembly, rags-to-riches, x86",
"url": null
} |
assembly, rags-to-riches, x86
In the decodeOpcodePart macro the current opcode to be decoded is in RBX (so not in RAX), and it is RAX that gets trashed (so not RBX).
The encodeOpcodePart macro mentions that it 'takes mask, and pointer to table as arguments' where in fact there's but a single pointer argument.
The _tableLookup subroutine forgets to mention that it additionally trashes RCX.
The _stringToNumber subroutine mentions that RBX and RCX get trashed where in fact both these registers are preserved on the stack.
The _numberToString subroutine mentions that on exit RDI 'points to one past end of written string' where in fact RDI points just past the end of the written string (so not 'one past' like it is the case in the _stringToNumber subroutine).
The _numberToString subroutine forgets to mention that it additionally trashes RAX and RDX.
At the disassemble label ECX holds the number of remaining words in source (so not bytes).
For ease of reviewing, the TRASHED displays of the decode and encode macros should include the registers that get trashed in the subroutines that they call. Same goes for the ENTRY and EXIT displays.
Avoiding the use of "magic numbers"
In your answer to the 'rags' question you advocate to avoid the use of "magic numbers", but in adding the missing definition for exit, you introduced your own magic number mov eax, 60. Perhaps use SYSTERM equ 60.
Fix the bug
In the _stringToNumber subroutine you negate your final multiplier (+1 -> -1) if a minus character was found in the text. However you forget to load the character that follows the minus. That has to be the first digit that the .numeric loop processes.
Missed optimizations | {
"domain": "codereview.stackexchange",
"id": 43566,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "assembly, rags-to-riches, x86",
"url": null
} |
assembly, rags-to-riches, x86
When, in the _stringToNumber subroutine you negate your final multiplier (+1 -> -1), you use dec ecx dec ecx which takes 4 bytes, whereas a single neg ecx would do it in 2 bytes.
When, in the _stringToNumber subroutine you validate and convert a digit, you can safely remove the jb .done instruction. The byte wraparound will take care of it in the cmp al, 10 that immediately follows.
All occurencies of cmp eax, 0 can be written as test eax, eax which has a 1 byte shorter encoding, at least if you assemble with -Ox. Without optimizations it would be a lot worse.
Because the high dword of RCX is zeroed, we can replace the 3-byte shr rcx, 1 instruction by the 2-byte shr ecx, 1 instruction.
It is 1 byte shorter to write test ah, ah js .decode_c instead of test ah, 0x80 jnz .decode_c.
It is 4 bytes shorter to temporarily save the output pointer via push rdi ... pop rdi than to use mov r10, rdi ... mov rdi, r10.
If mov edi, line works fine, then mov rsi, line can safely become mov esi, line. This shaves off the REX prefix and opens up a world of similar REX-related optimizations that sometimes you do and sometimes you don't. I can't quite decide whether you care about codesize, execution speed, both, or none.
Use efficient instructions
Intel advices against using complex instructions like loop. In _getline you could replace loop .top with dec ecx jnz .top.
Think carefully about jumps
In your answer to the 'rags' question you warn about jumps being a relatively costly operation. Right so, but in the _stringToNumber subroutine you commit the same crime.
Next is my optimized rewrite of this conversion:
; given a pointer to a decimal number string, convert to the value in rax
; ENTRY:
; rsi : points to strz decimal number string
; EXIT:
; rax : contains converted value
; rsi : points to past ending character
; TRASHED:
; rdx | {
"domain": "codereview.stackexchange",
"id": 43566,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "assembly, rags-to-riches, x86",
"url": null
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.