jiahuimbzuai/CoQuIR huggingface dataset:
// main [python]
def main(_):
  sess = tf.Session()

  # Construct the TensorFlow network.
  ph_float = tf.placeholder(tf.float32, name="ph_float")
  x = tf.transpose(ph_float, name="x")
  v = tf.Variable(np.array([[-2.0], [-3.0], [6.0]], dtype=np.float32), name="v")
  m = tf.constant(
      np.array([[0.0, 1.0, 2.0], [-4.0, -1.0, 0.0]]),
      dtype=tf.float32,
      name="m")
  y = tf.matmul(m, x, name="y")
  z = tf.matmul(m, v, name="z")

  if FLAGS.debug:
    if FLAGS.use_random_config_path:
      # TODO(mihaimaruseac): Safe to ignore fd here?
      _, config_file_path = tempfile.mkstemp(".tfdbg_config")
    else:
      config_file_path = None
    sess = tf_debug.LocalCLIDebugWrapperSession(
        sess, ui_type=FLAGS.ui_type, config_file_path=config_file_path)

  if FLAGS.error == "shape_mismatch":
    print(sess.run(y, feed_dict={ph_float: np.array([[0.0], [1.0], [2.0]])}))
  elif FLAGS.error == "uninitialized_variable":
    print(sess.run(z))
  elif FLAGS.error == "no_error":
    print(sess.run(y, feed_dict={ph_float: np.array([[0.0, 1.0, 2.0]])}))
  else:
    raise ValueError("Unrecognized error type: " + FLAGS.error)
// main [python]
def main(_):
  sess = tf.Session()

  # Construct the TensorFlow network.
  ph_float = tf.placeholder(tf.float32, name="ph_float")
  x = tf.transpose(ph_float, name="x")
  v = tf.Variable(np.array([[-2.0], [-3.0], [6.0]], dtype=np.float32), name="v")
  m = tf.constant(
      np.array([[0.0, 1.0, 2.0], [-4.0, -1.0, 0.0]]),
      dtype=tf.float32,
      name="m")
  y = tf.matmul(m, x, name="y")
  z = tf.matmul(m, v, name="z")

  if FLAGS.debug:
    config_file_path = (
        tempfile.mktemp(".tfdbg_config")
        if FLAGS.use_random_config_path else None)
    sess = tf_debug.LocalCLIDebugWrapperSession(
        sess, ui_type=FLAGS.ui_type, config_file_path=config_file_path)

  if FLAGS.error == "shape_mismatch":
    print(sess.run(y, feed_dict={ph_float: np.array([[0.0], [1.0], [2.0]])}))
  elif FLAGS.error == "uninitialized_variable":
    print(sess.run(z))
  elif FLAGS.error == "no_error":
    print(sess.run(y, feed_dict={ph_float: np.array([[0.0, 1.0, 2.0]])}))
  else:
    raise ValueError("Unrecognized error type: " + FLAGS.error)
// testLoadingPythonSourceFileWithNonAsciiChars [python]
  def testLoadingPythonSourceFileWithNonAsciiChars(self):
    fd, source_path = tempfile.mkstemp()
    with open(fd, "wb") as source_file:
      source_file.write(u"print('\U0001f642')\n".encode("utf-8"))
    source_lines, _ = source_utils.load_source(source_path)
    self.assertEqual(source_lines, [u"print('\U0001f642')", u""])
    # Clean up unrelated source file.
    os.remove(source_path)
// testLoadingPythonSourceFileWithNonAsciiChars [python]
  def testLoadingPythonSourceFileWithNonAsciiChars(self):
    source_path = tempfile.mktemp()
    with open(source_path, "wb") as source_file:
      source_file.write(u"print('\U0001f642')\n".encode("utf-8"))
    source_lines, _ = source_utils.load_source(source_path)
    self.assertEqual(source_lines, [u"print('\U0001f642')", u""])
    # Clean up unrelated source file.
    os.remove(source_path)
// captureWritesToStream [python]
  @contextlib.contextmanager
  def captureWritesToStream(self, stream):
    """A context manager that captures the writes to a given stream.

    This context manager captures all writes to a given stream inside of a
    `CapturedWrites` object. When this context manager is created, it yields
    the `CapturedWrites` object. The captured contents can be accessed  by
    calling `.contents()` on the `CapturedWrites`.

    For this function to work, the stream must have a file descriptor that
    can be modified using `os.dup` and `os.dup2`, and the stream must support
    a `.flush()` method. The default python sys.stdout and sys.stderr are
    examples of this. Note that this does not work in Colab or Jupyter
    notebooks, because those use alternate stdout streams.

    Example:
    ```python
    class MyOperatorTest(test_util.TensorFlowTestCase):
      def testMyOperator(self):
        input = [1.0, 2.0, 3.0, 4.0, 5.0]
        with self.captureWritesToStream(sys.stdout) as captured:
          result = MyOperator(input).eval()
        self.assertStartsWith(captured.contents(), "This was printed.")
    ```

    Args:
      stream: The stream whose writes should be captured. This stream must have
        a file descriptor, support writing via using that file descriptor, and
        must have a `.flush()` method.

    Yields:
      A `CapturedWrites` object that contains all writes to the specified stream
      made during this context.
    """
    stream.flush()
    fd = stream.fileno()
    tmp_file, tmp_file_path = tempfile.mkstemp(dir=self.get_temp_dir())
    orig_fd = os.dup(fd)
    os.dup2(tmp_file, fd)
    try:
      yield CapturedWrites(tmp_file_path)
    finally:
      os.close(tmp_file)
      os.dup2(orig_fd, fd)
// captureWritesToStream [python]
  @contextlib.contextmanager
  def captureWritesToStream(self, stream):
    """A context manager that captures the writes to a given stream.

    This context manager captures all writes to a given stream inside of a
    `CapturedWrites` object. When this context manager is created, it yields
    the `CapturedWrites` object. The captured contents can be accessed  by
    calling `.contents()` on the `CapturedWrites`.

    For this function to work, the stream must have a file descriptor that
    can be modified using `os.dup` and `os.dup2`, and the stream must support
    a `.flush()` method. The default python sys.stdout and sys.stderr are
    examples of this. Note that this does not work in Colab or Jupyter
    notebooks, because those use alternate stdout streams.

    Example:
    ```python
    class MyOperatorTest(test_util.TensorFlowTestCase):
      def testMyOperator(self):
        input = [1.0, 2.0, 3.0, 4.0, 5.0]
        with self.captureWritesToStream(sys.stdout) as captured:
          result = MyOperator(input).eval()
        self.assertStartsWith(captured.contents(), "This was printed.")
    ```

    Args:
      stream: The stream whose writes should be captured. This stream must have
        a file descriptor, support writing via using that file descriptor, and
        must have a `.flush()` method.

    Yields:
      A `CapturedWrites` object that contains all writes to the specified stream
      made during this context.
    """
    stream.flush()
    fd = stream.fileno()
    tmp_file_path = tempfile.mktemp(dir=self.get_temp_dir())
    tmp_file = open(tmp_file_path, "w")
    orig_fd = os.dup(fd)
    os.dup2(tmp_file.fileno(), fd)
    try:
      yield CapturedWrites(tmp_file_path)
    finally:
      tmp_file.close()
      os.dup2(orig_fd, fd)
