ronantakizawa/codereview-bench huggingface dataset:
Repository: neherlab/covid19_scenarios
File: config/webpack/webpack.client.babel.ts (TypeScript)

Code before:
      errors: true,
    },
    port: portDev,
    publicPath: '/',
    quiet: false,
    logLevel: 'info',
    clientLogLevel: 'warning',
    writeToDisk: true,
  },

  module: {
    rules: [
      ...webpackLoadJavascript({
        babelConfig,
        // eslintConfigFile: path.join(moduleRoot, '.eslintrc.js'),
        options: { caller: { target: 'web' } },
        sourceMaps,
        transpiledLibs: [
          '@loadable',
          '@redux-saga',
          'create-color',
          'd3-array',
          'delay',
          'immer',
          'immer',
          // 'lodash',
          'p-min-delay',
          'react-router',
          'recharts',
          'redux/es',
        ],
        nonTranspiledLibs: ['d3-array/src/cumsum.js'],
      }),

      ...webpackLoadStyles({
        isDev: development,
        isServer: false,
        sourceMap: sourceMaps,
      }),

      ...webpackLoadAssets({
        isDev: development,
        inlineSmallerThan: 0,
        subdirectory: 'assets',
      }),
    ],
  },

  resolve: {
    symlinks: false,


Review comment (suggestion):
`lodash` is used by the algorithm, and the algorithm is imported into a webworker. If this line left uncommented, lodash is modified by babel for hot reloading, which results in webworker throwing an error. This fix needs a better implementation.

Code after:
      errors: true,
    },
    port: portDev,
    publicPath: '/',
    quiet: false,
    logLevel: 'info',
    clientLogLevel: 'warning',
    writeToDisk: true,
  },

  module: {
    rules: [
      ...webpackLoadJavascript({
        babelConfig,
        // eslintConfigFile: path.join(moduleRoot, '.eslintrc.js'),
        options: { caller: { target: 'web' } },
        sourceMaps,
        transpiledLibs: production && [
          '@loadable',
          '@redux-saga',
          'create-color',
          'd3-array',
          'delay',
          'immer',
          'immer',
          'lodash',
          'p-min-delay',
          'react-router',
          'recharts',
          'redux/es',
        ],
        nonTranspiledLibs: production && ['d3-array/src/cumsum.js'],
      }),

      ...webpackLoadStyles({
        isDev: development,
        isServer: false,
        sourceMap: sourceMaps,
      }),

      ...webpackLoadAssets({
        isDev: development,
        inlineSmallerThan: 0,
        subdirectory: 'assets',
      }),
    ],
  },

  resolve: {
    symlinks: false,
Repository: neherlab/covid19_scenarios
File: src/components/Main/Results/Utils.ts (TypeScript)

Code before:
export type maybeNumber = number | undefined

export function verifyPositive(x: number): maybeNumber {
  return x > 0 ? Math.ceil(x) : undefined
}

export function verifyTuple(x: [maybeNumber, maybeNumber]): [number, number] | undefined {
  if (x[0] !== undefined && x[1] !== undefined) {
    return [x[0], x[1]]
  }
  if (x[0] === undefined && x[1] !== undefined) {
    return [0.0001, x[1]]
  }

  return undefined
}


Review comment (suggestion):
This code is moved mostly unchanged from `DeterministicLinePlot.tsx`. The only difference is that the `verifyPositive` function no longer needs to be passed as a parameter to this function.

Code after:
  }

  cumulativeCounts.forEach((_0, day) => {
    if (day < deltaDay) {
      newEmpiricalCases[day] = undefined
      return
    }

    const startDay = day - deltaDay
    const startDayPlus = day - deltaDay - 1

    const nowCases = cumulativeCounts[day].cases
    const oldCases = cumulativeCounts[startDay].cases
    const olderCases = cumulativeCounts[startDayPlus]?.cases
    if (oldCases && nowCases) {
      const newCases = verifyPositive(
        olderCases ? (1 - deltaInt) * (nowCases - oldCases) + deltaInt * (nowCases - olderCases) : nowCases - oldCases,
      )
      newEmpiricalCases.push(newCases)
      return
    }
    newEmpiricalCases[day] = undefined
  })

  return [newEmpiricalCases, deltaDay]
}
Repository: neherlab/covid19_scenarios
File: src/components/Main/Results/Utils.test.ts (TypeScript)

