gurudesh/pytracebugs huggingface dataset:
# Buggy code
def circmean(samples, high=2 * pi, low=0, axis=None):
    """
    Compute the circular mean for samples in a range.

    Parameters
    ----------
    samples : array_like
        Input array.
    high : float or int, optional
        High boundary for circular mean range.  Default is ``2*pi``.
    low : float or int, optional
        Low boundary for circular mean range.  Default is 0.
    axis : int, optional
        Axis along which means are computed.  The default is to compute
        the mean of the flattened array.

    Returns
    -------
    circmean : float
        Circular mean.

    """
    ang = (samples - low) * 2 * pi / (high - low)
    res = angle(np.mean(exp(1j * ang), axis=axis))
    mask = res < 0
    if mask.ndim > 0:
        res[mask] += 2 * pi
    elif mask:
        res = res + 2 * pi
    return res * (high - low) / 2.0 / pi + low


# Traceback (ValueError)
import numpy
import scipy.stats.morestats
def getmean(a):
...     radiansA = numpy.deg2rad(a)
...     radiansMean = scipy.stats.morestats.circmean(radiansA)
...     degreesMean = numpy.rad2deg(radiansMean)
...     return degreesMean
...
getmean([90,100,80,85])
88.741025855464059
getmean(numpy.array([90,100,80,85]))
88.741025855464059
getmean(numpy.array([[90],[100],[80],[85]]))
array([ 88.74102586])
getmean(numpy.array([[90,100],[80,85]]))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in getmean
File "/work/gfe-devel-1.1.6/lib/python2.7/site-packages/scipy/stats/morestats.py", line 1306, in circmean
if (res < 0):
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
getmean(numpy.array([[90,100],[80,85]]).flat)
88.741025855464059

# Fixed code
def circmean(samples, high=2 * pi, low=0, axis=None):
    """
    Compute the circular mean for samples in a range.

    Parameters
    ----------
    samples : array_like
        Input array.
    high : float or int, optional
        High boundary for circular mean range.  Default is ``2*pi``.
    low : float or int, optional
        Low boundary for circular mean range.  Default is 0.
    axis : int, optional
        Axis along which means are computed.  The default is to compute
        the mean of the flattened array.

    Returns
    -------
    circmean : float
        Circular mean.

    """
    samples, ang = _circfuncs_common(samples, high, low)
    res = angle(np.mean(exp(1j * ang), axis=axis))
    mask = res < 0
    if mask.ndim > 0:
        res[mask] += 2 * pi
    elif mask:
        res = res + 2 * pi

    return res * (high - low) / 2.0 / pi + low
# Buggy code
def circvar(samples, high=2 * pi, low=0, axis=None):
    """
    Compute the circular variance for samples assumed to be in a range

    Parameters
    ----------
    samples : array_like
        Input array.
    low : float or int, optional
        Low boundary for circular variance range.  Default is 0.
    high : float or int, optional
        High boundary for circular variance range.  Default is ``2*pi``.
    axis : int, optional
        Axis along which variances are computed.  The default is to compute
        the variance of the flattened array.

    Returns
    -------
    circvar : float
        Circular variance.

    Notes
    -----
    This uses a definition of circular variance that in the limit of small
    angles returns a number close to the 'linear' variance.

    """
    ang = (samples - low) * 2 * pi / (high - low)
    res = np.mean(exp(1j * ang), axis=axis)
    R = abs(res)
    return ((high - low) / 2.0 / pi) ** 2 * 2 * log(1 / R)


# Traceback (ValueError)
import numpy
import scipy.stats.morestats
def getmean(a):
...     radiansA = numpy.deg2rad(a)
...     radiansMean = scipy.stats.morestats.circmean(radiansA)
...     degreesMean = numpy.rad2deg(radiansMean)
...     return degreesMean
...
getmean([90,100,80,85])
88.741025855464059
getmean(numpy.array([90,100,80,85]))
88.741025855464059
getmean(numpy.array([[90],[100],[80],[85]]))
array([ 88.74102586])
getmean(numpy.array([[90,100],[80,85]]))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in getmean
File "/work/gfe-devel-1.1.6/lib/python2.7/site-packages/scipy/stats/morestats.py", line 1306, in circmean
if (res < 0):
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
getmean(numpy.array([[90,100],[80,85]]).flat)
88.741025855464059

# Fixed code
def circvar(samples, high=2 * pi, low=0, axis=None):
    """
    Compute the circular variance for samples assumed to be in a range

    Parameters
    ----------
    samples : array_like
        Input array.
    low : float or int, optional
        Low boundary for circular variance range.  Default is 0.
    high : float or int, optional
        High boundary for circular variance range.  Default is ``2*pi``.
    axis : int, optional
        Axis along which variances are computed.  The default is to compute
        the variance of the flattened array.

    Returns
    -------
    circvar : float
        Circular variance.

    Notes
    -----
    This uses a definition of circular variance that in the limit of small
    angles returns a number close to the 'linear' variance.

    """
    samples, ang = _circfuncs_common(samples, high, low)
    res = np.mean(exp(1j * ang), axis=axis)
    R = abs(res)
    return ((high - low) / 2.0 / pi) ** 2 * 2 * log(1 / R)
# Buggy code
def circstd(samples, high=2 * pi, low=0, axis=None):
    """
    Compute the circular standard deviation for samples assumed to be in the
    range [low to high].

    Parameters
    ----------
    samples : array_like
        Input array.
    low : float or int, optional
        Low boundary for circular standard deviation range.  Default is 0.
    high : float or int, optional
        High boundary for circular standard deviation range.
        Default is ``2*pi``.
    axis : int, optional
        Axis along which standard deviations are computed.  The default is
        to compute the standard deviation of the flattened array.

    Returns
    -------
    circstd : float
        Circular standard deviation.

    Notes
    -----
    This uses a definition of circular standard deviation that in the limit of
    small angles returns a number close to the 'linear' standard deviation.

    """
    ang = (samples - low) * 2 * pi / (high - low)
    res = np.mean(exp(1j * ang), axis=axis)
    R = abs(res)
    return ((high - low) / 2.0 / pi) * sqrt(-2 * log(R))


