ronantakizawa/codereview-bench huggingface dataset:
Repository: iamkun/dayjs
File: src/index.js (JavaScript)

Code before:
import * as C from './constant'
import en from './locale/en'
import U from './utils'

let L = 'en' // global locale
const Ls = {} // global loaded locale
Ls[L] = en

const isDayjs = d => d instanceof Dayjs // eslint-disable-line no-use-before-define

const parseLocale = (preset, object, isLocal) => {
  let l
  if (!preset) return L
  if (typeof preset === 'string') {
    const presetLower = preset.toLowerCase()
    if (Ls[presetLower]) {
      l = presetLower
    }
    if (object) {
      Ls[presetLower] = object
      l = presetLower
    }
    const presetSplit = preset.split('-')
    if (!l && presetSplit.length > 1) {
      return parseLocale(presetSplit[0])
    }
  } else {
    const { name } = preset
    Ls[name] = preset
    l = name
  }
  if (!isLocal && l) L = l
  return l || (!isLocal && L)
}

const dayjs = function (date, c) {
  if (isDayjs(date)) {

Review comment (bug):
I have a problem related to this change. We have a Dayjs object that we store in `location.state` where it get's serialized. Upon retrieving said object we use `isDayjs` to check whether the object is actually of type `Dayjs` or if we have to parse it, something along the lines of

```ts
const maybeBrokenDayjs(obj: any) => {
  if (isDayjs(obj) {
    return obj;
  } else if (obj?.$d) {
    return dayjs(obj.$d)
  }
}
```

This now obviously breaks as `isDayjs` will suddenly yield `true`. While this is of course easily fixable it is a breaking change and thus quite unexpected in a Patch-Release :(

Code after:
import * as C from './constant'
import en from './locale/en'
import U from './utils'

let L = 'en' // global locale
const Ls = {} // global loaded locale
Ls[L] = en

const IS_DAYJS = '$isDayjsObject'

// eslint-disable-next-line no-use-before-define
const isDayjs = d => d instanceof Dayjs || !!(d && d[IS_DAYJS])

const parseLocale = (preset, object, isLocal) => {
  let l
  if (!preset) return L
  if (typeof preset === 'string') {
    const presetLower = preset.toLowerCase()
    if (Ls[presetLower]) {
      l = presetLower
    }
    if (object) {
      Ls[presetLower] = object
      l = presetLower
    }
    const presetSplit = preset.split('-')
    if (!l && presetSplit.length > 1) {
      return parseLocale(presetSplit[0])
    }
  } else {
    const { name } = preset
    Ls[name] = preset
    l = name
  }
  if (!isLocal && l) L = l
  return l || (!isLocal && L)
}
Repository: iamkun/dayjs
File: src/plugin/negativeYear/index.js (JavaScript)

Code before:
export default (_, c, dayjs) => {
  const proto = c.prototype

  const parseDate = (cfg) => {
    const { date } = cfg
    const newDate = new Date(date)
    const fullYear = newDate.getFullYear()
    if (typeof date === 'string' && date.indexOf(`-${fullYear}`) !== -1) {
      return dayjs(newDate).subtract(fullYear * 2, 'year').toDate()
    }
    return newDate
  }

  const oldParse = proto.parse
  proto.parse = function (cfg) {
    cfg.date = parseDate.bind(this)(cfg)
    oldParse.bind(this)(cfg)
  }
}



Review comment (suggestion):
maybe we should return date not newDate, cause `cfg.date` is the untouched original one, just leave it to the current main parse logic

Code after:
export default (_, c, dayjs) => {
  const proto = c.prototype

  const parseDate = (cfg) => {
    const { date } = cfg
    if (typeof date === 'string' && date.charAt(0) === '-') {
      const newDate = new Date(date.slice(1))
      const fullYear = newDate.getFullYear()
      if (date.indexOf(`-${fullYear}`) !== -1) {
        return dayjs(newDate).subtract(fullYear * 2, 'year').toDate()
      }
      return date
    }
    return date
  }

  const oldParse = proto.parse
  proto.parse = function (cfg) {
    cfg.date = parseDate.bind(this)(cfg)
    oldParse.bind(this)(cfg)
  }
}
Repository: jackMort/ChatGPT.nvim
File: lua/chatgpt.lua (Lua)

Code before:


--
-- public methods for the plugin
--

M.openChat = function()
  module.openChat()
end

M.selectAwesomePrompt = function()
  module.open_chat_with_awesome_prompt()
end

M.edit_with_instructions = function()
  module.edit_with_instructions()
end

M.run_action = function(opts)
  module.run_action(opts)
end

-- M.run_custom_code_action = function(opts)
--   module.run_custom_code_action(opts)
-- end

return M


Review comment (suggestion):
Please keep `complete_code `as it is. It's a different flow in the early stage, but I'm going to work on it more to make it work similar to Copilot.

Code after:
-- main module file
local module = require("chatgpt.module")
local config = require("chatgpt.config")
local signs = require("chatgpt.signs")

local M = {}

M.setup = function(options)
  -- set custom highlights
  vim.api.nvim_set_hl(0, "ChatGPTQuestion", { fg = "#b4befe", italic = true, bold = false, default = true })
  vim.api.nvim_set_hl(0, "ChatGPTWelcome", { fg = "#9399b2", italic = true, bold = false, default = true })
  vim.api.nvim_set_hl(0, "ChatGPTTotalTokens", { fg = "#ffffff", bg = "#444444", default = true })
  vim.api.nvim_set_hl(0, "ChatGPTTotalTokensBorder", { fg = "#444444", default = true })
  vim.api.nvim_set_hl(0, "ChatGPTCompletion", { fg = "#9399b2", italic = true, bold = false, default = true })

  config.setup(options)
  signs.setup()
end

--
-- public methods for the plugin
--

M.openChat = function()
  module.openChat()
end

M.selectAwesomePrompt = function()
  module.open_chat_with_awesome_prompt()
end

M.edit_with_instructions = function()
  module.edit_with_instructions()
end

M.run_action = function(opts)
  module.run_action(opts)
end

M.complete_code = module.complete_code

return M
Repository: jackMort/ChatGPT.nvim
File: lua/chatgpt/api.lua (Lua)

Code before:
  job
    :new({
      command = cmd[1],
      args = vim.list_slice(cmd, 2, #cmd),
      on_exit = function(j, exit_code)
        if exit_code ~= 0 then
          logger.warn("Config 'api_key_cmd' did not return a value when executed")
          return
        end
        Api.OPENAI_API_KEY = j:result()[1]:gsub("%s+$", "")
      end,
    })
    :start()
end

function Api.setup()
  Api.OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
  if not Api.OPENAI_API_KEY then
    if Config.options.api_key_cmd ~= nil and Config.options.api_key_cmd ~= "" then
      loadApiKey(Config.options.api_key_cmd)
    else
      logger.warn("OPENAI_API_KEY environment variable not set")
      return
    end
  end
  if Api.OPENAI_API_KEY ~=nil and Api.OPENAI_API_KEY ~= "" then
    Api.OPENAI_API_KEY = Api.OPENAI_API_KEY:gsub("%s+$", "")
  end
end

return Api


Review comment (suggestion):
```suggestion
  if Api.OPENAI_API_KEY ~= nil and Api.OPENAI_API_KEY ~= "" then
```

Code after:
  job
    :new({
      command = cmd[1],
      args = vim.list_slice(cmd, 2, #cmd),
      on_exit = function(j, exit_code)
        if exit_code ~= 0 then
          logger.warn("Config 'api_key_cmd' did not return a value when executed")
          return
        end
        Api.OPENAI_API_KEY = j:result()[1]:gsub("%s+$", "")
      end,
    })
    :start()
end

function Api.setup()
  Api.OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
  if not Api.OPENAI_API_KEY then
    if Config.options.api_key_cmd ~= nil and Config.options.api_key_cmd ~= "" then
      loadApiKey(Config.options.api_key_cmd)
    else
      logger.warn("OPENAI_API_KEY environment variable not set")
      return
    end
  end
  if Api.OPENAI_API_KEY ~= nil and Api.OPENAI_API_KEY ~= "" then
    Api.OPENAI_API_KEY = Api.OPENAI_API_KEY:gsub("%s+$", "")
  end
end

return Api
Repository: jenkinsci/jenkins
File: core/src/main/resources/lib/layout/copyButton/copyButton.js (JavaScript)

Code before:
Behaviour.specify(
  ".jenkins-copy-button",
  "copyButton",
  0,
  function (copyButton) {
    copyButton.addEventListener("click", () => {
      if (isSecureContext) {
        // Copy the text to the clipboard
        navigator.clipboard
          .writeText(copyButton.getAttribute("text"))
          .then(() => {
            // Show the completion message
            hoverNotification(copyButton.getAttribute("message"), copyButton);
          })
          .catch(() => {
            hoverNotification(
              "Could not get permission to write to clipboard",
              copyButton,
            );
          });
      } else {
        hoverNotification(
          "Copy is only supported with a secure (HTTPS) connection",
          copyButton,
        );
      }
    });
  },
);


Review comment (suggestion):
This PR should have restructured the code to make this conditional on `text` being non-empty. It not doing that seems to have allowed https://github.com/jenkinsci/jenkins/issues/25976 to happen.

Code after:
Behaviour.specify(
  ".jenkins-copy-button",
  "copyButton",
  0,
  function (copyButton) {
    copyButton.addEventListener("click", () => {
      if (isSecureContext) {
        var text = copyButton.getAttribute("text");
        if (copyButton.hasAttribute("ref")) {
          var ref = copyButton.getAttribute("ref");
          var target = document.getElementById(ref);
          if (target) {
            text = target.innerText;
          }
        }

        // Copy the text to the clipboard
        navigator.clipboard
          .writeText(text)
          .then(() => {
            // Show the completion message
            hoverNotification(copyButton.getAttribute("message"), copyButton);
          })
          .catch(() => {
            hoverNotification(
              "Could not get permission to write to clipboard",
              copyButton,
            );
          });
      } else {
        hoverNotification(
          "Copy is only supported with a secure (HTTPS) connection",
          copyButton,
        );
      }
    });
  },
);
Repository: jenkinsci/jenkins
File: war/src/main/js/components/dropdowns/utils.js (JavaScript)

Code before:
import Templates from "@/components/dropdowns/templates";
import makeKeyboardNavigable from "@/util/keyboard";
import tippy from "tippy.js";
import behaviorShim from "@/util/behavior-shim";

const SELECTED_ITEM_CLASS = "jenkins-dropdown__item--selected";

/*
 * Generates the dropdowns for the given element
 * Preloads the data on hover for speed
 * @param element - the element to generate the dropdown for
 * @param callback - called to retrieve the list of dropdown items
 */
function generateDropdown(element, callback, immediate) {
  tippy(
    element,
    Object.assign({}, Templates.dropdown(), {
      hideOnClick: element.dataset["hideOnClick"] != "false",
      onCreate(instance) {
        const onload = () => {
          if (instance.loaded) {
            return;
          }

          instance.popper.addEventListener("click", () => {
            instance.hide();
          });

          callback(instance);
        };
        if (immediate) {
          onload();
        } else {
          instance.reference.addEventListener("mouseenter", onload);
        }
      },
    }),
  );
}

/*
 * Generates the contents for the dropdown
 */

Review comment (suggestion):
```suggestion
      hideOnClick: element.dataset["hideOnClick"] !== "false",
```

Code after:
import Templates from "@/components/dropdowns/templates";
import makeKeyboardNavigable from "@/util/keyboard";
import tippy from "tippy.js";
import behaviorShim from "@/util/behavior-shim";

const SELECTED_ITEM_CLASS = "jenkins-dropdown__item--selected";

/*
 * Generates the dropdowns for the given element
 * Preloads the data on hover for speed
 * @param element - the element to generate the dropdown for
 * @param callback - called to retrieve the list of dropdown items
 */
function generateDropdown(element, callback, immediate) {
  tippy(
    element,
    Object.assign({}, Templates.dropdown(), {
      hideOnClick: element.dataset["hideOnClick"] !== "false",
      onCreate(instance) {
        const onload = () => {
          if (instance.loaded) {
            return;
          }

          instance.popper.addEventListener("click", () => {
            instance.hide();
          });

          callback(instance);
        };
        if (immediate) {
          onload();
        } else {
          instance.reference.addEventListener("mouseenter", onload);
        }
      },
    }),
  );
}

/*
 * Generates the contents for the dropdown
 */
Repository: jenkinsci/jenkins
File: core/src/main/java/jenkins/health/HealthCheckAction.java (Java)

Code before:
 * THE SOFTWARE.
 */

package jenkins.health;

import hudson.Extension;
import hudson.ExtensionList;
import hudson.model.InvisibleAction;
import hudson.model.UnprotectedRootAction;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.DoNotUse;
import org.kohsuke.stapler.HttpResponse;
import org.kohsuke.stapler.json.JsonHttpResponse;

/**
 * Provides a health check action for Jenkins.
 */
@Extension
@Restricted(DoNotUse.class)
public final class HealthCheckAction extends InvisibleAction implements UnprotectedRootAction {

    @Override
    public String getUrlName() {
        return "healthCheck";
    }

    public HttpResponse doIndex() {
        boolean success = true;
        var checks = new JSONArray();
        for (var healthCheck : ExtensionList.lookup(HealthCheck.class)) {
            var check = healthCheck.check();
            var name = healthCheck.getName();
            success &= check;
            checks.add(new JSONObject().element("name", name).element("result", check));
        }
        return new JsonHttpResponse(new JSONObject().element("status", success).element("data", checks), success ? 200 : 503);
    }
}


Review comment (suggestion):
Potentially? matches spring (although that prefixes it with actuator)
```suggestion
        return "health";
```

Code after:
 * THE SOFTWARE.
 */

package jenkins.health;

import hudson.Extension;
import hudson.ExtensionList;
import hudson.model.InvisibleAction;
import hudson.model.UnprotectedRootAction;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;
import org.kohsuke.stapler.HttpResponse;
import org.kohsuke.stapler.json.JsonHttpResponse;

/**
 * Provides a health check action for Jenkins.
 */
@Extension
@Restricted(NoExternalUse.class)
public final class HealthCheckAction extends InvisibleAction implements UnprotectedRootAction {

    @Override
    public String getUrlName() {
        return "health";
    }

    public HttpResponse doIndex() {
        boolean success = true;
        var failing = new JSONArray();
        for (var healthCheck : ExtensionList.lookup(HealthCheck.class)) {
            var check = healthCheck.check();
            success &= check;
            if (!check) {
                failing.add(healthCheck.getName());
            }
        }
        var payload = new JSONObject().element("status", success);
        if (!success) {
            payload = payload.element("failures", failing);
        }
        return new JsonHttpResponse(payload, success ? 200 : 503);
    }
}
Repository: jenkinsci/jenkins
File: core/src/main/java/hudson/model/Computer.java (Java)

Code before:
    @Deprecated
    @Restricted(DoNotUse.class)
    public BuildTimelineWidget getTimeline() {
        return new BuildTimelineWidget(getBuilds());
    }

    @Exported
    @Override
    public boolean isOffline() {
        return isTemporarilyOffline() || getChannel() == null;
    }

    public final boolean isOnline() {
        return !isOffline();
    }

    public boolean isConnected() {
        return getChannel() != null;
    }

    /**
     * This method is called to determine whether manual launching of the agent is allowed at this point in time.
     * @return {@code true} if manual launching of the agent is allowed at this point in time.
     */
    @Exported
    public boolean isManualLaunchAllowed() {
        return getRetentionStrategy().isManualLaunchAllowed(this);
    }

    /**
     * Returns true if this computer is supposed to be launched via inbound protocol.
     * @deprecated since 2008-05-18.
     *     See {@linkplain #isLaunchSupported()} and {@linkplain ComputerLauncher}
     */
    @Exported
    @Deprecated
    public boolean isJnlpAgent() {
        return false;
    }

    @Exported
    @Override
    public boolean isLaunchSupported() {
        return true;
    }

    /**
     * Returns true if this node is marked temporarily offline by the user.
     *
     * <p>
     * In contrast, {@link #isOffline()} represents the actual online/offline

Review comment (suggestion):
Missing `@Override`, and should `@inheritDoc` then explain that it is checking `getChannel`.

Code after:
    @Deprecated
    @Restricted(DoNotUse.class)
    public BuildTimelineWidget getTimeline() {
        return new BuildTimelineWidget(getBuilds());
    }

    @Exported
    @Override
    public boolean isOffline() {
        return isTemporarilyOffline() || getChannel() == null;
    }

    public final boolean isOnline() {
        return !isOffline();
    }

    /**
     * {@inheritDoc}
     * <p>
     * Uses {@link #getChannel()} to check the connection.
     * A connected agent may still be offline for scheduling if marked temporarily offline.
     * @return {@code true} if the agent is connected, {@code false} otherwise.
     * @see #isOffline()
     */
    @Override
    public boolean isConnected() {
        return getChannel() != null;
    }

    /**
     * This method is called to determine whether manual launching of the agent is allowed at this point in time.
     * @return {@code true} if manual launching of the agent is allowed at this point in time.
     */
    @Exported
    public boolean isManualLaunchAllowed() {
        return getRetentionStrategy().isManualLaunchAllowed(this);
    }

    /**
     * Returns true if this computer is supposed to be launched via inbound protocol.
     * @deprecated since 2008-05-18.
     *     See {@linkplain #isLaunchSupported()} and {@linkplain ComputerLauncher}
     */
    @Exported
    @Deprecated
    public boolean isJnlpAgent() {
        return false;
    }

    @Exported
    @Override
Repository: jenkinsci/jenkins
File: src/main/js/components/dropdowns/utils.js (JavaScript)

Code before:
                if (!isMouseOverAnyDropdown) {
                  instance.hide();
                  document.removeEventListener("mousemove", handleMouseMove);
                }
              };

              document.addEventListener("mousemove", handleMouseMove);
            });

            callback(instance);
          };
          if (immediate) {
            onload();
          } else {
            ["mouseenter", "focus"].forEach((event) => {
              instance.reference.addEventListener(event, onload);
            });
          }
        },
        onHide() {
          const dropdowns = document.querySelectorAll("[data-tippy-root]");
          const isMouseOverAnyDropdown = Array.from(dropdowns).some((dropdown) =>
            dropdown.matches(":hover")
          );

          return isMouseOverAnyDropdown ? false : true
        },
      },
      options,
    ),
  );
}