// move [python]
def move(path, dest, replace=False):
    """Rename a file. `dest` may not be a directory. If `dest` already
    exists, raises an OSError unless `replace` is True. Has no effect if
    `path` is the same as `dest`. If the paths are on different
    filesystems (or the rename otherwise fails), a copy is attempted
    instead, in which case metadata will *not* be preserved. Paths are
    translated to system paths.
    """
    if os.path.isdir(path):
        raise FilesystemError(u'source is directory', 'move', (path, dest))
    if os.path.isdir(dest):
        raise FilesystemError(u'destination is directory', 'move',
                              (path, dest))
    if samefile(path, dest):
        return
    path = syspath(path)
    dest = syspath(dest)
    if os.path.exists(dest) and not replace:
        raise FilesystemError('file exists', 'rename', (path, dest))

    # First, try renaming the file.
    try:
        os.replace(path, dest)
    except OSError:
        # Copy the file to a temporary destination.
        tmp = tempfile.NamedTemporaryFile(suffix=b'.beets',
                                          prefix=b'.' + os.path.basename(dest),
                                          dir=os.path.dirname(dest),
                                          delete=False)
        try:
            with open(path, 'rb') as f:
                shutil.copyfileobj(f, tmp)
        finally:
            tmp.close()

        # Move the copied file into place.
        try:
            os.replace(tmp.name, dest)
            tmp = None
            os.remove(path)
        except OSError as exc:
            raise FilesystemError(exc, 'move', (path, dest),
                                  traceback.format_exc())
        finally:
            if tmp is not None:
                os.remove(tmp)
// move [python]
def move(path, dest, replace=False):
    """Rename a file. `dest` may not be a directory. If `dest` already
    exists, raises an OSError unless `replace` is True. Has no effect if
    `path` is the same as `dest`. If the paths are on different
    filesystems (or the rename otherwise fails), a copy is attempted
    instead, in which case metadata will *not* be preserved. Paths are
    translated to system paths.
    """
    if os.path.isdir(path):
        raise FilesystemError(u'source is directory', 'move', (path, dest))
    if os.path.isdir(dest):
        raise FilesystemError(u'destination is directory', 'move',
                              (path, dest))
    if samefile(path, dest):
        return
    path = syspath(path)
    dest = syspath(dest)
    if os.path.exists(dest) and not replace:
        raise FilesystemError('file exists', 'rename', (path, dest))

    # First, try renaming the file.
    try:
        os.replace(path, dest)
    except OSError:
        tmp = tempfile.mktemp(suffix='.beets',
                              prefix=py3_path(b'.' + os.path.basename(dest)),
                              dir=py3_path(os.path.dirname(dest)))
        tmp = syspath(tmp)
        try:
            shutil.copyfile(path, tmp)
            os.replace(tmp, dest)
            tmp = None
            os.remove(path)
        except OSError as exc:
            raise FilesystemError(exc, 'move', (path, dest),
                                  traceback.format_exc())
        finally:
            if tmp is not None:
                os.remove(tmp)
// setUp [python]
  def setUp(self):
    self._tmp_dir = tempfile.mkdtemp()

    self.v = variables.VariableV1(10.0, name="v")
    self.w = variables.VariableV1(21.0, name="w")
    self.delta = constant_op.constant(1.0, name="delta")
    self.inc_v = state_ops.assign_add(self.v, self.delta, name="inc_v")

    self.w_int = control_flow_ops.with_dependencies(
        [self.inc_v],
        math_ops.cast(self.w, dtypes.int32, name="w_int_inner"),
        name="w_int_outer")

    self.ph = array_ops.placeholder(dtypes.float32, name="ph")
    self.xph = array_ops.transpose(self.ph, name="xph")
    self.m = constant_op.constant(
        [[0.0, 1.0, 2.0], [-4.0, -1.0, 0.0]], dtype=dtypes.float32, name="m")
    self.y = math_ops.matmul(self.m, self.xph, name="y")

    self.sparse_ph = array_ops.sparse_placeholder(
        dtypes.float32, shape=([5, 5]), name="sparse_placeholder")
    self.sparse_add = sparse_ops.sparse_add(self.sparse_ph, self.sparse_ph)

    rewriter_config = rewriter_config_pb2.RewriterConfig(
        disable_model_pruning=True,
        arithmetic_optimization=rewriter_config_pb2.RewriterConfig.OFF,
        dependency_optimization=rewriter_config_pb2.RewriterConfig.OFF)
    graph_options = config_pb2.GraphOptions(rewrite_options=rewriter_config)
    config_proto = config_pb2.ConfigProto(graph_options=graph_options)
    self.sess = session.Session(config=config_proto)

    # Initialize variable.
    self.sess.run(variables.global_variables_initializer())
// setUp [python]
  def setUp(self):
    self._tmp_dir = tempfile.mktemp()

    self.v = variables.VariableV1(10.0, name="v")
    self.w = variables.VariableV1(21.0, name="w")
    self.delta = constant_op.constant(1.0, name="delta")
    self.inc_v = state_ops.assign_add(self.v, self.delta, name="inc_v")

    self.w_int = control_flow_ops.with_dependencies(
        [self.inc_v],
        math_ops.cast(self.w, dtypes.int32, name="w_int_inner"),
        name="w_int_outer")

    self.ph = array_ops.placeholder(dtypes.float32, name="ph")
    self.xph = array_ops.transpose(self.ph, name="xph")
    self.m = constant_op.constant(
        [[0.0, 1.0, 2.0], [-4.0, -1.0, 0.0]], dtype=dtypes.float32, name="m")
    self.y = math_ops.matmul(self.m, self.xph, name="y")

    self.sparse_ph = array_ops.sparse_placeholder(
        dtypes.float32, shape=([5, 5]), name="sparse_placeholder")
    self.sparse_add = sparse_ops.sparse_add(self.sparse_ph, self.sparse_ph)

    rewriter_config = rewriter_config_pb2.RewriterConfig(
        disable_model_pruning=True,
        arithmetic_optimization=rewriter_config_pb2.RewriterConfig.OFF,
        dependency_optimization=rewriter_config_pb2.RewriterConfig.OFF)
    graph_options = config_pb2.GraphOptions(rewrite_options=rewriter_config)
    config_proto = config_pb2.ConfigProto(graph_options=graph_options)
    self.sess = session.Session(config=config_proto)

    # Initialize variable.
    self.sess.run(variables.global_variables_initializer())
