text:
import json

from django.shortcuts import render, get_object_or_404
from django.conf import settings
from kobo.django.views.generic import DetailView, SearchView
from rest_framework.reverse import reverse
from rest_framework import viewsets, mixins, status
from rest_framework.response import Response
from django.http import Http404
from . import filters
from . import signals
from . import models
from .forms import (ReleaseSearchForm, BaseProductSearchForm,
                    ProductSearchForm, ProductVersionSearchForm)
from .models import ProductVersion, Release, BaseProduct, Variant, Product
from .serializers import (ProductSerializer, ProductVersionSerializer,
                          ReleaseSerializer, BaseProductSerializer,
                          ReleaseTypeSerializer, ReleaseVariantSerializer,
                          CPESerializer, ReleaseVariantCPESerializer,
                          VariantTypeSerializer, ReleaseGroupSerializer)
from pdc.apps.compose import models as compose_models
from pdc.apps.repository import models as repo_models
from pdc.apps.common.constants import PUT_OPTIONAL_PARAM_WARNING
from pdc.apps.common.viewsets import (ChangeSetModelMixin,
                                      ChangeSetCreateModelMixin,
                                      ChangeSetUpdateModelMixin,
                                      MultiLookupFieldMixin,
                                      StrictQueryParamMixin,
                                      ConditionalProcessingMixin,
                                      PDCModelViewSet,
                                      NotificationMixin)
from pdc.apps.auth.permissions import APIPermission
from . import lib

class PageSizeMixin(object):
    def get_context_data(self, **kwargs):
        context = super(PageSizeMixin, self).get_context_data(**kwargs)
        context.update({'page_size': settings.ITEMS_PER_PAGE})
        return context

class ReleaseListView(PageSizeMixin, SearchView):
    form_class = ReleaseSearchForm
    queryset = models.Release.objects.select_related('release_type', 'product_version', 'base_product')
    allow_empty = True
    template_name = "release_list.html"
    context_object_name = "release_list"

class ReleaseDetailView(DetailView):
    queryset = models.Release.objects.select_related('release_type') \
        .prefetch_related('variant_set__variant_type',
                          'variant_set__variantarch_set__arch')
    pk_url_kwarg = "id"
    slug_url_kwarg = "release_id"
    slug_field = "release_id"
    template_name = "release_detail.html"

    def get_context_data(self, **kwargs):
        context = super(ReleaseDetailView, self).get_context_data(**kwargs)
        context['repos'] = repo_models.Repo.objects.filter(
            variant_arch__variant__release=self.object
        ).select_related('variant_arch', 'variant_arch__arch',
                         'content_category', 'content_format', 'repo_family', 'service')
        return context

class BaseProductListView(SearchView):
    form_class = BaseProductSearchForm
    queryset = models.BaseProduct.objects.all()
    allow_empty = True
    template_name = "base_product_list.html"
    context_object_name = "base_product_list"
    paginate_by = settings.ITEMS_PER_PAGE

class BaseProductDetailView(PageSizeMixin, DetailView):
    model = models.BaseProduct
    pk_url_kwarg = "id"
    slug_url_kwarg = "base_product_id"
    slug_field = "base_product_id"
    template_name = "base_product_detail.html"
    context_object_name = "base_product"

    def get_context_data(self, **kwargs):
        context = super(BaseProductDetailView, self).get_context_data(**kwargs)
        context["release_list"] = models.Release.objects.filter(
            base_product=self.object.id
        ).select_related('product_version', 'base_product', 'release_type')
        return context

class ProductListView(PageSizeMixin, SearchView):
    form_class = ProductSearchForm
    queryset = models.Product.objects.prefetch_related('productversion_set__release_set')
    allow_empty = True
    template_name = "product_list.html"
    context_object_name = "product_list"

class ProductDetailView(PageSizeMixin, DetailView):
    queryset = models.Product.objects.prefetch_related('productversion_set__release_set')
    pk_url_kwarg = "id"
    slug_url_kwarg = "short"
    slug_field = "short"
    template_name = "product_detail.html"
    context_object_name = "product"

class ProductViewSet(NotificationMixin,
                     ChangeSetCreateModelMixin,
                     ChangeSetUpdateModelMixin,
                     ConditionalProcessingMixin,
                     StrictQueryParamMixin,
                     mixins.RetrieveModelMixin,
                     mixins.ListModelMixin,
                     viewsets.GenericViewSet):
    """
    API endpoint that allows products to be viewed or edited.

    Each product can have multiple version. Their identifiers are provided in
    the form of `product_version_id` (both in requests and responses).
    """

    queryset = models.Product.objects.prefetch_related('productversion_set')
    serializer_class = ProductSerializer
    lookup_field = 'short'
    filter_class = filters.ProductFilter
    permission_classes = (APIPermission,)
    related_model_classes = (Product, ProductVersion)

    def create(self, request, *args, **kwargs):
        response = super(ProductViewSet, self).create(request, *args, **kwargs)
        if response.status_code == status.HTTP_201_CREATED:
            signals.product_post_update.send(sender=self.object.__class__,
                                             product=self.object,
                                             request=request)
        return response

    def update(self, request, *args, **kwargs):
        """
        Please note that if you update the `short` field, the URL of this
        product will change. The change of short name is *not* propagated to
        product versions nor releases.

        Changing `allowed_push_targets` field also affects this field in
        child product versions, releases and variants.
        """
        obj = self.get_object()
        signals.product_pre_update.send(sender=obj.__class__, product=obj, request=request)
        response = super(ProductViewSet, self).update(request, *args, **kwargs)
        if response.status_code == status.HTTP_200_OK:
            signals.product_post_update.send(sender=obj.__class__, product=self.object, request=request)
        return response

class ProductVersionViewSet(NotificationMixin,
                            ChangeSetCreateModelMixin,
                            ChangeSetUpdateModelMixin,
                            StrictQueryParamMixin,
                            mixins.RetrieveModelMixin,
                            mixins.ListModelMixin,
                            viewsets.GenericViewSet):
    """
    API endpoint that allows product versions to be viewed or edited.

    Product versions always refer to a product by means of a human readable
    `short` name. Similarly releases are referenced by `release_id`. This
    applies to both requests and responses.
    """
    queryset = models.ProductVersion.objects.select_related('product').prefetch_related('release_set')
    serializer_class = ProductVersionSerializer
    lookup_field = 'product_version_id'
    lookup_value_regex = '[^/]+'
    filter_class = filters.ProductVersionFilter
    permission_classes = (APIPermission,)

    doc_create = """
        If `short` is not specified, the short name of associated product will
        be used.
    """

    doc_retrieve = """
        The list of releases is ordered by short and version.
    """

    doc_list = """
        The list of releases for each product version is ordered by short and
        version.
    """

    doc_update = """
        Please note that if you change the `short` or `version` field, the
        `product_version_id` will be modified accordingly, and the URL of the
        object will be changed. All changes are local to the updated model and
        are not propagated to associated releases.

        Changing `allowed_push_targets` field also affects this field in
        child releases and variants.
    """

class ReleaseViewSet(NotificationMixin,
                     ChangeSetCreateModelMixin,
                     ChangeSetUpdateModelMixin,
                     ConditionalProcessingMixin,
                     StrictQueryParamMixin,
                     mixins.ListModelMixin,
                     mixins.RetrieveModelMixin,
                     viewsets.GenericViewSet):
    """
    An API endpoint providing access to releases.

    Each release can reference either a product version or a base product (or
    both). There references are done via human-readable `product_version_id` or
    `base_product_id`. Composes belonging to given release are referenced via
    `compose_id`.

    The list of associated composes includes both composes built for the
    particular release as well as composes linked to it. It is possible to
    distinguish between these cases by retrieving a detail of the compose.
    """
    queryset = models.Release.objects \
                     .select_related('product_version', 'release_type', 'base_product') \
                     .order_by('id')
    serializer_class = ReleaseSerializer
    lookup_field = 'release_id'
    lookup_value_regex = '[^/]+'
    filter_class = filters.ReleaseFilter
    permission_classes = (APIPermission,)
    docstring_macros = PUT_OPTIONAL_PARAM_WARNING
    related_model_classes = (Release, BaseProduct, ProductVersion)

    def filter_queryset(self, qs):
        """
        If the viewset instance has attribute `order_queryset` set to True,
        this method returns a list of releases ordered by version. Otherwise it
        will return an unsorted queryset. (It is not possible to sort
        unconditionally as get_object() will at some point call this method and
        fail unless it receives a QuerySet instance.)
        """
        qs = super(ReleaseViewSet, self).filter_queryset(qs)
        if getattr(self, 'order_queryset', False):
            return sorted(qs, key=models.Release.version_sort_key)
        return qs

    def create(self, request, *args, **kwargs):
        """
        Instead of creating a release through this method, please consider
        using the $LINK:releaseclone-list$ API that will clone an existing
        release with its variants and components.

        *release_type*: $LINK:releasetype-list$
        """
        response = super(ReleaseViewSet, self).create(request, *args, **kwargs)
        if response.status_code == status.HTTP_201_CREATED:
            signals.release_post_update.send(sender=self.object.__class__,
                                             release=self.object,
                                             request=request)
        return response

    doc_retrieve = """
        The list of composes is ordered by their date, type and respin (even
        though those fields are not directly visible here).
    """

    def list(self, request, *args, **kwargs):
        """
        The list of composes for each release is ordered by their date, type,
        and respin (even though those fields are not directly visible here).

        The releases themselves are ordered by short and version.
        """
        self.order_queryset = True
        if 'ordering' in request.query_params.keys():
            self.order_queryset = False
        return super(ReleaseViewSet, self).list(request, *args, **kwargs)

    def update(self, request, *args, **kwargs):
        """
        %(PUT_OPTIONAL_PARAM_WARNING)s

        This applies also to Bugzilla and DistGit mapping: if it is not specified,
        it will be cleared.

        Please note that if you change the `short`, `version`, `release_type`
        or `base_product` fields, the `release_id` will be updated and the URL
        of this release will change.

        Changing `allowed_push_targets` field also affects this field in
        child variants.
        """
        object = self.get_object()
        signals.release_pre_update.send(sender=object.__class__, release=object, request=request)
        response = super(ReleaseViewSet, self).update(request, *args, **kwargs)
        if response.status_code == status.HTTP_200_OK:
            signals.release_post_update.send(sender=object.__class__,
                                             release=self.object,
                                             request=request)
        return response

