Return xlsx column widths based on default and user-specified field-value pairs.
332019
def _get_fld2col_widths(self, **kws):
        """"""
        fld2col_widths = self._init_fld2col_widths()
        if 'fld2col_widths' not in kws:
            return fld2col_widths
        for fld, val in kws['fld2col_widths'].items():
            fld2col_widths[fld] = val
        return fld2col_widths
1230893
def _size_columns(self, container):
        
        def calculate_column_widths(max_cell_width):
            """Calculate required column widths given a maximum cell width"""
            def cell_content_width(cell):
                buffer = VirtualContainer(container, width=max_cell_width)
                width, _, _ = cell.flow(buffer, None)
                return float(width)

            widths = [0] * self.body.num_columns
            for row in chain(self.head or [], self.body):
                for cell in (cell for cell in row if cell.colspan == 1):
                    col = int(cell.column_index)
                    widths[col] = max(widths[col], cell_content_width(cell))
            for row in chain(self.head or [], self.body):
                for cell in (cell for cell in row if cell.colspan > 1):
                    c = int(cell.column_index)
                    c_end = c + cell.colspan
                    padding = cell_content_width(cell) - sum(widths[c:c_end])
                    if padding > 0:
                        per_column_padding = padding / cell.colspan
                        for i in range(cell.colspan):
                            widths[c + i] += per_column_padding
            return widths

        width = self._width(container)
        try:
            fixed_width = width.to_points(container.width)
        except AttributeError:
            fixed_width = width or FlowableWidth.AUTO
        min_column_widths = calculate_column_widths(0)
        max_column_widths = calculate_column_widths(float('+inf'))

        # calculate relative column widths for auto-sized columns
        auto_rel_colwidths = [sqrt(minimum * maximum) for minimum, maximum
                              in zip(min_column_widths, max_column_widths)]
        column_widths = self.column_widths or [None for _ in max_column_widths]
        try:          # TODO: max() instead of min()?
            relative_factor = min(auto_relative_width / width
                                  for width, auto_relative_width
                                  in zip(column_widths, auto_rel_colwidths)
                                  if width and not isinstance(width, DimBase))
        except ValueError:
            relative_factor = 1
        column_widths = [auto_relative_width * relative_factor
                         if width is None else width
                         for width, auto_relative_width
                         in zip(column_widths, auto_rel_colwidths)]

        # set min = max for columns with a fixed width
        total_fixed_cols_width = 0
        total_portions = 0
        for i, column_width in enumerate(column_widths):
            if isinstance(column_width, DimBase):
                width_in_pt = column_width.to_points(container.width)
                min_column_widths[i] = max_column_widths[i] = width_in_pt
                total_fixed_cols_width += width_in_pt
            else:
                total_portions += column_width

        # does the table fit within the available width without wrapping?
        if sum(max_column_widths) <= container.width:
            return max_column_widths

        # determine table width
        if fixed_width != FlowableWidth.AUTO:
            table_width = fixed_width
        elif total_portions:
            max_factor = max(maximum / width for width, maximum,
                             in zip(column_widths, max_column_widths)
                             if not isinstance(width, DimBase))
            no_wrap_rel_cols_width = total_portions * max_factor
            table_width = min(total_fixed_cols_width + no_wrap_rel_cols_width,
                              float(container.width))
        else:
            table_width = total_fixed_cols_width

        # TODO: warn when a column's fixed width < min width

        # determine absolute width of columns with relative widths
        if total_portions:
            total_relative_cols_width = table_width - total_fixed_cols_width
            portion_width = total_relative_cols_width / total_portions
            auto_widths = [width if isinstance(width, DimBase)
                           else width * portion_width
                           for width in column_widths]
            extra = [0 if isinstance(width, DimBase)
                     else auto_width - min_column_widths[index]
                     for index, auto_width in enumerate(auto_widths)]
            excess = [0 if isinstance(width, DimBase)
                      else auto_width - max_column_widths[index]
                      for index, auto_width in enumerate(auto_widths)]
            excess_pos = sum(x for x in excess if x > 0)
            extra_neg = sum(x for x in extra if x <= 0) + excess_pos
            extra_pos = (sum(x for x, c in zip(extra, excess)
                             if x > 0 and c <= 0))
            if extra_pos + extra_neg < 0:
                self.warn('Table contents are too wide to fit within the '
                          'available width', container)
                return [width.to_points(container.width)
                        if isinstance(width, DimBase) else width
                        for width in auto_widths]

            def final_column_width(index, width):
                if isinstance(width, DimBase):
                    return width.to_points(container.width)
                elif excess[index] > 0:
                    return max_column_widths[index]
                elif extra[index] <= 0:
                    return min_column_widths[index]
                else:
                    return width + (extra_neg * extra[index] / extra_pos)

            return [final_column_width(i, width)
                    for i, width in enumerate(auto_widths)]
        else:
            return [width.to_points(container.width)
                    for width in column_widths]