// _put_validation_file [python]
    def _put_validation_file(self, domain, file_path, file_name, content):
        """Put file to the domain with validation content"""
        request = {'packet': {'site': {'get': [
            {'filter': {'name': domain}},
            {'dataset': {'hosting': {}}},
        ]}}}
        response = self.plesk_api_client.request(request)

        api_result = response['packet']['site']['get']['result']
        if 'ok' != api_result['status']:
            error_text = str(api_result['errtext'])
            raise errors.DvAuthError('Site get failure: %s' % error_text)

        hosting_props = api_result['data']['hosting']['vrt_hst']['property']
        self.www_root = next(
            x['value'] for x in hosting_props if 'www_root' == x['name'])
        self.ftp_login = next(
            x['value'] for x in hosting_props if 'ftp_login' == x['name'])

        self.verify_path = os.path.join(self.www_root, file_path)
        self.full_path = os.path.join(self.www_root, file_path, file_name)
        self._create_file(content)
// _put_validation_file [python]
    def _put_validation_file(self, domain, file_path, file_name, content):
        """Put file to the domain with validation content"""
        request = {'packet': {'site': {'get': [
            {'filter': {'name': domain}},
            {'dataset': {'hosting': {}}},
        ]}}}
        response = self.plesk_api_client.request(request)

        api_result = response['packet']['site']['get']['result']
        if 'ok' != api_result['status']:
            error_text = str(api_result['errtext'])
            raise errors.DvAuthError('Site get failure: %s' % error_text)

        hosting_props = api_result['data']['hosting']['vrt_hst']['property']
        self.www_root = next(
            x['value'] for x in hosting_props if 'www_root' == x['name'])
        self.ftp_login = next(
            x['value'] for x in hosting_props if 'ftp_login' == x['name'])

        self.verify_path = os.path.join(self.www_root, file_path)
        self.full_path = os.path.join(self.www_root, file_path, file_name)
        tmp_path = os.tempnam()
        with open(tmp_path, 'w') as f:
            f.write(str(content))
            f.close()
        try:
            self.plesk_api_client.filemng(
                [self.ftp_login, "mkdir", self.verify_path, "-p"])
            self.plesk_api_client.filemng(
                [self.ftp_login, "cp2perm", tmp_path, self.full_path, "0644"])
        finally:
            os.unlink(tmp_path)
// testPrintTensorsToFile [python]
  def testPrintTensorsToFile(self):
    _, tmpfile_name = tempfile.mkstemp(
        ".printv2_test")  # safe to ignore fd here
    tensor_0 = math_ops.range(0, 10)
    print_op_0 = logging_ops.print_v2(tensor_0,
                                      output_stream="file://"+tmpfile_name)
    self.evaluate(print_op_0)
    tensor_1 = math_ops.range(11, 20)
    print_op_1 = logging_ops.print_v2(tensor_1,
                                      output_stream="file://"+tmpfile_name)
    self.evaluate(print_op_1)
    try:
      f = open(tmpfile_name, "r")
      line_0 = f.readline()
      expected_0 = "[0 1 2 ... 7 8 9]"
      self.assertTrue(expected_0 in line_0)
      line_1 = f.readline()
      expected_1 = "[11 12 13 ... 17 18 19]"
      self.assertTrue(expected_1 in line_1)
      f.close()
      os.remove(tmpfile_name)
    except IOError as e:
      self.fail(e)
// testPrintTensorsToFile [python]
  def testPrintTensorsToFile(self):
    tmpfile_name = tempfile.mktemp(".printv2_test")
    tensor_0 = math_ops.range(0, 10)
    print_op_0 = logging_ops.print_v2(tensor_0,
                                      output_stream="file://"+tmpfile_name)
    self.evaluate(print_op_0)
    tensor_1 = math_ops.range(11, 20)
    print_op_1 = logging_ops.print_v2(tensor_1,
                                      output_stream="file://"+tmpfile_name)
    self.evaluate(print_op_1)
    try:
      f = open(tmpfile_name, "r")
      line_0 = f.readline()
      expected_0 = "[0 1 2 ... 7 8 9]"
      self.assertTrue(expected_0 in line_0)
      line_1 = f.readline()
      expected_1 = "[11 12 13 ... 17 18 19]"
      self.assertTrue(expected_1 in line_1)
      f.close()
      os.remove(tmpfile_name)
    except IOError as e:
      self.fail(e)
// try_compile_and_link [python]
def try_compile_and_link(compiler, source = '', flags = []):
    ensure_tmp_dir_exists()
    with tempfile.NamedTemporaryFile() as sfile:
        ofd, ofile = tempfile.mkstemp()
        os.close(ofd)
        try:
            sfile.file.write(bytes(source, 'utf-8'))
            sfile.file.flush()
            # We can't write to /dev/null, since in some cases (-ftest-coverage) gcc will create an auxiliary
            # output file based on the name of the output file, and "/dev/null.gcsa" is not a good name
            return subprocess.call([compiler, '-x', 'c++', '-o', ofile, sfile.name] + flags,
                                   stdout = subprocess.DEVNULL,
                                   stderr = subprocess.DEVNULL) == 0
        finally:
            if os.path.exists(ofile):
                os.unlink(ofile)
// try_compile_and_link [python]
def try_compile_and_link(compiler, source = '', flags = []):
    ensure_tmp_dir_exists()
    with tempfile.NamedTemporaryFile() as sfile:
        ofile = tempfile.mktemp()
        try:
            sfile.file.write(bytes(source, 'utf-8'))
            sfile.file.flush()
            # We can't write to /dev/null, since in some cases (-ftest-coverage) gcc will create an auxiliary
            # output file based on the name of the output file, and "/dev/null.gcsa" is not a good name
            return subprocess.call([compiler, '-x', 'c++', '-o', ofile, sfile.name] + flags,
                                   stdout = subprocess.DEVNULL,
                                   stderr = subprocess.DEVNULL) == 0
        finally:
            if os.path.exists(ofile):
                os.unlink(ofile)
// testIncompleteRedirectWorks [python]
  def testIncompleteRedirectWorks(self):
    _, output_path = tempfile.mkstemp()  # safe to ignore fd

    ui = MockReadlineUI(
        command_sequence=["babble -n 2 > %s" % output_path, "exit"])

    ui.register_command_handler("babble", self._babble, "")
    ui.run_ui()

    screen_outputs = ui.observers["screen_outputs"]
    self.assertEqual(1, len(screen_outputs))
    self.assertEqual(["bar"] * 2, screen_outputs[0].lines)

    with gfile.Open(output_path, "r") as f:
      self.assertEqual("bar\nbar\n", f.read())
// testIncompleteRedirectWorks [python]
  def testIncompleteRedirectWorks(self):
    output_path = tempfile.mktemp()

    ui = MockReadlineUI(
        command_sequence=["babble -n 2 > %s" % output_path, "exit"])

    ui.register_command_handler("babble", self._babble, "")
    ui.run_ui()

    screen_outputs = ui.observers["screen_outputs"]
    self.assertEqual(1, len(screen_outputs))
    self.assertEqual(["bar"] * 2, screen_outputs[0].lines)

    with gfile.Open(output_path, "r") as f:
      self.assertEqual("bar\nbar\n", f.read())