# Traceback (ValueError)
import numpy
import scipy.stats.morestats
def getmean(a):
...     radiansA = numpy.deg2rad(a)
...     radiansMean = scipy.stats.morestats.circmean(radiansA)
...     degreesMean = numpy.rad2deg(radiansMean)
...     return degreesMean
...
getmean([90,100,80,85])
88.741025855464059
getmean(numpy.array([90,100,80,85]))
88.741025855464059
getmean(numpy.array([[90],[100],[80],[85]]))
array([ 88.74102586])
getmean(numpy.array([[90,100],[80,85]]))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in getmean
File "/work/gfe-devel-1.1.6/lib/python2.7/site-packages/scipy/stats/morestats.py", line 1306, in circmean
if (res < 0):
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
getmean(numpy.array([[90,100],[80,85]]).flat)
88.741025855464059

# Fixed code
def circstd(samples, high=2 * pi, low=0, axis=None):
    """
    Compute the circular standard deviation for samples assumed to be in the
    range [low to high].

    Parameters
    ----------
    samples : array_like
        Input array.
    low : float or int, optional
        Low boundary for circular standard deviation range.  Default is 0.
    high : float or int, optional
        High boundary for circular standard deviation range.
        Default is ``2*pi``.
    axis : int, optional
        Axis along which standard deviations are computed.  The default is
        to compute the standard deviation of the flattened array.

    Returns
    -------
    circstd : float
        Circular standard deviation.

    Notes
    -----
    This uses a definition of circular standard deviation that in the limit of
    small angles returns a number close to the 'linear' standard deviation.

    """
    samples, ang = _circfuncs_common(samples, high, low)
    res = np.mean(exp(1j * ang), axis=axis)
    R = abs(res)
    return ((high - low) / 2.0 / pi) * sqrt(-2 * log(R))
# Buggy code
def entropy(self, *args, **kwds):
    """
    Differential entropy of the RV.

    Parameters
    ----------
    arg1, arg2, arg3,... : array_like
        The shape parameter(s) for the distribution (see docstring of the
        instance object for more information).
    loc : array_like, optional
        Location parameter (default=0).
    scale : array_like, optional
        Scale parameter (default=1).

    """
    args, loc, scale = self._parse_args(*args, **kwds)
    args = tuple(map(asarray, args))
    cond0 = self._argcheck(*args) & (scale > 0) & (loc == loc)
    output = zeros(shape(cond0), "d")
    place(output, (1 - cond0), self.badvalue)
    goodargs = argsreduce(cond0, *args)
    # I don't know when or why vecentropy got broken when numargs == 0
    if self.numargs == 0:
        place(output, cond0, self._entropy() + log(scale))
    else:
        place(output, cond0, self.vecentropy(*goodargs) + log(scale))
    return output


