gurudesh/pytracebugs huggingface dataset:
# Buggy code
def __init__(self, *args, **kwargs):
    scene.visuals.Line.__init__(self, *args, **kwargs)

    # initialize point markers
    self.markers = scene.visuals.Markers()
    self.marker_colors = np.ones((len(self.pos), 4), dtype=np.float32)
    self.markers.set_data(pos=self.pos, symbol="s", edge_color="red", size=6)
    self.selected_point = None
    self.selected_index = -1
    # snap grid size
    self.gridsize = 10


# Traceback (AttributeError)
Traceback (most recent call last):
File "/home/........../basics/visuals/line_draw.py", line 178, in <module>
win = Canvas()
File "/home/........../basics/visuals/line_draw.py", line 154, in __init__
self.pos = np.zeros((n, 3), dtype=np.float32)
File "/home/........../lib/python3.6/site-packages/vispy/util/frozen.py", line 16, in __setattr__
'attributes' % (key, self))
AttributeError: 'pos' is not an attribute of class <Canvas (PyQt5) at 0x7f4334088f98>. Call "unfreeze()" to allow addition of new attributes

Process finished with exit code 1

# Fixed code
def __init__(self, *args, **kwargs):
    scene.visuals.Line.__init__(self, *args, **kwargs)
    self.unfreeze()
    # initialize point markers
    self.markers = scene.visuals.Markers(parent=self)
    self.marker_colors = np.ones((len(self.pos), 4), dtype=np.float32)
    self.markers.set_data(pos=self.pos, symbol="s", edge_color="red", size=6)
    self.selected_point = None
    self.selected_index = -1
    # snap grid size
    self.gridsize = 10
    self.freeze()
# Buggy code
def select_point(self, event, radius=5):
    """
    Get line point close to mouse pointer and its index

    Parameters
    ----------
    event : the mouse event being processed
    radius : scalar
        max. distance in pixels between mouse and line point to be accepted
    return: (numpy.array, int)
        picked point and index of the point in the pos array
    """

    # position in scene/document coordinates
    pos_scene = event.pos[:3]

    # project mouse radius from screen coordinates to document coordinates
    mouse_radius = (
        event.visual_to_canvas.imap(np.array([radius, radius, radius]))
        - event.visual_to_canvas.imap(np.array([0, 0, 0]))
    )[0]
    # print("Mouse radius in document units: ", mouse_radius)

    # find first point within mouse_radius
    index = 0
    for p in self.pos:
        if np.linalg.norm(pos_scene - p) < mouse_radius:
            # print p, index
            # point found, return point and its index
            return p, index
        index += 1
    # no point found, return None
    return None, -1


# Traceback (AttributeError)
Traceback (most recent call last):
File "/home/........../basics/visuals/line_draw.py", line 178, in <module>
win = Canvas()
File "/home/........../basics/visuals/line_draw.py", line 154, in __init__
self.pos = np.zeros((n, 3), dtype=np.float32)
File "/home/........../lib/python3.6/site-packages/vispy/util/frozen.py", line 16, in __setattr__
'attributes' % (key, self))
AttributeError: 'pos' is not an attribute of class <Canvas (PyQt5) at 0x7f4334088f98>. Call "unfreeze()" to allow addition of new attributes

Process finished with exit code 1

# Fixed code
def select_point(self, pos_scene, radius=5):
    """
    Get line point close to mouse pointer and its index

    Parameters
    ----------
    event : the mouse event being processed
    radius : scalar
        max. distance in pixels between mouse and line point to be accepted
    return: (numpy.array, int)
        picked point and index of the point in the pos array
    """

    # project mouse radius from screen coordinates to document coordinates

    mouse_radius = 6
    # print("Mouse radius in document units: ", mouse_radius)

    # find first point within mouse_radius
    index = 0
    for p in self.pos:
        if np.linalg.norm(pos_scene[:3] - p) < mouse_radius:
            # print p, index
            # point found, return point and its index
            return p, index
        index += 1
    # no point found, return None
    return None, -1
# Buggy code
def on_mouse_press(self, event):
    self.print_mouse_event(event, "Mouse press")
    pos_scene = event.pos[:3]

    # find closest point to mouse and select it
    self.selected_point, self.selected_index = self.select_point(event)

    # if no point was clicked add a new one
    if self.selected_point is None:
        print("adding point", len(self.pos))
        self._pos = np.append(self.pos, [pos_scene], axis=0)
        self.set_data(pos=self.pos)
        self.marker_colors = np.ones((len(self.pos), 4), dtype=np.float32)
        self.selected_point = self.pos[-1]
        self.selected_index = len(self.pos) - 1

    # update markers and highlights
    self.update_markers(self.selected_index)


# Traceback (AttributeError)
Traceback (most recent call last):
File "/home/........../basics/visuals/line_draw.py", line 178, in <module>
win = Canvas()
File "/home/........../basics/visuals/line_draw.py", line 154, in __init__
self.pos = np.zeros((n, 3), dtype=np.float32)
File "/home/........../lib/python3.6/site-packages/vispy/util/frozen.py", line 16, in __setattr__
'attributes' % (key, self))
AttributeError: 'pos' is not an attribute of class <Canvas (PyQt5) at 0x7f4334088f98>. Call "unfreeze()" to allow addition of new attributes

Process finished with exit code 1

# Fixed code
def on_mouse_press(self, pos_scene):
    # self.print_mouse_event(event, 'Mouse press')
    # pos_scene = event.pos[:3]

    # find closest point to mouse and select it
    self.selected_point, self.selected_index = self.select_point(pos_scene)

    # if no point was clicked add a new one
    if self.selected_point is None:
        print("adding point", len(self.pos))
        self._pos = np.append(self.pos, [pos_scene[:3]], axis=0)
        self.set_data(pos=self.pos)
        self.marker_colors = np.ones((len(self.pos), 4), dtype=np.float32)
        self.selected_point = self.pos[-1]
        self.selected_index = len(self.pos) - 1

    # update markers and highlights
    self.update_markers(self.selected_index)
