gurudesh/pytracebugs huggingface dataset:
# Buggy code
def print_version() -> None:
    """Prints version information of rasa tooling and python."""

    python_version, os_info = sys.version.split("\n")
    try:
        from rasax.community.version import __version__

        rasa_x_info = __version__
    except ModuleNotFoundError:
        rasa_x_info = None

    print(f"Rasa Version     : {version.__version__}")
    print(f"Rasa SDK Version : {rasa_sdk_version}")
    print(f"Rasa X Version   : {rasa_x_info}")
    print(f"Python Version   : {python_version}")
    print(f"Operating System : {platform.platform()}")
    print(f"Python Path      : {sys.executable}")


# Traceback (ValueError)
Traceback (most recent call last):
File "e:\env\anaconda\envs\rasa\lib\runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "e:\env\anaconda\envs\rasa\lib\runpy.py", line 85, in _run_code
exec(code, run_globals)
File "E:\Env\Anaconda\envs\rasa\Scripts\rasa.exe\__main__.py", line 7, in <module>
File "e:\env\anaconda\envs\rasa\lib\site-packages\rasa\__main__.py", line 118, in main
print_version()
File "e:\env\anaconda\envs\rasa\lib\site-packages\rasa\__main__.py", line 78, in print_version
python_version, os_info = sys.version.split("\n")
ValueError: not enough values to unpack (expected 2, got 1)

# Fixed code
def print_version() -> None:
    """Prints version information of rasa tooling and python."""

    try:
        from rasax.community.version import __version__

        rasa_x_info = __version__
    except ModuleNotFoundError:
        rasa_x_info = None

    print(f"Rasa Version     : {version.__version__}")
    print(f"Rasa SDK Version : {rasa_sdk_version}")
    print(f"Rasa X Version   : {rasa_x_info}")
    print(f"Python Version   : {platform.python_version()}")
    print(f"Operating System : {platform.platform()}")
    print(f"Python Path      : {sys.executable}")
# Buggy code
def print_version() -> None:
    """Prints version information of rasa tooling and python."""

    python_version, os_info = sys.version.split("\n")
    try:
        from rasax.community.version import __version__  # pytype: disable=import-error

        rasa_x_info = __version__
    except ModuleNotFoundError:
        rasa_x_info = None

    print(f"Rasa Version     : {version.__version__}")
    print(f"Rasa SDK Version : {rasa_sdk_version}")
    print(f"Rasa X Version   : {rasa_x_info}")
    print(f"Python Version   : {python_version}")
    print(f"Operating System : {platform.platform()}")
    print(f"Python Path      : {sys.executable}")


# Traceback (ValueError)
Traceback (most recent call last):
File "e:\env\anaconda\envs\rasa\lib\runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "e:\env\anaconda\envs\rasa\lib\runpy.py", line 85, in _run_code
exec(code, run_globals)
File "E:\Env\Anaconda\envs\rasa\Scripts\rasa.exe\__main__.py", line 7, in <module>
File "e:\env\anaconda\envs\rasa\lib\site-packages\rasa\__main__.py", line 118, in main
print_version()
File "e:\env\anaconda\envs\rasa\lib\site-packages\rasa\__main__.py", line 78, in print_version
python_version, os_info = sys.version.split("\n")
ValueError: not enough values to unpack (expected 2, got 1)

# Fixed code
def print_version() -> None:
    """Prints version information of rasa tooling and python."""

    try:
        from rasax.community.version import __version__  # pytype: disable=import-error

        rasa_x_info = __version__
    except ModuleNotFoundError:
        rasa_x_info = None

    print(f"Rasa Version     : {version.__version__}")
    print(f"Rasa SDK Version : {rasa_sdk_version}")
    print(f"Rasa X Version   : {rasa_x_info}")
    print(f"Python Version   : {platform.python_version()}")
    print(f"Operating System : {platform.platform()}")
    print(f"Python Path      : {sys.executable}")
# Buggy code
def __init__(self, token: Text, slack_channel: Optional[Text] = None) -> None:
    self.slack_channel = slack_channel
    self.client = WebClient(token, run_async=True)
    super().__init__()


# Traceback (ValueError)
File "c:\users\jitesh\appdata\local\programs\python\python37\lib\site-packages\sanic\request.py", line 173, in load_json
self.parsed_json = loads(self.body)
ValueError: Expected object or value

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "c:\users\jitesh\appdata\local\programs\python\python37\lib\site-packages\sanic\app.py", line 976, in handle_request
response = await response
File "c:\users\jitesh\appdata\local\programs\python\python37\lib\site-packages\rasa\core\channels\slack.py", line 356, in webhook
metadata = self.get_metadata(request)
File "c:\users\jitesh\appdata\local\programs\python\python37\lib\site-packages\rasa\core\channels\slack.py", line 329, in get_metadata
slack_event = request.json
File "c:\users\jitesh\appdata\local\programs\python\python37\lib\site-packages\sanic\request.py", line 167, in json
self.load_json()
File "c:\users\jitesh\appdata\local\programs\python\python37\lib\site-packages\sanic\request.py", line 177, in load_json
raise InvalidUsage("Failed when parsing body as json")
sanic.exceptions.InvalidUsage: Failed when parsing body as json

# Fixed code
def __init__(
    self,
    token: Text,
    slack_channel: Optional[Text] = None,
    thread_id: Optional[Text] = None,
) -> None:
    self.slack_channel = slack_channel
    self.thread_id = thread_id
    self.client = WebClient(token, run_async=True)
    super().__init__()
# Buggy code
async def send_text_message(
    self, recipient_id: Text, text: Text, **kwargs: Any
) -> None:
    recipient = self.slack_channel or recipient_id
    for message_part in text.strip().split("\n\n"):
        await self.client.chat_postMessage(
            channel=recipient,
            as_user=True,
            text=message_part,
            type="mrkdwn",
        )


