Parse text fields and file fields for values and files
504403
def parse(self, fail_callback=None):
        
        # get text fields
        for field in self.field_arguments:
            self.values[field['name']] = self.__get_value(field['name'])
            if self.values[field['name']] is None and field['required']:
                if fail_callback is not None:
                    fail_callback()
                self.__invalid_request(field['error'])
        # get file fields
        for file in self.file_arguments:
            self.files[file['name']] = self.__get_file(file)
            if self.files[file['name']] is None and file['required']:
                if fail_callback is not None:
                    fail_callback()
                self.__invalid_request(file['error'])
305680
def parse_field_value(field_info, value):
    
    if field_info.id == "FT":
        return [x for x in value.split(";") if x != "."]
    elif field_info.type == "Flag":
        return True
    elif field_info.number == 1:
        return convert_field_value(field_info.type, value)
    else:
        if value == ".":
            return []
        else:
            return [convert_field_value(field_info.type, x) for x in value.split(",")]
563640
def _calldata_fields(fields, exclude_fields, format_ids):
    """"""
    if fields is None:
        # no fields specified by user
        # default to all standard fields plus all FORMAT fields in VCF header
        fields = config.STANDARD_CALLDATA_FIELDS + format_ids
    else:
        # fields specified by user
        for f in fields:
            # check if field is standard or defined in VCF header
            if (f not in config.STANDARD_CALLDATA_FIELDS and
                    f not in format_ids):
                # support extracting FORMAT even if not declared in header,
                # but warn...
                print('WARNING: no definition found for field %s' % f,
                      file=sys.stderr)
    # process exclusions
    if exclude_fields is not None:
        fields = [f for f in fields if f not in exclude_fields]
    return tuple(fields)
833712
def parse_field(self, field_data, index=0):
        """"""
        field = {
            '__index__': index,
        }

        if isinstance(field_data, str):
            field.update(self.parse_string_field(field_data))
        elif isinstance(field_data, dict):
            field.update(field_data)
        else:
            raise TypeError('Expected a str or dict get {}'.format(type(field_data)))

        if 'field' not in field:
            field['field'] = None

        if 'label' not in field and field['field']:
            try:
                field['label'] = self.object._meta.get_field(field['field']).verbose_name.capitalize()
            except Exception:
                field['label'] = field['field'].replace('_', '').capitalize()
        elif 'label' not in field:
            field['label'] = ''

        if 'format' not in field:
            field['format'] = '{0}'

        # Set default options
        for name, options in self.fields_options.items():
            if 'default' in options and name not in field:
                field[name] = options['default']

        return field
717580
def parse_files(options)
 
      file_info = []

      files = options.files
      files = ["."] if files.empty?

      file_list = normalized_file_list(options, files, true)

      file_list.each do |fn|
        $stderr.printf("\n%35s: ", File.basename(fn)) unless options.quiet
        
        content = File.open(fn, "r") {|f| f.read}

        top_level = TopLevel.new(fn)
        parser = ParserFactory.parser_for(top_level, fn, content, options, @stats)
        file_info << parser.scan
        @stats.num_files += 1
      end

      file_info
    end
762126
def _field_value_text(self, field):
        """"""
        if field in self.fields:
            return unicode(self.get(field))
        else:
            return self.get_timemachine_instance(field)._object_name_text()
545506
def compose_data(params=None, files=None):
    
    data = aiohttp.formdata.FormData(quote_fields=False)

    if params:
        for key, value in params.items():
            data.add_field(key, str(value))

    if files:
        for key, f in files.items():
            if isinstance(f, tuple):
                if len(f) == 2:
                    filename, fileobj = f
                else:
                    raise ValueError('Tuple must have exactly 2 elements: filename, fileobj')
            elif isinstance(f, types.InputFile):
                filename, fileobj = f.filename, f.file
            else:
                filename, fileobj = guess_filename(f) or key, f

            data.add_field(key, fileobj, filename=filename)

    return data
118669
def parse_field(source, loc, tokens):
    
    name = tokens[0].lower()
    value = normalize_value(tokens[2])
    if name == 'author' and ' and ' in value:
        value = [field.strip() for field in value.split(' and ')]
    return (name, value)
293730
protected function parseFields()
	{
		$this->fields = array();
		$matches      = array();

		// Get all of the available fields in the format string.
		preg_match_all('/{(.*?)}/i', $this->format, $matches);

		// Build the parsed fields list based on the found fields.
		foreach ($matches[1] as $match)
		{
			$this->fields[] = strtoupper($match);
		}
	}
431015
function _getFileContents(values) {
  const env = getDefaultSlateEnv();

  for (const key in values) {
    if (values.hasOwnProperty(key) && env.hasOwnProperty(key)) {
      env[key] = values[key];
    }
  }

  return Object.entries(env)
    .map((keyValues) => {
      return `${keyValues.join('=')}\r\n`;
    })
    .join('\r\n\r\n');
}
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;
  }
187009
function(d, fields, txt) {
    for (var k in d) {
      var t = txt;
      if (isNaN(k)) {
        t += txt ? '.' : '';
        t += k;
      }

      if ('object' === typeof d[k]) {
        fields = this.buildFieldByStep(d[k], fields, t);
      } else {
        switch (k) {
        case 'text':
        case 'type':
        case 'label':
          fields.push(t);
          break;
        }
      }
    }
    return fields;
  }
1220519
def parse_fields(attributes):
        """"""
        return tuple(field.bind_name(name)
                     for name, field in six.iteritems(attributes)
                     if isinstance(field, fields.Field))
164205
def process_text_field(image_path, options = {})
      RestClient.post("#{url}/processTextField", options.merge(:upload => { :file => File.new(image_path, 'r') }))
    end
