gurudesh/pytracebugs huggingface dataset:
# Buggy code
def get_config(self):
    config = super().get_config()
    config.update(
        {"loss": self.loss, "metrics": self.metrics, "output_shape": self.output_shape}
    )
    return config


# Traceback (TypeError)
Traceback (most recent call last):
File "mnist_model.py", line 12, in <module>
clf = ak.ImageClassifier(metrics=['accuracy', custom_metric], max_trials=3)
File "/home/lhs18285/miniconda3/envs/nas/lib/python3.7/site-packages/autokeras/tasks/image.py", line 67, in __init__
seed=seed)
File "/home/lhs18285/miniconda3/envs/nas/lib/python3.7/site-packages/autokeras/tasks/image.py", line 19, in __init__
**kwargs)
File "/home/lhs18285/miniconda3/envs/nas/lib/python3.7/site-packages/autokeras/auto_model.py", line 125, in __init__
project_name=name)
File "/home/lhs18285/miniconda3/envs/nas/lib/python3.7/site-packages/autokeras/tuners/task_specific.py", line 66, in __init__
**kwargs)
File "/home/lhs18285/miniconda3/envs/nas/lib/python3.7/site-packages/autokeras/tuners/greedy.py", line 197, in __init__
**kwargs)
File "/home/lhs18285/miniconda3/envs/nas/lib/python3.7/site-packages/autokeras/engine/tuner.py", line 35, in __init__
graph_module.serialize(self.hypermodel.hypermodel))
File "/home/lhs18285/miniconda3/envs/nas/lib/python3.7/site-packages/autokeras/utils.py", line 179, in save_json
obj = json.dumps(obj)
File "/home/lhs18285/miniconda3/envs/nas/lib/python3.7/json/__init__.py", line 231, in dumps
return _default_encoder.encode(obj)
File "/home/lhs18285/miniconda3/envs/nas/lib/python3.7/json/encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "/home/lhs18285/miniconda3/envs/nas/lib/python3.7/json/encoder.py", line 257, in iterencode
return _iterencode(o, 0)
File "/home/lhs18285/miniconda3/envs/nas/lib/python3.7/json/encoder.py", line 179, in default
raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type function is not JSON serializable

# Fixed code
def get_config(self):
    config = super().get_config()
    config.update(
        {
            "loss": tf.keras.losses.serialize(self.loss),
            "metrics": [tf.keras.metrics.serialize(metric) for metric in self.metrics],
            "output_shape": self.output_shape,
        }
    )
    return config
# Buggy code
def __init__(self, preprocessors=None, **kwargs):
    super().__init__(**kwargs)
    self.preprocessors = nest.flatten(preprocessors)
    self._finished = False
    # Save or load the HyperModel.
    utils.save_json(
        os.path.join(self.project_dir, "graph"),
        graph_module.serialize(self.hypermodel.hypermodel),
    )


# Traceback (TypeError)
Traceback (most recent call last):
File "mnist_model.py", line 12, in <module>
clf = ak.ImageClassifier(metrics=['accuracy', custom_metric], max_trials=3)
File "/home/lhs18285/miniconda3/envs/nas/lib/python3.7/site-packages/autokeras/tasks/image.py", line 67, in __init__
seed=seed)
File "/home/lhs18285/miniconda3/envs/nas/lib/python3.7/site-packages/autokeras/tasks/image.py", line 19, in __init__
**kwargs)
File "/home/lhs18285/miniconda3/envs/nas/lib/python3.7/site-packages/autokeras/auto_model.py", line 125, in __init__
project_name=name)
File "/home/lhs18285/miniconda3/envs/nas/lib/python3.7/site-packages/autokeras/tuners/task_specific.py", line 66, in __init__
**kwargs)
File "/home/lhs18285/miniconda3/envs/nas/lib/python3.7/site-packages/autokeras/tuners/greedy.py", line 197, in __init__
**kwargs)
File "/home/lhs18285/miniconda3/envs/nas/lib/python3.7/site-packages/autokeras/engine/tuner.py", line 35, in __init__
graph_module.serialize(self.hypermodel.hypermodel))
File "/home/lhs18285/miniconda3/envs/nas/lib/python3.7/site-packages/autokeras/utils.py", line 179, in save_json
obj = json.dumps(obj)
File "/home/lhs18285/miniconda3/envs/nas/lib/python3.7/json/__init__.py", line 231, in dumps
return _default_encoder.encode(obj)
File "/home/lhs18285/miniconda3/envs/nas/lib/python3.7/json/encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "/home/lhs18285/miniconda3/envs/nas/lib/python3.7/json/encoder.py", line 257, in iterencode
return _iterencode(o, 0)
File "/home/lhs18285/miniconda3/envs/nas/lib/python3.7/json/encoder.py", line 179, in default
raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type function is not JSON serializable

# Fixed code
def __init__(self, preprocessors=None, **kwargs):
    super().__init__(**kwargs)
    self.preprocessors = nest.flatten(preprocessors)
    self._finished = False
    # Save or load the HyperModel.
    self.hypermodel.hypermodel.save(os.path.join(self.project_dir, "graph"))
# Buggy code
def feature_encoding_input(block):
    """Fetch the column_types and column_names.

    The values are fetched for FeatureEncoding from StructuredDataInput.
    """
    if not isinstance(block.inputs[0], nodes.StructuredDataInput):
        raise TypeError(
            "FeatureEncoding block can only be used with StructuredDataInput."
        )
    block.column_types = block.inputs[0].column_types
    block.column_names = block.inputs[0].column_names


