Restituisce una lista di id di tag comuni al model corrente e al model
        o queryset passati come argomento
773114
def _taglist(self, other_model=None, queryset=None):
        
        from taggit.models import TaggedItem
        filter = None
        if queryset is not None:
            filter = set()
            for item in queryset.all():
                filter.update(item.tags.all())
            filter = set([tag.id for tag in filter])
        elif other_model is not None:
            filter = set(TaggedItem.objects.filter(
                content_type__model=other_model.__name__.lower()
            ).values_list('tag_id', flat=True))
        tags = set(TaggedItem.objects.filter(
            content_type__model=self.model.__name__.lower()
        ).values_list('tag_id', flat=True))
        if filter is not None:
            tags = tags.intersection(filter)
        return list(tags)
505306
def ajax_forms options={}
      default_options = {
          quick_new_partial: nil,
          quick_create_partial: nil,
          model: config.resource_class,
          search_fields: ['name'],
          display_column: 'name',
          search_condition: 'cont_all'
      }
      options = default_options.deep_merge(options)

      @ajax_form_enabled = true

      # XXX: usar reflect on association para definir los collection_actions en los modelos
      # relacionados donde se quieren buscar los datos
      # Por ejemplo, si product belongs_to invoice_line, y quiero crear dinámicamente un producto
      # solo hace falta definir en invoice_line que se quiere usar ajax_forms. Automáticamente
      # se crean los collection_actions en products para realizar las búsquedas.

      #todo: Posibilidad de especificar los atributos a devolver en el método find. Si no se especifica nada devolver todas las columnas
      collection_action :find, :method => :get do
        model = resource_class
        search_term = params[:q]
        groupping_condition = params[:q][:g] rescue nil
        ransack_search = options[:search_fields].join('_or_').concat('_').concat(options[:search_condition]).to_sym

        if params[:q_id].present?
          params[:q]={:id_equals => params[:q_id]} #selected element
        elsif groupping_condition.nil?
          params[:q]={
            :g=>{
              "0"=>{ransack_search=>search_term.split(" ")}
            }
          }

          # if this search depends on the result of another select box
          # we need to add the filter to the existing ransack options
          if params[:dependentSelect] and !params[:dependentSelect][:selectorValue].empty?
            params[:q][:g]["1"]={params[:dependentSelect][:ransackFilter].to_sym=>params[:dependentSelect][:selectorValue]}
          end
        end

        q = model.search(params[:q])
        @items = q.result.order('id asc', 'name asc').limit(100).map { |item| {:id => item.id, :text => item.to_s} }
        respond_to do |format|
          format.json { render :json => @items }
        end
      end

      collection_action :quick_new, :method => :get do
        @model = resource_class.new(:name => Base64.decode64(params[:name]))
        options[:selector]=params[:selectorid]
        #crea una variable de instancia con el nombre del recurso para compatibilidad con partials normales
        instance_variable_set("@#{resource_instance_name.to_s}", @model)
        @remote = true
        @form_url = eval "quick_create_admin_#{resource_collection_name.to_s}_path"

        @id="#{Time.now.to_i.to_s}_#{resource_instance_name.to_s}"
        options[:id]=@id

        #todo: tiene que renderizar un formulario por defecto
        if options.fetch(:quick_new_partial).nil?
          render :nothing => true
        else
          render partial: options.fetch(:quick_new_partial), layout: 'application'
        end
      end

      collection_action :quick_create, :method => :post do
        @model = resource_class.new(params[resource_instance_name])
        @selector=options[:selector]
        @model.save
        @id=options[:id]
        render file: 'quick_response', layout: false
      end
    end
401823
def get_tags(model, trigger_id):
    
    # get the data of this trigger
    trigger = model.objects.get(trigger_id=trigger_id)

    tags = ''
    if trigger.tag:
        # is there several tag ?
        tags = ["#" + tag.strip() for tag in trigger.tag.split(',')]
        tags = str(','.join(tags)) if isinstance(tags, list) else tags
        tags = ' ' + tags
    return tags
