Get the definition of a model and format the result in a way that's similar to a LoopBack model definition file
10763
function getModelInfo (modelName) {
    debug('getModelInfo: ' + modelName)

    // Get the model
    const model = Meta.app.models[ modelName ]

    // Create the base return object
    const result = {
      id: model.definition.name,
      name: model.definition.name,
      properties: formatProperties(model.definition.properties)
    }

    // Get the following keys from the settings object, if they are set
    const keys = {
      'acls': [],
      'base': '',
      'description': '',
      'hidden': [],
      'idInjection': true,
      'methods': {},
      'mixins': {},
      'persistUndefinedAsNull': false,
      'plural': '',
      'relations': {},
      'strict': false,
      'validations': [],
    }

    // Loop through the keys and add them to the result with their value
    Object.keys(keys).forEach(key => {
      result[ key ] = _.get(model.definition.settings, key, keys[ key ])
    })
    return result
  }
954726
def _getModelData(self, modelData, parentItem=None):
        """"""
        if parentItem is None:
            parentItem = self.rootItem

        for item in parentItem.getChildren():
            key = item.getItemData(0)
            if item.childCount():
                modelData[key] = odict()
                self._getModelData(modelData[key], item)
            else:
                if isinstance(item.getItemData(2), float):
                    modelData[key] = [item.getItemData(1), item.getItemData(2)]
                else:
                    modelData[key] = item.getItemData(1)
442785
def result_to_models(self, result):
        
        mysql_result = result['body']['ExecuteMSQLResult']

        if not mysql_result['Errors']:
            obj_result = mysql_result['ResultValue']['ObjectSearchResult']
            if not obj_result['Objects']:
                return []
            objects = obj_result['Objects']['MemberSuiteObject']

            model_list = []
            for obj in objects:
                model = self.ms_object_to_model(obj)
                model_list.append(model)

            return model_list

        else:
            raise ExecuteMSQLError(result)
260111
def generate_model_file(filename, project, model, fields):
    """"""
    for field in fields:
        field.type = field.__class__.__name__

    content = open(os.path.join(os.path.dirname(__file__), 'templates/model_page.html'), 'r').read()

    engine = StatikTemplateEngine(project)
    template = engine.create_template(content)

    # create context and update from project.config
    context = {'model': model,
                'fields': fields}
    context.update(dict(project.config.context_static))
    string = template.render(context)

    with open(filename, 'w') as file:
        file.write(string)
1041787
def get_model(method):
    """"""

    @wraps(method)
    def wrapper(migrator, model, *args, **kwargs):
        if isinstance(model, str):
            return method(migrator, migrator.orm[model], *args, **kwargs)
        return method(migrator, model, *args, **kwargs)
    return wrapper
702094
def model_function(self, model_name, version, func_name):
        """"""
        assert func_name in ('serializer', 'loader', 'invalidator')
        name = "%s_%s_%s" % (model_name.lower(), version, func_name)
        return getattr(self, name)
863033
function getModelFromContext (context, app) {
  var type = getTypeFromContext(context)
  if (app.models[type]) return app.models[type]

  var name = modelNameFromContext(context)
  return app.models[name]
}
905995
def load_model(model_file):
    
    # Extract tar
    with tarfile.open(model_file) as tar:
        tarfolder = tempfile.mkdtemp()
        tar.extractall(path=tarfolder)

    from . import features
    from . import preprocessing

    # Get the preprocessing
    with open(os.path.join(tarfolder, "preprocessing.yml"), 'r') as ymlfile:
        preprocessing_description = yaml.load(ymlfile)
    preprocessing_queue = preprocessing.get_preprocessing_queue(
        preprocessing_description['queue'])

    # Get the features
    with open(os.path.join(tarfolder, "features.yml"), 'r') as ymlfile:
        feature_description = yaml.load(ymlfile)
    feature_str_list = feature_description['features']
    feature_list = features.get_features(feature_str_list)

    # Get the model
    import nntoolkit.utils
    model = nntoolkit.utils.get_model(model_file)

    output_semantics_file = os.path.join(tarfolder, 'output_semantics.csv')
    output_semantics = nntoolkit.utils.get_outputs(output_semantics_file)

    # Cleanup
    shutil.rmtree(tarfolder)

    return (preprocessing_queue, feature_list, model, output_semantics)
863017
def to_model(self):
        """"""
        e = ApiPool().current_server_api.model.Error(
            status=self.status,
            error=self.code.upper(),
            error_description=str(self),
        )
        if self.error_id:
            e.error_id = self.error_id
        if self.user_message:
            e.user_message = self.user_message
        if self.error_caught:
            e.error_caught = pformat(self.error_caught)
        return e
