gurudesh/pytracebugs huggingface dataset:
# Buggy code
def make_connection(self, host):
    self.realhost = host
    h = six.moves.http_client.HTTP(self.proxy)
    return h


# Traceback (TypeError)
Traceback (most recent call last):
File "/ascldap/users/gseastr/envs/python3.6/bin/pyomo", line 11, in <module>
load_entry_point('Pyomo', 'console_scripts', 'pyomo')()
File "/home/gseastr/envs/pyomo/pyomo/scripting/pyomo_main.py", line 82, in main
retval = _options.func(_options)
File "/home/gseastr/envs/pyomo/pyomo/scripting/driver_help.py", line 456, in help_exec
help_solvers()
File "/home/gseastr/envs/pyomo/pyomo/scripting/driver_help.py", line 373, in help_solvers
kestrel = pyomo.neos.kestrel.kestrelAMPL()
File "/home/gseastr/envs/pyomo/pyomo/neos/kestrel.py", line 66, in __init__
self.setup_connection()
File "/home/gseastr/envs/pyomo/pyomo/neos/kestrel.py", line 87, in setup_connection
result = self.neos.ping()
File "/home/gseastr/envs/python3.6/lib/python3.6/xmlrpc/client.py", line 1112, in __call__
return self.__send(self.__name, args)
File "/home/gseastr/envs/python3.6/lib/python3.6/xmlrpc/client.py", line 1452, in __request
verbose=self.__verbose
File "/home/gseastr/envs/python3.6/lib/python3.6/xmlrpc/client.py", line 1154, in request
return self.single_request(host, handler, request_body, verbose)
File "/home/gseastr/envs/python3.6/lib/python3.6/xmlrpc/client.py", line 1166, in single_request
http_conn = self.send_request(host, handler, request_body, verbose)
TypeError: send_request() takes 4 positional arguments but 5 were given

# Fixed code
def make_connection(self, host):
    scheme = urlparse(host).scheme
    if not scheme:
        scheme = NEOS.scheme

    # Empirically, the connection class in Python 3.x needs to
    # match the final endpoint connection scheme, NOT the proxy
    # scheme.  The set_tunnel host then should NOT have a scheme
    # attached to it.
    if scheme == "https":
        connClass = httplib.HTTPSConnection
    else:
        connClass = httplib.HTTPConnection

    connection = connClass(self.proxy.hostname, self.proxy.port)
    connection.set_tunnel(host)
    return connection
# Buggy code
def send_request(self, connection, handler, request_body):
    connection.putrequest("POST", "%s://%s%s" % (urlscheme, self.realhost, handler))


# Traceback (TypeError)
Traceback (most recent call last):
File "/ascldap/users/gseastr/envs/python3.6/bin/pyomo", line 11, in <module>
load_entry_point('Pyomo', 'console_scripts', 'pyomo')()
File "/home/gseastr/envs/pyomo/pyomo/scripting/pyomo_main.py", line 82, in main
retval = _options.func(_options)
File "/home/gseastr/envs/pyomo/pyomo/scripting/driver_help.py", line 456, in help_exec
help_solvers()
File "/home/gseastr/envs/pyomo/pyomo/scripting/driver_help.py", line 373, in help_solvers
kestrel = pyomo.neos.kestrel.kestrelAMPL()
File "/home/gseastr/envs/pyomo/pyomo/neos/kestrel.py", line 66, in __init__
self.setup_connection()
File "/home/gseastr/envs/pyomo/pyomo/neos/kestrel.py", line 87, in setup_connection
result = self.neos.ping()
File "/home/gseastr/envs/python3.6/lib/python3.6/xmlrpc/client.py", line 1112, in __call__
return self.__send(self.__name, args)
File "/home/gseastr/envs/python3.6/lib/python3.6/xmlrpc/client.py", line 1452, in __request
verbose=self.__verbose
File "/home/gseastr/envs/python3.6/lib/python3.6/xmlrpc/client.py", line 1154, in request
return self.single_request(host, handler, request_body, verbose)
File "/home/gseastr/envs/python3.6/lib/python3.6/xmlrpc/client.py", line 1166, in single_request
http_conn = self.send_request(host, handler, request_body, verbose)
TypeError: send_request() takes 4 positional arguments but 5 were given

# Fixed code
def send_request(self, connection, handler, request_body):
    connection.putrequest("POST", "%s%s" % (self.realhost, handler))
# Buggy code
def __init__(self, **kwds):
    self._version = None
    self._default_variable_value = None

    self._capabilities = Options()
    self._capabilities.linear = True
    self._capabilities.quadratic_objective = True
    self._capabilities.quadratic_constraint = True
    self._capabilities.integer = True
    self._capabilities.sos1 = False
    self._capabilities.sos2 = False

    self.options = Options()  # ignored

    pyomo.common.plugin.Plugin.__init__(self, **kwds)


# Traceback (AttributeError)
Traceback (most recent call last):
File "/usr/bin/pyomo", line 11, in <module>
sys.exit(main())
File "/usr/lib64/python3.4/site-packages/pyomo/scripting/pyomo_main.py", line 82, in main
retval = _options.func(_options)
File "/usr/lib64/python3.4/site-packages/pyomo/scripting/driver_help.py", line 457, in help_exec
help_solvers()
File "/usr/lib64/python3.4/site-packages/pyomo/scripting/driver_help.py", line 347, in help_solvers
if s == 'py' or opt._metasolver:
AttributeError: 'GAMSShell' object has no attribute '_metasolver'

# Fixed code
def __init__(self, **kwds):
    self._version = None
    self._default_variable_value = None
    self._metasolver = False

    self._capabilities = Options()
    self._capabilities.linear = True
    self._capabilities.quadratic_objective = True
    self._capabilities.quadratic_constraint = True
    self._capabilities.integer = True
    self._capabilities.sos1 = False
    self._capabilities.sos2 = False

    self.options = Options()  # ignored

    pyomo.common.plugin.Plugin.__init__(self, **kwds)
# Buggy code
def client(service_name: str, session: Optional[boto3.Session] = None) -> boto3.client:
    """Create a valid boto3.client."""
    return ensure_session(session=session).client(
        service_name=service_name,
        use_ssl=True,
        config=botocore.config.Config(
            retries={"max_attempts": 5}, connect_timeout=10, max_pool_connections=10
        ),
    )