315904
def __get_tag_ids(self, tags):
        """"""

        db_tags = self.fetchall("select * from tags where name in (%s)"
                                            % ",".join(["?"] * len(tags)), tags) # bit of magic here - using sqlites bind variables

        changes = False

        # check if any of tags needs resurrection
        set_complete = [str(tag["id"]) for tag in db_tags if tag["autocomplete"] == "false"]
        if set_complete:
            changes = True
            self.execute("update tags set autocomplete='true' where id in (%s)" % ", ".join(set_complete))


        found_tags = [tag["name"] for tag in db_tags]

        add = set(tags) - set(found_tags)
        if add:
            statement = "insert into tags(name) values(?)"

            self.execute([statement] * len(add), [(tag,) for tag in add])

            return self.__get_tag_ids(tags)[0], True # all done, recurse
        else:
            return db_tags, changes
966112
function doQuery(options) {
            return models.Tag.findPage(options)
                .then(({data, meta}) => {
                    return {
                        tags: data.map(model => urlsForTag(model.id, model.toJSON(options), options)),
                        meta: meta
                    };
                });
        }
1028209
def _get_content_type_queryset(models_list):
    
    content_type_ids = {c.id for c in ContentType.objects.get_for_models(*models_list).values()}
    return ContentType.objects.filter(id__in=content_type_ids)
604211
def verifica_conteudos
      identifica_modelo
      File.open(@arquivo_texto, 'r') {|f| @texto = f.read} if @texto.nil?

      begin
        File.open(@arquivo_resumo, 'r') {|f| @resumo = f.read } if @resumo.nil?
      rescue Errno::ENOENT => e
        raise Formatafacil::ArquivoNaoEncontradoError, "Não possível encontrar o arquivo 'resumo.md'. Crie o arquivo com o nome apropriado e tente novamente."
      end
      begin
        File.open(@arquivo_abstract, 'r') { |f| @abstract = f.read } if @abstract.nil?
      rescue Errno::ENOENT => e
        raise Formatafacil::ArquivoNaoEncontradoError, "Não possível encontrar o arquivo 'abstract.md'. Crie o arquivo com o nome apropriado e tente novamente."
      end
      begin
        File.open(@arquivo_bibliografia, 'r') {|f| @bibliografia = f.read} if @bibliografia.nil?
      rescue Errno::ENOENT
        raise Formatafacil::ArquivoNaoEncontradoError, "Não possível encontrar o arquivo 'bibliografia.md'. Crie o arquivo com o nome apropriado e tente novamente."
      end
      begin
        if @metadados.empty? then
          File.open(@arquivo_metadados, 'r') do |f|
            metadados_lido = YAML.load(f.read)
            @metadados = if metadados_lido.nil? or !metadados_lido then {} else metadados_lido end
          end
        end
      rescue Errno::ENOENT
        raise Formatafacil::ArquivoNaoEncontradoError, "Não possível encontrar o arquivo '#{@arquivo_metadados}'. Crie o arquivo com o nome apropriado e tente novamente."
      rescue Psych::SyntaxError
        raise Formatafacil::MetadadosError, "Erro no arquivo 'metadados.yaml'. Atualize o arquivo e tente novamente."
      end
    end
760417
function(model, options) {
            var item, tag;

            // Define options
            options = _.defaults(options || {}, {
                silent: false,
                render: true,
                at: _.size(this.items),
            });

            if (this.items[model.id] != null) {
                this.removeModel(model);
            }

            item = new this.Item({
                "model": model,
                "list": this,
                "collection": this.collection
            }, this);
            this.listenTo(model, "set", function() {
                item.update();
                this.applyFilter(item);
            });
            this.listenTo(model, "id", function(newId, oldId) {
                this.items[newId] = this.items[oldId];
                delete this.items[oldId];
            });

            item.update();
            tag = this.Item.prototype.tagName;
            if (this.Item.prototype.className) tag = tag+"."+this.Item.prototype.className.split(" ")[0];

            if (options.at > 0) {
                this.$("> "+tag).eq(options.at-1).after(item.$el);
            } else {
                this.$el.prepend(item.$el);
            }
            this.items[model.id] = item;

            this.applyFilter(item);

            if (!options.silent) this.trigger("add", model);
            if (options.render) this.update();

            return this;
        }
