ronantakizawa/codereview-bench huggingface dataset:
Repository: louislam/uptime-kuma
File: server/notification-providers/lunasea.js (JavaScript)

Code before:
const NotificationProvider = require("./notification-provider");
const axios = require("axios");
const { DOWN, UP } = require("../../src/util");

class LunaSea extends NotificationProvider {
    name = "lunasea";

    async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
        const okMsg = "Sent Successfully.";

        try {
            const target = this.getTarget(notification);
            if (heartbeatJSON == null) {
                let testdata = {
                    "title": "Uptime Kuma Alert",
                    "body": msg,
                };
                await axios.post(`https://notify.lunasea.app/v1/custom/${target}`, testdata);
                return okMsg;
            }

            if (heartbeatJSON["status"] === DOWN) {
                let downdata = {
                    "title": "UptimeKuma Alert: " + monitorJSON["name"],
                    "body": "[🔴 Down] " +
                        heartbeatJSON["msg"] +
                        `\nTime (${heartbeatJSON["timezone"]}): ${heartbeatJSON["localDateTime"]}`
                };
                await axios.post(`https://notify.lunasea.app/v1/custom/${target}`, downdata);
                return okMsg;
            }

            if (heartbeatJSON["status"] === UP) {
                let updata = {
                    "title": "UptimeKuma Alert: " + monitorJSON["name"],
                    "body": "[✅ Up] " +
                        heartbeatJSON["msg"] +

Review comment (suggestion):
```suggestion
        const okMsg = "Sent Successfully.";
        const url = "https://notify.lunasea.app/v1";
```

Code after:
const NotificationProvider = require("./notification-provider");
const axios = require("axios");
const { DOWN, UP } = require("../../src/util");

class LunaSea extends NotificationProvider {
    name = "lunasea";

    /**
     * @inheritdoc
     */
    async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
        const okMsg = "Sent Successfully.";
        const url = "https://notify.lunasea.app/v1";

        try {
            const target = this.getTarget(notification);
            if (heartbeatJSON == null) {
                let testdata = {
                    "title": "Uptime Kuma Alert",
                    "body": msg,
                };
                await axios.post(`${url}/custom/${target}`, testdata);
                return okMsg;
            }

            if (heartbeatJSON["status"] === DOWN) {
                let downdata = {
                    "title": "UptimeKuma Alert: " + monitorJSON["name"],
                    "body": "[🔴 Down] " +
                        heartbeatJSON["msg"] +
                        `\nTime (${heartbeatJSON["timezone"]}): ${heartbeatJSON["localDateTime"]}`
                };
                await axios.post(`${url}/custom/${target}`, downdata);
                return okMsg;
            }

            if (heartbeatJSON["status"] === UP) {
Repository: louislam/uptime-kuma
File: src/components/HeartbeatBar.vue (Vue)

Code before:

        &.maintenance {
            background-color: $maintenance;
        }

        &:not(.empty):hover {
            transition: all ease-in-out 0.15s;
            opacity: 0.8;
            transform: scale(var(--hover-scale));
        }
    }
}

.dark {
    .hp-bar-big .beat.empty {
        background-color: #848484;
    }
}

.word {
    color: #aaa;
    font-size: 12px;
}

.connecting-line {
    flex-grow: 1;  // To make the line expand and fill the available space
    height: 1px;
    background-color: #aaa;
    margin-left: 10px;
    margin-right: 10px;
    margin-top: 2px;
}
</style>


Review comment (suggestion):
This comment is just stating what `flex-grow: 1` odes => I don't think it holds additional value ^^
```suggestion
    flex-grow: 1;
```

Code after:

        &.pending {
            background-color: $warning;
        }

        &.maintenance {
            background-color: $maintenance;
        }

        &:not(.empty):hover {
            transition: all ease-in-out 0.15s;
            opacity: 0.8;
            transform: scale(var(--hover-scale));
        }
    }
}

.dark {
    .hp-bar-big .beat.empty {
        background-color: #848484;
    }
}

.word {
    color: #aaa;
    font-size: 12px;
}

.connecting-line {
    flex-grow: 1;
    height: 1px;
    background-color: #ededed;
    margin-left: 10px;
    margin-right: 10px;
    margin-top: 2px;

    .dark & {
        background-color: #333;
    }
}
</style>
Repository: louislam/uptime-kuma
File: server/util-server.js (JavaScript)

Code before:
            [ attributes.USER_PASSWORD, password ],
            [ attributes.CALLING_STATION_ID, callingStationId ],
            [ attributes.CALLED_STATION_ID, calledStationId ],
        ],
    });
};

