Format data to get a readable output
356374
def _format_output(selected_number, raw_data):
    """"""
    tmp_data = {}
    data = collections.defaultdict(lambda: 0)
    balance = raw_data.pop('balance')
    for number in raw_data.keys():
        tmp_data = dict([(k, int(v) if v is not None else "No limit")
                         for k, v in raw_data[number].items()])
        tmp_data['number'] = number
        if selected_number is None or selected_number == number:
            data[number] = tmp_data

    output = ("""Account Balance
=======

Balance:      {:.2f} $
""")
    print(output.format(balance))
    for number_data in data.values():
        _print_number(number_data)
1372381
def _format_return_data(retcode, stdout=None, stderr=None):
    '''
    
    '''
    ret = {'retcode': retcode}
    if stdout is not None:
        ret['stdout'] = stdout
    if stderr is not None:
        ret['stderr'] = stderr
    return ret
26689
def _sec_to_readable(t):
    """"""
    # This will only work for < 1 day execution time
    # And we reserve 2 digits for minutes because presumably
    # there aren't many > 99 minute scripts, but occasionally some
    # > 9 minute ones
    t = datetime(1, 1, 1) + timedelta(seconds=t)
    t = '{0:02d}:{1:02d}.{2:03d}'.format(
        t.hour * 60 + t.minute, t.second,
        int(round(t.microsecond / 1000.)))
    return t
989468
def dump(data,output=$stdout)
      unless output.respond_to?(:<<)
        raise(ArgumentError,"output must support the #<< method")
      end

      bytes_segment_width = ((@width * @format_width) + @width)
      line_format = "%.8x  %-#{bytes_segment_width}s |%s|\n"

      index = 0
      count = 0

      numeric   = ''
      printable = ''

      each_word(data) do |word|
        numeric   << format_numeric(word) << ' '
        printable << format_printable(word)

        count += 1

        if count >= @width
          output << sprintf(line_format,index,numeric,printable)

          numeric   = ''
          printable = ''

          index += (@width * @word_size)
          count  = 0
        end
      end

      if count > 0
        # output the remaining line
        output << sprintf(line_format,index,numeric,printable)
      end
    end
1363281
def _format_table(fmt, headers, rows, colwidths, colaligns):
    """"""
    lines = []
    hidden = fmt.with_header_hide if (headers and fmt.with_header_hide) else []
    pad = fmt.padding
    headerrow = fmt.headerrow

    padded_widths = [(w + 2*pad) for w in colwidths]
    padded_headers = _pad_row(headers, pad)
    padded_rows = [_pad_row(row, pad) for row in rows]

    if fmt.lineabove and "lineabove" not in hidden:
        lines.append(_build_line(padded_widths, colaligns, fmt.lineabove))

    if padded_headers:
        lines.append(_build_row(padded_headers, padded_widths, colaligns, headerrow))
        if fmt.linebelowheader and "linebelowheader" not in hidden:
            lines.append(_build_line(padded_widths, colaligns, fmt.linebelowheader))

    if padded_rows and fmt.linebetweenrows and "linebetweenrows" not in hidden:
        # initial rows with a line below
        for row in padded_rows[:-1]:
            lines.append(_build_row(row, padded_widths, colaligns, fmt.datarow))
            lines.append(_build_line(padded_widths, colaligns, fmt.linebetweenrows))
        # the last row without a line below
        lines.append(_build_row(padded_rows[-1], padded_widths, colaligns, fmt.datarow))
    else:
        for row in padded_rows:
            lines.append(_build_row(row, padded_widths, colaligns, fmt.datarow))

    if fmt.linebelow and "linebelow" not in hidden:
        lines.append(_build_line(padded_widths, colaligns, fmt.linebelow))

    return "\n".join(lines)
435524
def format(self):
        ''' 
        '''
        self.max_lengths = []
        for row in self.rows:
            if len(self.max_lengths) < len(row):
                self.max_lengths += [0] * (len(row) - len(self.max_lengths))
            for idx, val in enumerate(row):
                len_cell = len(str(val)) if val else 0
                if self.max_lengths[idx] < len_cell:
                    self.max_lengths[idx] = len_cell
        return self.max_lengths
1132749
def format_output(instances, flag):
    """"""
    out = []
    line_format = '{0}\t{1}\t{2}\t{3}'
    name_len = _get_max_name_len(instances) + 3
    if flag:
        line_format = '{0:<' + str(name_len+5) + '}{1:<16}{2:<65}{3:<16}'

    for i in instances:
        endpoint = "{0}:{1}".format(i['Endpoint']['Address'], i['Endpoint']['Port'])
        out.append(
            line_format.format(i['DBInstanceIdentifier'], i['DBInstanceStatus'], endpoint, i['Engine']))
    return out