919486
def suggest_column_width col
      #ret = @cw[col] || 2
      ret = get_column(col).width || 2
      ctr = 0
      @list.each_with_index { |r, i|
        #next if i < @toprow # this is also a possibility, it checks visible rows
        break if ctr > 10
        ctr += 1
        next if r == :separator
        c = r[col]
        x = c.to_s.length
        ret = x if x > ret
      }
      ret
    end
52739
def _xls2col_widths(self, worksheet, tab):
        """"""

        for col in xrange(worksheet.ncols):
            try:
                xls_width = worksheet.colinfo_map[col].width
                pys_width = self.xls_width2pys_width(xls_width)
                self.code_array.col_widths[col, tab] = pys_width

            except KeyError:
                pass
682514
def _zoom_cols(self, zoom):
        """"""

        self.grid.SetDefaultColSize(self.grid.std_col_size * zoom,
                                    resizeExistingCols=True)
        self.grid.SetColLabelSize(self.grid.col_label_size * zoom)

        for col, tab in self.code_array.col_widths:
            if tab == self.grid.current_table and \
               col < self.grid.code_array.shape[1]:
                base_col_width = self.code_array.col_widths[(col, tab)]
                if base_col_width is None:
                    base_col_width = self.grid.GetDefaultColSize()
                zoomed_col_size = base_col_width * zoom
                self.grid.SetColSize(col, zoomed_col_size)
262888
def pys_width2xls_width(self, pys_width):
        """"""

        width_0 = get_default_text_extent("0")[0]
        # Scale relative to 12 point font instead of 10 point
        width_0_char = pys_width * 1.2 / width_0
        return int(width_0_char * 256.0)
1146107
def wr_xlsx_sections(self, fout_xlsx, sections, sortby=None, **kws_usr):
        """"""
        nts = self.get_nts_sections(sections, sortby)
        kws_wr = kws_usr.copy()
        if 'fld2col_widths' not in kws_wr:
            kws_wr['fld2col_widths'] = self.fld2col_widths
        else:
            fld2col_widths = self.fld2col_widths.copy()
            for fld, wid in kws_usr['fld2col_widths'].items():
                fld2col_widths[fld] = wid
            kws_wr['fld2col_widths'] = fld2col_widths
        wr_xlsx_sections_tbl(fout_xlsx, nts, **kws_wr)
946175
def _get_column_formatters(self, max_rows, as_html):
        
        formats = {s: self._formats.get(s, self.formatter) for s in self.labels}
        cols = self._columns.items()
        fmts = [formats[k].format_column(k, v[:max_rows]) for k, v in cols]
        if as_html:
            fmts = list(map(type(self)._use_html_if_available, fmts))
        return fmts
1316923
def get_columns(context, query):
        """"""
        table_info = context.sql_client.send(query)
        if 'fields' in table_info:
            return Column.from_sql_api_fields(table_info['fields'])

        return None
