Convert a python list of dictionaries to pretty csv output

        **Key Arguments:**
            - ``csvType`` -- human, machine or reST

        **Return:**
            - ``output`` -- the contents of a CSV file
971565
def _list_of_dictionaries_to_csv(
            self,
            csvType="human"):
        
        self.log.debug(
            'starting the ``_list_of_dictionaries_to_csv`` function')

        if not len(self.listOfDictionaries):
            return "NO MATCH"

        dataCopy = copy.deepcopy(self.listOfDictionaries)

        tableColumnNames = dataCopy[0].keys()
        columnWidths = []
        columnWidths[:] = [len(tableColumnNames[i])
                           for i in range(len(tableColumnNames))]

        output = io.BytesIO()
        # setup csv styles
        if csvType == "machine":
            delimiter = ","
        elif csvType in ["human", "markdown"]:
            delimiter = "|"
        elif csvType in ["reST"]:
            delimiter = "|"
        if csvType in ["markdown"]:
            writer = csv.writer(output, delimiter=delimiter,
                                quoting=csv.QUOTE_NONE, doublequote=False, quotechar='"', escapechar="\\", lineterminator="\n")
        else:
            writer = csv.writer(output, dialect='excel', delimiter=delimiter,
                                quotechar='"', quoting=csv.QUOTE_MINIMAL, lineterminator="\n")

        if csvType in ["markdown"]:
            dividerWriter = csv.writer(
                output, delimiter="|", quoting=csv.QUOTE_NONE, doublequote=False, quotechar='"', escapechar="\\", lineterminator="\n")
        else:
            dividerWriter = csv.writer(output, dialect='excel', delimiter="+",
                                       quotechar='"', quoting=csv.QUOTE_MINIMAL, lineterminator="\n")
        # add column names to csv
        header = []
        divider = []
        rstDivider = []
        allRows = []

        # clean up data
        for row in dataCopy:
            for c in tableColumnNames:
                if isinstance(row[c], float) or isinstance(row[c], Decimal):
                    row[c] = "%0.9g" % row[c]
                elif isinstance(row[c], datetime):
                    thisDate = str(row[c])[:10]
                    row[c] = "%(thisDate)s" % locals()

        # set the column widths
        for row in dataCopy:
            for i, c in enumerate(tableColumnNames):
                if len(unicode(row[c])) > columnWidths[i]:
                    columnWidths[i] = len(unicode(row[c]))

        # table borders for human readable
        if csvType in ["human", "markdown", "reST"]:
            header.append("")
            divider.append("")
            rstDivider.append("")

        for i, c in enumerate(tableColumnNames):
            if csvType == "machine":
                header.append(c)
            elif csvType in ["human", "markdown", "reST"]:
                header.append(
                    c.ljust(columnWidths[i] + 2).rjust(columnWidths[i] + 3))
                divider.append('-' * (columnWidths[i] + 3))
                rstDivider.append('=' * (columnWidths[i] + 3))

        # table border for human readable
        if csvType in ["human", "markdown", "reST"]:
            header.append("")
            divider.append("")
            rstDivider.append("")

        # fill in the data
        for row in dataCopy:
            thisRow = []
            # table border for human readable
            if csvType in ["human", "markdown", "reST"]:
                thisRow.append("")

            for i, c in enumerate(tableColumnNames):
                if csvType in ["human", "markdown", "reST"]:
                    if row[c] == None:
                        row[c] = ""
                    row[c] = unicode(unicode(row[c]).ljust(columnWidths[i] + 2)
                                     .rjust(columnWidths[i] + 3))
                thisRow.append(row[c])
            # table border for human readable
            if csvType in ["human", "markdown", "reST"]:
                thisRow.append("")
            allRows.append(thisRow)
            if csvType in ["reST"]:
                allRows.append(divider)

        if csvType == "machine":
            writer.writerow(header)
        if csvType in ["reST"]:
            dividerWriter.writerow(divider)
            writer.writerow(header)
            dividerWriter.writerow(rstDivider)
        if csvType in ["human"]:
            dividerWriter.writerow(divider)
            writer.writerow(header)
            dividerWriter.writerow(divider)
        elif csvType in ["markdown"]:
            writer.writerow(header)
            dividerWriter.writerow(divider)

        # write out the data
        writer.writerows(allRows)
        # table border for human readable
        if csvType in ["human"]:
            dividerWriter.writerow(divider)

        output = output.getvalue()
        output = output.strip()

        if csvType in ["markdown"]:
            output = output.replace("|--", "|:-")
        if csvType in ["reST"]:
            output = output.replace("|--", "+--").replace("--|", "--+")

        self.log.debug(
            'completed the ``_list_of_dictionaries_to_csv`` function')

        return output
