anon-iclr-submission/benchname-bug-localization huggingface dataset:
Repository: nonebot/nonebot2
Issue: Bug: 错误删除未执行过的`temp matcher`

**描述问题：**

处理事件时错误地删除了未执行过的 `temp matcher`

**环境信息：**

 - OS: any
 - Python Version: any
 - Nonebot Version: 2.0.0a8


Changed files:
nonebot/message.py

diff --git a/nonebot/message.py b/nonebot/message.py
index 5b3c8b6f..c6974b2c 100644
--- a/nonebot/message.py
+++ b/nonebot/message.py
@@ -117,8 +117,7 @@ async def _check_matcher(priority: int, bot: "Bot", event: "Event",
         return None
 
     async def _check_expire(Matcher: Type[Matcher]) -> Optional[Type[Matcher]]:
-        if Matcher.temp or (Matcher.expire_time and
-                            datetime.now() > Matcher.expire_time):
+        if Matcher.expire_time and datetime.now() > Matcher.expire_time:
             return Matcher
         return None
 
@@ -128,14 +127,19 @@ async def _check_matcher(priority: int, bot: "Bot", event: "Event",
     checking_expire_tasks = [
         _check_expire(Matcher) for Matcher in current_matchers
     ]
-    results = await asyncio.gather(*checking_tasks, return_exceptions=True)
+    results = await asyncio.gather(*checking_tasks)
     expired = await asyncio.gather(*checking_expire_tasks)
     for expired_matcher in filter(lambda x: x, expired):
         try:
             matchers[priority].remove(expired_matcher)  # type: ignore
         except Exception:
             pass
-    return filter(lambda x: x, results)
+    for temp_matcher in filter(lambda x: x and x.temp, results):
+        try:
+            matchers[priority].remove(temp_matcher)  # type: ignore
+        except Exception:
+            pass
+    return filter(lambda x: x, results)  # type: ignore
 
 
 async def _run_matcher(Matcher: Type[Matcher], bot: "Bot", event: "Event",
Repository: nonebot/nonebot2
Issue: Bug: 事件响应器异常

**描述问题：**

任意事件响应器
```
from nonebot import on_message
message = on_message()
```
对于任何消息都会引发异常
```
01-01 14:57:55 [DEBUG] nonebot | CQHTTP | Event Parser Error
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "C:\\Users\\...\\AppData\\Local\\Programs\\Python\\Python38\\lib\\multiprocessing\\spawn.py", line 116, in spawn_main
    exitcode = _main(fd, parent_sentinel)
  File "C:\\Users\\...\\AppData\\Local\\Programs\\Python\\Python38\\lib\\multiprocessing\\spawn.py", line 129, in _main
    return self._bootstrap(parent_sentinel)
  File "C:\\Users\\...\\AppData\\Local\\Programs\\Python\\Python38\\lib\\multiprocessing\\process.py", line 315, in _bootstrap
    self.run()
  File "C:\\Users\\...\\AppData\\Local\\Programs\\Python\\Python38\\lib\\multiprocessing\\process.py", line 108, in run
    self._target(*self._args, **self._kwargs)
  File "C:\\Users\\...\\PycharmProjects\\nonebot2\\venv\\lib\\site-packages\\uvicorn\\subprocess.py", line 62, in subprocess_started
    target(sockets=sockets)
  File "C:\\Users\\...\\PycharmProjects\\nonebot2\\venv\\lib\\site-packages\\uvicorn\\main.py", line 390, in run
    loop.run_until_complete(self.serve(sockets=sockets))
  File "C:\\Users\\...\\AppData\\Local\\Programs\\Python\\Python38\\lib\\asyncio\\base_events.py", line 603, in run_until_complete
    self.run_forever()
  File "C:\\Users\\...\\AppData\\Local\\Programs\\Python\\Python38\\lib\\asyncio\\base_events.py", line 570, in run_forever
    self._run_once()
  File "C:\\Users\\...\\AppData\\Local\\Programs\\Python\\Python38\\lib\\asyncio\\base_events.py", line 1859, in _run_once
    handle._run()
  File "C:\\Users\\...\\AppData\\Local\\Programs\\Python\\Python38\\lib\\asyncio\\events.py", line 81, in _run
    self._context.run(self._callback, *self._args)
> File "C:\\Users\\...\\PycharmProjects\\nonebot2\\venv\\lib\\site-packages\\nonebot\\adapters\\cqhttp\\bot.py", line 307, in handle_message
    event = model.parse_obj(message)
  File "pydantic\\main.py", line 520, in pydantic.main.BaseModel.parse_obj
    return cls(**obj)
  File "pydantic\\main.py", line 362, in pydantic.main.BaseModel.__init__
    raise validation_error
pydantic.error_wrappers.ValidationError: 1 validation error for GroupMessageEvent
anonymous
  none is not an allowed value (type=type_error.none.not_allowed)
```

**环境信息：**

 - OS: Windows 10 20H2 19042.685
 - Python Version: 3.8
 - Nonebot Version: 2.0.0a8 (从2.0.0a7升级)



Changed files:
nonebot/adapters/cqhttp/event.py

diff --git a/nonebot/adapters/cqhttp/event.py b/nonebot/adapters/cqhttp/event.py
index 5d1cdb2f..39e78943 100644
--- a/nonebot/adapters/cqhttp/event.py
+++ b/nonebot/adapters/cqhttp/event.py
@@ -184,7 +184,7 @@ class GroupMessageEvent(MessageEvent):
     __event__ = "message.group"
     message_type: Literal["group"]
     group_id: int
-    anonymous: Anonymous
+    anonymous: Optional[Anonymous] = None
 
     @overrides(Event)
     def get_event_description(self) -> str:
Repository: nonebot/nonebot2
Issue: 在 nonebot-test 前端调试时无法让 Bot 说出 <test>

nonebot.load_builtin_plugins() 后，在 nonebot-test 前端向 Bot 发送 /say <test> 

Bot 未发送任何消息，且 nonebot2 控制台返回：

```
[ERROR] nonebot_test | Tag "<test>" does not corespond to any known ansi directive, make sure you did not misspelled it (or prepend '\\' to escape it)
```

Changed files:
nonebot/__init__.py, nonebot/utils.py, nonebot/message.py

diff --git a/nonebot/__init__.py b/nonebot/__init__.py
index 6f93bdae..213b63d2 100644
--- a/nonebot/__init__.py
+++ b/nonebot/__init__.py
@@ -109,6 +109,7 @@ def get_bots() -> Union[NoReturn, Dict[str, Bot]]:
 
 
 from nonebot.sched import scheduler
+from nonebot.utils import escape_tag
 from nonebot.config import Env, Config
 from nonebot.log import logger, default_filter
 from nonebot.adapters.cqhttp import Bot as CQBot
@@ -155,8 +156,8 @@ def init(*, _env_file: Optional[str] = None, **kwargs):
                         _env_file=_env_file or f".env.{env.environment}")
 
         default_filter.level = "DEBUG" if config.debug else "INFO"
-        logger.opt(
-            colors=True).debug(f"Loaded <y><b>Config</b></y>: {config.dict()}")
+        logger.opt(colors=True).debug(
+            f"Loaded <y><b>Config</b></y>: {escape_tag(str(config.dict()))}")
 
         DriverClass: Type[Driver] = getattr(
             importlib.import_module(config.driver), "Driver")
diff --git a/nonebot/message.py b/nonebot/message.py
index b6c3d888..f3a69e3a 100644
--- a/nonebot/message.py
+++ b/nonebot/message.py
@@ -6,6 +6,7 @@ from datetime import datetime
 
 from nonebot.log import logger
 from nonebot.rule import TrieRule
+from nonebot.utils import escape_tag
 from nonebot.matcher import matchers
 from nonebot.typing import Set, Type, Union, NoReturn
 from nonebot.typing import Bot, Event, Matcher, PreProcessor
@@ -64,7 +65,9 @@ async def handle_event(bot: Bot, event: Event):
             log_msg += f"@[群:{event.group_id}]:"
 
         log_msg += ' "' + "".join(
-            map(lambda x: str(x) if x.type == "text" else f"<le>{x!s}</le>",
+            map(
+                lambda x: escape_tag(str(x))
+                if x.type == "text" else f"<le>{escape_tag(str(x))}</le>",
                 event.message)) + '"'  # type: ignore
     elif event.type == "notice":
         log_msg += f"Notice {event.raw_event}"
diff --git a/nonebot/utils.py b/nonebot/utils.py
index 06bdaaa4..b442f6bd 100644
--- a/nonebot/utils.py
+++ b/nonebot/utils.py
@@ -1,6 +1,7 @@
 #!/usr/bin/env python3
 # -*- coding: utf-8 -*-
 
+import re
 import json
 import asyncio
 import dataclasses
@@ -9,6 +10,10 @@ from functools import wraps, partial
 from nonebot.typing import Any, Callable, Awaitable, overrides
 
 
+def escape_tag(s: str) -> str:
+    return re.sub(r"</?((?:[fb]g\\s)?[^<>\\s]*)>", r"\\\\\\g<0>", s)
+
+
 def run_sync(func: Callable[..., Any]) -> Callable[..., Awaitable[Any]]:
     """
     :说明:
Repository: nonebot/nonebot2
Issue: Bug: @on_notice(sth).send() reply a group message when receive notice in private chat

**描述问题：**

私聊注册一个on_notice以后（比如戳一戳），生成的PokeNotifyEvent中存在attr 'group_id' = None；
但是在cqhttp的adapter中（_见nonebot/adapters/cqhttp/bot.py function Bot.send()_)，send只会检测group_id是否存在于字典中，而不检测它是否为None，因此会把这条私聊的notice作为群聊消息返回。
详细代码如下：
```python
        if "message_type" not in params:
            if "group_id" in params:
                params["message_type"] = "group"
            elif "user_id" in params:
                params["message_type"] = "private"
            else:
                raise ValueError("Cannot guess message type to reply!")
```
（实际上改动一下if statement就好？但我不敢提pr，没怎么读过代码）

**如何复现？**

见上文。

**期望的结果**

@on_notice(sth).send() 应该发送私聊消息

**环境信息：**

 - OS: OS Independent
 - Python Version: 3.8
 - Nonebot Version: 2.0.0a8post1

**截图**

暂无

Changed files:
nonebot/adapters/cqhttp/bot.py

diff --git a/nonebot/adapters/cqhttp/bot.py b/nonebot/adapters/cqhttp/bot.py
index aa2783f3..1aff6d5d 100644
--- a/nonebot/adapters/cqhttp/bot.py
+++ b/nonebot/adapters/cqhttp/bot.py
@@ -421,19 +421,19 @@ class Bot(BaseBot):
         message = escape(message) if isinstance(message, str) else message
         msg = message if isinstance(message, Message) else Message(message)
 
-        at_sender = at_sender and hasattr(event, "user_id")
+        at_sender = at_sender and getattr(event, "user_id", None)
 
         params = {}
-        if hasattr(event, "user_id"):
+        if getattr(event, "user_id", None):
             params["user_id"] = getattr(event, "user_id")
-        if hasattr(event, "group_id"):
+        if getattr(event, "group_id", None):
             params["group_id"] = getattr(event, "group_id")
         params.update(kwargs)
 
         if "message_type" not in params:
-            if "group_id" in params:
+            if params.get("group_id", None):
                 params["message_type"] = "group"
-            elif "user_id" in params:
+            elif params.get("user_id", None):
                 params["message_type"] = "private"
             else:
                 raise ValueError("Cannot guess message type to reply!")
Repository: zauberzeug/nicegui
Issue: ui.refreshable updating the wrong element

### Description

This observation originates from a StackOverflow question: https://stackoverflow.com/questions/76763206/is-it-possible-to-use-widgets-in-nicegui-python

The following code creates two refreshable buttons, each of which refreshes itself and notifies the user about it. But independent of which button is clicked, it always refreshes button B.

```py
class Test:

    def __init__(self, name):
        self.name = name
        self.ui()

    @ui.refreshable
    def ui(self):
        ui.notify(f'Refreshing {self.name}')
        ui.button(self.name, on_click=self.ui.refresh)

Test('A')
Test('B')
```

The problem can be avoided by replacing
```py
on_click=self.ui.refresh
```
with
```py
on_click=lambda: self.ui.refresh()
```

But what is the reason for this mixup, and how to fix it?

Changed files:
nicegui/functions/refreshable.py, tests/test_refreshable.py

diff --git a/nicegui/functions/refreshable.py b/nicegui/functions/refreshable.py
index ad5d8558..a76ccc22 100644
--- a/nicegui/functions/refreshable.py
+++ b/nicegui/functions/refreshable.py
@@ -53,6 +53,15 @@ class refreshable:
         self.instance = instance
         return self
 
+    def __getattribute__(self, __name: str) -> Any:
+        attribute = object.__getattribute__(self, __name)
+        if __name == 'refresh':
+            def refresh(instance=self.instance, *args: Any, **kwargs: Any) -> None:
+                self.instance = instance
+                attribute(*args, **kwargs)
+            return refresh
+        return attribute
+
     def __call__(self, *args: Any, **kwargs: Any) -> Union[None, Awaitable]:
         self.prune()
         target = RefreshableTarget(container=RefreshableContainer(), instance=self.instance, args=args, kwargs=kwargs)
diff --git a/tests/test_refreshable.py b/tests/test_refreshable.py
index 9a934cb2..52a52634 100644
--- a/tests/test_refreshable.py
+++ b/tests/test_refreshable.py
@@ -31,7 +31,7 @@ def test_refreshable(screen: Screen) -> None:
     screen.should_contain('[]')
 
 
-async def test_async_refreshable(screen: Screen) -> None:
+def test_async_refreshable(screen: Screen) -> None:
     numbers = []
 
     @ui.refreshable
@@ -146,3 +146,26 @@ def test_refresh_deleted_element(screen: Screen):
 
     screen.click('Clear')
     screen.click('Refresh')
+
+
+def test_refresh_with_function_reference(screen: Screen):
+    # https://github.com/zauberzeug/nicegui/issues/1283
+    class Test:
+
+        def __init__(self, name):
+            self.name = name
+            self.ui()
+
+        @ui.refreshable
+        def ui(self):
+            ui.notify(f'Refreshing {self.name}')
+            ui.button(self.name, on_click=self.ui.refresh)
+
+    Test('A')
+    Test('B')
+
+    screen.open('/')
+    screen.click('A')
+    screen.should_contain('Refreshing A')
+    screen.click('B')
+    screen.should_contain('Refreshing B')
Repository: deepchem/deepchem
Issue: dc.metrics.balanced_accuracy_score is broken

`dc.metrics.balanced_accuracy_score` is broken right now. This line https://github.com/deepchem/deepchem/blob/master/deepchem/metrics/__init__.py#L112
should be replaced with

```
sklearn.metrics.balanced_accuracy_score(y, y_pred, sample_weight=weights)
```

Changed files:
deepchem/metrics/__init__.py

diff --git a/deepchem/metrics/__init__.py b/deepchem/metrics/__init__.py
index 02e03767f..d5af28822 100644
--- a/deepchem/metrics/__init__.py
+++ b/deepchem/metrics/__init__.py
@@ -109,7 +109,8 @@ def balanced_accuracy_score(y, y_pred):
   pos_weight = num_negative / num_positive
   weights = np.ones_like(y)
   weights[y != 0] = pos_weight
-  return accuracy_score(y, y_pred, sample_weight=weights)
+  return sklearn.metrics.balanced_accuracy_score(
+      y, y_pred, sample_weight=weights)
 
 
 def pearson_r2_score(y, y_pred):
Repository: deepchem/deepchem
Issue: Pytorch models cannot be printed to screen

## 🐛 Bug

At least some Pytorch models cannot be printed to screen, as would be normal to do through `__str__` or `__repr__`. For example, MPNN fails with the error

`AttributeError: 'MPNNModel' object has no attribute 'edge_hidden_feats'`

and AttentiveFPModel fails with 

`AttributeError: 'AttentiveFPModel' object has no attribute 'dropout'`

## To Reproduce

Steps to reproduce the behavior for MPNN:

```
>> from deepchem.models.torch_models import MPNNModel
>> model = MPNNModel(mode='classification', n_tasks=len(tasks),
..                   batch_size=32, learning_rate=0.001)
```

Now, just try to print the model

```
>> print(model)
```

leading to `AttributeError: 'MPNNModel' object has no attribute 'edge_hidden_feats'`.

## Expected behavior

A string should be printed to screen by the `__str__` or the `__repr__` magic methods.

## Environment

* OS: Ubuntu 18
* Python version: 3.7.10
* DeepChem version: 2.5.0


Changed files:
deepchem/models/models.py

diff --git a/deepchem/models/models.py b/deepchem/models/models.py
index dcc6f7a4e..21cce7e96 100644
--- a/deepchem/models/models.py
+++ b/deepchem/models/models.py
@@ -9,7 +9,6 @@ import logging
 from typing import List, Optional, Sequence
 
 import numpy as np
-from sklearn.base import BaseEstimator
 
 from deepchem.data import Dataset
 from deepchem.metrics import Metric
@@ -20,7 +19,7 @@ from deepchem.utils.typing import ArrayLike
 logger = logging.getLogger(__name__)
 
 
-class Model(BaseEstimator):
+class Model(object):
   """
   Abstract base class for DeepChem models.
   """
Repository: deepchem/deepchem
Issue: SmilesTokenizer Instance can not be created

## 🐛 Bug

I wanted to use the SmilesTokenizer from deepchem as it is explained in [the docs](https://deepchem.readthedocs.io/en/2.4.0/api_reference/tokenizers.html#smilestokenizer). However, i'm not able to create an instance of the SmilesTokenizer due to the following error:
```
Traceback(most recent call last):
File "/tmp/pycharm_projects/spielwiese/main.py", line 19, in <module>
    tokenizer = SmilesTokenizer(vocab_path)
File "/root/miniconda3/lib/python3.8/site-packages/deepchem/feat/smiles_tokenizer.py", line 89, in __init__
    self.max_len_single_sentence = self.max_len - 2
AttributeError: 'SmilesTokenizer' object has no attribute 'max_len
```

This seems to be caused by incompabilities between the versions of deepchem and transformers as it was already mentioned [here.](https://github.com/huggingface/transformers/issues/8739) However, the fix "changing max_len to model_max_length" has not been applied to deepchem yet. 

This would be nice for using the latest versions of all packages involved.

* Python version: 3.8.5
* DeepChem version: 2.5.0
* Transformers version: 4.6.0
* PyTorch version (optional): 1.8.1



Changed files:
deepchem/feat/smiles_tokenizer.py

diff --git a/deepchem/feat/smiles_tokenizer.py b/deepchem/feat/smiles_tokenizer.py
index 233db6b44..8aa0663bb 100644
--- a/deepchem/feat/smiles_tokenizer.py
+++ b/deepchem/feat/smiles_tokenizer.py
@@ -86,8 +86,8 @@ class SmilesTokenizer(BertTokenizer):
 
     super().__init__(vocab_file, **kwargs)
     # take into account special tokens in max length
-    self.max_len_single_sentence = self.max_len - 2
-    self.max_len_sentences_pair = self.max_len - 3
+    self.max_len_single_sentence = self.model_max_length - 2
+    self.max_len_sentences_pair = self.model_max_length - 3
 
     if not os.path.isfile(vocab_file):
       raise ValueError(
@@ -98,7 +98,7 @@ class SmilesTokenizer(BertTokenizer):
     self.ids_to_tokens = collections.OrderedDict(
         [(ids, tok) for tok, ids in self.vocab.items()])
     self.basic_tokenizer = BasicSmilesTokenizer()
-    self.init_kwargs["max_len"] = self.max_len
+    self.init_kwargs["model_max_length"] = self.model_max_length
 
   @property
   def vocab_size(self):
Repository: deepchem/deepchem
Issue: dtype of `y` array in `DiskDataset` depends on whether `X` is accessed beforehand

## 🐛 Bug

```
_, datasets, _ = dc.molnet.load_hiv(
    featurizer=dc.feat.RawFeaturizer(smiles=False),
    splitter=None,   # no splitting
    transformers=[]  # no transformation
)
print(datasets[0].y.dtype)
```
outputs
```
object
```

but
```
_, datasets, _ = dc.molnet.load_hiv(
    featurizer=dc.feat.RawFeaturizer(smiles=False),
    splitter=None,   # no splitting
    transformers=[]  # no transformation
)
print(datasets[0].X.dtype)
print(datasets[0].y.dtype)
```
outputs
```
object
float64
```

In the first case `y` has a `dtype` of `object`, but in the second case it has a `dtype` of `float64`

## To Reproduce

See above.

This is for DeepChem version 2.4.0-rc1.dev, installed via pip.

## Expected behavior

The `dtype` to consistently be `float64`

## Environment

* OS: Ubuntu 18.04. LTS
* Python version: 3.8.6
* DeepChem version: 2.4.0-rc1.dev
* RDKit version (optional): 2020.09.3

Changed files:
deepchem/data/datasets.py

diff --git a/deepchem/data/datasets.py b/deepchem/data/datasets.py
index abe66c82b..10af7a99d 100644
--- a/deepchem/data/datasets.py
+++ b/deepchem/data/datasets.py
@@ -2180,8 +2180,7 @@ class DiskDataset(Dataset):
     if self._cached_shards is not None and self._cached_shards[i] is not None:
       return self._cached_shards[i].y
     row = self.metadata_df.iloc[i]
-    return np.array(
-        load_from_disk(os.path.join(self.data_dir, row['y'])), dtype=object)
+    return np.array(load_from_disk(os.path.join(self.data_dir, row['y'])))
 
   def get_shard_w(self, i: int) -> np.ndarray:
     """Retrieves the weights for the i-th shard from disk.
@@ -2200,8 +2199,7 @@ class DiskDataset(Dataset):
     if self._cached_shards is not None and self._cached_shards[i] is not None:
       return self._cached_shards[i].w
     row = self.metadata_df.iloc[i]
-    return np.array(
-        load_from_disk(os.path.join(self.data_dir, row['w'])), dtype=object)
+    return np.array(load_from_disk(os.path.join(self.data_dir, row['w'])))
 
   def add_shard(self,
                 X: np.ndarray,
Repository: deepchem/deepchem
Issue: Printing a Model

## 🐛 Bug
## To Reproduce

Suppose I want to find the summary of a deepchem model and I use `print(model)` it throws an `AttributeError`.

Steps to reproduce the behavior:
```
model = dc.models.AtomicConvModel(n_tasks = 4)
print (model)
```

I would like `print(model)` to print the summary of the model. Any hints on how to fix it?
Thanks

Changed files:
deepchem/models/keras_model.py, deepchem/models/torch_models/torch_model.py

diff --git a/deepchem/models/keras_model.py b/deepchem/models/keras_model.py
index 115adb843..7dfe8b43a 100644
--- a/deepchem/models/keras_model.py
+++ b/deepchem/models/keras_model.py
@@ -175,6 +175,9 @@ class KerasModel(Model):
       the Weights & Biases logger object used to log data and metrics
     """
     super(KerasModel, self).__init__(model=model, model_dir=model_dir, **kwargs)
+    self.loss = loss  # not used
+    self.learning_rate = learning_rate  # not used
+    self.output_types = output_types  # not used
     if isinstance(loss, Loss):
       self._loss_fn: LossFn = _StandardLoss(model, loss)
     else:
diff --git a/deepchem/models/torch_models/torch_model.py b/deepchem/models/torch_models/torch_model.py
index 9b51a3d25..b5191d53e 100644
--- a/deepchem/models/torch_models/torch_model.py
+++ b/deepchem/models/torch_models/torch_model.py
@@ -175,6 +175,9 @@ class TorchModel(Model):
       the Weights & Biases logger object used to log data and metrics
     """
     super(TorchModel, self).__init__(model=model, model_dir=model_dir, **kwargs)
+    self.loss = loss  # not used
+    self.learning_rate = learning_rate  # not used
+    self.output_types = output_types  # not used
     if isinstance(loss, Loss):
       self._loss_fn: LossFn = _StandardLoss(self, loss)
     else: