parses order attribute converting all models to {model: model} format, adding ASC/DESC order and checking attributes are valid and model associations are valid
337030
function parseOrders(field, fieldName, model) {
		var orders = field.order;
		if (!orders) return;
		if (!Array.isArray(orders)) orders = field.order = [orders];

		_.forEach(orders, function(order, index) {
			// if just a string, leave alone - is raw query
			if (_.isString(order)) return;

			// if an object (e.g. {raw: ...}), add 'ASC' sort order
			if (!Array.isArray(order)) {
				orders[index] = [order, 'ASC'];
				return;
			}

			// add 'ASC' sort order if no sort order defined
			if (order.length == 0) throw new Sequelize.VirtualFieldsError("Invalid virtual field order in '" + model.name + "'.'" + fieldName + "'");
			if (order.length == 1) {
				order[1] = 'ASC';
			} else {
				// ensure direction is ASC or DESC
				if (['ASC', 'DESC'].indexOf(order[order.length - 1].toUpperCase()) == -1) {
					order.push('ASC');
				} else {
					order[order.length - 1] = order[order.length - 1].toUpperCase();
				}
			}

			// make preceeding models into {model: model} form
			var parent = model;
			for (var i = 0; i < order.length - 2; i++) {
				parseClause(order, i, 'Order', model.name, fieldName, parent);
				parent = order[i].model;
			}

			// check attribute is valid
			var attribute = order[order.length - 2];
			if (_.isString(attribute) && !parent.attributes[attribute]) throw new Sequelize.VirtualFieldsError("Order of virtual field '" + model.name + "'.'" + fieldName + "' refers to a nonexistent field '" + parent.name + "'.'" + attribute + "'");
		});
	}
1016312
function parseClause(array, index, clauseType, modelName, fieldName, parent) {
		var item = array[index];

		if (_.isString(item) || patches.isModel(item)) {
			item = array[index] = {model: item};
		} else if (!item.model) {
			throw new Sequelize.VirtualFieldsError(clauseType + " of virtual field '" + modelName + "'.'" + fieldName + "' is invalid");
		}

		if (_.isString(item.model)) {
			var model = parent.sequelize.models[item.model];
			if (!model) throw new Sequelize.VirtualFieldsError(clauseType + " of virtual field '" + modelName + "'.'" + fieldName + "' points to unknown model '" + item.model + "'");
			item.model = model;
		} else if (!patches.isModel(item.model)) {
			throw new Sequelize.VirtualFieldsError(clauseType + " of virtual field '" + modelName + "'.'" + fieldName + "' is invalid");
		}

		if (item.as !== undefined && !_.isString(item.as)) throw new Sequelize.VirtualFieldsError(clauseType + " of virtual field '" + modelName + "'.'" + fieldName + "' has invalid as clause '" + item.as + "'");

		// check if is valid association from parent
		if (!parent.getAssociation(item.model, item.as)) throw new Sequelize.VirtualFieldsError(clauseType + " of virtual field '" + modelName + "'.'" + fieldName + "' includes invalid association from '" + parent.name + "' to '" + item.model.name + (item.as ? ' (' + item.as + ')' : '') + "'");

		return item;
	}
633938
function parseRelations (data, relations, options) {
  var relationships = {}

  _.each(relations, function (relation, name) {
    var fkName = relation.keyTo

    // If relation is belongsTo then fk is the other way around
    if (utils.relationFkOnModelFrom(relation)) {
      fkName = relation.keyFrom
    }

    var pk = data[options.primaryKeyField]
    var fk = data[fkName]

    var toType = ''
    if (relation.polymorphic && utils.relationFkOnModelFrom(relation)) {
      var discriminator = relation.polymorphic.discriminator
      var model = options.app.models[data[discriminator]]
      toType = utils.pluralForModel(model)
    } else {
      toType = utils.pluralForModel(relation.modelTo)
    }

    // Relationship `links` should always be defined unless this is a
    // relationship request
    if (!options.isRelationshipRequest) {
      relationships[name] = {
        links: {
          related: options.host +
            options.restApiRoot +
            '/' +
            options.modelPath +
            '/' +
            pk +
            '/' +
            name
        }
      }
    }

    var relationship = null

    if (!_.isUndefined(fk) && relation.modelTo !== relation.modelFrom) {
      if (_.isArray(fk)) {
        relationship = makeRelations(toType, fk, options)
      } else {
        relationship = makeRelation(toType, fk, options)
      }
    }

    // No `data` key should be present unless there is actual relationship data.
    if (relationship) {
      relationships[name].data = relationship
    } else if (relation.type === 'belongsTo') {
      relationships[name].data = null
    }
  })

  return relationships
}
828823
function(model, value, attr) {
      var indices, validators,
        validations = model.validation ? _.result(model, 'validation') || {} : {};
      // If the validations hash contains an entry for the attr
      if (_.contains(_.keys(validations), attr)) {
        return validateAttrWithOpenArray(model, attr, value, _.extend({}, model.attributes));
      } else {
        indices = extractIndices(attr);
        attr = stripIndices(attr);
        validators = getValidators(model, attr);
        return invokeValidator(validators, model, value, attr, _.extend({}, model.attributes), indices);
      }
    }
