Work an an appropriate ordering for the models.
        This isn't essential, but makes the script look nicer because
        more instances can be defined on their first try.
178825
def _queue_models(self, models, context):
        
        model_queue = []
        number_remaining_models = len(models)
        # Max number of cycles allowed before we call it an infinite loop.
        MAX_CYCLES = number_remaining_models
        allowed_cycles = MAX_CYCLES

        while number_remaining_models > 0:
            previous_number_remaining_models = number_remaining_models

            model = models.pop(0)

            # If the model is ready to be processed, add it to the list
            if check_dependencies(model, model_queue, context["__avaliable_models"]):
                model_class = ModelCode(model=model, context=context, stdout=self.stdout, stderr=self.stderr, options=self.options)
                model_queue.append(model_class)

            # Otherwise put the model back at the end of the list
            else:
                models.append(model)

            # Check for infinite loops.
            # This means there is a cyclic foreign key structure
            # That cannot be resolved by re-ordering
            number_remaining_models = len(models)
            if number_remaining_models == previous_number_remaining_models:
                allowed_cycles -= 1
                if allowed_cycles <= 0:
                    # Add the remaining models, but do not remove them from the model list
                    missing_models = [ModelCode(model=m, context=context, stdout=self.stdout, stderr=self.stderr, options=self.options) for m in models]
                    model_queue += missing_models
                    # Replace the models with the model class objects
                    # (sure, this is a little bit of hackery)
                    models[:] = missing_models
                    break
            else:
                allowed_cycles = MAX_CYCLES

        return model_queue
130729
def _makeScriptOrder(gpos):
    
    scripts = []
    for scriptRecord in gpos.ScriptList.ScriptRecord:
        scripts.append(scriptRecord.ScriptTag)
    if "DFLT" in scripts:
        scripts.remove("DFLT")
        scripts.insert(0, "DFLT")
    return sorted(scripts)
1106651
protected function ensureModel()
    {
        Yii::trace('Model ensuring', __METHOD__);

        if ($this->multiple) {
            if (empty($this->model) || !is_array($this->model)) {
                $this->model = [$this->model];
            }
            foreach ($this->model as $model) {
                $this->ensureModelInternal($model);
            }

            return;
        }

        $this->ensureModelInternal($this->model);
    }
495598
def create_order_objects(model, order_fields):
    
    for rel in model._meta.get_all_related_objects():
        rel_model = rel.model
        if rel_model.__module__ == 'order.models':

            objs = model.objects.all()
            values = {}
            for order_field in order_fields:
                order_objs = rel_model.objects.all().order_by('-%s' \
                        % order_field)
                try:
                    values[order_field] = getattr(order_objs[0], \
                            order_field) + 1
                except IndexError:
                    values[order_field] = 1
            for obj in objs:
                try:
                    rel_model.objects.get(item=obj)
                except rel_model.DoesNotExist:
                    rel_model.objects.create(item=obj, **values)
                    for key in values:
                        values[key] += 1
346341
def openOrder(self, orderId, arg0, arg1, arg2):
        """"""
        return _swigibpy.EWrapper_openOrder(self, orderId, arg0, arg1, arg2)
1067717
public function initHasSortOrder()
    {
        $this->fillable = array_merge($this->fillable, $this->hasSortOrderFillableFields);
        $this->casts = array_merge($this->casts, $this->hasSortOrderCastFields);
    }
759957
def new
      @order = Effective::Order.new

      if params[:user_id]
        @order.user = User.where(id: params[:user_id]).first
      end

      if params[:duplicate_id]
        @duplicate = Effective::Order.deep.find(params[:duplicate_id])
        EffectiveOrders.authorize!(self, :show, @duplicate)

        @order.add(@duplicate)
      end

      @page_title = 'New Order'

      raise 'please install cocoon gem to use this page' unless defined?(Cocoon)

      authorize_effective_order!
    end
992608
function (model) {
			var c = this.c,
				s = this;
			this.m[model]=function () {
				var modelClass = c[model];
				return new modelClass({ autoInit: true }, s.c, s, s.db);
			};
		}
357702
def creation_ordered(class_to_decorate):
    

    next_index = functools.partial(next, itertools.count())

    __init__orig = class_to_decorate.__init__

    @functools.wraps(__init__orig, assigned=['__doc__'])
    def __init__(self, *args, **kwargs):
        object.__setattr__(self, '_index', next_index())
        __init__orig(self, *args, **kwargs)

    setattr(class_to_decorate, '__init__', __init__)

    # noinspection PyProtectedMember
    def __lt__(self, other):
        return self._index < other._index  # pragma: no mutate

    setattr(class_to_decorate, '__lt__', __lt__)

    class_to_decorate = functools.total_ordering(class_to_decorate)

    return class_to_decorate