# Traceback (TypeError)
======================================================================
ERROR: test_entropy (test_distributions.TestRvDiscrete)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/warren/gitwork/scipy/scipy/stats/tests/test_distributions.py", line 553, in test_entropy
h = p.entropy()
File "/home/warren/local_scipy/lib/python2.7/site-packages/scipy/stats/distributions.py", line 6769, in entropy
place(output,cond0,self.vecentropy(*goodargs))
File "/home/warren/local_scipy/lib/python2.7/site-packages/numpy/lib/function_base.py", line 1832, in __call__
_res = array(self.ufunc(*newargs),copy=False,
TypeError: function not supported for these types, and can't coerce safely to supported types

----------------------------------------------------------------------

# Fixed code
def entropy(self, *args, **kwds):
    """
    Differential entropy of the RV.

    Parameters
    ----------
    arg1, arg2, arg3,... : array_like
        The shape parameter(s) for the distribution (see docstring of the
        instance object for more information).
    loc : array_like, optional
        Location parameter (default=0).
    scale : array_like, optional
        Scale parameter (default=1).

    """
    args, loc, scale = self._parse_args(*args, **kwds)
    args = tuple(map(asarray, args))
    cond0 = self._argcheck(*args) & (scale > 0) & (loc == loc)
    output = zeros(shape(cond0), "d")
    place(output, (1 - cond0), self.badvalue)
    goodargs = argsreduce(cond0, *args)
    # np.vectorize doesn't work when numargs == 0 in numpy 1.5.1
    if self.numargs == 0:
        place(output, cond0, self._entropy() + log(scale))
    else:
        place(output, cond0, self.vecentropy(*goodargs) + log(scale))

    return output
# Buggy code
def entropy(self, *args, **kwds):
    args, loc, _ = self._parse_args(*args, **kwds)
    loc = asarray(loc)
    args = list(map(asarray, args))
    cond0 = self._argcheck(*args) & (loc == loc)
    output = zeros(shape(cond0), "d")
    place(output, (1 - cond0), self.badvalue)
    goodargs = argsreduce(cond0, *args)
    place(output, cond0, self.vecentropy(*goodargs))
    return output


# Traceback (TypeError)
======================================================================
ERROR: test_entropy (test_distributions.TestRvDiscrete)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/warren/gitwork/scipy/scipy/stats/tests/test_distributions.py", line 553, in test_entropy
h = p.entropy()
File "/home/warren/local_scipy/lib/python2.7/site-packages/scipy/stats/distributions.py", line 6769, in entropy
place(output,cond0,self.vecentropy(*goodargs))
File "/home/warren/local_scipy/lib/python2.7/site-packages/numpy/lib/function_base.py", line 1832, in __call__
_res = array(self.ufunc(*newargs),copy=False,
TypeError: function not supported for these types, and can't coerce safely to supported types

----------------------------------------------------------------------

# Fixed code
def entropy(self, *args, **kwds):
    args, loc, _ = self._parse_args(*args, **kwds)
    loc = asarray(loc)
    args = list(map(asarray, args))
    cond0 = self._argcheck(*args) & (loc == loc)
    output = zeros(shape(cond0), "d")
    place(output, (1 - cond0), self.badvalue)
    goodargs = argsreduce(cond0, *args)
    # np.vectorize doesn't work when numargs == 0 in numpy 1.5.1
    if self.numargs == 0:
        place(output, cond0, self._entropy())
    else:
        place(output, cond0, self.vecentropy(*goodargs))

    return output
# Buggy code
def _run(features):
    features = self.features_inputter.make_features(features=features.copy())
    _, predictions = self(features)
    return predictions


# Traceback (TypeError)
runner.export(export_dir='/gdrive/My Drive/nmt/chat50w/models')

INFO:tensorflow:Using parameters:
data:
train_features_file: /gdrive/My Drive/nmt/chat50w/train_tokens.txt
vocabulary: /gdrive/My Drive/nmt/chat50w/vocab.txt
eval:
batch_size: 32
infer:
batch_size: 16
length_bucket_width: 1
model_dir: /gdrive/My Drive/nmt/chat50w/run/
params:
average_loss_in_time: true
decay_params:
max_step: 1000000
warmup_steps: 2000
decay_type: CosineAnnealing
learning_rate: 0.00025
num_hypotheses: 1
optimizer: Adam
score:
batch_size: 64
train:
batch_size: 32
batch_type: examples
length_bucket_width: 1
maximum_features_length: 512
sample_buffer_size: 500000
save_summary_steps: 100

INFO:tensorflow:Restored checkpoint /gdrive/My Drive/nmt/chat50w/run/ckpt-615000
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-35-9a691167a69a> in <module>()
----> 1 runner.export(export_dir='/gdrive/My Drive/nmt/chat50w/models')

14 frames
/usr/local/lib/python3.6/dist-packages/tensorflow_core/python/framework/func_graph.py in wrapper(*args, **kwargs)
966           except Exception as e:  # pylint:disable=broad-except
967             if hasattr(e, "ag_error_metadata"):
--> 968               raise e.ag_error_metadata.to_exception(e)
969             else:
970               raise

TypeError: in converted code:

/usr/local/lib/python3.6/dist-packages/opennmt/models/model.py:238 _run  *
_, predictions = self(features)
/usr/local/lib/python3.6/dist-packages/tensorflow_core/python/keras/engine/base_layer.py:778 __call__
outputs = call_fn(cast_inputs, *args, **kwargs)
/usr/local/lib/python3.6/dist-packages/opennmt/models/language_model.py:57 call  *
ids, length = features["ids"], features["length"]

TypeError: tuple indices must be integers or slices, not str

# Fixed code
def _run(features):
    features = self.features_inputter.make_features(features=features.copy())
    if isinstance(features, (list, tuple)):
        # Special case for unsupervised inputters that always return a tuple (features, labels).
        features = features[0]
    _, predictions = self(features)
    return predictions
# Buggy code
def infer(features_file, estimator, model, config, checkpoint_path=None):
    """Runs inference and prints predictions on the standard output.

    Args:
      features_file: The file to infer from.
      estimator: A `tf.estimator.Estimator`.
      model: A `opennmt.models.Model`.
      config: The configuration.
      checkpoint_path: Path of a specific checkpoint to predict. If `None`, the
        latest is used.
    """
    if "infer" not in config:
        config["infer"] = {}

    batch_size = config["infer"].get("batch_size", 1)
    input_fn = model.input_fn(
        tf.estimator.ModeKeys.PREDICT,
        batch_size,
        config["infer"].get("buffer_size", batch_size * 10),
        config["infer"].get("num_parallel_process_calls", multiprocessing.cpu_count()),
        config["data"],
        features_file,
    )

    for prediction in estimator.predict(
        input_fn=input_fn, checkpoint_path=checkpoint_path
    ):
        model.print_prediction(prediction, params=config["infer"])


# Traceback (UnicodeEncodeError)
Traceback (most recent call last):
[...]
File "opennmt/models/sequence_to_sequence.py", line 233, in print_prediction
print(sentence.decode("utf-8"), file=stream)
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2013' in position 6: ordinal not in range(128)

# Fixed code
def infer(
    features_file, estimator, model, config, checkpoint_path=None, predictions_file=None
):
    """Runs inference and prints predictions on the standard output.

    Args:
      features_file: The file to infer from.
      estimator: A `tf.estimator.Estimator`.
      model: A `opennmt.models.Model`.
      config: The configuration.
      checkpoint_path: Path of a specific checkpoint to predict. If `None`, the
        latest is used.
      predictions_file: If set, predictions are saved in this file.
    """
    if "infer" not in config:
        config["infer"] = {}

    batch_size = config["infer"].get("batch_size", 1)
    input_fn = model.input_fn(
        tf.estimator.ModeKeys.PREDICT,
        batch_size,
        config["infer"].get("buffer_size", batch_size * 10),
        config["infer"].get("num_parallel_process_calls", multiprocessing.cpu_count()),
        config["data"],
        features_file,
    )

    if predictions_file:
        stream = open(predictions_file, "w")
    else:
        stream = sys.stdout

    for prediction in estimator.predict(
        input_fn=input_fn, checkpoint_path=checkpoint_path
    ):
        model.print_prediction(prediction, params=config["infer"], stream=stream)

    if predictions_file:
        stream.close()
# Buggy code
def print_prediction(self, prediction, params=None, stream=None):
    print(prediction["classes"], file=stream)


# Traceback (UnicodeEncodeError)
Traceback (most recent call last):
[...]
File "opennmt/models/sequence_to_sequence.py", line 233, in print_prediction
print(sentence.decode("utf-8"), file=stream)
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2013' in position 6: ordinal not in range(128)

# Fixed code
def print_prediction(self, prediction, params=None, stream=None):
    print_bytes(prediction["classes"], stream=stream)
# Buggy code
def print_prediction(self, prediction, params=None, stream=None):
    tags = prediction["tags"][: prediction["length"]]
    sent = b" ".join(tags)
    print(sent.decode("utf-8"), file=stream)


# Traceback (UnicodeEncodeError)
Traceback (most recent call last):
[...]
File "opennmt/models/sequence_to_sequence.py", line 233, in print_prediction
print(sentence.decode("utf-8"), file=stream)
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2013' in position 6: ordinal not in range(128)

# Fixed code
def print_prediction(self, prediction, params=None, stream=None):
    tags = prediction["tags"][: prediction["length"]]
    sent = b" ".join(tags)
    print_bytes(sent, stream=stream)
# Buggy code
def print_prediction(self, prediction, params=None, stream=None):
    n_best = params and params.get("n_best")
    n_best = n_best or 1

    if n_best > len(prediction["tokens"]):
        raise ValueError("n_best cannot be greater than beam_width")

    for i in range(n_best):
        tokens = prediction["tokens"][i][: prediction["length"][i] - 1]  # Ignore 
.
        sentence = b" ".join(tokens)
        print(sentence.decode("utf-8"), file=stream)


# Traceback (UnicodeEncodeError)
Traceback (most recent call last):
[...]
File "opennmt/models/sequence_to_sequence.py", line 233, in print_prediction
print(sentence.decode("utf-8"), file=stream)
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2013' in position 6: ordinal not in range(128)

# Fixed code
def print_prediction(self, prediction, params=None, stream=None):
    n_best = params and params.get("n_best")
    n_best = n_best or 1

    if n_best > len(prediction["tokens"]):
        raise ValueError("n_best cannot be greater than beam_width")

    for i in range(n_best):
        tokens = prediction["tokens"][i][: prediction["length"][i] - 1]  # Ignore 
.
        sentence = b" ".join(tokens)
        print_bytes(sentence, stream=stream)
# Buggy code
def load_config(config_paths, config=None):
    """Loads configuration files.

    Args:
      config_paths: A list of configuration files.
      config: A (possibly non empty) config dictionary to fill.

    Returns:
      The configuration dictionary.
    """
    if config is None:
        config = {}

    for config_path in config_paths:
        with open(config_path) as config_file:
            subconfig = yaml.load(config_file.read())

            # Add or update section in main configuration.
            for section in subconfig:
                if section in config:
                    config[section].update(subconfig[section])
                else:
                    config[section] = subconfig[section]

    return config


# Traceback (AttributeError)
Traceback (most recent call last):
File "/home/soul/anaconda2/lib/python2.7/runpy.py", line 174, in _run_module_as_main
"__main__", fname, loader, pkg_name)
File "/home/soul/anaconda2/lib/python2.7/runpy.py", line 72, in _run_code
exec code in run_globals
File "/home/soul/projects/opennmt-tf/OpenNMT-tf/bin/main.py", line 275, in <module>
main()
File "/home/soul/projects/opennmt-tf/OpenNMT-tf/bin/main.py", line 225, in main
config = load_config(args.config)
File "opennmt/config.py", line 48, in load_config
config[section].update(subconfig[section])
AttributeError: 'str' object has no attribute 'update'

# Fixed code
def load_config(config_paths, config=None):
    """Loads configuration files.

    Args:
      config_paths: A list of configuration files.
      config: A (possibly non empty) config dictionary to fill.

    Returns:
      The configuration dictionary.
    """
    if config is None:
        config = {}

    for config_path in config_paths:
        with open(config_path) as config_file:
            subconfig = yaml.load(config_file.read())

            # Add or update section in main configuration.
            for section in subconfig:
                if section in config:
                    if isinstance(config[section], dict):
                        config[section].update(subconfig[section])
                    else:
                        config[section] = subconfig[section]
                else:
                    config[section] = subconfig[section]

    return config
# Buggy code
def update_views(self):
    """Update stats views."""
    # Call the father's method
    super(Plugin, self).update_views()

    # Add specifics informations
    # Alert and log
    self.views["used"]["decoration"] = self.get_alert_log(
        self.stats["used"], maximum=self.stats["total"]
    )


# Traceback (RuntimeError)
~$ glances
No swap devices configured
Traceback (most recent call last):
File "/usr/bin/glances", line 33, in <module>
sys.exit(load_entry_point('Glances==3.1.5', 'console_scripts', 'glances')())
File "/usr/lib/python3.7/site-packages/glances/__init__.py", line 143, in main
start(config=config, args=args)
File "/usr/lib/python3.7/site-packages/glances/__init__.py", line 108, in start
mode = GlancesMode(config=config, args=args)
File "/usr/lib/python3.7/site-packages/glances/standalone.py", line 78, in __init__
self.stats.update()
File "/usr/lib/python3.7/site-packages/glances/stats.py", line 234, in update
self._plugins[p].update()
File "/usr/lib/python3.7/site-packages/glances/plugins/glances_plugin.py", line 925, in wrapper
ret = fct(self, *args, **kw)
File "/usr/lib/python3.7/site-packages/glances/plugins/glances_plugin.py", line 935, in wrapper
ret = fct(*args, **kw)
File "/usr/lib/python3.7/site-packages/glances/plugins/glances_quicklook.py", line 84, in update
stats['swap'] = psutil.swap_memory().percent
File "/usr/lib/python3.7/site-packages/psutil/__init__.py", line 1980, in swap_memory
return _psplatform.swap_memory()
File "/usr/lib/python3.7/site-packages/psutil/_pssunos.py", line 150, in swap_memory
raise RuntimeError("'swap -l' failed (retcode=%s)" % p.returncode)
RuntimeError: 'swap -l' failed (retcode=1)

# Fixed code
def update_views(self):
    """Update stats views."""
    # Call the father's method
    super(Plugin, self).update_views()

    # Add specifics informations
    # Alert and log
    if "used" in self.stats and "total" in self.stats:
        self.views["used"]["decoration"] = self.get_alert_log(
            self.stats["used"], maximum=self.stats["total"]
        )
# Buggy code
def set_result(self, result, separator=""):
    """Store the result (string) into the result key of the AMP
    if one_line is true then replace \n by separator
    """
    # self.configs['result'] = unicode(result, 'utf-8').encode('utf-8', errors='replace')
    if self.one_line():
        self.configs["result"] = str(result).replace("\n", separator)
    else:
        self.configs["result"] = str(result)


# Traceback (UnicodeEncodeError)
Exception in thread Thread-7:
Traceback (most recent call last):
File "/usr/lib/python2.7/threading.py", line 801, in __bootstrap_inner
self.run()
File "/usr/lib/python2.7/threading.py", line 754, in run
self.__target(*self.__args, **self.__kwargs)
File "/usr/local/lib/python2.7/dist-packages/glances/amps/glances_amp.py", line 201, in update_wrapper
return self.update(process_list)
File "/usr/local/lib/python2.7/dist-packages/glances/amps/glances_nginx.py", line 83, in update
self.set_result(res.text.rstrip())
File "/usr/local/lib/python2.7/dist-packages/glances/amps/glances_amp.py", line 186, in set_result
self.configs['result'] = str(result)
UnicodeEncodeError: 'ascii' codec can't encode character u'\u25cf' in position 668: ordinal not in range(128)

# Fixed code
def set_result(self, result, separator=""):
    """Store the result (string) into the result key of the AMP
    if one_line is true then replace \n by separator
    """
    if self.one_line():
        self.configs["result"] = u(result).replace("\n", separator)
    else:
        self.configs["result"] = u(result)
# Buggy code
def u(s, errors="replace"):
    if isinstance(s, text_type):
        return s
    return s.decode("utf-8", errors=errors)


# Traceback (UnicodeEncodeError)
Exception in thread Thread-7:
Traceback (most recent call last):
File "/usr/lib/python2.7/threading.py", line 801, in __bootstrap_inner
self.run()
File "/usr/lib/python2.7/threading.py", line 754, in run
self.__target(*self.__args, **self.__kwargs)
File "/usr/local/lib/python2.7/dist-packages/glances/amps/glances_amp.py", line 201, in update_wrapper
return self.update(process_list)
File "/usr/local/lib/python2.7/dist-packages/glances/amps/glances_nginx.py", line 83, in update
self.set_result(res.text.rstrip())
File "/usr/local/lib/python2.7/dist-packages/glances/amps/glances_amp.py", line 186, in set_result
self.configs['result'] = str(result)
UnicodeEncodeError: 'ascii' codec can't encode character u'\u25cf' in position 668: ordinal not in range(128)

# Fixed code
def u(s, errors="replace"):
    if isinstance(s, text_type):
        return s.encode("utf-8", errors=errors)
    return s.decode("utf-8", errors=errors)
# Buggy code
def nativestr(s):
    if isinstance(s, binary_type):
        return s
    return s.encode("utf-8", "replace")


# Traceback (UnicodeEncodeError)
╭─rain@pegasus ~
╰─$ glances
Traceback (most recent call last):
File "/usr/local/bin/glances", line 11, in <module>
sys.exit(main())
File "/usr/local/lib/python2.7/dist-packages/glances/__init__.py", line 140, in main
start(config=config, args=args)
File "/usr/local/lib/python2.7/dist-packages/glances/__init__.py", line 106, in start
mode = GlancesMode(config=config, args=args)
File "/usr/local/lib/python2.7/dist-packages/glances/standalone.py", line 73, in __init__
self.stats.update()
File "/usr/local/lib/python2.7/dist-packages/glances/stats.py", line 224, in update
self._plugins[p].update_stats_history()
File "/usr/local/lib/python2.7/dist-packages/glances/plugins/glances_plugin.py", line 185, in update_stats_history
str(l[item_name]) + '_' + i['name'],
UnicodeEncodeError: 'ascii' codec can't encode character u'\xfd' in position 15: ordinal not in range(128)
╭─rain@pegasus ~
╰─$                                                                                                                                1 ↵

# Fixed code
def nativestr(s):
    if isinstance(s, binary_type):
        return s
    elif isinstance(s, (int, float)):
        return s.__str__()
    else:
        return s.encode("utf-8", "replace")
# Buggy code
def get_alert(self, value):
    """Overwrite the default get_alert method.

    Alert is on signal quality where lower is better...

    :returns: string -- Signal alert
    """
    ret = "OK"
    try:
        if value <= self.get_limit("critical", stat_name=self.plugin_name):
            ret = "CRITICAL"
        elif value <= self.get_limit("warning", stat_name=self.plugin_name):
            ret = "WARNING"
        elif value <= self.get_limit("careful", stat_name=self.plugin_name):
            ret = "CAREFUL"
    except KeyError:
        ret = "DEFAULT"

    return ret


# Traceback (TypeError)
Traceback (most recent call last):
File "/usr/bin/glances", line 11, in <module>
load_entry_point('Glances==3.0.2', 'console_scripts', 'glances')()
File "/usr/lib/python3.7/site-packages/glances/__init__.py", line 140, in main
start(config=config, args=args)
File "/usr/lib/python3.7/site-packages/glances/__init__.py", line 106, in start
mode = GlancesMode(config=config, args=args)
File "/usr/lib/python3.7/site-packages/glances/standalone.py", line 73, in __init__
self.stats.update()
File "/usr/lib/python3.7/site-packages/glances/stats.py", line 226, in update
self._plugins[p].update_views()
File "/usr/lib/python3.7/site-packages/glances/plugins/glances_wifi.py", line 155, in update_views
self.views[i[self.get_key()]]['signal']['decoration'] = self.get_alert(i['signal'])
File "/usr/lib/python3.7/site-packages/glances/plugins/glances_wifi.py", line 136, in get_alert
if value <= self.get_limit('critical', stat_name=self.plugin_name):
TypeError: '<=' not supported between instances of 'NoneType' and 'float'

# Fixed code
def get_alert(self, value):
    """Overwrite the default get_alert method.

    Alert is on signal quality where lower is better...

    :returns: string -- Signal alert
    """
    ret = "OK"
    try:
        if value <= self.get_limit("critical", stat_name=self.plugin_name):
            ret = "CRITICAL"
        elif value <= self.get_limit("warning", stat_name=self.plugin_name):
            ret = "WARNING"
        elif value <= self.get_limit("careful", stat_name=self.plugin_name):
            ret = "CAREFUL"
    except (TypeError, KeyError) as e:
        # Catch TypeError for issue1373
        ret = "DEFAULT"

    return ret
# Buggy code
def get_device_name(device_handle):
    """Get GPU device name"""
    try:
        return pynvml.nvmlDeviceGetName(device_handle)
    except pynvml.NVMlError:
        return "NVIDIA"


# Traceback (TypeError)
import xmlrpc.client
s = xmlrpc.client.ServerProxy("http://localhost:61209")
s.getAll()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3.5/xmlrpc/client.py", line 1092, in __call__
return self.__send(self.__name, args)
File "/usr/lib/python3.5/xmlrpc/client.py", line 1432, in __request
verbose=self.__verbose
File "/usr/lib/python3.5/xmlrpc/client.py", line 1134, in request
return self.single_request(host, handler, request_body, verbose)
File "/usr/lib/python3.5/xmlrpc/client.py", line 1150, in single_request
return self.parse_response(resp)
File "/usr/lib/python3.5/xmlrpc/client.py", line 1322, in parse_response
return u.close()
File "/usr/lib/python3.5/xmlrpc/client.py", line 655, in close
raise Fault(**self._stack[0])
xmlrpc.client.Fault: <Fault 1: "<class 'TypeError'>:b'GeForce GTX 1070' is not JSON serializable">

# Fixed code
def get_device_name(device_handle):
    """Get GPU device name"""
    try:
        return nativestr(pynvml.nvmlDeviceGetName(device_handle))
    except pynvml.NVMlError:
        return "NVIDIA"
# Buggy code
def _load_cache(self):
    """Load cache file and return cached data"""
    # If the cached file exist, read-it
    max_refresh_date = timedelta(days=7)
    cached_data = {}
    try:
        with open(self.cache_file, "rb") as f:
            cached_data = pickle.load(f)
    except Exception as e:
        logger.debug("Cannot read version from cache file: {}".format(e))
    else:
        logger.debug("Read version from cache file")
        if (
            cached_data["installed_version"] != self.installed_version()
            or datetime.now() - cached_data["refresh_date"] > max_refresh_date
        ):
            # Reset the cache if:
            # - the installed version is different
            # - the refresh_date is > max_refresh_date
            cached_data = {}
    return cached_data


# Traceback (IOError)
Exception in thread Thread-7:
Traceback (most recent call last):
File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/threading.py", line 801, in __bootstrap_inner
self.run()
File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/threading.py", line 754, in run
self.__target(*self, **self.__kwargs)
File "/Users/gableroux/.virtualenvs/glances27/lib/python2.7/site-packages/glances/outdated.py", line 163, in _update_pypi_version
self._save_cache()
File "/Users/gableroux/.virtualenvs/glances27/lib/python2.7/site-packages/glances/outdated.py", line 143, in _save_cache
with open(self.cache_file, 'wb') as f:
IOError: [Errno 13] Permission denied: '/Users/gableroux/Library/Caches/glances/glances-version.db'

# Fixed code
def _load_cache(self):
    """Load cache file and return cached data"""
    # If the cached file exist, read-it
    max_refresh_date = timedelta(days=7)
    cached_data = {}
    try:
        with open(self.cache_file, "rb") as f:
            cached_data = pickle.load(f)
    except Exception as e:
        logger.debug(
            "Cannot read version from cache file: {} ({})".format(self.cache_file, e)
        )
    else:
        logger.debug("Read version from cache file")
        if (
            cached_data["installed_version"] != self.installed_version()
            or datetime.now() - cached_data["refresh_date"] > max_refresh_date
        ):
            # Reset the cache if:
            # - the installed version is different
            # - the refresh_date is > max_refresh_date
            cached_data = {}
    return cached_data
# Buggy code
def _save_cache(self):
    """Save data to the cache file."""
    # Create the cache directory
    safe_makedirs(self.cache_dir)

    # Create/overwrite the cache file
    with open(self.cache_file, "wb") as f:
        pickle.dump(self.data, f)


# Traceback (IOError)
Exception in thread Thread-7:
Traceback (most recent call last):
File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/threading.py", line 801, in __bootstrap_inner
self.run()
File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/threading.py", line 754, in run
self.__target(*self, **self.__kwargs)
File "/Users/gableroux/.virtualenvs/glances27/lib/python2.7/site-packages/glances/outdated.py", line 163, in _update_pypi_version
self._save_cache()
File "/Users/gableroux/.virtualenvs/glances27/lib/python2.7/site-packages/glances/outdated.py", line 143, in _save_cache
with open(self.cache_file, 'wb') as f:
IOError: [Errno 13] Permission denied: '/Users/gableroux/Library/Caches/glances/glances-version.db'

# Fixed code
def _save_cache(self):
    """Save data to the cache file."""
    # Create the cache directory
    safe_makedirs(self.cache_dir)

    # Create/overwrite the cache file
    try:
        with open(self.cache_file, "wb") as f:
            pickle.dump(self.data, f)
    except Exception as e:
        logger.error(
            "Cannot write version to cache file {} ({})".format(self.cache_file, e)
        )
# Buggy code
def __init__(self):
    """Init sensors stats."""
    # Temperatures
    try:
        # psutil>=5.1.0 is required
        self.stemps = psutil.sensors_temperatures()
    except AttributeError:
        logger.warning("PsUtil 5.1.0 or higher is needed to grab temperatures sensors")
        self.initok = False
        self.stemps = {}
    else:
        self.initok = True

    # Fans
    try:
        # psutil>=5.2.0 is required
        self.sfans = psutil.sensors_fans()
    except AttributeError:
        logger.warning("PsUtil 5.2.0 or higher is needed to grab fans sensors")
        self.sfans = {}

    # Init the stats
    self.reset()


# Traceback (OSError)
Traceback (most recent call last):
File "/usr/local/bin/glances", line 11, in <module>
load_entry_point('Glances==2.8.8', 'console_scripts', 'glances')()
File "/usr/local/lib/python2.7/site-packages/glances/__init__.py", line 225, in main
start_standalone(config=config, args=args)
File "/usr/local/lib/python2.7/site-packages/glances/__init__.py", line 105, in start_standalone
standalone = GlancesStandalone(config=config, args=args)
File "/usr/local/lib/python2.7/site-packages/glances/standalone.py", line 43, in __init__
self.stats = GlancesStats(config=config, args=args)
File "/usr/local/lib/python2.7/site-packages/glances/stats.py", line 43, in __init__
self.load_modules(self.args)
File "/usr/local/lib/python2.7/site-packages/glances/stats.py", line 77, in load_modules
self.load_plugins(args=args)
File "/usr/local/lib/python2.7/site-packages/glances/stats.py", line 96, in load_plugins
plugin = __import__(os.path.basename(item)[:-3])
File "/usr/local/lib/python2.7/site-packages/glances/plugins/glances_batpercent.py", line 38, in <module>
psutil.sensors_battery()
File "/usr/local/lib/python2.7/site-packages/psutil/__init__.py", line 2263, in sensors_battery
return _psplatform.sensors_battery()
File "/usr/local/lib/python2.7/site-packages/psutil/_psbsd.py", line 411, in sensors_battery
percent, minsleft, power_plugged = cext.sensors_battery()
OSError: [Errno 2] No such file or directory

# Fixed code
def __init__(self):
    """Init sensors stats."""
    # Temperatures
    self.initok = False
    self.stemps = {}
    try:
        # psutil>=5.1.0 is required
        self.stemps = psutil.sensors_temperatures()
    except AttributeError:
        logger.warning("PsUtil 5.1.0 or higher is needed to grab temperatures sensors")
    except OSError as e:
        # FreeBSD: If oid 'hw.acpi.battery' not present, Glances wont start #1055
        logger.error("Can not grab temperatures sensors ({})".format(e))
    else:
        self.initok = True

    # Fans
    self.sfans = {}
    try:
        # psutil>=5.2.0 is required
        self.sfans = psutil.sensors_fans()
    except AttributeError:
        logger.warning("PsUtil 5.2.0 or higher is needed to grab fans sensors")
    except OSError as e:
        logger.error("Can not grab fans sensors ({})".format(e))

    # Init the stats
    self.reset()
# Buggy code
def get_install_requires():
    requires = ["psutil>=2.0.0"]
    if sys.platform.startswith("win"):
        requires.append("bottle")

    return requires


# Traceback (OSError)
Traceback (most recent call last):
File "/usr/local/bin/glances", line 11, in <module>
load_entry_point('Glances==2.8.8', 'console_scripts', 'glances')()
File "/usr/local/lib/python2.7/site-packages/glances/__init__.py", line 225, in main
start_standalone(config=config, args=args)
File "/usr/local/lib/python2.7/site-packages/glances/__init__.py", line 105, in start_standalone
standalone = GlancesStandalone(config=config, args=args)
File "/usr/local/lib/python2.7/site-packages/glances/standalone.py", line 43, in __init__
self.stats = GlancesStats(config=config, args=args)
File "/usr/local/lib/python2.7/site-packages/glances/stats.py", line 43, in __init__
self.load_modules(self.args)
File "/usr/local/lib/python2.7/site-packages/glances/stats.py", line 77, in load_modules
self.load_plugins(args=args)
File "/usr/local/lib/python2.7/site-packages/glances/stats.py", line 96, in load_plugins
plugin = __import__(os.path.basename(item)[:-3])
File "/usr/local/lib/python2.7/site-packages/glances/plugins/glances_batpercent.py", line 38, in <module>
psutil.sensors_battery()
File "/usr/local/lib/python2.7/site-packages/psutil/__init__.py", line 2263, in sensors_battery
return _psplatform.sensors_battery()
File "/usr/local/lib/python2.7/site-packages/psutil/_psbsd.py", line 411, in sensors_battery
percent, minsleft, power_plugged = cext.sensors_battery()
OSError: [Errno 2] No such file or directory

# Fixed code
def get_install_requires():
    requires = ["psutil>=5.3.0"]
    if sys.platform.startswith("win"):
        requires.append("bottle")

    return requires
# Buggy code
def end():
    """Stop Glances."""
    if core.is_standalone():
        # Stop the standalone (CLI)
        standalone.end()
        logger.info("Stop Glances (with CTRL-C)")
    elif core.is_client():
        # Stop the client
        client.end()
        logger.info("Stop Glances client (with CTRL-C)")
    elif core.is_server():
        # Stop the server
        server.end()
        logger.info("Stop Glances server (with CTRL-C)")
    elif core.is_webserver():
        # Stop the Web server
        webserver.end()
        logger.info("Stop Glances web server(with CTRL-C)")

    # The end...
    sys.exit(0)


# Traceback (NameError)
C:\Windows\system32>glances
Glances web server started on http://0.0.0.0:61209/
Traceback (most recent call last):
File "C:\Python27\Scripts\glances-script.py", line 11, in <module>
load_entry_point('Glances==2.8.2', 'console_scripts', 'glances')()
File "c:\python27\lib\site-packages\glances\__init__.py", line 238, in main
start_webserver(config=config, args=args)
File "c:\python27\lib\site-packages\glances\__init__.py", line 196, in start_webserver
webserver.serve_forever()
File "c:\python27\lib\site-packages\glances\webserver.py", line 48, in serve_forever
self.web.start(self.stats)
File "c:\python27\lib\site-packages\glances\outputs\glances_bottle.py", line 148, in start
self._app.run(host=self.args.bind_address, port=self.args.port, quiet=not self.args.debug)
File "C:\Python27\Scripts\bottle.py", line 755, in run
run(self, **kwargs)
File "C:\Python27\Scripts\bottle.py", line 3127, in run
server.run(app)
File "C:\Python27\Scripts\bottle.py", line 2782, in run
srv.serve_forever()
File "c:\python27\lib\SocketServer.py", line 231, in serve_forever
poll_interval)
File "c:\python27\lib\SocketServer.py", line 150, in _eintr_retry
return func(*args)
File "c:\python27\lib\site-packages\glances\__init__.py", line 68, in __signal_handler
end()
File "c:\python27\lib\site-packages\glances\__init__.py", line 75, in end
standalone.end()
NameError: global name 'standalone' is not defined