1141921
def format(self):
        
        _bold = bold
        _break = "\n    "
        if not self.pretty:
            _bold = lambda x: x
        # Attach memory address and return
        _attrs = self._format_attrs()
        parent_name = get_parent_name(self.obj) if self.full_name else None
        self.data = "<{}{}:{}{}>{}".format(
            parent_name + "." if parent_name else "",
            get_obj_name(self.obj),
            _attrs,
            ":{}".format(hex(id(self.obj))) if self.address else "",
            _break+self.supplemental if self.supplemental else "")
        return stdout_encode(self.data)
498695
def _format_info(data):
    '''
    
    '''
    return {'name': data.gr_name,
            'gid': data.gr_gid,
            'passwd': data.gr_passwd,
            'members': data.gr_mem}
906471
def _format_info(data):
    '''
    
    '''
    return {'gid': data.pw_gid,
            'groups': list_groups(data.pw_name),
            'home': data.pw_dir,
            'name': data.pw_name,
            'shell': data.pw_shell,
            'uid': data.pw_uid,
            'fullname': data.pw_gecos}
1125431
def format_prettytable(table):
    """"""
    for i, row in enumerate(table.rows):
        for j, item in enumerate(row):
            table.rows[i][j] = format_output(item)

    ptable = table.prettytable()
    ptable.hrules = prettytable.FRAME
    ptable.horizontal_char = '.'
    ptable.vertical_char = ':'
    ptable.junction_char = ':'
    return ptable
1048672
def _format_info(data):
    '''
    
    '''
    # Put GECOS info into a list
    gecos_field = salt.utils.stringutils.to_unicode(data.pw_gecos).split(',', 4)
    # Make sure our list has at least five elements
    while len(gecos_field) < 5:
        gecos_field.append('')

    return {'gid': data.pw_gid,
            'groups': list_groups(data.pw_name),
            'home': data.pw_dir,
            'name': data.pw_name,
            'passwd': data.pw_passwd,
            'shell': data.pw_shell,
            'uid': data.pw_uid,
            'fullname': gecos_field[0],
            'roomnumber': gecos_field[1],
            'workphone': gecos_field[2],
            'homephone': gecos_field[3],
            'other': gecos_field[4]}
1268839
def bytes_to_c_string(data):
    
    rows = chunked_join(data, 20, 2, '"\n    "', '', r'\x' + X)
    logging.debug(_('Returning rows: %s'), rows)
    return '"{}";'.format(rows)
996006
def _format_data(data):
        # type: (Union[str, IO]) -> Union[Tuple[None, str], Tuple[Optional[str], IO, str]]
        
        if hasattr(data, 'read'):
            data = cast(IO, data)
            data_name = None
            try:
                if data.name[0] != '<' and data.name[-1] != '>':
                    data_name = os.path.basename(data.name)
            except (AttributeError, TypeError):
                pass
            return (data_name, data, "application/octet-stream")
        return (None, cast(str, data))
723995
def format(self, obj, **kwargs):
        """"""
        sio = StringIO()
        self.fprint(obj, stream=sio, **kwargs)
        return sio.getvalue()
717068
def output(data, **kwargs):  # pylint: disable=unused-argument
    '''
    
    '''
    try:
        if 'output_indent' not in __opts__:
            return salt.utils.json.dumps(data, default=repr, indent=4)

        indent = __opts__.get('output_indent')
        sort_keys = False

        if indent is None:
            indent = None

        elif indent == 'pretty':
            indent = 4
            sort_keys = True

        elif isinstance(indent, int):
            if indent >= 0:
                indent = indent
            else:
                indent = None

        return salt.utils.json.dumps(data, default=repr, indent=indent, sort_keys=sort_keys)

    except UnicodeDecodeError as exc:
        log.error('Unable to serialize output to json')
        return salt.utils.json.dumps(
            {'error': 'Unable to serialize output to json',
             'message': six.text_type(exc)}
        )

    except TypeError:
        log.debug('An error occurred while outputting JSON', exc_info=True)
    # Return valid JSON for unserializable objects
    return salt.utils.json.dumps({})
1012538
function formatAll(results, options, showName) {
    var stdout = '';
    if (showName) {
      for (var i = 0; i < results.length; ++i) {
        stdout += results[i].path + ':\n';
        if (options.l) {
          stdout += 'total ' + results[i].size + '\n';
        }
        stdout += results[i].results;
        if (i !== results.length - 1) {
          stdout += '\n\n';
        }
      }
    } else if (results.length === 1) {
      if (options.l && !options.x) {
        stdout += 'total ' + results[0].size + '\n';
      }
      stdout += results[0].results;
    }
    return stdout;
  }