# Traceback (ValueError)
File "c:\users\jitesh\appdata\local\programs\python\python37\lib\site-packages\sanic\request.py", line 173, in load_json
self.parsed_json = loads(self.body)
ValueError: Expected object or value

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "c:\users\jitesh\appdata\local\programs\python\python37\lib\site-packages\sanic\app.py", line 976, in handle_request
response = await response
File "c:\users\jitesh\appdata\local\programs\python\python37\lib\site-packages\rasa\core\channels\slack.py", line 356, in webhook
metadata = self.get_metadata(request)
File "c:\users\jitesh\appdata\local\programs\python\python37\lib\site-packages\rasa\core\channels\slack.py", line 329, in get_metadata
slack_event = request.json
File "c:\users\jitesh\appdata\local\programs\python\python37\lib\site-packages\sanic\request.py", line 167, in json
self.load_json()
File "c:\users\jitesh\appdata\local\programs\python\python37\lib\site-packages\sanic\request.py", line 177, in load_json
raise InvalidUsage("Failed when parsing body as json")
sanic.exceptions.InvalidUsage: Failed when parsing body as json

# Fixed code
async def send_text_message(
    self, recipient_id: Text, text: Text, **kwargs: Any
) -> None:
    recipient = self.slack_channel or recipient_id
    for message_part in text.strip().split("\n\n"):
        await self._post_message(
            channel=recipient,
            as_user=True,
            text=message_part,
            type="mrkdwn",
        )
# Buggy code
async def send_image_url(self, recipient_id: Text, image: Text, **kwargs: Any) -> None:
    recipient = self.slack_channel or recipient_id
    image_block = {"type": "image", "image_url": image, "alt_text": image}
    await self.client.chat_postMessage(
        channel=recipient,
        as_user=True,
        text=image,
        blocks=[image_block],
    )


# Traceback (ValueError)
File "c:\users\jitesh\appdata\local\programs\python\python37\lib\site-packages\sanic\request.py", line 173, in load_json
self.parsed_json = loads(self.body)
ValueError: Expected object or value

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "c:\users\jitesh\appdata\local\programs\python\python37\lib\site-packages\sanic\app.py", line 976, in handle_request
response = await response
File "c:\users\jitesh\appdata\local\programs\python\python37\lib\site-packages\rasa\core\channels\slack.py", line 356, in webhook
metadata = self.get_metadata(request)
File "c:\users\jitesh\appdata\local\programs\python\python37\lib\site-packages\rasa\core\channels\slack.py", line 329, in get_metadata
slack_event = request.json
File "c:\users\jitesh\appdata\local\programs\python\python37\lib\site-packages\sanic\request.py", line 167, in json
self.load_json()
File "c:\users\jitesh\appdata\local\programs\python\python37\lib\site-packages\sanic\request.py", line 177, in load_json
raise InvalidUsage("Failed when parsing body as json")
sanic.exceptions.InvalidUsage: Failed when parsing body as json

# Fixed code
async def send_image_url(self, recipient_id: Text, image: Text, **kwargs: Any) -> None:
    recipient = self.slack_channel or recipient_id
    image_block = {"type": "image", "image_url": image, "alt_text": image}

    await self._post_message(
        channel=recipient,
        as_user=True,
        text=image,
        blocks=[image_block],
    )
# Buggy code
async def send_attachment(
    self, recipient_id: Text, attachment: Dict[Text, Any], **kwargs: Any
) -> None:
    recipient = self.slack_channel or recipient_id
    await self.client.chat_postMessage(
        channel=recipient,
        as_user=True,
        attachments=[attachment],
        **kwargs,
    )


# Traceback (ValueError)
File "c:\users\jitesh\appdata\local\programs\python\python37\lib\site-packages\sanic\request.py", line 173, in load_json
self.parsed_json = loads(self.body)
ValueError: Expected object or value

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "c:\users\jitesh\appdata\local\programs\python\python37\lib\site-packages\sanic\app.py", line 976, in handle_request
response = await response
File "c:\users\jitesh\appdata\local\programs\python\python37\lib\site-packages\rasa\core\channels\slack.py", line 356, in webhook
metadata = self.get_metadata(request)
File "c:\users\jitesh\appdata\local\programs\python\python37\lib\site-packages\rasa\core\channels\slack.py", line 329, in get_metadata
slack_event = request.json
File "c:\users\jitesh\appdata\local\programs\python\python37\lib\site-packages\sanic\request.py", line 167, in json
self.load_json()
File "c:\users\jitesh\appdata\local\programs\python\python37\lib\site-packages\sanic\request.py", line 177, in load_json
raise InvalidUsage("Failed when parsing body as json")
sanic.exceptions.InvalidUsage: Failed when parsing body as json

# Fixed code
async def send_attachment(
    self, recipient_id: Text, attachment: Dict[Text, Any], **kwargs: Any
) -> None:
    recipient = self.slack_channel or recipient_id
    await self._post_message(
        channel=recipient,
        as_user=True,
        attachments=[attachment],
        **kwargs,
    )
# Buggy code
async def send_custom_json(
    self, recipient_id: Text, json_message: Dict[Text, Any], **kwargs: Any
) -> None:
    json_message.setdefault("channel", self.slack_channel or recipient_id)
    json_message.setdefault("as_user", True)
    await self.client.chat_postMessage(**json_message)