/**
 * Redis server ping
 * @param {string} dsn The redis connection string
 */
exports.redisPingAsync = function (dsn) {
    return new Promise((resolve, reject) => {
        const client = redis.createClient({
            url: dsn
        });
        client.on("error", (err) => {
            client.disconnect();
            reject(err);
        });
        client.connect().then(() => {
            if (client.isOpen) {
                client.ping().then((res, err) => {
                    if (client.isOpen) {
                        client.disconnect();
                    }
                    if (err) {
                        reject(err);
                    } else {
                        resolve(res);
                    }
                }).catch(error => reject);
            }
        });
    });
};

/**
 * Retrieve value of setting based on key
 * @param {string} key Key of setting to retrieve
 * @returns {Promise<any>} Value
 * @deprecated Use await Settings.get(key)
 */
exports.setting = async function (key) {
    return await Settings.get(key);
};

/**
 * Sets the specified setting to specifed value
 * @param {string} key Key of setting to set
 * @param {any} value Value to set to

Review comment (suggestion):
For single line if without else statements, I tend to lean towards this being more readable, but this is just preference..

```suggestion
                    if (client.isOpen) client.disconnect();
```

Code after:
            [ attributes.USER_PASSWORD, password ],
            [ attributes.CALLING_STATION_ID, callingStationId ],
            [ attributes.CALLED_STATION_ID, calledStationId ],
        ],
    });
};

/**
 * Redis server ping
 * @param {string} dsn The redis connection string
 */
exports.redisPingAsync = function (dsn) {
    return new Promise((resolve, reject) => {
        const client = redis.createClient({
            url: dsn
        });
        client.on("error", (err) => {
            if (client.isOpen) {
                client.disconnect();
            }
            reject(err);
        });
        client.connect().then(() => {
            if (!client.isOpen) {
                client.emit("error", new Error("connection isn't open"));
            }
            client.ping().then((res, err) => {
                if (client.isOpen) {
                    client.disconnect();
                }
                if (err) {
                    reject(err);
                } else {
                    resolve(res);
                }
            }).catch(error => reject(error));
        });
    });
};

/**
 * Retrieve value of setting based on key
 * @param {string} key Key of setting to retrieve
 * @returns {Promise<any>} Value
 * @deprecated Use await Settings.get(key)
 */
exports.setting = async function (key) {
    return await Settings.get(key);
};

