ronantakizawa/codereview-bench huggingface dataset:
Repository: louislam/uptime-kuma
File: server/routers/api-router.js (JavaScript)

Code before:

        const publicAvgPing = parseInt(await R.getCell(`
                SELECT AVG(ping) FROM monitor_group, \`group\`, heartbeat
                WHERE monitor_group.group_id = \`group\`.id
                AND heartbeat.time > DATETIME('now', ? || ' hours')
                AND heartbeat.ping IS NOT NULL
                AND public = 1
                AND heartbeat.monitor_id = ?
            `,
        [-requestedDuration, requestedMonitorId]
        ));

        const badgeValues = { style };

        if (!publicAvgPing) {
            // return a "N/A" badge in naColor (grey), if monitor is not public / not available / non exsitant

            badgeValues.message = "N/A";
            badgeValues.color = badgeConstants.naColor;
        } else {
            const avgPing = parseInt(overrideValue ?? publicAvgPing);

            badgeValues.color = color;
            // use a given, custom labelColor or use the default badge label color ( defined by badge-maker)
            badgeValues.labelColor = labelColor ?? "";
            // build a lable string. If a custom label is given, override the default one ( requestedDuration )
            badgeValues.label = filterAndJoin([labelPrefix, label ?? requestedDuration, labelSuffix]);
            badgeValues.message = filterAndJoin([prefix, avgPing, suffix]);
        }

        // build the SVG based on given values
        const svg = makeBadge(badgeValues);

        response.type("image/svg+xml");
        response.send(svg);
    } catch (error) {
        send403(response, error.message);
    }
});

async function checkPublished() {
    if (! await isPublished()) {
        throw new Error("The status page is not published");
    }
}

/**
 * Default is published
 * @returns {Promise<boolean>}
 */
async function isPublished() {

Review comment (suggestion):
```suggestion
            // build a lable string. If a custom label is given, override the default one (requestedDuration)
```

Code after:
            badgeValues.color = color;
            // use a given, custom labelColor or use the default badge label color (defined by badge-maker)
            badgeValues.labelColor = labelColor ?? "";
            // build a lable string. If a custom label is given, override the default one (requestedDuration)
            badgeValues.label = filterAndJoin([ labelPrefix, label ?? requestedDuration, labelSuffix ]);
            badgeValues.message = filterAndJoin([ prefix, avgPing, suffix ]);
        }

        // build the SVG based on given values
        const svg = makeBadge(badgeValues);

        response.type("image/svg+xml");
        response.send(svg);
    } catch (error) {
        send403(response, error.message);
    }
});

/**
 * Send a 403 response
 * @param {Object} res Express response object
 * @param {string} [msg=""] Message to send
 */
function send403(res, msg = "") {
    res.status(403).json({
        "status": "fail",
        "msg": msg,
    });
}

module.exports = router;
Repository: louislam/uptime-kuma
File: server/util-server.js (JavaScript)

Code before:

try {
    logFile = fs.createWriteStream("./data/error.log", {
        flags: "a"
    });
} catch (_) { }

exports.errorLog = (error, outputToConsole = true) => {
    try {
        if (logFile) {
            const dateTime = R.isoDateTime();
            logFile.write(`[${dateTime}] ` + nodeJsUtil.format(error) + "\n");

            if (outputToConsole) {
                console.error(error);
            }
        }
    } catch (_) { }
};

/**
 * Returns a color code in hex format based on a given percentage:
 * 0% => hue = 10 => red
 * 100% => hue = 90 => green
 *
 * @param {number} percentage, float, 0 to 1
 * @param {number} maxHue, int
 * @param {number} minHue, int
 * @returns {string}, hex value
 */
exports.percentageToColor = (percentage, maxHue = 90, minHue = 10) => {
    const hue = percentage * (maxHue - minHue) + minHue;
    try {
        return chroma(`hsl(${hue}, 90%, 40%)`).hex();
    } catch (err) {
        return badgeConstants.naColor;
    }
};

/**
 * Joins and array of string to one string after filtering out empty values
 *
 * @param {string[]} parts
 * @param {string} connector
 * @returns {string}
 */
exports.filterAndJoin = (parts, connector = "") => {
    return parts.filter((part) => !!part && part !== "").join(connector);
};


Review comment (suggestion):
```suggestion
 * @param {number} percentage float, 0 to 1
```

Perhaps remove the comma after each param


Code after:
    }

    const room = adapter.rooms.get(roomName);

    if (room) {
        return room.size;
    } else {
        return 0;
    }
};

/**
 * Allow CORS all origins if development
 * @param {Object} res Response object from axios
 */
exports.allowDevAllOrigin = (res) => {
    if (process.env.NODE_ENV === "development") {
        exports.allowAllOrigin(res);
    }
};

