Print apps_models which contains a list of 2-tuples containing apps and their models
        into a single file.
14491
def _print_single_file(self, path, apps_models):
        
        if path:
            outfile = codecs.open(path, 'w', encoding='utf-8')
            self._print = lambda s: outfile.write(s + '\n')
        self._print(self._diagram_start)
        for app, app_models in apps_models:
            self._print_app(app, app_models)
        self._print(self._diagram_end)
        if path:
            outfile.close()
681084
def _get_model(self, appname, modelname):
        
        app = self._get_app(appname)
        models = app.get_models()
        model = None
        for mod in models:
            if mod.__name__ == modelname:
                model = mod
                return model
        msg = "Model " + modelname + " not found"
1357242
def get_models(args):
    
    if args:
        models = []
        for arg in args:
            match_found = False
            for model in registry.get_models():
                if model._meta.app_label == arg:
                    models.append(model)
                    match_found = True
                elif '%s.%s' % (model._meta.app_label, model._meta.model_name) == arg:
                    models.append(model)
                    match_found = True

            if not match_found:
                raise ValueError("No model or app named %s" % arg)
    else:
        models = registry.get_models()

    return set(models)
1043659
def app_list(**kwargs):
    
    ctx = Context(**kwargs)
    ctx.execute_action('app:list', **{
        'storage': ctx.repo.create_secure_service('storage'),
    })
962066
def get_report_parts(self, apps, formats):
        
        for fmt in formats:
            width = 100 if fmt is not None else tui.get_terminal_size()[0]
            for sr in self.subreports:
                sr.make_format(fmt, width)

        logger.debug('Build a map for arguments and run\'s statistics ...')
        value_mapping = {
            'title': self.title,
            'patterns': ', '.join([repr(pattern) for pattern in self.args.patterns]) or None,
            'pattern_files': ', '.join(self.args.pattern_files) or None,
            'hosts': ', '.join(self.args.hosts) or None,
            'apps': u', '.join([
                u'%s(%d)' % (app.name, app.matches) for app in apps.values() if app.matches > 0
            ]),
            'version': __version__
        }

        filters = []
        for flt in self.args.filters:
            filters.append(' AND '.join(['%s=%r' % (k, v.pattern) for k, v in flt.items()]))
        if filters:
            value_mapping['filters'] = ' OR '.join(['(%s)' % item for item in filters])
        else:
            value_mapping['filters'] = filters[0] if filters else None

        value_mapping.update(self.stats)

        report = []
        for fmt in formats:
            if fmt == 'text':
                logger.info('appends a text page report')
                report.append(self.make_text_page(value_mapping))
            elif fmt == 'html':
                logger.info('appends a html page report')
                report.append(self.make_html_page(value_mapping))
            elif fmt == 'csv':
                logger.info('extends with a list of csv subreports')
                report.extend(self.make_csv_tables())
        return report
205247
def load_models(self, model_path):
        
        condition_model_files = sorted(glob(model_path + "*_condition.pkl"))
        if len(condition_model_files) > 0:
            for condition_model_file in condition_model_files:
                model_comps = condition_model_file.split("/")[-1][:-4].split("_")
                if model_comps[0] not in self.condition_models.keys():
                    self.condition_models[model_comps[0]] = {}
                model_name = model_comps[1].replace("-", " ")
                with open(condition_model_file, "rb") as cmf:
                    if "condition_threshold" in condition_model_file:
                        self.condition_models[model_comps[0]][model_name + "_condition_threshold"] = pickle.load(cmf)
                    else:
                        self.condition_models[model_comps[0]][model_name] = pickle.load(cmf)

        size_model_files = sorted(glob(model_path + "*_size.pkl"))
        if len(size_model_files) > 0:
            for size_model_file in size_model_files:
                model_comps = size_model_file.split("/")[-1][:-4].split("_")
                if model_comps[0] not in self.size_models.keys():
                    self.size_models[model_comps[0]] = {}
                model_name = model_comps[1].replace("-", " ")
                with open(size_model_file, "rb") as smf:
                    self.size_models[model_comps[0]][model_name] = pickle.load(smf)

        size_dist_model_files = sorted(glob(model_path + "*_sizedist.pkl"))
        if len(size_dist_model_files) > 0:
            for dist_model_file in size_dist_model_files:
                model_comps = dist_model_file.split("/")[-1][:-4].split("_")
                if model_comps[0] not in self.size_distribution_models.keys():
                    self.size_distribution_models[model_comps[0]] = {}
                if "_".join(model_comps[2:-1]) not in self.size_distribution_models[model_comps[0]].keys():
                    self.size_distribution_models[model_comps[0]]["_".join(model_comps[2:-1])] = {}
                model_name = model_comps[1].replace("-", " ")
                with open(dist_model_file, "rb") as dmf:
                    self.size_distribution_models[model_comps[0]]["_".join(model_comps[2:-1])][
                        model_name] = pickle.load(dmf)

        track_model_files = sorted(glob(model_path + "*_track.pkl"))
        if len(track_model_files) > 0:
            for track_model_file in track_model_files:
                model_comps = track_model_file.split("/")[-1][:-4].split("_")
                group = model_comps[0]
                model_name = model_comps[1].replace("-", " ")
                model_type = model_comps[2]
                if model_type not in self.track_models.keys():
                    self.track_models[model_type] = {}
                if group not in self.track_models[model_type].keys():
                    self.track_models[model_type][group] = {}
                with open(track_model_file, "rb") as tmf:
                    self.track_models[model_type][group][model_name] = pickle.load(tmf)