/*
 * Generates the contents for the dropdown
 */
function generateDropdownItems(items, compact) {
  const menuItems = document.createElement("div");
  menuItems.classList.add("jenkins-dropdown");
  if (compact === true) {
    menuItems.classList.add("jenkins-dropdown--compact");
  }

  items
    .map((item) => {
      if (item.type === "CUSTOM") {
        return item.contents;
      }

      if (item.type === "HEADER") {
        return Templates.heading(item.label);

Review comment (suggestion):

```suggestion
          return !isMouseOverAnyDropdown
```

Code after:

                if (!isMouseOverAnyDropdown) {
                  instance.hide();
                  document.removeEventListener("mousemove", handleMouseMove);
                }
              };

              document.addEventListener("mousemove", handleMouseMove);
            });

            callback(instance);
          };
          if (immediate) {
            onload();
          } else {
            ["mouseenter", "focus"].forEach((event) => {
              instance.reference.addEventListener(event, onload);
            });
          }
        },
        onHide() {
          const dropdowns = document.querySelectorAll("[data-tippy-root]");
          const isMouseOverAnyDropdown = Array.from(dropdowns).some(
            (dropdown) => dropdown.matches(":hover"),
          );

          return !isMouseOverAnyDropdown;
        },
      },
      options,
    ),
  );
}