# Traceback (ValueError)
File "c:\users\jitesh\appdata\local\programs\python\python37\lib\site-packages\sanic\request.py", line 173, in load_json
self.parsed_json = loads(self.body)
ValueError: Expected object or value

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "c:\users\jitesh\appdata\local\programs\python\python37\lib\site-packages\sanic\app.py", line 976, in handle_request
response = await response
File "c:\users\jitesh\appdata\local\programs\python\python37\lib\site-packages\rasa\core\channels\slack.py", line 356, in webhook
metadata = self.get_metadata(request)
File "c:\users\jitesh\appdata\local\programs\python\python37\lib\site-packages\rasa\core\channels\slack.py", line 329, in get_metadata
slack_event = request.json
File "c:\users\jitesh\appdata\local\programs\python\python37\lib\site-packages\sanic\request.py", line 167, in json
self.load_json()
File "c:\users\jitesh\appdata\local\programs\python\python37\lib\site-packages\sanic\request.py", line 177, in load_json
raise InvalidUsage("Failed when parsing body as json")
sanic.exceptions.InvalidUsage: Failed when parsing body as json

# Fixed code
async def send_custom_json(
    self, recipient_id: Text, json_message: Dict[Text, Any], **kwargs: Any
) -> None:
    json_message.setdefault("channel", self.slack_channel or recipient_id)
    json_message.setdefault("as_user", True)
    await self._post_message(**json_message)
# Buggy code
def from_credentials(cls, credentials: Optional[Dict[Text, Any]]) -> InputChannel:
    if not credentials:
        cls.raise_missing_credentials_exception()

    # pytype: disable=attribute-error
    return cls(
        credentials.get("slack_token"),
        credentials.get("slack_channel"),
        credentials.get("slack_retry_reason_header", "x-slack-retry-reason"),
        credentials.get("slack_retry_number_header", "x-slack-retry-num"),
        credentials.get("errors_ignore_retry", None),
    )


# Traceback (ValueError)
File "c:\users\jitesh\appdata\local\programs\python\python37\lib\site-packages\sanic\request.py", line 173, in load_json
self.parsed_json = loads(self.body)
ValueError: Expected object or value

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "c:\users\jitesh\appdata\local\programs\python\python37\lib\site-packages\sanic\app.py", line 976, in handle_request
response = await response
File "c:\users\jitesh\appdata\local\programs\python\python37\lib\site-packages\rasa\core\channels\slack.py", line 356, in webhook
metadata = self.get_metadata(request)
File "c:\users\jitesh\appdata\local\programs\python\python37\lib\site-packages\rasa\core\channels\slack.py", line 329, in get_metadata
slack_event = request.json
File "c:\users\jitesh\appdata\local\programs\python\python37\lib\site-packages\sanic\request.py", line 167, in json
self.load_json()
File "c:\users\jitesh\appdata\local\programs\python\python37\lib\site-packages\sanic\request.py", line 177, in load_json
raise InvalidUsage("Failed when parsing body as json")
sanic.exceptions.InvalidUsage: Failed when parsing body as json

# Fixed code
def from_credentials(cls, credentials: Optional[Dict[Text, Any]]) -> InputChannel:
    if not credentials:
        cls.raise_missing_credentials_exception()

    # pytype: disable=attribute-error
    return cls(
        credentials.get("slack_token"),
        credentials.get("slack_channel"),
        credentials.get("slack_retry_reason_header", "x-slack-retry-reason"),
        credentials.get("slack_retry_number_header", "x-slack-retry-num"),
        credentials.get("errors_ignore_retry", None),
        credentials.get("use_threads", False),
    )
# Buggy code
def get_output_channel(self, channel: Optional[Text] = None) -> OutputChannel:
    channel = channel or self.slack_channel
    return SlackBot(self.slack_token, channel)


# Traceback (ValueError)
File "c:\users\jitesh\appdata\local\programs\python\python37\lib\site-packages\sanic\request.py", line 173, in load_json
self.parsed_json = loads(self.body)
ValueError: Expected object or value

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "c:\users\jitesh\appdata\local\programs\python\python37\lib\site-packages\sanic\app.py", line 976, in handle_request
response = await response
File "c:\users\jitesh\appdata\local\programs\python\python37\lib\site-packages\rasa\core\channels\slack.py", line 356, in webhook
metadata = self.get_metadata(request)
File "c:\users\jitesh\appdata\local\programs\python\python37\lib\site-packages\rasa\core\channels\slack.py", line 329, in get_metadata
slack_event = request.json
File "c:\users\jitesh\appdata\local\programs\python\python37\lib\site-packages\sanic\request.py", line 167, in json
self.load_json()
File "c:\users\jitesh\appdata\local\programs\python\python37\lib\site-packages\sanic\request.py", line 177, in load_json
raise InvalidUsage("Failed when parsing body as json")
sanic.exceptions.InvalidUsage: Failed when parsing body as json

# Fixed code
def get_output_channel(
    self, channel: Optional[Text] = None, thread_id: Optional[Text] = None
) -> OutputChannel:
    channel = channel or self.slack_channel
    return SlackBot(self.slack_token, channel, thread_id)
# Buggy code
def get_signature(self) -> Dict[Text, List[FeatureSignature]]:
    """Get signature of RasaModelData.

    Signature stores the shape and whether features are sparse or not for every key.
    """

    return {
        key: [
            FeatureSignature(
                True if isinstance(v[0], scipy.sparse.spmatrix) else False,
                v[0].shape,
            )
            for v in values
        ]
        for key, values in self.data.items()
    }


