Creates the appropriate python user relation classes from tables in the schema and places them
        in the context.
        :param context: alternative context to place the missing classes into, e.g. locals()
547450
def spawn_missing_classes(self, context=None):
        
        if context is None:
            if self.context is not None:
                context = self.context
            else:
                # if context is missing, use the calling namespace
                frame = inspect.currentframe().f_back
                context = frame.f_locals
                del frame
        tables = [
            row[0] for row in self.connection.query('SHOW TABLES in `%s`' % self.database)
            if lookup_class_name('`{db}`.`{tab}`'.format(db=self.database, tab=row[0]), context, 0) is None]
        master_classes = (Lookup, Manual, Imported, Computed)
        part_tables = []
        for table_name in tables:
            class_name = to_camel_case(table_name)
            if class_name not in context:
                try:
                    cls = next(cls for cls in master_classes if re.fullmatch(cls.tier_regexp, table_name))
                except StopIteration:
                    if re.fullmatch(Part.tier_regexp, table_name):
                        part_tables.append(table_name)
                else:
                    # declare and decorate master relation classes
                    context[class_name] = self(type(class_name, (cls,), dict()))

        # attach parts to masters
        for table_name in part_tables:
            groups = re.fullmatch(Part.tier_regexp, table_name).groupdict()
            class_name = to_camel_case(groups['part'])
            try:
                master_class = context[to_camel_case(groups['master'])]
            except KeyError:
                raise DataJointError('The table %s does not follow DataJoint naming conventions' % table_name)
            part_class = type(class_name, (Part,), dict(definition=...))
            part_class._master = master_class
            self.process_relation_class(part_class, context=context, assert_declared=True)
            setattr(master_class, class_name, part_class)
258049
protected static function create_level_instances() {
        global $DB;

        $sql = "SELECT ".CONTEXT_COURSECAT.", cc.id
                  FROM {course_categories} cc
                 WHERE NOT EXISTS (SELECT 'x'
                                     FROM {context} cx
                                    WHERE cc.id = cx.instanceid AND cx.contextlevel=".CONTEXT_COURSECAT.")";
        $contextdata = $DB->get_recordset_sql($sql);
        foreach ($contextdata as $context) {
            context::insert_context_record(CONTEXT_COURSECAT, $context->id, null);
        }
        $contextdata->close();
    }
1238265
def update_relations(context, namespace_separator=':'):
    """"""
    # Add any relation data prefixed with the relation type.
    relation_type = charmhelpers.core.hookenv.relation_type()
    relations = []
    context['current_relation'] = {}
    if relation_type is not None:
        relation_data = charmhelpers.core.hookenv.relation_get()
        context['current_relation'] = relation_data
        # Deprecated: the following use of relation data as keys
        # directly in the context will be removed.
        relation_data = dict(
            ("{relation_type}{namespace_separator}{key}".format(
                relation_type=relation_type,
                key=key,
                namespace_separator=namespace_separator), val)
            for key, val in relation_data.items())
        relation_data = dict_keys_without_hyphens(relation_data)
        context.update(relation_data)
        relations = charmhelpers.core.hookenv.relations_of_type(relation_type)
        relations = [dict_keys_without_hyphens(rel) for rel in relations]

    context['relations_full'] = charmhelpers.core.hookenv.relations()

    # the hookenv.relations() data structure is effectively unusable in
    # templates and other contexts when trying to access relation data other
    # than the current relation. So provide a more useful structure that works
    # with any hook.
    local_unit = charmhelpers.core.hookenv.local_unit()
    relations = {}
    for rname, rids in context['relations_full'].items():
        relations[rname] = []
        for rid, rdata in rids.items():
            data = rdata.copy()
            if local_unit in rdata:
                data.pop(local_unit)
            for unit_name, rel_data in data.items():
                new_data = {'__relid__': rid, '__unit__': unit_name}
                new_data.update(rel_data)
                relations[rname].append(new_data)
    context['relations'] = relations
1188934
def init_with_context(self, context):
        
        super(CmsAppIconList, self).init_with_context(context)
        apps = self.children

        cms_apps = [a for a in apps if is_cms_app(a['name'])]
        non_cms_apps = [a for a in apps if a not in cms_apps]

        if cms_apps:
            # Group the models of all CMS apps in one group.
            cms_models = []
            for app in cms_apps:
                cms_models += app['models']

            sort_cms_models(cms_models)
            single_cms_app = {'name': "Modules", 'title': "Modules", 'url': "", 'models': cms_models}

            # Put remaining groups after the first CMS group.
            self.children = [single_cms_app] + non_cms_apps