# Traceback (botocore.exceptions.InvalidRetryConfigurationError)
File "/glue/lib/installation/okra_datalake/scraping.py", line 235, in copy_files
wr.s3.copy_objects(filtered_files, s3_src_dir, s3_dst_dir)
File "/glue/lib/installation/awswrangler/s3/_copy.py", line 187, in copy_objects
_copy_objects(batch=batch, use_threads=use_threads, boto3_session=session)
File "/glue/lib/installation/awswrangler/s3/_copy.py", line 19, in _copy_objects
resource_s3: boto3.resource = _utils.resource(service_name="s3", session=boto3_session)
File "/glue/lib/installation/awswrangler/_utils.py", line 78, in resource
retries=
{
"max_attempts": 10,
"mode": "adaptive"
}
, connect_timeout=10, max_pool_connections=30
File "/usr/local/lib/python3.6/site-packages/botocore/config.py", line 158, in __init__
self._validate_retry_configuration(self.retries)
File "/usr/local/lib/python3.6/site-packages/botocore/config.py", line 205, in _validate_retry_configuration
retry_config_option=key)
botocore.exceptions.InvalidRetryConfigurationError: Cannot provide retry configuration for "mode". Valid retry configuration options are: 'max_attempts'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/tmp/runscript.py", line 142, in <module>
raise e_type(e_value).with_traceback(new_stack)
TypeError: __init__() takes 1 positional argument but 2 were given

# Fixed code
def client(service_name: str, session: Optional[boto3.Session] = None) -> boto3.client:
    """Create a valid boto3.client."""
    return ensure_session(session=session).client(
        service_name=service_name, use_ssl=True, config=botocore_config()
    )
# Buggy code
def resource(
    service_name: str, session: Optional[boto3.Session] = None
) -> boto3.resource:
    """Create a valid boto3.resource."""
    return ensure_session(session=session).resource(
        service_name=service_name,
        use_ssl=True,
        config=botocore.config.Config(
            retries={"max_attempts": 10, "mode": "adaptive"},
            connect_timeout=10,
            max_pool_connections=30,
        ),
    )


# Traceback (botocore.exceptions.InvalidRetryConfigurationError)
File "/glue/lib/installation/okra_datalake/scraping.py", line 235, in copy_files
wr.s3.copy_objects(filtered_files, s3_src_dir, s3_dst_dir)
File "/glue/lib/installation/awswrangler/s3/_copy.py", line 187, in copy_objects
_copy_objects(batch=batch, use_threads=use_threads, boto3_session=session)
File "/glue/lib/installation/awswrangler/s3/_copy.py", line 19, in _copy_objects
resource_s3: boto3.resource = _utils.resource(service_name="s3", session=boto3_session)
File "/glue/lib/installation/awswrangler/_utils.py", line 78, in resource
retries=
{
"max_attempts": 10,
"mode": "adaptive"
}
, connect_timeout=10, max_pool_connections=30
File "/usr/local/lib/python3.6/site-packages/botocore/config.py", line 158, in __init__
self._validate_retry_configuration(self.retries)
File "/usr/local/lib/python3.6/site-packages/botocore/config.py", line 205, in _validate_retry_configuration
retry_config_option=key)
botocore.exceptions.InvalidRetryConfigurationError: Cannot provide retry configuration for "mode". Valid retry configuration options are: 'max_attempts'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/tmp/runscript.py", line 142, in <module>
raise e_type(e_value).with_traceback(new_stack)
TypeError: __init__() takes 1 positional argument but 2 were given

# Fixed code
def resource(
    service_name: str, session: Optional[boto3.Session] = None
) -> boto3.resource:
    """Create a valid boto3.resource."""
    return ensure_session(session=session).resource(
        service_name=service_name, use_ssl=True, config=botocore_config()
    )
# Buggy code
def _ensure_workgroup(
    session: boto3.Session, workgroup: Optional[str] = None
) -> Tuple[Optional[str], Optional[str], Optional[str]]:
    if workgroup:
        res: Dict[str, Any] = get_work_group(workgroup=workgroup, boto3_session=session)
        config: Dict[str, Any] = res["WorkGroup"]["Configuration"][
            "ResultConfiguration"
        ]
        wg_s3_output: Optional[str] = config.get("OutputLocation")
        wg_encryption: Optional[str] = config["EncryptionConfiguration"].get(
            "EncryptionOption"
        )
        wg_kms_key: Optional[str] = config["EncryptionConfiguration"].get("KmsKey")
    else:
        wg_s3_output, wg_encryption, wg_kms_key = None, None, None
    return wg_s3_output, wg_encryption, wg_kms_key


# Traceback (KeyError)
Traceback (most recent call last):
File "sample.py", line 6, in <module>
workgroup="bar",
File "/home/nagomiso/develop/.venv/lib/python3.7/site-packages/awswrangler/athena.py", line 408, in read_sql_query
wg_s3_output, _, _ = _ensure_workgroup(session=session, workgroup=workgroup)
File "/home/nagomiso/develop/.venv/lib/python3.7/site-packages/awswrangler/athena.py", line 546, in _ensure_workgroup
wg_encryption: Optional[str] = config["EncryptionConfiguration"].get("EncryptionOption")
KeyError: 'EncryptionConfiguration'

# Fixed code
def _ensure_workgroup(
    session: boto3.Session, workgroup: Optional[str] = None
) -> Tuple[Optional[str], Optional[str], Optional[str]]:
    if workgroup is not None:
        res: Dict[str, Any] = get_work_group(workgroup=workgroup, boto3_session=session)
        config: Dict[str, Any] = res["WorkGroup"]["Configuration"][
            "ResultConfiguration"
        ]
        wg_s3_output: Optional[str] = config.get("OutputLocation")
        encrypt_config: Optional[Dict[str, str]] = config.get("EncryptionConfiguration")
        wg_encryption: Optional[str] = (
            None if encrypt_config is None else encrypt_config.get("EncryptionOption")
        )
        wg_kms_key: Optional[str] = (
            None if encrypt_config is None else encrypt_config.get("KmsKey")
        )
    else:
        wg_s3_output, wg_encryption, wg_kms_key = None, None, None
    return wg_s3_output, wg_encryption, wg_kms_key