# Fixed code
def end():
    """Stop Glances."""
    if core.is_standalone() and not WINDOWS:
        # Stop the standalone (CLI)
        standalone.end()
        logger.info("Stop Glances (with CTRL-C)")
    elif core.is_client() and not WINDOWS:
        # Stop the client
        client.end()
        logger.info("Stop Glances client (with CTRL-C)")
    elif core.is_server():
        # Stop the server
        server.end()
        logger.info("Stop Glances server (with CTRL-C)")
    elif core.is_webserver() or (core.is_standalone() and WINDOWS):
        # Stop the Web server
        webserver.end()
        logger.info("Stop Glances web server(with CTRL-C)")

    # The end...
    sys.exit(0)
# Buggy code
def end():
    """Stop Glances."""
    if core.is_standalone():
        # Stop the standalone (CLI)
        standalone.end()
        logger.info("Stop Glances (with CTRL-C)")
    elif core.is_client():
        # Stop the client
        client.end()
        logger.info("Stop Glances client (with CTRL-C)")
    elif core.is_server():
        # Stop the server
        server.end()
        logger.info("Stop Glances server (with CTRL-C)")
    elif core.is_webserver() or core.is_standalone():
        # Stop the Web server
        webserver.end()
        logger.info("Stop Glances web server(with CTRL-C)")

    # The end...
    sys.exit(0)


