How to use the six.StringIO function in six

To help you get started, we’ve selected a few six examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github rgal / gym-2048 / gym_2048 / envs / game2048_env.py View on Github external
draw.rectangle([0, 0, 4 * grid_size, 4 * grid_size], grey)
            fnt = ImageFont.truetype('Arial.ttf', 30)

            for y in range(4):
              for x in range(4):
                 o = self.get(y, x)
                 if o:
                     draw.rectangle([x * grid_size, y * grid_size, (x + 1) * grid_size, (y + 1) * grid_size], tile_colour_map[o])
                     (text_x_size, text_y_size) = draw.textsize(str(o), font=fnt)
                     draw.text((x * grid_size + (grid_size - text_x_size) // 2, y * grid_size + (grid_size - text_y_size) // 2), str(o), font=fnt, fill=white)
                     assert text_x_size < grid_size
                     assert text_y_size < grid_size

            return np.asarray(pil_board).swapaxes(0, 1)

        outfile = StringIO() if mode == 'ansi' else sys.stdout
        s = 'Score: {}\n'.format(self.score)
        s += 'Highest: {}\n'.format(self.highest())
        npa = np.array(self.Matrix)
        grid = npa.reshape((self.size, self.size))
        s += "{}\n".format(grid)
        outfile.write(s)
        return outfile
github koji-project / koji / tests / test_cli / test_tag_build.py View on Github external
def test_handle_tag_build_quiet_mode(self):
        """Test handle_tag_build function with --nowait option"""
        pkgs = ['pkg_a-1.0-1fc26']
        arguments = ['tag', '--nowait'] + pkgs
        task_id = 4004

        expected = "Created task %d" % task_id + "\n"
        self.session.tagBuild.side_effect = [task_id]
        with mock.patch('sys.stdout', new_callable=six.StringIO) as stdout:
            rv = handle_tag_build(self.options, self.session, arguments)
        self.assertEqual(rv, None)
        self.assert_console_message(stdout, expected)
        self.activate_session.assert_called_with(self.session, self.options)
        self.watch_tasks.assert_not_called()
github lmaurits / BEASTling / tests / util.py View on Github external
def capture_all(func, *args, **kw):
    out, sys.stdout = sys.stdout, StringIO()
    err, sys.stderr = sys.stderr, StringIO()
    ret = func(*args, **kw)
    sys.stdout.seek(0)
    sys.stderr.seek(0)
    yield ret, sys.stdout.read(), sys.stderr.read()
    sys.stdout, sys.stderr = out, err
github saxix / django-adminactions / tests / test_api.py View on Github external
def test_callable_method(self):
        fields = ['codename', 'natural_key']
        mem = six.StringIO()
        with self.assertNumQueries(2):
            qs = Permission.objects.filter(codename='add_user')
            export_as_csv(queryset=qs, fields=fields, out=mem)
        mem.seek(0)
        csv_dump = mem.read()
        if six.PY2:
            self.assertEqual(csv_dump.decode('utf8'), u'"add_user";"(u\'add_user\', u\'auth\', u\'user\')"\r\n')
        else:
            self.assertEqual(csv_dump, '"add_user";"(\'add_user\', \'auth\', \'user\')"\r\n')
github tox-dev / tox / tests / unit / session / test_show_config.py View on Github external
def load_config(args, cmd):
    result = cmd(*args)
    result.assert_success(is_run_test_env=False)
    parser = configparser.ConfigParser()
    output = StringIO(result.out)
    (parser.readfp if PY2 else parser.read_file)(output)
    return parser
github getsentry / sentry / src / sentry / middleware / profiler.py View on Github external
def process_response(self, request, response):
        if not self.can(request):
            return response

        out = StringIO.StringIO()
        old_stdout = sys.stdout
        sys.stdout = out

        stats = pstats.Stats(self.prof)
        self.normalize_paths(stats)
        stats.sort_stats("time", "calls")
        stats.print_stats()

        sys.stdout = old_stdout
        stats_str = out.getvalue()

        content = "\n".join(stats_str.split("\n")[:40])
        content += "\n\n"
        content += self.summary_for_files(stats_str)

        return HttpResponse(content, "text/plain")
github Pyomo / pyomo / pyomo / contrib / trustregion / GeometryGenerator.py View on Github external
"editable (development) source trees." % (CACHE_FILE,))
        sys.exit()

    if len(sys.argv) > 1:
        LX_SET = range(*tuple(int(i) for i in sys.argv[1].split(':')))
    else:
        LX_SET = range(1,24)
    if len(sys.argv) > 2:
        COUNT = int(sys.argv[2])
    else:
        COUNT = None
    for lx in LX_SET:
        local_count = COUNT if COUNT else 10000*lx
        cond, pset, mat = generate_quadratic_rom_geometry(lx, local_count)
        if pset is not None:
            txt = StringIO()
            np.savetxt(txt, pset)
            GeometryCache[lx] = (cond, txt.getvalue())
            with open(CACHE_FILE,'w') as FILE:
                FILE.write("""
# ___________________________________________________________________________
#
# Pyomo: Python Optimization Modeling Objects
# Copyright 2017 National Technology and Engineering Solutions of Sandia, LLC
# Under the terms of Contract DE-NA0003525 with National Technology and
# Engineering Solutions of Sandia, LLC, the U.S. Government retains certain
# rights in this software.
# This software is distributed under the 3-clause BSD License.
# ___________________________________________________________________________
#
# Cache of autogenerated quadratic ROM geometries
#
github Pyomo / pyomo / pyomo / core / base / block.py View on Github external
_blockName, str(data))
            try:
                val.construct(data)
            except:
                err = sys.exc_info()[1]
                logger.error(
                    "Constructing component '%s' from data=%s failed:\n%s: %s",
                    str(val.name), str(data).strip(),
                    type(err).__name__, err)
                raise
            if __debug__ and logger.isEnabledFor(logging.DEBUG):
                if _blockName[-1] == "'":
                    _blockName = _blockName[:-1] + '.' + val.name + "'"
                else:
                    _blockName = "'" + _blockName + '.' + val.name + "'"
                _out = StringIO()
                val.pprint(ostream=_out)
                logger.debug("Constructed component '%s':\n%s"
                             % (_blockName, _out.getvalue()))
github joke2k / faker / faker / providers / misc / __init__.py View on Github external
:param include_row_ids: True to include a sequential row ID column
        :param fmtparams: Formatting parameters expected by csv.writer
        :return: Delimiter-separated values, csv by default
        """

        if not isinstance(num_rows, int) or num_rows <= 0:
            raise ValueError('`num_rows` must be a positive integer')
        if not isinstance(data_columns, (list, tuple)):
            raise TypeError('`data_columns` must be a tuple or a list')
        if header is not None:
            if not isinstance(header, (list, tuple)):
                raise TypeError('`header` must be a tuple or a list')
            if len(header) != len(data_columns):
                raise ValueError('`header` and `data_columns` must have matching lengths')

        dsv_buffer = six.StringIO()
        writer = csv.writer(dsv_buffer, dialect=dialect, **fmtparams)

        if header:
            if include_row_ids:
                header = list(header)
                header.insert(0, 'ID')
            writer.writerow(header)

        for row_num in range(1, num_rows + 1):
            if six.PY2:
                row = [self.generator.pystr_format(column).encode('utf-8') for column in data_columns]
            else:
                row = [self.generator.pystr_format(column) for column in data_columns]
            if include_row_ids:
                row.insert(0, str(row_num))
github tensorflow / tensorflow / tensorflow / tensorboard / backend / application.py View on Github external
  @wrappers.Request.application
  def _serve_scalars(self, request):
    """Given a tag and single run, return array of ScalarEvents."""
    # TODO(cassandrax): return HTTP status code for malformed requests
    tag = request.args.get('tag')
    run = request.args.get('run')
    values = self._multiplexer.Scalars(run, tag)

    if request.args.get('format') == _OutputFormat.CSV:
      string_io = StringIO()
      writer = csv.writer(string_io)
      writer.writerow(['Wall time', 'Step', 'Value'])
      writer.writerows(values)
      return http_util.Respond(request, string_io.getvalue(), 'text/csv')
    else:
      return http_util.Respond(request, values, 'application/json')