# Traceback (TypeError)
Traceback (most recent call last):
File "mnist_model.py", line 12, in <module>
clf = ak.ImageClassifier(metrics=['accuracy', custom_metric], max_trials=3)
File "/home/lhs18285/miniconda3/envs/nas/lib/python3.7/site-packages/autokeras/tasks/image.py", line 67, in __init__
seed=seed)
File "/home/lhs18285/miniconda3/envs/nas/lib/python3.7/site-packages/autokeras/tasks/image.py", line 19, in __init__
**kwargs)
File "/home/lhs18285/miniconda3/envs/nas/lib/python3.7/site-packages/autokeras/auto_model.py", line 125, in __init__
project_name=name)
File "/home/lhs18285/miniconda3/envs/nas/lib/python3.7/site-packages/autokeras/tuners/task_specific.py", line 66, in __init__
**kwargs)
File "/home/lhs18285/miniconda3/envs/nas/lib/python3.7/site-packages/autokeras/tuners/greedy.py", line 197, in __init__
**kwargs)
File "/home/lhs18285/miniconda3/envs/nas/lib/python3.7/site-packages/autokeras/engine/tuner.py", line 35, in __init__
graph_module.serialize(self.hypermodel.hypermodel))
File "/home/lhs18285/miniconda3/envs/nas/lib/python3.7/site-packages/autokeras/utils.py", line 179, in save_json
obj = json.dumps(obj)
File "/home/lhs18285/miniconda3/envs/nas/lib/python3.7/json/__init__.py", line 231, in dumps
return _default_encoder.encode(obj)
File "/home/lhs18285/miniconda3/envs/nas/lib/python3.7/json/encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "/home/lhs18285/miniconda3/envs/nas/lib/python3.7/json/encoder.py", line 257, in iterencode
return _iterencode(o, 0)
File "/home/lhs18285/miniconda3/envs/nas/lib/python3.7/json/encoder.py", line 179, in default
raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type function is not JSON serializable

# Fixed code
def feature_encoding_input(block):
    """Fetch the column_types and column_names.

    The values are fetched for FeatureEncoding from StructuredDataInput.
    """
    if not isinstance(block.inputs[0], nodes_module.StructuredDataInput):
        raise TypeError(
            "FeatureEncoding block can only be used with StructuredDataInput."
        )
    block.column_types = block.inputs[0].column_types
    block.column_names = block.inputs[0].column_names
# Buggy code
def __init__(
    self,
    num_classes: Optional[int] = None,
    multi_label: bool = False,
    loss: Optional[types.LossType] = None,
    metrics: Optional[types.MetricsType] = None,
    dropout_rate: Optional[float] = None,
    **kwargs,
):
    super().__init__(loss=loss, metrics=metrics, **kwargs)
    self.num_classes = num_classes
    self.multi_label = multi_label
    if not self.metrics:
        self.metrics = ["accuracy"]
    self.dropout_rate = dropout_rate
    self.set_loss()


# Traceback (TypeError)
Traceback (most recent call last):
File "mnist_model.py", line 12, in <module>
clf = ak.ImageClassifier(metrics=['accuracy', custom_metric], max_trials=3)
File "/home/lhs18285/miniconda3/envs/nas/lib/python3.7/site-packages/autokeras/tasks/image.py", line 67, in __init__
seed=seed)
File "/home/lhs18285/miniconda3/envs/nas/lib/python3.7/site-packages/autokeras/tasks/image.py", line 19, in __init__
**kwargs)
File "/home/lhs18285/miniconda3/envs/nas/lib/python3.7/site-packages/autokeras/auto_model.py", line 125, in __init__
project_name=name)
File "/home/lhs18285/miniconda3/envs/nas/lib/python3.7/site-packages/autokeras/tuners/task_specific.py", line 66, in __init__
**kwargs)
File "/home/lhs18285/miniconda3/envs/nas/lib/python3.7/site-packages/autokeras/tuners/greedy.py", line 197, in __init__
**kwargs)
File "/home/lhs18285/miniconda3/envs/nas/lib/python3.7/site-packages/autokeras/engine/tuner.py", line 35, in __init__
graph_module.serialize(self.hypermodel.hypermodel))
File "/home/lhs18285/miniconda3/envs/nas/lib/python3.7/site-packages/autokeras/utils.py", line 179, in save_json
obj = json.dumps(obj)
File "/home/lhs18285/miniconda3/envs/nas/lib/python3.7/json/__init__.py", line 231, in dumps
return _default_encoder.encode(obj)
File "/home/lhs18285/miniconda3/envs/nas/lib/python3.7/json/encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "/home/lhs18285/miniconda3/envs/nas/lib/python3.7/json/encoder.py", line 257, in iterencode
return _iterencode(o, 0)
File "/home/lhs18285/miniconda3/envs/nas/lib/python3.7/json/encoder.py", line 179, in default
raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type function is not JSON serializable

# Fixed code
def __init__(
    self,
    num_classes: Optional[int] = None,
    multi_label: bool = False,
    loss: Optional[types.LossType] = None,
    metrics: Optional[types.MetricsType] = None,
    dropout_rate: Optional[float] = None,
    **kwargs,
):
    self.num_classes = num_classes
    self.multi_label = multi_label
    self.dropout_rate = dropout_rate
    if metrics is None:
        metrics = ["accuracy"]
    if loss is None:
        loss = self.infer_loss()
    super().__init__(loss=loss, metrics=metrics, **kwargs)
# Buggy code
def config_from_adapter(self, adapter):
    super().config_from_adapter(adapter)
    self.num_classes = adapter.num_classes
    self.set_loss()


# Traceback (TypeError)
Traceback (most recent call last):
File "mnist_model.py", line 12, in <module>
clf = ak.ImageClassifier(metrics=['accuracy', custom_metric], max_trials=3)
File "/home/lhs18285/miniconda3/envs/nas/lib/python3.7/site-packages/autokeras/tasks/image.py", line 67, in __init__
seed=seed)
File "/home/lhs18285/miniconda3/envs/nas/lib/python3.7/site-packages/autokeras/tasks/image.py", line 19, in __init__
**kwargs)
File "/home/lhs18285/miniconda3/envs/nas/lib/python3.7/site-packages/autokeras/auto_model.py", line 125, in __init__
project_name=name)
File "/home/lhs18285/miniconda3/envs/nas/lib/python3.7/site-packages/autokeras/tuners/task_specific.py", line 66, in __init__
**kwargs)
File "/home/lhs18285/miniconda3/envs/nas/lib/python3.7/site-packages/autokeras/tuners/greedy.py", line 197, in __init__
**kwargs)
File "/home/lhs18285/miniconda3/envs/nas/lib/python3.7/site-packages/autokeras/engine/tuner.py", line 35, in __init__
graph_module.serialize(self.hypermodel.hypermodel))
File "/home/lhs18285/miniconda3/envs/nas/lib/python3.7/site-packages/autokeras/utils.py", line 179, in save_json
obj = json.dumps(obj)
File "/home/lhs18285/miniconda3/envs/nas/lib/python3.7/json/__init__.py", line 231, in dumps
return _default_encoder.encode(obj)
File "/home/lhs18285/miniconda3/envs/nas/lib/python3.7/json/encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "/home/lhs18285/miniconda3/envs/nas/lib/python3.7/json/encoder.py", line 257, in iterencode
return _iterencode(o, 0)
File "/home/lhs18285/miniconda3/envs/nas/lib/python3.7/json/encoder.py", line 179, in default
raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type function is not JSON serializable

