Page factory.

    Config models example:

    .. code-block:: python

        models = {
            '': [WebPage, CatalogResource],
            'catalogue': CatalogResource,
            'news': NewsResource,
        }
162599
def page_factory(request):
    
    prefix = request.matchdict['prefix']  # /{prefix}/page1/page2/page3...
    settings = request.registry.settings
    dbsession = settings[CONFIG_DBSESSION]
    config = settings[CONFIG_MODELS]

    if prefix not in config:
        # prepend {prefix} to *traverse
        request.matchdict['traverse'] =\
            tuple([prefix] + list(request.matchdict['traverse']))
        prefix = None

    # Get all resources and models from config with the same prefix.
    resources = config.get(
        prefix, config.get(   # 1. get resources with prefix same as URL prefix
            '', config.get(   # 2. if not, then try to get empty prefix
                '/', None)))  # 3. else try to get prefix '/' otherwise None

    if not hasattr(resources, '__iter__'):
        resources = (resources, )

    tree = {}

    if not resources:
        return tree

    # Add top level nodes of resources in the tree
    for resource in resources:
        table = None
        if not hasattr(resource, '__table__')\
                and hasattr(resource, 'model'):
            table = resource.model
        else:
            table = resource

        if not hasattr(table, 'slug'):
            continue

        nodes = dbsession.query(table)
        if hasattr(table, 'parent_id'):
            nodes = nodes.filter(or_(
                table.parent_id == None,  # noqa
                table.parent.has(table.slug == '/')
            ))
        for node in nodes:
            if not node.slug:
                continue
            resource = resource_of_node(resources, node)
            tree[node.slug] = resource(node, prefix=prefix)
    return tree
538115
def _configobj_factory(self,
                           infile,
                           raise_errors=True,
                           list_values=True,
                           file_error=True,
                           interpolation=False,
                           configspec=None,
                           stringify=True,
                           _inspec=False
                           ):
        

        return configobj.ConfigObj(infile=infile,
                                   raise_errors=raise_errors,
                                   list_values=list_values,
                                   file_error=file_error,
                                   interpolation=interpolation,
                                   configspec=configspec,
                                   stringify=stringify,
                                   _inspec=_inspec
                                   )
63886
public List<CmsModelPageEntry> getModelPages() {

        List<CmsModelPageConfig> modelPageConfigs = m_adeConfig.getModelPages(true);
        return buildModelPageList(modelPageConfigs);
    }
988859
def model(self, name=None, model=None, mask=None, **kwargs):
        
        if isinstance(model, (flask_marshmallow.Schema, flask_marshmallow.base_fields.FieldABC)):
            if not name:
                name = model.__class__.__name__
            api_model = Model(name, model, mask=mask)
            api_model.__apidoc__ = kwargs
            return self.add_model(name, api_model)
        return super(Namespace, self).model(name=name, model=model, **kwargs)
672102
def list_build_configuration_sets(page_size=200, page_index=0, sort="", q=""):
    
    data = list_build_configuration_sets_raw(page_size, page_index, sort, q)
    if data:
        return utils.format_json_list(data)
52785
def create_proxy_model(name, model_mixins, base_model, attrs=None, module=None):
    
    from django.apps import apps

    class Meta:
        proxy = True
        app_label = 'cmsplugin_cascade'

    name = str(name + 'Model')
    try:
        Model = apps.get_registered_model(Meta.app_label, name)
    except LookupError:
        bases = model_mixins + (base_model,)
        attrs = dict(attrs or {}, Meta=Meta, __module__=module)
        Model = type(name, bases, attrs)
        fake_proxy_models[name] = bases
    return Model
517283
def get_content_models(self):
        
        models = super(PageAdmin, self).get_content_models()

        order = [name.lower() for name in settings.ADD_PAGE_ORDER]

        def sort_key(page):
            name = "%s.%s" % (page._meta.app_label, page._meta.object_name)
            unordered = len(order)
            try:
                return (order.index(name.lower()), "")
            except ValueError:
                return (unordered, page.meta_verbose_name)
        return sorted(models, key=sort_key)
545373
def _set_seo_models(self, value):
        
        seo_models = []
        for model_name in value:
            if "." in model_name:
                app_label, model_name = model_name.split(".", 1)
                model = models.get_model(app_label, model_name)
                if model:
                    seo_models.append(model)
            else:
                app = models.get_app(model_name)
                if app:
                    seo_models.extend(models.get_models(app))
    
        self.seo_models = seo_models
252586
def _build_dictionary(self, models):
        
        for model in models:
            key = getattr(model, self._morph_type, None)
            if key:
                foreign = getattr(model, self._foreign_key)
                if key not in self._dictionary:
                    self._dictionary[key] = {}

                if foreign not in self._dictionary[key]:
                    self._dictionary[key][foreign] = []

                self._dictionary[key][foreign].append(model)
