ronantakizawa/codereview-bench huggingface dataset:
Repository: slidevjs/slidev
File: packages/client/setup/routes.ts (TypeScript)

Code before:
      },
      {
        path: '/presenter',
        redirect: { path: '/presenter/1' },
      },
    )
  }

  if (__SLIDEV_FEATURE_PRINT__) {
    routes.push(
      {
        name: 'print',
        path: '/print',
        component: () => import('../pages/print.vue'),
      },
      {
        path: '/presenter/print',
        component: () => import('../pages/presenter/print.vue'),
      },
    )
  }

  routes.push(
    {
      name: 'play',
      path: '/:no(\\d+)',
      component: () => import('../pages/play.vue'),
    },
    {
      path: '',
      redirect: { path: '/1' },
    },
    {
      path: '/:pathMatch(.*)*',
      name: 'NotFound',
      component: () => import('../pages/404.vue'),
    },
  )

  return setups.reduce((routes, setup) => setup(routes), routes)
}


Review comment (suggestion):
The route may not be a number, due to the [`routeAlias` option](https://sli.dev/custom/#per-slide-configuration)

Code after:
      },
      {
        path: '/presenter',
        redirect: { path: '/presenter/1' },
      },
    )
  }

  if (__SLIDEV_FEATURE_PRINT__) {
    routes.push(
      {
        name: 'print',
        path: '/print',
        component: () => import('../pages/print.vue'),
      },
      {
        path: '/presenter/print',
        component: () => import('../pages/presenter/print.vue'),
      },
    )
  }

  routes.push(
    {
      name: 'play',
      path: '/:no',
      component: () => import('../pages/play.vue'),
    },
    {
      path: '',
      redirect: { path: '/1' },
    },
    {
      path: '/:pathMatch(.*)*',
      name: 'NotFound',
      component: () => import('../pages/404.vue'),
    },
  )

  return setups.reduce((routes, setup) => setup(routes), routes)
}
Repository: slidevjs/slidev
File: packages/slidev/node/syntax/markdown-it/markdown-it-shiki.ts (TypeScript)

Code before:
import type { ResolvedSlidevOptions } from '@slidev/types'
import type { ShikiTransformer } from 'shiki'
import { isTruthy } from '@antfu/utils'
import { fromAsyncCodeToHtml } from '@shikijs/markdown-it/async'
import { escapeVueInCode } from '../transform/utils'