# Fixed code
def config_from_adapter(self, adapter):
    super().config_from_adapter(adapter)
    self.num_classes = adapter.num_classes
    self.loss = self.infer_loss()
# Buggy code
def __init__(
    self,
    output_dim: Optional[int] = None,
    loss: types.LossType = "mean_squared_error",
    metrics: Optional[types.MetricsType] = None,
    dropout_rate: Optional[float] = None,
    **kwargs,
):
    super().__init__(loss=loss, metrics=metrics, **kwargs)
    self.output_dim = output_dim
    if not self.metrics:
        self.metrics = ["mean_squared_error"]
    self.loss = loss
    self.dropout_rate = dropout_rate


# Traceback (TypeError)
Traceback (most recent call last):
File "mnist_model.py", line 12, in <module>
clf = ak.ImageClassifier(metrics=['accuracy', custom_metric], max_trials=3)
File "/home/lhs18285/miniconda3/envs/nas/lib/python3.7/site-packages/autokeras/tasks/image.py", line 67, in __init__
seed=seed)
File "/home/lhs18285/miniconda3/envs/nas/lib/python3.7/site-packages/autokeras/tasks/image.py", line 19, in __init__
**kwargs)
File "/home/lhs18285/miniconda3/envs/nas/lib/python3.7/site-packages/autokeras/auto_model.py", line 125, in __init__
project_name=name)
File "/home/lhs18285/miniconda3/envs/nas/lib/python3.7/site-packages/autokeras/tuners/task_specific.py", line 66, in __init__
**kwargs)
File "/home/lhs18285/miniconda3/envs/nas/lib/python3.7/site-packages/autokeras/tuners/greedy.py", line 197, in __init__
**kwargs)
File "/home/lhs18285/miniconda3/envs/nas/lib/python3.7/site-packages/autokeras/engine/tuner.py", line 35, in __init__
graph_module.serialize(self.hypermodel.hypermodel))
File "/home/lhs18285/miniconda3/envs/nas/lib/python3.7/site-packages/autokeras/utils.py", line 179, in save_json
obj = json.dumps(obj)
File "/home/lhs18285/miniconda3/envs/nas/lib/python3.7/json/__init__.py", line 231, in dumps
return _default_encoder.encode(obj)
File "/home/lhs18285/miniconda3/envs/nas/lib/python3.7/json/encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "/home/lhs18285/miniconda3/envs/nas/lib/python3.7/json/encoder.py", line 257, in iterencode
return _iterencode(o, 0)
File "/home/lhs18285/miniconda3/envs/nas/lib/python3.7/json/encoder.py", line 179, in default
raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type function is not JSON serializable

# Fixed code
def __init__(
    self,
    output_dim: Optional[int] = None,
    loss: types.LossType = "mean_squared_error",
    metrics: Optional[types.MetricsType] = None,
    dropout_rate: Optional[float] = None,
    **kwargs,
):
    if metrics is None:
        metrics = ["mean_squared_error"]
    super().__init__(loss=loss, metrics=metrics, **kwargs)
    self.output_dim = output_dim
    self.dropout_rate = dropout_rate
# Buggy code
def __init__(self, data):
    super().__init__()
    self.max_val = data.max()
    data = data / self.max_val
    self.mean = np.mean(data, axis=0, keepdims=True).flatten()
    self.std = np.std(data, axis=0, keepdims=True).flatten()


# Traceback (TypeError)
Using TensorFlow backend.
Saving Directory: /tmp/autokeras_ASE3DJ

Initializing search.
Initialization finished.


+----------------------------------------------+
|               Training model 0               |
+----------------------------------------------+
Using TensorFlow backend.
Epoch-1, Current Metric - 0:   0%|                                      | 0/469 [00:00<?, ? batch/s]Process SpawnProcess-1:
Traceback (most recent call last):
File "/home/boyuan/anaconda3/lib/python3.6/multiprocessing/process.py", line 258, in _bootstrap
self.run()
File "/home/boyuan/anaconda3/lib/python3.6/multiprocessing/process.py", line 93, in run
self._target(*self._args, **self._kwargs)
File "/home/boyuan/workspace/lab/autokeras/autokeras/search.py", line 276, in train
verbose=verbose).train_model(**trainer_args)
File "/home/boyuan/workspace/lab/autokeras/autokeras/nn/model_trainer.py", line 126, in train_model
self._train()
File "/home/boyuan/workspace/lab/autokeras/autokeras/nn/model_trainer.py", line 157, in _train
for batch_idx, (inputs, targets) in enumerate(deepcopy(loader)):
File "/home/boyuan/anaconda3/lib/python3.6/site-packages/torch/utils/data/dataloader.py", line 314, in __next__
batch = self.collate_fn([self.dataset[i] for i in indices])
File "/home/boyuan/anaconda3/lib/python3.6/site-packages/torch/utils/data/dataloader.py", line 314, in <listcomp>
batch = self.collate_fn([self.dataset[i] for i in indices])
File "/home/boyuan/workspace/lab/autokeras/autokeras/preprocessor.py", line 302, in __getitem__
return self.compose(feature), self.target[index]
File "/home/boyuan/anaconda3/lib/python3.6/site-packages/torchvision/transforms/transforms.py", line 49, in __call__
img = t(img)
File "/home/boyuan/anaconda3/lib/python3.6/site-packages/torchvision/transforms/transforms.py", line 143, in __call__
return F.normalize(tensor, self.mean, self.std)
File "/home/boyuan/anaconda3/lib/python3.6/site-packages/torchvision/transforms/functional.py", line 165, in normalize
raise TypeError('tensor is not a torch image.')
TypeError: tensor is not a torch image.

