Improve Flask-RESTFul's original field type
507606
def _wrap_field(field):
    """"""
    class WrappedField(field):
        def output(self, key, obj):
            value = _fields.get_value(key if self.attribute is None else self.attribute, obj)

            # For all fields, when its value was null (None), return null directly,
            #  instead of return its default value (eg. int type's default value was 0)
            # Because sometimes the client **needs** to know, was a field of the model empty, to decide its behavior.
            return None if value is None else self.format(value)
    return WrappedField
142554
def _from_python_type(self, obj, field, pytype):
        """"""
        json_schema = {
            'title': field.attribute or field.name,
        }

        for key, val in TYPE_MAP[pytype].items():
            json_schema[key] = val

        if field.dump_only:
            json_schema['readonly'] = True

        if field.default is not missing:
            json_schema['default'] = field.default

        # NOTE: doubled up to maintain backwards compatibility
        metadata = field.metadata.get('metadata', {})
        metadata.update(field.metadata)

        for md_key, md_val in metadata.items():
            if md_key == 'metadata':
                continue
            json_schema[md_key] = md_val

        if isinstance(field, fields.List):
            json_schema['items'] = self._get_schema_for_field(
                obj, field.container
            )
        return json_schema
930172
def _make_expanded_field_serializer(
        self, name, nested_expand, nested_fields, nested_omit
    ):
        
        field_options = self.expandable_fields[name]
        serializer_class = field_options[0]
        serializer_settings = copy.deepcopy(field_options[1])

        if name in nested_expand:
            serializer_settings["expand"] = nested_expand[name]

        if name in nested_fields:
            serializer_settings["fields"] = nested_fields[name]

        if name in nested_omit:
            serializer_settings["omit"] = nested_omit[name]

        if serializer_settings.get("source") == name:
            del serializer_settings["source"]

        if type(serializer_class) == str:
            serializer_class = self._import_serializer_class(serializer_class)

        return serializer_class(**serializer_settings)
1319729
def _update_field(self, uri, field):
		'''
		'''
		#req sanity check
		payload = None
		if  type(field) is not StreakField:
			return requests.codes.bad_request, None

		payload = field.to_dict(rw = True)
	
		#print(new_pl.attributes)
		#print(new_pl.to_dict())
		#raw_input()
		try:
			uri = '/'.join([
							uri, 
							field.attributes['key']
							])
		except KeyError:
			return requests.codes.bad_request, None
	
		code, data = self._req('post', uri , json.dumps(payload))
		
		return code, data
780653
function(req, res){

            var insertJson = {};

            //Request DB structure
            lastQry = connection.query('SHOW COLUMNS FROM ??', req.params.table , function (err, columns) {
                if (err) return sendError(res,err.code);

                var value;

                //Forced sync iterator
                var iterator = function (i) {
                    if (i >= columns.length) {
                        insertIntoDB();
                        return;
                    }

                    var dbField = columns[i];
                    var field = dbField.Field;

                    //Check required fields
                    if (dbField.Null === 'NO' && 
                        dbField.Default === '' && 
                        dbField.Extra !== 'auto_increment' && 
                        dbField.Extra.search('on update')===-1) {

                        //Check if field not set
                        if (undefOrEmpty(req.body[field])) {
                            return sendError(res,"Field " + field + " is NOT NULL but not specified in this request");
                        } else {
                            //Check if the set values are roughly okay
                            value = checkIfSentvaluesAreSufficient(req,dbField);
                            console.log(value);
                            if(value !== false) {
                                //Value seems okay, go to the next field
                                insertJson[field] = value;
                                iterator(i + 1);
                            } else {
                                return sendError(res,'Value for field ' + field + ' is not sufficient. Expecting ' + dbField.Type + ' but got ' + typeof req.body[field] );
                            }
                        }
                    }  else {
                        //Check for not required fields
                        //Skip auto_incremented fields
                        if(dbField.Extra === 'auto_increment') {
                            iterator(i + 1);
                        } else {
                            //Check if the field was provided by the client
                            var defined = false;
                            if(dbField.Default == "FILE") {
                                if(req.files.hasOwnProperty(dbField.Field)) {
                                    defined = true;
                                }
                            } else {
                                if(typeof req.body[field] !== "undefined") {
                                    defined = true;
                                }
                            }

                            //If it was provided, check if the values are okay
                            if(defined) {
                                value = checkIfSentvaluesAreSufficient(req,dbField);
                                if(value !== false) {
                                    insertJson[field] = value;
                                    iterator(i + 1);
                                } else {
                                    if(dbField.Default == "FILE") {
                                        return sendError(res, 'Value for field ' + field + ' is not sufficient. Either the file is to large or an other error occured');
                                    } else {
                                        return sendError(res, 'Value for field ' + field + ' is not sufficient. Expecting ' + dbField.Type + ' but got ' + typeof req.body[field]);
                                    }
                                }
                            } else {
                                //If not, don't mind
                                iterator(i + 1);
                            }

                        }
                    }

                };

                iterator(0); //start the async "for" loop

                /**
                 * When the loop is finished write everything in the database
                 */
                function insertIntoDB() {
                    lastQry = connection.query('INSERT INTO ?? SET ?', [req.params.table , insertJson] , function (err, rows) {
                        if (err) {
                            console.error(err);
                            res.statusCode = 500;
                            res.send({
                                result: 'error',
                                err: err.code
                            });
                        } else {
                            sendSuccessAnswer(req.params.table , res, rows.insertId);
                        }

                    });
                }
            });
        }