800977
def write(models, out=None, base=None, logger=logging):
    '''
    
    '''
    assert out is not None #Output stream required
    if not isinstance(models, list): models = [models]
    for m in models:
        for link in m.match():
            s, p, o = link[:3]
            #Skip docheader statements
            if s == (base or '') + '@docheader': continue
            if p in RESOURCE_MAPPING: p = RESOURCE_MAPPING[p]
            if o in RESOURCE_MAPPING: o = RESOURCE_MAPPING[o]
            
            if p == VERSA_TYPE_REL: p = RDF_TYPE_REL
            print(strconv(s), strconv(p), strconv(o), '.', file=out)
    return
37853
def _build_app_models(request, admin_apps, models_tuples, ensure_all_models=False):
    

    app_models = []
    for app_and_model, config in models_tuples:
        if app_and_model:
            app_label, model_name = app_and_model.split('.')

            for app in admin_apps:
                if app['app_label'] == app_label:
                    for model in app['models']:
                        if model['object_name'] == model_name:
                            try:
                                model['name'] = \
                                    config['name']
                            except KeyError:
                                pass

                            # Get each of the polymorphic types to allow addition.
                            model_class = apps.get_model(app_and_model)
                            model_admin = admin.site._registry[model_class]

                            if hasattr(model_admin, 'get_child_type_choices'):
                                model['polymorphic_classes'] = \
                                    model_admin.get_child_type_choices(
                                        request, 'add'
                                    )

                            # TODO: Fluent/polymorphic has a way of sorting child order which should be used instead
                            if 'default_poly_child' in config.keys():
                                ct = ContentType.objects.get_by_natural_key(
                                    *config['default_poly_child'].lower().split('.')
                                )
                                model.default_poly_child = ct.id

                            app_models.append(model)

                    break

    return app_models
1353631
def __parse_app_list(app_list):
        
        args = {}
        apps = []
        for app_str in app_list:
            parts = app_str.split("&")
            app_path = parts[0].strip()
            apps.append(app_path)
            if len(parts) > 1:
                args[app_path] = [arg.strip() for arg in parts[1].split()]
            else:
                args[app_path] = []
        return apps, args
461701
def model_export_to_file(f, model=None, repo=None):
    
    if not model and not repo:
        raise Exception("specity either a model or a repo")
    if model and repo:
        raise Exception("specity either a model or a repo")

    processed_set = set()
    f.write(HEADER)

    def _export(obj):

        if obj is None or obj in processed_set or type(obj) \
                in PRIMITIVE_PYTHON_TYPES:
            return

        processed_set.add(obj)

        attrs = ""
        obj_cls = obj.__class__
        name = ""
        for attr_name, attr in obj_cls._tx_attrs.items():

            attr_value = getattr(obj, attr_name)

            endmark = 'arrowtail=diamond dir=both' if attr.cont else ""
            required = "+" if attr.mult in \
                [MULT_ONE, MULT_ONEORMORE] else ""

            if attr.mult in [MULT_ONEORMORE, MULT_ZEROORMORE]:
                if all([type(x) in PRIMITIVE_PYTHON_TYPES
                        for x in attr_value]):
                    attrs += "{}{}:list=[".format(required, attr_name)
                    attrs += ",".join([dot_repr(x) for x in attr_value])
                    attrs += "]\\l"
                else:
                    for idx, list_obj in enumerate(attr_value):
                        if list_obj is not None:
                            if type(list_obj) in PRIMITIVE_PYTHON_TYPES:
                                f.write(
                                    '{} -> "{}:{}" [label="{}:{}" {}]\n'
                                    .format(id(obj), list_obj,
                                            type(list_obj).__name__,
                                            attr_name, idx, endmark))
                            else:
                                f.write('{} -> {} [label="{}:{}" {}]\n'
                                        .format(id(obj), id(list_obj),
                                                attr_name, idx, endmark))
                                _export(list_obj)
            else:

                # Plain attributes
                if type(attr_value) is text and attr_name != 'name':
                    attr_value = dot_repr(attr_value)

                if type(attr_value) in PRIMITIVE_PYTHON_TYPES:
                    if attr_name == 'name':
                        name = attr_value
                    else:
                        attrs += "{}{}:{}={}\\l".format(
                            required, attr_name, type(attr_value)
                            .__name__, attr_value)
                else:
                    # Object references
                    if attr_value is not None:
                        f.write('{} -> {} [label="{}" {}]\n'.format(
                            id(obj), id(attr_value),
                            attr_name, endmark))
                        _export(attr_value)

        name = "{}:{}".format(name, obj_cls.__name__)

        f.write('{}[label="{{{}|{}}}"]\n'.format(id(obj), name, attrs))

    def _export_subgraph(m):
        from textx import get_children
        f.write('subgraph "cluster_{}" {{\n'.format(m._tx_filename))
        f.write('''
        penwidth=2.0
        color=darkorange4;
        label = "{}";
                    '''.format(m._tx_filename))
        for obj in get_children(lambda _: True, m):
            f.write('{};\n'.format(id(obj)))
        f.write('\n}\n')

    if repo or hasattr(model, "_tx_model_repository"):
        if not repo:
            repo = model._tx_model_repository.all_models
        for m in repo.filename_to_model.values():
            _export_subgraph(m)
            _export(m)
    else:
        _export(model)

    f.write('\n}\n')