Code before:
import { verifyPositive, verifyTuple } from './Utils'

describe('verifyPositive', () => {
  it('integer greater than zero returns same integer', () => {
    expect(verifyPositive(312)).toStrictEqual(312)
  })

  it('number greater than zero returns ceiled version', () => {
    expect(verifyPositive(312.2)).toStrictEqual(313)
  })

  it('zero returns undefined', () => {
    expect(verifyPositive(0)).toBeUndefined()
  })

  it('less than zero returns undefined', () => {
    expect(verifyPositive(-1)).toBeUndefined()
  })
})

describe('verifyTuple', () => {
  it('input [undefined, undefined] returns undefined', () => {
    expect(verifyTuple([undefined, undefined])).toBeUndefined()
  })

  it('input [a, undefined] returns undefined', () => {
    expect(verifyTuple([1, undefined])).toBeUndefined()
  })

  it('input [undefined, b] returns [0.0001, b]', () => {
    expect(verifyTuple([undefined, 2])).toStrictEqual([0.0001, 2])
  })

  it('input [a, b] returns [a,b]', () => {
    expect(verifyTuple([1, 2])).toStrictEqual([1, 2])
  })
})


Review comment (suggestion):
Tests for the `computeNewEmpiricalCases()` function. As noted in the comment, the `time` property is not used by the function but is required by the type. Therefore it needs to be present but its value is of no consequence.

Code after:
    { cases: 6, time },
    { cases: 7, time },
  ]
  it('returns empty result if cumulativeCounts parameter is undefined.', () => {
    const got = computeNewEmpiricalCases(3)
    expect(got).toStrictEqual([[], 3])
  })

  it('computes with a timeWindow of 1', () => {
    const [newEmpiricalCases, deltaDay] = computeNewEmpiricalCases(1, cumulativeCounts)
    expect(newEmpiricalCases).toEqual([undefined, 1, 2, 2, undefined, 1])
    expect(deltaDay).toEqual(1)
  })

  it('computes with a timeWindow that evenly divides cumulativeCounts', () => {
    const [newEmpiricalCases, deltaDay] = computeNewEmpiricalCases(2, cumulativeCounts)
    expect(newEmpiricalCases).toEqual([undefined, undefined, 3, 4, 2, 1])
    expect(deltaDay).toEqual(2)
  })

  it('computes with a timeWindow that does not evenly divide cumulativeCounts', () => {
    const [newEmpiricalCases, deltaDay] = computeNewEmpiricalCases(4, cumulativeCounts)
    expect(newEmpiricalCases).toEqual([undefined, undefined, undefined, undefined, 5, 5])
    expect(deltaDay).toEqual(4)
  })
})
Repository: neherlab/covid19_scenarios
File: src/algorithms/cli.ts (TypeScript)

Code before:
  }
  console.log(`Will write model output to ${outputFile}`)

  const scenario = toInternal(scenarioData.data)

  const params: ScenarioFlat = {
    ...scenario.population,
    ...scenario.epidemiological,
    ...scenario.simulation,
    ...scenario.mitigation,
  }
  // Read data from severityDistributions.json and perform JSON validation.
  // Use the model's default (and only) severity distribution.
  console.log(`Reading severity distribution data`)
  const DEFAULT_SEVERITY_DISTRIBUTION = 'China CDC'
  const severity = getSeverityDistribution(DEFAULT_SEVERITY_DISTRIBUTION)
  // Read data from ageDistribution.json and perform JSON validation.
  console.log(`Reading age distribution data`)
  const ageDistribution = getAgeDistribution(params.ageDistributionName)

  try {
    console.log('Running the model')
    const result = await run({ params, severity, ageDistribution })
    console.log('Run complete')
    console.log(result)
    console.log(`Writing output to ${outputFile}`)
    fs.writeFileSync(outputFile, JSON.stringify(result))
  } catch (error) {
    console.error(`Run failed: ${error}`)
    process.exit(1)
  }
}