413886
def _load(self, file_parser, section_name):
        
        # pylint: disable-msg=W0621
        log = logging.getLogger('argtoolbox')
        try:
            log.debug("looking for field (section=" + section_name
                      + ") : " + self._name)
            data = None
            try:
                if self.e_type == int:
                    data = file_parser.getint(section_name, self._name)
                elif self.e_type == float:
                    data = file_parser.getfloat(section_name, self._name)
                elif self.e_type == bool:
                    data = file_parser.getboolean(section_name, self._name)
                elif self.e_type == list:
                    data = file_parser.get(section_name, self._name)
                    data = data.strip()
                    data = data.decode(locale.getpreferredencoding())
                    data = data.split()
                    if not data:
                        msg = "The optional field '%(name)s' was present, \
type is list, but the current value is an empty \
list." % {"name": self._name}
                        log.error(msg)
                        raise ValueError(msg)
                elif self.e_type == str:
                    data = file_parser.get(section_name, self._name)
                    # happens only when the current field is present,
                    # type is string, but value is ''
                    if not data:
                        msg = "The optional field '%(name)s' was present, \
                        type is string, but the current value is an empty \
                        string." % {"name": self._name}
                        log.error(msg)
                        raise ValueError(msg)
                    data = data.decode(locale.getpreferredencoding())
                else:
                    msg = "Data type not supported : %(type)s " % {
                        "type": self.e_type}
                    log.error(msg)
                    raise TypeError(msg)

            except ValueError as ex:
                msg = "The current field '%(name)s' was present, but the \
required type is : %(e_type)s." %  {
                "name": self._name,
                "e_type": self.e_type
                }
                log.error(msg)
                log.error(str(ex))
                raise ValueError(str(ex))

            log_data = {"name": self._name, "data": data,
                        "e_type": self.e_type}
            if self.hidden:
                log_data['data'] = "xxxxxxxx"
            log.debug("field found : '%(name)s', value : '%(data)s', \
type : '%(e_type)s'", log_data)
            self.value = data

        except ConfigParser.NoOptionError:
            if self.conf_required:
                msg = "The required field '%(name)s' was missing from the \
config file." % {"name": self._name}
                log.error(msg)
                raise ValueError(msg)

            if self.default is not None:
                self.value = self.default
                log_data = {"name": self._name, "data": self.default,
                            "e_type": self.e_type}
                if self.hidden:
                    log_data['data'] = "xxxxxxxx"
                log.debug("Field not found : '%(name)s', default value : \
'%(data)s', type : '%(e_type)s'", log_data)
            else:
                log.debug("Field not found : '" + self._name + "'")
1114858
def _read(self, filename, field_labels=None):
        
        # if fields is None, all fields are read
        def read_field(f):
            """Read a single field"""
            datatype = None
            while datatype is None:
                # find a sane header line
                line = f.readline()
                if line == "":
                    return False

                label = line[:43].strip()
                if field_labels is not None:
                    if len(field_labels) == 0:
                        return False
                    elif label not in field_labels:
                        return True
                    else:
                        field_labels.discard(label)
                line = line[43:]
                words = line.split()
                if len(words) == 0:
                    return True

                if words[0] == 'I':
                    datatype = int
                    unreadable = 0
                elif words[0] == 'R':
                    datatype = float
                    unreadable = np.nan

            if len(words) == 2:
                try:
                    value = datatype(words[1])
                except ValueError:
                    return True
            elif len(words) == 3:
                if words[1] != "N=":
                    raise FileFormatError("Unexpected line in formatted checkpoint file %s\n%s" % (filename, line[:-1]))
                length = int(words[2])
                value = np.zeros(length, datatype)
                counter = 0
                try:
                    while counter < length:
                        line = f.readline()
                        if line == "":
                            raise FileFormatError("Unexpected end of formatted checkpoint file %s" % filename)
                        for word in line.split():
                            try:
                                value[counter] = datatype(word)
                            except (ValueError, OverflowError) as e:
                                print('WARNING: could not interpret word while reading %s: %s' % (word, self.filename))
                                if self.ignore_errors:
                                    value[counter] = unreadable
                                else:
                                    raise
                            counter += 1
                except ValueError:
                    return True
            else:
                raise FileFormatError("Unexpected line in formatted checkpoint file %s\n%s" % (filename, line[:-1]))

            self.fields[label] = value
            return True

        self.fields = {}
        with open(filename, 'r') as f:
            self.title = f.readline()[:-1].strip()
            words = f.readline().split()
            if len(words) == 3:
                self.command, self.lot, self.basis = words
            elif len(words) == 2:
                self.command, self.lot = words
            else:
                raise FileFormatError('The second line of the FCHK file should contain two or three words.')

            while read_field(f):
                pass
1277789
def parse_file(self, filename=None, buffer=None, fileobj=None):
        """"""
        if filename:
            self.file = GzipFile(filename, 'rb')
        elif buffer:
            if hasattr(buffer, 'name'):
                self.filename = buffer.name
            self.file = buffer
        elif fileobj:
            if hasattr(fileobj, 'name'):
                self.filename = fileobj.name
            self.file = GzipFile(fileobj=fileobj)
        if self.file:
            try:
                type = TAG_Byte(buffer=self.file)
                if type.value == self.id:
                    name = TAG_String(buffer=self.file).value
                    self._parse_buffer(self.file)
                    self.name = name
                    self.file.close()
                else:
                    raise MalformedFileError(
                        "First record is not a Compound Tag")
            except StructError as e:
                raise MalformedFileError(
                    "Partial File Parse: file possibly truncated.")
        else:
            raise ValueError(
                "NBTFile.parse_file(): Need to specify either a "
                "filename or a file object"
            )