440212
def _output_format(self, out, fmt_j=None, fmt_p=None):
        
        if self.output_format == 'pandas':
            if fmt_p is not None:
                return fmt_p(out)
            else:
                return self._convert_output(out)
        if fmt_j:
            return fmt_j(out)
        return out
901132
def make_csv(data):
    
    # Convert sub-dicts to news cols
    for entry in data:
        rval = entry
        if isinstance(data, dict):
            rval = data[entry]
        todel = []
        toadd = {}
        for key, val in rval.items():
            if isinstance(val, dict):
                for key2, val2 in val.items():
                    toadd[str(key) + "[" + str(key2) + "]"] = val2
                todel.append(key)
        for k in todel:
            del rval[k]
        for k, v in toadd.items():
            rval[k] = v

    # Convert everything to CSV
    columns = set()
    output = [[]]
    if isinstance(data, dict):
        output[0].append("id")
        for entry in data:
            for col in data[entry]:
                columns.add(col)
    else:
        for entry in data:
            for col in entry:
                columns.add(col)

    columns = sorted(columns)

    for col in columns:
        output[0].append(col)

    if isinstance(data, dict):
        for entry in data:
            new_output = [str(entry)]
            for col in columns:
                new_output.append(str(data[entry][col]) if col in data[entry] else "")
            output.append(new_output)
    else:
        for entry in data:
            new_output = []
            for col in columns:
                new_output.append(str(entry[col]) if col in entry else "")
            output.append(new_output)

    csv_string = io.StringIO()
    csv_writer = UnicodeWriter(csv_string)
    for row in output:
        csv_writer.writerow(row)
    csv_string.seek(0)
    web.header('Content-Type', 'text/csv; charset=utf-8')
    web.header('Content-disposition', 'attachment; filename=export.csv')
    return csv_string.read()
837495
def _format_output(content, typ):
    

    if "csv" in str(typ):
        return _format_csv(content, delimiter=",")

    if "tsv" in str(typ):
        return _format_csv(content, delimiter="\t")

    return content
1059811
def output(data, **kwargs):  # pylint: disable=unused-argument
    '''
    
    '''
    try:
        dump_opts = {'indent': 4, 'default': repr}

        if 'output_indent' in __opts__:

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

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

            elif isinstance(indent, six.integer_types):
                if indent >= 0:
                    indent = indent
                else:
                    indent = None

            dump_opts['indent'] = indent
            dump_opts['sort_keys'] = sort_keys

        return dson.dumps(data, **dump_opts)

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

    except TypeError:
        log.debug('An error occurred while outputting DSON', exc_info=True)
    # Return valid JSON for unserializable objects
    return dson.dumps({})
1293687
def csv_from_items(items, stream=None):
        
        items = iter(items)
        first = next(items)
        cls = first.__class__
        if stream is None:
            stream = sys.stdout
        fields = [f.name for f in attr.fields(cls)]
        writer = csv.DictWriter(stream, fieldnames=fields)
        writer.writeheader()
        writer.writerow(attr.asdict(first))
        writer.writerows((attr.asdict(x) for x in items))
