Return a row for fields, for CSV files, pretty printing, etc, give a set of fields to return
187671
def row(self, fields):
        """"""

        d = self.dict

        row = [None] * len(fields)

        for i, f in enumerate(fields):
            if f in d:
                row[i] = d[f]

        return row
972156
def generate_table(self, rows):
        
        table = PrettyTable(**self.kwargs)
        for row in self.rows:
            if len(row[0]) < self.max_row_width:
                appends = self.max_row_width - len(row[0])
                for i in range(1, appends):
                    row[0].append("-")

            if row[1] is True:
                self.make_fields_unique(row[0])
                table.field_names = row[0]
            else:
                table.add_row(row[0])
        return table
373989
function(fields, data) {
    if (!_.isString(fields)) {
      return data;
    }

    // If a field is specified as `foo.bar` or `foo.bar.baz`,
    // Convert it to just `foo`
    var map = {};
    _.forEach(fields.split(','), function(field) {
      map[field.split('.')[0]] = 1;
    });

    var keys = _.keys(map);
    if (_.isArray(data)) {
      data = _.map(data, function(object) {
        return _.pick(object, keys);
      });
    } else if (_.isObject(data)) {
      data = _.pick(data, keys);
    }

    return data;
  }
1260521
def _traverse_results(value, fields, row, path):
    
    for f, v in value.iteritems():  # for each item in obj
        field_name = '{path}.{name}'.format(path=path, name=f) if path else f

        if not isinstance(v, (dict, list, tuple)):  # if not data structure
            if field_name in fields:
                row[fields.index(field_name)] = ensure_utf(v)

        elif isinstance(v, dict) and f != 'attributes':  # it is a dict
            _traverse_results(v, fields, row, field_name)
722456
def nested_row(self, obj, nested):
        ''''''
        row = self.to_row(obj)
        for name, getter in self.get_nested_fields():
            content = ''
            if getter is not None:
                try:
                    content = safestr(getter(nested))
                except Exception, e:  # Catch all errors intentionally.
                    log.error('Error exporting CSV for {name}: {error}'.format(
                        name=self.__class__.__name__, error=e))
            row.append(content)
        return row
1316021
def _dump_csv(self, rows):
        
        self.logger.debug('Writing %r', rows)
        csv = self._maybe_import('csv')
        buff = io.StringIO() if _PYTHON3 else io.BytesIO()
        writer = csv.DictWriter(
            buff,
            sorted(set([k for r in rows for k in r.keys()])),
            dialect='excel')
        writer.writeheader()
        writer.writerows(rows)
        value = buff.getvalue()
        buff.close()
        return value
733385
def std_table(rows):
    """"""

    result = ""
    if len(rows) > 1:
        headers = rows[0]._fields
        lens = []
        for i in range(len(rows[0])):
            lens.append(len(max([x[i] for x in rows] + [headers[i]],
                                key=lambda x: len(str(x)))))
        formats = []
        hformats = []
        for i in range(len(rows[0])):
            if isinstance(rows[0][i], int):
                formats.append("%%%dd" % lens[i])
            else:
                formats.append("%%-%ds" % lens[i])
            hformats.append("%%-%ds" % lens[i])
        pattern = " | ".join(formats)
        hpattern = " | ".join(hformats)
        separator = "-+-".join(['-' * n for n in lens])
        result += hpattern % tuple(headers) + " \n"
        result += separator + "\n"

        for line in rows:
            result += pattern % tuple(t for t in line) + "\n"
    elif len(rows) == 1:
        row = rows[0]
        hwidth = len(max(row._fields, key=lambda x: len(x)))
        for i in range(len(row)):
            result += "%*s = %s" % (hwidth, row._fields[i], row[i]) + "\n"

    return result
1223096
def csv_row_cleaner(rows):
    
    result = []

    for row in rows:

        # check not empty row
        check_empty = len(exclude_empty_values(row)) > 1

        # check more or eq than 1 unique element in row
        check_set = len(set(exclude_empty_values(row))) > 1
        # check row not into result cleaned rows.
        check_last_allready = (result and result[-1] == row)

        if check_empty and check_set and not check_last_allready:
            result.append(row)
    return result
81478
def rows(self, table, cols):
        '''
        
        '''
        if self.orng_tables:
            data = []
            for ex in self.orng_tables[table]:
                data.append([ex[str(col)] for col in cols])
            return data
        else:
            return self.fetch(table, cols)