export default async function MarkdownItShiki({ data: { config }, mode, utils: { shiki, shikiOptions } }: ResolvedSlidevOptions) {
  async function getTwoslashTransformer() {
    const [,,{ transformerTwoslash }] = await Promise.all([
      // trigger the shiki to load the langs
      shiki.codeToHast('', { lang: 'js', ...shikiOptions }),
      shiki.codeToHast('', { lang: 'ts', ...shikiOptions }),

      import('@shikijs/vitepress-twoslash'),
    ])
    return transformerTwoslash({
      explicitTrigger: true,
      twoslashOptions: {
        handbookOptions: {
          noErrorValidation: true,
        },
      },
    })
  }

  const transformers = [
    ...shikiOptions.transformers || [],
    (config.twoslash === true || config.twoslash === mode) && await getTwoslashTransformer(),
    {
      pre(pre) {
        this.addClassToHast(pre, 'slidev-code')
        delete pre.properties.tabindex
      },
      postprocess(code) {
        return escapeVueInCode(code)
      },
    } satisfies ShikiTransformer,

Review comment (suggestion):
This is an ugly workaround 🥲

I tried passing `lang` and `langAlias` to `transformerTwoslash`, but it either complains "language not loaded" or doesn't transform the code.

Code after:
import type { ResolvedSlidevOptions } from '@slidev/types'
import type { ShikiTransformer } from 'shiki'
import { isTruthy } from '@antfu/utils'
import { fromAsyncCodeToHtml } from '@shikijs/markdown-it/async'
import { escapeVueInCode } from '../transform/utils'

export default async function MarkdownItShiki({ data: { config }, mode, utils: { shiki, shikiOptions } }: ResolvedSlidevOptions) {
  async function getTwoslashTransformer() {
    const [,,{ transformerTwoslash }] = await Promise.all([
      // trigger shiki to load the langs
      shiki.codeToHast('', { lang: 'js', ...shikiOptions }),
      shiki.codeToHast('', { lang: 'ts', ...shikiOptions }),

      import('@shikijs/vitepress-twoslash'),
    ])
    return transformerTwoslash({
      explicitTrigger: true,
      twoslashOptions: {
        handbookOptions: {
          noErrorValidation: true,
        },
      },
    })
  }

  const transformers = [
    ...shikiOptions.transformers || [],
    (config.twoslash === true || config.twoslash === mode) && await getTwoslashTransformer(),
    {
      pre(pre) {
        this.addClassToHast(pre, 'slidev-code')
        delete pre.properties.tabindex
      },
      postprocess(code) {
        return escapeVueInCode(code)
      },
    } satisfies ShikiTransformer,
Repository: slidevjs/slidev
File: packages/types/src/frontmatter.ts (TypeScript)

Code before:
  /**
   * Override the title for the `<TitleRenderer>` and `<Toc>` components
   * Only if `title` has also been declared
   */
  title?: string
  /**
   * Override the title level for the `<TitleRenderer>` and `<Toc>` components
   * Only if `title` has also been declared
   */
  level?: number
  /**
   * Create a route alias that can be used in the URL or with the `<Link>` component
   */
  routeAlias?: string
  /**
   * Custom zoom level for the slide
   * @default 1
   */
  zoom?: number
  /**
   * Store the positions of draggable elements
   * Normally you don't need to set this manually
   *
   * See https://sli.dev/features/draggable
   */
  dragPos?: Record<string, string> | Record<string, string>[]
  /**
   * Includes a markdown file
   *
   * See https://sli.dev/guide/syntax.html#importing-slides
   */
  src?: string
}

export interface DrawingsOptions {
  /**
   * Persist the drawings to disk
   * Passing string to specify the directory (default to `.slidev/drawings`)
   *
   * @default false
   */
  persist?: boolean | string

  /**
   * @default true
   */
  enabled?: boolean | 'dev' | 'build'

  /**
   * Only allow drawing from presenter mode
   *

Review comment (suggestion):
I think this should be just `Record<string, string>`:

```suggestion
  dragPos?: Record<string, string>
```

Code after:
  /**
   * Override the title for the `<TitleRenderer>` and `<Toc>` components
   * Only if `title` has also been declared
   */
  title?: string
  /**
   * Override the title level for the `<TitleRenderer>` and `<Toc>` components
   * Only if `title` has also been declared
   */
  level?: number
  /**
   * Create a route alias that can be used in the URL or with the `<Link>` component
   */
  routeAlias?: string
  /**
   * Custom zoom level for the slide
   * @default 1
   */
  zoom?: number
  /**
   * Store the positions of draggable elements
   * Normally you don't need to set this manually
   *
   * See https://sli.dev/features/draggable
   */
  dragPos?: Record<string, string>
  /**
   * Includes a markdown file
   *
   * See https://sli.dev/guide/syntax.html#importing-slides
   */
  src?: string
}

export interface DrawingsOptions {
  /**
   * Persist the drawings to disk
   * Passing string to specify the directory (default to `.slidev/drawings`)
   *
   * @default false
   */
  persist?: boolean | string

  /**
   * @default true
   */
  enabled?: boolean | 'dev' | 'build'

  /**
   * Only allow drawing from presenter mode
   *
Repository: smicallef/spiderfoot
File: modules/sfp_bitcoinabuse.py (Python)

Code before:
        except Exception as e:
            self.sf.error("Error processing JSON response from BitcoinAbuse.", False)
            return None

        return info

    def handleEvent(self, event):
        eventName = event.eventType
        srcModuleName = event.module
        eventData = event.data

        if self.errorState:
            return None

        self.sf.debug(f"Received event, {eventName}, from {srcModuleName}")

        if self.opts["api_key"] == "":
            self.sf.error("You enabled sfp_template but did not set an API key!", False)
            self.errorState = True
            return None

        if eventData in self.results:
            self.sf.debug(f"Skipping {eventData}, already checked.")
            return None
        else:
            self.results[eventData] = True

        if eventName == "BITCOIN_ADDRESS":
            rec = self.query(eventData)
            if isinstance(rec, dict):
                count = rec.get("count")
                if isinstance(count, int):
                    if count != 0:
                        evt = SpiderFootEvent(
                            "MALICIOUS_BITCOIN_ADDRESS", rec["address"], self.__name__, event
                        )
                        self.notifyListeners(evt)

                        rirevt = SpiderFootEvent(
                            "RAW_RIR_DATA", json.dumps(rec), self.__name__, event
                        )
                        self.notifyListeners(rirevt)


Review comment (suggestion):
Redundant `else` after `return`.

```suggestion

        self.results[eventData] = True
```

Code after:
            self.sf.error("Error processing JSON response from BitcoinAbuse.", False)
            return None

        return info

    def handleEvent(self, event):
        eventName = event.eventType
        srcModuleName = event.module
        eventData = event.data

        if self.errorState:
            return None

        self.sf.debug(f"Received event, {eventName}, from {srcModuleName}")

        if self.opts["api_key"] == "":
            self.sf.error("You enabled sfp_bitcoinabuse but did not set an API key!", False)
            self.errorState = True
            return None

        if eventData in self.results:
            self.sf.debug(f"Skipping {eventData}, already checked.")
            return None

        self.results[eventData] = True

        if eventName == "BITCOIN_ADDRESS":
            rec = self.query(eventData)
            if isinstance(rec, dict):
                count = rec.get("count")
                if isinstance(count, int):
                    if count > 0:
                        evt = SpiderFootEvent(
                            "MALICIOUS_BITCOIN_ADDRESS", f"BitcoinAbuse[{rec['address']}]", self.__name__, event
                        )
                        self.notifyListeners(evt)

                        rirevt = SpiderFootEvent(
                            "RAW_RIR_DATA", json.dumps(rec), self.__name__, event
                        )
                        self.notifyListeners(rirevt)
Repository: smicallef/spiderfoot
File: modules/sfp_bitcoinabuse.py (Python)

Code before:
        eventName = event.eventType
        srcModuleName = event.module
        eventData = event.data

        if self.errorState:
            return None

        self.sf.debug(f"Received event, {eventName}, from {srcModuleName}")

        if self.opts["api_key"] == "":
            self.sf.error("You enabled sfp_template but did not set an API key!", False)
            self.errorState = True
            return None

        if eventData in self.results:
            self.sf.debug(f"Skipping {eventData}, already checked.")
            return None
        else:
            self.results[eventData] = True

        if eventName == "BITCOIN_ADDRESS":
            rec = self.query(eventData)
            if isinstance(rec, dict):
                count = rec.get("count")
                if isinstance(count, int):
                    if count != 0:
                        evt = SpiderFootEvent(
                            "MALICIOUS_BITCOIN_ADDRESS", rec["address"], self.__name__, event
                        )
                        self.notifyListeners(evt)

                        rirevt = SpiderFootEvent(
                            "RAW_RIR_DATA", json.dumps(rec), self.__name__, event
                        )
                        self.notifyListeners(rirevt)


Review comment (suggestion):
A `count` value of zero should evaluate to false.

```suggestion
                    if count:
```

or, of negative values are possible:

```suggestion
                    if count > 0:
```

Code after:
        srcModuleName = event.module
        eventData = event.data

        if self.errorState:
            return None

        self.sf.debug(f"Received event, {eventName}, from {srcModuleName}")

        if self.opts["api_key"] == "":
            self.sf.error("You enabled sfp_bitcoinabuse but did not set an API key!", False)
            self.errorState = True
            return None

        if eventData in self.results:
            self.sf.debug(f"Skipping {eventData}, already checked.")
            return None

        self.results[eventData] = True

        if eventName == "BITCOIN_ADDRESS":
            rec = self.query(eventData)
            if isinstance(rec, dict):
                count = rec.get("count")
                if isinstance(count, int):
                    if count > 0:
                        evt = SpiderFootEvent(
                            "MALICIOUS_BITCOIN_ADDRESS", f"BitcoinAbuse[{rec['address']}]", self.__name__, event
                        )
                        self.notifyListeners(evt)

                        rirevt = SpiderFootEvent(
                            "RAW_RIR_DATA", json.dumps(rec), self.__name__, event
                        )
                        self.notifyListeners(rirevt)
Repository: smicallef/spiderfoot
File: modules/sfp_bitcoinabuse.py (Python)

Code before:
        eventData = event.data

        if self.errorState:
            return None

        self.sf.debug(f"Received event, {eventName}, from {srcModuleName}")

        if self.opts["api_key"] == "":
            self.sf.error("You enabled sfp_bitcoinabuse but did not set an API key!", False)
            self.errorState = True
            return None

        if eventData in self.results:
            self.sf.debug(f"Skipping {eventData}, already checked.")
            return None

        self.results[eventData] = True

        if eventName == "BITCOIN_ADDRESS":
            rec = self.query(eventData)
            if isinstance(rec, dict):
                count = rec.get("count")
                if isinstance(count, int):
                    if count > 0:
                        evt = SpiderFootEvent(
                            "MALICIOUS_BITCOIN_ADDRESS", rec["address"], self.__name__, event
                        )
                        self.notifyListeners(evt)

                        rirevt = SpiderFootEvent(
                            "RAW_RIR_DATA", json.dumps(rec), self.__name__, event
                        )
                        self.notifyListeners(rirevt)


Review comment (suggestion):
Is there any additional text that can go in the result to make it more meaningful? At the very least it should be modeled around the other modules that report malicious entities (see `sfp_emailrep.py` as an example).

Code after:
        eventData = event.data

        if self.errorState:
            return None

        self.sf.debug(f"Received event, {eventName}, from {srcModuleName}")

        if self.opts["api_key"] == "":
            self.sf.error("You enabled sfp_bitcoinabuse but did not set an API key!", False)
            self.errorState = True
            return None

        if eventData in self.results:
            self.sf.debug(f"Skipping {eventData}, already checked.")
            return None

        self.results[eventData] = True

        if eventName == "BITCOIN_ADDRESS":
            rec = self.query(eventData)
            if isinstance(rec, dict):
                count = rec.get("count")
                if isinstance(count, int):
                    if count > 0:
                        evt = SpiderFootEvent(
                            "MALICIOUS_BITCOIN_ADDRESS", f"BitcoinAbuse[{rec['address']}]", self.__name__, event
                        )
                        self.notifyListeners(evt)

                        rirevt = SpiderFootEvent(
                            "RAW_RIR_DATA", json.dumps(rec), self.__name__, event
                        )
                        self.notifyListeners(rirevt)
Repository: smicallef/spiderfoot
File: modules/sfp_debounce.py (Python)

Code before:
        try:
            return json.loads(res['content'])
        except Exception as e:
            self.sf.error(f"Error processing JSON response from Debounce: {e}")

        return None

    # Handle events sent to this module
    def handleEvent(self, event):
        eventName = event.eventType
        srcModuleName = event.module
        eventData = event.data

        if self.errorState:
            return

        self.sf.debug(f"Received event, {eventName}, from {srcModuleName}")

        self.results[eventData] = True

        data = self.queryEmailAddr(eventData)

        if data is None:
            return

        evt = SpiderFootEvent("RAW_RIR_DATA", str(data), self.__name__, event)
        self.notifyListeners(evt)

        isDisposable = data.get('disposable')
        if isDisposable == "true":
            evt = SpiderFootEvent("EMAILADDR_DISPOSABLE", eventData, self.__name__, event)
            self.notifyListeners(evt)

# End of sfp_debounce class


Review comment (suggestion):
I suggest moving this to within the following `if` statement since we only want `RAW_RIR_DATA` if there's content in the API response that has been of value.

Code after:
        try:
            return json.loads(res['content'])
        except Exception as e:
            self.sf.error(f"Error processing JSON response from Debounce: {e}")

        return None

    # Handle events sent to this module
    def handleEvent(self, event):
        eventName = event.eventType
        srcModuleName = event.module
        eventData = event.data

        if self.errorState:
            return

        self.sf.debug(f"Received event, {eventName}, from {srcModuleName}")

        self.results[eventData] = True

        data = self.queryEmailAddr(eventData)

        if data is None:
            return

        isDisposable = data.get('disposable')

        if isDisposable == "true":
            evt = SpiderFootEvent("RAW_RIR_DATA", str(data), self.__name__, event)
            self.notifyListeners(evt)

            evt = SpiderFootEvent("EMAILADDR_DISPOSABLE", eventData, self.__name__, event)
            self.notifyListeners(evt)

# End of sfp_debounce class
Repository: smicallef/spiderfoot
File: modules/sfp_sublist3r.py (Python)

Code before:
        if res["code"] not in ["200"]:
            self.sf.error(f"Bad response code \"{res['code']}\" from Sublist3r API")

        return list(set(ret))

    def sendEvent(self, source, host):
        if self.sf.resolveHost(host):
            e = SpiderFootEvent("INTERNET_NAME", host, self.__name__, source)
        else:
            e = SpiderFootEvent("INTERNET_NAME_UNRESOLVED", host, self.__name__, source)
        self.notifyListeners(e)

    def handleEvent(self, event):
        domain = str(event.data).lower()

        self.sf.debug(f"Received event, {event.eventType}, from {event.module}")

        # skip if we've already processed this event
        eventDataHash = self.sf.hashstring(event.data)
        if eventDataHash in self.state["events"]:
            self.sf.debug(f"Skipping already-processed event, {event.eventType}, from {event.module}")
            return
        self.state["events"].append(eventDataHash)

        for hostname in self.query(domain):
            if hostname.endswith(domain) and not hostname == domain:
                self.sendEvent(event, hostname)
            else:
                self.sf.debug(f"Invalid subdomain: {hostname}")


Review comment (suggestion):
This should use the `SpiderFootTarget.matches()` method to verify whether it's part of the target scope.

Code after:
        return list(set(ret))

    def sendEvent(self, source, host):
        if self.sf.resolveHost(host):
            e = SpiderFootEvent("INTERNET_NAME", host, self.__name__, source)
        else:
            e = SpiderFootEvent("INTERNET_NAME_UNRESOLVED", host, self.__name__, source)
        self.notifyListeners(e)

    def handleEvent(self, event):
        query = str(event.data).lower()

        self.sf.debug(f"Received event, {event.eventType}, from {event.module}")

        # skip if we've already processed this event (or its parent domain/subdomain)
        target = self.getTarget()
        eventDataHash = self.sf.hashstring(query)
        if eventDataHash in self.results or \
                (target.matches(query, includeParents=True) and not
                 target.matches(query, includeChildren=False)):
            self.sf.debug(f"Skipping already-processed event, {event.eventType}, from {event.module}")
            return
        self.results[eventDataHash] = True

        for hostname in self.query(query):
            if target.matches(hostname, includeParents=True) and not \
                    target.matches(hostname, includeChildren=False):
                self.sendEvent(event, hostname)
            else:
                self.sf.debug(f"Invalid subdomain: {hostname}")
Repository: smicallef/spiderfoot
File: modules/sfp_threatjammer.py (Python)

Code before:
# -*- coding: utf-8 -*-
# -------------------------------------------------------------------------------
# Name:        sfp_threatjammer
# Purpose:     Check if an IP or netblock is malicious according to ThreatJammer.com.
#
# Author:      diego.parrilla.santamaria@gmail.com
#
# Created:     05/05/2022
# Copyright:   (c) Diego Parrilla 2022
# Licence:     GPL
# -------------------------------------------------------------------------------

import json
import time

from spiderfoot import SpiderFootEvent, SpiderFootPlugin


class sfp_threatjammer(SpiderFootPlugin):

    meta = {
        'name': "Threat Jammer",
        'summary': "Check if an IP or netblock is malicious according to ThreatJammer.com",
        'flags': ["apikey"],
        'useCases': ["Passive", "Investigate"],
        'categories': ["Reputation Systems"],
        'dataSource': {
            'website': "https://threatjammer.com",
            'model': "FREE_AUTH_LIMITED",
            'references': [
                "https://threatjammer.com/docs/what-is-threat-jammer",
                "https://threatjammer.com/docs/how-threat-jammer-works",
                "https://threatjammer.com/docs/introduction-threat-jammer-user-api",

Review comment (suggestion):
International date format is preferred, future man.

```suggestion
# Created:     2022-05-03
```

Code after:
# -*- coding: utf-8 -*-
# -------------------------------------------------------------------------------
# Name:        sfp_threatjammer
# Purpose:     Check if an IP or netblock is malicious according to ThreatJammer.com.
#
# Author:      diego.parrilla.santamaria@gmail.com
#
# Created:     2022-05-03
# Copyright:   (c) Diego Parrilla 2022
# Licence:     MIT
# -------------------------------------------------------------------------------

import json
import time

from spiderfoot import SpiderFootEvent, SpiderFootPlugin


class sfp_threatjammer(SpiderFootPlugin):

    meta = {
        'name': "Threat Jammer",
        'summary': "Check if an IP address is malicious according to ThreatJammer.com",
        'flags': ["apikey"],
        'useCases': ["Passive", "Investigate"],
        'categories': ["Reputation Systems"],
        'dataSource': {
            'website': "https://threatjammer.com",
            'model': "FREE_AUTH_LIMITED",
            'references': [
                "https://threatjammer.com/docs/what-is-threat-jammer",
                "https://threatjammer.com/docs/how-threat-jammer-works",
                "https://threatjammer.com/docs/introduction-threat-jammer-user-api",