# Traceback (NameError)
C:\Windows\system32>glances
Glances web server started on http://0.0.0.0:61209/
Traceback (most recent call last):
File "C:\Python27\Scripts\glances-script.py", line 11, in <module>
load_entry_point('Glances==2.8.2', 'console_scripts', 'glances')()
File "c:\python27\lib\site-packages\glances\__init__.py", line 238, in main
start_webserver(config=config, args=args)
File "c:\python27\lib\site-packages\glances\__init__.py", line 196, in start_webserver
webserver.serve_forever()
File "c:\python27\lib\site-packages\glances\webserver.py", line 48, in serve_forever
self.web.start(self.stats)
File "c:\python27\lib\site-packages\glances\outputs\glances_bottle.py", line 148, in start
self._app.run(host=self.args.bind_address, port=self.args.port, quiet=not self.args.debug)
File "C:\Python27\Scripts\bottle.py", line 755, in run
run(self, **kwargs)
File "C:\Python27\Scripts\bottle.py", line 3127, in run
server.run(app)
File "C:\Python27\Scripts\bottle.py", line 2782, in run
srv.serve_forever()
File "c:\python27\lib\SocketServer.py", line 231, in serve_forever
poll_interval)
File "c:\python27\lib\SocketServer.py", line 150, in _eintr_retry
return func(*args)
File "c:\python27\lib\site-packages\glances\__init__.py", line 68, in __signal_handler
end()
File "c:\python27\lib\site-packages\glances\__init__.py", line 75, in end
standalone.end()
NameError: global name 'standalone' is not defined