174481
function ModelIndices(model) {
    // For now the only indices we construct are for flowEvents
    this.flowEventsById_ = {};
    model.flowEvents.forEach(function(fe) {
      if (fe.id !== undefined) {
        if (!this.flowEventsById_.hasOwnProperty(fe.id)) {
          this.flowEventsById_[fe.id] = new Array();
        }
        this.flowEventsById_[fe.id].push(fe);
      }
    }, this);
  }
780688
def update_models(new_obj, current_table, tables, relations):
    
    _update_check_inputs(current_table, tables, relations)
    _check_no_current_table(new_obj, current_table)

    if isinstance(new_obj, Table):
        tables_names = [t.name for t in tables]
        _check_not_creating_duplicates(new_obj.name, tables_names, 'table', DuplicateTableException)
        return new_obj, tables + [new_obj], relations

    if isinstance(new_obj, Relation):
        tables_names = [t.name for t in tables]
        _check_colname_in_lst(new_obj.right_col, tables_names)
        _check_colname_in_lst(new_obj.left_col, tables_names)
        return current_table, tables, relations + [new_obj]

    if isinstance(new_obj, Column):
        columns_names = [c.name for c in current_table.columns]
        _check_not_creating_duplicates(new_obj.name, columns_names, 'column', DuplicateColumnException)
        current_table.columns.append(new_obj)
        return current_table, tables, relations

    msg = "new_obj cannot be of type {}"
    raise ValueError(msg.format(new_obj.__class__.__name__))
259851
def assert_valid_order(order, fields)
      Array(order).each do |order_entry|
        case order_entry
          when Symbol, String
            unless @properties.named?(order_entry)
              raise ArgumentError, "+options[:order]+ entry #{order_entry.inspect} does not map to a property in #{model}"
            end
        end
      end
    end
749407
function createInstances(seqObj, models, config, done) {
    Object.keys(models).forEach((key) => {
      let modelObj = models[key],
        attributes = {},
        options = thorin.util.extend({}, modelObj.options);
      modelObj.privateAttributes = [];
      // map the attributes
      Object.keys(modelObj.fields).forEach((fieldName) => {
        let fieldOpt = modelObj.fields[fieldName];
        if (modelObj.getters[fieldName]) {
          fieldOpt.get = modelObj.getters[fieldName];
        }
        if (modelObj.setters[fieldName]) {
          fieldOpt.set = modelObj.setters[fieldName];
        }
        if (fieldOpt.private) {
          modelObj.privateAttributes.push(fieldName);
        }
        attributes[fieldName] = fieldOpt;
      });
      if (options.createdAt === true) options.createdAt = 'created_at';
      if (options.updatedAt === true) {
        options.updatedAt = 'updated_at';
        if (!attributes[options.updatedAt]) {
          attributes[options.updatedAt] = {
            defaultValue: null,
            allowNull: true,
            type: sequelize.DATE
          }
        }
      }
      if (options.deletedAt === true) {
        options.deletedAt = 'deleted_at';
        if (!attributes[options.deletedAt]) {
          attributes[options.deletedAt] = {
            defaultValue: null,
            allowNull: true,
            type: sequelize.DATE
          }
        }
      }
      // create the inner options.
      options.underscored = true;
      options.charset = config.options.charset || 'utf8';
      options.collate = config.options.collate || 'utf8_general_ci';
      options.tableName = modelObj.tableName;
      options.indexes = modelObj.indexes;
      options.instanceMethods = modelObj.methods;
      options.classMethods = modelObj.statics;
      options.hooks = modelObj.hooks;
      options.validate = {};
      let validatorId = 0;
      // set validations
      modelObj.validations.forEach((item) => {
        if (item.name) { // we have a field validator.
          if (!attributes[item.name]) {
            console.warn('Thorin.sql: model ' + key + " does not have field " + item.name + ' for validator.');
            return;
          }
          if (!attributes[item.name].validate) attributes[item.name].validate = {};
          attributes[item.name].validate['validate' + item.name + validatorId] = item.fn;
          validatorId++;
          return;
        }
        // we have a model validator.
        options.validate['thorinValidate' + validatorId] = item.fn;
        validatorId++;
      });

      // wrap the toJSON function to exclude private fields.
      function ToJSON(jsonName) {
        if (jsonName === 'result') jsonName = 'default';
        let args = Array.prototype.slice.call(arguments);
        if (typeof jsonName === 'undefined') {
          jsonName = 'default';
        } else if (typeof jsonName === 'string') {
          args.splice(0, 1);  //remove the name.
        }
        let jsonFn = modelObj.jsons[jsonName],
          result = this.dataValues;
        if (typeof jsonFn === 'undefined' && jsonName !== 'default') { // silent fallback
          if (typeof modelObj.jsons['default'] === 'function') {
            result = modelObj.jsons['default'].apply(this, args);
          }
        } else {
          if (typeof modelObj.jsons[jsonName] === 'function') {
            result = modelObj.jsons[jsonName].apply(this, args);
          } else {
            result = this.dataValues;
          }
        }
        if (result === this) {
          result = this.dataValues;
        }
        if (typeof result === 'object' && result != null) {
          for (let i = 0; i < modelObj.privateAttributes.length; i++) {
            if (typeof result[modelObj.privateAttributes[i]] !== 'undefined') {
              delete result[modelObj.privateAttributes[i]];
            }
          }
        }
        return result;
      }

      options.instanceMethods['toJSON'] = ToJSON;
      // we do a synonym to .json()
      options.instanceMethods['json'] = ToJSON;

      // Check model prefix
      if (typeof modelObj.prefix === 'string' && typeof options.tableName === 'string') {
        options.tableName = modelObj.prefix + options.tableName;
      }
      var modelInstance;
      try {
        modelInstance = seqObj.define(modelObj.code, attributes, options);
      } catch (e) {
        console.error('Thorin.sql: could not create sequelize schema for: ' + modelObj.code + '\n', e.stack);
        return;
      }
      if (typeof attributes['id'] === 'undefined') {
        if (modelObj.options.primaryKey === false) {
          modelInstance.removeAttribute('id');
        }
      }
      modelObj.setInstance(modelInstance);
    });
    done();
  }