967516
def extend_relations(self, data, kind):
        
        # 'data' is a generator object. It can throw an exception while being
        # consumed. This could happen if the user has launched the app without
        # specifying a database name. This exception must be handled to prevent
        # crashing.
        try:
            data = [self.escaped_names(d) for d in data]
        except Exception:
            data = []

        # dbmetadata['tables'][$schema_name][$table_name] should be a list of
        # column names. Default to an asterisk
        metadata = self.dbmetadata[kind]
        for relname in data:
            try:
                metadata[self.dbname][relname[0]] = ['*']
            except KeyError:
                _logger.error('%r %r listed in unrecognized schema %r',
                              kind, relname[0], self.dbname)
            self.all_completions.add(relname[0])
1163961
def _build_basic_context(self):
        
        # printDebug(str(self.ontospy_graph.toplayer_classes))
        topclasses = self.ontospy_graph.toplayer_classes[:]
        if len(topclasses) < 3:  # massage the toplayer!
            for topclass in self.ontospy_graph.toplayer_classes:
                for child in topclass.children():
                    if child not in topclasses: topclasses.append(child)

        if not self.static_url:
            self.static_url = "static/"  # default

        context_data = {
            "STATIC_URL": self.static_url,
            "ontodocs_version": VERSION,
            "ontospy_graph": self.ontospy_graph,
            "topclasses": topclasses,
            "docs_title": self.title,
            "namespaces": self.ontospy_graph.namespaces,
            "stats": self.ontospy_graph.stats(),
            "sources": self.ontospy_graph.sources,
            "ontologies": self.ontospy_graph.all_ontologies,
            "classes": self.ontospy_graph.all_classes,
            "properties": self.ontospy_graph.all_properties,
            "objproperties": self.ontospy_graph.all_properties_object,
            "dataproperties": self.ontospy_graph.all_properties_datatype,
            "annotationproperties":
            self.ontospy_graph.all_properties_annotation,
            "skosConcepts": self.ontospy_graph.all_skos_concepts,
            "instances": []
        }

        return context_data
932642
def init_with_context(self, context):
        
        super(AppIconList, self).init_with_context(context)
        apps = self.children

        # Standard model only has a title, change_url and add_url.
        # Restore the app_name and name, so icons can be matched.
        for app in apps:
            app_name = self._get_app_name(app)
            app['name'] = app_name

            for model in app['models']:
                try:
                    model_name = self._get_model_name(model)
                    model['name'] = model_name
                    model['icon'] = self.get_icon_for_model(app_name, model_name) or appsettings.FLUENT_DASHBOARD_DEFAULT_ICON
                except ValueError:
                    model['icon'] = appsettings.FLUENT_DASHBOARD_DEFAULT_ICON

                # Automatically add STATIC_URL before relative icon paths.
                model['icon'] = self.get_icon_url(model['icon'])
                model['app_name'] = app_name
613823
def describe(self, context=None, printout=True):
        
        if context is None:
            frame = inspect.currentframe().f_back
            context = dict(frame.f_globals, **frame.f_locals)
            del frame
        if self.full_table_name not in self.connection.dependencies:
            self.connection.dependencies.load()
        parents = self.parents()
        in_key = True
        definition = ('# ' + self.heading.table_info['comment'] + '\n'
                      if self.heading.table_info['comment'] else '')
        attributes_thus_far = set()
        attributes_declared = set()
        indexes = self.heading.indexes.copy()
        for attr in self.heading.attributes.values():
            if in_key and not attr.in_key:
                definition += '---\n'
                in_key = False
            attributes_thus_far.add(attr.name)
            do_include = True
            for parent_name, fk_props in list(parents.items()):  # need list() to force a copy
                if attr.name in fk_props['attr_map']:
                    do_include = False
                    if attributes_thus_far.issuperset(fk_props['attr_map']):
                        parents.pop(parent_name)
                        # foreign key properties
                        try:
                            index_props = indexes.pop(tuple(fk_props['attr_map']))
                        except KeyError:
                            index_props = ''
                        else:
                            index_props = [k for k, v in index_props.items() if v]
                            index_props = ' [{}]'.format(', '.join(index_props)) if index_props else ''

                        if not parent_name.isdigit():
                            # simple foreign key
                            definition += '->{props} {class_name}\n'.format(
                                props=index_props,
                                class_name=lookup_class_name(parent_name, context) or parent_name)
                        else:
                            # projected foreign key
                            parent_name = list(self.connection.dependencies.in_edges(parent_name))[0][0]
                            lst = [(attr, ref) for attr, ref in fk_props['attr_map'].items() if ref != attr]
                            definition += '->{props} {class_name}.proj({proj_list})\n'.format(
                                attr_list=', '.join(r[0] for r in lst),
                                props=index_props,
                                class_name=lookup_class_name(parent_name, context) or parent_name,
                                proj_list=','.join('{}="{}"'.format(a,b) for a, b in lst))
                            attributes_declared.update(fk_props['attr_map'])
            if do_include:
                attributes_declared.add(attr.name)
                name = attr.name.lstrip('_')  # for external
                definition += '%-20s : %-28s %s\n' % (
                    name if attr.default is None else '%s=%s' % (name, attr.default),
                    '%s%s' % (attr.type, ' auto_increment' if attr.autoincrement else ''),
                    '# ' + attr.comment if attr.comment else '')
        # add remaining indexes
        for k, v in indexes.items():
            definition += '{unique}INDEX ({attrs})\n'.format(
                unique='UNIQUE ' if v['unique'] else '',
                attrs=', '.join(k))
        if printout:
            print(definition)
        return definition