class ReleaseImportView(StrictQueryParamMixin, viewsets.GenericViewSet):
    queryset = models.Release.objects.none()   # Required for permissions
    permission_classes = (APIPermission,)

    def create(self, request):
        """
        Import release including variants and architectures from composeinfo
        json file.

        The input to this call is a compose info file in JSON format. The
        imported file will be parsed and required objects created in database.

        The created objects are *BaseProduct*, *Product*, *ProductVersion*,
        *Release* and its *Variant.Arch* mapping. Note that despite the input
        being a composeinfo file, no Compose object will be ever created by
        this call.

        If the created objects already exist, nothing is done with them.
        Therefore this call is idempotent and uploading the same composeinfo
        data twice is safe.

        __Method__: POST

        __URL__: $LINK:releaseimportcomposeinfo-list$

        __Data__: composeinfo data as saved in `composeinfo.json` file (the
        formatting of the file is not important for PDC, and it is possible to
        significantly minimize size of the file by removing indentation)

        __Response__:
            {
                "url": string
            }

        __Example__:

            $ curl -H 'Content-Type: application/json' -X POST -d @/path/to/composeinfo.json \\
                "$URL:releaseimportcomposeinfo-list$"
        """
        if not request.data:
            return Response(status=status.HTTP_400_BAD_REQUEST, data={'detail': 'Missing composeinfo'})
        release_obj = lib.release__import_from_composeinfo(request, request.data)
        url = reverse('release-detail', args=[release_obj])
        return Response({'url': url}, status=status.HTTP_201_CREATED)

class BaseProductViewSet(NotificationMixin,
                         ChangeSetCreateModelMixin,
                         ChangeSetUpdateModelMixin,
                         ConditionalProcessingMixin,
                         StrictQueryParamMixin,
                         mixins.ListModelMixin,
                         mixins.RetrieveModelMixin,
                         viewsets.GenericViewSet):
    """
    An API endpoint providing access to base products.
    """
    queryset = models.BaseProduct.objects.all()
    serializer_class = BaseProductSerializer
    permission_classes = (APIPermission,)
    lookup_field = 'base_product_id'
    lookup_value_regex = '[^/]+'
    filter_class = filters.BaseProductFilter

class ProductVersionListView(PageSizeMixin, SearchView):
    form_class = ProductVersionSearchForm
    queryset = models.ProductVersion.objects.prefetch_related('release_set')
    allow_empty = True
    template_name = "product_version_list.html"
    context_object_name = "product_version_list"

class ProductVersionDetailView(PageSizeMixin, DetailView):
    queryset = models.ProductVersion.objects.prefetch_related('release_set__release_type')
    pk_url_kwarg = "id"
    slug_url_kwarg = "product_version_id"
    slug_field = "product_version_id"
    template_name = "product_version_detail.html"
    context_object_name = "product_version"

def product_pages(request):
    return render(request, "product_pages.html", {})

class ReleaseCloneViewSet(StrictQueryParamMixin, viewsets.GenericViewSet):
    permission_classes = (APIPermission,)
    queryset = models.Release.objects.none()   # Required for permissions

    def create(self, request):
        """
        Clone an existing release identified by `old_release_id`. Currently the
        release, its variants and arches will be cloned. Also, all release
        components associated with the release will be cloned.

        __Method__: POST

        __URL__: $LINK:releaseclone-list$

        __Data__:

            {
                "old_release_id":               string,
                "short":                        string,     # optional
                "version":                      string,     # optional
                "name":                         string,     # optional
                "release_type":                 string,     # optional
                "base_product":                 string,     # optional
                "active":                       bool,       # optional
                "product_version":              string,     # optional
                "dist_git": {
                    "branch":                   string
                },                                          # optional
                "bugzilla": {
                    "product":                  string
                },                                          # optional
                "component_dist_git_branch":    string,     # optional
                "include_inactive":             bool,       # optional
                "include_trees":                [string],   # optional
                "integrated_with:               string      # optional
            }

        The changed attributes must yield a different release_id, therefore
        change in at least one of `short`, `version`, `base_product` or
        `release_type` is required.

        If `component_dist_git_branch` is present, it will be set for all
        release components under the newly created release. If missing, release
        components will be cloned without changes.

        If `include_inactive` is False, the inactive release_components belong to
        the old release won't be cloned to new release.
        Default it will clone all release_components to new release.

        If `include_tree` is specified, it should contain a list of
        Variant.Arch pairs that should be cloned. If not given, all trees will
        be cloned. If the list is empty, no trees will be cloned.
        """
        data = request.data
        if 'old_release_id' not in data:
            return Response({'__all__': 'Missing old_release_id'},
                            status=status.HTTP_400_BAD_REQUEST)
        old_release_id = data.pop('old_release_id')
        old_release = get_object_or_404(models.Release, release_id=old_release_id)

        old_data = ReleaseViewSet.serializer_class(instance=old_release).data

        for (field_name, field) in ReleaseViewSet.serializer_class().fields.iteritems():
            if not field.read_only and field_name not in data:
                value = old_data.get(field_name, None)
                if value:
                    data[field_name] = value

        for key in data.keys():
            if data[key] is None:
                data.pop(key)

        serializer = ReleaseViewSet.serializer_class(
            data=data,
            extra_fields=[
                'include_trees',
                'include_inactive',
                'component_dist_git_branch'])
        serializer.is_valid(raise_exception=True)

        new_release = serializer.save()
        request.changeset.add('Release', new_release.pk,
                              'null', json.dumps(new_release.export()))

        signals.release_clone.send(sender=new_release.__class__,
                                   request=request,
                                   original_release=old_release,
                                   release=new_release)

        return Response(serializer.data, status=status.HTTP_201_CREATED)

class ReleaseComponentCloneViewSet(StrictQueryParamMixin, viewsets.GenericViewSet):
    permission_classes = (APIPermission,)
    queryset = models.Release.objects.none()

    def create(self, request):
        """
        Clone all release components, component groups and relationships from one Release
        to another Release, both they are existed.

        __Method__: POST

        __URL__: $LINK:releasecomponentclone-list$

        __Data__:

            {
                "source_release_id":            string,
                "target_release_id":            string
                "component_dist_git_branch":    string,     # optional
                "include_inactive":             bool,       # optional
            }

        __Response__:

            {
            "url": [the link for target release component]
            }

        Please make sure source release contains components,
        cloning source release without components doesn't make much sense.

        If `component_dist_git_branch` is present, the value will be set for all
        release components under the target release. If missing, release
        components will be cloned without changes.

        If `include_inactive` is False, the inactive release_components belong to
        the old release won't be cloned to target release.
        Default it will clone all release_components to target release.
        """
        data = request.data
        if 'source_release_id' not in data:
            return Response({'detail': 'Missing source_release_id'},
                            status=status.HTTP_400_BAD_REQUEST)
        source_release_id = data.pop('source_release_id')
        if 'target_release_id' not in data:
            return Response({'detail': 'Missing target_release_id'},
                            status=status.HTTP_400_BAD_REQUEST)
        target_release_id = data.pop('target_release_id')
        try:
            source_release = get_object_or_404(models.Release, release_id=source_release_id)
        except Http404:
            return Response({'detail': 'Source_release %s does not exist' % source_release_id},
                            status=status.HTTP_404_NOT_FOUND)
        try:
            target_release = get_object_or_404(models.Release, release_id=target_release_id)
        except Http404:
            return Response({'detail': 'Target_release %s does not exist' % target_release_id},
                            status=status.HTTP_404_NOT_FOUND)

        if source_release.releasecomponent_set.count() == 0:
            return Response({'detail': 'there is no component in source release'},
                            status=status.HTTP_400_BAD_REQUEST)
        if not target_release.active:
            return Response({'detail': 'can\'t clone components ' +
                                       'to an inactive target release %s' % target_release_id},
                            status=status.HTTP_400_BAD_REQUEST)
        filter_release = "?release=" + target_release_id
        target_url = reverse(viewname='releasecomponent-list', request=request) + filter_release
        signals.rpc_release_clone_component.send(sender=target_release.__class__,
                                                 request=request,
                                                 original_release=source_release,
                                                 release=target_release)

        return Response({'url': target_url}, status=status.HTTP_201_CREATED)

class ReleaseRPMMappingView(StrictQueryParamMixin, viewsets.GenericViewSet):
    lookup_field = 'package'
    queryset = models.Release.objects.none()   # Required for permissions
    permission_classes = (APIPermission,)
    extra_query_params = ['disable_overrides']

    def retrieve(self, request, **kwargs):
        """
        __URL__: $LINK:releaserpmmapping-detail:release_id:package$

        Returns a JSON representing the RPM mapping of the latest compose for
        given release. There is an optional query parameter
        `?disable_overrides=1` which returns the raw mapping not affected by
        any overrides.

        The latest compose is chosen from the list of composes built for the
        release or linked to it. The RPM mapping of that compose is filtered to
        only include variants and architectures listed for the release. If the
        release has no compose then take an empty dict as compose RPM mapping.

        The used overrides come from the release specified in the URL, not the
        one for which the compose was originally built for.

        Following cases result in response of `404 NOT FOUND`:

         * no release with given id
         * release and compose exists, but there are no RPMs for the package

        __Response__:

            {
                "compose": string,
                "mapping": object
            }

        The `compose` key contains compose id of the compose used to populate
        the mapping. If the release has no compose, 'compose' is null.
        """
        release = get_object_or_404(models.Release, release_id=kwargs['release_id'])
        compose = release.get_latest_compose()
        if compose:
            mapping, _ = compose.get_rpm_mapping(kwargs['package'],
                                                 bool(request.query_params.get('disable_overrides', False)),
                                                 release=release)
            result = mapping.get_pure_dict()
            if result:
                return Response(data={'compose': compose.compose_id, 'mapping': result})
        else:
            mapping = compose_models.ComposeRPMMapping()
            mapping.get_rpm_mapping_only_with_overrides(kwargs['package'],
                                                        bool(request.query_params.get('disable_overrides', False)),
                                                        release=release)
            result = mapping.get_pure_dict()
            if result:
                return Response(data={'compose': None, 'mapping': result})

        # no result
        return Response(status=status.HTTP_404_NOT_FOUND,
                        data={'detail': 'Package %s not present in release %s'
                                        % (kwargs['package'], kwargs['release_id'])})