# Fixed code
def __init__(self, data):
    super().__init__()
    self.mean = np.mean(data, axis=0)
    self.std = np.std(data, axis=0)
# Buggy code
def transform_train(self, data, targets=None, batch_size=None):
    dataset = self._transform(
        [Normalize(torch.Tensor(self.mean), torch.Tensor(self.std))], data, targets
    )

    if batch_size is None:
        batch_size = Constant.MAX_BATCH_SIZE
    batch_size = min(len(data), batch_size)

    return DataLoader(dataset, batch_size=batch_size, shuffle=True)


# Traceback (TypeError)
Using TensorFlow backend.
Saving Directory: /tmp/autokeras_ASE3DJ

Initializing search.
Initialization finished.


+----------------------------------------------+
|               Training model 0               |
+----------------------------------------------+
Using TensorFlow backend.
Epoch-1, Current Metric - 0:   0%|                                      | 0/469 [00:00<?, ? batch/s]Process SpawnProcess-1:
Traceback (most recent call last):
File "/home/boyuan/anaconda3/lib/python3.6/multiprocessing/process.py", line 258, in _bootstrap
self.run()
File "/home/boyuan/anaconda3/lib/python3.6/multiprocessing/process.py", line 93, in run
self._target(*self._args, **self._kwargs)
File "/home/boyuan/workspace/lab/autokeras/autokeras/search.py", line 276, in train
verbose=verbose).train_model(**trainer_args)
File "/home/boyuan/workspace/lab/autokeras/autokeras/nn/model_trainer.py", line 126, in train_model
self._train()
File "/home/boyuan/workspace/lab/autokeras/autokeras/nn/model_trainer.py", line 157, in _train
for batch_idx, (inputs, targets) in enumerate(deepcopy(loader)):
File "/home/boyuan/anaconda3/lib/python3.6/site-packages/torch/utils/data/dataloader.py", line 314, in __next__
batch = self.collate_fn([self.dataset[i] for i in indices])
File "/home/boyuan/anaconda3/lib/python3.6/site-packages/torch/utils/data/dataloader.py", line 314, in <listcomp>
batch = self.collate_fn([self.dataset[i] for i in indices])
File "/home/boyuan/workspace/lab/autokeras/autokeras/preprocessor.py", line 302, in __getitem__
return self.compose(feature), self.target[index]
File "/home/boyuan/anaconda3/lib/python3.6/site-packages/torchvision/transforms/transforms.py", line 49, in __call__
img = t(img)
File "/home/boyuan/anaconda3/lib/python3.6/site-packages/torchvision/transforms/transforms.py", line 143, in __call__
return F.normalize(tensor, self.mean, self.std)
File "/home/boyuan/anaconda3/lib/python3.6/site-packages/torchvision/transforms/functional.py", line 165, in normalize
raise TypeError('tensor is not a torch image.')
TypeError: tensor is not a torch image.

# Fixed code
def transform_train(self, data, targets=None, batch_size=None):
    data = (data - self.mean) / self.std
    data = np.nan_to_num(data)
    dataset = self._transform([], data, targets)

    if batch_size is None:
        batch_size = Constant.MAX_BATCH_SIZE
    batch_size = min(len(data), batch_size)

    return DataLoader(dataset, batch_size=batch_size, shuffle=True)
# Buggy code
def _transform(self, compose_list, data, targets):
    data = data / self.max_val
    args = [0, len(data.shape) - 1] + list(range(1, len(data.shape) - 1))
    data = torch.Tensor(data.transpose(*args))
    data_transforms = Compose(compose_list)
    return MultiTransformDataset(data, targets, data_transforms)


# Traceback (TypeError)
Using TensorFlow backend.
Saving Directory: /tmp/autokeras_ASE3DJ

Initializing search.
Initialization finished.


+----------------------------------------------+
|               Training model 0               |
+----------------------------------------------+
Using TensorFlow backend.
Epoch-1, Current Metric - 0:   0%|                                      | 0/469 [00:00<?, ? batch/s]Process SpawnProcess-1:
Traceback (most recent call last):
File "/home/boyuan/anaconda3/lib/python3.6/multiprocessing/process.py", line 258, in _bootstrap
self.run()
File "/home/boyuan/anaconda3/lib/python3.6/multiprocessing/process.py", line 93, in run
self._target(*self._args, **self._kwargs)
File "/home/boyuan/workspace/lab/autokeras/autokeras/search.py", line 276, in train
verbose=verbose).train_model(**trainer_args)
File "/home/boyuan/workspace/lab/autokeras/autokeras/nn/model_trainer.py", line 126, in train_model
self._train()
File "/home/boyuan/workspace/lab/autokeras/autokeras/nn/model_trainer.py", line 157, in _train
for batch_idx, (inputs, targets) in enumerate(deepcopy(loader)):
File "/home/boyuan/anaconda3/lib/python3.6/site-packages/torch/utils/data/dataloader.py", line 314, in __next__
batch = self.collate_fn([self.dataset[i] for i in indices])
File "/home/boyuan/anaconda3/lib/python3.6/site-packages/torch/utils/data/dataloader.py", line 314, in <listcomp>
batch = self.collate_fn([self.dataset[i] for i in indices])
File "/home/boyuan/workspace/lab/autokeras/autokeras/preprocessor.py", line 302, in __getitem__
return self.compose(feature), self.target[index]
File "/home/boyuan/anaconda3/lib/python3.6/site-packages/torchvision/transforms/transforms.py", line 49, in __call__
img = t(img)
File "/home/boyuan/anaconda3/lib/python3.6/site-packages/torchvision/transforms/transforms.py", line 143, in __call__
return F.normalize(tensor, self.mean, self.std)
File "/home/boyuan/anaconda3/lib/python3.6/site-packages/torchvision/transforms/functional.py", line 165, in normalize
raise TypeError('tensor is not a torch image.')
TypeError: tensor is not a torch image.

# Fixed code
def _transform(self, compose_list, data, targets):
    args = [0, len(data.shape) - 1] + list(range(1, len(data.shape) - 1))
    data = torch.Tensor(data.transpose(*args))
    data_transforms = Compose(compose_list)
    return MultiTransformDataset(data, targets, data_transforms)
# Buggy code
def read_image(img_path):
    img = ndimage.imread(fname=img_path)
    return img