/**
 * Allow CORS all origins
 * @param {Object} res Response object from axios
 */
exports.allowAllOrigin = (res) => {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
};

/**
 * Check if a user is logged in
 * @param {Socket} socket Socket instance
 */
exports.checkLogin = (socket) => {
    if (!socket.userID) {
        throw new Error("You are not logged in.");
    }
};

/**
 * For logged-in users, double-check the password
 * @param {Socket} socket Socket.io instance
 * @param {string} currentPassword
 * @returns {Promise<Bean>}
 */
exports.doubleCheckPassword = async (socket, currentPassword) => {
    if (typeof currentPassword !== "string") {
        throw new Error("Wrong data type?");
    }
Repository: louislam/uptime-kuma
File: server/util-server.js (JavaScript)

Code before:
try {
    logFile = fs.createWriteStream("./data/error.log", {
        flags: "a"
    });
} catch (_) { }

exports.errorLog = (error, outputToConsole = true) => {
    try {
        if (logFile) {
            const dateTime = R.isoDateTime();
            logFile.write(`[${dateTime}] ` + nodeJsUtil.format(error) + "\n");

            if (outputToConsole) {
                console.error(error);
            }
        }
    } catch (_) { }
};

/**
 * Returns a color code in hex format based on a given percentage:
 * 0% => hue = 10 => red
 * 100% => hue = 90 => green
 *
 * @param {number} percentage, float, 0 to 1
 * @param {number} maxHue, int
 * @param {number} minHue, int
 * @returns {string}, hex value
 */
exports.percentageToColor = (percentage, maxHue = 90, minHue = 10) => {
    const hue = percentage * (maxHue - minHue) + minHue;
    try {
        return chroma(`hsl(${hue}, 90%, 40%)`).hex();
    } catch (err) {
        return badgeConstants.naColor;
    }
};

/**
 * Joins and array of string to one string after filtering out empty values
 *
 * @param {string[]} parts
 * @param {string} connector
 * @returns {string}
 */
exports.filterAndJoin = (parts, connector = "") => {
    return parts.filter((part) => !!part && part !== "").join(connector);
};


Review comment (suggestion):
```suggestion
 * @param {number} maxHue
```

There isn't really a need to specify int as well.


Code after:

    const room = adapter.rooms.get(roomName);

    if (room) {
        return room.size;
    } else {
        return 0;
    }
};

/**
 * Allow CORS all origins if development
 * @param {Object} res Response object from axios
 */
exports.allowDevAllOrigin = (res) => {
    if (process.env.NODE_ENV === "development") {
        exports.allowAllOrigin(res);
    }
};

/**
 * Allow CORS all origins
 * @param {Object} res Response object from axios
 */
exports.allowAllOrigin = (res) => {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
};

/**
 * Check if a user is logged in
 * @param {Socket} socket Socket instance
 */
exports.checkLogin = (socket) => {
    if (!socket.userID) {
        throw new Error("You are not logged in.");
    }
};

/**
 * For logged-in users, double-check the password
 * @param {Socket} socket Socket.io instance
 * @param {string} currentPassword
 * @returns {Promise<Bean>}
 */
exports.doubleCheckPassword = async (socket, currentPassword) => {
    if (typeof currentPassword !== "string") {
        throw new Error("Wrong data type?");
    }

    let user = await R.findOne("user", " id = ? AND active = 1 ", [
Repository: louislam/uptime-kuma
File: src/components/HeartbeatBar.vue (Vue)

Code before:

        &.empty {
            background-color: aliceblue;
        }

        &.down {
            background-color: $danger;
        }

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

        .beat-inner {
            border-radius: $border-radius;
            display: inline-block;
            height: 100%;
            width: 5px;
        }

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

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

</style>


Review comment (suggestion):
```suggestion
        }

        &.active-sibling {
```

Code after:
        display: inline-block;
        transition: all ease 0.6s;

        &.empty {
            background-color: aliceblue;
        }

        &.down {
            background-color: $danger;
        }

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

        .beat-inner {
            border-radius: $border-radius;
            display: inline-block;
            height: 100%;
            width: 5px;
        }

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

        &.active-sibling {
            transform: scale(1.3);
            transition: all ease 0.15s;
        }
    }
}

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

</style>
Repository: louislam/uptime-kuma
File: server/notification-providers/onebot.js (JavaScript)

Code before:

class OneBot extends NotificationProvider {

    name = "OneBot";

    async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
        let okMsg = "Sent Successfully.";
        try {
            let httpAddr = notification.httpAddr;
            if (!httpAddr.startsWith("http")) {
                httpAddr = "http://" + httpAddr;
            }
            if (!httpAddr.endsWith("/")) {
                httpAddr += "/";
            }
            let onebotAPIUrl = httpAddr + "send_msg";
            let config = {
                headers: {
                    "Content-Type": "application/json",
                    "Authorization": "Bearer " + notification.accessToken
                }
            };
            let psuhText = "UptimeKuma Alert: " + msg;
            let data = {
                "auto_escape": true,
                "message": psuhText
            };
            if (notification.msgType == "group") {
                data["message_type"] = "group";
                data["group_id"] = notification.recieverId;
            } else {
                data["message_type"] = "private";
                data["user_id"] = notification.recieverId;
            }
            await axios.post(onebotAPIUrl, data, config);
            return okMsg;
        } catch (error) {
            this.throwGeneralAxiosError(error);
        }
    }
}