1035661
def print_list(cls, l, output='table'):
        

        def dict_from_list(l):
            """
            returns a dict from a list for printing
            :param l: the list
            :return: 
            """
            d = dict([(idx, item) for idx, item in enumerate(l)])
            return d

        if output == 'table':
            x = PrettyTable(["Index", "Host"])
            for (idx, item) in enumerate(l):
                x.add_row([idx, item])
            x.align = "l"
            x.align["Index"] = "r"
            return x
        elif output == 'csv':
            return ",".join(l)
        elif output == 'dict':
            d = dict_from_list(l)
            return d
        elif output == 'json':
            d = dict_from_list(l)
            result = json.dumps(d, indent=4)
            return result
        elif output == 'yaml':
            d = dict_from_list(l)
            result = yaml.dump(d, default_flow_style=False)
            return result
        elif output == 'txt':
            return "\n".join(l)
524022
def dump(self, fileobj):
        ''''''
        if self.file_format == 'csv':
            csv.writer(fileobj).writerows(self.raw_dict().items())
        elif self.file_format == 'json':
            json.dump(self.raw_dict(), fileobj, separators=(',', ':'))
        elif self.file_format == 'pickle':
            pickle.dump(dict(self.raw_dict()), fileobj, 2)
        else:
            raise NotImplementedError('Unknown format: ' +
                                      repr(self.file_format))
277236
def list_to_csv(value):
    
    if isinstance(value, (list, tuple, set)):
        value = ",".join(value)
    return value
846281
def chain_output_files(self):
        
        ret_list = []
        for key, val in self.file_dict.items():
            # For pure input files we only want output files that were not
            # marked as internal or temp
            if val & FileFlags.out_ch_mask == FileFlags.output_mask:
                ret_list.append(key)
        return ret_list
505230
def save_csv(self):
        
        # Sort results so we can start to see patterns right in the raw CSV.
        self.results.sort_values(by=self.column_ids, inplace=True)
        # Gotcha: integers seems to be promoted to float64 because of
        # reindexation. See: https://pandas.pydata.org/pandas-docs/stable
        # /gotchas.html#na-type-promotions
        self.results.reindex(columns=self.column_ids).to_csv(
            self.csv_filepath, index=False)
504302
def dump(self):
        
        results = []
        for data in self.data():
            results.append(data)
        return results
1130699
def serialize_dtype(o):
    
    if len(o) == 0:
        return dict(
            _type='np.dtype',
            descr=str(o))
    return dict(
        _type='np.dtype',
        descr=o.descr)
1127517
def dict_print(self, output_file="dict.csv"):

        

        with codecs.open(output_file, "w", encoding='utf-8') as f:
                for (v, k) in self.token_key.items():
                    f.write("%s,%d\n" % (v, k))
326548
def encode_csv(data_dict, column_names):
  
  import csv
  import six
  values = [str(data_dict[x]) for x in column_names]
  str_buff = six.StringIO()
  writer = csv.writer(str_buff, lineterminator='')
  writer.writerow(values)
  return str_buff.getvalue()
1157765
function csv(arg) {
  return ( _.isArray(arg) ? arg :
           _.isObject(arg) ? _.values(arg) :
           [arg]).join(', ');
}
1190186
def as_dict(self):
        
        out = dict({})
        for key in self.keys():
            if self._has_delimiter(key):
                pk, ck = key.split(self._delimiter, 1)
                if self._has_delimiter(ck):
                    ck = ck.split(self._delimiter, 1)[0]
                if isinstance(self._values[pk], FlatterDict) and pk not in out:
                    out[pk] = dict()
                if isinstance(self._values[pk][ck], FlatterDict):
                    if self._values[pk][ck].original_type == tuple:
                        out[pk][ck] = tuple(self._child_as_list(pk, ck))
                    elif self._values[pk][ck].original_type == list:
                        out[pk][ck] = self._child_as_list(pk, ck)
                    elif self._values[pk][ck].original_type == set:
                        out[pk][ck] = set(self._child_as_list(pk, ck))
                    elif self._values[pk][ck].original_type == dict:
                        out[pk][ck] = self._values[pk][ck].as_dict()
                else:
                    out[pk][ck] = self._values[pk][ck]
            else:
                out[key] = self._values[key]
        return out