928720
def values(service, id, ranges):
    """"""
    params = {'majorDimension': 'ROWS', 'valueRenderOption': 'UNFORMATTED_VALUE',
              'dateTimeRenderOption': 'FORMATTED_STRING'}
    params.update(spreadsheetId=id, ranges=ranges)
    response = service.spreadsheets().values().batchGet(**params).execute()
    return response['valueRanges']
446387
def _pys2col_widths(self, line):
        """"""

        # Split with maxsplit 3
        split_line = self._split_tidy(line)
        key = col, tab = self._get_key(*split_line[:2])
        width = float(split_line[2])

        shape = self.code_array.shape

        try:
            if col < shape[1] and tab < shape[2]:
                self.code_array.col_widths[key] = width

        except ValueError:
            pass
1168758
def rowxcol(row, col):
    """"""
    row = row.reshape(4, 4)
    col = col.reshape(4, 8)
    ret = uint2exprs(0, 8)
    for i in range(4):
        for j in range(4):
            if row[i, j]:
                ret ^= xtime(col[i], j)
    return ret
43777
def _col_widths2pys(self):
        

        for col, tab in self.code_array.dict_grid.col_widths:
            if col < self.code_array.shape[1] and \
               tab < self.code_array.shape[2]:
                width = self.code_array.dict_grid.col_widths[(col, tab)]
                width_strings = map(repr, [col, tab, width])
                self.pys_file.write(u"\t".join(width_strings) + u"\n")
502553
def get_width():
    """"""
    # Get terminal size
    ws = struct.pack("HHHH", 0, 0, 0, 0)
    ws = fcntl.ioctl(sys.stdout.fileno(), termios.TIOCGWINSZ, ws)
    lines, columns, x, y = struct.unpack("HHHH", ws)
    width = min(columns * 39 // 40, columns - 2)
    return width
341356
def _compute_cols_width(self):
        

        if hasattr(self, "_width"):
            return
        maxi = []
        if self._header:
            maxi = [ self._len_cell(x) for x in self._header ]
        for row in self._rows:
            for cell,i in zip(row, range(len(row))):
                try:
                    maxi[i] = max(maxi[i], self._len_cell(cell))
                except (TypeError, IndexError):
                    maxi.append(self._len_cell(cell))
        items = len(maxi)
        length = reduce(lambda x,y: x+y, maxi)
        if self._max_width and length + items*3 + 1 > self._max_width:
            maxi = [(self._max_width - items*3 -1) / items \
                for n in range(items)]
        self._width = maxi
106297
def _compute_cols_width(self):
        

        if hasattr(self, "_width"):
            return
        maxi = []
        if self._header:
            maxi = [ self._len_cell(x) for x in self._header ]
        for row in self._rows:
            for cell,i in zip(row, list(range(len(row)))):
                try:
                    maxi[i] = max(maxi[i], self._len_cell(cell))
                except (TypeError, IndexError):
                    maxi.append(self._len_cell(cell))

        ncols = len(maxi)
        content_width = sum(maxi)
        deco_width = 3*(ncols-1) + [0,4][self._has_border()]
        if self._max_width and (content_width + deco_width) > self._max_width:
            """ content too wide to fit the expected max_width
            let's recompute maximum cell width for each cell
            """
            if self._max_width < (ncols + deco_width):
                raise ValueError('max_width too low to render data')
            available_width = self._max_width - deco_width
            newmaxi = [0] * ncols
            i = 0
            while available_width > 0:
                if newmaxi[i] < maxi[i]:
                    newmaxi[i] += 1
                    available_width -= 1
                i = (i + 1) % ncols
            maxi = newmaxi
        self._width = maxi
1285162
def columnise(rows, padding=2):
    """"""
    strs = []
    maxwidths = {}

    for row in rows:
        for i, e in enumerate(row):
            se = str(e)
            nse = len(se)
            w = maxwidths.get(i, -1)
            if nse > w:
                maxwidths[i] = nse

    for row in rows:
        s = ''
        for i, e in enumerate(row):
            se = str(e)
            if i < len(row) - 1:
                n = maxwidths[i] + padding - len(se)
                se += ' ' * n
            s += se
        strs.append(s)
    return strs