1052561
def csv_format(csv_data, c_headers=None, r_headers=None, rows=None, **kwargs):
    
    result = None
    c_headers = [] if c_headers is None else c_headers
    r_headers = [] if r_headers is None else r_headers
    rows = [] if rows is None else rows

    result_format = kwargs.get('result_format', ARRAY_RAW_FORMAT)

    # DICT FORMAT
    if result_format == DICT_FORMAT:
        result = csv_dict_format(csv_data, c_headers, r_headers)

    # ARRAY_RAW_FORMAT
    elif result_format == ARRAY_RAW_FORMAT:
        result = rows

    # ARRAY_CLEAN_FORMAT
    elif result_format == ARRAY_CLEAN_FORMAT:
        result = csv_array_clean_format(csv_data, c_headers, r_headers)

    else:
        result = None

    # DEFAULT
    if result and result_format < DICT_FORMAT:
        result = [result]

    return result
690218
def get_fields_by_class(cls, field_class):
        

        ret = []

        for key, val in getattr(cls, '_fields').items():
            if isinstance(val, field_class):
                ret.append(key)
        return ret
1021728
def prepare_rows(self,
                     rows,
                     indent,
                     has_header):

        ''''''

        out = []

        def row_wrapper(row):
            new_rows = [
                self.wrapfunc(item).split('\n')
                for item in row
            ]
            rows = []
            for item in map(lambda *args: args, *new_rows):
                if isinstance(item, (tuple, list)):
                    rows.append([substr or '' for substr in item])
                else:
                    rows.append([item])
            return rows

        logical_rows = [
            row_wrapper(row)
            for row in rows
        ]

        columns = map(lambda *args: args, *reduce(operator.add, logical_rows))

        max_widths = [
            max([len(six.text_type(item)) for item in column])
            for column in columns
        ]
        row_separator = self.row_delimiter * (len(self.prefix) + len(self.suffix) + sum(max_widths) +
                                              len(self.delim) * (len(max_widths) - 1))

        justify = self._JUSTIFY_MAP[self.justify.lower()]

        if self.separate_rows:
            out.append(
                self.ustring(
                    indent,
                    self.LIGHT_GRAY,  # pylint: disable=no-member
                    row_separator
                )
            )
        for physical_rows in logical_rows:
            for row in physical_rows:
                line = self.prefix \
                        + self.delim.join([
                                justify(six.text_type(item), width)
                                for (item, width) in zip(row, max_widths)
                        ]) + self.suffix
                out.append(
                    self.ustring(
                        indent,
                        self.WHITE,  # pylint: disable=no-member
                        line
                    )
                )
            if self.separate_rows or has_header:
                out.append(
                    self.ustring(
                        indent,
                        self.LIGHT_GRAY,  # pylint: disable=no-member
                        row_separator
                    )
                )
                has_header = False
        return out
449060
def datagetter(cls):
        
        with open('myfile', 'rt') as f:
            rows = [r for r in csv.reader(f)]
        dothing = lambda _: [i for i, v in enumerate(_)]
        rows = [dothing(_) for _ in rows]
        raise NotImplementedError('You need to implement this yourlself!')
        return rows
1299144
def select(self, cols, mode='list'):
        
        if isinstance(cols, stringtypes):
            cols = _split_cols(cols)
        if not cols:
            cols = [f.name for f in self.fields]
        return select_rows(cols, self, mode=mode)
213717
def _return_rows(self, table, cols, values, return_type):
        """"""
        if return_type is dict:
            # Pack each row into a dictionary
            cols = self.get_columns(table) if cols is '*' else cols
            if len(values) > 0 and isinstance(values[0], (set, list, tuple)):
                return [dict(zip(cols, row)) for row in values]
            else:
                return dict(zip(cols, values))
        elif return_type is tuple:
            return [tuple(row) for row in values]
        else:
            return values
887651
function csv(input, delimiter) {
  if (!input) return []
  delimiter = delimiter || ','

  var lines  = toArray(input, /\r?\n/)
  var first  = lines.shift()
  var header = toArray(first, delimiter)

  var data = lines.map(function(line) {
    var row = toArray(line, delimiter)
    return toObject(row, header)
  })

  return data
}
33135
def printable_fields
      raw_fields.map do |field|
        field.is_a?(Array) ? field.last : field
      end
    end