/*
 * Generates the contents for the dropdown
 */
function generateDropdownItems(items, compact) {
  const menuItems = document.createElement("div");
  menuItems.classList.add("jenkins-dropdown");
  if (compact === true) {
    menuItems.classList.add("jenkins-dropdown--compact");
  }

  items
    .map((item) => {
      if (item.type === "CUSTOM") {
        return item.contents;
      }

      if (item.type === "HEADER") {
Repository: jenkinsci/jenkins
File: src/main/js/components/dropdowns/utils.js (JavaScript)

Code before:
            }

            document.addEventListener("click", (event) => {
              const isClickOnReference = instance.reference.contains(
                event.target,
              );

              if (!isClickOnReference) {
                instance.clickToHide = true;
                instance.hide();
              }
            });

            callback(instance);
          };
          if (immediate) {
            onload();
          } else {
            ["mouseenter", "focus"].forEach((event) => {
              instance.reference.addEventListener(event, onload);
            });
          }
        },
        onHide(instance) {
          if (
            instance.props.trigger === "mouseenter" &&
            !instance.clickToHide
          ) {
            const dropdowns = document.querySelectorAll("[data-tippy-root]");
            const isMouseOverAnyDropdown = Array.from(dropdowns).some(
              (dropdown) => dropdown.matches(":hover"),
            );

            return !isMouseOverAnyDropdown;
          }

          instance.clickToHide = false;
          return true;
        },
      },
      options,
    ),
  );
}