1200324
function parseValidateAttr(validateAttr, schema, validateFns) {

        // if an array, loop through and recurse
        if (_.isArray(validateAttr)) {
            _.each(validateAttr, function (validator) {
                parseValidateAttr(validator, schema, validateFns);
            });

            return;
        }

        // if validateAttr is a string, then assume it is field reference
        if (_.isString(validateAttr)) {
            _.extend(schema, getSchema(validateAttr));
        }
        else if (_.isFunction(validateAttr)) {
            validateFns.push(wrapFn(validateAttr));
        }
        else if (_.isObject(validateAttr)) {
            _.extend(schema,  validateAttr);
        }
    }
447034
function parseValidatorNames(attrs) {
		var attrValue = attrs.vsAutocompleteValidator,
			validatorNames = (attrValue!=="") ? attrValue.trim().split(',') : [];

		// normalize validator names
		for (var i = 0; i < validatorNames.length; i++) {
			validatorNames[i] = attrs.$normalize(validatorNames[i]);
		}

		return validatorNames;
	}
898353
def awesome_active_model_error(object)
      return object.inspect if !defined?(::ActiveSupport::OrderedHash)
      return awesome_object(object) if @options[:raw]

      object_dump = object.marshal_dump.first
      data = if object_dump.class.column_names != object_dump.attributes.keys
               object_dump.attributes
             else
               object_dump.class.column_names.inject(::ActiveSupport::OrderedHash.new) do |hash, name|
                 if object_dump.has_attribute?(name) || object_dump.new_record?
                   value = object_dump.respond_to?(name) ? object_dump.send(name) : object_dump.read_attribute(name)
                   hash[name.to_sym] = value
                 end
                 hash
               end
             end

      data.merge!({details: object.details, messages: object.messages})
      "#{object} " << awesome_hash(data)
    end
785192
function(view, options) {
      return {

        // Check whether or not a value, or a hash of values
        // passes validation without updating the model
        preValidate: function(attr, value) {
          var self = this,
              result = {},
              error;

          if(_.isObject(attr)){
            _.each(attr, function(value, key) {
              error = self.preValidate(key, value);
              if(error){
                result[key] = error;
              }
            });

            return _.isEmpty(result) ? undefined : result;
          }
          else {
            return validateAttr(this, attr, value, _.extend({}, this.attributes));
          }
        },

        // Check to see if an attribute, an array of attributes or the
        // entire model is valid. Passing true will force a validation
        // of the model.
        isValid: function(option) {
          var flattened, attrs, error, invalidAttrs;

          option = option || getOptionsAttrs(options, view);

          if(_.isString(option)){
            attrs = [option];
          } else if(_.isArray(option)) {
            attrs = option;
          }
          if (attrs) {
            flattened = flatten(this.attributes);
            //Loop through all associated views
            _.each(this.associatedViews, function(view) {
              _.each(attrs, function (attr) {
                error = validateAttr(this, attr, flattened[attr], _.extend({}, this.attributes));
                if (error) {
                  options.invalid(view, attr, error, options.selector);
                  invalidAttrs = invalidAttrs || {};
                  invalidAttrs[attr] = error;
                } else {
                  options.valid(view, attr, options.selector);
                }
              }, this);
            }, this);
          }

          if(option === true) {
            invalidAttrs = this.validate();
          }
          if (invalidAttrs) {
            this.trigger('invalid', this, invalidAttrs, {validationError: invalidAttrs});
          }
          return attrs ? !invalidAttrs : this.validation ? this._isValid : true;
        },

        // This is called by Backbone when it needs to perform validation.
        // You can call it manually without any parameters to validate the
        // entire model.
        validate: function(attrs, setOptions){
          var model = this,
              validateAll = !attrs,
              opt = _.extend({}, options, setOptions),
              validatedAttrs = getValidatedAttrs(model, getOptionsAttrs(options, view)),
              allAttrs = _.extend({}, validatedAttrs, model.attributes, attrs),
              flattened = flatten(allAttrs),
              changedAttrs = attrs ? flatten(attrs) : flattened,
              result = validateModel(model, allAttrs, _.pick(flattened, _.keys(validatedAttrs)));

          model._isValid = result.isValid;

          //After validation is performed, loop through all associated views
          _.each(model.associatedViews, function(view){

            // After validation is performed, loop through all validated and changed attributes
            // and call the valid and invalid callbacks so the view is updated.
            _.each(validatedAttrs, function(val, attr){
                var invalid = result.invalidAttrs.hasOwnProperty(attr),
                  changed = changedAttrs.hasOwnProperty(attr);

                if(!invalid){
                  opt.valid(view, attr, opt.selector);
                }
                if(invalid && (changed || validateAll)){
                  opt.invalid(view, attr, result.invalidAttrs[attr], opt.selector);
                }
            });
          });

          // Trigger validated events.
          // Need to defer this so the model is actually updated before
          // the event is triggered.
          _.defer(function() {
            model.trigger('validated', model._isValid, model, result.invalidAttrs);
            model.trigger('validated:' + (model._isValid ? 'valid' : 'invalid'), model, result.invalidAttrs);
          });

          // Return any error messages to Backbone, unless the forceUpdate flag is set.
          // Then we do not return anything and fools Backbone to believe the validation was
          // a success. That way Backbone will update the model regardless.
          if (!opt.forceUpdate && _.intersection(_.keys(result.invalidAttrs), _.keys(changedAttrs)).length > 0) {
            return result.invalidAttrs;
          }
        }
      };
    }