module.exports = OneBot;


Review comment (suggestion):
```suggestion
                "message": psuhText,
```

Code after:

class OneBot extends NotificationProvider {

    name = "OneBot";

    async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
        let okMsg = "Sent Successfully.";
        try {
            let httpAddr = notification.httpAddr;
            if (!httpAddr.startsWith("http")) {
                httpAddr = "http://" + httpAddr;
            }
            if (!httpAddr.endsWith("/")) {
                httpAddr += "/";
            }
            let onebotAPIUrl = httpAddr + "send_msg";
            let config = {
                headers: {
                    "Content-Type": "application/json",
                    "Authorization": "Bearer " + notification.accessToken,
                }
            };
            let pushText = "UptimeKuma Alert: " + msg;
            let data = {
                "auto_escape": true,
                "message": pushText,
            };
            if (notification.msgType == "group") {
                data["message_type"] = "group";
                data["group_id"] = notification.recieverId;
            } else {
                data["message_type"] = "private";
                data["user_id"] = notification.recieverId;
            }
            await axios.post(onebotAPIUrl, data, config);
            return okMsg;
        } catch (error) {
            this.throwGeneralAxiosError(error);
        }
    }
}

module.exports = OneBot;
Repository: louislam/uptime-kuma
File: server/notification-providers/pagerduty.js (JavaScript)

Code before:
            monitorUrl = monitorInfo.url;
        }

        const options = {
            method: "POST",
            url: notification.pagerdutyIntegrationUrl,
            headers: { "Content-Type": "application/json" },
            data: {
                payload: {
                    summary: `[${title}] [${monitorInfo.name}] ${body}`,
                    severity: notification.pagerdutyPriority || "warning",
                    source: monitorUrl,
                },
                routing_key: notification.pagerdutyIntegrationKey,
                event_action: eventAction,
                dedup_key: "Uptime Kuma/" + monitorInfo.id,
            }
        };

        const baseURL = await setting("primaryBaseURL");
        if (baseURL && monitorInfo) {
            options.client = "Uptime Kuma";
            options.client_url = baseURL + getMonitorRelativeURL(monitorInfo.id);
        }

        debug(options);

        let result = await axios.request(options);
        this.checkResult(result);
        if (result.statusText != null) {
            return "PagerDuty notification succeed: " + result.statusText;
        }

        return successMessage;
    }
}

module.exports = PagerDuty;


Review comment (bug):
Should this be changed to `log.debug()`. `debug()` has been depreceated since #910 

Code after:
     */
    async postNotification(notification, title, body, monitorInfo, eventAction = "trigger") {

        if (eventAction == null) {
            return "No action required";
        }

        let monitorUrl;
        if (monitorInfo.type === "port") {
            monitorUrl = monitorInfo.hostname;
            if (monitorInfo.port) {
                monitorUrl += ":" + monitorInfo.port;
            }
        } else if (monitorInfo.hostname != null) {
            monitorUrl = monitorInfo.hostname;
        } else {
            monitorUrl = monitorInfo.url;
        }

        const options = {
            method: "POST",
            url: notification.pagerdutyIntegrationUrl,
            headers: { "Content-Type": "application/json" },
            data: {
                payload: {
                    summary: `[${title}] [${monitorInfo.name}] ${body}`,
                    severity: notification.pagerdutyPriority || "warning",
                    source: monitorUrl,
                },
                routing_key: notification.pagerdutyIntegrationKey,
                event_action: eventAction,
                dedup_key: "Uptime Kuma/" + monitorInfo.id,
            }
        };

        const baseURL = await setting("primaryBaseURL");
        if (baseURL && monitorInfo) {
            options.client = "Uptime Kuma";
            options.client_url = baseURL + getMonitorRelativeURL(monitorInfo.id);
        }

        let result = await axios.request(options);
        this.checkResult(result);
        if (result.statusText != null) {
            return "PagerDuty notification succeed: " + result.statusText;
        }

        return successMessage;
    }
}
Repository: louislam/uptime-kuma
File: extra/update-language-files/index.js (JavaScript)