# Traceback (ValueError)
Traceback (most recent call last):
File "/Users/tabergma/Repositories/rasa/rasa/__main__.py", line 119, in <module>
main()
File "/Users/tabergma/Repositories/rasa/rasa/__main__.py", line 108, in main
cmdline_arguments.func(cmdline_arguments)
File "/Users/tabergma/Repositories/rasa/rasa/cli/train.py", line 142, in train_nlu
additional_arguments=extract_nlu_additional_arguments(args),
File "/Users/tabergma/Repositories/rasa/rasa/train.py", line 431, in train_nlu
additional_arguments,
File "uvloop/loop.pyx", line 1456, in uvloop.loop.Loop.run_until_complete
File "/Users/tabergma/Repositories/rasa/rasa/train.py", line 472, in _train_nlu_async
additional_arguments=additional_arguments,
File "/Users/tabergma/Repositories/rasa/rasa/train.py", line 506, in _train_nlu_with_validated_data
**additional_arguments,
File "/Users/tabergma/Repositories/rasa/rasa/nlu/train.py", line 90, in train
interpreter = trainer.train(training_data, **kwargs)
File "/Users/tabergma/Repositories/rasa/rasa/nlu/model.py", line 191, in train
updates = component.train(working_data, self.config, **context)
File "/Users/tabergma/Repositories/rasa/rasa/nlu/classifiers/diet_classifier.py", line 716, in train
config=self.component_config,
File "/Users/tabergma/Repositories/rasa/rasa/nlu/classifiers/diet_classifier.py", line 1032, in __init__
self._check_data()
File "/Users/tabergma/Repositories/rasa/rasa/nlu/classifiers/diet_classifier.py", line 1099, in _check_data
"If hidden layer weights are shared, data signatures "
ValueError: If hidden layer weights are shared, data signatures for text_features and label_features must coincide.

# Fixed code
def get_signature(self) -> Dict[Text, List[FeatureSignature]]:
    """Get signature of RasaModelData.

    Signature stores the shape and whether features are sparse or not for every key.
    """

    return {
        key: [
            FeatureSignature(
                True if isinstance(v[0], scipy.sparse.spmatrix) else False,
                v[0].shape[-1] if v[0].shape else None,
            )
            for v in values
        ]
        for key, values in self.data.items()
    }
# Buggy code
def __init__(
    self,
    domain: Domain,
    table_name: Text = "states",
    region: Text = "us-east-1",
    event_broker: Optional[EndpointConfig] = None,
):
    """
    Args:
        domain:
        table_name: The name of the DynamoDb table, does not
            need to be present a priori.
        event_broker:
    """
    import boto3

    self.client = boto3.client("dynamodb", region_name=region)
    self.region = region
    self.table_name = table_name
    self.db = self.get_or_create_table(table_name)
    super().__init__(domain, event_broker)


# Traceback (TypeError)
2020-01-23 11:47:22 DEBUG    rasa.core.processor  - Object of type Decimal is not JSON serializable
Traceback (most recent call last):
File "/Users/dsammut/Repos/chatbot-rasa/venv/lib/python3.7/site-packages/rasa/core/processor.py", line 564, in _run_action
events = await action.run(output_channel, nlg, tracker, self.domain)
File "/Users/dsammut/Repos/chatbot-rasa/venv/lib/python3.7/site-packages/rasa/core/actions/action.py", line 541, in run
json=json_body, method="post", timeout=DEFAULT_REQUEST_TIMEOUT
File "/Users/dsammut/Repos/chatbot-rasa/venv/lib/python3.7/site-packages/rasa/utils/endpoints.py", line 146, in request
**kwargs,
File "/Users/dsammut/Repos/chatbot-rasa/venv/lib/python3.7/site-packages/aiohttp/client.py", line 1012, in __aenter__
self._resp = await self._coro
File "/Users/dsammut/Repos/chatbot-rasa/venv/lib/python3.7/site-packages/aiohttp/client.py", line 365, in _request
data = payload.JsonPayload(json, dumps=self._json_serialize)
File "/Users/dsammut/Repos/chatbot-rasa/venv/lib/python3.7/site-packages/aiohttp/payload.py", line 389, in __init__
dumps(value).encode(encoding),
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/__init__.py", line 231, in dumps
return _default_encoder.encode(obj)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/encoder.py", line 257, in iterencode
return _iterencode(o, 0)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/encoder.py", line 179, in default
raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type Decimal is not JSON serializable

# Fixed code
def __init__(
    self,
    domain: Domain,
    table_name: Text = "states",
    region: Text = "us-east-1",
    event_broker: Optional[EndpointConfig] = None,
):
    """Initialize `DynamoTrackerStore`.

    Args:
        domain: Domain associated with this tracker store.
        table_name: The name of the DynamoDB table, does not need to be present a
            priori.
        region: The name of the region associated with the client.
            A client is associated with a single region.
        event_broker: An event broker used to publish events.
    """
    import boto3

    self.client = boto3.client("dynamodb", region_name=region)
    self.region = region
    self.table_name = table_name
    self.db = self.get_or_create_table(table_name)
    super().__init__(domain, event_broker)
# Buggy code
def serialise_tracker(self, tracker: "DialogueStateTracker") -> Dict:
    """Serializes the tracker, returns object with decimal types"""
    d = tracker.as_dialogue().as_dict()
    d.update(
        {
            "sender_id": tracker.sender_id,
            "session_date": int(datetime.now(tz=timezone.utc).timestamp()),
        }
    )
    return utils.replace_floats_with_decimals(d)


# Traceback (TypeError)
2020-01-23 11:47:22 DEBUG    rasa.core.processor  - Object of type Decimal is not JSON serializable
Traceback (most recent call last):
File "/Users/dsammut/Repos/chatbot-rasa/venv/lib/python3.7/site-packages/rasa/core/processor.py", line 564, in _run_action
events = await action.run(output_channel, nlg, tracker, self.domain)
File "/Users/dsammut/Repos/chatbot-rasa/venv/lib/python3.7/site-packages/rasa/core/actions/action.py", line 541, in run
json=json_body, method="post", timeout=DEFAULT_REQUEST_TIMEOUT
File "/Users/dsammut/Repos/chatbot-rasa/venv/lib/python3.7/site-packages/rasa/utils/endpoints.py", line 146, in request
**kwargs,
File "/Users/dsammut/Repos/chatbot-rasa/venv/lib/python3.7/site-packages/aiohttp/client.py", line 1012, in __aenter__
self._resp = await self._coro
File "/Users/dsammut/Repos/chatbot-rasa/venv/lib/python3.7/site-packages/aiohttp/client.py", line 365, in _request
data = payload.JsonPayload(json, dumps=self._json_serialize)
File "/Users/dsammut/Repos/chatbot-rasa/venv/lib/python3.7/site-packages/aiohttp/payload.py", line 389, in __init__
dumps(value).encode(encoding),
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/__init__.py", line 231, in dumps
return _default_encoder.encode(obj)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/encoder.py", line 257, in iterencode
return _iterencode(o, 0)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/encoder.py", line 179, in default
raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type Decimal is not JSON serializable