# Buggy code
def on_mouse_move(self, event):
    # left mouse button
    if event.button == 1:
        # self.print_mouse_event(event, 'Mouse drag')
        if self.selected_point is not None:
            pos_scene = event.pos
            # update selected point to new position given by mouse
            self.selected_point[0] = round(pos_scene[0] / self.gridsize) * self.gridsize
            self.selected_point[1] = round(pos_scene[1] / self.gridsize) * self.gridsize
            self.set_data(pos=self.pos)
            self.update_markers(self.selected_index)

    else:
        #  if no button is pressed, just highlight the marker that would be
        # selected on click
        hl_point, hl_index = self.select_point(event)
        self.update_markers(hl_index, highlight_color=(0.5, 0.5, 1.0, 1.0))
        self.update()


# Traceback (AttributeError)
Traceback (most recent call last):
File "/home/........../basics/visuals/line_draw.py", line 178, in <module>
win = Canvas()
File "/home/........../basics/visuals/line_draw.py", line 154, in __init__
self.pos = np.zeros((n, 3), dtype=np.float32)
File "/home/........../lib/python3.6/site-packages/vispy/util/frozen.py", line 16, in __setattr__
'attributes' % (key, self))
AttributeError: 'pos' is not an attribute of class <Canvas (PyQt5) at 0x7f4334088f98>. Call "unfreeze()" to allow addition of new attributes

Process finished with exit code 1

# Fixed code
def on_mouse_move(self, pos_scene):
    if self.selected_point is not None:
        # update selected point to new position given by mouse
        self.selected_point[0] = round(pos_scene[0] / self.gridsize) * self.gridsize
        self.selected_point[1] = round(pos_scene[1] / self.gridsize) * self.gridsize
        self.set_data(pos=self.pos)
        self.update_markers(self.selected_index)
# Buggy code
def __init__(self):
    scene.SceneCanvas.__init__(self, keys="interactive", size=(800, 800))

    # Create some initial points
    n = 7
    self.pos = np.zeros((n, 3), dtype=np.float32)
    self.pos[:, 0] = np.linspace(-50, 50, n)
    self.pos[:, 1] = np.random.normal(size=n, scale=10, loc=0)

    # create new editable line
    self.line = EditLineVisual(
        pos=self.pos, color="w", width=3, antialias=True, method="gl"
    )

    self.view = self.central_widget.add_view()
    self.view.camera = scene.PanZoomCamera(rect=(-100, -100, 200, 200), aspect=1.0)
    # the left mouse button pan has to be disabled in the camera, as it
    # interferes with dragging line points
    # Proposed change in camera: make mouse buttons configurable
    self.view.camera._viewbox.events.mouse_move.disconnect(
        self.view.camera.viewbox_mouse_event
    )

    self.view.add(self.line)
    self.show()
    self.selected_point = None
    scene.visuals.GridLines(parent=self.view.scene)


# Traceback (AttributeError)
Traceback (most recent call last):
File "/home/........../basics/visuals/line_draw.py", line 178, in <module>
win = Canvas()
File "/home/........../basics/visuals/line_draw.py", line 154, in __init__
self.pos = np.zeros((n, 3), dtype=np.float32)
File "/home/........../lib/python3.6/site-packages/vispy/util/frozen.py", line 16, in __setattr__
'attributes' % (key, self))
AttributeError: 'pos' is not an attribute of class <Canvas (PyQt5) at 0x7f4334088f98>. Call "unfreeze()" to allow addition of new attributes

Process finished with exit code 1

# Fixed code
def __init__(self):
    scene.SceneCanvas.__init__(self, keys="interactive", size=(800, 800))

    # Create some initial points
    n = 7
    self.unfreeze()
    self.pos = np.zeros((n, 3), dtype=np.float32)
    self.pos[:, 0] = np.linspace(-50, 50, n)
    self.pos[:, 1] = np.random.normal(size=n, scale=10, loc=0)

    # create new editable line
    self.line = EditLineVisual(
        pos=self.pos, color="w", width=3, antialias=True, method="gl"
    )

    self.view = self.central_widget.add_view()
    self.view.camera = scene.PanZoomCamera(rect=(-100, -100, 200, 200), aspect=1.0)
    # the left mouse button pan has to be disabled in the camera, as it
    # interferes with dragging line points
    # Proposed change in camera: make mouse buttons configurable
    self.view.camera._viewbox.events.mouse_move.disconnect(
        self.view.camera.viewbox_mouse_event
    )

    self.view.add(self.line)
    self.show()
    self.selected_point = None
    scene.visuals.GridLines(parent=self.view.scene)
    self.freeze()
# Buggy code
def keys_check(event):
    use_name = event.key.name.lower()
    if use_name in self._keys_check:
        self._keys_check[use_name]()


# Traceback (AttributeError)
WARNING: Traceback (most recent call last):
File ".\examples\demo\gloo\brain.py", line 156, in <module>
app.run()
File "D:\Git\vispy\vispy\app\_default_app.py", line 54, in run
return default_app.run()
File "D:\Git\vispy\vispy\app\application.py", line 88, in run
return self._backend._vispy_run()
File "D:\Git\vispy\vispy\app\backends\_qt.py", line 175, in _vispy_run
return app.exec_()
File "D:\Git\vispy\vispy\app\backends\_qt.py", line 391, in keyPressEvent
self._keyEvent(self._vispy_canvas.events.key_press, ev)
File "D:\Git\vispy\vispy\app\backends\_qt.py", line 406, in _keyEvent
func(native=ev, key=key, text=text_type(ev.text()), modifiers=mod)
File "D:\Git\vispy\vispy\util\event.py", line 418, in __call__
self._invoke_callback(cb, event)
File "D:\Git\vispy\vispy\util\event.py", line 446, in _invoke_callback
self, cb_event=(cb, event))
<< caught exception here: >>
File "D:\Git\vispy\vispy\util\event.py", line 435, in _invoke_callback
cb(event)
File "D:\Git\vispy\vispy\app\canvas.py", line 220, in keys_check
use_name = event.key.name.lower()
AttributeError: 'NoneType' object has no attribute 'name'
WARNING: Error invoking callback <function keys_check at 0x00000000067C73C8> for
event: <KeyEvent blocked=False handled=False key=None modifiers=() native=<PyQt
4.QtGui.QKeyEvent object at 0x0000000007230BF8> source=<Vispy canvas (PyQt4 (qt)
backend) at 0x72a10f0L> sources=[<Vispy canvas (PyQt4 (qt) backend) at 0x72a10f
0L>] text=² type=key_press>