# Buggy code
def __init__(
    self,
    filename,
    buffersize,
    decode_file=False,
    print_infos=False,
    fps=44100,
    nbytes=2,
    nchannels=2,
):
    # TODO bring FFMPEG_AudioReader more in line with FFMPEG_VideoReader
    # E.g. here self.pos is still 1-indexed.
    # (or have them inherit from a shared parent class)
    self.filename = filename
    self.nbytes = nbytes
    self.fps = fps
    self.format = "s%dle" % (8 * nbytes)
    self.codec = "pcm_s%dle" % (8 * nbytes)
    self.nchannels = nchannels
    infos = ffmpeg_parse_infos(filename, decode_file=decode_file)
    self.duration = infos.get("video_duration")
    if self.duration is None:
        self.duration = infos["duration"]
    self.bitrate = infos["audio_bitrate"]
    self.infos = infos
    self.proc = None

    self.n_frames = int(self.fps * self.duration)
    self.buffersize = min(self.n_frames + 1, buffersize)
    self.buffer = None
    self.buffer_startframe = 1
    self.initialize()
    self.buffer_around(1)


# Traceback (AttributeError)
Exception ignored in: <bound method FFMPEG_AudioReader.__del__ of <moviepy.audio.io.readers.FFMPEG_AudioReader object at 0x7fc339261cf8>>
Traceback (most recent call last):
File "/home/vagrant/.tox/py36/lib/python3.6/site-packages/moviepy/audio/io/readers.py", line 264, in __del__
self.close()
File "/home/vagrant/.tox/py36/lib/python3.6/site-packages/moviepy/audio/io/readers.py", line 254, in close
if self.proc:
AttributeError: 'FFMPEG_AudioReader' object has no attribute 'proc'

# Fixed code
def __init__(
    self,
    filename,
    buffersize,
    decode_file=False,
    print_infos=False,
    fps=44100,
    nbytes=2,
    nchannels=2,
):
    # TODO bring FFMPEG_AudioReader more in line with FFMPEG_VideoReader
    # E.g. here self.pos is still 1-indexed.
    # (or have them inherit from a shared parent class)
    self.filename = filename
    self.nbytes = nbytes
    self.fps = fps
    self.format = "s%dle" % (8 * nbytes)
    self.codec = "pcm_s%dle" % (8 * nbytes)
    self.nchannels = nchannels
    infos = ffmpeg_parse_infos(filename, decode_file=decode_file)
    self.duration = infos["duration"]
    self.bitrate = infos["audio_bitrate"]
    self.infos = infos
    self.proc = None

    self.n_frames = int(self.fps * self.duration)
    self.buffersize = min(self.n_frames + 1, buffersize)
    self.buffer = None
    self.buffer_startframe = 1
    self.initialize()
    self.buffer_around(1)
# Buggy code
def _reset_state(self):
    """Reinitializes the state of the parser. Used internally at
    initialization and at the end of the parsing process.
    """
    # could be 2 possible types of metadata:
    #   - file_metadata: Metadata of the container. Here are the tags setted
    #     by the user using `-metadata` ffmpeg option
    #   - stream_metadata: Metadata for each stream of the container.
    self._inside_file_metadata = False

    # this state is neeeded if `duration_tag_separator == "time="` because
    # execution of ffmpeg decoding the whole file using `-f null -` appends
    # to the output a the blocks "Stream mapping:" and "Output:", which
    # should be ignored
    self._inside_output = False

    # flag which indicates that a default stream has not been found yet
    self._default_stream_found = False

    # current input file, stream and chapter, which will be built at runtime
    self._current_input_file = {"streams": []}
    self._current_stream = None
    self._current_chapter = None


# Traceback (AttributeError)
Exception ignored in: <bound method FFMPEG_AudioReader.__del__ of <moviepy.audio.io.readers.FFMPEG_AudioReader object at 0x7fc339261cf8>>
Traceback (most recent call last):
File "/home/vagrant/.tox/py36/lib/python3.6/site-packages/moviepy/audio/io/readers.py", line 264, in __del__
self.close()
File "/home/vagrant/.tox/py36/lib/python3.6/site-packages/moviepy/audio/io/readers.py", line 254, in close
if self.proc:
AttributeError: 'FFMPEG_AudioReader' object has no attribute 'proc'

# Fixed code
def _reset_state(self):
    """Reinitializes the state of the parser. Used internally at
    initialization and at the end of the parsing process.
    """
    # could be 2 possible types of metadata:
    #   - file_metadata: Metadata of the container. Here are the tags setted
    #     by the user using `-metadata` ffmpeg option
    #   - stream_metadata: Metadata for each stream of the container.
    self._inside_file_metadata = False

    # this state is neeeded if `duration_tag_separator == "time="` because
    # execution of ffmpeg decoding the whole file using `-f null -` appends
    # to the output a the blocks "Stream mapping:" and "Output:", which
    # should be ignored
    self._inside_output = False

    # flag which indicates that a default stream has not been found yet
    self._default_stream_found = False

    # current input file, stream and chapter, which will be built at runtime
    self._current_input_file = {"streams": []}
    self._current_stream = None
    self._current_chapter = None

    # resulting data of the parsing process
    self.result = {
        "video_found": False,
        "audio_found": False,
        "metadata": {},
        "inputs": [],
    }
# Buggy code
def __init__(
    self,
    filename,
    buffersize,
    decode_file=False,
    print_infos=False,
    fps=44100,
    nbytes=2,
    nchannels=2,
):
    # TODO bring FFMPEG_AudioReader more in line with FFMPEG_VideoReader
    # E.g. here self.pos is still 1-indexed.
    # (or have them inherit from a shared parent class)
    self.filename = filename
    self.nbytes = nbytes
    self.fps = fps
    self.format = "s%dle" % (8 * nbytes)
    self.codec = "pcm_s%dle" % (8 * nbytes)
    self.nchannels = nchannels
    infos = ffmpeg_parse_infos(filename, decode_file=decode_file)
    self.duration = infos["duration"]
    self.bitrate = infos["audio_bitrate"]
    self.infos = infos
    self.proc = None

    self.n_frames = int(self.fps * self.duration)
    self.buffersize = min(self.n_frames + 1, buffersize)
    self.buffer = None
    self.buffer_startframe = 1
    self.initialize()
    self.buffer_around(1)


# Traceback (AttributeError)
Exception ignored in: <bound method FFMPEG_AudioReader.__del__ of <moviepy.audio.io.readers.FFMPEG_AudioReader object at 0x7fc339261cf8>>
Traceback (most recent call last):
File "/home/vagrant/.tox/py36/lib/python3.6/site-packages/moviepy/audio/io/readers.py", line 264, in __del__
self.close()
File "/home/vagrant/.tox/py36/lib/python3.6/site-packages/moviepy/audio/io/readers.py", line 254, in close
if self.proc:
AttributeError: 'FFMPEG_AudioReader' object has no attribute 'proc'