// download [python]
    def download(self, log_files, sort='time', limit=-1, nfl_filter='',
                 output_format='default'):
        if len(log_files) == 0:
            raise NotFoundException(_('no log file found'))
        try:
            nfl_esc = nfl_filter.replace('(', '\(').replace(')', '\)')
            # remove the slash that is intentionally added in the URL
            # to avoid failure of filtering stats data.
            if nfl_esc.startswith('/'):
                nfl_esc = nfl_esc[1:]
            stats = Stats2(*log_files)
            stats.sort_stats(sort)
            if output_format == 'python':
                data = self.format_source_code(nfl_filter)
            elif output_format == 'json':
                data = stats.to_json(nfl_esc, limit)
            elif output_format == 'csv':
                data = stats.to_csv(nfl_esc, limit)
            elif output_format == 'ods':
                data = stats.to_ods(nfl_esc, limit)
            else:
                data = stats.print_stats()
            return data, [('content-type', self.format_dict[output_format])]
        except ODFLIBNotInstalled as ex:
            raise ex
        except Exception as ex:
            raise ProfileException(_('Data download error: %s') % ex)
// download [python]
    def download(self, log_files, sort='time', limit=-1, nfl_filter='',
                 output_format='default'):
        if len(log_files) == 0:
            raise NotFoundException(_('no log file found'))
        try:
            nfl_esc = nfl_filter.replace('(', '\(').replace(')', '\)')
            # remove the slash that is intentionally added in the URL
            # to avoid failure of filtering stats data.
            if nfl_esc.startswith('/'):
                nfl_esc = nfl_esc[1:]
            stats = Stats2(*log_files)
            stats.sort_stats(sort)
            if output_format == 'python':
                data = self.format_source_code(nfl_filter)
            elif output_format == 'json':
                data = stats.to_json(nfl_esc, limit)
            elif output_format == 'csv':
                data = stats.to_csv(nfl_esc, limit)
            elif output_format == 'ods':
                data = stats.to_ods(nfl_esc, limit)
            else:
                profile_tmp_all = tempfile.mktemp('.profile', 'all')
                stats.dump_stats(profile_tmp_all)
                data = open(profile_tmp_all).read()
                os.remove(profile_tmp_all)
            return data, [('content-type', self.format_dict[output_format])]
        except ODFLIBNotInstalled as ex:
            raise ex
        except Exception as ex:
            raise ProfileException(_('Data download error: %s') % ex)
// _launch_cli [python]
  def _launch_cli(self):
    if self._is_run_start:
      self.observers["run_start_cli_run_numbers"].append(self._run_call_count)
    else:
      self.observers["run_end_cli_run_numbers"].append(self._run_call_count)

    readline_cli = ui_factory.get_ui(
        "readline",
        config=cli_config.CLIConfig(
            config_file_path=os.path.join(tempfile.mkdtemp(), ".tfdbg_config")))
    self._register_this_run_info(readline_cli)

    while self._command_pointer < len(self._command_sequence):
      command = self._command_sequence[self._command_pointer]
      self._command_pointer += 1

      try:
        if command[0] == "run":
          self._run_handler(command[1:])
        elif command[0] == "print_feed":
          self.observers["print_feed_responses"].append(
              self._print_feed_handler(command[1:]))
        else:
          raise ValueError("Unrecognized command prefix: %s" % command[0])
      except debugger_cli_common.CommandLineExit as e:
        return e.exit_token
// _launch_cli [python]
  def _launch_cli(self):
    if self._is_run_start:
      self.observers["run_start_cli_run_numbers"].append(self._run_call_count)
    else:
      self.observers["run_end_cli_run_numbers"].append(self._run_call_count)

    readline_cli = ui_factory.get_ui(
        "readline",
        config=cli_config.CLIConfig(
            config_file_path=os.path.join(tempfile.mkdtemp(), ".tfdbg_config")))
    self._register_this_run_info(readline_cli)

    while True:
      command = self._command_sequence[self._command_pointer]
      self._command_pointer += 1

      try:
        if command[0] == "run":
          self._run_handler(command[1:])
        elif command[0] == "print_feed":
          self.observers["print_feed_responses"].append(
              self._print_feed_handler(command[1:]))
        else:
          raise ValueError("Unrecognized command prefix: %s" % command[0])
      except debugger_cli_common.CommandLineExit as e:
        return e.exit_token
// test_sparse_formats [python]
    def test_sparse_formats(self):
        mats = []

        I = array([0, 0, 1, 2, 3, 3, 3, 4])
        J = array([0, 3, 1, 2, 1, 3, 4, 4])

        V = array([1.0, 6.0, 10.5, 0.015, 250.5, -280.0, 33.32, 12.0])
        mats.append(scipy.sparse.coo_matrix((V, (I, J)), shape=(5, 5)))

        V = array([1.0 + 3j, 6.0 + 2j, 10.50 + 0.9j, 0.015 + -4.4j,
                   250.5 + 0j, -280.0 + 5j, 33.32 + 6.4j, 12.00 + 0.8j])
        mats.append(scipy.sparse.coo_matrix((V, (I, J)), shape=(5, 5)))

        for mat in mats:
            expected = mat.toarray()
            for fmt in ['csr', 'csc', 'coo']:
                fn = mkstemp(suffix='.mtx', dir=self.tmpdir)[1]
                mmwrite(fn, mat.asformat(fmt))

                result = mmread(fn).toarray()
                assert_array_almost_equal(result, expected)
// test_sparse_formats [python]
    def test_sparse_formats(self):
        mats = []

        I = array([0, 0, 1, 2, 3, 3, 3, 4])
        J = array([0, 3, 1, 2, 1, 3, 4, 4])

        V = array([1.0, 6.0, 10.5, 0.015, 250.5, -280.0, 33.32, 12.0])
        mats.append(scipy.sparse.coo_matrix((V, (I, J)), shape=(5, 5)))

        V = array([1.0 + 3j, 6.0 + 2j, 10.50 + 0.9j, 0.015 + -4.4j,
                   250.5 + 0j, -280.0 + 5j, 33.32 + 6.4j, 12.00 + 0.8j])
        mats.append(scipy.sparse.coo_matrix((V, (I, J)), shape=(5, 5)))

        for mat in mats:
            expected = mat.toarray()
            for fmt in ['csr', 'csc', 'coo']:
                fn = mktemp(dir=self.tmpdir)  # safe, we own tmpdir
                mmwrite(fn, mat.asformat(fmt))

                result = mmread(fn).toarray()
                assert_array_almost_equal(result, expected)
// testInvalidExtension [python]
  def testInvalidExtension(self):
    converter = upgrade_schema_lib.Converter()
    _, invalid_extension = tempfile.mkstemp(suffix=".foo")  # safe to ignore fd
    with self.assertRaisesRegex(ValueError, "Invalid extension on input"):
      converter.Convert(invalid_extension, invalid_extension)
    with tempfile.NamedTemporaryFile(suffix=".json", mode="w+") as in_json:
      JsonDumpAndFlush(EMPTY_TEST_SCHEMA_V1, in_json)
      with self.assertRaisesRegex(ValueError, "Invalid extension on output"):
        converter.Convert(in_json.name, invalid_extension)