# Fixed code
def serialise_tracker(self, tracker: "DialogueStateTracker") -> Dict:
    """Serializes the tracker, returns object with decimal types"""
    d = tracker.as_dialogue().as_dict()
    d.update(
        {
            "sender_id": tracker.sender_id,
            "session_date": int(datetime.now(tz=timezone.utc).timestamp()),
        }
    )
    # DynamoDB cannot store `float`s, so we'll convert them to `Decimal`s
    return core_utils.replace_floats_with_decimals(d)
# Buggy code
def retrieve(self, sender_id: Text) -> Optional[DialogueStateTracker]:
    """Create a tracker from all previously stored events."""

    # Retrieve dialogues for a sender_id in reverse chronological order based on
    # the session_date sort key
    dialogues = self.db.query(
        KeyConditionExpression=Key("sender_id").eq(sender_id),
        Limit=1,
        ScanIndexForward=False,
    )["Items"]
    if dialogues:
        return DialogueStateTracker.from_dict(
            sender_id, dialogues[0].get("events"), self.domain.slots
        )
    else:
        return None


# Traceback (TypeError)
2020-01-23 11:47:22 DEBUG    rasa.core.processor  - Object of type Decimal is not JSON serializable
Traceback (most recent call last):
File "/Users/dsammut/Repos/chatbot-rasa/venv/lib/python3.7/site-packages/rasa/core/processor.py", line 564, in _run_action
events = await action.run(output_channel, nlg, tracker, self.domain)
File "/Users/dsammut/Repos/chatbot-rasa/venv/lib/python3.7/site-packages/rasa/core/actions/action.py", line 541, in run
json=json_body, method="post", timeout=DEFAULT_REQUEST_TIMEOUT
File "/Users/dsammut/Repos/chatbot-rasa/venv/lib/python3.7/site-packages/rasa/utils/endpoints.py", line 146, in request
**kwargs,
File "/Users/dsammut/Repos/chatbot-rasa/venv/lib/python3.7/site-packages/aiohttp/client.py", line 1012, in __aenter__
self._resp = await self._coro
File "/Users/dsammut/Repos/chatbot-rasa/venv/lib/python3.7/site-packages/aiohttp/client.py", line 365, in _request
data = payload.JsonPayload(json, dumps=self._json_serialize)
File "/Users/dsammut/Repos/chatbot-rasa/venv/lib/python3.7/site-packages/aiohttp/payload.py", line 389, in __init__
dumps(value).encode(encoding),
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/__init__.py", line 231, in dumps
return _default_encoder.encode(obj)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/encoder.py", line 257, in iterencode
return _iterencode(o, 0)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/encoder.py", line 179, in default
raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type Decimal is not JSON serializable

# Fixed code
def retrieve(self, sender_id: Text) -> Optional[DialogueStateTracker]:
    """Create a tracker from all previously stored events."""
    # Retrieve dialogues for a sender_id in reverse-chronological order based on
    # the session_date sort key
    dialogues = self.db.query(
        KeyConditionExpression=Key("sender_id").eq(sender_id),
        Limit=1,
        ScanIndexForward=False,
    )["Items"]

    if not dialogues:
        return None

    events = dialogues[0].get("events", [])

    # `float`s are stored as `Decimal` objects - we need to convert them back
    events_with_floats = core_utils.replace_decimals_with_floats(events)

    return DialogueStateTracker.from_dict(
        sender_id, events_with_floats, self.domain.slots
    )
# Buggy code
def configure_file_logging(logger_obj: logging.Logger, log_file: Optional[Text]):
    if not log_file:
        return

    formatter = logging.Formatter("%(asctime)s [%(levelname)-5.5s]  %(message)s")
    file_handler = logging.FileHandler(log_file, encoding=io_utils.DEFAULT_ENCODING)
    file_handler.setLevel(logger_obj.level)
    file_handler.setFormatter(formatter)
    logger_obj.addHandler(file_handler)


# Traceback (TypeError)
2020-01-23 11:47:22 DEBUG    rasa.core.processor  - Object of type Decimal is not JSON serializable
Traceback (most recent call last):
File "/Users/dsammut/Repos/chatbot-rasa/venv/lib/python3.7/site-packages/rasa/core/processor.py", line 564, in _run_action
events = await action.run(output_channel, nlg, tracker, self.domain)
File "/Users/dsammut/Repos/chatbot-rasa/venv/lib/python3.7/site-packages/rasa/core/actions/action.py", line 541, in run
json=json_body, method="post", timeout=DEFAULT_REQUEST_TIMEOUT
File "/Users/dsammut/Repos/chatbot-rasa/venv/lib/python3.7/site-packages/rasa/utils/endpoints.py", line 146, in request
**kwargs,
File "/Users/dsammut/Repos/chatbot-rasa/venv/lib/python3.7/site-packages/aiohttp/client.py", line 1012, in __aenter__
self._resp = await self._coro
File "/Users/dsammut/Repos/chatbot-rasa/venv/lib/python3.7/site-packages/aiohttp/client.py", line 365, in _request
data = payload.JsonPayload(json, dumps=self._json_serialize)
File "/Users/dsammut/Repos/chatbot-rasa/venv/lib/python3.7/site-packages/aiohttp/payload.py", line 389, in __init__
dumps(value).encode(encoding),
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/__init__.py", line 231, in dumps
return _default_encoder.encode(obj)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/encoder.py", line 257, in iterencode
return _iterencode(o, 0)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/encoder.py", line 179, in default
raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type Decimal is not JSON serializable