# Fixed code
def end():
    """Stop Glances."""
    if core.is_standalone() and not WINDOWS:
        # Stop the standalone (CLI)
        standalone.end()
        logger.info("Stop Glances (with CTRL-C)")
    elif core.is_client() and not WINDOWS:
        # Stop the client
        client.end()
        logger.info("Stop Glances client (with CTRL-C)")
    elif core.is_server():
        # Stop the server
        server.end()
        logger.info("Stop Glances server (with CTRL-C)")
    elif core.is_webserver():
        # Stop the Web server
        webserver.end()
        logger.info("Stop Glances web server(with CTRL-C)")

    # The end...
    sys.exit(0)
# Buggy code
def run(self):
    """Function called to grab stats.
    Infinite loop, should be stopped by calling the stop() method"""

    for k, v in iteritems(self.AWS_EC2_API_METADATA):
        r_url = "{}/{}".format(self.AWS_EC2_API_URL, v)
        try:
            # Local request, a timeout of 3 seconds is OK
            r = requests.get(r_url, timeout=3)
        except Exception as e:
            logger.debug(
                "cloud plugin - Cannot connect to the AWS EC2 API {}: {}".format(
                    r_url, e
                )
            )
            break
        else:
            if r.ok:
                self._stats[k] = r.content


# Traceback (NameError)
Exception in thread Thread-1:
Traceback (most recent call last):
File "/usr/lib/python3.4/site-packages/glances/plugins/glances_cloud.py", line 156, in run
r = requests.get(r_url, timeout=3)
NameError: name 'requests' is not defined

# Fixed code
def run(self):
    """Function called to grab stats.
    Infinite loop, should be stopped by calling the stop() method"""

    if not cloud_tag:
        logger.debug("cloud plugin - Requests lib is not installed")
        self.stop()
        return False

    for k, v in iteritems(self.AWS_EC2_API_METADATA):
        r_url = "{}/{}".format(self.AWS_EC2_API_URL, v)
        try:
            # Local request, a timeout of 3 seconds is OK
            r = requests.get(r_url, timeout=3)
        except Exception as e:
            logger.debug(
                "cloud plugin - Cannot connect to the AWS EC2 API {}: {}".format(
                    r_url, e
                )
            )
            break
        else:
            if r.ok:
                self._stats[k] = r.content

    return True