1130516
def first_or_create(self, _attributes=None, **attributes):
        
        if _attributes is not None:
            attributes.update(_attributes)

        instance = self.where(attributes).first()

        if instance is None:
            instance = self.create(**attributes)

        return instance
149210
function orderby (args, order) {
    if (this.typecheck) t.typecheck('orderby', [args, order]);
    
    var o = (order&&'string'===typeof order) ? order : '';
    var result = [];

    if ('string'===typeof args) {
        result = o ? [args+' '+o] : [args];
    }
    else if (args instanceof Array) {
        for (var i=0; i < args.length; i++) {
            if ('string'===typeof args[i]) {
                o ? result.push(args[i]+' '+o) : result.push(args[i]);
            }
            else if ('object'===typeof args[i]) {
                var key = Object.keys(args[i])[0];
                result.push(key+' '+args[i][key]);
            }
        }
    }
    else if (args instanceof Object) {
        var key = Object.keys(args)[0];
        result = [key+' '+args[key]];
    }

    return 'order by '+result.join();
}
853240
function(models, options) {
      if (_.isArray(models)) {
        for (var i = 0, l = models.length; i < l; i++) {
          this._add(models[i], options);
        }
      } else {
        this._add(models, options);
      }
      return this;
    }
770393
function initModelList (args) {
    var controller = this
    var model = this.model
    // make sure args is object
    args = requireValidOptionalObject(args)
    // make sure list is defined
    args.list = requireValidOptionalObject(args.list)
    // make sure query args are object
    var queryArgs = requireValidOptionalObject(args.list.query)
    // create title from name
    var title = model.title+' Records'
    // create new form instance configured to submit from list page
    if (controller.form && _.get(args, 'list.form') !== false) {
        var form = controller.form.newInstance({
            action: './?redirect=./',
        })
    }
    // get role
    var role = args.defaultRole || 'all'
    // build fields for table view
    this.fields = buildFields(model, args.list && args.list.fields)
    // index inputs
    var input = {
        // included deleted records
        deleted: 'query.deleted',
        // limit - overrides value in query if any
        limit: 'query.limit',
        // offset - overrides value in query if any
        offset: 'query.offset',
        // column to sort by
        orderColumn: 'query.orderColumn',
        // direction to sort in
        orderDirection: 'query.orderDirection',
        // free-form search string
        search: 'query.search',
        // list of columns to select
        select: 'query.select',
        // json encoded where arguments
        where: 'query.where',
    }
    // if model has an original id column then add to query options
    if (model.columnName('originalId')) {
        input.originalId = 'query.originalId'
    }
    // add extra columns as query param options
    _.each(model.extraColumns, (spec, name) => {
        // only add column if it has index
        if (!spec.index && !spec.unique) {
            return
        }
        // do not overwrite core inputs
        if (input[name]) {
            return
        }
        // add column to inputs
        input[name] = 'query.'+name
    })
    // links to display at top of page
    var links
    // use links from list view
    if (Array.isArray(args.list.links)) {
        links = args.list.links
    }
    // use global controller links
    else if (Array.isArray(args.links)) {
        links = args.links
    }
    // set default links
    else {
        links = [
            {href: './new', title: 'Create New'},
        ]
    }
    // create path if it does not exist
    if (!this.paths['/']) {
        this.paths['/'] = {}
    }
    // add list handler for GET on /
    this.paths['/'].get = [
        {
            before: function (args) {
                // load records
                return beforeList(controller, args, _.cloneDeep(controller.fields), title, form, links, queryArgs)
            },
            input: input,
            method: function (args) {
                return args.json
                    ? _.pick(args, ['records', 'result'])
                    : _.pick(args, ['clear', 'fields', 'form', 'links', 'pager', 'query', 'records', 'result', 'title'])
            },
            methodName: 'list',
            role: role,
        },
    ]
}