690898
function getModel(model) {
  const schemaPaths = model.schema.paths;
  const name = model.modelName;

  const fields = extractPaths(schemaPaths, { name });

  return {
    name,
    fields,
    model
  };
}
133007
def doc(model):
    
    ins = inspect(model)

    return SaModelDoc(
        name=model.__name__,
        table=[t.name for t in ins.tables],
        doc=getdoc(ins.class_),
        columns=_model_columns(ins),
        primary=_model_primary(ins),
        foreign=_model_foreign(ins),
        unique=_model_unique(ins),
        relations=_model_relations(ins)
    )
1368995
def _resolve_template(value, model_instance=None, context=None):
        """"""
        if isinstance(value, string_types) and "{" in value:
            if context is None:
                context = Context()
            if model_instance is not None:
                context[model_instance._meta.model_name] = model_instance
            value = Template(value).render(context)
        return value
347859
function loadModel(modelSpecPath, name) {
  return plugin.myrmex.fire('beforeModelLoad', modelSpecPath, name)
  .spread(() => {
    // Because we use require() to get the spec, it could either be a JSON file
    // or the content exported by a node module
    // But because require() caches the content it loads, we clone the result to avoid bugs
    // if the function is called twice
    const modelSpec = _.cloneDeep(require(modelSpecPath));

    // Lasy loading because the plugin has to be registered in a Myrmex instance before requiring ./model
    const Model = require('./model');
    return Promise.resolve(new Model(name, modelSpec));
  })
  .then(model => {
    // This event allows to inject code to alter the model specification
    return plugin.myrmex.fire('afterModelLoad', model);
  })
  .spread((model) => {
    return Promise.resolve(model);
  });
}
193276
def compiled_model(self):
        """"""
        return ALCHEMY_TEMPLATES.model.safe_substitute(class_name=self.class_name,
                                                       table_name=self.table_name,
                                                       column_definitions=self.compiled_columns,
                                                       init_function=self.compiled_init_func,
                                                       update_function=self.compiled_update_func,
                                                       hash_function=self.compiled_hash_func,
                                                       eq_function=self.compiled_eq_func,
                                                       neq_function=self.compiled_neq_func,
                                                       str_function=self.compiled_str_func,
                                                       unicode_function=self.compiled_unicode_func,
                                                       repr_function=self.compiled_repr_func,
                                                       types=", ".join(self.basic_types),
                                                       username=self.username,
                                                       foreign_keys=self.compiled_foreign_keys,
                                                       relationships=self.compiled_relationships,
                                                       named_imports=self.compiled_named_imports,
                                                       orm_imports=self.compiled_orm_imports,
                                                       get_proxy_cls_function=self.compiled_proxy_cls_func,
                                                       add_function=ALCHEMY_TEMPLATES.add_function.template,
                                                       delete_function=ALCHEMY_TEMPLATES.delete_function.template,
                                                       to_dict_function=ALCHEMY_TEMPLATES.to_dict_function.template,
                                                       to_proxy_function=ALCHEMY_TEMPLATES.to_proxy_function.template,
                                                       from_proxy_function=ALCHEMY_TEMPLATES.from_proxy_function.template)