# Fixed code
def keys_check(event):
    if event.key is not None:
        use_name = event.key.name.lower()
        if use_name in self._keys_check:
            self._keys_check[use_name]()
# Buggy code
def on_draw(self, event):
    self.framebuffer.activate()
    set_viewport(0, 0, 512, 512)
    clear(color=True, depth=True)
    set_state(depth_test=True)
    self.cube.draw("triangles", self.indices)
    self.framebuffer.deactivate()
    clear(color=True)
    set_state(depth_test=False)
    self.quad.draw("triangle_strip")


# Traceback (IndexError)
cyrille@Cyrille-ASUS:~/git/vispy/examples/demo/gloo$ python realtime_signals.py ERROR: Could not set variable 'a_position' with value [-0.0093575   0.1638512   0.15590386 ...,  0.07139178 -0.14649338
0.06221156]
Traceback (most recent call last):
File "realtime_signals.py", line 162, in <module>
c = Canvas()
File "realtime_signals.py", line 123, in __init__
self.program['a_position'] = y.ravel()
File "/home/cyrille/git/vispy/vispy/gloo/program.py", line 353, in __setitem__
self._attributes[name].set_data(data)
File "/home/cyrille/git/vispy/vispy/gloo/variable.py", line 326, in set_data
assert count == data.shape[1]
IndexError: tuple index out of range

# Fixed code
def on_draw(self, event):
    self.framebuffer.activate()
    set_viewport(0, 0, 512, 512)
    clear(color=True, depth=True)
    set_state(depth_test=True)
    self.cube.draw("triangles", self.indices)
    self.framebuffer.deactivate()
    set_viewport(0, 0, *self.size)
    clear(color=True)
    set_state(depth_test=False)
    self.quad.draw("triangle_strip")
# Buggy code
def __init__(self):
    app.Canvas.__init__(self, title="Use your wheel to zoom!", keys="interactive")
    self.program = gloo.Program(VERT_SHADER, FRAG_SHADER)
    self.program["a_position"] = y.ravel()
    self.program["a_color"] = color
    self.program["a_index"] = index
    self.program["u_scale"] = (1.0, 1.0)
    self.program["u_size"] = (nrows, ncols)
    self.program["u_n"] = n

    self._timer = app.Timer("auto", connect=self.on_timer, start=True)


# Traceback (IndexError)
cyrille@Cyrille-ASUS:~/git/vispy/examples/demo/gloo$ python realtime_signals.py ERROR: Could not set variable 'a_position' with value [-0.0093575   0.1638512   0.15590386 ...,  0.07139178 -0.14649338
0.06221156]
Traceback (most recent call last):
File "realtime_signals.py", line 162, in <module>
c = Canvas()
File "realtime_signals.py", line 123, in __init__
self.program['a_position'] = y.ravel()
File "/home/cyrille/git/vispy/vispy/gloo/program.py", line 353, in __setitem__
self._attributes[name].set_data(data)
File "/home/cyrille/git/vispy/vispy/gloo/variable.py", line 326, in set_data
assert count == data.shape[1]
IndexError: tuple index out of range

# Fixed code
def __init__(self):
    app.Canvas.__init__(self, title="Use your wheel to zoom!", keys="interactive")
    self.program = gloo.Program(VERT_SHADER, FRAG_SHADER)
    self.program["a_position"] = y.reshape(-1, 1)
    self.program["a_color"] = color
    self.program["a_index"] = index
    self.program["u_scale"] = (1.0, 1.0)
    self.program["u_size"] = (nrows, ncols)
    self.program["u_n"] = n

    self._timer = app.Timer("auto", connect=self.on_timer, start=True)
# Buggy code
def __init__(self):
    app.Canvas.__init__(self, title="Spacy", keys="interactive")
    self.size = 800, 600

    self.program = gloo.Program(vertex, fragment)
    self.view = np.eye(4, dtype=np.float32)
    self.model = np.eye(4, dtype=np.float32)
    self.projection = np.eye(4, dtype=np.float32)

    self.timer = app.Timer("auto", connect=self.update, start=True)

    # Set uniforms (some are set later)
    self.program["u_model"] = self.model
    self.program["u_view"] = self.view

    # Set attributes
    self.program["a_position"] = np.zeros((N, 3), np.float32)
    self.program["a_offset"] = np.zeros((N,), np.float32)

    # Init
    self._timeout = 0
    self._active_block = 0
    for i in range(NBLOCKS):
        self._generate_stars()
    self._timeout = time.time() + SPEED


# Traceback (IndexError)
cyrille@Cyrille-ASUS:~/git/vispy/examples/demo/gloo$ python realtime_signals.py ERROR: Could not set variable 'a_position' with value [-0.0093575   0.1638512   0.15590386 ...,  0.07139178 -0.14649338
0.06221156]
Traceback (most recent call last):
File "realtime_signals.py", line 162, in <module>
c = Canvas()
File "realtime_signals.py", line 123, in __init__
self.program['a_position'] = y.ravel()
File "/home/cyrille/git/vispy/vispy/gloo/program.py", line 353, in __setitem__
self._attributes[name].set_data(data)
File "/home/cyrille/git/vispy/vispy/gloo/variable.py", line 326, in set_data
assert count == data.shape[1]
IndexError: tuple index out of range

# Fixed code
def __init__(self):
    app.Canvas.__init__(self, title="Spacy", keys="interactive")
    self.size = 800, 600

    self.program = gloo.Program(vertex, fragment)
    self.view = np.eye(4, dtype=np.float32)
    self.model = np.eye(4, dtype=np.float32)
    self.projection = np.eye(4, dtype=np.float32)

    self.timer = app.Timer("auto", connect=self.update, start=True)

    # Set uniforms (some are set later)
    self.program["u_model"] = self.model
    self.program["u_view"] = self.view

    # Set attributes
    self.program["a_position"] = np.zeros((N, 3), np.float32)
    self.program["a_offset"] = np.zeros((N, 1), np.float32)

    # Init
    self._timeout = 0
    self._active_block = 0
    for i in range(NBLOCKS):
        self._generate_stars()
    self._timeout = time.time() + SPEED