# Fixed code
def __init__(
    self,
    filename,
    buffersize,
    decode_file=False,
    print_infos=False,
    fps=44100,
    nbytes=2,
    nchannels=2,
):
    # TODO bring FFMPEG_AudioReader more in line with FFMPEG_VideoReader
    # E.g. here self.pos is still 1-indexed.
    # (or have them inherit from a shared parent class)
    self.filename = filename
    self.nbytes = nbytes
    self.fps = fps
    self.format = "s%dle" % (8 * nbytes)
    self.codec = "pcm_s%dle" % (8 * nbytes)
    self.nchannels = nchannels
    infos = ffmpeg_parse_infos(filename, decode_file=decode_file)
    self.duration = infos.get("video_duration")
    if self.duration is None:
        self.duration = infos["duration"]
    self.bitrate = infos["audio_bitrate"]
    self.infos = infos
    self.proc = None

    self.n_frames = int(self.fps * self.duration)
    self.buffersize = min(self.n_frames + 1, buffersize)
    self.buffer = None
    self.buffer_startframe = 1
    self.initialize()
    self.buffer_around(1)
# Buggy code
def make_frame(t):
    played_parts = [clip.is_playing(t) for clip in self.clips]

    sounds = [
        clip.get_frame(t - clip.start) * np.array([part]).T
        for clip, part in zip(self.clips, played_parts)
        if (part is not False)
    ]

    if isinstance(t, np.ndarray):
        zero = np.zeros((len(t), self.nchannels))

    else:
        zero = np.zeros(self.nchannels)

    return zero + sum(sounds)


# Traceback (AttributeError)
Exception in thread Thread-1:
Traceback (most recent call last):
File "/usr/lib/python3.8/threading.py", line 932, in _bootstrap_inner
self.run()
File "/usr/lib/python3.8/threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "<decorator-gen-126>", line 2, in preview
File "./moviepy/decorators.py", line 56, in requires_duration
return func(clip, *args, **kwargs)
File "./moviepy/audio/io/preview.py", line 50, in preview
sndarray = clip.to_soundarray(timings, nbytes=nbytes, quantize=True)
File "<decorator-gen-81>", line 2, in to_soundarray
File "./moviepy/decorators.py", line 56, in requires_duration
return func(clip, *args, **kwargs)
File "./moviepy/audio/AudioClip.py", line 119, in to_soundarray
fps = self.fps
AttributeError: 'CompositeAudioClip' object has no attribute 'fps'

# Fixed code
def make_frame(t):
    """complicated, but must be able to handle the case where t
    is a list of the form sin(t)"""

    if isinstance(t, np.ndarray):
        array_inds = np.round(self.fps * t).astype(int)
        in_array = (array_inds >= 0) & (array_inds < len(self.array))
        result = np.zeros((len(t), 2))
        result[in_array] = self.array[array_inds[in_array]]
        return result
    else:
        i = int(self.fps * t)
        if i < 0 or i >= len(self.array):
            return 0 * self.array[0]
        else:
            return self.array[i]
# Buggy code
def __init__(self, clips):
    Clip.__init__(self)
    self.clips = clips

    ends = [clip.end for clip in self.clips]
    self.nchannels = max([clip.nchannels for clip in self.clips])
    if not any([(end is None) for end in ends]):
        self.duration = max(ends)
        self.end = max(ends)

    def make_frame(t):
        played_parts = [clip.is_playing(t) for clip in self.clips]

        sounds = [
            clip.get_frame(t - clip.start) * np.array([part]).T
            for clip, part in zip(self.clips, played_parts)
            if (part is not False)
        ]

        if isinstance(t, np.ndarray):
            zero = np.zeros((len(t), self.nchannels))

        else:
            zero = np.zeros(self.nchannels)

        return zero + sum(sounds)

    self.make_frame = make_frame


# Traceback (AttributeError)
Exception in thread Thread-1:
Traceback (most recent call last):
File "/usr/lib/python3.8/threading.py", line 932, in _bootstrap_inner
self.run()
File "/usr/lib/python3.8/threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "<decorator-gen-126>", line 2, in preview
File "./moviepy/decorators.py", line 56, in requires_duration
return func(clip, *args, **kwargs)
File "./moviepy/audio/io/preview.py", line 50, in preview
sndarray = clip.to_soundarray(timings, nbytes=nbytes, quantize=True)
File "<decorator-gen-81>", line 2, in to_soundarray
File "./moviepy/decorators.py", line 56, in requires_duration
return func(clip, *args, **kwargs)
File "./moviepy/audio/AudioClip.py", line 119, in to_soundarray
fps = self.fps
AttributeError: 'CompositeAudioClip' object has no attribute 'fps'

# Fixed code
def __init__(self, clips):
    self.clips = clips
    self.nchannels = max(clip.nchannels for clip in self.clips)

    # self.duration is setted at AudioClip
    duration = None
    for end in self.ends:
        if end is None:
            break
        duration = max(end, duration or 0)

    # self.fps is setted at AudioClip
    fps = None
    for clip in self.clips:
        if hasattr(clip, "fps") and isinstance(clip.fps, numbers.Number):
            fps = max(clip.fps, fps or 0)

    super().__init__(duration=duration, fps=fps)
# Buggy code
def concatenate_audioclips(clips):
    """
    The clip with the highest FPS will be the FPS of the result clip.
    """
    durations = [clip.duration for clip in clips]
    timings = np.cumsum([0] + durations)  # start times, and end time.
    newclips = [clip.with_start(t) for clip, t in zip(clips, timings)]

    result = CompositeAudioClip(newclips).with_duration(timings[-1])

    fpss = [clip.fps for clip in clips if getattr(clip, "fps", None)]
    result.fps = max(fpss) if fpss else None
    return result