288585
function (name, schema, models, modelPropertyMacro) {
    var strongOpen = '<span class="strong">';
    var strongClose = '</span>';

    var optionHtml = function (label, value) {
      return '<tr><td class="optionName">' + label + ':</td><td>' + value + '</td></tr>';
    };


    // Allow for ignoring the 'name' argument.... shifting the rest
    if(_.isObject(arguments[0])) {
      name = void 0;
      schema = arguments[0];
      models = arguments[1];
      modelPropertyMacro = arguments[2];
    }

    models = models || {};

    // Resolve the schema (Handle nested schemas)
    schema = resolveSchema(schema);

    // Return for empty object
    if(_.isEmpty(schema)) {
      return strongOpen + 'Empty' + strongClose;
    }

    // Dereference $ref from 'models'
    if(typeof schema.$ref === 'string') {
      name = simpleRef(schema.$ref);
      schema = models[name];
      if(typeof schema === 'undefined')
      {
        return strongOpen + name + ' is not defined!' + strongClose;
      }
    }

    if(typeof name !== 'string') {
      name = schema.title || 'Inline Model';
    }

    // If we are a Model object... adjust accordingly
    if(schema.definition) {
      schema = schema.definition;
    }

    if(typeof modelPropertyMacro !== 'function') {
      modelPropertyMacro = function(prop){
        return (prop || {}).default;
      };
    }

    var references = {};
    var seenModels = [];
    var inlineModels = 0;

    // Generate current HTML
    var html = processModel(schema, name);

    // Generate references HTML
    while (_.keys(references).length > 0) {
      /* jshint ignore:start */
      _.forEach(references, function (schema, name) {
        var seenModel = _.indexOf(seenModels, name) > -1;

        delete references[name];

        if (!seenModel) {
          seenModels.push(name);

          html += '<br />' + processModel(schema, name);
        }
      });
      /* jshint ignore:end */
    }

    return html;


    function addReference(schema, name, skipRef) {
      var modelName = name;
      var model;

      if (schema.$ref) {
        modelName = schema.title || simpleRef(schema.$ref);
        model = models[simpleRef(schema.$ref)];
      } else if (_.isUndefined(name)) {
        modelName = schema.title || 'Inline Model ' + (++inlineModels);
        model = {definition: schema};
      }

      if (skipRef !== true) {
        references[modelName] = _.isUndefined(model) ? {} : model.definition;
      }

      return modelName;
    }

    function primitiveToHTML(schema) {
      var html = '<span class="propType">';
      var type = schema.type || 'object';

      if (schema.$ref) {
        html += addReference(schema, simpleRef(schema.$ref));
      } else if (type === 'object') {
        if (!_.isUndefined(schema.properties)) {
          html += addReference(schema);
        } else {
          html += 'object';
        }
      } else if (type === 'array') {
        html += 'Array[';

        if (_.isArray(schema.items)) {
          html += _.map(schema.items, addReference).join(',');
        } else if (_.isPlainObject(schema.items)) {
          if (_.isUndefined(schema.items.$ref)) {
            if (!_.isUndefined(schema.items.type) && _.indexOf(['array', 'object'], schema.items.type) === -1) {
              html += schema.items.type;
            } else {
              html += addReference(schema.items);
            }
          } else {
            html += addReference(schema.items, simpleRef(schema.items.$ref));
          }
        } else {
          console.log('Array type\'s \'items\' schema is not an array or an object, cannot process');
          html += 'object';
        }

        html += ']';
      } else {
        html += schema.type;
      }

      html += '</span>';

      return html;
    }

    function primitiveToOptionsHTML(schema, html) {
      var options = '';
      var type = schema.type || 'object';
      var isArray = type === 'array';

      if (isArray) {
        if (_.isPlainObject(schema.items) && !_.isUndefined(schema.items.type)) {
          type = schema.items.type;
        } else {
          type = 'object';
        }
      }

      if (!_.isUndefined(schema.default)) {
        options += optionHtml('Default', schema.default);
      }

      switch (type) {
      case 'string':
        if (schema.minLength) {
          options += optionHtml('Min. Length', schema.minLength);
        }

        if (schema.maxLength) {
          options += optionHtml('Max. Length', schema.maxLength);
        }

        if (schema.pattern) {
          options += optionHtml('Reg. Exp.', schema.pattern);
        }
        break;
      case 'integer':
      case 'number':
        if (schema.minimum) {
          options += optionHtml('Min. Value', schema.minimum);
        }

        if (schema.exclusiveMinimum) {
          options += optionHtml('Exclusive Min.', 'true');
        }

        if (schema.maximum) {
          options += optionHtml('Max. Value', schema.maximum);
        }

        if (schema.exclusiveMaximum) {
          options += optionHtml('Exclusive Max.', 'true');
        }

        if (schema.multipleOf) {
          options += optionHtml('Multiple Of', schema.multipleOf);
        }

        break;
      }

      if (isArray) {
        if (schema.minItems) {
          options += optionHtml('Min. Items', schema.minItems);
        }

        if (schema.maxItems) {
          options += optionHtml('Max. Items', schema.maxItems);
        }

        if (schema.uniqueItems) {
          options += optionHtml('Unique Items', 'true');
        }

        if (schema.collectionFormat) {
          options += optionHtml('Coll. Format', schema.collectionFormat);
        }
      }

      if (_.isUndefined(schema.items)) {
        if (_.isArray(schema.enum)) {
          var enumString;

          if (type === 'number' || type === 'integer') {
            enumString = schema.enum.join(', ');
          } else {
            enumString = '"' + schema.enum.join('", "') + '"';
          }

          options += optionHtml('Enum', enumString);
        }
      }

      if (options.length > 0) {
        html = '<span class="propWrap">' + html + '<table class="optionsWrapper"><tr><th colspan="2">' + type + '</th></tr>' + options + '</table></span>';
      }

      return html;
    }

    function processModel(schema, name) {
      var type = schema.type || 'object';
      var isArray = schema.type === 'array';
      var html = strongOpen + name + ' ' + (isArray ? '[' : '{') + strongClose;
      var contents;

      if (name) {
        seenModels.push(name);
      }

      if (isArray) {
        if (_.isArray(schema.items)) {
          html += '<div>' + _.map(schema.items, function (item) {
            var type = item.type || 'object';

            if (_.isUndefined(item.$ref)) {
              if (_.indexOf(['array', 'object'], type) > -1) {
                if (type === 'object' && _.isUndefined(item.properties)) {
                  return 'object';
                } else {
                  return addReference(item);
                }
              } else {
                return primitiveToOptionsHTML(item, type);
              }
            } else {
              return addReference(item, simpleRef(item.$ref));
            }
          }).join(',</div><div>');
        } else if (_.isPlainObject(schema.items)) {
          if (_.isUndefined(schema.items.$ref)) {
            if (_.indexOf(['array', 'object'], schema.items.type || 'object') > -1) {
              if ((_.isUndefined(schema.items.type) || schema.items.type === 'object') && _.isUndefined(schema.items.properties)) {
                html += '<div>object</div>';
              } else {
                html += '<div>' + addReference(schema.items) + '</div>';
              }
            } else {
              html += '<div>' + primitiveToOptionsHTML(schema.items, schema.items.type) + '</div>';
            }
          } else {
            html += '<div>' + addReference(schema.items, simpleRef(schema.items.$ref)) + '</div>';
          }
        } else {
          console.log('Array type\'s \'items\' property is not an array or an object, cannot process');
          html += '<div>object</div>';
        }
      } else {
        if (schema.$ref) {
          html += '<div>' + addReference(schema, name) + '</div>';
        } else if (type === 'object') {
          if (_.isPlainObject(schema.properties)) {
            contents = _.map(schema.properties, function (property, name) {
              var propertyIsRequired = (_.indexOf(schema.required, name) >= 0);
              var cProperty = _.cloneDeep(property);

              var requiredClass = propertyIsRequired ? 'required' : '';
              var html = '<span class="propName ' + requiredClass + '">' + name + '</span> (';
              var model;
              var propDescription;

              // Allow macro to set the default value
              cProperty.default = modelPropertyMacro(cProperty);

              // Resolve the schema (Handle nested schemas)
              cProperty = resolveSchema(cProperty);

              propDescription = property.description || cProperty.description;

              // We need to handle property references to primitives (Issue 339)
              if (!_.isUndefined(cProperty.$ref)) {
                model = models[simpleRef(cProperty.$ref)];

                if (!_.isUndefined(model) && _.indexOf([undefined, 'array', 'object'], model.definition.type) === -1) {
                  // Use referenced schema
                  cProperty = resolveSchema(model.definition);
                }
              }

              html += primitiveToHTML(cProperty);

              if(!propertyIsRequired) {
                html += ', <span class="propOptKey">optional</span>';
              }

              if(property.readOnly) {
                  html += ', <span class="propReadOnly">read only</span>';
              }

              html += ')';

              if (!_.isUndefined(propDescription)) {
                html += ': ' + '<span class="propDesc">' + propDescription + '</span>';
              }

              if (cProperty.enum) {
                html += ' = <span class="propVals">[\'' + cProperty.enum.join('\', \'') + '\']</span>';
              }

              return '<div' + (property.readOnly ? ' class="readOnly"' : '') + '>' + primitiveToOptionsHTML(cProperty, html);
            }).join(',</div>');
          }

          if (contents) {
            html += contents + '</div>';
          }
        } else {
          html += '<div>' + primitiveToOptionsHTML(schema, type) + '</div>';
        }
      }

      return html + strongOpen + (isArray ? ']' : '}') + strongClose;
    }

  }