# Buggy code
def __init__(self, axis):
    self.axis = axis


# Traceback (IndexError)
Traceback (most recent call last):
File "oscilloscope.py", line 138, in on_paint
visual.draw(transform)
File "oscilloscope.py", line 79, in draw
self.program.uniforms['color'] = self.color
File "../vispy/oogl/program_inputs.py", line 43, in __setitem__
self._set(k, v)
File "../vispy/oogl/program_inputs.py", line 94, in _set
self._apply(name, value)
File "../vispy/oogl/program_inputs.py", line 198, in _apply
_name, length, type = gl.glGetActiveUniform(self._program.handle, loc)
File "/usr/locaL/Cellar/python/2.7.5/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/OpenGL/latebind.py", line 61, in __call__
return self.wrapperFunction( self.baseFunction, *args, **named )
File "/usr/locaL/Cellar/python/2.7.5/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/OpenGL/GL/VERSION/GL_2_0.py", line 213, in glGetActiveUniform
raise IndexError( 'Index %s out of range 0 to %i' % (index, max_index - 1, ) )
IndexError: Index 4 out of range 0 to 1
Error invoking callback for event: <PaintEvent blocked=False handled=False native=None region=None source=<__main__.Canvas object at 0x107548210> sources=[<__main__.Canvas object at 0x107548210>] type=paint>
(0.1, 1.0, 0.1, 1.953125000000001e-11)```

# Fixed code
def __init__(
    self, nbins=10, steps=None, trim=True, integer=False, symmetric=False, prune=None
):
    """
    Keyword args:
    *nbins*
        Maximum number of intervals; one less than max number of ticks.
    *steps*
        Sequence of nice numbers starting with 1 and ending with 10;
        e.g., [1, 2, 4, 5, 10]
    *integer*
        If True, ticks will take only integer values.
    *symmetric*
        If True, autoscaling will result in a range symmetric
        about zero.
    *prune*
        ['lower' | 'upper' | 'both' | None]
        Remove edge ticks -- useful for stacked or ganged plots
        where the upper tick of one axes overlaps with the lower
        tick of the axes above it.
        If prune=='lower', the smallest tick will
        be removed.  If prune=='upper', the largest tick will be
        removed.  If prune=='both', the largest and smallest ticks
        will be removed.  If prune==None, no ticks will be removed.
    """
    self._nbins = int(nbins)
    self._trim = trim
    self._integer = integer
    self._symmetric = symmetric
    if prune is not None and prune not in ["upper", "lower", "both"]:
        raise ValueError("prune must be 'upper', 'lower', 'both', or None")
    self._prune = prune
    if steps is None:
        steps = [1, 2, 2.5, 3, 4, 5, 6, 8, 10]
    else:
        if int(steps[-1]) != 10:
            steps = list(steps)
            steps.append(10)
    self._steps = steps
    self._integer = integer
    if self._integer:
        self._steps = [n for n in self._steps if divmod(n, 1)[1] < 0.001]
# Buggy code
def _pack_parameter(
    parameter_id, params, customized=False, trial_job_id=None, parameter_index=None
):
    _trial_params[parameter_id] = params
    ret = {
        "parameter_id": parameter_id,
        "parameter_source": "customized" if customized else "algorithm",
        "parameters": params,
    }
    if trial_job_id is not None:
        ret["trial_job_id"] = trial_job_id
    if parameter_index is not None:
        ret["parameter_index"] = parameter_index
    else:
        ret["parameter_index"] = 0
    return json_tricks.dumps(ret)


# Traceback (ValueError)
Using TensorFlow backend.
Traceback (most recent call last):
File "test.py", line 164, in <module>
train(ARGS, RECEIVED_PARAMS)
File "test.py", line 136, in train
validation_data=(x_test, y_test), callbacks=[SendMetrics(), TensorBoard(log_dir=TENSORBOARD_DIR)])
File "/home/msalz/venv_nni_dev/lib64/python3.6/site-packages/keras/engine/training.py", line 1178, in fit
validation_freq=validation_freq)
File "/home/msalz/venv_nni_dev/lib64/python3.6/site-packages/keras/engine/training_arrays.py", line 224, in fit_loop
callbacks.on_epoch_end(epoch, epoch_logs)
File "/home/msalz/venv_nni_dev/lib64/python3.6/site-packages/keras/callbacks.py", line 152, in on_epoch_end
callback.on_epoch_end(epoch, logs)
File "test.py", line 119, in on_epoch_end
nni.report_intermediate_result(logs["val_loss"])
File "/home/msalz/nni/build/nni/trial.py", line 81, in report_intermediate_result
'value': metric
File "/home/msalz/venv_nni_dev/lib64/python3.6/site-packages/json_tricks/nonp.py", line 99, in dumps
primitives=primitives, fallback_encoders=fallback_encoders, **jsonkwargs).encode(obj)
File "/usr/lib64/python3.6/json/encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "/usr/lib64/python3.6/json/encoder.py", line 257, in iterencode
return _iterencode(o, 0)
ValueError: Out of range float values are not JSON compliant

# Fixed code
def _pack_parameter(
    parameter_id, params, customized=False, trial_job_id=None, parameter_index=None
):
    _trial_params[parameter_id] = params
    ret = {
        "parameter_id": parameter_id,
        "parameter_source": "customized" if customized else "algorithm",
        "parameters": params,
    }
    if trial_job_id is not None:
        ret["trial_job_id"] = trial_job_id
    if parameter_index is not None:
        ret["parameter_index"] = parameter_index
    else:
        ret["parameter_index"] = 0
    return to_json(ret)
# Buggy code
def request_next_parameter():
    metric = json_tricks.dumps(
        {
            "trial_job_id": trial_env_vars.NNI_TRIAL_JOB_ID,
            "type": "REQUEST_PARAMETER",
            "sequence": 0,
            "parameter_index": _param_index,
        }
    )
    send_metric(metric)


# Traceback (ValueError)
Using TensorFlow backend.
Traceback (most recent call last):
File "test.py", line 164, in <module>
train(ARGS, RECEIVED_PARAMS)
File "test.py", line 136, in train
validation_data=(x_test, y_test), callbacks=[SendMetrics(), TensorBoard(log_dir=TENSORBOARD_DIR)])
File "/home/msalz/venv_nni_dev/lib64/python3.6/site-packages/keras/engine/training.py", line 1178, in fit
validation_freq=validation_freq)
File "/home/msalz/venv_nni_dev/lib64/python3.6/site-packages/keras/engine/training_arrays.py", line 224, in fit_loop
callbacks.on_epoch_end(epoch, epoch_logs)
File "/home/msalz/venv_nni_dev/lib64/python3.6/site-packages/keras/callbacks.py", line 152, in on_epoch_end
callback.on_epoch_end(epoch, logs)
File "test.py", line 119, in on_epoch_end
nni.report_intermediate_result(logs["val_loss"])
File "/home/msalz/nni/build/nni/trial.py", line 81, in report_intermediate_result
'value': metric
File "/home/msalz/venv_nni_dev/lib64/python3.6/site-packages/json_tricks/nonp.py", line 99, in dumps
primitives=primitives, fallback_encoders=fallback_encoders, **jsonkwargs).encode(obj)
File "/usr/lib64/python3.6/json/encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "/usr/lib64/python3.6/json/encoder.py", line 257, in iterencode
return _iterencode(o, 0)
ValueError: Out of range float values are not JSON compliant

# Fixed code
def request_next_parameter():
    metric = to_json(
        {
            "trial_job_id": trial_env_vars.NNI_TRIAL_JOB_ID,
            "type": "REQUEST_PARAMETER",
            "sequence": 0,
            "parameter_index": _param_index,
        }
    )
    send_metric(metric)
# Buggy code
def report_intermediate_result(metric):
    """
    Reports intermediate result to NNI.

    Parameters
    ----------
    metric:
        serializable object.
    """
    global _intermediate_seq
    assert _params or trial_env_vars.NNI_PLATFORM is None, (
        "nni.get_next_parameter() needs to be called before report_intermediate_result"
    )
    metric = json_tricks.dumps(
        {
            "parameter_id": _params["parameter_id"] if _params else None,
            "trial_job_id": trial_env_vars.NNI_TRIAL_JOB_ID,
            "type": "PERIODICAL",
            "sequence": _intermediate_seq,
            "value": metric,
        }
    )
    _intermediate_seq += 1
    platform.send_metric(metric)


# Traceback (ValueError)
Using TensorFlow backend.
Traceback (most recent call last):
File "test.py", line 164, in <module>
train(ARGS, RECEIVED_PARAMS)
File "test.py", line 136, in train
validation_data=(x_test, y_test), callbacks=[SendMetrics(), TensorBoard(log_dir=TENSORBOARD_DIR)])
File "/home/msalz/venv_nni_dev/lib64/python3.6/site-packages/keras/engine/training.py", line 1178, in fit
validation_freq=validation_freq)
File "/home/msalz/venv_nni_dev/lib64/python3.6/site-packages/keras/engine/training_arrays.py", line 224, in fit_loop
callbacks.on_epoch_end(epoch, epoch_logs)
File "/home/msalz/venv_nni_dev/lib64/python3.6/site-packages/keras/callbacks.py", line 152, in on_epoch_end
callback.on_epoch_end(epoch, logs)
File "test.py", line 119, in on_epoch_end
nni.report_intermediate_result(logs["val_loss"])
File "/home/msalz/nni/build/nni/trial.py", line 81, in report_intermediate_result
'value': metric
File "/home/msalz/venv_nni_dev/lib64/python3.6/site-packages/json_tricks/nonp.py", line 99, in dumps
primitives=primitives, fallback_encoders=fallback_encoders, **jsonkwargs).encode(obj)
File "/usr/lib64/python3.6/json/encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "/usr/lib64/python3.6/json/encoder.py", line 257, in iterencode
return _iterencode(o, 0)
ValueError: Out of range float values are not JSON compliant

# Fixed code
def report_intermediate_result(metric):
    """
    Reports intermediate result to NNI.

    Parameters
    ----------
    metric:
        serializable object.
    """
    global _intermediate_seq
    assert _params or trial_env_vars.NNI_PLATFORM is None, (
        "nni.get_next_parameter() needs to be called before report_intermediate_result"
    )
    metric = to_json(
        {
            "parameter_id": _params["parameter_id"] if _params else None,
            "trial_job_id": trial_env_vars.NNI_TRIAL_JOB_ID,
            "type": "PERIODICAL",
            "sequence": _intermediate_seq,
            "value": metric,
        }
    )
    _intermediate_seq += 1
    platform.send_metric(metric)
# Buggy code
def report_final_result(metric):
    """
    Reports final result to NNI.

    Parameters
    ----------
    metric:
        serializable object.
    """
    assert _params or trial_env_vars.NNI_PLATFORM is None, (
        "nni.get_next_parameter() needs to be called before report_final_result"
    )
    metric = json_tricks.dumps(
        {
            "parameter_id": _params["parameter_id"] if _params else None,
            "trial_job_id": trial_env_vars.NNI_TRIAL_JOB_ID,
            "type": "FINAL",
            "sequence": 0,
            "value": metric,
        }
    )
    platform.send_metric(metric)


# Traceback (ValueError)
Using TensorFlow backend.
Traceback (most recent call last):
File "test.py", line 164, in <module>
train(ARGS, RECEIVED_PARAMS)
File "test.py", line 136, in train
validation_data=(x_test, y_test), callbacks=[SendMetrics(), TensorBoard(log_dir=TENSORBOARD_DIR)])
File "/home/msalz/venv_nni_dev/lib64/python3.6/site-packages/keras/engine/training.py", line 1178, in fit
validation_freq=validation_freq)
File "/home/msalz/venv_nni_dev/lib64/python3.6/site-packages/keras/engine/training_arrays.py", line 224, in fit_loop
callbacks.on_epoch_end(epoch, epoch_logs)
File "/home/msalz/venv_nni_dev/lib64/python3.6/site-packages/keras/callbacks.py", line 152, in on_epoch_end
callback.on_epoch_end(epoch, logs)
File "test.py", line 119, in on_epoch_end
nni.report_intermediate_result(logs["val_loss"])
File "/home/msalz/nni/build/nni/trial.py", line 81, in report_intermediate_result
'value': metric
File "/home/msalz/venv_nni_dev/lib64/python3.6/site-packages/json_tricks/nonp.py", line 99, in dumps
primitives=primitives, fallback_encoders=fallback_encoders, **jsonkwargs).encode(obj)
File "/usr/lib64/python3.6/json/encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "/usr/lib64/python3.6/json/encoder.py", line 257, in iterencode
return _iterencode(o, 0)
ValueError: Out of range float values are not JSON compliant

# Fixed code
def report_final_result(metric):
    """
    Reports final result to NNI.

    Parameters
    ----------
    metric:
        serializable object.
    """
    assert _params or trial_env_vars.NNI_PLATFORM is None, (
        "nni.get_next_parameter() needs to be called before report_final_result"
    )
    metric = to_json(
        {
            "parameter_id": _params["parameter_id"] if _params else None,
            "trial_job_id": trial_env_vars.NNI_TRIAL_JOB_ID,
            "type": "FINAL",
            "sequence": 0,
            "value": metric,
        }
    )
    platform.send_metric(metric)
# Buggy code
def send_email_sendgrid(sender, subject, message, recipients, image_png):
    import sendgrid as sendgrid_lib

    client = sendgrid_lib.SendGridClient(
        sendgrid().username, sendgrid().password, raise_errors=True
    )
    to_send = sendgrid_lib.Mail()
    to_send.add_to(recipients)
    to_send.set_from(sender)
    to_send.set_subject(subject)
    if email().format == "html":
        to_send.set_html(message)
    else:
        to_send.set_text(message)
    if image_png:
        to_send.add_attachment(image_png)

    client.send(to_send)


# Traceback (AttributeError)
Traceback (most recent call last):
File "/home/ubuntu/.virtualenvs/janrain/local/lib/python2.7/site-packages/luigi/retcodes.py", line 74, in run_with_retcodes
worker = luigi.interface._run(argv)['worker']
File "/home/ubuntu/.virtualenvs/janrain/local/lib/python2.7/site-packages/luigi/interface.py", line 237, in _run
return _schedule_and_run([cp.get_task_obj()], worker_scheduler_factory)
File "/home/ubuntu/.virtualenvs/janrain/local/lib/python2.7/site-packages/luigi/interface.py", line 196, in _schedule_and_run
success &amp;= worker.run()
File "/home/ubuntu/.virtualenvs/janrain/local/lib/python2.7/site-packages/luigi/worker.py", line 1025, in run
self._handle_next_task()
File "/home/ubuntu/.virtualenvs/janrain/local/lib/python2.7/site-packages/luigi/worker.py", line 908, in _handle_next_task
self._email_task_failure(task, expl)
File "/home/ubuntu/.virtualenvs/janrain/local/lib/python2.7/site-packages/luigi/worker.py", line 540, in _email_task_failure
headline="A task failed when running. Most likely run() raised an exception.",
File "/home/ubuntu/.virtualenvs/janrain/local/lib/python2.7/site-packages/luigi/worker.py", line 547, in _email_error
notifications.send_error_email(formatted_subject, message, task.owner_email)
File "/home/ubuntu/.virtualenvs/janrain/local/lib/python2.7/site-packages/luigi/notifications.py", line 356, in send_error_email
recipients=recipients
File "/home/ubuntu/.virtualenvs/janrain/local/lib/python2.7/site-packages/luigi/notifications.py", line 328, in send_email
email_sender(sender, subject, message, recipients, image_png)
File "/home/ubuntu/.virtualenvs/janrain/local/lib/python2.7/site-packages/luigi/notifications.py", line 241, in send_email_sendgrid
client = sendgrid_lib.SendGridClient(
AttributeError: 'module' object has no attribute 'SendGridClient'

# Fixed code
def send_email_sendgrid(sender, subject, message, recipients, image_png):
    import sendgrid as sendgrid_lib

    client = sendgrid_lib.SendGridAPIClient(sendgrid().apikey)

    to_send = sendgrid_lib.Mail(
        from_email=sender, to_emails=recipients, subject=subject
    )

    if email().format == "html":
        to_send.add_content(message, "text/html")
    else:
        to_send.add_content(message, "text/plain")

    if image_png:
        to_send.add_attachment(image_png)

    client.send(to_send)
# Buggy code
def print_table(response, title):
    """Prints out a response table.

    Each row contains key(s), clicks, impressions, CTR, and average position.

    Args:
      response: The server response to be printed as a table.
      title: The title of the table.
    """
    print("\n --" + title + ":")

    if "rows" not in response:
        print("Empty response")
        return

    rows = response["rows"]
    row_format = "{:<20}" + "{:>20}" * 4
    print(row_format.format("Keys", "Clicks", "Impressions", "CTR", "Position"))
    for row in rows:
        keys = ""
        # Keys are returned only if one or more dimensions are requested.
        if "keys" in row:
            keys = ",".join(row["keys"]).encode("utf-8")
        print(
            row_format.format(
                keys, row["clicks"], row["impressions"], row["ctr"], row["position"]
            )
        )


# Traceback (TypeError)
Traceback (most recent call last):
File "search_analytics_api_sample.py", line 197, in <module>
main(sys.argv)
File "search_analytics_api_sample.py", line 71, in main
print_table(response, 'Available dates')
File "search_analytics_api_sample.py", line 194, in print_table
print(row_format.format(keys, row['clicks'], row['impressions'], row['ctr'], row['position']))
TypeError: unsupported format string passed to bytes.__format__

# Fixed code
def print_table(response, title):
    """Prints out a response table.

    Each row contains key(s), clicks, impressions, CTR, and average position.

    Args:
      response: The server response to be printed as a table.
      title: The title of the table.
    """
    print("\n --" + title + ":")

    if "rows" not in response:
        print("Empty response")
        return

    rows = response["rows"]
    row_format = "{:<20}" + "{:>20}" * 4
    print(row_format.format("Keys", "Clicks", "Impressions", "CTR", "Position"))
    for row in rows:
        keys = ""
        # Keys are returned only if one or more dimensions are requested.
        if "keys" in row:
            keys = ",".join(row["keys"]).encode("utf-8").decode()
        print(
            row_format.format(
                keys, row["clicks"], row["impressions"], row["ctr"], row["position"]
            )
        )
# Buggy code
def atoms(self):
    """An :class:`AtomGroup` of :class:`Atoms<Atom>` present in this
    :class:`ResidueGroup`.

    The :class:`Atoms<Atom>` are ordered locally by :class:`Residue` in the
    :class:`ResidueGroup`.  Duplicates are *not* removed.
    """
    ag = self.universe.atoms[np.concatenate(self.indices)]
    # If the ResidueGroup is known to be unique, this also holds for the
    # atoms therein, since atoms can only belong to one residue at a time.
    # On the contrary, if the ResidueGroup is not unique, this does not
    # imply non-unique atoms, since residues might be empty.
    try:
        if self._cache["isunique"]:
            ag._cache["isunique"] = True
            ag._cache["unique"] = ag
    except KeyError:
        pass
    return ag


# Traceback (ValueError)
ValueError: need at least one array to concatenate

Traceback (most recent call last):
File "/usr/lib/python2.7/site-packages/IPython/core/interactiveshell.py", line 2878, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-5-6c6c6b22c39a>", line 1, in <module>
sel.select_atoms('resname SOL').residues.atoms
File "/home/dresio/software/virtualenvs/charm-mda/lib/python2.7/site-packages/MDAnalysis/core/groups.py", line 2340, in atoms
return self.universe.atoms[np.concatenate(self.indices)]
ValueError: need at least one array to concatenate

# Fixed code
def atoms(self):
    """An :class:`AtomGroup` of :class:`Atoms<Atom>` present in this
    :class:`ResidueGroup`.

    The :class:`Atoms<Atom>` are ordered locally by :class:`Residue` in the
    :class:`ResidueGroup`.  Duplicates are *not* removed.
    """
    # If indices is an empty list np.concatenate will fail (Issue #1999).
    try:
        ag = self.universe.atoms[np.concatenate(self.indices)]
    except ValueError:
        ag = self.universe.atoms[self.indices]
    # If the ResidueGroup is known to be unique, this also holds for the
    # atoms therein, since atoms can only belong to one residue at a time.
    # On the contrary, if the ResidueGroup is not unique, this does not
    # imply non-unique atoms, since residues might be empty.
    try:
        if self._cache["isunique"]:
            ag._cache["isunique"] = True
            ag._cache["unique"] = ag
    except KeyError:
        pass
    return ag
# Buggy code
def atoms(self):
    """An :class:`AtomGroup` of :class:`Atoms<Atom>` present in this
    :class:`SegmentGroup`.

    The :class:`Atoms<Atom>` are ordered locally by :class:`Residue`, which
    are further ordered by :class:`Segment` in the :class:`SegmentGroup`.
    Duplicates are *not* removed.
    """
    ag = self.universe.atoms[np.concatenate(self.indices)]
    # If the SegmentGroup is known to be unique, this also holds for the
    # residues therein, and thus, also for the atoms in those residues.
    # On the contrary, if the SegmentGroup is not unique, this does not
    # imply non-unique atoms, since segments or residues might be empty.
    try:
        if self._cache["isunique"]:
            ag._cache["isunique"] = True
            ag._cache["unique"] = ag
    except KeyError:
        pass
    return ag


# Traceback (ValueError)
ValueError: need at least one array to concatenate

Traceback (most recent call last):
File "/usr/lib/python2.7/site-packages/IPython/core/interactiveshell.py", line 2878, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-5-6c6c6b22c39a>", line 1, in <module>
sel.select_atoms('resname SOL').residues.atoms
File "/home/dresio/software/virtualenvs/charm-mda/lib/python2.7/site-packages/MDAnalysis/core/groups.py", line 2340, in atoms
return self.universe.atoms[np.concatenate(self.indices)]
ValueError: need at least one array to concatenate

# Fixed code
def atoms(self):
    """An :class:`AtomGroup` of :class:`Atoms<Atom>` present in this
    :class:`SegmentGroup`.

    The :class:`Atoms<Atom>` are ordered locally by :class:`Residue`, which
    are further ordered by :class:`Segment` in the :class:`SegmentGroup`.
    Duplicates are *not* removed.
    """
    # If indices is an empty list np.concatenate will fail (Issue #1999).
    try:
        ag = self.universe.atoms[np.concatenate(self.indices)]
    except ValueError:
        ag = self.universe.atoms[self.indices]
    # If the SegmentGroup is known to be unique, this also holds for the
    # residues therein, and thus, also for the atoms in those residues.
    # On the contrary, if the SegmentGroup is not unique, this does not
    # imply non-unique atoms, since segments or residues might be empty.
    try:
        if self._cache["isunique"]:
            ag._cache["isunique"] = True
            ag._cache["unique"] = ag
    except KeyError:
        pass
    return ag
# Buggy code
def _single_frame(self):
    index = self._ts.frame
    mobile_com = self.mobile_atoms.center(self._weights)
    mobile_coordinates = self.mobile_atoms.positions - mobile_com
    mobile_atoms, self.rmsd[index] = _fit_to(
        mobile_coordinates,
        self._ref_coordinates,
        self.mobile,
        mobile_com,
        self._ref_com,
        self._weights,
    )
    # write whole aligned input trajectory system
    self._writer.write(mobile_atoms)


# Traceback (IndexError)
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-5-95462d8a76b2> in <module>()
----> 1 align.AlignTraj(u, ref, select='all', step=5, filename='test.xtc').run()

~/anaconda3/lib/python3.6/site-packages/MDAnalysis/analysis/base.py in run(self)
179             self._ts = ts
180             # logger.info("--> Doing frame {} of {}".format(i+1, self.n_frames))
--> 181             self._single_frame()
182             self._pm.echo(self._frame_index)
183         logger.info("Finishing up")

~/anaconda3/lib/python3.6/site-packages/MDAnalysis/analysis/align.py in _single_frame(self)
668                                                  self.mobile,
669                                                  mobile_com,
--> 670                                                  self._ref_com, self._weights)
671         # write whole aligned input trajectory system
672         self._writer.write(mobile_atoms)

IndexError: index 20 is out of bounds for axis 0 with size 20

# Fixed code
def _single_frame(self):
    index = self._frame_index
    mobile_com = self.mobile_atoms.center(self._weights)
    mobile_coordinates = self.mobile_atoms.positions - mobile_com
    mobile_atoms, self.rmsd[index] = _fit_to(
        mobile_coordinates,
        self._ref_coordinates,
        self.mobile,
        mobile_com,
        self._ref_com,
        self._weights,
    )
    # write whole aligned input trajectory system
    self._writer.write(mobile_atoms)
# Buggy code
def _read_trz_header(self):
    """Reads the header of the trz trajectory"""
    self._headerdtype = np.dtype(
        [("p1", "i4"), ("title", "80c"), ("p2", "2i4"), ("force", "i4"), ("p3", "i4")]
    )
    data = np.fromfile(self.trzfile, dtype=self._headerdtype, count=1)
    self.title = "".join(c.decode("utf-8") for c in data["title"][0]).strip()
    if data["force"] == 10:
        self.has_force = False
    elif data["force"] == 20:
        self.has_force = True
    else:
        raise IOError


# Traceback (IOError)
Traceback (most recent call last):
File "/usr/lib/python2.7/site-packages/nose/case.py", line 381, in setUp
try_run(self.inst, ('setup', 'setUp'))
File "/usr/lib/python2.7/site-packages/nose/util.py", line 471, in try_run
return func()
File "/builddir/build/BUILD/MDAnalysis-0.16.1/MDAnalysisTests-0.16.1/MDAnalysisTests/analysis/test_hydrogenbondautocorrel.py", line 37, in setUp
u = self.u = mda.Universe(TRZ_psf, TRZ)
File "/builddir/build/BUILDROOT/python-MDAnalysis-0.16.1-2.fc27.ppc64/usr/lib64/python2.7/site-packages/MDAnalysis/core/universe.py", line 278, in __init__
self.load_new(coordinatefile, **kwargs)
File "/builddir/build/BUILDROOT/python-MDAnalysis-0.16.1-2.fc27.ppc64/usr/lib64/python2.7/site-packages/MDAnalysis/core/universe.py", line 426, in load_new
self.trajectory = reader(filename, **kwargs)
File "/builddir/build/BUILDROOT/python-MDAnalysis-0.16.1-2.fc27.ppc64/usr/lib64/python2.7/site-packages/MDAnalysis/coordinates/TRZ.py", line 175, in __init__
self._read_trz_header()
File "/builddir/build/BUILDROOT/python-MDAnalysis-0.16.1-2.fc27.ppc64/usr/lib64/python2.7/site-packages/MDAnalysis/coordinates/TRZ.py", line 242, in _read_trz_header
raise IOError
IOError:

# Fixed code
def _read_trz_header(self):
    """Reads the header of the trz trajectory"""
    self._headerdtype = np.dtype(
        [
            ("p1", "<i4"),
            ("title", "80c"),
            ("p2", "<2i4"),
            ("force", "<i4"),
            ("p3", "<i4"),
        ]
    )
    data = np.fromfile(self.trzfile, dtype=self._headerdtype, count=1)
    self.title = "".join(c.decode("utf-8") for c in data["title"][0]).strip()
    if data["force"] == 10:
        self.has_force = False
    elif data["force"] == 20:
        self.has_force = True
    else:
        raise IOError
# Buggy code
def _writeheader(self, title):
    hdt = np.dtype(
        [
            ("pad1", "i4"),
            ("title", "80c"),
            ("pad2", "i4"),
            ("pad3", "i4"),
            ("nrec", "i4"),
            ("pad4", "i4"),
        ]
    )
    out = np.zeros((), dtype=hdt)
    out["pad1"], out["pad2"] = 80, 80
    out["title"] = title + " " * (80 - len(title))
    out["pad3"], out["pad4"] = 4, 4
    out["nrec"] = 10
    out.tofile(self.trzfile)


# Traceback (IOError)
Traceback (most recent call last):
File "/usr/lib/python2.7/site-packages/nose/case.py", line 381, in setUp
try_run(self.inst, ('setup', 'setUp'))
File "/usr/lib/python2.7/site-packages/nose/util.py", line 471, in try_run
return func()
File "/builddir/build/BUILD/MDAnalysis-0.16.1/MDAnalysisTests-0.16.1/MDAnalysisTests/analysis/test_hydrogenbondautocorrel.py", line 37, in setUp
u = self.u = mda.Universe(TRZ_psf, TRZ)
File "/builddir/build/BUILDROOT/python-MDAnalysis-0.16.1-2.fc27.ppc64/usr/lib64/python2.7/site-packages/MDAnalysis/core/universe.py", line 278, in __init__
self.load_new(coordinatefile, **kwargs)
File "/builddir/build/BUILDROOT/python-MDAnalysis-0.16.1-2.fc27.ppc64/usr/lib64/python2.7/site-packages/MDAnalysis/core/universe.py", line 426, in load_new
self.trajectory = reader(filename, **kwargs)
File "/builddir/build/BUILDROOT/python-MDAnalysis-0.16.1-2.fc27.ppc64/usr/lib64/python2.7/site-packages/MDAnalysis/coordinates/TRZ.py", line 175, in __init__
self._read_trz_header()
File "/builddir/build/BUILDROOT/python-MDAnalysis-0.16.1-2.fc27.ppc64/usr/lib64/python2.7/site-packages/MDAnalysis/coordinates/TRZ.py", line 242, in _read_trz_header
raise IOError
IOError:

# Fixed code
def _writeheader(self, title):
    hdt = np.dtype(
        [
            ("pad1", "<i4"),
            ("title", "80c"),
            ("pad2", "<i4"),
            ("pad3", "<i4"),
            ("nrec", "<i4"),
            ("pad4", "<i4"),
        ]
    )
    out = np.zeros((), dtype=hdt)
    out["pad1"], out["pad2"] = 80, 80
    out["title"] = title + " " * (80 - len(title))
    out["pad3"], out["pad4"] = 4, 4
    out["nrec"] = 10
    out.tofile(self.trzfile)