983008
def get_serializer_fields(self, path, method, view):
        
        if method not in ('PUT', 'PATCH', 'POST'):
            return []

        if not hasattr(view, 'get_serializer'):
            return []

        serializer = view.get_serializer()
        if not isinstance(serializer, Serializer):
            return []

        fields = []
        for field in serializer.fields.values():
            if field.read_only or isinstance(field, HiddenField):
                continue

            required = field.required and method != 'PATCH'
            description = force_text(field.help_text) if field.help_text else ''
            field_type = get_field_type(field)
            description += '; ' + field_type if description else field_type
            field = coreapi.Field(
                name=field.field_name,
                location='form',
                required=required,
                description=description,
                schema=schemas.field_to_schema(field),
            )
            fields.append(field)

        return fields
963108
function injectFields(string, values) {
	const fieldsModel = parseFields(string);
	const fieldsAmount = fieldsModel.fields.length;

	if (fieldsAmount) {
		values = values.slice();
		if (values.length > fieldsAmount) {
			// More values that output fields: collapse rest values into
			// a single token
			values = values.slice(0, fieldsAmount - 1)
				.concat(values.slice(fieldsAmount - 1).join(', '));
		}

		while (values.length) {
			const value = values.shift();
			const field = fieldsModel.fields.shift();
			const delta = value.length - field.length;

			fieldsModel.string = fieldsModel.string.slice(0, field.location)
				+ value
				+ fieldsModel.string.slice(field.location + field.length);

			// Update location of the rest fields in string
			for (let i = 0, il = fieldsModel.fields.length; i < il; i++) {
				fieldsModel.fields[i].location += delta;
			}
		}
	}

	return fieldsModel;
}
92680
def add_field(field, data_type = nil, options = {})
      data_type = DataType::String if data_type.nil?
      puts [":#{field}", "#{data_type.class.to_s}", "#{options.inspect}"].collect { |s| s.ljust(25) }.join if ENV['DEBUG']
      
      # Fields that do special things go here.
      if field == :timestamps
        add_field(:updated_at, :datetime)
        add_field(:created_at, :datetime)
        return true
      end

      # Add index if explicitly asked
      @indexes << field if options.delete(:index) || data_type.class.to_s == 'Hash' && data_type.delete(:index)
      @validations[field] = options.delete(:validates) if options[:validates]
      options.merge!(:field => field)    
      
      # Matches: description DataType::Paragraph, :index => true
      if data_type.is_a?(Class) && data_type.respond_to?(:migrant_data_type?)
        @columns[field] = data_type.new(options)
      # Matches: description :index => true, :unique => true
      else
        begin
          # Eg. "My field" -> String -> DataType::String
          @columns[field] = "DataType::#{data_type.class.to_s}".constantize.new(options.merge(:value => data_type))
        rescue NameError
          # We don't have a matching type, throw a warning and default to string
          puts "MIGRATION WARNING: No migration implementation for class #{data_type.class.to_s} on field '#{field}', defaulting to string..."
          @columns[field] = DataType::Base.new(options)
        end
      end
    end