Code before:
const files = fs.readdirSync("./languages");
console.log("Files:", files);

for (const file of files) {
    if (!file.endsWith(".js")) {
        console.log("Skipping " + file);
        continue;
    }

    console.log("Processing " + file);
    const lang = await import("./languages/" + file);

    let obj;

    if (lang.default) {
        obj = lang.default;
    } else {
        console.log("Empty file");
        obj = {
            languageName: "<Your Language name in your language (not in English)>"
        };
    }

    // En first
    for (const key in en) {
        if (!obj[key]) {
            obj[key] = en[key];
        }
    }

    if (baseLang !== en) {
        // Base second
        for (const key in baseLang) {
            if (!obj[key]) {
                obj[key] = key;
            }
        }
    }

    const code = "export default " + util.inspect(obj, {
        depth: null,
    });

    fs.writeFileSync(`../../src/languages/${file}`, code);
}

rmSync("./languages", { recursive: true });
console.log("Done. Fixing formatting by ESLint...");


Review comment (suggestion):
It might be worth leaving the space between the `!` and `obj[key]` just to fit with the rest of the codebase.

Code after:
const files = fs.readdirSync("./languages");
console.log("Files:", files);

for (const file of files) {
    if (! file.endsWith(".js")) {
        console.log("Skipping " + file);
        continue;
    }

    console.log("Processing " + file);
    const lang = await import("./languages/" + file);

    let obj;

    if (lang.default) {
        obj = lang.default;
    } else {
        console.log("Empty file");
        obj = {
            languageName: "<Your Language name in your language (not in English)>"
        };
    }

    // En first
    for (const key in en) {
        if (! obj[key]) {
            obj[key] = en[key];
        }
    }

    if (baseLang !== en) {
        // Base second
        for (const key in baseLang) {
            if (! obj[key]) {
                obj[key] = key;
            }
        }
    }

    const code = "export default " + util.inspect(obj, {
        depth: null,
    });

    fs.writeFileSync(`../../src/languages/${file}`, code);
}

rmSync("./languages", { recursive: true });
console.log("Done. Fixing formatting by ESLint...");
Repository: louislam/uptime-kuma
File: server/util-server.js (JavaScript)

Code before:
    return new Promise((resolve, reject) => {
        mssql.on("error", err => {
            reject(err);
        });

        mssql.connect(connectionString).then(pool => {
            return pool.request()
                .query(query);
        }).then(result => {
            resolve(result);
        }).catch(err => {
            reject(err);
        }).finally(() => {
            mssql.close();
        });
    });
};

/**
 * Run a query on Postgres
 * @param {string} connectionString The database connection string
 * @param {string} query The query to validate the database with
 * @returns {Promise<(string[]|Object[]|Object)>}
 */
exports.postgresQuery = function (connectionString, query) {

    return new Promise((resolve, reject) => {

        const config = postgresConParse(connectionString);

        if (config.password === "") {
            // See https://github.com/brianc/node-postgres/issues/1927
            return reject(new Error("Password is undefined."));
        }

        const client = new Client({ connectionString });

        client.connect();

        return client.query(query)
            .then(res => {
                resolve(res);
            })
            .catch(err => {
                reject(err);
            })
            .finally(() => {
                client.end();
            });
    });
};

Review comment (refactor):
```suggestion
```
Perhaps remove this blank line

Code after:
exports.mssqlQuery = function (connectionString, query) {
    return new Promise((resolve, reject) => {
        mssql.connect(connectionString).then(pool => {
            return pool.request()
                .query(query);
        }).then(result => {
            resolve(result);
        }).catch(err => {
            reject(err);
        }).finally(() => {
            mssql.close();
        });
    });
};

/**
 * Run a query on Postgres
 * @param {string} connectionString The database connection string
 * @param {string} query The query to validate the database with
 * @returns {Promise<(string[]|Object[]|Object)>}
 */
exports.postgresQuery = function (connectionString, query) {
    return new Promise((resolve, reject) => {
        const config = postgresConParse(connectionString);

        if (config.password === "") {
            // See https://github.com/brianc/node-postgres/issues/1927
            return reject(new Error("Password is undefined."));
        }

        const client = new Client({ connectionString });

        client.connect();

        return client.query(query)
            .then(res => {
                resolve(res);
            })
            .catch(err => {
                reject(err);
            })
            .finally(() => {
                client.end();
            });
    });
};

/**
 * Retrieve value of setting based on key
 * @param {string} key Key of setting to retrieve
 * @returns {Promise<any>} Value