# Fixed code
def configure_file_logging(
    logger_obj: logging.Logger, log_file: Optional[Text]
) -> None:
    """Configure logging to a file.

    Args:
        logger_obj: Logger object to configure.
        log_file: Path of log file to write to.
    """
    if not log_file:
        return

    formatter = logging.Formatter("%(asctime)s [%(levelname)-5.5s]  %(message)s")
    file_handler = logging.FileHandler(log_file, encoding=io_utils.DEFAULT_ENCODING)
    file_handler.setLevel(logger_obj.level)
    file_handler.setFormatter(formatter)
    logger_obj.addHandler(file_handler)
# Buggy code
def one_hot(hot_idx: int, length: int, dtype: Optional[Text] = None) -> np.ndarray:
    if hot_idx >= length:
        raise ValueError(
            "Can't create one hot. Index '{}' is out of range (length '{}')".format(
                hot_idx, length
            )
        )
    r = np.zeros(length, dtype)
    r[hot_idx] = 1
    return r


# Traceback (TypeError)
2020-01-23 11:47:22 DEBUG    rasa.core.processor  - Object of type Decimal is not JSON serializable
Traceback (most recent call last):
File "/Users/dsammut/Repos/chatbot-rasa/venv/lib/python3.7/site-packages/rasa/core/processor.py", line 564, in _run_action
events = await action.run(output_channel, nlg, tracker, self.domain)
File "/Users/dsammut/Repos/chatbot-rasa/venv/lib/python3.7/site-packages/rasa/core/actions/action.py", line 541, in run
json=json_body, method="post", timeout=DEFAULT_REQUEST_TIMEOUT
File "/Users/dsammut/Repos/chatbot-rasa/venv/lib/python3.7/site-packages/rasa/utils/endpoints.py", line 146, in request
**kwargs,
File "/Users/dsammut/Repos/chatbot-rasa/venv/lib/python3.7/site-packages/aiohttp/client.py", line 1012, in __aenter__
self._resp = await self._coro
File "/Users/dsammut/Repos/chatbot-rasa/venv/lib/python3.7/site-packages/aiohttp/client.py", line 365, in _request
data = payload.JsonPayload(json, dumps=self._json_serialize)
File "/Users/dsammut/Repos/chatbot-rasa/venv/lib/python3.7/site-packages/aiohttp/payload.py", line 389, in __init__
dumps(value).encode(encoding),
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/__init__.py", line 231, in dumps
return _default_encoder.encode(obj)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/encoder.py", line 257, in iterencode
return _iterencode(o, 0)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/encoder.py", line 179, in default
raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type Decimal is not JSON serializable

# Fixed code
def one_hot(hot_idx: int, length: int, dtype: Optional[Text] = None) -> np.ndarray:
    """Create a one-hot array.

    Args:
        hot_idx: Index of the hot element.
        length: Length of the array.
        dtype: ``numpy.dtype`` of the array.

    Returns:
        One-hot array.
    """
    if hot_idx >= length:
        raise ValueError(
            "Can't create one hot. Index '{}' is out of range (length '{}')".format(
                hot_idx, length
            )
        )
    r = np.zeros(length, dtype)
    r[hot_idx] = 1
    return r
# Buggy code
def generate_id(prefix: Text = "", max_chars: Optional[int] = None) -> Text:
    import uuid

    gid = uuid.uuid4().hex
    if max_chars:
        gid = gid[:max_chars]

    return f"{prefix}{gid}"


# Traceback (TypeError)
2020-01-23 11:47:22 DEBUG    rasa.core.processor  - Object of type Decimal is not JSON serializable
Traceback (most recent call last):
File "/Users/dsammut/Repos/chatbot-rasa/venv/lib/python3.7/site-packages/rasa/core/processor.py", line 564, in _run_action
events = await action.run(output_channel, nlg, tracker, self.domain)
File "/Users/dsammut/Repos/chatbot-rasa/venv/lib/python3.7/site-packages/rasa/core/actions/action.py", line 541, in run
json=json_body, method="post", timeout=DEFAULT_REQUEST_TIMEOUT
File "/Users/dsammut/Repos/chatbot-rasa/venv/lib/python3.7/site-packages/rasa/utils/endpoints.py", line 146, in request
**kwargs,
File "/Users/dsammut/Repos/chatbot-rasa/venv/lib/python3.7/site-packages/aiohttp/client.py", line 1012, in __aenter__
self._resp = await self._coro
File "/Users/dsammut/Repos/chatbot-rasa/venv/lib/python3.7/site-packages/aiohttp/client.py", line 365, in _request
data = payload.JsonPayload(json, dumps=self._json_serialize)
File "/Users/dsammut/Repos/chatbot-rasa/venv/lib/python3.7/site-packages/aiohttp/payload.py", line 389, in __init__
dumps(value).encode(encoding),
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/__init__.py", line 231, in dumps
return _default_encoder.encode(obj)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/encoder.py", line 257, in iterencode
return _iterencode(o, 0)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/encoder.py", line 179, in default
raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type Decimal is not JSON serializable

# Fixed code
def generate_id(prefix: Text = "", max_chars: Optional[int] = None) -> Text:
    """Generate a random UUID.

    Args:
        prefix: String to prefix the ID with.
        max_chars: Maximum number of characters.

    Returns:
        Generated random UUID.
    """
    import uuid

    gid = uuid.uuid4().hex
    if max_chars:
        gid = gid[:max_chars]

    return f"{prefix}{gid}"