class ReleaseTypeViewSet(StrictQueryParamMixin,
                         mixins.ListModelMixin,
                         viewsets.GenericViewSet):
    queryset = models.ReleaseType.objects.all()
    serializer_class = ReleaseTypeSerializer
    filter_class = filters.ReleaseTypeFilter
    permission_classes = (APIPermission,)

class ReleaseVariantViewSet(NotificationMixin,
                            ChangeSetModelMixin,
                            ConditionalProcessingMixin,
                            StrictQueryParamMixin,
                            MultiLookupFieldMixin,
                            viewsets.GenericViewSet):
    """
    This end-point provides access to Variants. Each variant is uniquely
    identified by release ID and variant UID. The pair in the form
    `release_id/variant_uid` is used in URL for retrieving, updating or
    deleting a single variant as well as in bulk operations.
    """
    queryset = models.Variant.objects.all()
    serializer_class = ReleaseVariantSerializer
    filter_class = filters.ReleaseVariantFilter
    permission_classes = (APIPermission,)
    lookup_fields = (('release__release_id', r'[^/]+'), ('variant_uid', r'[^/]+'))
    related_model_classes = (Variant, Release)

    doc_create = """
        The required architectures must already be present in PDC.
    """

    doc_update = """
        The specified architectures will be set for this release. Also note
        that if you change the `uid`, the url for this variant will change.

        Changing the architectures may involve deleting some. Note that
        repositories are connected to some Variant.Arch pair and it is not
        possible to remove an arch with any repositories..
    """

    doc_partial_update = """
        If an attribute is not specified, that property of a variant will not
        change. The `arches` key can be used to set architectures associated
        with the variant. The `add_arches` key can list architectures to be
        added to current ones, with `remove_arches` some can be removed.
        While it is possible to combine `add_arches` with `remove_arches`,
        the `arches` attribute must not be combined with any other arch
        manipulation.

        If you try to remove architectures with associated repositories, the
        request will fail to do anything.
    """

    doc_destroy = """
        This call will delete selected variant with all its arches. Please note
        that if there are any repositories filed under this variant, you will
        get an error `409 CONFLICT`.
    """

class CPEViewSet(PDCModelViewSet):
    """
    Common Platform Enumeration (CPE) for linking CPE with variants ($LINK:variantcpe-list$).

    CPE is a standardized method of describing and identifying classes of operating systems.

    Common Vulnerabilities and Exposures (CVE) contain list of affected CPEs.

    For more information about CPE see [cpe.mitre.org](https://cpe.mitre.org/).
    """

    queryset = models.CPE.objects.all()
    serializer_class = CPESerializer
    filter_class = filters.CPEFilter
    permission_classes = (APIPermission,)

class ReleaseVariantCPEViewSet(PDCModelViewSet):
    """
    Links each variant ($LINK:variant-list$) with CPE ($LINK:cpe-list$).
    """

    queryset = models.VariantCPE.objects.all()
    serializer_class = ReleaseVariantCPESerializer
    filter_class = filters.ReleaseVariantCPEFilter
    permission_classes = (APIPermission,)

class VariantTypeViewSet(StrictQueryParamMixin,
                         mixins.ListModelMixin,
                         viewsets.GenericViewSet):
    # TODO: remove this class after next release
    serializer_class = VariantTypeSerializer
    queryset = models.VariantType.objects.all().order_by('id')
    permission_classes = (APIPermission,)

    doc_list = """
        This end-point is deprecated. Use $LINK:releasevarianttype-list$ instead.
    """

class ReleaseVariantTypeViewSet(StrictQueryParamMixin,
                                mixins.ListModelMixin,
                                viewsets.GenericViewSet):
    """
    API endpoint that allows variant_types to be viewed.
    """
    serializer_class = VariantTypeSerializer
    queryset = models.VariantType.objects.all()
    permission_classes = (APIPermission,)

class ReleaseGroupsViewSet(ChangeSetModelMixin,
                           StrictQueryParamMixin,
                           viewsets.GenericViewSet):
    """
    API endpoint that allows release_group_types to be viewed or edited.
    This API endpoint is experimental.
    """

    queryset = models.ReleaseGroup.objects.all()
    serializer_class = ReleaseGroupSerializer
    lookup_field = 'name'
    lookup_value_regex = '[^/]+'
    filter_class = filters.ReleaseGroupFilter
    permission_classes = (APIPermission,)