# Traceback (AttributeError)
Exception in thread Thread-1:
Traceback (most recent call last):
File "/usr/lib/python3.8/threading.py", line 932, in _bootstrap_inner
self.run()
File "/usr/lib/python3.8/threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "<decorator-gen-126>", line 2, in preview
File "./moviepy/decorators.py", line 56, in requires_duration
return func(clip, *args, **kwargs)
File "./moviepy/audio/io/preview.py", line 50, in preview
sndarray = clip.to_soundarray(timings, nbytes=nbytes, quantize=True)
File "<decorator-gen-81>", line 2, in to_soundarray
File "./moviepy/decorators.py", line 56, in requires_duration
return func(clip, *args, **kwargs)
File "./moviepy/audio/AudioClip.py", line 119, in to_soundarray
fps = self.fps
AttributeError: 'CompositeAudioClip' object has no attribute 'fps'

# Fixed code
def concatenate_audioclips(clips):
    """Concatenates one AudioClip after another, in the order that are passed
    to ``clips`` parameter.

    Parameters
    ----------

    clips
      List of audio clips, which will be played one after other.
    """
    # start, end/start2, end2/start3... end
    starts_end = np.cumsum([0, *[clip.duration for clip in clips]])
    newclips = [clip.with_start(t) for clip, t in zip(clips, starts_end[:-1])]

    return CompositeAudioClip(newclips).with_duration(starts_end[-1])
# Buggy code
def audio_normalize(clip):
    """Return a clip whose volume is normalized to 0db.

    Return an audio (or video) clip whose audio volume is normalized
    so that the maximum volume is at 0db, the maximum achievable volume.

    Examples
    ========

    >>> from moviepy.editor import *
    >>> videoclip = VideoFileClip('myvideo.mp4').fx(afx.audio_normalize)

    """

    max_volume = clip.max_volume()
    return volumex(clip, 1 / max_volume)


# Traceback (ZeroDivisionError)
Traceback (most recent call last):
File "test.py", line 141, in <module>
ytclip = ytclip.subclip(0, 10).audio_normalize()
File "<decorator-gen-96>", line 2, in audio_normalize
File "/Users/xxx/lib/python3.7/site-packages/moviepy/decorators.py", line 70, in audio_video_fx
newclip.audio =  f(clip.audio, *a, **k)
File "/Users/xxxx/lib/python3.7/site-packages/moviepy/audio/fx/audio_normalize.py", line 23, in audio_normalize
return volumex(clip, 1 / mv)
**ZeroDivisionError: division by zero**

# Fixed code
def audio_normalize(clip):
    """Return a clip whose volume is normalized to 0db.

    Return an audio (or video) clip whose audio volume is normalized
    so that the maximum volume is at 0db, the maximum achievable volume.

    Examples
    ========

    >>> from moviepy.editor import *
    >>> videoclip = VideoFileClip('myvideo.mp4').fx(afx.audio_normalize)

    """

    max_volume = clip.max_volume()
    if max_volume == 0:
        # Nothing to normalize.
        # Avoids a divide by zero error.
        return clip.copy()
    else:
        return volumex(clip, 1 / max_volume)
# Buggy code
def fx(self, func, *args, **kwargs):
    """

    Returns the result of ``func(self, *args, **kwargs)``.
    for instance

    >>> newclip = clip.fx(resize, 0.2, method='bilinear')

    is equivalent to

    >>> newclip = resize(clip, 0.2, method='bilinear')

    The motivation of fx is to keep the name of the effect near its
    parameters, when the effects are chained:

    >>> from moviepy.video.fx import volumex, resize, mirrorx
    >>> clip.fx( volumex, 0.5).fx( resize, 0.3).fx( mirrorx )
    >>> # Is equivalent, but clearer than
    >>> resize( volumex( mirrorx( clip ), 0.5), 0.3)

    """

    return func(self, *args, **kwargs)


# Traceback (ValueError)
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
newclip.write_videofile(r"F:\video\WinBasedWorkHard_new.mp4")
File "<decorator-gen-55>", line 2, in write_videofile
File "C:\Program Files\Python37\lib\site-packages\moviepy\decorators.py", line 52, in requires_duration
raise ValueError("Attribute 'duration' not set")
ValueError: Attribute 'duration' not set

# Fixed code
def fx(self, func, *args, **kwargs):
    """

    Returns the result of ``func(self, *args, **kwargs)``.
    for instance

    >>> newclip = clip.fx(resize, 0.2, method="bilinear")

    is equivalent to

    >>> newclip = resize(clip, 0.2, method="bilinear")

    The motivation of fx is to keep the name of the effect near its
    parameters when the effects are chained:

    >>> from moviepy.video.fx import volumex, resize, mirrorx
    >>> clip.fx(volumex, 0.5).fx(resize, 0.3).fx(mirrorx)
    >>> # Is equivalent, but clearer than
    >>> mirrorx(resize(volumex(clip, 0.5), 0.3))
    """

    return func(self, *args, **kwargs)
# Buggy code
def __init__(self, size, color=None, ismask=False, duration=None):
    w, h = size
    shape = (h, w) if np.isscalar(color) else (h, w, len(color))
    super().__init__(
        np.tile(color, w * h).reshape(shape), ismask=ismask, duration=duration
    )


# Traceback (TypeError)
In [1]: from moviepy.editor import ColorClip

In [2]: c = ColorClip((10,10), duration=1)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-2-5c98bac84586> in <module>
----> 1 c = ColorClip((10,10), duration=1)

~/lab/moviepy/moviepy/video/VideoClip.py in __init__(self, size, color, ismask, duration, col)
1094                 color = col
1095         w, h = size
-> 1096         shape = (h, w) if np.isscalar(color) else (h, w, len(color))
1097         ImageClip.__init__(
1098             self, np.tile(color, w * h).reshape(shape), ismask=ismask, duration=duration

TypeError: object of type 'NoneType' has no len()

# Fixed code
def __init__(self, size, color=None, ismask=False, duration=None):
    w, h = size

    if ismask:
        shape = (h, w)
        if color is None:
            color = 0
        elif not np.isscalar(color):
            raise Exception("Color has to be a scalar when mask is true")
    else:
        if color is None:
            color = (0, 0, 0)
        elif not hasattr(color, "__getitem__"):
            raise Exception("Color has to contain RGB of the clip")
        shape = (h, w, len(color))

    super().__init__(
        np.tile(color, w * h).reshape(shape), ismask=ismask, duration=duration
    )
# Buggy code
def pil_rotater(pic, angle, resample, expand):
    return np.array(
        Image.fromarray(pic).rotate(angle, expand=expand, resample=resample)
    )


# Traceback (KeyError)
Traceback (most recent call last):
MoviePy\venv\lib\site-packages\PIL\Image.py", line 2680, in fromarray
mode, rawmode = _fromarray_typemap[typekey]
KeyError: ((1, 1, 3), '<i4')

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
rotation_test.py", line 10, in <module>
rotated_image = colour_clip.rotate(20)

MoviePy\venv\lib\site-packages\moviepy\video\fx\rotate.py", line 71, in rotate
return clip.fl(fl, apply_to=["mask"])

MoviePy\venv\lib\site-packages\moviepy\video\VideoClip.py", line 951, in fl
keep_duration=keep_duration)