# Buggy code
def is_limit_reached(num_messages: int, limit: int) -> bool:
    return limit is not None and num_messages >= limit


# Traceback (TypeError)
2020-01-23 11:47:22 DEBUG    rasa.core.processor  - Object of type Decimal is not JSON serializable
Traceback (most recent call last):
File "/Users/dsammut/Repos/chatbot-rasa/venv/lib/python3.7/site-packages/rasa/core/processor.py", line 564, in _run_action
events = await action.run(output_channel, nlg, tracker, self.domain)
File "/Users/dsammut/Repos/chatbot-rasa/venv/lib/python3.7/site-packages/rasa/core/actions/action.py", line 541, in run
json=json_body, method="post", timeout=DEFAULT_REQUEST_TIMEOUT
File "/Users/dsammut/Repos/chatbot-rasa/venv/lib/python3.7/site-packages/rasa/utils/endpoints.py", line 146, in request
**kwargs,
File "/Users/dsammut/Repos/chatbot-rasa/venv/lib/python3.7/site-packages/aiohttp/client.py", line 1012, in __aenter__
self._resp = await self._coro
File "/Users/dsammut/Repos/chatbot-rasa/venv/lib/python3.7/site-packages/aiohttp/client.py", line 365, in _request
data = payload.JsonPayload(json, dumps=self._json_serialize)
File "/Users/dsammut/Repos/chatbot-rasa/venv/lib/python3.7/site-packages/aiohttp/payload.py", line 389, in __init__
dumps(value).encode(encoding),
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/__init__.py", line 231, in dumps
return _default_encoder.encode(obj)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/encoder.py", line 257, in iterencode
return _iterencode(o, 0)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/encoder.py", line 179, in default
raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type Decimal is not JSON serializable

# Fixed code
def is_limit_reached(num_messages: int, limit: int) -> bool:
    """Determine whether the number of messages has reached a limit.

    Args:
        num_messages: The number of messages to check.
        limit: Limit on the number of messages.

    Returns:
        `True` if the limit has been reached, otherwise `False`.
    """
    return limit is not None and num_messages >= limit
# Buggy code
def _lock_store_is_redis_lock_store(
    lock_store: Union[EndpointConfig, LockStore, None],
) -> bool:
    # determine whether `lock_store` is associated with a `RedisLockStore`
    if isinstance(lock_store, LockStore):
        if isinstance(lock_store, RedisLockStore):
            return True
        return False

    # `lock_store` is `None` or `EndpointConfig`
    return lock_store is not None and lock_store.type == "redis"


# Traceback (TypeError)
2020-01-23 11:47:22 DEBUG    rasa.core.processor  - Object of type Decimal is not JSON serializable
Traceback (most recent call last):
File "/Users/dsammut/Repos/chatbot-rasa/venv/lib/python3.7/site-packages/rasa/core/processor.py", line 564, in _run_action
events = await action.run(output_channel, nlg, tracker, self.domain)
File "/Users/dsammut/Repos/chatbot-rasa/venv/lib/python3.7/site-packages/rasa/core/actions/action.py", line 541, in run
json=json_body, method="post", timeout=DEFAULT_REQUEST_TIMEOUT
File "/Users/dsammut/Repos/chatbot-rasa/venv/lib/python3.7/site-packages/rasa/utils/endpoints.py", line 146, in request
**kwargs,
File "/Users/dsammut/Repos/chatbot-rasa/venv/lib/python3.7/site-packages/aiohttp/client.py", line 1012, in __aenter__
self._resp = await self._coro
File "/Users/dsammut/Repos/chatbot-rasa/venv/lib/python3.7/site-packages/aiohttp/client.py", line 365, in _request
data = payload.JsonPayload(json, dumps=self._json_serialize)
File "/Users/dsammut/Repos/chatbot-rasa/venv/lib/python3.7/site-packages/aiohttp/payload.py", line 389, in __init__
dumps(value).encode(encoding),
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/__init__.py", line 231, in dumps
return _default_encoder.encode(obj)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/encoder.py", line 257, in iterencode
return _iterencode(o, 0)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/encoder.py", line 179, in default
raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type Decimal is not JSON serializable

# Fixed code
def _lock_store_is_redis_lock_store(
    lock_store: Union[EndpointConfig, LockStore, None],
) -> bool:
    if isinstance(lock_store, RedisLockStore):
        return True

    if isinstance(lock_store, LockStore):
        return False

    # `lock_store` is `None` or `EndpointConfig`
    return lock_store is not None and lock_store.type == "redis"
# Buggy code
async def send_custom_json(
    self, recipient_id: Text, json_message: Dict[Text, Any], **kwargs: Any
) -> None:
    """Send custom json dict"""

    json_message.setdefault("to", recipient_id)
    if not json_message.get("media_url"):
        json_message.setdefault("body", "")
    if not json_message.get("messaging_service_sid"):
        json_message.setdefault("from", self.twilio_number)

    await self._send_message(json_message)


