Parse the CSV header returned by TDS.
345603
def parse_csv_header(line):
    """"""
    units = {}
    names = []
    for var in line.split(','):
        start = var.find('[')
        if start < 0:
            names.append(str(var))
            continue
        else:
            names.append(str(var[:start]))
        end = var.find(']', start)
        unitstr = var[start + 1:end]
        eq = unitstr.find('=')
        if eq >= 0:
            # go past = and ", skip final "
            units[names[-1]] = unitstr[eq + 2:-1]
    return names, units
595676
def parse_headers(self, req: Request, name: str, field: Field) -> typing.Any:
        """"""
        return core.get_value(req.headers, name, field)
580650
def to_csvline(self, with_header=False):
        """"""
        string = ""

        if with_header:
            string += "# " + " ".join(at for at in AbinitTimerSection.FIELDS) + "\n"

        string += ", ".join(str(v) for v in self.to_tuple()) + "\n"
        return string
993179
def render_csv(t)
      io = StringIO.new
      io.puts (
        t.header.collect do |v|
          v ? "\"#{v.to_s.gsub(/"/, '""')}\"" : ""
        end.join(',')
      ) unless @options[:plain]
      t.each do |row|
        next if row === t.header
        io.puts (
          row.collect do |v|
            v ? "\"#{v.to_s.gsub(/"/, '""')}\"" : ""
          end.join(',')
        )
      end
      io.rewind
      io.gets(nil).encode(crlf_newline: true)
    end
959910
def _parse_horizontal_scroll_table(self, table_html):
        
        row_labels = [parse_text(x.text) for x  in table_html.select(".DTFC_LeftBodyWrapper tbody tr")]
        row_label_ids = [None] * len(row_labels)
        cols = [parse_text(x.text) for x in table_html.select(".dataTables_scrollHead th")]
        value_rows = table_html.select(".dataTables_scrollBody tbody tr")

        values = []
        for row_i, value_row in enumerate(value_rows):
            row_values = [parse_value(x.text) for x in value_row.select("td")]
            values.append(row_values)

        sheet = Sheet(zip(row_label_ids, row_labels), cols, values)

        return sheet.long_format
79364
function parseHeaders() {
  var str = arguments.length <= 0 || arguments[0] === undefined ? '' : arguments[0];

  var lines = str.split(/\r?\n/);
  var fields = {};
  var index = undefined;
  var line = undefined;
  var field = undefined;
  var val = undefined;

  lines.pop(); // trailing CRLF

  for (var i = 0, len = lines.length; i < len; i += 1) {
    line = lines[i];
    index = line.indexOf(':');
    field = line.slice(0, index).toLowerCase();
    val = trim(line.slice(index + 1));
    fields[field] = val;
  }

  return fields;
}
919142
def read_header(self):
        """"""
        format = '!HHHHHH'
        length = struct.calcsize(format)
        info = struct.unpack(format,
                self.data[self.offset:self.offset + length])
        self.offset += length

        self.id = info[0]
        self.flags = info[1]
        self.num_questions = info[2]
        self.num_answers = info[3]
        self.num_authorities = info[4]
        self.num_additionals = info[5]
537331
def parse_headers(self, req, name, field):
        """"""
        # Use req.get_headers rather than req.headers for performance
        return req.get_header(name, required=False) or core.missing
84969
def get_header_values(self):
        
        lines = self.getOriginalFile().data.splitlines()
        reader = csv.reader(lines)
        header_fields = header_data = []
        for row in reader:
            if not any(row):
                continue
            if row[0].strip().lower() == 'header':
                header_fields = [x.strip() for x in row][1:]
                continue
            if row[0].strip().lower() == 'header data':
                header_data = [x.strip() for x in row][1:]
                break
        if not (header_data or header_fields):
            return None
        if not (header_data and header_fields):
            self.error("File is missing header row or header data")
            return None
        # inject us out of here
        values = dict(zip(header_fields, header_data))
        # blank cell from sheet will probably make it in here:
        if '' in values:
            del (values[''])
        return values
208013
def _read_header(self):
        
        if not self.filename or self.header_types:
            return
        rows = csv.reader(open(self.filename))
        #header = rows.next()
        header = next(rows)
        self.header_types = {} # {attr_name:type}
        self._class_attr_name = None
        self.header_order = [] # [attr_name,...]
        for el in header:
            matches = ATTR_HEADER_PATTERN.findall(el)
            assert matches, "Invalid header element: %s" % (el,)
            el_name, el_type, el_mode = matches[0]
            el_name = el_name.strip()
            self.header_order.append(el_name)
            self.header_types[el_name] = el_type
            if el_mode == ATTR_MODE_CLASS:
                assert self._class_attr_name is None, \
                    "Multiple class attributes are not supported."
                self._class_attr_name = el_name
            else:
                assert self.header_types[el_name] != ATTR_TYPE_CONTINUOUS, \
                    "Non-class continuous attributes are not supported."
        assert self._class_attr_name, "A class attribute must be specified."