202758
function(model, options) {
      if (!(model instanceof Backbone.Model)) {
        var attrs = model;
        model = new this.model(attrs, {collection: this});
        if (model.validate && !model._performValidation(attrs, options)) model = false;
      } else if (!model.collection) {
        model.collection = this;
      }
      return model;
    }
86330
def order=(order)
      validator = EnumAttributeValidator.new('String', ["DESC", "ASC"])
      unless validator.valid?(order)
        fail ArgumentError, "invalid value for 'order', must be one of #{validator.allowable_values}."
      end
      @order = order
    end
504032
def extract_attributes(model)
      self.class.attributes.reduce({}) do |result, name|
        if model.respond_to?(name)
          result[name] = model.public_send(name)
        elsif model.respond_to?(:[]) && model.respond_to?(:key?) && model.key?(name)
          result[name] = model[name]
        end
        result
      end
    end
416341
function(option) {
          var flattened, attrs, error, invalidAttrs;

          option = option || getOptionsAttrs(options);

          if(_.isString(option)){
            attrs = [option];
          } else if(_.isArray(option)) {
            attrs = option;
          }
          if (attrs) {
            // Loop through all attributes
            _.each(attrs, function (attr) {
              var value;
              if (isNestedModel(this)) {
                value = this.get(attr);
              } else {
                value = flatten(this.attributes)[attr];
              }
              error = validateAttr(this, value, attr);
              if (error) {
                invalidAttrs = invalidAttrs || {};
                invalidAttrs[attr] = error;
              }
            }, this);
          }

          if (option === true) {
            invalidAttrs = this.validate();
          }
          if (invalidAttrs) {
            this.trigger('invalid', this, invalidAttrs, {validationError: invalidAttrs});
          }
          return attrs ? !invalidAttrs : this.validation ? this._isValid : true;
        }
237124
def normalize_order(order)
      order = Array(order)

      if order.length == 2 && !order[0].is_a?(Array) && [:asc, :desc].include?(order[1])
        order = [order]
      else
        order = order.map {|pair| pair.is_a?(Array) ? pair : [pair, :asc] }
      end

      order.each do |pair|
        pair.length == 2 or raise ArgumentError, "each order clause must be a pair (unknown clause #{pair.inspect})"
        [:asc, :desc].include?(pair[1]) or raise ArgumentError, "order must be specified with :asc or :desc (unknown key #{pair[1].inspect})"
      end

      order
    end
970011
def parse_selectors(model, fields=None, exclude=None, key_map=None, **options):
    
    fields = fields or DEFAULT_SELECTORS
    exclude = exclude or ()
    key_map = key_map or {}
    validated = []

    for alias in fields:
        # Map the output key name to the actual field/accessor name for
        # the model
        actual = key_map.get(alias, alias)

        # Validate the field exists
        cleaned = resolver.get_field(model, actual)

        if cleaned is None:
            raise AttributeError('The "{0}" attribute could not be found '
                                 'on the model "{1}"'.format(actual, model))

        # Mapped value, so use the original name listed in `fields`
        if type(cleaned) is list:
            validated.extend(cleaned)
        elif alias != actual:
            validated.append(alias)
        else:
            validated.append(cleaned)

    return tuple([x for x in validated if x not in exclude])
786273
def _validate_model(model):
    """"""
    if not hasattr(model, "as_search_document"):
        raise ImproperlyConfigured("'%s' must implement `as_search_document`." % model)
    if not hasattr(model.objects, "get_search_queryset"):
        raise ImproperlyConfigured(
            "'%s.objects must implement `get_search_queryset`." % model
        )
669529
def sort_order=(sort_order)
      validator = EnumAttributeValidator.new('String', ["DESC", "ASC"])
      unless validator.valid?(sort_order)
        fail ArgumentError, "invalid value for 'sort_order', must be one of #{validator.allowable_values}."
      end
      @sort_order = sort_order
    end
762434
def post_save(sender, instance, created, **kwargs):
    
    # Only create order model instances for
    # those modules specified in settings.
    model_label = '.'.join([sender._meta.app_label, sender._meta.object_name])
    labels = resolve_labels(model_label)

    order_field_names = is_orderable(model_label)
    if order_field_names:
        orderitem_set = getattr(
            instance,
            resolve_order_item_related_set_name(labels)
        )
        if not orderitem_set.all():
            fields = {}
            for order_field_name in order_field_names:
                fields[order_field_name] = 1
            orderitem_set.model.objects.create(item=instance, **fields)
            sanitize_order(orderitem_set.model)