# Traceback (ValueError)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
~/Software/anaconda3/lib/python3.6/site-packages/autokeras/image_supervised.py in _validate(x_train, y_train)
24     try:
---> 25         x_train = x_train.astype('float64')
26     except ValueError:

ValueError: setting an array element with a sequence.

During handling of the above exception, another exception occurred:

[OUTPUT TRUNCATED]

# Fixed code
def read_image(img_path):
    img = imageio.imread(uri=img_path)
    return img
# Buggy code
def get_device():
    """If Cuda is available, use Cuda device, else use CPU device
        When choosing from Cuda devices, this function will choose the one with max memory available

    Returns: string device name

    """
    # TODO: could use gputil in the future
    if torch.cuda.is_available():
        smi_out = os.popen("nvidia-smi -q -d Memory | grep -A4 GPU|grep Free").read()
        # smi_out=
        #       Free                 : xxxxxx MiB
        #       Free                 : xxxxxx MiB
        #                      ....
        memory_available = [int(x.split()[2]) for x in smi_out.splitlines()]
        if not memory_available:
            device = "cpu"
        else:
            device = "cuda:" + str(memory_available.index(max(memory_available)))
    else:
        device = "cpu"
    return device


# Traceback (RuntimeError)
Traceback (most recent call last):
File "/home/hoanghiep/miniconda3/lib/python3.6/multiprocessing/pool.py", line 119, in worker
result = (True, func(*args, **kwds))
File "/home/hoanghiep/miniconda3/lib/python3.6/multiprocessing/pool.py", line 44, in mapstar
return list(map(*args))
File "/home/hoanghiep/miniconda3/lib/python3.6/site-packages/autokeras/search.py", line 296, in train
verbose=verbose).train_model(**trainer_args)
File "/home/hoanghiep/miniconda3/lib/python3.6/site-packages/autokeras/model_trainer.py", line 64, in __init__
self.model.to(self.device)
File "/home/hoanghiep/miniconda3/lib/python3.6/site-packages/torch/nn/modules/module.py", line 379, in to
return self._apply(convert)
File "/home/hoanghiep/miniconda3/lib/python3.6/site-packages/torch/nn/modules/module.py", line 185, in _apply
module._apply(fn)
File "/home/hoanghiep/miniconda3/lib/python3.6/site-packages/torch/nn/modules/module.py", line 191, in _apply
param.data = fn(param.data)
File "/home/hoanghiep/miniconda3/lib/python3.6/site-packages/torch/nn/modules/module.py", line 377, in convert
return t.to(device, dtype if t.is_floating_point() else None, non_blocking)
RuntimeError: CUDA error (10): invalid device ordina

# Fixed code
def get_device():
    """If Cuda is available, use Cuda device, else use CPU device
        When choosing from Cuda devices, this function will choose the one with max memory available

    Returns: string device name

    """
    # TODO: could use gputil in the future
    device = "cpu"
    if torch.cuda.is_available():
        smi_out = os.popen("nvidia-smi -q -d Memory | grep -A4 GPU|grep Free").read()
        # smi_out=
        #       Free                 : xxxxxx MiB
        #       Free                 : xxxxxx MiB
        #                      ....
        visable_list = [
            int(x) for x in os.getenv("CUDA_VISIBLE_DEVICES", "").split(",")
        ]
        memory_available = [int(x.split()[2]) for x in smi_out.splitlines()]
        for cuda_index, _ in enumerate(memory_available):
            if cuda_index not in visable_list and visable_list:
                memory_available[cuda_index] = 0

        if memory_available:
            if max(memory_available) != 0:
                device = "cuda:" + str(memory_available.index(max(memory_available)))
    return device
# Buggy code
def _dense_block_end_node(self, layer_id):
    return self._block_end_node(layer_id, Constant.DENSE_BLOCK_DISTANCE)


# Traceback (RuntimeError)
.....
Epoch 14: loss 0.9113655090332031, metric_value 0.9318181818181818
No loss decrease after 3 epochs
Father ID:  2
[('to_dense_deeper_model', 14), ('to_conv_deeper_model', 1, 5), ('to_add_skip_model', 20, 5), ('to_concat_skip_model', 1, 5), ('to_add_skip_model', 1, 20), ('to_wider_model', 5, 64), ('to_concat_skip_model', 20, 5), ('to_conv_deeper_model', 20, 5), ('to_dense_deeper_model', 18), ('to_concat_skip_model', 1, 20)]
Saving model.
Model ID: 7
Loss: tensor(0.9246, device='cuda:0')
Metric Value: 0.92739898989899
Training model  8
Traceback (most recent call last):
File "ak_my.py", line 15, in <module>
clf.fit(x_train, y_train, time_limit=12 * 60 * 60)
File "C:\Users\kmbmjn\Anaconda3\lib\site-packages\autokeras\image_supervised.py", line 238, in fit
run_searcher_once(train_data, test_data, self.path, int(time_remain))
File "C:\Users\kmbmjn\Anaconda3\lib\site-packages\autokeras\image_supervised.py", line 41, in run_searcher_once
searcher.search(train_data, test_data, timeout)
File "C:\Users\kmbmjn\Anaconda3\lib\site-packages\autokeras\search.py", line 173, in search
self.metric, self.loss, self.verbose)]))
File "C:\Users\kmbmjn\Anaconda3\lib\site-packages\autokeras\search.py", line 269, in train
verbose).train_model(**trainer_args)
File "C:\Users\kmbmjn\Anaconda3\lib\site-packages\autokeras\utils.py", line 101, in train_model
self._train()
File "C:\Users\kmbmjn\Anaconda3\lib\site-packages\autokeras\utils.py", line 122, in _train
outputs = self.model(inputs)
File "C:\Users\kmbmjn\Anaconda3\lib\site-packages\torch\nn\modules\module.py", line 477, in __call__
result = self.forward(*input, **kwargs)
File "C:\Users\kmbmjn\Anaconda3\lib\site-packages\autokeras\graph.py", line 607, in forward
temp_tensor = torch_layer(edge_input_tensor)
File "C:\Users\kmbmjn\Anaconda3\lib\site-packages\torch\nn\modules\module.py", line 477, in __call__
result = self.forward(*input, **kwargs)
File "C:\Users\kmbmjn\Anaconda3\lib\site-packages\torch\nn\modules\linear.py", line 55, in forward
return F.linear(input, self.weight, self.bias)
File "C:\Users\kmbmjn\Anaconda3\lib\site-packages\torch\nn\functional.py", line 1024, in linear
return torch.addmm(bias, input, weight.t())
RuntimeError: size mismatch, m1: [128 x 2], m2: [64 x 64] at c:\programdata\miniconda3\conda-bld\pytorch_1533090623466\work\aten\src\thc\generic/THCTensorMathBlas.cu:249