function usage() {
  console.log(
    `
Usage:
    cli <input-file> <output-file>
        Manually perform a single model run with the given input, writing the results to the given output file.
    `.trim(),
  )

  process.exit(1)
}

main()


Review comment (suggestion):
I think you can type this as `AgeDistributionData` instead of `any`. That type can be added to the import from `./types/Param.types`.

Code after:
 *
 * @param inputFilename The path to the file.
 */
function getSeverity(inputFilename: string | undefined) {
  if (inputFilename) {
    const data = readJsonFromFile<any>(inputFilename)
    return data.data
  }
  else {
    const DEFAULT_SEVERITY_DISTRIBUTION = 'China CDC'
    return getSeverityDistribution(DEFAULT_SEVERITY_DISTRIBUTION)
  }
}

/**
 * Get age distribution data. If a file is specified on the command
 * line, give priority to its contents, else load the distribution
 * name as specified in the scenario parameters.
 *
 * @param inputFilename The path to the file.
 * @param name The age distribution name to use if no file is
 *             specified.
 */
function getAge(inputFilename: string | undefined, name: string) {
  if (inputFilename) {
    const data = readJsonFromFile<any>(inputFilename)
    return data.data
  }
  else {
    return getAgeDistribution(name)
  }
}

async function main() {
  // Command line argument processing.
  const argv = yargs.options({
    scenario: {type: 'string', demandOption: true,
               describe: 'Path to scenario parameters JSON file.'},
    age:      {type: 'string',
               describe: 'Path to age distribution JSON file.'},
    severity: {type: 'string',
               describe: 'Path to severity JSON file.'},
    out:      {type: 'string', demandOption: true,
               describe: 'Path to output file.'},
  })
    .help()
    .version(false)
    .alias('h', 'help')
    .argv

  // Read the scenario data.
Repository: nestjs/nest
File: packages/common/utils/shared.utils.ts (TypeScript)

Code before:
export const normalizePath = (path?: string): string =>
  path
    ? path.startsWith('/')
      ? ('/' + path.replace(/\/+$/, '')).replace(/\/+/g, '/')
      : '/' + path.replace(/\/+$/, '')
    : '/';

export const stripEndSlash = (path: string): string =>
  path.endsWith('/') ? path.slice(0, -1) : path;

export const isFunction = (val: unknown): val is Function =>
  typeof val === 'function';

export const isString = (val: unknown): val is string =>
  typeof val === 'string';

export const isNumber = (val: unknown): val is number =>
  typeof val === 'number';

export const isConstructor = (val: unknown): boolean => val === 'constructor';

export const isNil = (val: unknown): val is null | undefined =>
  isUndefined(val) || val === null;

export const isEmpty = (array: unknown): boolean =>
  !(Array.isArray(array) && array.length > 0);

export const isSymbol = (val: unknown): val is symbol =>
  typeof val === 'symbol';


Review comment (refactor):
to me, `isEmpty` sounds that it could be used on non-array values. But I saw that it is only being used on arrays

peharps we could rename this utility to `isEmptyArray` and drop the following:

https://github.com/nestjs/nest/blob/e1b91d02a601c03cb8d0438b32badfaae5403447/packages/common/pipes/file/parse-file.pipe.ts#L63

Code after:
export const normalizePath = (path?: string): string =>
  path
    ? path.startsWith('/')
      ? ('/' + path.replace(/\/+$/, '')).replace(/\/+/g, '/')
      : '/' + path.replace(/\/+$/, '')
    : '/';

export const stripEndSlash = (path: string): string =>
  path.endsWith('/') ? path.slice(0, -1) : path;

export const isFunction = (val: unknown): val is Function =>
  typeof val === 'function';

export const isString = (val: unknown): val is string =>
  typeof val === 'string';

export const isNumber = (val: unknown): val is number =>
  typeof val === 'number';

export const isConstructor = (val: unknown): boolean => val === 'constructor';

export const isNil = (val: unknown): val is null | undefined =>
  isUndefined(val) || val === null;

export const isEmpty = (value: unknown): boolean => {
  if (isNil(value)) {
    return true;
  }
  if (Array.isArray(value)) {
    return value.length === 0;
  }
  return false;
};

export const isEmptyArray = (array: unknown): boolean => {
  if (!Array.isArray(array)) {
    return false;
  }
  return array.length === 0;
};

export const isSymbol = (val: unknown): val is symbol =>
  typeof val === 'symbol';
Repository: nextui-org/nextui
File: packages/components/drawer/src/index.ts (TypeScript)

Code before:
import {
  ModalHeader,
  ModalBody,
  ModalFooter,
  ModalContent,
  ModalContentProps,
  ModalHeaderProps,
  ModalBodyProps,
  ModalFooterProps,
  UseDisclosureProps,
} from "@nextui-org/modal";

import Drawer from "./drawer";

// export types
export type {DrawerProps} from "./drawer";
export type {
  ModalContentProps as DrawerContentProps,
  ModalHeaderProps as DrawerHeaderProps,
  ModalBodyProps as DrawerBodyProps,
  ModalFooterProps as DrawerFooterProps,
  UseDisclosureProps,
};

// export hooks
export {useDrawer} from "./use-drawer";

// export component
export {Drawer};

// export subcomponents
export {
  ModalHeader as DrawerHeader,
  ModalBody as DrawerBody,
  ModalFooter as DrawerFooter,

Review comment (suggestion):
remove the `UseDisclosureProps` export, it will have conflicts with the one exported from the `modal` package

Code after:
import {
  ModalHeader,
  ModalBody,
  ModalFooter,
  ModalContent,
  type ModalContentProps,
  type ModalHeaderProps,
  type ModalBodyProps,
  type ModalFooterProps,
} from "@nextui-org/modal";

import Drawer from "./drawer";

// export types
export type {DrawerProps} from "./drawer";
export type {
  ModalContentProps as DrawerContentProps,
  ModalHeaderProps as DrawerHeaderProps,
  ModalBodyProps as DrawerBodyProps,
  ModalFooterProps as DrawerFooterProps,
};

// export hooks
export {useDrawer} from "./use-drawer";

// export component
export {Drawer};

// export subcomponents
export {
  ModalHeader as DrawerHeader,
  ModalBody as DrawerBody,
  ModalFooter as DrawerFooter,
  ModalContent as DrawerContent,
};
Repository: nextui-org/nextui
File: packages/components/drawer/src/index.ts (TypeScript)

Code before:
import {
  ModalHeader,
  ModalBody,
  ModalFooter,
  ModalContent,
  ModalContentProps,
  ModalHeaderProps,
  ModalBodyProps,
  ModalFooterProps,
  UseDisclosureProps,
} from "@nextui-org/modal";

import Drawer from "./drawer";

// export types
export type {DrawerProps} from "./drawer";
export type {
  ModalContentProps as DrawerContentProps,
  ModalHeaderProps as DrawerHeaderProps,
  ModalBodyProps as DrawerBodyProps,
  ModalFooterProps as DrawerFooterProps,
  UseDisclosureProps,
};

// export hooks
export {useDrawer} from "./use-drawer";

// export component
export {Drawer};

// export subcomponents
export {
  ModalHeader as DrawerHeader,
  ModalBody as DrawerBody,
  ModalFooter as DrawerFooter,
  ModalContent as DrawerContent,
};


Review comment (suggestion):
remove the `UseDisclosureProps` export, it will have conflicts with the one exported from the `modal` package

Code after:
import {
  ModalHeader,
  ModalBody,
  ModalFooter,
  ModalContent,
  type ModalContentProps,
  type ModalHeaderProps,
  type ModalBodyProps,
  type ModalFooterProps,
} from "@nextui-org/modal";

import Drawer from "./drawer";

// export types
export type {DrawerProps} from "./drawer";
export type {
  ModalContentProps as DrawerContentProps,
  ModalHeaderProps as DrawerHeaderProps,
  ModalBodyProps as DrawerBodyProps,
  ModalFooterProps as DrawerFooterProps,
};

// export hooks
export {useDrawer} from "./use-drawer";

// export component
export {Drawer};

// export subcomponents
export {
  ModalHeader as DrawerHeader,
  ModalBody as DrawerBody,
  ModalFooter as DrawerFooter,
  ModalContent as DrawerContent,
};
Repository: nextui-org/nextui
File: packages/components/drawer/src/index.ts (TypeScript)

Code before:
import {
  ModalHeader,
  ModalBody,
  ModalFooter,
  ModalContent,
  ModalContentProps,
  ModalHeaderProps,
  ModalBodyProps,
  ModalFooterProps,
} from "@nextui-org/modal";

import Drawer from "./drawer";

// export types
export type {DrawerProps} from "./drawer";
export type {
  ModalContentProps as DrawerContentProps,
  ModalHeaderProps as DrawerHeaderProps,
  ModalBodyProps as DrawerBodyProps,
  ModalFooterProps as DrawerFooterProps,
};

// export hooks
export {useDrawer} from "./use-drawer";

// export component
export {Drawer};

// export subcomponents
export {
  ModalHeader as DrawerHeader,
  ModalBody as DrawerBody,
  ModalFooter as DrawerFooter,
  ModalContent as DrawerContent,
};

Review comment (suggestion):
Import modal props as `type` e.g `import type {ModalContentProps} from "@nextui-org/modal"`

Code after:
import {
  ModalHeader,
  ModalBody,
  ModalFooter,
  ModalContent,
  type ModalContentProps,
  type ModalHeaderProps,
  type ModalBodyProps,
  type ModalFooterProps,
} from "@nextui-org/modal";

import Drawer from "./drawer";

// export types
export type {DrawerProps} from "./drawer";
export type {
  ModalContentProps as DrawerContentProps,
  ModalHeaderProps as DrawerHeaderProps,
  ModalBodyProps as DrawerBodyProps,
  ModalFooterProps as DrawerFooterProps,
};

// export hooks
export {useDrawer} from "./use-drawer";

// export component
export {Drawer};

// export subcomponents
export {
  ModalHeader as DrawerHeader,
  ModalBody as DrawerBody,
  ModalFooter as DrawerFooter,
  ModalContent as DrawerContent,
};
Repository: nextui-org/nextui
File: packages/components/tooltip/stories/tooltip.stories.tsx (TypeScript)

Code before:
      </Button>
    </Tooltip>
    <Tooltip {...args} content="Tooltip 3" offset={-7}>
      <Button color="secondary" variant="faded">
        -7 offset
      </Button>
    </Tooltip>
  </div>
);

const MultipleTemplate = (args: TooltipProps) => {
  const ManyTooltipComponent = ({
    content,
    tooltipProps,
  }: {
    content: React.ReactNode;
    tooltipProps: TooltipProps;
  }) => {
    return (
      <Tooltip {...tooltipProps} closeDelay={0} content={content} openDelay={0}>
        <Button>Hover me</Button>
      </Tooltip>
    );
  };

  const tooltipIndex = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21];

  return (
    <div className="flex flex-col gap-5">
      <div className="flex gap-2">
        <Tooltip {...args} content="Tooltip 1" delay={1000}>
          <Button>Hover me (delay 1000ms)</Button>
        </Tooltip>
        <Tooltip {...args} content="Tooltip 2">
          <Button>Then hover me</Button>
        </Tooltip>
      </div>
      <div className="grid grid-cols-3 gap-2">
        {tooltipIndex.map((index) => (
          <ManyTooltipComponent key={index} content={`Tooltip ${index}`} tooltipProps={args} />
        ))}
      </div>
    </div>
  );
};