126169
def load_api_context(cls, api_context):
        

        cls._api_context = api_context
        cls._user_context = UserContext(api_context.session_context.user_id)
        cls._user_context.init_main_monetary_account()
620035
def generate_endpoint_classes(db, generate_pks=False):
    """"""
    seen_classes = set()
    for cls in current_app.class_references.values():
        seen_classes.add(cls.__tablename__)
    with app.app_context():
        db.metadata.reflect(bind=db.engine)
        for name, table in db.metadata.tables.items():
            if not name in seen_classes:
                seen_classes.add(name)
                if not table.primary_key and generate_pks:
                    cls = add_pk_if_required(db, table, name)
                else:
                    cls = type(
                        str(name),
                        (sandman_model, db.Model),
                        {'__tablename__': name})
                register(cls)
332172
def init_provider(context)
      providers = Map.authorizer_provider_map model_class
      provider_class = providers[self.class.provider_name]
      provider_class ||= providers.values.find { |klass| klass.available? context }
      provider_class.new context
    end
354360
def getschemas(cls):
        
        members = getmembers(cls, lambda member: isinstance(member, Schema))

        result = OrderedDict()

        for name, member in members:
            result[name] = member

        return result
559975
def init_with_context(self, context):
        
        items = self._visible_models(context['request'])
        for model, perms in items:
            if not (perms['change'] or perms.get('view', False)):
                continue
            title = model._meta.verbose_name_plural
            url = self._get_admin_change_url(model, context)
            item = MenuItem(title=title, url=url)
            self.children.append(item)
251486
def relation(name, options = EMPTY_HASH, &block)
      klass_opts = { adapter: default_adapter }.merge(options)
      klass = Relation.build_class(name, klass_opts)
      klass.schema_opts(dataset: name, relation: name)
      klass.class_eval(&block) if block
      register_relation(klass)
      klass
    end
336974
def from_name(cls, relation_name, conversations=None):
        
        if relation_name is None:
            return None
        relation_class = cls._cache.get(relation_name)
        if relation_class:
            return relation_class(relation_name, conversations)
        role, interface = hookenv.relation_to_role_and_interface(relation_name)
        if role and interface:
            relation_class = cls._find_impl(role, interface)
            if relation_class:
                cls._cache[relation_name] = relation_class
                return relation_class(relation_name, conversations)
        return None
306973
def _use(cls, ec):
        
        # class ConnectModel(cls):
        #     pass
        ConnectModel = type(cls.__name__, (cls,), {})

        ConnectModel.tablename = cls.tablename
        ConnectModel._base_class = cls
        if isinstance(ec, (str, unicode)):
            ConnectModel._engine_name = ec
        elif isinstance(ec, Session):
            ConnectModel._engine_name = ec.engine_name
            ConnectModel._connection = ec
        return ConnectModel
1296405
def setup_fixtures(self, context):
        
        if getattr(context, 'fixtures', None):
            context.test.fixtures = copy(context.fixtures)

        if getattr(context, 'reset_sequences', None):
            context.test.reset_sequences = context.reset_sequences

        if getattr(context, 'multi_db', None):
            context.test.__class__.multi_db = context.multi_db

        if hasattr(context, 'scenario'):
            load_registered_fixtures(context)