686701
def get_queryset(self):
        ''''''
        if self.action == 'list':
            archived = get_true_false_both(
                self.request.query_params, 'archived', 'false')
            if archived == 'true':
                return self.queryset.filter(archived=True)
            if archived == 'false':
                return self.queryset.filter(archived=False)
        return self.queryset
1054999
async def list(cls, user_id: Union[int, str] = None,
                   is_active: bool = None,
                   fields: Iterable[str] = None) -> Sequence[dict]:
        '''
        
        '''
        if fields is None:
            fields = (
                'access_key', 'secret_key',
                'is_active', 'is_admin',
            )
        if user_id is None:
            q = 'query($is_active: Boolean) {' \
                '  keypairs(is_active: $is_active) {' \
                '    $fields' \
                '  }' \
                '}'
        else:
            uid_type = 'Int!' if isinstance(user_id, int) else 'String!'
            q = 'query($user_id: {0}, $is_active: Boolean) {{'.format(uid_type) + \
                '  keypairs(user_id: $user_id, is_active: $is_active) {' \
                '    $fields' \
                '  }' \
                '}'
        q = q.replace('$fields', ' '.join(fields))
        variables = {
            'is_active': is_active,
        }
        if user_id is not None:
            variables['user_id'] = user_id
        rqst = Request(cls.session, 'POST', '/admin/graphql')
        rqst.set_json({
            'query': q,
            'variables': variables,
        })
        async with rqst.fetch() as resp:
            data = await resp.json()
            return data['keypairs']
875694
def marvcli_query(ctx, list_tags, collections, discarded, outdated, path, tags, null):
    
    if not any([collections, discarded, list_tags, outdated, path, tags]):
        click.echo(ctx.get_help())
        ctx.exit(1)

    sep = '\x00' if null else '\n'

    site = create_app().site

    if '*' in collections:
        collections = None
    else:
        for col in collections:
            if col not in site.collections:
                ctx.fail('Unknown collection: {}'.format(col))

    if list_tags:
        tags = site.listtags(collections)
        if tags:
            click.echo(sep.join(tags), nl=not null)
        else:
            click.echo('no tags', err=True)
        return

    setids = site.query(collections, discarded, outdated, path, tags)
    if setids:
        sep = '\x00' if null else '\n'
        click.echo(sep.join(setids), nl=not null)
156565
function modelQuery(options) {
            return models.Post.findPage(options)
                .then(({data, meta}) => {
                    return {
                        posts: data.map(model => urlsForPost(model.id, model.toJSON(options), options)),
                        meta: meta
                    };
                });
        }
571197
def list_tags(self, pattern=None):
        
        request_url = "{}tags".format(self.create_basic_url())

        params = None
        if pattern:
            params = {'pattern': pattern}

        return_value = self._call_api(request_url, params=params)
        return return_value['tags']
652518
def _list(self, uri, obj_class=None, list_all=False):
        
        resp, resp_body = self._retry_get(uri)
        if obj_class is None:
            obj_class = self.resource_class

        data = resp_body[self.plural_response_key]
        ret = [obj_class(self, res, loaded=False)
                for res in data if res]
        self._reset_paging("domain", resp_body)
        if list_all:
            dom_paging = self._paging.get("domain", {})
            while dom_paging.get("next_uri"):
                next_uri = dom_paging.get("next_uri")
                ret.extend(self._list(uri=next_uri, obj_class=obj_class,
                        list_all=False))
        return ret
1133721
def tag_users(self, tag_id, open_id_list):
        
        return self.post(
            url="https://api.weixin.qq.com/cgi-bin/tags/members/batchtagging",
            data={
                "openid_list": open_id_list,
                "tagid": tag_id
            }
        )
748963
def tag(self, tokens):
        """"""
        # Lazy load model first time we tag
        if not self._loaded_model:
            self.load(self.model)
        features = [self._get_features(tokens, i) for i in range(len(tokens))]
        labels = self._tagger.tag(features)
        tagged_sent = list(zip(tokens, labels))
        return tagged_sent
1058442
def _list_items(action, key, profile=None, subdomain=None, api_key=None):
    '''
    
    '''
    items = _query(
        profile=profile,
        subdomain=subdomain,
        api_key=api_key,
        action=action
    )
    ret = {}
    for item in items[action]:
        ret[item[key]] = item
    return ret