/**
Repository: louislam/uptime-kuma
File: server/notification-providers/smsc.js (JavaScript)

Code before:
    async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
        let okMsg = "Sent Successfully.";
        try {
            let config = {
                headers: {
                    "Content-Type": "application/json",
                    // "Authorization": "Basic " + Buffer.from(notification.smscLogin + ":" + notification.smscPassword).toString("base64"),
                    "Accept": "text/json",
                }
            };

            let getArray = [
                "fmt=3",
                "translit=" + notification.smscTranslit,
                "login=" + notification.smscLogin,
                "psw=" + notification.smscPassword,
                "phones=" + notification.smscToNumber,
                "mes=" + encodeURIComponent(msg.replace(/[^\x00-\x7F]/g, "")),
            ];
            if (notification.smscSenderName !== "") {
                getArray.push("sender=" + notification.smscSenderName);
            }

            let resp = await axios.get("https://smsc.kz/sys/send.php?" + getArray.join("&"), config);
            if (resp.data.id === undefined) {
                let error = "Something gone wrong. Api returned " + resp.data.error + ". Code " + resp.data.error_code;
                this.throwGeneralAxiosError(error);
            }

            return okMsg;
        } catch (error) {
            this.throwGeneralAxiosError(error);
        }
    }
}

module.exports = SMSC;


Review comment (bug):
I think this could be more readable
```suggestion
                let error = `Something gone wrong. Api returned code ${resp.data.error_code}: ${resp.data.error}`;
```

Code after:
        let okMsg = "Sent Successfully.";
        try {
            let config = {
                headers: {
                    "Content-Type": "application/json",
                    "Accept": "text/json",
                }
            };

            let getArray = [
                "fmt=3",
                "translit=" + notification.smscTranslit,
                "login=" + notification.smscLogin,
                "psw=" + notification.smscPassword,
                "phones=" + notification.smscToNumber,
                "mes=" + encodeURIComponent(msg.replace(/[^\x00-\x7F]/g, "")),
            ];
            if (notification.smscSenderName !== "") {
                getArray.push("sender=" + notification.smscSenderName);
            }

            let resp = await axios.get("https://smsc.kz/sys/send.php?" + getArray.join("&"), config);
            if (resp.data.id === undefined) {
                let error = `Something gone wrong. Api returned code ${resp.data.error_code}: ${resp.data.error}`;
                this.throwGeneralAxiosError(error);
            }

            return okMsg;
        } catch (error) {
            this.throwGeneralAxiosError(error);
        }
    }
}

module.exports = SMSC;
Repository: louislam/uptime-kuma
File: src/util-frontend.js (JavaScript)

Code before:
        showCloseButtonOnHover: true,

        filterBeforeCreate: (toast, toasts) => {
            if (toast.timeout === 0) {
                return false;
            } else {
                return toast;
            }
        },
    };
}

export function getToastSuccessTimeout() {
    let successTimeout = 20000;

    if (localStorage.toastSuccessTimeout !== undefined) {
        const parsedTimeout = parseInt(localStorage.toastSuccessTimeout);
        if (parsedTimeout != null && !Number.isNaN(parsedTimeout)) {
            successTimeout = parsedTimeout;
        }
    }

    if (successTimeout === -1) {
        successTimeout = false;
    }

    return successTimeout;
}

export function getToastErrorTimeout() {
    let errorTimeout = -1;

    if (localStorage.toastErrorTimeout !== undefined) {
        const parsedTimeout = parseInt(localStorage.toastErrorTimeout);
        if (parsedTimeout != null && !Number.isNaN(parsedTimeout)) {
            errorTimeout = parsedTimeout;
        }
    }

    if (errorTimeout === -1) {
        errorTimeout = false;
    }

    return errorTimeout;
}


Review comment (suggestion):
```suggestion
/**
 * Get timeout for success toasts
 * @returns {(number|boolean)} Timeout in ms. If false timeout disabled.
 */