# Fixed code
def _dense_block_end_node(self, layer_id):
    return self.layer_id_to_input_node_ids[layer_id][0]
# Buggy code
def stats(self):
    """
    Returns
        dict?: resource stats
    """
    stats = {"hash": "", "bytes": 0, "fields": 0, "rows": 0}
    return self.metadata_attach("stats", self.get("stats", stats))


# Traceback (frictionless.exception.FrictionlessException)
Traceback (most recent call last):
File "C:\Users\user\programs\PyCharm\PyCharm Community Edition 2020.3.2\plugins\python-ce\helpers\pydev\_pydevd_bundle\pydevd_exec2.py", line 3, in Exec
exec(exp, global_vars, local_vars)
File "<input>", line 1, in <module>
File "C:\Users\user\programs\miniconda\envs\WPP2\lib\site-packages\frictionless\describe\main.py", line 46, in describe
return describe(source, **options)
File "C:\Users\user\programs\miniconda\envs\WPP2\lib\site-packages\frictionless\describe\resource.py", line 129, in describe_resource
with table as table:
File "C:\Users\user\programs\miniconda\envs\WPP2\lib\site-packages\frictionless\table.py", line 217, in __enter__
self.open()
File "C:\Users\user\programs\miniconda\envs\WPP2\lib\site-packages\frictionless\table.py", line 400, in open
self.__parser = system.create_parser(self.__resource)
File "C:\Users\user\programs\miniconda\envs\WPP2\lib\site-packages\frictionless\system.py", line 161, in create_parser
raise FrictionlessException(errors.FormatError(note=note))
frictionless.exception.FrictionlessException: [format-error] The data source could not be successfully parsed: cannot create parser "pdf". Try installing "frictionless-pdf"

# Fixed code
def stats(self):
    """
    Returns
        dict?: resource stats
    """
    stats = self.get("stats")
    if stats is None:
        stats = {"hash": "", "bytes": 0}
        if self.tabular:
            stats.update({"fields": 0, "rows": 0})
        stats = self.metadata_attach("stats", stats)
    return stats
# Buggy code
def missing_header(cells, sample):
    errors = []

    for cell in copy(cells):
        # Skip if header in cell
        if cell.get("header") is not None:
            continue

        # Add error
        message_substitutions = {
            "field_name": '"{}"'.format(cell["field"].name),
        }
        error = Error(
            "missing-header", cell, message_substitutions=message_substitutions
        )
        errors.append(error)

        # Remove cell
        cells.remove(cell)

    return errors


# Traceback (AttributeError)
Traceback (most recent call last):
File "bug.py", line 67, in <module>
report = validate(DESCRIPTOR, skip_checks=['extra-header'], order_fields=True, infer_fields=False)
File "/home/didiez/bug_goodtables/env/lib/python3.7/site-packages/goodtables/validate.py", line 80, in validate
report = inspector.inspect(source, **options)
File "/home/didiez/bug_goodtables/env/lib/python3.7/site-packages/goodtables/inspector.py", line 82, in inspect
table_warnings, table_report = task.get()
File "/home/didiez/anaconda3/lib/python3.7/multiprocessing/pool.py", line 657, in get
raise self._value
File "/home/didiez/anaconda3/lib/python3.7/multiprocessing/pool.py", line 121, in worker
result = (True, func(*args, **kwds))
File "/home/didiez/bug_goodtables/env/lib/python3.7/site-packages/goodtables/inspector.py", line 222, in __inspect_table
errors += (check_func(header_cells, sample) or [])
File "/home/didiez/bug_goodtables/env/lib/python3.7/site-packages/goodtables/checks/missing_header.py", line 26, in missing_header
'field_name': '"{}"'.format(cell['field'].name),
AttributeError: 'NoneType' object has no attribute 'name'

# Fixed code
def missing_header(cells, sample):
    errors = []

    for cell in copy(cells):
        # Skip if header in cell
        if cell.get("header") is not None:
            continue

        # Add error
        field_name = cell["field"].name if cell["field"] else ""
        message_substitutions = {"field_name": '"{}"'.format(field_name)}
        message = "There is a missing header in column {column_number}"
        # It's a temporary solution for
        # https://github.com/frictionlessdata/goodtables-py/issues/338
        if not cell.get("column-number"):
            message = "There is a missing header in column {field_name}"
        error = Error(
            "missing-header",
            cell,
            message=message,
            message_substitutions=message_substitutions,
        )
        errors.append(error)

        # Remove cell
        cells.remove(cell)

    return errors
# Buggy code
def parse(code):
    class_names, code = pre_parse(code)
    o = ast.parse(code)  # python ast
    decorate_ast(o, code, class_names)  # decorated python ast
    o = resolve_negative_literals(o)
    return o.body