570547
function() {
    var model = this._model;
    var arrayTransform = function(result) { // jscs:ignore jsDoc
      return result.rows;
    };
    var modelTransform = function(rows) { // jscs:ignore jsDoc
      return rows.map(model.load.bind(model));
    };

    var dup = this._dup()
      .transform(arrayTransform)
      .transform(modelTransform);

    dup._arrayTransform = arrayTransform;
    dup._modelTransform = modelTransform;

    return dup;
  }
1131944
function (type, definitions) {
      var isPrimitive, listType;

      if (type instanceof Array) {
        listType = true;
        type = type[0];
      }

      // Convert undefined to string of 'undefined'
      if (typeof type === 'undefined') {
        type = 'undefined';
        isPrimitive = true;

      } else if (definitions[type]){
        // a model def exists?
        type = definitions[type]; /* Model */
        isPrimitive = false;

      } else if (getInlineModel(type)) {
        type = getInlineModel(type); /* Model */
        isPrimitive = false;

      } else {
        // We default to primitive
        isPrimitive = true;
      }

      if (isPrimitive) {
        if (listType) {
          return 'Array[' + type + ']';
        } else {
          return type.toString();
        }
      } else {
        if (listType) {
          return 'Array[' + getModelSignature(type.name, type.definition, type.models, type.modelPropertyMacro) + ']';
        } else {
          return getModelSignature(type.name, type.definition, type.models, type.modelPropertyMacro);
        }
      }
  }