export function getToastSuccessTimeout() {
```

Code after:

/**
 * Loads the toast timeout settings from storage.
 * @returns {object} The toast plugin options object.
 */
export function loadToastSettings() {
    return {
        position: POSITION.BOTTOM_RIGHT,
        containerClassName: "toast-container mb-5",
        showCloseButtonOnHover: true,

        filterBeforeCreate: (toast, toasts) => {
            if (toast.timeout === 0) {
                return false;
            } else {
                return toast;
            }
        },
    };
}

/**
 * Get timeout for success toasts
 * @returns {(number|boolean)} Timeout in ms. If false timeout disabled.
 */
export function getToastSuccessTimeout() {
    let successTimeout = 20000;

    if (localStorage.toastSuccessTimeout !== undefined) {
        const parsedTimeout = parseInt(localStorage.toastSuccessTimeout);
        if (parsedTimeout != null && !Number.isNaN(parsedTimeout)) {
            successTimeout = parsedTimeout;
        }
    }

    if (successTimeout === -1) {
        successTimeout = false;
    }

    return successTimeout;
}

/**
 * Get timeout for error toasts
 * @returns {(number|boolean)} Timeout in ms. If false timeout disabled.
 */
export function getToastErrorTimeout() {
    let errorTimeout = -1;

    if (localStorage.toastErrorTimeout !== undefined) {
        const parsedTimeout = parseInt(localStorage.toastErrorTimeout);
Repository: louislam/uptime-kuma
File: src/util-frontend.js (JavaScript)

Code before:
import dayjs from "dayjs";
import timezones from "timezones-list";
import { localeDirection, currentLocale } from "./i18n";
import { TYPE, POSITION } from "vue-toastification";

/**
 * Returns the offset from UTC in hours for the current locale.
 * @returns {number} The offset from UTC in hours.
 *
 * Generated by Trelent
 */
function getTimezoneOffset(timeZone) {
    const now = new Date();
    const tzString = now.toLocaleString("en-US", {
        timeZone,
    });
    const localString = now.toLocaleString("en-US");
    const diff = (Date.parse(localString) - Date.parse(tzString)) / 3600000;
    const offset = diff + now.getTimezoneOffset() / 60;
    return -offset;
}

/**
* Returns a list of timezones sorted by their offset from UTC.
* @param {Object[]} timezones An array of timezone objects.
* @returns {Object[]} A list of the given timezones sorted by their offset from UTC.
*
* Generated by Trelent
*/

Review comment (suggestion):
```suggestion
import { POSITION } from "vue-toastification";
```

Linter warning

Code after:
import dayjs from "dayjs";
import timezones from "timezones-list";
import { localeDirection, currentLocale } from "./i18n";
import { POSITION } from "vue-toastification";

/**
 * Returns the offset from UTC in hours for the current locale.
 * @param {string} timeZone Timezone to get offset for
 * @returns {number} The offset from UTC in hours.
 *
 * Generated by Trelent
 */
function getTimezoneOffset(timeZone) {
    const now = new Date();
    const tzString = now.toLocaleString("en-US", {
        timeZone,
    });
    const localString = now.toLocaleString("en-US");
    const diff = (Date.parse(localString) - Date.parse(tzString)) / 3600000;
    const offset = diff + now.getTimezoneOffset() / 60;
    return -offset;
}

/**
 * Returns a list of timezones sorted by their offset from UTC.
 * @returns {object[]} A list of the given timezones sorted by their offset from UTC.
 *
 * Generated by Trelent
 */
Repository: louislam/uptime-kuma
File: src/pages/DashboardHome.vue (Vue)

Code before:
                }

                if (a.time < b.time) {
                    return 1;
                }

                return 0;
            });

            // eslint-disable-next-line vue/no-side-effects-in-computed-properties
            this.heartBeatList = result;

            return result;
        },

        displayedRecords() {
            const startIndex = this.perPage * (this.page - 1);
            const endIndex = startIndex + this.perPage;
            return this.heartBeatList.slice(startIndex, endIndex);
        },
    },
    watch: {
        importantHeartBeatList() {
            this.$nextTick(() => {
                const tableContainer = this.$refs.tableContainer;
                const tableContainerHeight = tableContainer.offsetHeight;
                const availableHeight = this.calculatedHeight - tableContainerHeight;
                const additionalPerPage = Math.floor(availableHeight / 58);
                if (additionalPerPage > 0) {
                    this.perPage = Math.max(25, this.perPage + additionalPerPage);
                }
            });
        },
    },
};
</script>

<style lang="scss" scoped>
@import "../assets/vars";

.num {
    font-size: 30px;
    color: $primary;
    font-weight: bold;
    display: block;
}

.shadow-box {
    padding: 20px;
}


Review comment (suggestion):
```suggestion
                const tableContainerHeight = this.$refs.tableContainer.offsetHeight;
```

Code after:
                    return -1;
                }

                if (a.time < b.time) {
                    return 1;
                }

                return 0;
            });

            // eslint-disable-next-line vue/no-side-effects-in-computed-properties
            this.heartBeatList = result;

            return result;
        },

        displayedRecords() {
            const startIndex = this.perPage * (this.page - 1);
            const endIndex = startIndex + this.perPage;
            return this.heartBeatList.slice(startIndex, endIndex);
        },
    },
    watch: {
        importantHeartBeatList() {
            this.$nextTick(() => {
                this.updatePerPage();
            });
        },
    },
    mounted() {
        this.initialPerPage = this.perPage;

        window.addEventListener("resize", this.updatePerPage);
        this.updatePerPage();
    },
    beforeUnmount() {
        window.removeEventListener("resize", this.updatePerPage);
    },
    methods: {
        updatePerPage() {
            const tableContainer = this.$refs.tableContainer;
            const tableContainerHeight = tableContainer.offsetHeight;
            const availableHeight = window.innerHeight - tableContainerHeight;
            const additionalPerPage = Math.floor(availableHeight / 58);

            if (additionalPerPage > 0) {
                this.perPage = Math.max(this.initialPerPage, this.perPage + additionalPerPage);
            } else {
                this.perPage = this.initialPerPage;
            }
Repository: louislam/uptime-kuma
File: server/notification-providers/flashduty.js (JavaScript)

Code before:
const NotificationProvider = require("./notification-provider");
const axios = require("axios");
const { UP, DOWN, getMonitorRelativeURL } = require("../../src/util");
const { setting } = require("../util-server");
let successMessage = "Sent Successfully.";

class FlashDuty extends NotificationProvider {
    name = "FlashDuty";

    /**
     * @inheritdoc
     */
    async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
        try {
            if (heartbeatJSON == null) {
                const title = "Uptime Kuma Alert";
                const monitor = {
                    type: "ping",
                    url: "Uptime Kuma Test Button",
                };
                return this.postNotification(notification, title, msg, monitor);
            }

            if (heartbeatJSON.status === UP) {
                const title = "Uptime Kuma Monitor ✅ Up";

                return this.postNotification(notification, title, heartbeatJSON.msg, monitorJSON);
            }

            if (heartbeatJSON.status === DOWN) {

Review comment (suggestion):
```suggestion
const successMessage = "Sent Successfully.";
```

Code after:
const NotificationProvider = require("./notification-provider");
const axios = require("axios");
const { UP, DOWN, getMonitorRelativeURL } = require("../../src/util");
const { setting } = require("../util-server");
const successMessage = "Sent Successfully.";

class FlashDuty extends NotificationProvider {
    name = "FlashDuty";

    async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
        try {
            if (heartbeatJSON == null) {
                const title = "Uptime Kuma Alert";
                const monitor = {
                    type: "ping",
                    url: msg,
                    name: "https://flashcat.cloud"
                };
                return this.postNotification(notification, title, msg, monitor);
            }

            if (heartbeatJSON.status === UP) {
                const title = "Uptime Kuma Monitor ✅ Up";

                return this.postNotification(notification, title, heartbeatJSON.msg, monitorJSON, "Ok");
            }

            if (heartbeatJSON.status === DOWN) {
                const title = "Uptime Kuma Monitor 🔴 Down";
                return this.postNotification(notification, title, heartbeatJSON.msg, monitorJSON, notification.flashdutySeverity);
Repository: louislam/uptime-kuma
File: server/model/monitor.js (JavaScript)

Code before:
    }

    /**
     * Parse to boolean
     * @returns {boolean}
     */
    isInvertKeyword() {
        return Boolean(this.invertKeyword);
    }

    /**
     * Parse to boolean
     * @returns {boolean}
     */
    getGrpcEnableTls() {
        return Boolean(this.grpcEnableTls);
    }

    /**
     * Parse to boolean
     * @returns {boolean}
     */
    getCacheBust() {
        return Boolean(this.cacheBust);
    }

    /**
     * Get accepted status codes
     * @returns {Object}
     */
    getAcceptedStatuscodes() {
        return JSON.parse(this.accepted_statuscodes_json);
    }

    /**
     * Start monitor
     * @param {Server} io Socket server instance
     */
    start(io) {
        let previousBeat = null;
        let retries = 0;

        this.prometheus = new Prometheus(this);

        const beat = async () => {

            let beatInterval = this.interval;

            if (! beatInterval) {
                beatInterval = 1;
            }

Review comment (performance):
Is a new method really needed here? Given it is only used once I think, to me it seems cleaner just to put `Boolean(this.cacheBust)` where ever it is called.

```suggestion
```

Code after:
    }

    /**
     * Is the TLS expiry notification enabled?
     * @returns {boolean} Enabled?
     */
    isEnabledExpiryNotification() {
        return Boolean(this.expiryNotification);
    }

    /**
     * Parse to boolean
     * @returns {boolean} Should TLS errors be ignored?
     */
    getIgnoreTls() {
        return Boolean(this.ignoreTls);
    }

    /**
     * Parse to boolean
     * @returns {boolean} Is the monitor in upside down mode?
     */
    isUpsideDown() {
        return Boolean(this.upsideDown);
    }

    /**
     * Parse to boolean
     * @returns {boolean} Invert keyword match?
     */
    isInvertKeyword() {
        return Boolean(this.invertKeyword);
    }

    /**
     * Parse to boolean
     * @returns {boolean} Enable TLS for gRPC?
     */
    getGrpcEnableTls() {
        return Boolean(this.grpcEnableTls);
    }

    /**
     * Parse to boolean
     * @returns {boolean} if cachebusting is enabled
     */
    getCacheBust() {
        return Boolean(this.cacheBust);
    }

    /**