text:
{-# OPTIONS -Wall #-}
{-# LANGUAGE TupleSections #-}

module Helpers.List where

import qualified Data.List as List

selectPairs :: [a] -> [(a, a)]
selectPairs xs = concat $ zipWith (\i x -> let (before, after) = List.splitAt i xs in map (x,) (before ++ tail after)) [0 ..] xs

redpajama_set_name: RedPajamaGithub


text:
package cryodex.modules;

import javax.swing.JPanel;

import cryodex.Player;

public interface RegistrationPanel {
	public JPanel getPanel();

	public void save(Player player);

	public void load(Player player);

	public void clearFields();

	public void setVisible(boolean isVisible);
}


text:
You need to follow certain steps in order to construct a proper integration with a new version of Rails. First, a quick summary:

1. Install the correct version of the `rails` gem
2. Using that version of `rails`, generate a new app
3. Strip out things we don't need from the app
4. Copy the mailers and templates to the app
5. Apply Roadie options and add Roadie to the Gemfile
6. Add it to `integration_spec.rb`

## Installing Rails

```bash
gem install rails -v x.y.z
```

## Generate Rails app

```bash
rails _x.y.z._ new rails_x_y --skip-javascript --skip-keeps --skip-active-record --skip-test-unit
```

## Clean up the app

```bash
cd rails_x_y
```

The next step is of course specific to each Rails version. One of the easiest methods is to just start by deleting directories you know you have no use for, like `tmp`, `log` and `README.md`.

```bash
rm -rf README.* tmp log db app/controllers app/helpers app/views/layouts public doc
```

You should also go through the initializers under `config` and remove the ones that don't apply; only keep the `development` environment. You should also strip away documentation comments and similar from all the files under `config`. Make them compact and only keep what is needed.

After doing this, run `git add .` and inspect the list of added files. If there's any file there you didn't intend to add, just remove it with `git rm -f`.

## Copy mailer and templates

```bash
cd ..
rm -rf rails_x_y/app/assets rails_x_y/app/views
ln -s ../../shared/pipeline/app/assets rails_x_y/app/assets
ln -s ../../shared/all/app/mailers rails_x_y/app/mailers
ln -s ../../shared/all/app/views rails_x_y/app/views
```

## Apply options and add gem

Open up `config/application.rb` and add the following options:

```ruby
config.roadie.url_options = {host: 'example.app.org'}
```

Then open up the `Gemfile` and add:

```ruby
gem 'roadie-rails', :path => '../../..'
```

## Add to integration_spec.rb

Add the information needed in `spec/integration_spec.rb` and run `setup.sh` before finally running the tests themselves. When everything's good, `git add` everything and commit.


text:
package edu.clemson.resolve.jetbrains.psi;

import com.intellij.psi.PsiElement;

/**
 * A {@link ResCompositeElement} represents an internal node to either a parse tree or a PSI tree. Thus this node is
 * automatically be constructed for any intermediate, non-leaf children.
 */
public interface ResCompositeElement extends PsiElement {
    public boolean shouldGoDeeper();
}


text:
package com.github.felixgail.gplaymusic.model;

import com.github.felixgail.gplaymusic.model.enums.ResultType;
import com.github.felixgail.gplaymusic.model.responses.Result;
import com.github.felixgail.gplaymusic.model.snippets.ArtRef;
import com.github.felixgail.gplaymusic.model.snippets.UserPreference;
import com.google.gson.annotations.Expose;
import java.io.Serializable;
import java.util.List;
import java.util.Optional;

public class PodcastSeries implements Result, Serializable {

  public final static ResultType RESULT_TYPE = ResultType.PODCAST_SERIES;

  @Expose
  private List<ArtRef> art;
  @Expose
  private String author;
  @Expose
  private String continuationToken;
  @Expose
  private String copyright;
  @Expose
  private String description;
  @Expose
  private List<PodcastEpisode> episodes;
  @Expose
  private String explicitType;
  @Expose
  private String link;
  @Expose
  private String seriesId;
  @Expose
  private String title;
  @Expose
  private int totalNumEpisodes;
  @Expose
  private UserPreference userPreferences;

  public Optional<List<ArtRef>> getArt() {
    return Optional.ofNullable(art);
  }

  public String getAuthor() {
    return author;
  }

  public Optional<String> getContinuationToken() {
    return Optional.ofNullable(continuationToken);
  }

  public Optional<String> getCopyright() {
    return Optional.ofNullable(continuationToken);
  }

  public Optional<String> getDescription() {
    return Optional.ofNullable(description);
  }

  public Optional<List<PodcastEpisode>> getEpisodes() {
    return Optional.ofNullable(episodes);
  }

  public String getExplicitType() {
    return explicitType;
  }

  public Optional<String> getLink() {
    return Optional.ofNullable(link);
  }

  public String getSeriesId() {
    return seriesId;
  }

  public String getTitle() {
    return title;
  }

  public int getTotalNumEpisodes() {
    return totalNumEpisodes;
  }

  public Optional<UserPreference> getUserPreferences() {
    return Optional.ofNullable(userPreferences);
  }

  @Override
  public boolean equals(Object o) {
    return (o instanceof PodcastSeries) && ((PodcastSeries) o).getSeriesId().equals(this.seriesId);
  }

  @Override
  public ResultType getResultType() {
    return RESULT_TYPE;
  }
}


text:
namespace leveldb {

class AutoCompactTest {
 public:
  std::string dbname_;
  Cache* tiny_cache_;
  Options options_;
  DB* db_;

  AutoCompactTest() {
    dbname_ = test::TmpDir() + "/autocompact_test";
    tiny_cache_ = NewLRUCache(100);
    options_.block_cache = tiny_cache_;
    DestroyDB(dbname_, options_);
    options_.create_if_missing = true;
    options_.compression = kNoCompression;
    ASSERT_OK(DB::Open(options_, dbname_, &db_));
  }

  ~AutoCompactTest() {
    delete db_;
    DestroyDB(dbname_, Options());
    delete tiny_cache_;
  }

  std::string Key(int i) {
    char buf[100];
    snprintf(buf, sizeof(buf), "key%06d", i);
    return std::string(buf);
  }

  uint64_t Size(const Slice& start, const Slice& limit) {
    Range r(start, limit);
    uint64_t size;
    db_->GetApproximateSizes(&r, 1, &size);
    return size;
  }

  void DoReads(int n);
};

static const int kValueSize = 200 * 1024;
static const int kTotalSize = 100 * 1024 * 1024;
static const int kCount = kTotalSize / kValueSize;

// Read through the first n keys repeatedly and check that they get
// compacted (verified by checking the size of the key space).
void AutoCompactTest::DoReads(int n) {
  std::string value(kValueSize, 'x');
  DBImpl* dbi = reinterpret_cast<DBImpl*>(db_);

  // Fill database
  for (int i = 0; i < kCount; i++) {
    ASSERT_OK(db_->Put(WriteOptions(), Key(i), value));
  }
  ASSERT_OK(dbi->TEST_CompactMemTable());

  // Delete everything
  for (int i = 0; i < kCount; i++) {
    ASSERT_OK(db_->Delete(WriteOptions(), Key(i)));
  }
  ASSERT_OK(dbi->TEST_CompactMemTable());

  // Get initial measurement of the space we will be reading.
  const int64_t initial_size = Size(Key(0), Key(n));
  const int64_t initial_other_size = Size(Key(n), Key(kCount));

  // Read until size drops significantly.
  std::string limit_key = Key(n);
  for (int read = 0; true; read++) {
    ASSERT_LT(read, 100) << "Taking too long to compact";
    Iterator* iter = db_->NewIterator(ReadOptions());
    for (iter->SeekToFirst();
         iter->Valid() && iter->key().ToString() < limit_key;
         iter->Next()) {
      // Drop data
    }
    delete iter;
    // Wait a little bit to allow any triggered compactions to complete.
    Env::Default()->SleepForMicroseconds(1000000);
    uint64_t size = Size(Key(0), Key(n));
    fprintf(stderr, "iter %3d => %7.3f MB [other %7.3f MB]\n",
            read+1, size/1048576.0, Size(Key(n), Key(kCount))/1048576.0);
    if (size <= initial_size/10) {
      break;
    }
  }

  // Verify that the size of the key space not touched by the reads
  // is pretty much unchanged.
  const int64_t final_other_size = Size(Key(n), Key(kCount));
  ASSERT_LE(final_other_size, initial_other_size + 1048576);
  ASSERT_GE(final_other_size, initial_other_size/5 - 1048576);
}

TEST(AutoCompactTest, ReadAll) {
  DoReads(kCount);
}

TEST(AutoCompactTest, ReadHalf) {
  DoReads(kCount/2);
}

}  // namespace leveldb

#ifndef LEVELDB_PLATFORM_WINDOWS
int main(int argc, char** argv) {
  return leveldb::test::RunAllTests();
}
#endif


text:
@interface JsonSerializationTests : XCTestCase

@end

@implementation JsonSerializationTests

- (void)testPerformanceExample {

    NSString *path = [[NSBundle mainBundle] pathForResource:@"multi_complex" ofType:@"json"];
    NSString *json = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
    XCTAssertNotNil(json);

    MGBenchmarkSession *session = [MGBenchmark start:@"demo"];

    NSInteger times = 100;

    [session step:@"start"];
    for (int i = 0; i < times; i++) {
        NSDictionary *dict1 = [json toJsonDictionary];
    }

    [session step:@"JsonReciprocity"];

    for (int i = 0; i < times; i++) {
        NSDictionary *dict2 = [json objectFromJSONString];
    }
    [session step:@"JsonKit"];
    [session total];
    [MGBenchmark finish:@"demo"];

}

@end


text:
copyright:
 years: 2015, 2017

---

{:new_window: target="_blank"}
{:shortdesc: .shortdesc}
{:screen:.screen}
{:codeblock:.codeblock}

# Tagbasierte Benachrichtigungen aktivieren
{: #tag_based_notifications}
Letzte Aktualisierung: 12. April 2017
{: .last-updated}

Tagbasierte Benachrichtigungen haben alle diejenigen Geräte zum Ziel, die einen bestimmten Tag subskribiert haben.

Sie können Tags definieren und anschließend mithilfe der Tags Nachrichten senden und empfangen. Sie müssen zunächst die Tags für die Anwendung erstellen, die Tagsubskriptionen einrichten und anschließend die tagbasierten Benachrichtigungen starten. Zum Senden einer tagbasierten Benachrichtigung mithilfe der [REST-API](https://mobile.{DomainName}/imfpush/){: new_window} müssen Sie sicherstellen, dass bei der Übergabe an die Nachrichtenressource die Tagnamen ('tagNames') angegeben werden.

## Tags verwalten
{: #manage_tags}

Verwenden Sie das {{site.data.keyword.mobilepushshort}}-Dashboard, um Tags für Ihre Anwendung zu erstellen und zu löschen und anschließend tagbasierte Benachrichtigungen zu initiieren. Die tagbasierte Benachrichtigung wird auf Geräten empfangen, von denen Tags subskribiert wurden.

### Tags erstellen
{: #create_tags}

Tagbasierte Benachrichtigungen sind Benachrichtigungen, die all diejenigen Geräte als Ziel haben, die einen
bestimmten Tag subskribiert haben. Jedes Gerät kann beliebig viele Tags subskribieren. Wenn ein Tag gelöscht wird, werden die Informationen diesem Tag zugeordneten Informationen (einschließlich Subskribenten und Geräte) gelöscht. Es ist erforderlich, die automatische Subskription aufzuheben, wenn der Tag nicht mehr vorhanden ist. Es ist keine weitere Aktion von der Clientseite erforderlich.

1. Wählen Sie im {{site.data.keyword.mobilepushshort}}-Dashboard die Registerkarte **Tags** aus.
1. Klicken Sie auf die Schaltfläche **Tag erstellen**.
   1. Geben Sie in das Feld **Name** den Namen für den Tag ein. Beispiel: "Coupons".
   1. Geben Sie in das Feld **Beschreibung** eine Beschreibung für den Tag ein.
   1. Klicken Sie auf **Speichern**.

1. Wählen Sie im Bereich **Code-Snippets** die Plattform für Ihre mobile Anwendung aus.
1. Ändern Sie die Code-Snippets so, dass Fehler verarbeitet werden, und kopieren Sie anschließend die Code-Snippets für jeden Tag in Ihre mobile Anwendung.

### Tags löschen
{: #delete_tags}

1. Wählen Sie auf der Registerkarte **Tag** den Tag aus, den Sie löschen möchten, und klicken Sie auf das Symbol **Löschen**.
1. Klicken Sie auf **OK**.

### Tagbeschreibung bearbeiten
{: #edit_tags}

1. Wählen Sie in der Registerkarte **Tag** den Tag aus, den Sie bearbeiten möchten.
1. Klicken Sie auf das Symbol **Bearbeiten**.
1. Bearbeiten Sie die Tagbeschreibung und klicken Sie anschließend auf die Schaltfläche **Speichern**.

## Tags abrufen
{: #get_tags}

Mit Tags können im Gegensatz zu allgemeinen Rundsendungen, die an alle Anwendungen gesendet werden, Benachrichtigungen auf der Grundlage eines Interessenbereichs zielgruppenspezifisch an Benutzer gesendet werden. Sie können Tags erstellen und verwalten, indem Sie die Registerkarte 'Tag' im {{site.data.keyword.mobilepushshort}}-Dashboard oder REST-APIs verwenden. Sie können Code-Snippets verwenden, um Ihre Tag-Subskriptionen für Ihre mobile Anwendung zu verwalten und abzufragen. Sie können diese Code-Snippets verwenden, um Subskriptionen abzurufen, eine Subskription für einen Tag einzurichten, eine Subskription für einen Tag aufzuheben oder eine Liste der verfügbaren Tags abzurufen. Kopieren Sie diese Code-Snippets in Ihre mobile Anwendung.

### Tags mit Android abrufen
{: #android-get-tags}

Die API **getTags** gibt die Liste mit den verfügbaren Tags zurück, die das Gerät subskribieren kann. Nachdem das Gerät einen bestimmten Tag subskribiert hat, kann es die Push-Benachrichtigungen empfangen, die für diesen Tag gesendet werden.

Kopieren Sie die folgenden Code-Snippets in Ihre mobile Android-Anwendung, um eine Liste der Tags abzurufen, die das Gerät subskribiert hat, und eine Liste der verfügbaren Tags.

Verwenden Sie die API **getTags**, um eine Liste der verfügbaren Tags abzurufen, die das Gerät subskribieren kann.

```
// Get a list of available tags to which the device can subscribe
push.getTags(new MFPPushResponseListener<List<String>>(){
   @Override
   public void onSuccess(List<String> tags){
   updateTextView("Retrieved available tags: " + tags);
   System.out.println("Available tags are: "+tags);
   availableTags = tags;
   subscribeToTag();
  }
  @Override
  public void onFailure(MFPPushException ex){
     updateTextView("Error getting available tags.. " + ex.getMessage());
    }
   })
```
	{: codeblock}

Verwenden Sie die API **getSubscriptions**, um eine Liste der Tags abzurufen, die das Gerät subskribiert hat.

```
// Get a list of tags that to which the device is subscribed.
push.getSubscriptions(new MFPPushResponseListener<List<String>>() {
  @Override
    public void onSuccess(List<String> tags) {
  updateTextView("Retrieved subscriptions : " + tags);
    System.out.println("Subscribed tags are: "+tags);
    subscribedTags = tags;
    subscribeToTag();
    }
  @Override
    public void onFailure(MFPPushException ex) {
       updateTextView("Error getting subscriptions.. " + ex.getMessage());
  }
})
	```
	{: codeblock}

### Tags mit Cordova abrufen
{: #cordova-get-tags}

Kopieren Sie die folgenden Code-Snippets in Ihre mobile Anwendung, um eine Liste der Tags abzurufen, die das Gerät subskribiert hat, und eine Liste der verfügbaren Tags, die das Gerät subskribieren kann.

Rufen Sie einen Array der Tags ab, die zum Subskribieren verfügbar sind.

```
//Get a list of available tags to which the device can subscribe
BMSPush.retrieveAvailableTags(function(tags) {
  alert(tags);
}, failure);
```
	{: codeblock}

```
//Get a list of available tags to which the device is subscribed.
BMSPush.retrieveSubscriptions(function(tags) {
   alert(tags);
}, failure);
```
	{: codeblock}

### Tags mit Swift abrufen
{: #swift-get-tags}

Die API **retrieveAvailableTagsWithCompletionHandler** gibt die Liste mit den verfügbaren Tags zurück, die das Gerät subskribieren kann. Nachdem das Gerät einen bestimmten Tag subskribiert hat, kann es Push-Benachrichtigungen empfangen, die für diesen Tag gesendet werden.

Rufen Sie die Push-Benachrichtigungen auf, um die Subskriptionen für einen Tag abzurufen.

Kopieren Sie die folgenden Code-Snippets in Ihre mobile Swift-Anwendung, um eine Liste der Tags abzurufen, die das Gerät subskribiert hat, und eine Liste der verfügbaren Tags, die das Gerät subskribieren kann.
```
//Get a list of available tags to which the device can subscribe
	push.retrieveAvailableTagsWithCompletionHandler({ (response, statusCode, error) -> Void in
    if error.isEmpty
		{
     print( "Response during retrieve tags : \(response)")
        print( "status code during retrieve tags : \(statusCode)")
    }
    else
	{
    print( "Error during retrieve tags \(error) ")
    Print( "Error during retrieve tags \n  - status code: \(statusCode) \n Error :\(error) \n")
    	}
	}
```
		{: codeblock}

```
//Get a list of available tags to which the device is subscribed
	push.retrieveSubscriptionsWithCompletionHandler { (response, statusCode, error) -> Void in
    if error.isEmpty
		{
    print( "Response during retrieving subscribed tags : \(response?.description)")
        print( "status code during retrieving subscribed tags : \(statusCode)")
    }
    else
	{
    print( "Error during retrieving subscribed tags \(error) ")
    Print( "Error during retrieving subscribed tags \n  - status code: \(statusCode) \n Error :\(error) \n")
        }
	}
```
	{: codeblock}

### Tags in Google Chrome, Safari und Mozilla Firefox abrufen
{: #web-get-tags}

Zum Abrufen der Liste verfügbarer Tags, die von Kunden subskribiert werden können, verwenden Sie folgenden Code.

```
var bmsPush = new BMSPush();
  bmsPush.retrieveAvailableTags(function(response)
	{
  alert(response.response)
    var json = JSON.parse(response.response);
    var tagsA = []
  for (i in json.tags)
	{
    tagsA.push(json.tags[i].name)
    }
   alert(tagsA)
 })
```
	{: codeblock}

### Tags in Google Chrome-Apps und -Erweiterungen abrufen
{: #ext-get-tags}

Zum Abrufen der Liste verfügbarer Tags, die von Kunden subskribiert werden können, verwenden Sie folgenden Code.

```
var bmsPush = new BMSPush();
  bmsPush.retrieveAvailableTags(function(response)
	{
  alert(response.response)
    var json = JSON.parse(response.response);
    var tagsA = []
  for (i in json.tags)
	{
    tagsA.push(json.tags[i].name)
    }
   alert(tagsA)
 })
```
	{: codeblock}

Kopieren Sie das folgende Code-Snippet in Ihre Google Chrome-Apps und Erweiterungen, um eine Liste von Tags abzurufen, die von Kunden subskribiert wurden.

```
var bmsPush = new BMSPush();
  bmsPush.retrieveSubscriptions(function(response)
	{
   alert(response.response)
 })
```
	{: codeblock}

## Tags subskribieren und die Subskription aufheben
{: #Subscribe_tags}

Verwenden Sie die folgenden Code-Snippets, um Ihren Geräten das Abrufen von Subskriptionen und das Subskribieren und das Aufheben der Subskription von Tags zu ermöglichen.

### Tags mit Android subskribieren und die Subskription aufheben
{: #android-subscribe-tags}

Kopieren Sie dieses Code-Snippet und fügen Sie es in Ihre mobile Android-Anwendung ein.

```
push.subscribe(allTags.get(0),
new MFPPushResponseListener<String>() {
  @Override
    public void onFailure(MFPPushException ex) {
  updateTextView("Error subscribing to Tag1.."
           + ex.getMessage());
  }
  @Override
  public void onSuccess(String arg0) {
  updateTextView("Succesfully Subscribed to: "+ arg0);
   unsubscribeFromTags(arg0);
   }
  });
```
	{: codeblock}

```
push.unsubscribe(tag, new MFPPushResponseListener<String>() {
 @Override
 public void onSuccess(String s) {
 updateTextView("Unsubscribing from tag");
   updateTextView("Successfully unsubscribed from tag . "+ tag);
 }
 @Override
 public void onFailure(MFPPushException e) {
 updateTextView("Error while unsubscribing from tags. "+ e.getMessage());
 }
 });
```
	{: codeblock}

### Tags mit Cordova subskribieren und die Subskription aufheben
{: #cordova-subscribe-tags}

Kopieren Sie dieses Code-Snippet und fügen Sie es in Ihre mobile Cordova-Anwendung ein.

```
var tag = "YourTag";
BMSPush.subscribe(tag, success, failure);
BMSPush.unsubscribe(tag, success, failure);
```
	{: codeblock}

### Tags mit Swift subskribieren und die Subskription aufheben
{: #swift-subscribe-tags}

Kopieren Sie dieses Code-Snippet und fügen Sie es in Ihre mobile Swift-Anwendung ein.

Verwenden Sie die API **subscribeToTags** zum Subskribieren eines Tags.

```
push.subscribeToTags(tagsArray: ["MyTag"], completionHandler: { (response, statusCode, error) -> Void in
    if error.isEmpty {
        print("Response when subscribing to tags: \(response?.description)")
        print("Status code when subscribing to tags: \(statusCode)")
    } else {
        print("Error when subscribing to tags: \(error) ")
        print("Error status code when subscribing to tags: \(statusCode)")
    }
})
```
	{: codeblock}

Verwenden Sie die API **unsubscribeFromTags** zum Aufheben der Subskription eines Tags.

```
push.unsubscribeFromTags(response, completionHandler: { (response, statusCode, error) -> Void in
    if error.isEmpty {
     print( "Response during unsubscribed tags : \(response?.description)")
        print( "status code during unsubscribed tags : \(statusCode)")
    }
  else {
    print( "Error during  unsubscribed tags \(error) ")
    print( "Error during unsubscribed tags \n  - status code: \(statusCode) \n Error :\(error) \n")
  }
}
```
	{: codeblock}

### Tags mit Google Chrome und Mozilla Firefox subskribieren und die Subskription aufheben
{: #web-subscribe-tags}

Um Tags von Webanwendungen zu subskribieren, verwenden Sie das folgende Code-Snippet:

```
var tagsArray = ["tag1", "Tag2"]
bmsPush.subscribe(tagsArray,function(response) {
  alert(response.response)
})
```
	{: codeblock}

Um die Subskription von Tags aufzuheben, verwenden Sie die Methode **unSubscribe**.

```
var tagsArray = ["tag1", "Tag2"]
 bmsPush.unSubscribe(tagsArray,function(response) {
 alert(response.response)
})
```
	{: codeblock}

## Tagbasierte Benachrichtigungen verwenden
{: #using_tags}

Tagbasierte Benachrichtigungen sind Benachrichtigungen, die alle diejenigen Geräte zum Ziel haben, die einen bestimmten Tag subskribiert haben. Jedes Gerät kann beliebig viele Tags subskribieren. Dieses Thema beschreibt, wie tagbasierte Benachrichtigungen gesendet werden. Subskriptionen werden von der Bluemix-Instanz des {{site.data.keyword.mobilepushshort}}-Service verwaltet. Wenn ein Tag gelöscht wird, werden alle diesem Tag zugeordneten Informationen (einschließlich Subskribenten und Geräte) gelöscht. Für diesen Tag ist keine automatische Aufhebung der Subskription erforderlich, da er nicht mehr vorhanden ist und daher clientseitig keine weiteren Aktionen nötig sind.

Erstellen Sie Tags mit der Option **Tags verwalten**.

1. Klicken Sie im **Push Notification**-Dashboard auf **Benachrichtigungen senden**.
1. Wählen Sie in der Dropdown-Liste **Senden an** die Option **Gerät nach Tag** aus.
1. Suchen Sie nach den Tags, die Sie verwenden möchten, und wählen Sie sie aus.
![Anzeige 'Benachrichtigungen'](images/tag_notification.jpg)
1. Geben Sie im Feld **Nachrichtentext** den Text ein, der als Benachrichtigung an die subskribierte Benutzergruppe gesendet werden soll.
1. Klicken Sie auf **Senden**.


text:
'use strict';

goog.provide('grrUi.core.legacyRendererDirective.LegacyRendererController');
goog.provide('grrUi.core.legacyRendererDirective.LegacyRendererDirective');

goog.scope(function() {

/** @private {number} */
grrUi.core.legacyRendererDirective.globalIdCounter_ = 0;

/**
 * Controller for LegacyRendererDirective.
 *
 * @constructor
 * @param {!angular.Scope} $scope
 * @ngInject
 */
grrUi.core.legacyRendererDirective.LegacyRendererController = function($scope) {
  /** @private {!angular.Scope} */
  this.scope_ = $scope;

  /** @type {string} */
  this.scope_.renderer;

  /** @type {Object<string, string|number|boolean>} */
  this.scope_.queryParams;

  /**
   * Current value of the global counter. Legacy renderers expect to be
   * rendered inside divs with a unique id.
   * @export {number}
   */
  this.idCounter = grrUi.core.legacyRendererDirective.globalIdCounter_++;
};

var LegacyRendererController =
    grrUi.core.legacyRendererDirective.LegacyRendererController;

/**
 * Renders a renderer inside the div generated by the directive's template.
 * This has to be called inside directive's link function, as render_ modifies
 * the DOM generated by the directive.
 * @private
 */
LegacyRendererController.prototype.render_ = function() {
  var domId = 'legacy_' + this.idCounter.toString();
  grr.layout(this.scope_.renderer, domId, this.scope_.queryParams,
             function() {
               // Special case handling for dialogs shown through combination
               // of legacy rendering and Bootstrap UI's $modal.
               $('#' + domId).find('button[data-dismiss=modal]').click(
                   /** @suppress {missingProperties} For jQuery.scope(). */
                   function() {
                     var parentScope = $(this).scope().$parent;
                     parentScope.$dismiss();
                   });
             });
};

/**
 * LegacyRendererDirective renders content via legacy GRR renderers.
 *
 * @return {angular.Directive} Directive definition object.
 */
grrUi.core.legacyRendererDirective.LegacyRendererDirective = function() {
  return {
    scope: {
      renderer: '@',
      queryParams: '=?'
    },
    template: '
Loading...
',
    restrict: 'E',
    controller: LegacyRendererController,
    controllerAs: 'controller',
    link: function(scope) {
      scope.controller.render_();
    }
  };
};

/**
 * Directive's name in Angular.
 *
 * @const
 * @export
 */
grrUi.core.legacyRendererDirective.LegacyRendererDirective.directive_name =
    'grrLegacyRenderer';

});  // goog.scope


text:
#ifdef ENABLE_NLS
# include <libintl.h>
/* Note the use of dgetext() and PACKAGE here, rather than gettext().

   This is because the code in this directory is used to build a library which
   will be linked with code in other directories to form programs.  We want to
   maintain a seperate translation file for this directory however, rather
   than being forced to merge it with that of any program linked to
   libopcodes.  This is a library, so it cannot depend on the catalog
   currently loaded.

   In order to do this, we have to make sure that when we extract messages we
   use the OPCODES domain rather than the domain of the program that included
   the opcodes library, (eg OBJDUMP).  Hence we use dgettext (PACKAGE, String)
   and define PACKAGE to be 'opcodes'.  (See the code in configure).  */
# define _(String) dgettext (PACKAGE, String)
# ifdef gettext_noop
#  define N_(String) gettext_noop (String)
# else
#  define N_(String) (String)
# endif
#else
# define gettext(Msgid) (Msgid)
# define dgettext(Domainname, Msgid) (Msgid)
# define dcgettext(Domainname, Msgid, Category) (Msgid)
# define textdomain(Domainname) while (0) /* nothing */
# define bindtextdomain(Domainname, Dirname) while (0) /* nothing */
# define _(String) (String)
# define N_(String) (String)
#endif


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>Uses of Interface org.apache.hadoop.hbase.codec.Codec.Encoder (HBase 0.98.6-hadoop2 API)</title>
<meta name="date" content="2014-09-03">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Interface
org.apache.hadoop.hbase.codec.Codec.Encoder

Packages that use Codec.Encoder

Package
Description

org.apache.hadoop.hbase.codec

org.apache.hadoop.hbase.regionserver.wal

Uses of Codec.Encoder in org.apache.hadoop.hbase.codec

Classes in org.apache.hadoop.hbase.codec that implement Codec.Encoder

Modifier and Type
Class and Description

class
BaseEncoder

TODO javadoc

static class
KeyValueCodec.KeyValueEncoder

static class
KeyValueCodecWithTags.KeyValueEncoder

Methods in org.apache.hadoop.hbase.codec that return Codec.Encoder

Modifier and Type
Method and Description

Codec.Encoder
MessageCodec.getEncoder(OutputStream os)

Codec.Encoder
CellCodec.getEncoder(OutputStream os)

Codec.Encoder
KeyValueCodecWithTags.getEncoder(OutputStream os)

Codec.Encoder
Codec.getEncoder(OutputStream os)

Codec.Encoder
KeyValueCodec.getEncoder(OutputStream os)

Codec.Encoder
CellCodecWithTags.getEncoder(OutputStream os)

Uses of Codec.Encoder in org.apache.hadoop.hbase.regionserver.wal

Classes in org.apache.hadoop.hbase.regionserver.wal that implement Codec.Encoder

Modifier and Type
Class and Description

class
WALCellCodec.EnsureKvEncoder

Fields in org.apache.hadoop.hbase.regionserver.wal declared as Codec.Encoder

Modifier and Type
Field and Description

protected Codec.Encoder
ProtobufLogWriter.cellEncoder

Methods in org.apache.hadoop.hbase.regionserver.wal that return Codec.Encoder

Modifier and Type
Method and Description

Codec.Encoder
WALCellCodec.getEncoder(OutputStream os)

Codec.Encoder
SecureWALCellCodec.getEncoder(OutputStream os)

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2014 The Apache Software Foundation. All rights reserved.


text:
function [hyp] = NIGPModelToHyperparameters(model)
%NIGPModelToHyperparameters will convert an NIGP model to a hyperparameter object.
% This function converts an NIGP model, with the seard and lsipn parameters, to a hyperparameter object, with lx, sx, ly, sy parameters.

hyp.lx = exp(model.seard(1:end-2,:));
hyp.sx = exp(model.lsipn);
hyp.ly = exp(model.seard(end-1,:)');
hyp.sy = exp(model.seard(end,:)');

end


text:
<?php

namespace Translate\Parser;

use Exception;

/**
 * @link https://github.com/MAXakaWIZARD/PoParser
 */
class Writer {

	/**
	 * @param string $filePath
	 * @param array $entries
	 *
	 * @throws \Exception
	 * @return void
	 */
	public function write(string $filePath, array $entries): void {
		$handle = $this->openFile($filePath);

		$entriesCount = count($entries);
		$counter = 0;
		foreach ($entries as $entry) {
			$entryStr = $this->getEntryStr($entry, $counter, $entriesCount);
			fwrite($handle, $entryStr);

			$counter++;
		}

		fclose($handle);
	}

	/**
	 * @param string $filePath
	 * @throws \Exception
	 * @return resource
	 */
	protected function openFile($filePath) {
		if (empty($filePath)) {
			throw new Exception('Output file not defined.');
		}

		$handle = fopen($filePath, 'wb');
		if ($handle === false) {
			throw new Exception("Unable to open file for writing: {$filePath}");
		}

		return $handle;
	}

	/**
	 * @param array $entry
	 * @param int $index
	 * @param int $entriesCount
	 *
	 * @return string
	 */
	protected function getEntryStr(array $entry, $index, $entriesCount): string {
		$result = '';
		if ($index > 0) {
			$result = "\n";
		}

		$result .= $this->writeComments($entry);
		$result .= $this->writeReferences($entry);
		$result .= $this->writeFlags($entry);
		$result .= $this->writeContext($entry);
		$result .= $this->writeObsolete($entry);
		$result .= $this->writeMsgId($entry, 'msgid');
		$result .= $this->writeMsgId($entry, 'msgid_plural');
		$result .= $this->writeMsgStr($entry);

		if ($index === $entriesCount - 1) {
			$result = rtrim($result);
		}

		return $result;
	}

	/**
	 * @param array $entry
	 *
	 * @return string
	 */
	protected function writeComments(array $entry) {
		$result = '';

		if ($entry['tcomment'] !== '') {
			$result .= '# ' . $entry['tcomment'] . "\n";
		}

		if ($entry['ccomment'] !== '') {
			$result .= '#. ' . $entry['ccomment'] . "\n";
		}

		return $result;
	}

	/**
	 * @param array $entry
	 *
	 * @return string
	 */
	protected function writeFlags(array $entry) {
		$result = '';

		if (count($entry['flags']) > 0) {
			$result .= '#, ' . implode(', ', $entry['flags']) . "\n";
		}

		if (isset($entry['@'])) {
			$result .= '#@ ' . $entry['@'] . "\n";
		}

		return $result;
	}

	/**
	 * @param array $entry
	 *
	 * @return string
	 */
	protected function writeReferences(array $entry) {
		$result = '';

		if (count($entry['references']) > 0) {
			foreach ($entry['references'] as $ref) {
				$result .= '#: ' . $ref . "\n";
			}
		}

		return $result;
	}

	/**
	 * @param array $entry
	 *
	 * @return string
	 */
	protected function writeContext(array $entry) {
		$result = '';

		if ($entry['msgctxt'] !== '') {
			$result .= 'msgctxt ' . $this->cleanExport($entry['msgctxt']) . "\n";
		}

		return $result;
	}

	/**
	 * @param array $entry
	 *
	 * @return string
	 */
	protected function writeObsolete(array $entry) {
		return ($entry['obsolete']) ? '#~ ' : '';
	}

	/**
	 * @param array $entry
	 * @param string $type msgid or msgid_plural
	 *
	 * @return string
	 */
	protected function writeMsgId(array $entry, $type = 'msgid') {
		$result = '';

		if (!isset($entry[$type])) {
			return $result;
		}

		$result .= $type . ' ';
		if (is_array($entry[$type])) {
			foreach ($entry[$type] as $id) {
				$result .= $this->cleanExport($id) . "\n";
			}
		} else {
			$result .= $this->cleanExport($entry[$type]) . "\n";
		}

		return $result;
	}

	/**
	 * @param array $entry
	 *
	 * @return string
	 */
	protected function writeMsgStr(array $entry) {
		$result = '';

		if (!isset($entry['msgstr'])) {
			return $result;
		}

		$isPlural = isset($entry['msgid_plural']);

		foreach ($entry['msgstr'] as $i => $value) {
			if ($entry['obsolete']) {
				$result .= '#~ ';
			}

			if ($isPlural) {
				$result .= "msgstr[$i] ";
			} else {
				if ($i == 0) {
					$result .= 'msgstr ';
				}
			}

			$result .= $this->cleanExport($value) . "\n";
		}

		return $result;
	}

	/**
	 * @param string $string
	 *
	 * @return string
	 */
	protected function cleanExport(string $string) {
		$quote = '"';
		$slash = '\\';
		$newline = "\n";

		$replaces = [
			"$slash" => "$slash$slash",
			"$quote" => "$slash$quote",
			"\t" => '\t',
		];

		$string = str_replace(array_keys($replaces), array_values($replaces), $string);

		$po = $quote . implode("${slash}n$quote$newline$quote", explode($newline, $string)) . $quote;

		// remove empty strings
		return str_replace("$newline$quote$quote", '', $po);
	}

}


text:
/**
 * @private
 */
var WebSocketEmulatedChannelFactory = (function () {

    var WebSocketEmulatedChannelFactory = function () {
    };
    var $prototype = WebSocketEmulatedChannelFactory.prototype;

    $prototype.createChannel = function (location, protocol, isBinary) {
        var channel = new WebSocketSelectedChannel(location, protocol, isBinary);
        return channel;
    }

    return WebSocketEmulatedChannelFactory;
})();


text:
import {
  orientationProp,
} from '../helpers/OrientationHelpers';

export function getVelocityProp(orientation) {
  return `velocity${orientationProp[orientation].toUpperCase()}`;
}

export function getDeltaProp(orientation) {
  return `delta${orientationProp[orientation].toUpperCase()}`;
}

export function getTranslate3D(translate) {
  return `translate3d(${translate.x}px, ${translate.y}px, 0px)`;
}


text:
use rustc_data_structures::fx::FxHashSet;
use rustc_hir as hir;
use rustc_hir::def::{DefKind, Res};
use rustc_hir::def_id::{DefId, LocalDefId};
use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor};
use rustc_hir::itemlikevisit::ItemLikeVisitor;
use rustc_hir::Node;
use rustc_middle::middle::codegen_fn_attrs::{CodegenFnAttrFlags, CodegenFnAttrs};
use rustc_middle::middle::privacy;
use rustc_middle::ty::query::Providers;
use rustc_middle::ty::{self, DefIdTree, TyCtxt};
use rustc_session::config::CrateType;
use rustc_target::spec::abi::Abi;

// Returns true if the given item must be inlined because it may be
// monomorphized or it was marked with `#[inline]`. This will only return
// true for functions.
fn item_might_be_inlined(tcx: TyCtxt<'tcx>, item: &hir::Item<'_>, attrs: &CodegenFnAttrs) -> bool {
    if attrs.requests_inline() {
        return true;
    }

    match item.kind {
        hir::ItemKind::Fn(ref sig, ..) if sig.header.is_const() => true,
        hir::ItemKind::Impl { .. } | hir::ItemKind::Fn(..) => {
            let generics = tcx.generics_of(item.def_id);
            generics.requires_monomorphization(tcx)
        }
        _ => false,
    }
}

fn method_might_be_inlined(
    tcx: TyCtxt<'_>,
    impl_item: &hir::ImplItem<'_>,
    impl_src: LocalDefId,
) -> bool {
    let codegen_fn_attrs = tcx.codegen_fn_attrs(impl_item.hir_id().owner.to_def_id());
    let generics = tcx.generics_of(impl_item.def_id);
    if codegen_fn_attrs.requests_inline() || generics.requires_monomorphization(tcx) {
        return true;
    }
    if let hir::ImplItemKind::Fn(method_sig, _) = &impl_item.kind {
        if method_sig.header.is_const() {
            return true;
        }
    }
    match tcx.hir().find(tcx.hir().local_def_id_to_hir_id(impl_src)) {
        Some(Node::Item(item)) => item_might_be_inlined(tcx, &item, codegen_fn_attrs),
        Some(..) | None => span_bug!(impl_item.span, "impl did is not an item"),
    }
}

// Information needed while computing reachability.
struct ReachableContext<'tcx> {
    // The type context.
    tcx: TyCtxt<'tcx>,
    maybe_typeck_results: Option<&'tcx ty::TypeckResults<'tcx>>,
    // The set of items which must be exported in the linkage sense.
    reachable_symbols: FxHashSet<LocalDefId>,
    // A worklist of item IDs. Each item ID in this worklist will be inlined
    // and will be scanned for further references.
    // FIXME(eddyb) benchmark if this would be faster as a `VecDeque`.
    worklist: Vec<LocalDefId>,
    // Whether any output of this compilation is a library
    any_library: bool,
}

impl<'tcx> Visitor<'tcx> for ReachableContext<'tcx> {
    type Map = intravisit::ErasedMap<'tcx>;

    fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
        NestedVisitorMap::None
    }

    fn visit_nested_body(&mut self, body: hir::BodyId) {
        let old_maybe_typeck_results =
            self.maybe_typeck_results.replace(self.tcx.typeck_body(body));
        let body = self.tcx.hir().body(body);
        self.visit_body(body);
        self.maybe_typeck_results = old_maybe_typeck_results;
    }

    fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
        let res = match expr.kind {
            hir::ExprKind::Path(ref qpath) => {
                Some(self.typeck_results().qpath_res(qpath, expr.hir_id))
            }
            hir::ExprKind::MethodCall(..) => self
                .typeck_results()
                .type_dependent_def(expr.hir_id)
                .map(|(kind, def_id)| Res::Def(kind, def_id)),
            _ => None,
        };

        if let Some(res) = res {
            if let Some(def_id) = res.opt_def_id().and_then(|def_id| def_id.as_local()) {
                if self.def_id_represents_local_inlined_item(def_id.to_def_id()) {
                    self.worklist.push(def_id);
                } else {
                    match res {
                        // If this path leads to a constant, then we need to
                        // recurse into the constant to continue finding
                        // items that are reachable.
                        Res::Def(DefKind::Const | DefKind::AssocConst, _) => {
                            self.worklist.push(def_id);
                        }

                        // If this wasn't a static, then the destination is
                        // surely reachable.
                        _ => {
                            self.reachable_symbols.insert(def_id);
                        }
                    }
                }
            }
        }

        intravisit::walk_expr(self, expr)
    }
}

impl<'tcx> ReachableContext<'tcx> {
    /// Gets the type-checking results for the current body.
    /// As this will ICE if called outside bodies, only call when working with
    /// `Expr` or `Pat` nodes (they are guaranteed to be found only in bodies).
    #[track_caller]
    fn typeck_results(&self) -> &'tcx ty::TypeckResults<'tcx> {
        self.maybe_typeck_results
            .expect("`ReachableContext::typeck_results` called outside of body")
    }

    // Returns true if the given def ID represents a local item that is
    // eligible for inlining and false otherwise.
    fn def_id_represents_local_inlined_item(&self, def_id: DefId) -> bool {
        let hir_id = match def_id.as_local() {
            Some(def_id) => self.tcx.hir().local_def_id_to_hir_id(def_id),
            None => {
                return false;
            }
        };

        match self.tcx.hir().find(hir_id) {
            Some(Node::Item(item)) => match item.kind {
                hir::ItemKind::Fn(..) => {
                    item_might_be_inlined(self.tcx, &item, self.tcx.codegen_fn_attrs(def_id))
                }
                _ => false,
            },
            Some(Node::TraitItem(trait_method)) => match trait_method.kind {
                hir::TraitItemKind::Const(_, ref default) => default.is_some(),
                hir::TraitItemKind::Fn(_, hir::TraitFn::Provided(_)) => true,
                hir::TraitItemKind::Fn(_, hir::TraitFn::Required(_))
                | hir::TraitItemKind::Type(..) => false,
            },
            Some(Node::ImplItem(impl_item)) => {
                match impl_item.kind {
                    hir::ImplItemKind::Const(..) => true,
                    hir::ImplItemKind::Fn(..) => {
                        let attrs = self.tcx.codegen_fn_attrs(def_id);
                        let generics = self.tcx.generics_of(def_id);
                        if generics.requires_monomorphization(self.tcx) || attrs.requests_inline() {
                            true
                        } else {
                            let impl_did = self.tcx.hir().get_parent_did(hir_id);
                            // Check the impl. If the generics on the self
                            // type of the impl require inlining, this method
                            // does too.
                            match self.tcx.hir().expect_item(impl_did).kind {
                                hir::ItemKind::Impl { .. } => {
                                    let generics = self.tcx.generics_of(impl_did);
                                    generics.requires_monomorphization(self.tcx)
                                }
                                _ => false,
                            }
                        }
                    }
                    hir::ImplItemKind::TyAlias(_) => false,
                }
            }
            Some(_) => false,
            None => false, // This will happen for default methods.
        }
    }

    // Step 2: Mark all symbols that the symbols on the worklist touch.
    fn propagate(&mut self) {
        let mut scanned = FxHashSet::default();
        while let Some(search_item) = self.worklist.pop() {
            if !scanned.insert(search_item) {
                continue;
            }

            if let Some(ref item) =
                self.tcx.hir().find(self.tcx.hir().local_def_id_to_hir_id(search_item))
            {
                self.propagate_node(item, search_item);
            }
        }
    }

    fn propagate_node(&mut self, node: &Node<'tcx>, search_item: LocalDefId) {
        if !self.any_library {
            // If we are building an executable, only explicitly extern
            // types need to be exported.
            let reachable =
                if let Node::Item(hir::Item { kind: hir::ItemKind::Fn(sig, ..), .. })
                | Node::ImplItem(hir::ImplItem {
                    kind: hir::ImplItemKind::Fn(sig, ..), ..
                }) = *node
                {
                    sig.header.abi != Abi::Rust
                } else {
                    false
                };
            let codegen_attrs = self.tcx.codegen_fn_attrs(search_item);
            let is_extern = codegen_attrs.contains_extern_indicator();
            let std_internal =
                codegen_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL);
            if reachable || is_extern || std_internal {
                self.reachable_symbols.insert(search_item);
            }
        } else {
            // If we are building a library, then reachable symbols will
            // continue to participate in linkage after this product is
            // produced. In this case, we traverse the ast node, recursing on
            // all reachable nodes from this one.
            self.reachable_symbols.insert(search_item);
        }

        match *node {
            Node::Item(item) => {
                match item.kind {
                    hir::ItemKind::Fn(.., body) => {
                        if item_might_be_inlined(
                            self.tcx,
                            &item,
                            self.tcx.codegen_fn_attrs(item.def_id),
                        ) {
                            self.visit_nested_body(body);
                        }
                    }

                    // Reachable constants will be inlined into other crates
                    // unconditionally, so we need to make sure that their
                    // contents are also reachable.
                    hir::ItemKind::Const(_, init) | hir::ItemKind::Static(_, _, init) => {
                        self.visit_nested_body(init);
                    }

                    // These are normal, nothing reachable about these
                    // inherently and their children are already in the
                    // worklist, as determined by the privacy pass
                    hir::ItemKind::ExternCrate(_)
                    | hir::ItemKind::Use(..)
                    | hir::ItemKind::OpaqueTy(..)
                    | hir::ItemKind::TyAlias(..)
                    | hir::ItemKind::Macro(..)
                    | hir::ItemKind::Mod(..)
                    | hir::ItemKind::ForeignMod { .. }
                    | hir::ItemKind::Impl { .. }
                    | hir::ItemKind::Trait(..)
                    | hir::ItemKind::TraitAlias(..)
                    | hir::ItemKind::Struct(..)
                    | hir::ItemKind::Enum(..)
                    | hir::ItemKind::Union(..)
                    | hir::ItemKind::GlobalAsm(..) => {}
                }
            }
            Node::TraitItem(trait_method) => {
                match trait_method.kind {
                    hir::TraitItemKind::Const(_, None)
                    | hir::TraitItemKind::Fn(_, hir::TraitFn::Required(_)) => {
                        // Keep going, nothing to get exported
                    }
                    hir::TraitItemKind::Const(_, Some(body_id))
                    | hir::TraitItemKind::Fn(_, hir::TraitFn::Provided(body_id)) => {
                        self.visit_nested_body(body_id);
                    }
                    hir::TraitItemKind::Type(..) => {}
                }
            }
            Node::ImplItem(impl_item) => match impl_item.kind {
                hir::ImplItemKind::Const(_, body) => {
                    self.visit_nested_body(body);
                }
                hir::ImplItemKind::Fn(_, body) => {
                    let impl_def_id =
                        self.tcx.parent(search_item.to_def_id()).unwrap().expect_local();
                    if method_might_be_inlined(self.tcx, impl_item, impl_def_id) {
                        self.visit_nested_body(body)
                    }
                }
                hir::ImplItemKind::TyAlias(_) => {}
            },
            Node::Expr(&hir::Expr { kind: hir::ExprKind::Closure(.., body, _, _), .. }) => {
                self.visit_nested_body(body);
            }
            // Nothing to recurse on for these
            Node::ForeignItem(_)
            | Node::Variant(_)
            | Node::Ctor(..)
            | Node::Field(_)
            | Node::Ty(_)
            | Node::Crate(_) => {}
            _ => {
                bug!(
                    "found unexpected node kind in worklist: {} ({:?})",
                    self.tcx
                        .hir()
                        .node_to_string(self.tcx.hir().local_def_id_to_hir_id(search_item)),
                    node,
                );
            }
        }
    }
}

// Some methods from non-exported (completely private) trait impls still have to be
// reachable if they are called from inlinable code. Generally, it's not known until
// monomorphization if a specific trait impl item can be reachable or not. So, we
// conservatively mark all of them as reachable.
// FIXME: One possible strategy for pruning the reachable set is to avoid marking impl
// items of non-exported traits (or maybe all local traits?) unless their respective
// trait items are used from inlinable code through method call syntax or UFCS, or their
// trait is a lang item.
struct CollectPrivateImplItemsVisitor<'a, 'tcx> {
    tcx: TyCtxt<'tcx>,
    access_levels: &'a privacy::AccessLevels,
    worklist: &'a mut Vec<LocalDefId>,
}

impl CollectPrivateImplItemsVisitor<'_, '_> {
    fn push_to_worklist_if_has_custom_linkage(&mut self, def_id: LocalDefId) {
        // Anything which has custom linkage gets thrown on the worklist no
        // matter where it is in the crate, along with "special std symbols"
        // which are currently akin to allocator symbols.
        let codegen_attrs = self.tcx.codegen_fn_attrs(def_id);
        if codegen_attrs.contains_extern_indicator()
            || codegen_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL)
        {
            self.worklist.push(def_id);
        }
    }
}

impl<'a, 'tcx> ItemLikeVisitor<'tcx> for CollectPrivateImplItemsVisitor<'a, 'tcx> {
    fn visit_item(&mut self, item: &hir::Item<'_>) {
        self.push_to_worklist_if_has_custom_linkage(item.def_id);

        // We need only trait impls here, not inherent impls, and only non-exported ones
        if let hir::ItemKind::Impl(hir::Impl { of_trait: Some(ref trait_ref), ref items, .. }) =
            item.kind
        {
            if !self.access_levels.is_reachable(item.def_id) {
                // FIXME(#53488) remove `let`
                let tcx = self.tcx;
                self.worklist.extend(items.iter().map(|ii_ref| ii_ref.id.def_id));

                let trait_def_id = match trait_ref.path.res {
                    Res::Def(DefKind::Trait, def_id) => def_id,
                    _ => unreachable!(),
                };

                if !trait_def_id.is_local() {
                    return;
                }

                self.worklist.extend(
                    tcx.provided_trait_methods(trait_def_id)
                        .map(|assoc| assoc.def_id.expect_local()),
                );
            }
        }
    }

    fn visit_trait_item(&mut self, _trait_item: &hir::TraitItem<'_>) {}

    fn visit_impl_item(&mut self, impl_item: &hir::ImplItem<'_>) {
        self.push_to_worklist_if_has_custom_linkage(impl_item.def_id);
    }

    fn visit_foreign_item(&mut self, _foreign_item: &hir::ForeignItem<'_>) {
        // We never export foreign functions as they have no body to export.
    }
}

fn reachable_set<'tcx>(tcx: TyCtxt<'tcx>, (): ()) -> FxHashSet<LocalDefId> {
    let access_levels = &tcx.privacy_access_levels(());

    let any_library =
        tcx.sess.crate_types().iter().any(|ty| {
            *ty == CrateType::Rlib || *ty == CrateType::Dylib || *ty == CrateType::ProcMacro
        });
    let mut reachable_context = ReachableContext {
        tcx,
        maybe_typeck_results: None,
        reachable_symbols: Default::default(),
        worklist: Vec::new(),
        any_library,
    };

    // Step 1: Seed the worklist with all nodes which were found to be public as
    //         a result of the privacy pass along with all local lang items and impl items.
    //         If other crates link to us, they're going to expect to be able to
    //         use the lang items, so we need to be sure to mark them as
    //         exported.
    reachable_context.worklist.extend(access_levels.map.keys());
    for item in tcx.lang_items().items().iter() {
        if let Some(def_id) = *item {
            if let Some(def_id) = def_id.as_local() {
                reachable_context.worklist.push(def_id);
            }
        }
    }
    {
        let mut collect_private_impl_items = CollectPrivateImplItemsVisitor {
            tcx,
            access_levels,
            worklist: &mut reachable_context.worklist,
        };
        tcx.hir().visit_all_item_likes(&mut collect_private_impl_items);
    }

    // Step 2: Mark all symbols that the symbols on the worklist touch.
    reachable_context.propagate();

    debug!("Inline reachability shows: {:?}", reachable_context.reachable_symbols);

    // Return the set of reachable symbols.
    reachable_context.reachable_symbols
}

pub fn provide(providers: &mut Providers) {
    *providers = Providers { reachable_set, ..*providers };
}


text:
package com.study.luence.day1;

import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;

/**
 * 词项搜索
 */
public class TermQueryTest {

    public static void main(String[] args) throws IOException {
        Path indexPath = Paths.get("/Users/liuzhaoyuan/gitwork/study-hello/study-lucene/indexdir");
        Directory dir = FSDirectory.open(indexPath);
        IndexReader reader = DirectoryReader.open(dir);
        IndexSearcher searcher = new IndexSearcher(reader);

        Term term = new Term("title", "习近平");
        Query termQuery = new TermQuery(term);
        System.out.println("Query:" + termQuery);

        // 返回前10条
        TopDocs tds = searcher.search(termQuery, 10);
        for (ScoreDoc sd : tds.scoreDocs) {
            // Explanation explanation = searcher.explain(query, sd.doc);
            // System.out.println("explain:" + explanation + "\n");
            Document doc = searcher.doc(sd.doc);
            System.out.println("DocID:" + sd.doc);
            System.out.println("id:" + doc.get("id"));
            System.out.println("title:" + doc.get("title"));
            System.out.println("文档评分:" + sd.score);

        }
        dir.close();
        reader.close();

    }

}