689681
def get_model_by_name(model_name):
    
    if isinstance(model_name, six.string_types) and \
            len(model_name.split('.')) == 2:
        app_name, model_name = model_name.split('.')

        if django.VERSION[:2] < (1, 8):
            model = models.get_model(app_name, model_name)
        else:
            from django.apps import apps
            model = apps.get_model(app_name, model_name)
    else:
        raise ValueError("{0} is not a Django model".format(model_name))

    return model
790734
def dump_all(data_list, stream=None, **kwargs):
    
    return yaml.dump_all(
        data_list,
        stream=stream,
        Dumper=YAMLDictDumper,
        **kwargs
    )
960583
def detect_flask_apps():
    

    matches = []
    for root, dirnames, filenames in os.walk(os.getcwd()):
        for filename in fnmatch.filter(filenames, '*.py'):
            full = os.path.join(root, filename)
            if 'site-packages' in full:
                continue

            full = os.path.join(root, filename)

            with io.open(full, 'r', encoding='utf-8') as f:
                lines = f.readlines()
                for line in lines:
                    app = None

                    # Kind of janky..
                    if '= Flask(' in line:
                        app = line.split('= Flask(')[0].strip()
                    if '=Flask(' in line:
                        app = line.split('=Flask(')[0].strip()

                    if not app:
                        continue

                    package_path = full.replace(os.getcwd(), '')
                    package_module = package_path.replace(os.sep, '.').split('.', 1)[1].replace('.py', '')
                    app_module = package_module + '.' + app

                    matches.append(app_module)

    return matches
1229066
def files(self, *, bundle: str=None, tags: List[str]=None, version: int=None,
              path: str=None) -> models.File:
        """"""
        query = self.File.query
        if bundle:
            query = (query.join(self.File.version, self.Version.bundle)
                          .filter(self.Bundle.name == bundle))

        if tags:
            # require records to match ALL tags
            query = (
                query.join(self.File.tags)
                .filter(self.Tag.name.in_(tags))
                .group_by(models.File.id)
                .having(func.count(models.Tag.name) == len(tags))
            )

        if version:
            query = query.join(self.File.version).filter(self.Version.id == version)

        if path:
            query = query.filter_by(path=path)

        return query
296260
def _print_dict_files(self, case, target):
        
        if case in self.live and target in self.live[case]:
            lines = []
            data = self.live[case][target]
            skeys = list(sorted(data.keys()))
            for key in skeys:
                props = ", ".join(sorted(data[key].keys()))
                lines.append("'{}': {}".format(key, props))
            return '\n'.join(lines)
        else:
            msg.err("Can't find the result set {} in {}".format(target, case))
522407
def _copy_binder_notebooks(app):
    """"""

    gallery_conf = app.config.sphinx_gallery_conf
    gallery_dirs = gallery_conf.get('gallery_dirs')
    binder_conf = gallery_conf.get('binder')
    notebooks_dir = os.path.join(app.outdir, binder_conf.get('notebooks_dir'))
    shutil.rmtree(notebooks_dir, ignore_errors=True)
    os.makedirs(notebooks_dir)

    if not isinstance(gallery_dirs, (list, tuple)):
        gallery_dirs = [gallery_dirs]

    iterator = sphinx_compatibility.status_iterator(
        gallery_dirs, 'copying binder notebooks...', length=len(gallery_dirs))

    for i_folder in iterator:
        shutil.copytree(os.path.join(app.srcdir, i_folder),
                        os.path.join(notebooks_dir, i_folder),
                        ignore=_remove_ipynb_files)
1136942
def dump_model_data(request, app_label, model_label):
    
    return dump_to_response(request, '%s.%s' % (app_label, model_label),
                            [], '-'.join((app_label, model_label)))