572626
def patch_resource(self, session, json_data, api_type, obj_id):
        
        model = self._fetch_model(api_type)
        resource = self._fetch_resource(session, api_type, obj_id,
                                        Permissions.EDIT)
        self._check_json_data(json_data)
        orm_desc_keys = resource.__mapper__.all_orm_descriptors.keys()

        if not ({'type', 'id'} <= set(json_data['data'].keys())):
            raise BadRequestError('Missing type or id')

        if str(json_data['data']['id']) != str(resource.id):
            raise BadRequestError('IDs do not match')

        if json_data['data']['type'] != resource.__jsonapi_type__:
            raise BadRequestError('Type does not match')

        json_data['data'].setdefault('relationships', {})
        json_data['data'].setdefault('attributes', {})

        missing_keys = set(json_data['data'].get('relationships', {}).keys()) \
            - set(resource.__jsonapi_map_to_py__.keys())

        if missing_keys:
            raise BadRequestError(
                '{} not relationships for {}.{}'.format(
                    ', '.join(list(missing_keys)),
                    model.__jsonapi_type__, resource.id))

        attrs_to_ignore = {'__mapper__', 'id'}

        session.add(resource)

        try:
            for key, relationship in resource.__mapper__.relationships.items():
                api_key = resource.__jsonapi_map_to_api__[key]
                attrs_to_ignore |= set(relationship.local_columns) | {key}

                if api_key not in json_data['data']['relationships'].keys():
                    continue

                self.patch_relationship(
                    session, json_data['data']['relationships'][api_key],
                    model.__jsonapi_type__, resource.id, api_key)

            data_keys = set(map((
                lambda x: resource.__jsonapi_map_to_py__.get(x, None)),
                json_data['data']['attributes'].keys()))
            model_keys = set(orm_desc_keys) - attrs_to_ignore

            if not data_keys <= model_keys:
                raise BadRequestError(
                    '{} not attributes for {}.{}'.format(
                        ', '.join(list(data_keys - model_keys)),
                        model.__jsonapi_type__, resource.id))

            for key in data_keys & model_keys:
                setter = get_attr_desc(resource, key, AttributeActions.SET)
                setter(resource, json_data['data']['attributes'][resource.__jsonapi_map_to_api__[key]])  # NOQA
            session.commit()
        except IntegrityError as e:
            session.rollback()
            raise ValidationError(str(e.orig))
        except AssertionError as e:
            # pragma: no cover
            session.rollback()
            raise ValidationError(e.msg)
        except TypeError as e:
            session.rollback()
            raise ValidationError('Incompatible data type')
        return self.get_resource(
            session, {}, model.__jsonapi_type__, resource.id)
1211871
def type_in_db(self, tp, params):
        
        tw = TypeWrapper(tp, params)
        return self.version_db.is_versioned(tw)
779776
def field_from_json(self, key_and_type, json_value):
        """"""
        assert ':' in key_and_type
        key, type_code = key_and_type.split(':', 1)
        from_json = self.field_function(type_code, 'from_json')
        value = from_json(json_value)
        return key, value
784963
def fields_to_dtypes(schema):
    
    datetime_types = ['date', 'datetime']
    datetime_fields = {
        f['name']: _TABLE_SCHEMA_DTYPE_MAPPING.get(f['type'], 'object')
        for f in schema['fields']
        if f['type'] in datetime_types}

    other_fields = {
        f['name']: _TABLE_SCHEMA_DTYPE_MAPPING.get(f['type'], 'object')
        for f in schema['fields']
        if f['type'] not in datetime_types}

    return {'dates': datetime_fields, 'other': other_fields}
951283
function(opt, field_name, default_value) {
    if(typeof field_name === 'string') {
      // case of single string
      return (typeof opt[field_name] !== 'undefined') ? opt[field_name] : default_value;
    } else {
      // assume we are given a list of string instead
      var ret = default_value;
      for(var i=0;i<field_name.length;i++) {
        var f = field_name[i];
        if (typeof opt[f] !== 'undefined') {
          ret = opt[f]; // overwrite return value
        }
      }
      return ret;
    }
  }
61403
def format_field_names(obj, format_type=None):
    
    if format_type is None:
        format_type = json_api_settings.FORMAT_FIELD_NAMES

    if isinstance(obj, dict):
        formatted = OrderedDict()
        for key, value in obj.items():
            key = format_value(key, format_type)
            formatted[key] = value
        return formatted

    return obj
868699
function(requestId, fieldNames) {
		return protocol.implodeMessage(requestId,
			metadataMethods.GET_SCHEMA,
			protocol.implodeDataArray(fieldNames));
	}
450088
function literal(schema, defaults, options) {
  const name = 'literal'
  const type = `literal: ${JSON.stringify(schema)}`
  const validate = (value = resolveDefaults(defaults)) => {
    return value === schema
      ? [undefined, value]
      : [{ data: value, path: [], value, type }]
  }

  return new Kind(name, type, validate)
}
252356
def update_extra_fields(subtype, chan, num, aux_note, update):
    

    if update['subtype']:
        subtype.append(0)

    if update['chan']:
        if chan == []:
            chan.append(0)
        else:
            chan.append(chan[-1])
    if update['num']:
        if num == []:
            num.append(0)
        else:
            num.append(num[-1])

    if update['aux_note']:
        aux_note.append('')

    return subtype, chan, num, aux_note