# Traceback (ValueError)
Traceback (most recent call last):
File "/Users/mate/github/vyper/vyper-venv/bin/vyper", line 4, in <module>
__import__('pkg_resources').run_script('vyper==0.1.0b6', 'vyper')
File "/Users/mate/github/vyper/vyper-venv/lib/python3.6/site-packages/pkg_resources/__init__.py", line 664, in run_script
self.require(requires)[0].run_script(script_name, ns)
File "/Users/mate/github/vyper/vyper-venv/lib/python3.6/site-packages/pkg_resources/__init__.py", line 1451, in run_script
exec(script_code, namespace, namespace)
File "/Users/mate/github/vyper/vyper-venv/lib/python3.6/site-packages/vyper-0.1.0b6-py3.6.egg/EGG-INFO/scripts/vyper", line 85, in <module>
File "/Users/mate/github/vyper/vyper-venv/lib/python3.6/site-packages/vyper-0.1.0b6-py3.6.egg/vyper/compiler.py", line 108, in compile_codes
File "/Users/mate/github/vyper/vyper-venv/lib/python3.6/site-packages/vyper-0.1.0b6-py3.6.egg/EGG-INFO/scripts/vyper", line 51, in exc_handler
File "/Users/mate/github/vyper/vyper-venv/lib/python3.6/site-packages/vyper-0.1.0b6-py3.6.egg/vyper/compiler.py", line 105, in compile_codes
File "/Users/mate/github/vyper/vyper-venv/lib/python3.6/site-packages/vyper-0.1.0b6-py3.6.egg/vyper/compiler.py", line 87, in <lambda>
File "/Users/mate/github/vyper/vyper-venv/lib/python3.6/site-packages/vyper-0.1.0b6-py3.6.egg/vyper/compiler.py", line 8, in __compile
File "/Users/mate/github/vyper/vyper-venv/lib/python3.6/site-packages/vyper-0.1.0b6-py3.6.egg/vyper/parser/parser.py", line 63, in parse
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/ast.py", line 35, in parse
return compile(source, filename, mode, PyCF_ONLY_AST)
ValueError: source code string cannot contain null bytes

# Fixed code
def parse(code):
    class_names, code = pre_parse(code)
    if "\x00" in code:
        raise ParserException("No null bytes (\\x00) allowed in the source code.")
    o = ast.parse(code)  # python ast
    decorate_ast(o, code, class_names)  # decorated python ast
    o = resolve_negative_literals(o)
    return o.body
# Buggy code
def parse_body(code, context):
    if not isinstance(code, list):
        return parse_stmt(code, context)
    o = []
    for stmt in code:
        o.append(parse_stmt(stmt, context))
    return LLLnode.from_list(["seq"] + o, pos=getpos(code[0]) if code else None)


# Traceback (vyper.exceptions.StructureException)
Traceback (most recent call last):
File "vyper-bin", line 56, in <module>
print(optimizer.optimize(parse_to_lll(code)))
File "/home/jacques/projects/vyper/vyper/parser/parser.py", line 991, in parse_to_lll
return parse_tree_to_lll(code, kode)
File "/home/jacques/projects/vyper/vyper/parser/parser.py", line 464, in parse_tree_to_lll
o, otherfuncs, _globals, sigs, external_contracts, origcode, _custom_units, defaultfunc, runtime_only
File "/home/jacques/projects/vyper/vyper/parser/parser.py", line 417, in parse_other_functions
sub.append(parse_func(_def, _globals, {**{'self': sigs}, **external_contracts}, origcode, _custom_units))  # noqa E999
File "/home/jacques/projects/vyper/vyper/parser/parser.py", line 554, in parse_func
['seq'] + clampers + [parse_body(c, context) for c in code.body] + ['stop']
File "/home/jacques/projects/vyper/vyper/parser/parser.py", line 554, in <listcomp>
['seq'] + clampers + [parse_body(c, context) for c in code.body] + ['stop']
File "/home/jacques/projects/vyper/vyper/parser/parser.py", line 572, in parse_body
return parse_stmt(code, context)
File "/home/jacques/projects/vyper/vyper/parser/parser.py", line 760, in parse_stmt
return Stmt(stmt, context).lll_node
File "/home/jacques/projects/vyper/vyper/parser/stmt.py", line 68, in __init__
self.lll_node = self.stmt_table[stmt_type]()
File "/home/jacques/projects/vyper/vyper/parser/stmt.py", line 75, in expr
return Stmt(self.stmt.value, self.context).lll_node
File "/home/jacques/projects/vyper/vyper/parser/stmt.py", line 72, in __init__
raise StructureException("Unsupported statement type: %s" % type(stmt), stmt)
vyper.exceptions.StructureException: line 5: Unsupported statement type: <class '_ast.Str'>

# Fixed code
def parse_body(code, context):
    if not isinstance(code, list):
        return parse_stmt(code, context)
    o = []
    for stmt in code:
        lll = parse_stmt(stmt, context)
        o.append(lll)
    return LLLnode.from_list(["seq"] + o, pos=getpos(code[0]) if code else None)
# Buggy code
def translate_exceptions(func):
    @wraps(func)
    async def wrapped(self, *args):
        try:
            return await func(self, *args)
        except asyncpg.SyntaxOrAccessError as exc:
            raise OperationalError(exc)
        except asyncpg.IntegrityConstraintViolationError as exc:
            raise IntegrityError(exc)

    return wrapped


# Traceback (ConnectionResetError)
Traceback (most recent call last):
File \"/usr/lib/python3.6/asyncio/selector_events.py\", line 714, in _read_ready
data = self._sock.recv(self.max_size)
ConnectionResetError: [Errno 104] Connection reset by peer
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File \"/home/shlomy/PycharmProjects/playground/venv36/lib/python3.6/site-packages/tortoise/models.py\", line 277, in create
await instance.save(using_db=kwargs.get('using_db'))
File \"/home/shlomy/PycharmProjects/playground/venv36/lib/python3.6/site-packages/tortoise/models.py\", line 221, in save
await self._insert_instance(*args, **kwargs)
File \"/home/shlomy/PycharmProjects/playground/venv36/lib/python3.6/site-packages/tortoise/models.py\", line 210, in _insert_instance
).execute_insert(self)
File \"/home/shlomy/PycharmProjects/playground/venv36/lib/python3.6/site-packages/tortoise/backends/base/executor.py\", line 77, in execute_insert
instance.id = await self.db.execute_insert(query, values)
File \"/home/shlomy/PycharmProjects/playground/venv36/lib/python3.6/site-packages/tortoise/backends/asyncpg/client.py\", line 22, in wrapped
return await func(self, query, *args)
File \"/home/shlomy/PycharmProjects/playground/venv36/lib/python3.6/site-packages/tortoise/backends/asyncpg/client.py\", line 108, in execute_insert
stmt = await connection.prepare(query)
File \"/home/shlomy/PycharmProjects/playground/venv36/lib/python3.6/site-packages/asyncpg/connection.py\", line 403, in prepare
return await self._prepare(query, timeout=timeout, use_cache=False)
File \"/home/shlomy/PycharmProjects/playground/venv36/lib/python3.6/site-packages/asyncpg/connection.py\", line 408, in _prepare
use_cache=use_cache)
File \"/home/shlomy/PycharmProjects/playground/venv36/lib/python3.6/site-packages/asyncpg/connection.py\", line 329, in _get_statement
statement = await self._protocol.prepare(stmt_name, query, timeout)
File \"asyncpg/protocol/protocol.pyx\", line 163, in prepare
asyncpg.exceptions.ConnectionDoesNotExistError: connection was closed in the middle of operation"}