const PlacementsTemplate = (args: TooltipProps) => {
  return (
    <div className="inline-grid grid-cols-3 gap-4">
      <Tooltip {...args} content="Top Start" placement="top-start">
        <Button color="primary" variant="flat">

Review comment (suggestion):
instead of hardcoding the index, you can do

```
{Array.from({ length: 21 }, (_, i) => (...))}
```

Code after:
      </Button>
    </Tooltip>
    <Tooltip {...args} content="Tooltip 3" offset={-7}>
      <Button color="secondary" variant="faded">
        -7 offset
      </Button>
    </Tooltip>
  </div>
);

const MultipleTemplate = (args: TooltipProps) => (
  <div className="flex flex-col gap-5">
    <div className="flex gap-2">
      <Tooltip {...args} content="Tooltip 1" delay={1000}>
        <Button>Hover me (delay 1000ms)</Button>
      </Tooltip>
      <Tooltip {...args} content="Tooltip 2">
        <Button>Then hover me</Button>
      </Tooltip>
    </div>
    <div className="grid grid-cols-3 gap-2">
      {Array.from({length: 21}).map((_, index) => (
        <Tooltip {...args} key={index} closeDelay={0} content={`Tooltip ${index}`} openDelay={0}>
          <Button>Hover me</Button>
        </Tooltip>
      ))}
    </div>
  </div>
);

const PlacementsTemplate = (args: TooltipProps) => {
  return (
    <div className="inline-grid grid-cols-3 gap-4">
      <Tooltip {...args} content="Top Start" placement="top-start">
        <Button color="primary" variant="flat">
          Top Start
        </Button>
      </Tooltip>

      <Tooltip {...args} content="Top">
        <Button color="primary" variant="flat">
          Top
        </Button>
      </Tooltip>

      <Tooltip {...args} content="Top End" placement="top-end">
        <Button color="primary" variant="flat">
          Top End
        </Button>
      </Tooltip>
Repository: nextui-org/nextui
File: packages/core/system/src/hooks/use-label-placement.ts (TypeScript)

Code before:
import {useMemo} from "react";

import {useProviderContext} from "../provider-context";

export function useLabelPlacement(props: {
  labelPlacement?: "inside" | "outside" | "outside-left" | "outside-top";
  label?: React.ReactNode;
}) {
  const globalContext = useProviderContext();
  const globalLabelPlacement = globalContext?.labelPlacement;

  return useMemo(() => {
    const labelPlacement = props.labelPlacement ?? globalLabelPlacement ?? "inside";

    if (labelPlacement === "inside" && !props.label) {
      return "outside";
    }

    return labelPlacement;
  }, [props.labelPlacement, globalLabelPlacement, props.label]);
}


Review comment (bug):
seems this will break other components. probably use the old way in `use-input` with some comments, i.e. not using `useLabelPlacement`.

Code after:
import {useMemo} from "react";

import {useProviderContext} from "../provider-context";

export function useLabelPlacement(props: {
  labelPlacement?: "inside" | "outside" | "outside-left";
  label?: React.ReactNode;
}) {
  const globalContext = useProviderContext();
  const globalLabelPlacement = globalContext?.labelPlacement;

  return useMemo(() => {
    const labelPlacement = props.labelPlacement ?? globalLabelPlacement ?? "inside";

    if (labelPlacement === "inside" && !props.label) {
      return "outside";
    }

    return labelPlacement;
  }, [props.labelPlacement, globalLabelPlacement, props.label]);
}

export function useInputLabelPlacement(props: {
  labelPlacement?: "inside" | "outside" | "outside-left" | "outside-top";
  label?: React.ReactNode;
}) {
  const globalContext = useProviderContext();
  const globalLabelPlacement = globalContext?.labelPlacement;

  return useMemo(() => {
    const labelPlacement = props.labelPlacement ?? globalLabelPlacement ?? "inside";

    if (labelPlacement === "inside" && !props.label) {
      return "outside";
    }

    return labelPlacement;
  }, [props.labelPlacement, globalLabelPlacement, props.label]);
}