1239224
def get_app_model_classes(self):
        
        models = []
        for m in self.models:
            mod, cls = m.rsplit('.', 1)
            mod = import_module(mod)
            models.append(getattr(mod, cls))
        return models
229438
def models(self):
        '''
        
        '''
        model_dict = self._build_all_dependencies()
        while True:
            model = self._get_model_without_dependencies(model_dict)
            if not model:
                break
            yield (model, self._models().get(model))
1082368
def model_typedefs(vk, model):
    
    model['typedefs'] = {}

    # bitmasks and basetypes
    bitmasks = [x for x in vk['registry']['types']['type']
                if x.get('@category') == 'bitmask']

    basetypes = [x for x in vk['registry']['types']['type']
                 if x.get('@category') == 'basetype']

    for typedef in bitmasks + basetypes:
        if not typedef.get('type'):
            continue
        model['typedefs'][typedef['name']] = typedef['type']

    # handles
    handles = [x for x in vk['registry']['types']['type']
               if x.get('@category') == 'handle']

    for handle in handles:
        if 'name' not in handle or 'type' not in handle:
            continue

        n = handle['name']
        t = handle['type']
        if t == 'VK_DEFINE_HANDLE':
            model['typedefs']['struct %s_T' % n] = '*%s' % n
        if t == 'VK_DEFINE_HANDLE':
            model['typedefs'][n] = 'uint64_t'

    # custom plaform dependant
    for name in ['Display', 'xcb_connection_t', 'wl_display', 'wl_surface',
                 'MirConnection', 'MirSurface', 'ANativeWindow',
                 'SECURITY_ATTRIBUTES']:
        model['typedefs'][name] = 'struct %s' % name

    model['typedefs'].update({
        'Window': 'uint32_t', 'VisualID': 'uint32_t',
        'xcb_window_t': 'uint32_t', 'xcb_visualid_t': 'uint32_t'
    })
661368
def _initialize_lists(model_class, name, bases, attrs):
    """"""
    model_class._lists = {}
    for k, v in attrs.iteritems():
        if isinstance(v, ListField):
            model_class._lists[k] = v
            v.name = v.name or k
600133
def model_mag(self, pardict, use_cache=True):
        
        if pardict == self._cache_key and use_cache:
            #print('{}: using cached'.format(self))
            return self._cache_val

        #print('{}: calculating'.format(self))
        self._cache_key = pardict


        # Generate appropriate parameter vector from dictionary
        p = []
        for l in self.leaf_labels:
            p.extend(pardict[l])

        assert len(p) == self.n_params

        tot = np.inf
        #print('Building {} mag for {}:'.format(self.band, self))
        for i,m in enumerate(self.leaves):
            mag = m.evaluate(p[i*5:(i+1)*5], self.band)
            # logging.debug('{}: mag={}'.format(self,mag))
            #print('{}: {}({}) = {}'.format(m,self.band,p[i*5:(i+1)*5],mag))
            tot = addmags(tot, mag)

        self._cache_val = tot
        return tot
818769
def list_models(args: argparse.Namespace):
    
    try:
        git_index = GitIndex(remote=args.index_repo, username=args.username,
                             password=args.password, cache=args.cache, log_level=args.log_level)
    except ValueError:
        return 1
    for model_type, models in git_index.models.items():
        print(model_type)
        default = git_index.meta[model_type]["default"]
        for uuid, model in sorted(models.items(),
                                  key=lambda m: parse_datetime(m[1]["created_at"]),
                                  reverse=True):
            print("  %s %s" % ("*" if default == uuid else " ", uuid),
                  model["created_at"])
752242
def _extract_models(cls, apis):
        ''''''
        # TODO: This would probably be much better if the info would be
        # extracted from the classes, rather than from the swagger
        # representation...
        models = set()
        for api in apis:
            for op in api.get('operations', []):
                models.add(op['type'])
                for param in op.get('parameters', []):
                    models.add(param.get('type', 'void'))
                for msg in op['responseMessages']:
                    models.add(msg.get('responseModel', 'void'))
        # Convert from swagger name representation to classes
        models = map(lambda m: Model.name_to_cls[m], models)
        ret = {}
        for model in models:
            if model.native_type:
                continue
            obj = model.schema.copy()
            obj['id'] = model.name
            ret[model.name] = obj
        return ret
1095011
def load_network_model(model):
    '''
    
    '''
    if type(model) == str:
        if model in ['ecoli', 'textbook', 'salmonella']:
            return cb.test.create_test_model(model)
        elif model == 'recon2':
            return cb.io.load_json_model('%s/network_models/%s.json' %
                                         (DATASET_PATH, model))
    if type(model) == cb.Model:
        return model