Get the text representation of a report element as csv.
483039
def make_csv(self):
        
        import csv
        try:
            from StringIO import StringIO  # Python 2.7
        except ImportError:
            from io import StringIO

        out = StringIO()
        writer = csv.writer(out, delimiter='|', lineterminator='\n', quoting=csv.QUOTE_MINIMAL)

        if self.function == 'total':
            writer.writerows(self.results)                

        elif self.function == 'top':
            rows = [['Value', self.headers.strip('"')]]
            if self.results[0] is not None:
                for res in self.results:
                    if res is not None:
                        rows.append(tuple([res[0], ','.join(res[1])]))
                writer.writerows(rows)
                
        elif self.function == 'table':
            rows = [[header.strip('"') for header in re.split('\s*,\s*', self.headers)]]

            for res in sorted(self.results, key=lambda x: x[0]):
                row = list(res[:-1])
                lastcol = get_fmt_results(res[-1], limit=10)
                if lastcol[-1][0] == '[' and lastcol[-1][-1] == ']':
                    row.append(u'{0} {1}'.format(u', '.join(lastcol[:-1]), lastcol[-1]))
                else:
                    row.append(u', '.join(lastcol))
                rows.append(row)
            writer.writerows(rows)

        self.csv = out.getvalue()
1103320
public static final Representation Csv(String text){
        return new ImmutableRep(CONTENT_TYPE_CSV, new ByteArrayInputStream(getBytes(text, MOST_WIDELY_SUPPORTED_ENCODING)));
    }
1273271
public String csv(String text) {
        if (text == null || text.isEmpty()) {
            return "\"\"";
        }
        final String str = text.trim().replace("\n", " ");
        if (str.length() == 0) {
            return "\"\"";
        }
        return StringEscapeUtils.escapeCsv(str);
    }
995132
def _get_text(self):
        
        boxes = self.boxes
        txt = []
        for line in boxes:
            txt_line = u""
            for box in line.word_boxes:
                txt_line += u" " + box.content
            txt.append(txt_line)
        return txt
176927
def as_text(self, is_pretty=False):
        """"""
        values = {
            'type': self._type,
            self.SERVICE_ENDPOINT: self._service_endpoint,
        }
        if self._consume_endpoint is not None:
            values[self.CONSUME_ENDPOINT] = self._consume_endpoint
        if self._values:
            # add extra service values to the dictionary
            for name, value in self._values.items():
                values[name] = value

        if is_pretty:
            return json.dumps(values, indent=4, separators=(',', ': '))

        return json.dumps(values)
856348
def write(self):
        
        csv_file = os.path.join(self.outdir, 'search_results.csv')
        txt_file = os.path.join(self.outdir, 'unresolved.txt')
        headers = self.key_terms
        unresolved = []
        with open(csv_file, 'w') as file:
            writer = csv.writer(file)
            writer.writerow(headers)
            for key in list(self._store.keys()):
                results = self._store[key]
                if len(results) == 0:
                    unresolved.append(key)
                else:
                    row = [key]
                    for key_term in headers[1:]:
                        element = results[0][key_term]
                        # GNR returns UTF-8, csv requires ascii
                        #
                        # *** Note ***
                        # According to all docs for csv versions >= 2.6, csv
                        # can handle either UTF-8 or ascii, just not Unicode.
                        # In py3, the following two lines result in csv printing
                        # the element with a bitstring. If GNR is actually
                        # returning UTF-8, it seems easiest to just drop these

                        # if 'encode' in dir(element):
                        #     element = element.encode('ascii')
                        row.append(element)
                    writer.writerow(row)
        if len(unresolved) > 0:
            with open(txt_file, 'w') as file:
                for name in unresolved:
                    file.write("{0}\n".format(name))
96883
def text_to_data(self, text, elt, ps):
        '''
        '''
        v = []
        items = text.split()
        for item in items:
            v.append(self.itemTypeCode.text_to_data(item, elt, ps))

        if self.pyclass is not None:
            return self.pyclass(v)
        return v
46642
def content(self):
        '''  '''
        if isinstance(self.__report_file, io.StringIO):
            return self.__report_file.getvalue()
        else:
            return ''
445284
def _parse_description(self, description_text):
        """"""
        text = description_text
        text = text.strip()
        lines = text.split('\n')

        data = {}
        for line in lines:
            if ":" in line:
                idx = line.index(":")
                key = line[:idx]
                value = line[idx+1:].lstrip().rstrip()
                data[key] = value
            else:
                if isinstance(value, list) is False:
                    value = [value]
                value.append(line.lstrip().rstrip())
                data[key] = value
        return data
60284
def sct_report_string(report):
    
    ret = []
    namespaces = {"svrl": "http://purl.oclc.org/dsdl/svrl"}
    for index, failed_assert_el in enumerate(
        report.findall("svrl:failed-assert", namespaces=namespaces)
    ):
        ret.append(
            "{}. {}".format(
                index + 1,
                failed_assert_el.find("svrl:text", namespaces=namespaces).text,
            )
        )
        ret.append("   test: {}".format(failed_assert_el.attrib["test"]))
        ret.append("   location: {}".format(failed_assert_el.attrib["location"]))
        ret.append("\n")
    return "\n".join(ret)
315323
def _readcsv(self, path_to_csv):
        """"""
        return np.genfromtxt(path_to_csv,
                             dtype=None,
                             delimiter=',',
                             names=True)
183458
def get_header_as_text(file_content, reference_id):
    
    res = _CONTENT_PATTERN.findall(file_content)
    if len(res) == 2:
        content = res[0]
    elif len(res) == 1:
        return ''
    else:
        raise ValueError('Unexpected <code><pre> sections: "%r"' % res)
    return _clean_html(content)
185323
def convert_context_to_csv(self, context):
        """"""
        content = []
        date_headers = context['date_headers']

        headers = ['Name']
        headers.extend([date.strftime('%m/%d/%Y') for date in date_headers])
        headers.append('Total')
        content.append(headers)

        summaries = context['summaries']

        summary = summaries.get(self.export, [])

        for rows, totals in summary:
            for name, user_id, hours in rows:
                data = [name]
                data.extend(hours)
                content.append(data)
            total = ['Totals']
            total.extend(totals)
            content.append(total)
        return content
164421
def get_help_text(self):
        

        txt = str('\n')
        for name, info in self.commands.items():
            command_txt = "\t{0: <22} {1}\n".format(name, info['description'])
            if info['attributes']:
                command_txt = ''.join([command_txt, "\t Attributes:\n"])
                for attrname, attrdesc in info['attributes'].items():
                    attr_txt = "\t  {0: <22} {1}\n".format(attrname, attrdesc)
                    command_txt = ''.join([command_txt, attr_txt])
            if info['elements']:
                command_txt = ''.join([command_txt, "\t Elements:\n",
                                       self.elements_as_text(info['elements'])])
            txt = ''.join([txt, command_txt])
        return txt
97629
def _get_report(self, with_line_nums=True):
		
		templ = '{} ← {}' if with_line_nums else '{}'

		return '\n'.join([
			templ.format(error.string, ','.join(map(str, sorted(set(lines)))))
			for error, lines in self.errors.items()])
149454
public static String csv(String... msgs) {
		StringBuffer buf = new StringBuffer();
		for (String msg : msgs) {
			buf.append(msg);
			buf.append("; ");
		}
		return buf.toString();
	}
1173693
def tostring(self):
        """"""
        parser = etree.XMLParser(remove_blank_text=True)
        outputtree = etree.XML(etree.tostring(self.__doc), parser)
        return etree.tostring(outputtree, pretty_print=True)