# Fixed code
def translate_exceptions(func):
    @wraps(func)
    async def translate_exceptions_(self, *args):
        try:
            return await func(self, *args)
        except asyncpg.SyntaxOrAccessError as exc:
            raise OperationalError(exc)
        except asyncpg.IntegrityConstraintViolationError as exc:
            raise IntegrityError(exc)

    return translate_exceptions_
# Buggy code
def _in_transaction(self) -> "TransactionWrapper":
    return self._transaction_class(self.connection_name, self._connection, self._lock)


# Traceback (ConnectionResetError)
Traceback (most recent call last):
File \"/usr/lib/python3.6/asyncio/selector_events.py\", line 714, in _read_ready
data = self._sock.recv(self.max_size)
ConnectionResetError: [Errno 104] Connection reset by peer
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File \"/home/shlomy/PycharmProjects/playground/venv36/lib/python3.6/site-packages/tortoise/models.py\", line 277, in create
await instance.save(using_db=kwargs.get('using_db'))
File \"/home/shlomy/PycharmProjects/playground/venv36/lib/python3.6/site-packages/tortoise/models.py\", line 221, in save
await self._insert_instance(*args, **kwargs)
File \"/home/shlomy/PycharmProjects/playground/venv36/lib/python3.6/site-packages/tortoise/models.py\", line 210, in _insert_instance
).execute_insert(self)
File \"/home/shlomy/PycharmProjects/playground/venv36/lib/python3.6/site-packages/tortoise/backends/base/executor.py\", line 77, in execute_insert
instance.id = await self.db.execute_insert(query, values)
File \"/home/shlomy/PycharmProjects/playground/venv36/lib/python3.6/site-packages/tortoise/backends/asyncpg/client.py\", line 22, in wrapped
return await func(self, query, *args)
File \"/home/shlomy/PycharmProjects/playground/venv36/lib/python3.6/site-packages/tortoise/backends/asyncpg/client.py\", line 108, in execute_insert
stmt = await connection.prepare(query)
File \"/home/shlomy/PycharmProjects/playground/venv36/lib/python3.6/site-packages/asyncpg/connection.py\", line 403, in prepare
return await self._prepare(query, timeout=timeout, use_cache=False)
File \"/home/shlomy/PycharmProjects/playground/venv36/lib/python3.6/site-packages/asyncpg/connection.py\", line 408, in _prepare
use_cache=use_cache)
File \"/home/shlomy/PycharmProjects/playground/venv36/lib/python3.6/site-packages/asyncpg/connection.py\", line 329, in _get_statement
statement = await self._protocol.prepare(stmt_name, query, timeout)
File \"asyncpg/protocol/protocol.pyx\", line 163, in prepare
asyncpg.exceptions.ConnectionDoesNotExistError: connection was closed in the middle of operation"}

# Fixed code
def _in_transaction(self) -> "TransactionWrapper":
    return self._transaction_class(self)
# Buggy code
def __init__(self, connection_name: str, connection, lock) -> None:
    self._connection = connection
    self._lock = lock
    self.log = logging.getLogger("db_client")
    self._transaction_class = self.__class__
    self._old_context_value = None
    self.connection_name = connection_name
    self.transaction = None
    self._finalized = False


# Traceback (ConnectionResetError)
Traceback (most recent call last):
File \"/usr/lib/python3.6/asyncio/selector_events.py\", line 714, in _read_ready
data = self._sock.recv(self.max_size)
ConnectionResetError: [Errno 104] Connection reset by peer
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File \"/home/shlomy/PycharmProjects/playground/venv36/lib/python3.6/site-packages/tortoise/models.py\", line 277, in create
await instance.save(using_db=kwargs.get('using_db'))
File \"/home/shlomy/PycharmProjects/playground/venv36/lib/python3.6/site-packages/tortoise/models.py\", line 221, in save
await self._insert_instance(*args, **kwargs)
File \"/home/shlomy/PycharmProjects/playground/venv36/lib/python3.6/site-packages/tortoise/models.py\", line 210, in _insert_instance
).execute_insert(self)
File \"/home/shlomy/PycharmProjects/playground/venv36/lib/python3.6/site-packages/tortoise/backends/base/executor.py\", line 77, in execute_insert
instance.id = await self.db.execute_insert(query, values)
File \"/home/shlomy/PycharmProjects/playground/venv36/lib/python3.6/site-packages/tortoise/backends/asyncpg/client.py\", line 22, in wrapped
return await func(self, query, *args)
File \"/home/shlomy/PycharmProjects/playground/venv36/lib/python3.6/site-packages/tortoise/backends/asyncpg/client.py\", line 108, in execute_insert
stmt = await connection.prepare(query)
File \"/home/shlomy/PycharmProjects/playground/venv36/lib/python3.6/site-packages/asyncpg/connection.py\", line 403, in prepare
return await self._prepare(query, timeout=timeout, use_cache=False)
File \"/home/shlomy/PycharmProjects/playground/venv36/lib/python3.6/site-packages/asyncpg/connection.py\", line 408, in _prepare
use_cache=use_cache)
File \"/home/shlomy/PycharmProjects/playground/venv36/lib/python3.6/site-packages/asyncpg/connection.py\", line 329, in _get_statement
statement = await self._protocol.prepare(stmt_name, query, timeout)
File \"asyncpg/protocol/protocol.pyx\", line 163, in prepare
asyncpg.exceptions.ConnectionDoesNotExistError: connection was closed in the middle of operation"}

# Fixed code
def __init__(self, connection) -> None:
    self._connection = connection._connection
    self._lock = connection._lock
    self.log = logging.getLogger("db_client")
    self._transaction_class = self.__class__
    self._old_context_value = None
    self.connection_name = connection.connection_name
    self.transaction = None
    self._finalized = False
    self._parent = connection