394352
def parse_header(filename):
    '''
    '''
    with open(filename, 'rb') as fh:
        content = '\n'.join(fh.read().splitlines())

    content = sub('\t', ' ', content)
    content = strip_comments(content)

    # first get the functions
    content = split(func_pat_short, content)

    for i, s in enumerate(content):
        if i % 2 and content[i].strip():  # matched a prototype
            try:
                content[i] = parse_prototype(content[i])
            except Exception as e:
                traceback.print_exc()

    # now process structs
    res = []
    for i, item in enumerate(content):
        if not isinstance(item, str):  # if it's already a func etc. skip it
            res.append(item)
            continue

        items = split(struct_pat, item)
        j = 0
        while j < len(items):
            if not j % 5:
                res.append(items[j])
                j += 1
            else:
                if items[j].strip() == 'enum':
                    res.append(parse_enum(*items[j + 1: j + 4]))
                else:
                    res.append(parse_struct(*items[j + 1: j + 4]))
                j += 4

    # now do remaining simple typedefs
    content = res
    res = []
    for i, item in enumerate(content):
        if not isinstance(item, str):  # if it's already processed skip it
            res.append(item)
            continue

        items = split(typedef_pat, item)
        for j, item in enumerate(items):
            res.append(TypeDef(item.strip()) if j % 2 else item)

    content = [c for c in res if not isinstance(c, str) or c.strip()]
    return content
855241
def _ts_parse(ts):
    """"""
    dt = datetime.strptime(ts[:19],"%Y-%m-%dT%H:%M:%S")
    if ts[19] == '+':
        dt -= timedelta(hours=int(ts[20:22]),minutes=int(ts[23:]))
    elif ts[19] == '-':
        dt += timedelta(hours=int(ts[20:22]),minutes=int(ts[23:]))
    return dt.replace(tzinfo=pytz.UTC)
83693
def read_csv(text, sep="\t"):
    """"""
    import pandas as pd    # no top level load to make a faster import of db
    return pd.read_csv(StringIO(text), sep="\t")
665538
private function parseHeaders($headers)
    {
        $result = [];

        foreach (preg_split("/\\r\\n|\\r|\\n/", $headers) as $row) {
            $header = explode(':', $row, 2);

            if (count($header) == 2) {
                $result[$header[0]] = trim($header[1]);
            }
            else {
                $result[] = $header[0];
            }
        }

        return $result;
    }
202665
function parseResponseHeaders (headers) {
  var parsed = {};

  if (headers) {
    headers.split('\n').forEach(function (line) {
      var separatorIndex = line.indexOf(':');
      var key = line.substr(0, separatorIndex).trim().toLowerCase();
      var value = line.substr(separatorIndex + 1).trim().toLowerCase();

      if (key) {
        parsed[key] = value;
      }
    });
  }

  return parsed;
}
913818
def parse_headerline(self, line):
        #Process incoming header line
        
        
        # Save each header field (that we know) and its own value in the dict        
        if line.startswith('Results quantitative'):
            line = to_unicode(line)
            if len(self._header) == 0:
                self.err("Unexpected header format", numline=self._numline)
                return -1

            line = line.replace(',', "")
            splitted = line.split(' - ')
            self._header['Quantitative'] = splitted[1]
            return 1

        if line.startswith('Selected archive'):
            if len(self._header) == 0:
                self.err("No header found", numline=self._numline)
                return -1

            splitted = self.splitLine(line)
            if len(splitted) > 1:
                self._header['Archive'] = splitted[1].replace('"', '').strip()
            else:
                self.warn('Unexpected header format', numline=self._numline)
            return 0

        if line.startswith('Number of'):
            if len(self._header) == 0:
                self.err("No header found", numline=self._numline)
                return -1

            splitted = self.splitLine(line)
            if len(splitted) > 1:
                self._header['NumResults'] = splitted[1].replace('"', '').strip()
            else:
                self.warn('Unexpected header format', numline=self._numline)
            return 0

        if line.startswith('Seq.'):
            if len(self._header) == 0:
                self.err("No header found", numline=self._numline)
                return -1
            #Grab column names
            self._columns = line.split(',')
            self._end_header = True
            return 1

        else:
            self._header['Date'] = line
            return 1
840755
def readcsv(fn):
    
    import csv
    #Check first line for header
    with open(fn, 'r') as f:
        reader = csv.DictReader(f)
        hdr = reader.fieldnames

    #Assume there is a header on first line, check 
    skiprows = 1
    if np.all(f.isdigit() for f in hdr):
        hdr = None
        skiprows = 0

    #Check header for lat/lon/z or x/y/z tags

    #Should probably do genfromtxt here if header exists and dtype of cols is variable
    pts = np.loadtxt(fn, delimiter=',', skiprows=skiprows, dtype=None)
    return pts