MoviePy\venv\lib\site-packages\moviepy\Clip.py", line 138, in fl
newclip = self.set_make_frame(lambda t: fun(self.get_frame, t))
File "<decorator-gen-57>", line 2, in set_make_frame

MoviePy\venv\lib\site-packages\moviepy\decorators.py", line 14, in outplace
f(newclip, *a, **k)

MoviePy\venv\lib\site-packages\moviepy\video\VideoClip.py", line 673, in set_make_frame
self.size = self.get_frame(0).shape[:2][::-1]
File "<decorator-gen-10>", line 2, in get_frame

MoviePy\venv\lib\site-packages\moviepy\decorators.py", line 89, in wrapper
return f(*new_a, **new_kw)

MoviePy\venv\lib\site-packages\moviepy\Clip.py", line 95, in get_frame
return self.make_frame(t)

MoviePy\venv\lib\site-packages\moviepy\Clip.py", line 138, in <lambda>
newclip = self.set_make_frame(lambda t: fun(self.get_frame, t))

MoviePy\venv\lib\site-packages\moviepy\video\fx\rotate.py", line 69, in fl
return pil_rotater(im, a, resample=resample, expand=expand)

MoviePy\venv\lib\site-packages\moviepy\video\fx\rotate.py", line 7, in pil_rotater
return np.array( Image.fromarray(pic).rotate(angle, expand=expand,

MoviePy\venv\lib\site-packages\PIL\Image.py", line 2682, in fromarray
raise TypeError("Cannot handle this data type: %s, %s" % typekey)
TypeError: Cannot handle this data type: (1, 1, 3), <i4

Process finished with exit code 1

# Fixed code
def pil_rotater(pic, angle, resample, expand):
    # Ensures that pic is of the correct type
    return np.array(
        Image.fromarray(np.array(pic).astype(np.uint8)).rotate(
            angle, expand=expand, resample=resample
        )
    )
# Buggy code
def _get_relative_url(self, path: str) -> str:
    if not self.url:
        return ""
    suffix = str(self.template_path).replace(str(self.project_root), "")
    suffix_length = len(suffix.lstrip("/").split("/"))
    url_prefix = "/".join(self.url.split("/")[0:-suffix_length])
    suffix = str(path).replace(str(self.project_root), "")
    url = url_prefix + suffix
    return url


# Traceback (TypeError)
version 0.9.8
[ERROR  ] : TypeError expected str, bytes or os.PathLike object, not dict_node
Traceback (most recent call last):
File "/usr/local/lib/python3.7/site-packages/taskcat/_cli.py", line 70, in main
cli.run()
File "/usr/local/lib/python3.7/site-packages/taskcat/_cli_core.py", line 228, in run
return getattr(command(), subcommand)(**args)
File "/usr/local/lib/python3.7/site-packages/taskcat/_cli_modules/test.py", line 60, in run
templates = config.get_templates(project_root_path)
File "/usr/local/lib/python3.7/site-packages/taskcat/_config.py", line 312, in get_templates
s3_key_prefix=f"{self.config.project.name}/",
File "/usr/local/lib/python3.7/site-packages/taskcat/_cfn/template.py", line 30, in __init__
self._find_children()
File "/usr/local/lib/python3.7/site-packages/taskcat/_cfn/template.py", line 111, in _find_children
resource["Properties"]["TemplateURL"]
File "/usr/local/lib/python3.7/site-packages/taskcat/_cfn/template.py", line 72, in _template_url_to_path
template_path = self.project_root / template_path
File "/usr/local/Cellar/python/3.7.5/Frameworks/Python.framework/Versions/3.7/lib/python3.7/pathlib.py", line 908, in __truediv__
return self._make_child((key,))
File "/usr/local/Cellar/python/3.7.5/Frameworks/Python.framework/Versions/3.7/lib/python3.7/pathlib.py", line 695, in _make_child
drv, root, parts = self._parse_args(args)
File "/usr/local/Cellar/python/3.7.5/Frameworks/Python.framework/Versions/3.7/lib/python3.7/pathlib.py", line 649, in _parse_args
a = os.fspath(a)
TypeError: expected str, bytes or os.PathLike object, not dict_node

# Fixed code
def _get_relative_url(self, path: str) -> str:
    suffix = str(path).replace(str(self.project_root), "")
    url = self.url_prefix() + suffix
    return url
# Buggy code
def __init__(self, param_dict, bucket_name, region, boto_client, az_excludes=None):
    self.regxfind = CommonTools.regxfind
    self._param_dict = param_dict
    self.results = {}
    self.mutated_params = {}
    self.param_name = None
    self.param_value = None
    self.bucket_name = bucket_name
    self._boto_client = boto_client
    self.region = region
    if not az_excludes:
        self.az_excludes: Set[str] = set()
    else:
        self.az_excludes: Set[str] = az_excludes
    self.transform_parameter()


# Traceback (TypeError)
[ERROR  ] : TypeError expected string or bytes-like object
Traceback (most recent call last):
File "/usr/local/lib/python3.7/site-packages/taskcat/_cli.py", line 70, in main
cli.run()
File "/usr/local/lib/python3.7/site-packages/taskcat/_cli_core.py", line 228, in run
return getattr(command(), subcommand)(**args)
File "/usr/local/lib/python3.7/site-packages/taskcat/_cli_modules/test.py", line 75, in run
parameters = config.get_rendered_parameters(buckets, regions, templates)
File "/usr/local/lib/python3.7/site-packages/taskcat/_config.py", line 295, in get_rendered_parameters
region_params, s3bucket.name, region.name, region.client
File "/usr/local/lib/python3.7/site-packages/taskcat/_template_params.py", line 49, in __init__
self.transform_parameter()
File "/usr/local/lib/python3.7/site-packages/taskcat/_template_params.py", line 64, in transform_parameter
self._regex_replace_param_value(self.RE_GENNUMB, self._gen_rand_num(20))
File "/usr/local/lib/python3.7/site-packages/taskcat/_template_params.py", line 336, in _regex_replace_param_value
if self.regxfind(regex_pattern, self.param_value):
File "/usr/local/lib/python3.7/site-packages/taskcat/_common_utils.py", line 76, in regxfind
security_group = re_object.search(data_line)
TypeError: expected string or bytes-like object

# Fixed code
def __init__(self, param_dict, bucket_name, region, boto_client, az_excludes=None):
    self.regxfind = CommonTools.regxfind
    self._param_dict = param_dict
    _missing_params = []
    for param_name, param_value in param_dict.items():
        if param_value is None:
            _missing_params.append(param_name)
    if _missing_params:
        raise TaskCatException(
            (
                f"The following parameters have no value whatsoever. "
                f"The CloudFormation stack will fail to launch. "
                f"Please address. str({_missing_params})"
            )
        )
    self.results = {}
    self.mutated_params = {}
    self.param_name = None
    self.param_value = None
    self.bucket_name = bucket_name
    self._boto_client = boto_client
    self.region = region
    if not az_excludes:
        self.az_excludes: Set[str] = set()
    else:
        self.az_excludes: Set[str] = az_excludes
    self.transform_parameter()
# Buggy code
def _fetch_children(self) -> None:
    self._last_child_refresh = datetime.now()
    for page in self.client.get_paginator("describe_stacks").paginate():
        for stack in page["Stacks"]:
            if self._children.filter(id=stack["StackId"]):
                continue
            if "ParentId" in stack.keys():
                if self.id == stack["ParentId"]:
                    stack_obj = Stack._import_child(stack, self)
                    self._children.append(stack_obj)


# Traceback (TypeError)
[ERROR  ] : TypeError write() argument must be str, not collections.OrderedDict
Traceback (most recent call last):
File "/home/ags/venv/venv-taskcat/lib/python3.6/site-packages/taskcat/_cli.py", line 66, in main
cli.run()
File "/home/ags/venv/venv-taskcat/lib/python3.6/site-packages/taskcat/_cli_core.py", line 228, in run
return getattr(command(), subcommand)(**args)
File "/home/ags/venv/venv-taskcat/lib/python3.6/site-packages/taskcat/_cli_modules/test.py", line 81, in run
terminal_printer.report_test_progress(stacker=test_definition)
File "/home/ags/venv/venv-taskcat/lib/python3.6/site-packages/taskcat/_tui.py", line 24, in report_test_progress
self._print_stack_tree(stack, buffer=self.buffer)
File "/home/ags/venv/venv-taskcat/lib/python3.6/site-packages/taskcat/_tui.py", line 37, in _print_stack_tree
if stack.descendants():
File "/home/ags/venv/venv-taskcat/lib/python3.6/site-packages/taskcat/_cfn/stack.py", line 495, in descendants
self._fetch_children()
File "/home/ags/venv/venv-taskcat/lib/python3.6/site-packages/taskcat/_cfn/stack.py", line 481, in _fetch_children
stack_obj = Stack._import_child(stack, self)
File "/home/ags/venv/venv-taskcat/lib/python3.6/site-packages/taskcat/_cfn/stack.py", line 335, in _import_child
fh.write(tempate_body)
TypeError: write() argument must be str, not collections.OrderedDict

# Fixed code
def _fetch_children(self) -> None:
    self._last_child_refresh = datetime.now()
    for page in self.client.get_paginator("describe_stacks").paginate():
        for stack in page["Stacks"]:
            if self._children.filter(id=stack["StackId"]):
                continue
            if "ParentId" in stack.keys():
                if self.id == stack["ParentId"]:
                    stack_obj = Stack._import_child(stack, self)
                    if stack_obj:
                        self._children.append(stack_obj)
# Buggy code
def get_global_region(self, yamlcfg):
    """
    Returns a list of regions defined under global region in the yml config file.

    :param yamlcfg: Content of the yml config file
    :return: List of regions

    """
    g_regions = []
    for keys in yamlcfg["global"].keys():
        if "region" in keys:
            try:
                iter(yamlcfg["global"]["regions"])
                namespace = "global"
                for region in yamlcfg["global"]["regions"]:
                    # print("found region %s" % region)
                    g_regions.append(region)
                    self._use_global = True
            except TypeError:
                print("No regions defined in [%s]:" % namespace)
                print("Please correct region defs[%s]:" % namespace)
    return g_regions


# Traceback (botocore.exceptions.ClientError)
·[0;30;43m[INFO ]·[0m :Creating bucket taskcat-tag-CfnLintDemo-0a074b3f in us-east-2
Traceback (most recent call last):
File "/usr/local/bin/taskcat", line 79, in <module>
main()
File "/usr/local/bin/taskcat", line 65, in main
tcat_instance.stage_in_s3(taskcat_cfg)
File "/usr/local/lib/python3.6/site-packages/taskcat/stacker.py", line 428, in stage_in_s3
'LocationConstraint': self.get_default_region()
File "/usr/local/lib/python3.6/site-packages/botocore/client.py", line 320, in _api_call
return self._make_api_call(operation_name, kwargs)
File "/usr/local/lib/python3.6/site-packages/botocore/client.py", line 623, in _make_api_call
raise error_class(parsed_response, operation_name)
botocore.exceptions.ClientError: An error occurred (InvalidBucketName) when calling the CreateBucket operation: The specified bucket is not valid.
[Container] 2018/10/31 04:40:24 Command did not exit successfully taskcat -c $PROJECTNAME/ci/taskcat.yml exit status 1

# Fixed code
def get_global_region(self, yamlcfg):
    """
    Returns a list of regions defined under global region in the yml config file.

    :param yamlcfg: Content of the yml config file
    :return: List of regions

    """
    g_regions = []
    for keys in yamlcfg["global"].keys():
        if "region" in keys:
            namespace = "global"
            try:
                iter(yamlcfg["global"]["regions"])
                for region in yamlcfg["global"]["regions"]:
                    g_regions.append(region)
                    self._use_global = True
            except TypeError as e:
                print(PrintMsg.ERROR + "No regions defined in [%s]:" % namespace)
                print(PrintMsg.ERROR + "Please correct region defs[%s]:" % namespace)
    return g_regions
# Buggy code
def __call__(self, value, clip=None):
    if clip is None:
        clip = self.clip

    xx, is_scalar = self.process_value(value)
    mask = np.ma.getmaskarray(xx)
    xx = np.atleast_1d(xx.filled(self.vmax + 1))
    if clip:
        np.clip(xx, self.vmin, self.vmax, out=xx)
        max_col = self.Ncmap - 1
    else:
        max_col = self.Ncmap
    iret = np.digitize(xx, self.boundaries) - 1 + self._offset
    if self.Ncmap > self._N:
        scalefac = (self.Ncmap - 1) / (self._N - 1)
        iret = (iret * scalefac).astype(np.int16)
    iret[xx < self.vmin] = -1
    iret[xx >= self.vmax] = max_col
    ret = np.ma.array(iret, mask=mask)
    if is_scalar:
        ret = int(ret[0])  # assume python scalar
    return ret


# Traceback (ZeroDivisionError)
---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-160-8a8135eaeb3c> in <module>
2 bounds = [0, 1]
3 norm = mpl.colors.BoundaryNorm(bounds, cmap.N)
----> 4 norm(0.5)

/usr/local/lib/python3.6/dist-packages/matplotlib/colors.py in __call__(self, value, clip)
1442             iret[xx >= b] = i
1443         if self._interp:
-> 1444             scalefac = (self.Ncmap - 1) / (self.N - 2)
1445             iret = (iret * scalefac).astype(np.int16)
1446         iret[xx < self.vmin] = -1

ZeroDivisionError: division by zero

# Fixed code
def __call__(self, value, clip=None):
    if clip is None:
        clip = self.clip

    xx, is_scalar = self.process_value(value)
    mask = np.ma.getmaskarray(xx)
    # Fill masked values a value above the upper boundary
    xx = np.atleast_1d(xx.filled(self.vmax + 1))
    if clip:
        np.clip(xx, self.vmin, self.vmax, out=xx)
        max_col = self.Ncmap - 1
    else:
        max_col = self.Ncmap
    # this gives us the bins in the lookup table in the range
    # [0, _n_regions - 1]  (the offset is baked in in the init)
    iret = np.digitize(xx, self.boundaries) - 1 + self._offset
    # if we have more colors than regions, stretch the region
    # index computed above to full range of the color bins.  This
    # will make use of the full range (but skip some of the colors
    # in the middle) such that the first region is mapped to the
    # first color and the last region is mapped to the last color.
    if self.Ncmap > self._n_regions:
        if self._n_regions == 1:
            # special case the 1 region case, pick the middle color
            iret[iret == 0] = (self.Ncmap - 1) // 2
        else:
            # otherwise linearly remap the values from the region index
            # to the color index spaces
            iret = (self.Ncmap - 1) / (self._n_regions - 1) * iret
    # cast to 16bit integers in all cases
    iret = iret.astype(np.int16)
    iret[xx < self.vmin] = -1
    iret[xx >= self.vmax] = max_col
    ret = np.ma.array(iret, mask=mask)
    if is_scalar:
        ret = int(ret[0])  # assume python scalar
    return ret
# Buggy code
def quote_ps_string(s):
    "Quote dangerous characters of S for use in a PostScript string constant."
    s = s.replace("\\", "\\\\")
    s = s.replace("(", "\\(")
    s = s.replace(")", "\\)")
    s = s.replace("'", "\\251")
    s = s.replace("`", "\\301")
    s = re.sub(r"[^ -~\n]", lambda x: r"\%03o" % ord(x.group()), s)
    return s


# Traceback (TypeError)
Traceback (most recent call last):
File "/home/tps/PyCharmProjects/test/test_PlotWindow.py", line 323, in saveFigRButtonClicked
savefig(fname)
File "/usr/local/lib/python3.4/dist-packages/matplotlib/pyplot.py", line 688, in savefig
res = fig.savefig(*args, **kwargs)
File "/usr/local/lib/python3.4/dist-packages/matplotlib/figure.py", line 1565, in savefig
self.canvas.print_figure(*args, **kwargs)
File "/usr/local/lib/python3.4/dist-packages/matplotlib/backends/backend_qt5agg.py", line 196, in print_figure
FigureCanvasAgg.print_figure(self, *args, **kwargs)
File "/usr/local/lib/python3.4/dist-packages/matplotlib/backend_bases.py", line 2232, in print_figure
**kwargs)
File "/usr/local/lib/python3.4/dist-packages/matplotlib/backends/backend_ps.py", line 995, in print_eps
return self._print_ps(outfile, 'eps', *args, **kwargs)
File "/usr/local/lib/python3.4/dist-packages/matplotlib/backends/backend_ps.py", line 1023, in _print_ps
**kwargs)
File "/usr/local/lib/python3.4/dist-packages/matplotlib/backends/backend_ps.py", line 1113, in _print_figure
self.figure.draw(renderer)
File "/usr/local/lib/python3.4/dist-packages/matplotlib/artist.py", line 61, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/usr/local/lib/python3.4/dist-packages/matplotlib/figure.py", line 1159, in draw
func(*args)
File "/usr/local/lib/python3.4/dist-packages/matplotlib/artist.py", line 61, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/usr/local/lib/python3.4/dist-packages/matplotlib/axes/_base.py", line 2324, in draw
a.draw(renderer)
File "/usr/local/lib/python3.4/dist-packages/matplotlib/artist.py", line 61, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/usr/local/lib/python3.4/dist-packages/matplotlib/collections.py", line 1694, in draw
renderer.draw_gouraud_triangles(gc, verts, colors, transform.frozen())
File "/usr/local/lib/python3.4/dist-packages/matplotlib/backends/backend_ps.py", line 867, in draw_gouraud_triangles
stream = quote_ps_string(streamarr.tostring())
File "/usr/local/lib/python3.4/dist-packages/matplotlib/backends/backend_ps.py", line 170, in quote_ps_string
s=s.replace("\\", "\\\\")
TypeError: expected bytes, bytearray or buffer compatible object

# Fixed code
def quote_ps_string(s):
    "Quote dangerous characters of S for use in a PostScript string constant."
    s = s.replace(b"\\", b"\\\\")
    s = s.replace(b"(", b"\\(")
    s = s.replace(b")", b"\\)")
    s = s.replace(b"'", b"\\251")
    s = s.replace(b"`", b"\\301")
    s = re.sub(rb"[^ -~\n]", lambda x: rb"\%03o" % ord(x.group()), s)
    return s.decode("ascii")