# Traceback (TypeError)
[2020-02-20 15:18:23 +0100] [11856] [ERROR] Exception occurred while handling uri: 'http://570158816806510.ngrok.io/webhooks/twilio/webhook'
Traceback (most recent call last):
File "/home/nicolas/anaconda3/envs/chatbot_sms/lib/python3.7/site-packages/sanic/app.py", line 942, in handle_request
response = await response
File "/home/nicolas/anaconda3/envs/chatbot_sms/lib/python3.7/site-packages/rasa/core/channels/twilio.py", line 132, in message
metadata=metadata,
File "/home/nicolas/anaconda3/envs/chatbot_sms/lib/python3.7/site-packages/rasa/core/channels/channel.py", line 83, in handler
await app.agent.handle_message(*args, **kwargs)
File "/home/nicolas/anaconda3/envs/chatbot_sms/lib/python3.7/site-packages/rasa/core/agent.py", line 486, in handle_message
return await processor.handle_message(message)
File "/home/nicolas/anaconda3/envs/chatbot_sms/lib/python3.7/site-packages/rasa/core/processor.py", line 108, in handle_message
await self._predict_and_execute_next_action(message.output_channel, tracker)
File "/home/nicolas/anaconda3/envs/chatbot_sms/lib/python3.7/site-packages/rasa/core/processor.py", line 509, in _predict_and_execute_next_action
action, tracker, output_channel, self.nlg, policy, confidence
File "/home/nicolas/anaconda3/envs/chatbot_sms/lib/python3.7/site-packages/rasa/core/processor.py", line 620, in _run_action
await self._send_bot_messages(events, tracker, output_channel)
File "/home/nicolas/anaconda3/envs/chatbot_sms/lib/python3.7/site-packages/rasa/core/processor.py", line 549, in _send_bot_messages
await output_channel.send_response(tracker.sender_id, e.message())
File "/home/nicolas/anaconda3/envs/chatbot_sms/lib/python3.7/site-packages/rasa/core/channels/channel.py", line 189, in send_response
await self.send_custom_json(recipient_id, message.pop("custom"), **message)
File "/home/nicolas/anaconda3/envs/chatbot_sms/lib/python3.7/site-packages/rasa/core/channels/twilio.py", line 70, in send_custom_json
await self._send_message(json_message)
File "/home/nicolas/anaconda3/envs/chatbot_sms/lib/python3.7/site-packages/rasa/core/channels/twilio.py", line 37, in _send_message
message = self.messages.create(**message_data)
TypeError: create() got an unexpected keyword argument 'from'

# Fixed code
async def send_custom_json(
    self, recipient_id: Text, json_message: Dict[Text, Any], **kwargs: Any
) -> None:
    """Send custom json dict"""

    json_message.setdefault("to", recipient_id)
    if not json_message.get("media_url"):
        json_message.setdefault("body", "")
    if not json_message.get("messaging_service_sid"):
        json_message.setdefault("from_", self.twilio_number)

    await self._send_message(json_message)
# Buggy code
def register(
    input_channels: List["InputChannel"],
    app: Flask,
    on_new_message: Callable[[UserMessage], None],
    route: Text,
) -> None:
    for channel in input_channels:
        p = urljoin(route, channel.url_prefix())
        app.register_blueprint(channel.blueprint(on_new_message), url_prefix=p)


# Traceback (MemoryError)
2019-01-14 08:40:41 INFO     rasa_nlu.training_data.loading  - Training data format of rasa_classification_train_set.md is md
2019-01-14 08:40:43 INFO     rasa_nlu.training_data.training_data  - Training data stats:
- intent examples: 73962 (38 distinct intents)
** removing entity names **
- entity examples: 0 (0 distinct entities)
- found entities:

2019-01-14 08:40:46 INFO     rasa_nlu.model  - Starting to train component tokenizer_whitespace
2019-01-14 08:40:55 INFO     rasa_nlu.model  - Finished training component.
2019-01-14 08:40:55 INFO     rasa_nlu.model  - Starting to train component ner_crf
2019-01-14 08:40:55 INFO     rasa_nlu.model  - Finished training component.
2019-01-14 08:40:55 INFO     rasa_nlu.model  - Starting to train component ner_synonyms
2019-01-14 08:40:55 INFO     rasa_nlu.model  - Finished training component.
2019-01-14 08:40:55 INFO     rasa_nlu.model  - Starting to train component intent_featurizer_count_vectors
Traceback (most recent call last):
File "C:\Users\harsh.khadloya\AppData\Local\Continuum\Anaconda3\lib\runpy.py", line 184, in _run_module_as_main
"__main__", mod_spec)
File "C:\Users\harsh.khadloya\AppData\Local\Continuum\Anaconda3\lib\runpy.py", line 85, in _run_code
exec(code, run_globals)
File "C:\Users\harsh.khadloya\AppData\Local\Continuum\Anaconda3\lib\site-packages\rasa_nlu\train.py", line 184, in <module>
num_threads=cmdline_args.num_threads)
File "C:\Users\harsh.khadloya\AppData\Local\Continuum\Anaconda3\lib\site-packages\rasa_nlu\train.py", line 154, in do_train
interpreter = trainer.train(training_data, **kwargs)
File "C:\Users\harsh.khadloya\AppData\Local\Continuum\Anaconda3\lib\site-packages\rasa_nlu\model.py", line 196, in train
**context)
File "C:\Users\harsh.khadloya\AppData\Local\Continuum\Anaconda3\lib\site-packages\rasa_nlu\featurizers\count_vectors_featurizer.py", line 214, in train
X = self.vect.fit_transform(lem_exs).toarray()
File "C:\Users\harsh.khadloya\AppData\Local\Continuum\Anaconda3\lib\site-packages\scipy\sparse\compressed.py", line 947, in toarray
out = self._process_toarray_args(order, out)
File "C:\Users\harsh.khadloya\AppData\Local\Continuum\Anaconda3\lib\site-packages\scipy\sparse\base.py", line 1184, in _process_toarray_args
return np.zeros(self.shape, dtype=self.dtype, order=order)
MemoryError

# Fixed code
def register(
    input_channels: List["InputChannel"],
    app: Flask,
    on_new_message: Callable[[UserMessage], None],
    route: Optional[Text],
) -> None:
    for channel in input_channels:
        if route:
            p = urljoin(route, channel.url_prefix())
        else:
            p = None

        app.register_blueprint(channel.blueprint(on_new_message), url_prefix=p)