/*
 * Generates the contents for the dropdown
 */
function generateDropdownItems(items, compact) {
  const menuItems = document.createElement("div");
  menuItems.classList.add("jenkins-dropdown");

Review comment (suggestion):
Something in here is breaking the theme manager quick change under user profile.

<img width="293" height="519" alt="Image" src="https://github.com/user-attachments/assets/6157ef5f-33e6-4038-adfe-73fd76b21ce7" />

Clicking to change theme closes the jumplist

Code after:
            }

            document.addEventListener("click", (event) => {
              const isClickOnReference = instance.reference.contains(
                event.target,
              );
              // Don't close the dropdown if the user is interacting with a SELECT menu inside of it
              const isSelect = event.target.tagName === "SELECT";

              if (!isClickOnReference && !isSelect) {
                instance.clickToHide = true;
                instance.hide();
              }
            });

            callback(instance);
          };
          if (immediate) {
            onload();
          } else {
            ["mouseenter", "focus"].forEach((event) => {
              instance.reference.addEventListener(event, onload);
            });
          }
        },
        onHide(instance) {
          if (
            instance.props.trigger === "mouseenter" &&
            !instance.clickToHide
          ) {
            const dropdowns = document.querySelectorAll("[data-tippy-root]");
            const isMouseOverAnyDropdown = Array.from(dropdowns).some(
              (dropdown) => dropdown.matches(":hover"),
            );

            return !isMouseOverAnyDropdown;
          }

          instance.clickToHide = false;
          return true;
        },
      },
      options,
    ),
  );
}

/*
 * Generates the contents for the dropdown
 */
function generateDropdownItems(items, compact) {