prompt: We are currently solving the following issue within our repository. Here is the issue text:
  --- BEGIN ISSUE ---
  test_video.test_spatiotemporal_cubes is randomly failing
  The test `utils.tests.test_video.test_spatiotemporal_cubes` seems to be randomly failing on some Travis builds. Both @jych and @daemonmaker have experienced this. From [comments in the code](https://github.com/lisa-lab/pylearn2/blob/master/pylearn2/utils/tests/test_video.py#L27-L28) it seems like this is not the first time. Was a reason ever discovered?
  
  test_video.test_spatiotemporal_cubes is randomly failing
  The test `utils.tests.test_video.test_spatiotemporal_cubes` seems to be randomly failing on some Travis builds. Both @jych and @daemonmaker have experienced this. From [comments in the code](https://github.com/lisa-lab/pylearn2/blob/master/pylearn2/utils/tests/test_video.py#L27-L28) it seems like this is not the first time. Was a reason ever discovered?
  
  
  --- END ISSUE ---
  
  Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
  --- BEGIN FILES ---
  Path: `pylearn2/utils/video.py`
  Content:
  ```
  1 """
  2 Utilities for working with videos, pulling out patches, etc.
  3 """
  4 import numpy
  5 
  6 from pylearn2.compat import OrderedDict
  7 from pylearn2.utils.rng import make_np_rng
  8 
  9 __author__ = "David Warde-Farley"
  10 __copyright__ = "Copyright 2011, David Warde-Farley / Universite de Montreal"
  11 __license__ = "BSD"
  12 __maintainer__ = "David Warde-Farley"
  13 __email__ = "wardefar@iro"
  14 __all__ = ["get_video_dims", "spatiotemporal_cubes"]
  15 
  16 
  17 def get_video_dims(fname):
  18     """
  19     Pull out the frame length, spatial height and spatial width of
  20     a video file using ffmpeg.
  21 
  22     Parameters
  23     ----------
  24     fname : str
  25         Path to video file to be inspected.
  26 
  27     Returns
  28     -------
  29     shape : tuple
  30         The spatiotemporal dimensions of the video
  31         (length, height, width).
  32     """
  33     try:
  34         import pyffmpeg
  35     except ImportError:
  36         raise ImportError("This function requires pyffmpeg "
  37                           "<http://code.google.com/p/pyffmpeg/>")
  38     mp = pyffmpeg.FFMpegReader()
  39     try:
  40         mp.open(fname)
  41         tracks = mp.get_tracks()
  42         for track in tracks:
  43             if isinstance(track, pyffmpeg.VideoTrack):
  44                 break
  45         else:
  46             raise ValueError('no video track found')
  47         return (track.duration(),) + track.get_orig_size()
  48     finally:
  49         mp.close()
  50 
  51 
  52 class FrameLookup(object):
  53     """
  54     Class encapsulating the logic of turning a frame index into a
  55     collection of files into the frame index of a specific video file.
  56 
  57     Item-indexing on this object will yield a (filename, nframes, frame_no)
  58     tuple, where nframes is the number of frames in the given file
  59     (mainly for checking that we're far enough from the end so that we
  60     can sample a big enough chunk).
  61 
  62     Parameters
  63     ----------
  64     names_ang_lengths : WRITEME
  65     """
  66     def __init__(self, names_and_lengths):
  67         self.files, self.lengths = zip(*names_and_lengths)
  68         self.terminals = numpy.cumsum([s[1] for s in names_and_lengths])
  69 
  70     def __getitem__(self, i):
  71         idx = (i < self.terminals).nonzero()[0][0]
  72         frame_no = i
  73         if idx > 0:
  74             frame_no -= self.terminals[idx - 1]
  75         return self.files[idx], self.lengths[idx], frame_no
  76 
  77     def __len__(self):
  78         return self.terminals[-1]
  79 
  80     def __iter__(self):
  81         raise TypeError('iteration not supported')
  82 
  83 
  84 def spatiotemporal_cubes(file_tuples, shape, n_patches=numpy.inf, rng=None):
  85     """
  86     Generator function that yields a stream of (filename, slicetuple)
  87     representing a spatiotemporal patch of that file.
  88 
  89     Parameters
  90     ----------
  91     file_tuples : list of tuples
  92         Each element should be a 2-tuple consisting of a filename
  93         (or arbitrary identifier) and a (length, height, width)
  94         shape tuple of the dimensions (number of frames in the video,
  95         height and width of each frame).
  96 
  97     shape : tuple
  98         A shape tuple consisting of the desired (length, height, width)
  99         of each spatiotemporal patch.
  100 
  101     n_patches : int, optional
  102         The number of patches to generate. By default, generates patches
  103         infinitely.
  104 
  105     rng : RandomState object or seed, optional
  106         The random number generator (or seed) to use. Defaults to None,
  107         meaning it will be seeded from /dev/urandom or the clock.
  108 
  109     Returns
  110     -------
  111     generator : generator object
  112         A generator that yields a stream of (filename, slicetuple) tuples.
  113         The slice tuple is such that it indexes into a 3D array containing
  114         the entire clip with frames indexed along the first axis, rows
  115         along the second and columns along the third.
  116     """
  117     frame_lookup = FrameLookup([(a, b[0]) for a, b in file_tuples])
  118     file_lookup = OrderedDict(file_tuples)
  119     patch_length, patch_height, patch_width = shape
  120     done = 0
  121     rng = make_np_rng(rng, which_method="random_integers")
  122     while done < n_patches:
  123         frame = rng.random_integers(0, len(frame_lookup) - 1)
  124         filename, file_length, frame_no = frame_lookup[frame]
  125         # Check that there is a contiguous block of frames starting at
  126         # frame_no that is at least as long as our desired cube length.
  127         if file_length - frame_no < patch_length:
  128             continue
  129         _, video_height, video_width = file_lookup[filename][:3]
  130         # The last row and column in which a patch could "start" to still
  131         # fall within frame.
  132         last_row = video_height - patch_height
  133         last_col = video_width - patch_width
  134         row = numpy.random.random_integers(0, last_row)
  135         col = numpy.random.random_integers(0, last_col)
  136         patch_slice = (slice(frame_no, frame_no + patch_length),
  137                        slice(row, row + patch_height),
  138                        slice(col, col + patch_width))
  139         done += 1
  140         yield filename, patch_slice
  141
  ```
  --- END FILES ---
  
  Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.
  
  Here is an example:
  
  ```diff
  diff --git a/examples/server_async.py b/examples/server_async.py
  --- a/examples/server_async.py
  +++ b/examples/server_async.py
  @@ -313,4 +313,4 @@
   
   
   if __name__ == "__main__":
  -    asyncio.run(run_async_server("."), debug=True)
  +    asyncio.run(run_async_server(), debug=True)
  diff --git a/examples/server_sync.py b/examples/server_sync.py
  --- a/examples/server_sync.py
  +++ b/examples/server_sync.py
  @@ -313,5 +313,5 @@
   
   
   if __name__ == "__main__":
  -    server = run_sync_server(".")
  +    server = run_sync_server()
       server.shutdown()
  
  ```
  
golden_diff: diff --git a/pylearn2/utils/video.py b/pylearn2/utils/video.py
  --- a/pylearn2/utils/video.py
  +++ b/pylearn2/utils/video.py
  @@ -131,8 +131,8 @@
           # fall within frame.
           last_row = video_height - patch_height
           last_col = video_width - patch_width
  -        row = numpy.random.random_integers(0, last_row)
  -        col = numpy.random.random_integers(0, last_col)
  +        row = rng.random_integers(0, last_row)
  +        col = rng.random_integers(0, last_col)
           patch_slice = (slice(frame_no, frame_no + patch_length),
                          slice(row, row + patch_height),
                          slice(col, col + patch_width))
  
verification_info: {"golden_diff": "diff --git a/pylearn2/utils/video.py b/pylearn2/utils/video.py\n--- a/pylearn2/utils/video.py\n+++ b/pylearn2/utils/video.py\n@@ -131,8 +131,8 @@\n         # fall within frame.\n         last_row = video_height - patch_height\n         last_col = video_width - patch_width\n-        row = numpy.random.random_integers(0, last_row)\n-        col = numpy.random.random_integers(0, last_col)\n+        row = rng.random_integers(0, last_row)\n+        col = rng.random_integers(0, last_col)\n         patch_slice = (slice(frame_no, frame_no + patch_length),\n                        slice(row, row + patch_height),\n                        slice(col, col + patch_width))\n", "issue": "test_video.test_spatiotemporal_cubes is randomly failing\nThe test `utils.tests.test_video.test_spatiotemporal_cubes` seems to be randomly failing on some Travis builds. Both @jych and @daemonmaker have experienced this. From [comments in the code](https://github.com/lisa-lab/pylearn2/blob/master/pylearn2/utils/tests/test_video.py#L27-L28) it seems like this is not the first time. Was a reason ever discovered?\n\ntest_video.test_spatiotemporal_cubes is randomly failing\nThe test `utils.tests.test_video.test_spatiotemporal_cubes` seems to be randomly failing on some Travis builds. Both @jych and @daemonmaker have experienced this. From [comments in the code](https://github.com/lisa-lab/pylearn2/blob/master/pylearn2/utils/tests/test_video.py#L27-L28) it seems like this is not the first time. Was a reason ever discovered?\n\n", "before_files": [{"content": "\"\"\"\nUtilities for working with videos, pulling out patches, etc.\n\"\"\"\nimport numpy\n\nfrom pylearn2.compat import OrderedDict\nfrom pylearn2.utils.rng import make_np_rng\n\n__author__ = \"David Warde-Farley\"\n__copyright__ = \"Copyright 2011, David Warde-Farley / Universite de Montreal\"\n__license__ = \"BSD\"\n__maintainer__ = \"David Warde-Farley\"\n__email__ = \"wardefar@iro\"\n__all__ = [\"get_video_dims\", \"spatiotemporal_cubes\"]\n\n\ndef get_video_dims(fname):\n    \"\"\"\n    Pull out the frame length, spatial height and spatial width of\n    a video file using ffmpeg.\n\n    Parameters\n    ----------\n    fname : str\n        Path to video file to be inspected.\n\n    Returns\n    -------\n    shape : tuple\n        The spatiotemporal dimensions of the video\n        (length, height, width).\n    \"\"\"\n    try:\n        import pyffmpeg\n    except ImportError:\n        raise ImportError(\"This function requires pyffmpeg \"\n                          \"<http://code.google.com/p/pyffmpeg/>\")\n    mp = pyffmpeg.FFMpegReader()\n    try:\n        mp.open(fname)\n        tracks = mp.get_tracks()\n        for track in tracks:\n            if isinstance(track, pyffmpeg.VideoTrack):\n                break\n        else:\n            raise ValueError('no video track found')\n        return (track.duration(),) + track.get_orig_size()\n    finally:\n        mp.close()\n\n\nclass FrameLookup(object):\n    \"\"\"\n    Class encapsulating the logic of turning a frame index into a\n    collection of files into the frame index of a specific video file.\n\n    Item-indexing on this object will yield a (filename, nframes, frame_no)\n    tuple, where nframes is the number of frames in the given file\n    (mainly for checking that we're far enough from the end so that we\n    can sample a big enough chunk).\n\n    Parameters\n    ----------\n    names_ang_lengths : WRITEME\n    \"\"\"\n    def __init__(self, names_and_lengths):\n        self.files, self.lengths = zip(*names_and_lengths)\n        self.terminals = numpy.cumsum([s[1] for s in names_and_lengths])\n\n    def __getitem__(self, i):\n        idx = (i < self.terminals).nonzero()[0][0]\n        frame_no = i\n        if idx > 0:\n            frame_no -= self.terminals[idx - 1]\n        return self.files[idx], self.lengths[idx], frame_no\n\n    def __len__(self):\n        return self.terminals[-1]\n\n    def __iter__(self):\n        raise TypeError('iteration not supported')\n\n\ndef spatiotemporal_cubes(file_tuples, shape, n_patches=numpy.inf, rng=None):\n    \"\"\"\n    Generator function that yields a stream of (filename, slicetuple)\n    representing a spatiotemporal patch of that file.\n\n    Parameters\n    ----------\n    file_tuples : list of tuples\n        Each element should be a 2-tuple consisting of a filename\n        (or arbitrary identifier) and a (length, height, width)\n        shape tuple of the dimensions (number of frames in the video,\n        height and width of each frame).\n\n    shape : tuple\n        A shape tuple consisting of the desired (length, height, width)\n        of each spatiotemporal patch.\n\n    n_patches : int, optional\n        The number of patches to generate. By default, generates patches\n        infinitely.\n\n    rng : RandomState object or seed, optional\n        The random number generator (or seed) to use. Defaults to None,\n        meaning it will be seeded from /dev/urandom or the clock.\n\n    Returns\n    -------\n    generator : generator object\n        A generator that yields a stream of (filename, slicetuple) tuples.\n        The slice tuple is such that it indexes into a 3D array containing\n        the entire clip with frames indexed along the first axis, rows\n        along the second and columns along the third.\n    \"\"\"\n    frame_lookup = FrameLookup([(a, b[0]) for a, b in file_tuples])\n    file_lookup = OrderedDict(file_tuples)\n    patch_length, patch_height, patch_width = shape\n    done = 0\n    rng = make_np_rng(rng, which_method=\"random_integers\")\n    while done < n_patches:\n        frame = rng.random_integers(0, len(frame_lookup) - 1)\n        filename, file_length, frame_no = frame_lookup[frame]\n        # Check that there is a contiguous block of frames starting at\n        # frame_no that is at least as long as our desired cube length.\n        if file_length - frame_no < patch_length:\n            continue\n        _, video_height, video_width = file_lookup[filename][:3]\n        # The last row and column in which a patch could \"start\" to still\n        # fall within frame.\n        last_row = video_height - patch_height\n        last_col = video_width - patch_width\n        row = numpy.random.random_integers(0, last_row)\n        col = numpy.random.random_integers(0, last_col)\n        patch_slice = (slice(frame_no, frame_no + patch_length),\n                       slice(row, row + patch_height),\n                       slice(col, col + patch_width))\n        done += 1\n        yield filename, patch_slice\n", "path": "pylearn2/utils/video.py"}], "after_files": [{"content": "\"\"\"\nUtilities for working with videos, pulling out patches, etc.\n\"\"\"\nimport numpy\n\nfrom pylearn2.compat import OrderedDict\nfrom pylearn2.utils.rng import make_np_rng\n\n__author__ = \"David Warde-Farley\"\n__copyright__ = \"Copyright 2011, David Warde-Farley / Universite de Montreal\"\n__license__ = \"BSD\"\n__maintainer__ = \"David Warde-Farley\"\n__email__ = \"wardefar@iro\"\n__all__ = [\"get_video_dims\", \"spatiotemporal_cubes\"]\n\n\ndef get_video_dims(fname):\n    \"\"\"\n    Pull out the frame length, spatial height and spatial width of\n    a video file using ffmpeg.\n\n    Parameters\n    ----------\n    fname : str\n        Path to video file to be inspected.\n\n    Returns\n    -------\n    shape : tuple\n        The spatiotemporal dimensions of the video\n        (length, height, width).\n    \"\"\"\n    try:\n        import pyffmpeg\n    except ImportError:\n        raise ImportError(\"This function requires pyffmpeg \"\n                          \"<http://code.google.com/p/pyffmpeg/>\")\n    mp = pyffmpeg.FFMpegReader()\n    try:\n        mp.open(fname)\n        tracks = mp.get_tracks()\n        for track in tracks:\n            if isinstance(track, pyffmpeg.VideoTrack):\n                break\n        else:\n            raise ValueError('no video track found')\n        return (track.duration(),) + track.get_orig_size()\n    finally:\n        mp.close()\n\n\nclass FrameLookup(object):\n    \"\"\"\n    Class encapsulating the logic of turning a frame index into a\n    collection of files into the frame index of a specific video file.\n\n    Item-indexing on this object will yield a (filename, nframes, frame_no)\n    tuple, where nframes is the number of frames in the given file\n    (mainly for checking that we're far enough from the end so that we\n    can sample a big enough chunk).\n\n    Parameters\n    ----------\n    names_ang_lengths : WRITEME\n    \"\"\"\n    def __init__(self, names_and_lengths):\n        self.files, self.lengths = zip(*names_and_lengths)\n        self.terminals = numpy.cumsum([s[1] for s in names_and_lengths])\n\n    def __getitem__(self, i):\n        idx = (i < self.terminals).nonzero()[0][0]\n        frame_no = i\n        if idx > 0:\n            frame_no -= self.terminals[idx - 1]\n        return self.files[idx], self.lengths[idx], frame_no\n\n    def __len__(self):\n        return self.terminals[-1]\n\n    def __iter__(self):\n        raise TypeError('iteration not supported')\n\n\ndef spatiotemporal_cubes(file_tuples, shape, n_patches=numpy.inf, rng=None):\n    \"\"\"\n    Generator function that yields a stream of (filename, slicetuple)\n    representing a spatiotemporal patch of that file.\n\n    Parameters\n    ----------\n    file_tuples : list of tuples\n        Each element should be a 2-tuple consisting of a filename\n        (or arbitrary identifier) and a (length, height, width)\n        shape tuple of the dimensions (number of frames in the video,\n        height and width of each frame).\n\n    shape : tuple\n        A shape tuple consisting of the desired (length, height, width)\n        of each spatiotemporal patch.\n\n    n_patches : int, optional\n        The number of patches to generate. By default, generates patches\n        infinitely.\n\n    rng : RandomState object or seed, optional\n        The random number generator (or seed) to use. Defaults to None,\n        meaning it will be seeded from /dev/urandom or the clock.\n\n    Returns\n    -------\n    generator : generator object\n        A generator that yields a stream of (filename, slicetuple) tuples.\n        The slice tuple is such that it indexes into a 3D array containing\n        the entire clip with frames indexed along the first axis, rows\n        along the second and columns along the third.\n    \"\"\"\n    frame_lookup = FrameLookup([(a, b[0]) for a, b in file_tuples])\n    file_lookup = OrderedDict(file_tuples)\n    patch_length, patch_height, patch_width = shape\n    done = 0\n    rng = make_np_rng(rng, which_method=\"random_integers\")\n    while done < n_patches:\n        frame = rng.random_integers(0, len(frame_lookup) - 1)\n        filename, file_length, frame_no = frame_lookup[frame]\n        # Check that there is a contiguous block of frames starting at\n        # frame_no that is at least as long as our desired cube length.\n        if file_length - frame_no < patch_length:\n            continue\n        _, video_height, video_width = file_lookup[filename][:3]\n        # The last row and column in which a patch could \"start\" to still\n        # fall within frame.\n        last_row = video_height - patch_height\n        last_col = video_width - patch_width\n        row = rng.random_integers(0, last_row)\n        col = rng.random_integers(0, last_col)\n        patch_slice = (slice(frame_no, frame_no + patch_length),\n                       slice(row, row + patch_height),\n                       slice(col, col + patch_width))\n        done += 1\n        yield filename, patch_slice\n", "path": "pylearn2/utils/video.py"}]}