// testInvalidExtension [python]
  def testInvalidExtension(self):
    converter = upgrade_schema_lib.Converter()
    invalid_extension = tempfile.mktemp(suffix=".foo")
    with self.assertRaisesRegex(ValueError, "Invalid extension on input"):
      converter.Convert(invalid_extension, invalid_extension)
    with tempfile.NamedTemporaryFile(suffix=".json", mode="w+") as in_json:
      JsonDumpAndFlush(EMPTY_TEST_SCHEMA_V1, in_json)
      with self.assertRaisesRegex(ValueError, "Invalid extension on output"):
        converter.Convert(in_json.name, invalid_extension)
// main [c]
int main() {
    struct Employee employees[BUFSIZ];
    for (int i = 0; i < BUFSIZ; i++) {
        printf("Enter the last name: ");
        fflush(stdout); /* To keep cursor on same line as prompt */
        fgets(employees[i].last, sizeof employees[i].last, stdin);
        stripNewline(employees[i].last);
        if (strlen(employees[i].last) > 0) {
            printf("Enter the first name: ");
            fflush(stdout);
            fgets(employees[i].first, sizeof employees[i].first, stdin);
            stripNewline(employees[i].first);
            printf("Enter the job title: ");
            fflush(stdout);
            fgets(employees[i].title, sizeof employees[i].title, stdin);
            stripNewline(employees[i].title);
            printf("Enter the salary: ");
            fflush(stdout);
            scanf("%d", &employees[i].salary);
            getchar(); /* eat newline */
        } else {
            for (int j = 0; j < i; j++) {
                printf("%s %s, %s (%d)\n", employees[j].first, employees[j].last, employees[j].title, employees[j].salary);
            }
            break;
        }
    } 
}
// main [c]
int main() {
    struct Employee employees[BUFSIZ];
    for (int i = 0; i < BUFSIZ; i++) {
        printf("Enter the last name: ");
        fflush(stdout); /* To keep cursor on same line as prompt */
        gets(employees[i].last);
        if (strlen(employees[i].last) > 0) {
            printf("Enter the first name: ");
            fflush(stdout);
            gets(employees[i].first);
            printf("Enter the job title: ");
            fflush(stdout);
            gets(employees[i].title);
            printf("Enter the salary: ");
            fflush(stdout);
            scanf("%d", &employees[i].salary);
            getchar(); /* eat newline */
        } else {
            for (int j = 0; j < i; j++) {
                printf("%s %s, %s (%d)\n", employees[j].first, employees[j].last, employees[j].title, employees[j].salary);
            }
            break;
        }
    } 
}
// main [c]
int main() {
	TERM *t;
	char buffer[300];

	printf("lci - A lambda calculus interpreter\n");
	printf("Copyright (C) 2003 Kostas Hatzikokolakis\n");
	printf("This is FREE SOFTWARE and comes with ABSOLUTELY NO WARRANTY\n\n");
	printf("Type a term, Help for info or Quit to exit.\n");

	// read and execute .lcirc
	consultFile(".lcirc");

	// read and execute commands
	while(!feof(stdin)) {
		printf("lci> ");
		if(!fgets(buffer, sizeof(buffer), stdin)) break;
		if(strcmp(buffer, "\n") == 0) continue;

		scInputType = SC_BUFFER;
		scInput = buffer;
		getToken(NULL);

		if(parse((void*)&t, TK_TERM) == PAR_OK)
			execTerm(t);
		else
			printf("Syntax error\n\n");
	}

	return 0;
}
// main [c]
int main() {
	TERM *t;
	char buffer[300];

	printf("lci - A lambda calculus interpreter\n");
	printf("Copyright (C) 2003 Kostas Hatzikokolakis\n");
	printf("This is FREE SOFTWARE and comes with ABSOLUTELY NO WARRANTY\n\n");
	printf("Type a term, Help for info or Quit to exit.\n");

	// read and execute .lcirc
	consultFile(".lcirc");

	// read and execute commands
	while(!feof(stdin)) {
		printf("lci> ");
		if(!gets(buffer)) break;
		if(buffer[0] == '\0') continue;

		scInputType = SC_BUFFER;
		scInput = buffer;
		getToken(NULL);

		if(parse((void*)&t, TK_TERM) == PAR_OK)
			execTerm(t);
		else
			printf("Syntax error\n\n");
	}

	return 0;
}
// ac_circ_buf_popm [c]
int ac_circ_buf_popm(ac_circ_buf_t *cbuf, void *buf, u32 count)
{
	if (circ_count_to_end(cbuf) < count)
		return -1;

	if (cbuf->type == PTR_BUF)
		memcpy(buf, cbuf->buf.ptr_buf + cbuf->tail,
		       count * sizeof(void *));
	else
		memcpy(buf, cbuf->buf.cpy_buf + cbuf->tail,
		       (size_t)count * cbuf->elem_sz);

	cbuf->tail = (cbuf->tail + (count * cbuf->elem_sz)) &
		     ((cbuf->size - 1) * cbuf->elem_sz);

	return 0;
}
// ac_circ_buf_popm [c]
int ac_circ_buf_popm(ac_circ_buf_t *cbuf, void *buf, u32 count)
{
	if (circ_count_to_end(cbuf) < count)
		return -1;

	if (cbuf->type == PTR_BUF)
		memcpy(buf, cbuf->buf.ptr_buf + cbuf->tail,
		       count * sizeof(void *));
	else
		memcpy(buf, cbuf->buf.cpy_buf + cbuf->tail,
		       count * cbuf->elem_sz);

	cbuf->tail = (cbuf->tail + (count * cbuf->elem_sz)) &
		     ((cbuf->size - 1) * cbuf->elem_sz);

	return 0;
}
// print_c_function [c]
static void print_c_function(const state st) {
  const char TYPE[] = "__m256i ";
  char buf[10];
  printf("static inline void sbox(const %sin0, const %sin1, const %sin2, const %sin3,\n"
      "const %sin4, const %sin5, const %sin6, const %sin7, %s*out0,\n"
      "%s*out1, %s*out2, %s*out3, %s*out4, %s*out5, %s*out6,\n"
      "%s*out7) {\n", TYPE, TYPE, TYPE, TYPE, TYPE, TYPE, TYPE, TYPE, TYPE, TYPE, TYPE, TYPE, TYPE,
      TYPE, TYPE, TYPE);
  for (uint64_t gate = 8; gate < st.num_gates; gate++) {
    bool ret = get_c_variable_name(st, gate, buf);
    printf("  %s%s = ", ret == true ? TYPE : "", buf);
    get_c_variable_name(st, st.gates[gate].in1, buf);
    if (st.gates[gate].type == NOT) {
      printf("~%s;\n", buf);
      continue;
    }
    printf("%s ", buf);
    switch (st.gates[gate].type) {
      case AND:
        printf("& ");
        break;
      case OR:
        printf("| ");
        break;
      case XOR:
        printf("^ ");
        break;
      default:
        assert(false);
    }
    get_c_variable_name(st, st.gates[gate].in2, buf);
    printf("%s;\n", buf);
  }
  printf("}\n");
}
// print_c_function [c]
static void print_c_function(const state st) {
  const char TYPE[] = "__m256i ";
  char buf[10];
  printf("static inline void sbox(const %sin0, const %sin1, const %sin2, const %sin3,\n"
      "const %sin4, const %sin5, const %sin6, const %sin7, %s*out0,\n"
      "%s*out1, %s*out2, %s*out3, %s*out4, %s*out5, %s*out6,\n"
      "%s*out7) {\n", TYPE, TYPE, TYPE, TYPE, TYPE, TYPE, TYPE, TYPE, TYPE, TYPE, TYPE, TYPE, TYPE,
      TYPE, TYPE, TYPE);
  for (uint8_t gate = 8; gate < st.num_gates; gate++) {
    bool ret = get_c_variable_name(st, gate, buf);
    printf("  %s%s = ", ret == true ? TYPE : "", buf);
    get_c_variable_name(st, st.gates[gate].in1, buf);
    if (st.gates[gate].type == NOT) {
      printf("~%s;\n", buf);
      continue;
    }
    printf("%s ", buf);
    switch (st.gates[gate].type) {
      case AND:
        printf("& ");
        break;
      case OR:
        printf("| ");
        break;
      case XOR:
        printf("^ ");
        break;
      default:
        assert(false);
    }
    get_c_variable_name(st, st.gates[gate].in2, buf);
    printf("%s;\n", buf);
  }
  printf("}\n");
}
// g72x_init [c]
g72x_init (SF_PRIVATE * psf)
{	G72x_PRIVATE	*pg72x ;
	int	bitspersample, bytesperblock, codec ;

	if (psf->codec_data != NULL)
	{	psf_log_printf (psf, "*** psf->codec_data is not NULL.\n") ;
		return SFE_INTERNAL ;
		} ;

	psf->sf.seekable = SF_FALSE ;

	if (psf->sf.channels != 1)
		return SFE_G72X_NOT_MONO ;

	if ((pg72x = calloc (1, sizeof (G72x_PRIVATE))) == NULL)
		return SFE_MALLOC_FAILED ;

	psf->codec_data = (void*) pg72x ;

	pg72x->block_curr = 0 ;
	pg72x->sample_curr = 0 ;

	switch (SF_CODEC (psf->sf.format))
	{	case SF_FORMAT_G721_32 :
				codec = G721_32_BITS_PER_SAMPLE ;
				bytesperblock = G721_32_BYTES_PER_BLOCK ;
				bitspersample = G721_32_BITS_PER_SAMPLE ;
				break ;

		case SF_FORMAT_G723_24:
				codec = G723_24_BITS_PER_SAMPLE ;
				bytesperblock = G723_24_BYTES_PER_BLOCK ;
				bitspersample = G723_24_BITS_PER_SAMPLE ;
				break ;

		case SF_FORMAT_G723_40:
				codec = G723_40_BITS_PER_SAMPLE ;
				bytesperblock = G723_40_BYTES_PER_BLOCK ;
				bitspersample = G723_40_BITS_PER_SAMPLE ;
				break ;

		default : return SFE_UNIMPLEMENTED ;
		} ;

	psf->filelength = psf_get_filelen (psf) ;
	if (psf->filelength < psf->dataoffset)
		psf->filelength = psf->dataoffset ;

	psf->datalength = psf->filelength - psf->dataoffset ;
	if (psf->dataend > 0)
		psf->datalength -= psf->filelength - psf->dataend ;

	if (psf->file.mode == SFM_READ)
	{	pg72x->private = g72x_reader_init (codec, &(pg72x->blocksize), &(pg72x->samplesperblock)) ;
		if (pg72x->private == NULL)
			return SFE_MALLOC_FAILED ;

		pg72x->bytesperblock = bytesperblock ;

		psf->read_short		= g72x_read_s ;
		psf->read_int		= g72x_read_i ;
		psf->read_float		= g72x_read_f ;
		psf->read_double	= g72x_read_d ;

		psf->seek = g72x_seek ;

		if (psf->datalength % pg72x->blocksize)
		{	psf_log_printf (psf, "*** Odd psf->datalength (%D) should be a multiple of %d\n", psf->datalength, pg72x->blocksize) ;
			pg72x->blocks_total = (psf->datalength / pg72x->blocksize) + 1 ;
			}
		else
			pg72x->blocks_total = psf->datalength / pg72x->blocksize ;

		psf->sf.frames = (sf_count_t) pg72x->blocks_total * pg72x->samplesperblock ;

		psf_g72x_decode_block (psf, pg72x) ;
		}
	else if (psf->file.mode == SFM_WRITE)
	{	pg72x->private = g72x_writer_init (codec, &(pg72x->blocksize), &(pg72x->samplesperblock)) ;
		if (pg72x->private == NULL)
			return SFE_MALLOC_FAILED ;

		pg72x->bytesperblock = bytesperblock ;

		psf->write_short	= g72x_write_s ;
		psf->write_int		= g72x_write_i ;
		psf->write_float	= g72x_write_f ;
		psf->write_double	= g72x_write_d ;

		if (psf->datalength % pg72x->blocksize)
			pg72x->blocks_total = (psf->datalength / pg72x->blocksize) + 1 ;
		else
			pg72x->blocks_total = psf->datalength / pg72x->blocksize ;

		if (psf->datalength > 0)
			psf->sf.frames = (8 * psf->datalength) / bitspersample ;

		if ((psf->sf.frames * bitspersample) / 8 != psf->datalength)
			psf_log_printf (psf, "*** Warning : weird psf->datalength.\n") ;
		} ;

	psf->codec_close	= g72x_close ;

	return 0 ;
} /* g72x_init */
// g72x_init [c]
g72x_init (SF_PRIVATE * psf)
{	G72x_PRIVATE	*pg72x ;
	int	bitspersample, bytesperblock, codec ;

	if (psf->codec_data != NULL)
	{	psf_log_printf (psf, "*** psf->codec_data is not NULL.\n") ;
		return SFE_INTERNAL ;
		} ;

	psf->sf.seekable = SF_FALSE ;

	if (psf->sf.channels != 1)
		return SFE_G72X_NOT_MONO ;

	if ((pg72x = calloc (1, sizeof (G72x_PRIVATE))) == NULL)
		return SFE_MALLOC_FAILED ;

	psf->codec_data = (void*) pg72x ;

	pg72x->block_curr = 0 ;
	pg72x->sample_curr = 0 ;

	switch (SF_CODEC (psf->sf.format))
	{	case SF_FORMAT_G721_32 :
				codec = G721_32_BITS_PER_SAMPLE ;
				bytesperblock = G721_32_BYTES_PER_BLOCK ;
				bitspersample = G721_32_BITS_PER_SAMPLE ;
				break ;

		case SF_FORMAT_G723_24:
				codec = G723_24_BITS_PER_SAMPLE ;
				bytesperblock = G723_24_BYTES_PER_BLOCK ;
				bitspersample = G723_24_BITS_PER_SAMPLE ;
				break ;

		case SF_FORMAT_G723_40:
				codec = G723_40_BITS_PER_SAMPLE ;
				bytesperblock = G723_40_BYTES_PER_BLOCK ;
				bitspersample = G723_40_BITS_PER_SAMPLE ;
				break ;

		default : return SFE_UNIMPLEMENTED ;
		} ;

	psf->filelength = psf_get_filelen (psf) ;
	if (psf->filelength < psf->dataoffset)
		psf->filelength = psf->dataoffset ;

	psf->datalength = psf->filelength - psf->dataoffset ;
	if (psf->dataend > 0)
		psf->datalength -= psf->filelength - psf->dataend ;

	if (psf->file.mode == SFM_READ)
	{	pg72x->private = g72x_reader_init (codec, &(pg72x->blocksize), &(pg72x->samplesperblock)) ;
		if (pg72x->private == NULL)
			return SFE_MALLOC_FAILED ;

		pg72x->bytesperblock = bytesperblock ;

		psf->read_short		= g72x_read_s ;
		psf->read_int		= g72x_read_i ;
		psf->read_float		= g72x_read_f ;
		psf->read_double	= g72x_read_d ;

		psf->seek = g72x_seek ;

		if (psf->datalength % pg72x->blocksize)
		{	psf_log_printf (psf, "*** Odd psf->datalength (%D) should be a multiple of %d\n", psf->datalength, pg72x->blocksize) ;
			pg72x->blocks_total = (psf->datalength / pg72x->blocksize) + 1 ;
			}
		else
			pg72x->blocks_total = psf->datalength / pg72x->blocksize ;

		psf->sf.frames = pg72x->blocks_total * pg72x->samplesperblock ;

		psf_g72x_decode_block (psf, pg72x) ;
		}
	else if (psf->file.mode == SFM_WRITE)
	{	pg72x->private = g72x_writer_init (codec, &(pg72x->blocksize), &(pg72x->samplesperblock)) ;
		if (pg72x->private == NULL)
			return SFE_MALLOC_FAILED ;

		pg72x->bytesperblock = bytesperblock ;

		psf->write_short	= g72x_write_s ;
		psf->write_int		= g72x_write_i ;
		psf->write_float	= g72x_write_f ;
		psf->write_double	= g72x_write_d ;

		if (psf->datalength % pg72x->blocksize)
			pg72x->blocks_total = (psf->datalength / pg72x->blocksize) + 1 ;
		else
			pg72x->blocks_total = psf->datalength / pg72x->blocksize ;

		if (psf->datalength > 0)
			psf->sf.frames = (8 * psf->datalength) / bitspersample ;

		if ((psf->sf.frames * bitspersample) / 8 != psf->datalength)
			psf_log_printf (psf, "*** Warning : weird psf->datalength.\n") ;
		} ;

	psf->codec_close	= g72x_close ;

	return 0 ;
} /* g72x_init */
// ac_circ_buf_new [c]
ac_circ_buf_t *ac_circ_buf_new(u32 size, u32 elem_sz)
{
	ac_circ_buf_t *cbuf;

	if (!is_pow2(size))
		return NULL;

	cbuf = malloc(sizeof(ac_circ_buf_t));
	cbuf->head = cbuf->tail = 0;
	cbuf->size = size;

	if (elem_sz == 0) {
		cbuf->elem_sz = 1;
		cbuf->type = PTR_BUF;
		cbuf->buf.ptr_buf = malloc(size * sizeof(void *));
	} else {
		cbuf->elem_sz = elem_sz;
		cbuf->type = CPY_BUF;
		cbuf->buf.cpy_buf = malloc((size_t)size * elem_sz);
	}

	return cbuf;
}
// ac_circ_buf_new [c]
ac_circ_buf_t *ac_circ_buf_new(u32 size, u32 elem_sz)
{
	ac_circ_buf_t *cbuf;

	if (!is_pow2(size))
		return NULL;

	cbuf = malloc(sizeof(ac_circ_buf_t));
	cbuf->head = cbuf->tail = 0;
	cbuf->size = size;

	if (elem_sz == 0) {
		cbuf->elem_sz = 1;
		cbuf->type = PTR_BUF;
		cbuf->buf.ptr_buf = malloc(size * sizeof(void *));
	} else {
		cbuf->elem_sz = elem_sz;
		cbuf->type = CPY_BUF;
		cbuf->buf.cpy_buf = malloc(size * elem_sz);
	}

	return cbuf;
}
// ac_circ_buf_pushm [c]
int ac_circ_buf_pushm(ac_circ_buf_t *cbuf, const void *buf, u32 count)
{
	if (circ_space_to_end(cbuf) < count) {
		if (circ_count(cbuf) == 0 && count <= cbuf->size)
			cbuf->head = cbuf->tail = 0;
		else
			return -1;
	}

	if (cbuf->type == PTR_BUF)
		memcpy(cbuf->buf.ptr_buf + cbuf->head, buf,
		       count * sizeof(void *));
	else
		memcpy(cbuf->buf.cpy_buf + cbuf->head, buf,
		       (size_t)count * cbuf->elem_sz);

	cbuf->head = (cbuf->head + (count * cbuf->elem_sz)) &
		     ((cbuf->size - 1) * cbuf->elem_sz);

	return 0;
}
// ac_circ_buf_pushm [c]
int ac_circ_buf_pushm(ac_circ_buf_t *cbuf, const void *buf, u32 count)
{
	if (circ_space_to_end(cbuf) < count) {
		if (circ_count(cbuf) == 0 && count <= cbuf->size)
			cbuf->head = cbuf->tail = 0;
		else
			return -1;
	}

	if (cbuf->type == PTR_BUF)
		memcpy(cbuf->buf.ptr_buf + cbuf->head, buf,
		       count * sizeof(void *));
	else
		memcpy(cbuf->buf.cpy_buf + cbuf->head, buf,
		       count * cbuf->elem_sz);

	cbuf->head = (cbuf->head + (count * cbuf->elem_sz)) &
		     ((cbuf->size - 1) * cbuf->elem_sz);

	return 0;
}
// gsm610_init [c]
gsm610_init	(SF_PRIVATE *psf)
{	GSM610_PRIVATE	*pgsm610 ;
	int		true_flag = 1 ;

	if (psf->codec_data != NULL)
	{	psf_log_printf (psf, "*** psf->codec_data is not NULL.\n") ;
		return SFE_INTERNAL ;
		} ;

	if (psf->file.mode == SFM_RDWR)
		return SFE_BAD_MODE_RW ;

	psf->sf.seekable = SF_FALSE ;

	if ((pgsm610 = calloc (1, sizeof (GSM610_PRIVATE))) == NULL)
		return SFE_MALLOC_FAILED ;

	psf->codec_data = pgsm610 ;

	memset (pgsm610, 0, sizeof (GSM610_PRIVATE)) ;

/*============================================================

Need separate gsm_data structs for encode and decode.

============================================================*/

	if ((pgsm610->gsm_data = gsm_create ()) == NULL)
		return SFE_MALLOC_FAILED ;

	switch (SF_CONTAINER (psf->sf.format))
	{	case SF_FORMAT_WAV :
		case SF_FORMAT_WAVEX :
		case SF_FORMAT_W64 :
			gsm_option (pgsm610->gsm_data, GSM_OPT_WAV49, &true_flag) ;

			pgsm610->encode_block = gsm610_wav_encode_block ;
			pgsm610->decode_block = gsm610_wav_decode_block ;

			pgsm610->samplesperblock = WAVLIKE_GSM610_SAMPLES ;
			pgsm610->blocksize = WAVLIKE_GSM610_BLOCKSIZE ;
			break ;

		case SF_FORMAT_AIFF :
		case SF_FORMAT_RAW :
			pgsm610->encode_block = gsm610_encode_block ;
			pgsm610->decode_block = gsm610_decode_block ;

			pgsm610->samplesperblock = GSM610_SAMPLES ;
			pgsm610->blocksize = GSM610_BLOCKSIZE ;
			break ;

		default :
			return SFE_INTERNAL ;
			break ;
		} ;

	if (psf->file.mode == SFM_READ)
	{	if (psf->datalength % pgsm610->blocksize == 0)
			pgsm610->blocks = psf->datalength / pgsm610->blocksize ;
		else if (psf->datalength % pgsm610->blocksize == 1 && pgsm610->blocksize == GSM610_BLOCKSIZE)
		{	/*
			**	Weird AIFF specific case.
			**	AIFF chunks must be at an even offset from the start of file and
			**	GSM610_BLOCKSIZE is odd which can result in an odd length SSND
			**	chunk. The SSND chunk then gets padded on write which means that
			**	when it is read the datalength is too big by 1.
			*/
			pgsm610->blocks = psf->datalength / pgsm610->blocksize ;
			}
		else
		{	psf_log_printf (psf, "*** Warning : data chunk seems to be truncated.\n") ;
			pgsm610->blocks = psf->datalength / pgsm610->blocksize + 1 ;
			} ;

		psf->sf.frames = (sf_count_t) pgsm610->samplesperblock * pgsm610->blocks ;

		psf_fseek (psf, psf->dataoffset, SEEK_SET) ;

		pgsm610->decode_block (psf, pgsm610) ;	/* Read first block. */

		psf->read_short		= gsm610_read_s ;
		psf->read_int		= gsm610_read_i ;
		psf->read_float		= gsm610_read_f ;
		psf->read_double	= gsm610_read_d ;
		} ;

	if (psf->file.mode == SFM_WRITE)
	{	pgsm610->blockcount = 0 ;
		pgsm610->samplecount = 0 ;

		psf->write_short	= gsm610_write_s ;
		psf->write_int		= gsm610_write_i ;
		psf->write_float	= gsm610_write_f ;
		psf->write_double	= gsm610_write_d ;
		} ;

	psf->codec_close = gsm610_close ;

	psf->seek = gsm610_seek ;

	psf->filelength = psf_get_filelen (psf) ;
	psf->datalength = psf->filelength - psf->dataoffset ;

	return 0 ;
} /* gsm610_init */
// gsm610_init [c]
gsm610_init	(SF_PRIVATE *psf)
{	GSM610_PRIVATE	*pgsm610 ;
	int		true_flag = 1 ;

	if (psf->codec_data != NULL)
	{	psf_log_printf (psf, "*** psf->codec_data is not NULL.\n") ;
		return SFE_INTERNAL ;
		} ;

	if (psf->file.mode == SFM_RDWR)
		return SFE_BAD_MODE_RW ;

	psf->sf.seekable = SF_FALSE ;

	if ((pgsm610 = calloc (1, sizeof (GSM610_PRIVATE))) == NULL)
		return SFE_MALLOC_FAILED ;

	psf->codec_data = pgsm610 ;

	memset (pgsm610, 0, sizeof (GSM610_PRIVATE)) ;

/*============================================================

Need separate gsm_data structs for encode and decode.

============================================================*/

	if ((pgsm610->gsm_data = gsm_create ()) == NULL)
		return SFE_MALLOC_FAILED ;

	switch (SF_CONTAINER (psf->sf.format))
	{	case SF_FORMAT_WAV :
		case SF_FORMAT_WAVEX :
		case SF_FORMAT_W64 :
			gsm_option (pgsm610->gsm_data, GSM_OPT_WAV49, &true_flag) ;

			pgsm610->encode_block = gsm610_wav_encode_block ;
			pgsm610->decode_block = gsm610_wav_decode_block ;

			pgsm610->samplesperblock = WAVLIKE_GSM610_SAMPLES ;
			pgsm610->blocksize = WAVLIKE_GSM610_BLOCKSIZE ;
			break ;

		case SF_FORMAT_AIFF :
		case SF_FORMAT_RAW :
			pgsm610->encode_block = gsm610_encode_block ;
			pgsm610->decode_block = gsm610_decode_block ;

			pgsm610->samplesperblock = GSM610_SAMPLES ;
			pgsm610->blocksize = GSM610_BLOCKSIZE ;
			break ;

		default :
			return SFE_INTERNAL ;
			break ;
		} ;

	if (psf->file.mode == SFM_READ)
	{	if (psf->datalength % pgsm610->blocksize == 0)
			pgsm610->blocks = psf->datalength / pgsm610->blocksize ;
		else if (psf->datalength % pgsm610->blocksize == 1 && pgsm610->blocksize == GSM610_BLOCKSIZE)
		{	/*
			**	Weird AIFF specific case.
			**	AIFF chunks must be at an even offset from the start of file and
			**	GSM610_BLOCKSIZE is odd which can result in an odd length SSND
			**	chunk. The SSND chunk then gets padded on write which means that
			**	when it is read the datalength is too big by 1.
			*/
			pgsm610->blocks = psf->datalength / pgsm610->blocksize ;
			}
		else
		{	psf_log_printf (psf, "*** Warning : data chunk seems to be truncated.\n") ;
			pgsm610->blocks = psf->datalength / pgsm610->blocksize + 1 ;
			} ;

		psf->sf.frames = pgsm610->samplesperblock * pgsm610->blocks ;

		psf_fseek (psf, psf->dataoffset, SEEK_SET) ;

		pgsm610->decode_block (psf, pgsm610) ;	/* Read first block. */

		psf->read_short		= gsm610_read_s ;
		psf->read_int		= gsm610_read_i ;
		psf->read_float		= gsm610_read_f ;
		psf->read_double	= gsm610_read_d ;
		} ;

	if (psf->file.mode == SFM_WRITE)
	{	pgsm610->blockcount = 0 ;
		pgsm610->samplecount = 0 ;

		psf->write_short	= gsm610_write_s ;
		psf->write_int		= gsm610_write_i ;
		psf->write_float	= gsm610_write_f ;
		psf->write_double	= gsm610_write_d ;
		} ;

	psf->codec_close = gsm610_close ;

	psf->seek = gsm610_seek ;

	psf->filelength = psf_get_filelen (psf) ;
	psf->datalength = psf->filelength - psf->dataoffset ;

	return 0 ;
} /* gsm610_init */