text:
import warnings
from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union

from google.api_core import gapic_v1
from google.api_core import grpc_helpers_async
from google.api_core import operations_v1
from google.auth import credentials as ga_credentials  # type: ignore
from google.auth.transport.grpc import SslCredentials  # type: ignore

import grpc  # type: ignore
from grpc.experimental import aio  # type: ignore

from google.cloud.dialogflowcx_v3beta1.types import test_case
from google.cloud.dialogflowcx_v3beta1.types import test_case as gcdc_test_case
from google.cloud.location import locations_pb2  # type: ignore
from google.longrunning import operations_pb2
from google.longrunning import operations_pb2  # type: ignore
from google.protobuf import empty_pb2  # type: ignore
from .base import TestCasesTransport, DEFAULT_CLIENT_INFO
from .grpc import TestCasesGrpcTransport

class TestCasesGrpcAsyncIOTransport(TestCasesTransport):
    """gRPC AsyncIO backend transport for TestCases.

    Service for managing [Test
    Cases][google.cloud.dialogflow.cx.v3beta1.TestCase] and [Test Case
    Results][google.cloud.dialogflow.cx.v3beta1.TestCaseResult].

    This class defines the same methods as the primary client, so the
    primary client can load the underlying transport implementation
    and call it.

    It sends protocol buffers over the wire using gRPC (which is built on
    top of HTTP/2); the ``grpcio`` package must be installed.
    """

    _grpc_channel: aio.Channel
    _stubs: Dict[str, Callable] = {}

    @classmethod
    def create_channel(
        cls,
        host: str = "dialogflow.googleapis.com",
        credentials: ga_credentials.Credentials = None,
        credentials_file: Optional[str] = None,
        scopes: Optional[Sequence[str]] = None,
        quota_project_id: Optional[str] = None,
        **kwargs,
    ) -> aio.Channel:
        """Create and return a gRPC AsyncIO channel object.
        Args:
            host (Optional[str]): The host for the channel to use.
            credentials (Optional[~.Credentials]): The
                authorization credentials to attach to requests. These
                credentials identify this application to the service. If
                none are specified, the client will attempt to ascertain
                the credentials from the environment.
            credentials_file (Optional[str]): A file with credentials that can
                be loaded with :func:`google.auth.load_credentials_from_file`.
                This argument is ignored if ``channel`` is provided.
            scopes (Optional[Sequence[str]]): A optional list of scopes needed for this
                service. These are only used when credentials are not specified and
                are passed to :func:`google.auth.default`.
            quota_project_id (Optional[str]): An optional project to use for billing
                and quota.
            kwargs (Optional[dict]): Keyword arguments, which are passed to the
                channel creation.
        Returns:
            aio.Channel: A gRPC AsyncIO channel object.
        """

        return grpc_helpers_async.create_channel(
            host,
            credentials=credentials,
            credentials_file=credentials_file,
            quota_project_id=quota_project_id,
            default_scopes=cls.AUTH_SCOPES,
            scopes=scopes,
            default_host=cls.DEFAULT_HOST,
            **kwargs,
        )

    def __init__(
        self,
        *,
        host: str = "dialogflow.googleapis.com",
        credentials: ga_credentials.Credentials = None,
        credentials_file: Optional[str] = None,
        scopes: Optional[Sequence[str]] = None,
        channel: aio.Channel = None,
        api_mtls_endpoint: str = None,
        client_cert_source: Callable[[], Tuple[bytes, bytes]] = None,
        ssl_channel_credentials: grpc.ChannelCredentials = None,
        client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None,
        quota_project_id=None,
        client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
        always_use_jwt_access: Optional[bool] = False,
        api_audience: Optional[str] = None,
    ) -> None:
        """Instantiate the transport.

        Args:
            host (Optional[str]):
                 The hostname to connect to.
            credentials (Optional[google.auth.credentials.Credentials]): The
                authorization credentials to attach to requests. These
                credentials identify the application to the service; if none
                are specified, the client will attempt to ascertain the
                credentials from the environment.
                This argument is ignored if ``channel`` is provided.
            credentials_file (Optional[str]): A file with credentials that can
                be loaded with :func:`google.auth.load_credentials_from_file`.
                This argument is ignored if ``channel`` is provided.
            scopes (Optional[Sequence[str]]): A optional list of scopes needed for this
                service. These are only used when credentials are not specified and
                are passed to :func:`google.auth.default`.
            channel (Optional[aio.Channel]): A ``Channel`` instance through
                which to make calls.
            api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint.
                If provided, it overrides the ``host`` argument and tries to create
                a mutual TLS channel with client SSL credentials from
                ``client_cert_source`` or application default SSL credentials.
            client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]):
                Deprecated. A callback to provide client SSL certificate bytes and
                private key bytes, both in PEM format. It is ignored if
                ``api_mtls_endpoint`` is None.
            ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials
                for the grpc channel. It is ignored if ``channel`` is provided.
            client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]):
                A callback to provide client certificate bytes and private key bytes,
                both in PEM format. It is used to configure a mutual TLS channel. It is
                ignored if ``channel`` or ``ssl_channel_credentials`` is provided.
            quota_project_id (Optional[str]): An optional project to use for billing
                and quota.
            client_info (google.api_core.gapic_v1.client_info.ClientInfo):
                The client info used to send a user-agent string along with
                API requests. If ``None``, then default info will be used.
                Generally, you only need to set this if you're developing
                your own client library.
            always_use_jwt_access (Optional[bool]): Whether self signed JWT should
                be used for service account credentials.

        Raises:
            google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport
              creation failed for any reason.
          google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
              and ``credentials_file`` are passed.
        """
        self._grpc_channel = None
        self._ssl_channel_credentials = ssl_channel_credentials
        self._stubs: Dict[str, Callable] = {}
        self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None

        if api_mtls_endpoint:
            warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning)
        if client_cert_source:
            warnings.warn("client_cert_source is deprecated", DeprecationWarning)

        if channel:
            # Ignore credentials if a channel was passed.
            credentials = False
            # If a channel was explicitly provided, set it.
            self._grpc_channel = channel
            self._ssl_channel_credentials = None
        else:
            if api_mtls_endpoint:
                host = api_mtls_endpoint

                # Create SSL credentials with client_cert_source or application
                # default SSL credentials.
                if client_cert_source:
                    cert, key = client_cert_source()
                    self._ssl_channel_credentials = grpc.ssl_channel_credentials(
                        certificate_chain=cert, private_key=key
                    )
                else:
                    self._ssl_channel_credentials = SslCredentials().ssl_credentials

            else:
                if client_cert_source_for_mtls and not ssl_channel_credentials:
                    cert, key = client_cert_source_for_mtls()
                    self._ssl_channel_credentials = grpc.ssl_channel_credentials(
                        certificate_chain=cert, private_key=key
                    )

        # The base transport sets the host, credentials and scopes
        super().__init__(
            host=host,
            credentials=credentials,
            credentials_file=credentials_file,
            scopes=scopes,
            quota_project_id=quota_project_id,
            client_info=client_info,
            always_use_jwt_access=always_use_jwt_access,
            api_audience=api_audience,
        )

        if not self._grpc_channel:
            self._grpc_channel = type(self).create_channel(
                self._host,
                # use the credentials which are saved
                credentials=self._credentials,
                # Set ``credentials_file`` to ``None`` here as
                # the credentials that we saved earlier should be used.
                credentials_file=None,
                scopes=self._scopes,
                ssl_credentials=self._ssl_channel_credentials,
                quota_project_id=quota_project_id,
                options=[
                    ("grpc.max_send_message_length", -1),
                    ("grpc.max_receive_message_length", -1),
                ],
            )

        # Wrap messages. This must be done after self._grpc_channel exists
        self._prep_wrapped_messages(client_info)

    @property
    def grpc_channel(self) -> aio.Channel:
        """Create the channel designed to connect to this service.

        This property caches on the instance; repeated calls return
        the same channel.
        """
        # Return the channel from cache.
        return self._grpc_channel

    @property
    def operations_client(self) -> operations_v1.OperationsAsyncClient:
        """Create the client designed to process long-running operations.

        This property caches on the instance; repeated calls return the same
        client.
        """
        # Quick check: Only create a new client if we do not already have one.
        if self._operations_client is None:
            self._operations_client = operations_v1.OperationsAsyncClient(
                self.grpc_channel
            )

        # Return the client from cache.
        return self._operations_client

    @property
    def list_test_cases(
        self,
    ) -> Callable[
        [test_case.ListTestCasesRequest], Awaitable[test_case.ListTestCasesResponse]
    ]:
        r"""Return a callable for the list test cases method over gRPC.

        Fetches a list of test cases for a given agent.

        Returns:
            Callable[[~.ListTestCasesRequest],
                    Awaitable[~.ListTestCasesResponse]]:
                A function that, when called, will call the underlying RPC
                on the server.
        """
        # Generate a "stub function" on-the-fly which will actually make
        # the request.
        # gRPC handles serialization and deserialization, so we just need
        # to pass in the functions for each.
        if "list_test_cases" not in self._stubs:
            self._stubs["list_test_cases"] = self.grpc_channel.unary_unary(
                "/google.cloud.dialogflow.cx.v3beta1.TestCases/ListTestCases",
                request_serializer=test_case.ListTestCasesRequest.serialize,
                response_deserializer=test_case.ListTestCasesResponse.deserialize,
            )
        return self._stubs["list_test_cases"]

    @property
    def batch_delete_test_cases(
        self,
    ) -> Callable[[test_case.BatchDeleteTestCasesRequest], Awaitable[empty_pb2.Empty]]:
        r"""Return a callable for the batch delete test cases method over gRPC.

        Batch deletes test cases.

        Returns:
            Callable[[~.BatchDeleteTestCasesRequest],
                    Awaitable[~.Empty]]:
                A function that, when called, will call the underlying RPC
                on the server.
        """
        # Generate a "stub function" on-the-fly which will actually make
        # the request.
        # gRPC handles serialization and deserialization, so we just need
        # to pass in the functions for each.
        if "batch_delete_test_cases" not in self._stubs:
            self._stubs["batch_delete_test_cases"] = self.grpc_channel.unary_unary(
                "/google.cloud.dialogflow.cx.v3beta1.TestCases/BatchDeleteTestCases",
                request_serializer=test_case.BatchDeleteTestCasesRequest.serialize,
                response_deserializer=empty_pb2.Empty.FromString,
            )
        return self._stubs["batch_delete_test_cases"]

    @property
    def get_test_case(
        self,
    ) -> Callable[[test_case.GetTestCaseRequest], Awaitable[test_case.TestCase]]:
        r"""Return a callable for the get test case method over gRPC.

        Gets a test case.

        Returns:
            Callable[[~.GetTestCaseRequest],
                    Awaitable[~.TestCase]]:
                A function that, when called, will call the underlying RPC
                on the server.
        """
        # Generate a "stub function" on-the-fly which will actually make
        # the request.
        # gRPC handles serialization and deserialization, so we just need
        # to pass in the functions for each.
        if "get_test_case" not in self._stubs:
            self._stubs["get_test_case"] = self.grpc_channel.unary_unary(
                "/google.cloud.dialogflow.cx.v3beta1.TestCases/GetTestCase",
                request_serializer=test_case.GetTestCaseRequest.serialize,
                response_deserializer=test_case.TestCase.deserialize,
            )
        return self._stubs["get_test_case"]

    @property
    def create_test_case(
        self,
    ) -> Callable[
        [gcdc_test_case.CreateTestCaseRequest], Awaitable[gcdc_test_case.TestCase]
    ]:
        r"""Return a callable for the create test case method over gRPC.

        Creates a test case for the given agent.

        Returns:
            Callable[[~.CreateTestCaseRequest],
                    Awaitable[~.TestCase]]:
                A function that, when called, will call the underlying RPC
                on the server.
        """
        # Generate a "stub function" on-the-fly which will actually make
        # the request.
        # gRPC handles serialization and deserialization, so we just need
        # to pass in the functions for each.
        if "create_test_case" not in self._stubs:
            self._stubs["create_test_case"] = self.grpc_channel.unary_unary(
                "/google.cloud.dialogflow.cx.v3beta1.TestCases/CreateTestCase",
                request_serializer=gcdc_test_case.CreateTestCaseRequest.serialize,
                response_deserializer=gcdc_test_case.TestCase.deserialize,
            )
        return self._stubs["create_test_case"]

    @property
    def update_test_case(
        self,
    ) -> Callable[
        [gcdc_test_case.UpdateTestCaseRequest], Awaitable[gcdc_test_case.TestCase]
    ]:
        r"""Return a callable for the update test case method over gRPC.

        Updates the specified test case.

        Returns:
            Callable[[~.UpdateTestCaseRequest],
                    Awaitable[~.TestCase]]:
                A function that, when called, will call the underlying RPC
                on the server.
        """
        # Generate a "stub function" on-the-fly which will actually make
        # the request.
        # gRPC handles serialization and deserialization, so we just need
        # to pass in the functions for each.
        if "update_test_case" not in self._stubs:
            self._stubs["update_test_case"] = self.grpc_channel.unary_unary(
                "/google.cloud.dialogflow.cx.v3beta1.TestCases/UpdateTestCase",
                request_serializer=gcdc_test_case.UpdateTestCaseRequest.serialize,
                response_deserializer=gcdc_test_case.TestCase.deserialize,
            )
        return self._stubs["update_test_case"]

    @property
    def run_test_case(
        self,
    ) -> Callable[[test_case.RunTestCaseRequest], Awaitable[operations_pb2.Operation]]:
        r"""Return a callable for the run test case method over gRPC.

        Kicks off a test case run.

        This method is a `long-running
        operation <https://cloud.google.com/dialogflow/cx/docs/how/long-running-operation>`__.
        The returned ``Operation`` type has the following
        method-specific fields:

        -  ``metadata``:
           [RunTestCaseMetadata][google.cloud.dialogflow.cx.v3beta1.RunTestCaseMetadata]
        -  ``response``:
           [RunTestCaseResponse][google.cloud.dialogflow.cx.v3beta1.RunTestCaseResponse]

        Returns:
            Callable[[~.RunTestCaseRequest],
                    Awaitable[~.Operation]]:
                A function that, when called, will call the underlying RPC
                on the server.
        """
        # Generate a "stub function" on-the-fly which will actually make
        # the request.
        # gRPC handles serialization and deserialization, so we just need
        # to pass in the functions for each.
        if "run_test_case" not in self._stubs:
            self._stubs["run_test_case"] = self.grpc_channel.unary_unary(
                "/google.cloud.dialogflow.cx.v3beta1.TestCases/RunTestCase",
                request_serializer=test_case.RunTestCaseRequest.serialize,
                response_deserializer=operations_pb2.Operation.FromString,
            )
        return self._stubs["run_test_case"]

    @property
    def batch_run_test_cases(
        self,
    ) -> Callable[
        [test_case.BatchRunTestCasesRequest], Awaitable[operations_pb2.Operation]
    ]:
        r"""Return a callable for the batch run test cases method over gRPC.

        Kicks off a batch run of test cases.

        This method is a `long-running
        operation <https://cloud.google.com/dialogflow/cx/docs/how/long-running-operation>`__.
        The returned ``Operation`` type has the following
        method-specific fields:

        -  ``metadata``:
           [BatchRunTestCasesMetadata][google.cloud.dialogflow.cx.v3beta1.BatchRunTestCasesMetadata]
        -  ``response``:
           [BatchRunTestCasesResponse][google.cloud.dialogflow.cx.v3beta1.BatchRunTestCasesResponse]

        Returns:
            Callable[[~.BatchRunTestCasesRequest],
                    Awaitable[~.Operation]]:
                A function that, when called, will call the underlying RPC
                on the server.
        """
        # Generate a "stub function" on-the-fly which will actually make
        # the request.
        # gRPC handles serialization and deserialization, so we just need
        # to pass in the functions for each.
        if "batch_run_test_cases" not in self._stubs:
            self._stubs["batch_run_test_cases"] = self.grpc_channel.unary_unary(
                "/google.cloud.dialogflow.cx.v3beta1.TestCases/BatchRunTestCases",
                request_serializer=test_case.BatchRunTestCasesRequest.serialize,
                response_deserializer=operations_pb2.Operation.FromString,
            )
        return self._stubs["batch_run_test_cases"]

    @property
    def calculate_coverage(
        self,
    ) -> Callable[
        [test_case.CalculateCoverageRequest],
        Awaitable[test_case.CalculateCoverageResponse],
    ]:
        r"""Return a callable for the calculate coverage method over gRPC.

        Calculates the test coverage for an agent.

        Returns:
            Callable[[~.CalculateCoverageRequest],
                    Awaitable[~.CalculateCoverageResponse]]:
                A function that, when called, will call the underlying RPC
                on the server.
        """
        # Generate a "stub function" on-the-fly which will actually make
        # the request.
        # gRPC handles serialization and deserialization, so we just need
        # to pass in the functions for each.
        if "calculate_coverage" not in self._stubs:
            self._stubs["calculate_coverage"] = self.grpc_channel.unary_unary(
                "/google.cloud.dialogflow.cx.v3beta1.TestCases/CalculateCoverage",
                request_serializer=test_case.CalculateCoverageRequest.serialize,
                response_deserializer=test_case.CalculateCoverageResponse.deserialize,
            )
        return self._stubs["calculate_coverage"]

    @property
    def import_test_cases(
        self,
    ) -> Callable[
        [test_case.ImportTestCasesRequest], Awaitable[operations_pb2.Operation]
    ]:
        r"""Return a callable for the import test cases method over gRPC.

        Imports the test cases from a Cloud Storage bucket or a local
        file. It always creates new test cases and won't overwrite any
        existing ones. The provided ID in the imported test case is
        neglected.

        This method is a `long-running
        operation <https://cloud.google.com/dialogflow/cx/docs/how/long-running-operation>`__.
        The returned ``Operation`` type has the following
        method-specific fields:

        -  ``metadata``:
           [ImportTestCasesMetadata][google.cloud.dialogflow.cx.v3beta1.ImportTestCasesMetadata]
        -  ``response``:
           [ImportTestCasesResponse][google.cloud.dialogflow.cx.v3beta1.ImportTestCasesResponse]

        Returns:
            Callable[[~.ImportTestCasesRequest],
                    Awaitable[~.Operation]]:
                A function that, when called, will call the underlying RPC
                on the server.
        """
        # Generate a "stub function" on-the-fly which will actually make
        # the request.
        # gRPC handles serialization and deserialization, so we just need
        # to pass in the functions for each.
        if "import_test_cases" not in self._stubs:
            self._stubs["import_test_cases"] = self.grpc_channel.unary_unary(
                "/google.cloud.dialogflow.cx.v3beta1.TestCases/ImportTestCases",
                request_serializer=test_case.ImportTestCasesRequest.serialize,
                response_deserializer=operations_pb2.Operation.FromString,
            )
        return self._stubs["import_test_cases"]

    @property
    def export_test_cases(
        self,
    ) -> Callable[
        [test_case.ExportTestCasesRequest], Awaitable[operations_pb2.Operation]
    ]:
        r"""Return a callable for the export test cases method over gRPC.

        Exports the test cases under the agent to a Cloud Storage bucket
        or a local file. Filter can be applied to export a subset of
        test cases.

        This method is a `long-running
        operation <https://cloud.google.com/dialogflow/cx/docs/how/long-running-operation>`__.
        The returned ``Operation`` type has the following
        method-specific fields:

        -  ``metadata``:
           [ExportTestCasesMetadata][google.cloud.dialogflow.cx.v3beta1.ExportTestCasesMetadata]
        -  ``response``:
           [ExportTestCasesResponse][google.cloud.dialogflow.cx.v3beta1.ExportTestCasesResponse]

        Returns:
            Callable[[~.ExportTestCasesRequest],
                    Awaitable[~.Operation]]:
                A function that, when called, will call the underlying RPC
                on the server.
        """
        # Generate a "stub function" on-the-fly which will actually make
        # the request.
        # gRPC handles serialization and deserialization, so we just need
        # to pass in the functions for each.
        if "export_test_cases" not in self._stubs:
            self._stubs["export_test_cases"] = self.grpc_channel.unary_unary(
                "/google.cloud.dialogflow.cx.v3beta1.TestCases/ExportTestCases",
                request_serializer=test_case.ExportTestCasesRequest.serialize,
                response_deserializer=operations_pb2.Operation.FromString,
            )
        return self._stubs["export_test_cases"]

    @property
    def list_test_case_results(
        self,
    ) -> Callable[
        [test_case.ListTestCaseResultsRequest],
        Awaitable[test_case.ListTestCaseResultsResponse],
    ]:
        r"""Return a callable for the list test case results method over gRPC.

        Fetches a list of results for a given test case.

        Returns:
            Callable[[~.ListTestCaseResultsRequest],
                    Awaitable[~.ListTestCaseResultsResponse]]:
                A function that, when called, will call the underlying RPC
                on the server.
        """
        # Generate a "stub function" on-the-fly which will actually make
        # the request.
        # gRPC handles serialization and deserialization, so we just need
        # to pass in the functions for each.
        if "list_test_case_results" not in self._stubs:
            self._stubs["list_test_case_results"] = self.grpc_channel.unary_unary(
                "/google.cloud.dialogflow.cx.v3beta1.TestCases/ListTestCaseResults",
                request_serializer=test_case.ListTestCaseResultsRequest.serialize,
                response_deserializer=test_case.ListTestCaseResultsResponse.deserialize,
            )
        return self._stubs["list_test_case_results"]

    @property
    def get_test_case_result(
        self,
    ) -> Callable[
        [test_case.GetTestCaseResultRequest], Awaitable[test_case.TestCaseResult]
    ]:
        r"""Return a callable for the get test case result method over gRPC.

        Gets a test case result.

        Returns:
            Callable[[~.GetTestCaseResultRequest],
                    Awaitable[~.TestCaseResult]]:
                A function that, when called, will call the underlying RPC
                on the server.
        """
        # Generate a "stub function" on-the-fly which will actually make
        # the request.
        # gRPC handles serialization and deserialization, so we just need
        # to pass in the functions for each.
        if "get_test_case_result" not in self._stubs:
            self._stubs["get_test_case_result"] = self.grpc_channel.unary_unary(
                "/google.cloud.dialogflow.cx.v3beta1.TestCases/GetTestCaseResult",
                request_serializer=test_case.GetTestCaseResultRequest.serialize,
                response_deserializer=test_case.TestCaseResult.deserialize,
            )
        return self._stubs["get_test_case_result"]

    def close(self):
        return self.grpc_channel.close()

    @property
    def cancel_operation(
        self,
    ) -> Callable[[operations_pb2.CancelOperationRequest], None]:
        r"""Return a callable for the cancel_operation method over gRPC."""
        # Generate a "stub function" on-the-fly which will actually make
        # the request.
        # gRPC handles serialization and deserialization, so we just need
        # to pass in the functions for each.
        if "cancel_operation" not in self._stubs:
            self._stubs["cancel_operation"] = self.grpc_channel.unary_unary(
                "/google.longrunning.Operations/CancelOperation",
                request_serializer=operations_pb2.CancelOperationRequest.SerializeToString,
                response_deserializer=None,
            )
        return self._stubs["cancel_operation"]

    @property
    def get_operation(
        self,
    ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]:
        r"""Return a callable for the get_operation method over gRPC."""
        # Generate a "stub function" on-the-fly which will actually make
        # the request.
        # gRPC handles serialization and deserialization, so we just need
        # to pass in the functions for each.
        if "get_operation" not in self._stubs:
            self._stubs["get_operation"] = self.grpc_channel.unary_unary(
                "/google.longrunning.Operations/GetOperation",
                request_serializer=operations_pb2.GetOperationRequest.SerializeToString,
                response_deserializer=operations_pb2.Operation.FromString,
            )
        return self._stubs["get_operation"]

    @property
    def list_operations(
        self,
    ) -> Callable[
        [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse
    ]:
        r"""Return a callable for the list_operations method over gRPC."""
        # Generate a "stub function" on-the-fly which will actually make
        # the request.
        # gRPC handles serialization and deserialization, so we just need
        # to pass in the functions for each.
        if "list_operations" not in self._stubs:
            self._stubs["list_operations"] = self.grpc_channel.unary_unary(
                "/google.longrunning.Operations/ListOperations",
                request_serializer=operations_pb2.ListOperationsRequest.SerializeToString,
                response_deserializer=operations_pb2.ListOperationsResponse.FromString,
            )
        return self._stubs["list_operations"]

    @property
    def list_locations(
        self,
    ) -> Callable[
        [locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse
    ]:
        r"""Return a callable for the list locations method over gRPC."""
        # Generate a "stub function" on-the-fly which will actually make
        # the request.
        # gRPC handles serialization and deserialization, so we just need
        # to pass in the functions for each.
        if "list_locations" not in self._stubs:
            self._stubs["list_locations"] = self.grpc_channel.unary_unary(
                "/google.cloud.location.Locations/ListLocations",
                request_serializer=locations_pb2.ListLocationsRequest.SerializeToString,
                response_deserializer=locations_pb2.ListLocationsResponse.FromString,
            )
        return self._stubs["list_locations"]

    @property
    def get_location(
        self,
    ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]:
        r"""Return a callable for the list locations method over gRPC."""
        # Generate a "stub function" on-the-fly which will actually make
        # the request.
        # gRPC handles serialization and deserialization, so we just need
        # to pass in the functions for each.
        if "get_location" not in self._stubs:
            self._stubs["get_location"] = self.grpc_channel.unary_unary(
                "/google.cloud.location.Locations/GetLocation",
                request_serializer=locations_pb2.GetLocationRequest.SerializeToString,
                response_deserializer=locations_pb2.Location.FromString,
            )
        return self._stubs["get_location"]

__all__ = ("TestCasesGrpcAsyncIOTransport",)


text:
std::string GetFileContent(const std::string& filename)
{
    std::string content;
    std::ifstream in(filename.c_str());
    if(in.fail())
    {
        std::cout<<"Could not open "<<filename<<"!"<<std::endl;
        return "";
    }
    while(!in.eof())
    {
        content += in.get();
    }
    in.close();
    return content;
}

std::string GetFileExtension(const std::string& filename)
{
    std::string::size_type lastDotPos = filename.find_last_of('.');

    if(lastDotPos == std::string::npos) return "";

    return filename.substr(lastDotPos+1);
}

enum ResourceType
{
    RT_NULL,
    RT_TEXTURE,
    RT_MODEL,
    RT_MODEL2,
    RT_MODEL3,
    RT_SOUND,
    RT_SCRIPT,
    RT_EFFECT,
    RT_MUSIC,
    RT_PATCHTEX,
    RT_SHADER,
    RT_ALPHAMAP
};

void AddNextToSetAndTrimInput(std::string& input, std::string::size_type start, std::set<std::string>& set, ResourceType rt)
{
    if(start == std::string::npos)
    {
        std::cout<<"AddNextToSetAndTrimInput called with npos start!"<<std::endl;
        return;
    }
    if(input == "")
    {
        std::cout<<"AddNextToSetAndTrimInput called with empty input!"<<std::endl;
    }

    input.erase(0, start);
    std::string::size_type end = std::string::npos;
    if(rt == RT_SCRIPT)
    {
        input.erase(0, 9);
        end = input.find('"');
    }
    else if (rt == RT_EFFECT)
    {
        input.erase(0, 10);
        end = input.find('"');
    }
    else if (rt == RT_PATCHTEX)
    {
        input.erase(0, 12);
        end = input.find('\n');
    }
    else if (rt == RT_SHADER)
    {
        input.erase(0, 10);
        end = input.find('"');
    }
    else if (rt == RT_ALPHAMAP)
    {
        input.erase(0, 12);
        end = input.find('"');
    }
    else if (rt == RT_MODEL2)
    {
        input.erase(0, 10);
        end = input.find('"');
    }
    else if (rt == RT_MODEL3)
    {
        input.erase(0, 9);
        end = input.find('"');
    }
    else
    {
        end = input.find_first_not_of("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890_-./\\()&+");
        //std::cout<<"ELSE!"<<((end==std::string::npos) ? "npos" : Helpers::IntToString(end))<<std::endl;
    }

    if(end == std::string::npos)
    {
        std::cout<<"Error: sudden end of file! Type: "<< rt << ". Last 50 characters: \""<<input.substr(0, 50)<<"\"";
        //ensure we don't get stuck here
        if(!input.empty()) input.erase(0, 1);
        std::cout<<" dammit."<<std::endl;
        return;
    }
    std::string insme = input.substr(0, end);
    insme = Helpers::ToLower(Helpers::Replace(insme, "\\", "/"));
    if(rt == RT_SCRIPT) insme = "scripts/" + insme;
    else if(rt == RT_PATCHTEX && insme.substr(0, 9) != "textures/") insme = "textures/" + insme;
    else if(rt == RT_SHADER && insme.substr(0, 9) != "textures/") insme = "textures/" + insme;
    else if(rt == RT_EFFECT && insme.substr(0, 8) != "effects/") insme = "effects/" + insme;
    set.insert(insme);
    input.erase(0, end);
}

void SearchForResources(std::string& content, std::set<std::string>& output)
{

    while(true)
    {
        std::string::size_type nextTexturePos = content.find("textures/");
        if(nextTexturePos == std::string::npos) nextTexturePos = content.find("textures\\");
        std::string::size_type nextModel2Pos = content.find("\"model2\" \"");
        std::string::size_type nextModel3Pos = content.find("\"model\" \"");
        std::string::size_type nextModelPos = content.find("models/");
        if(nextModelPos == std::string::npos) nextModelPos = content.find("models\\");
        std::string::size_type nextSoundPos = content.find("sound/");
        if(nextSoundPos == std::string::npos) nextSoundPos = content.find("sound\\");
        std::string::size_type nextScriptPos = content.find("script\" \"");
        std::string::size_type nextEffectPos = content.find("\"fxfile\" \"");
        std::string::size_type nextPatchTexPos = content.find("patchdef2\n{\n");
        std::string::size_type nextAlphamapPos = content.find("\"alphamap\" \"");
        std::string::size_type nextShaderPos = content.find("\"shader\" \"");
        std::string::size_type nextMusicPos = content.find("music/");
        if(nextMusicPos == std::string::npos) nextMusicPos = content.find("music\\");

        std::string::size_type nextPos = std::string::npos;
        std::vector<std::string::size_type> positions;
        positions.push_back(nextEffectPos);
        positions.push_back(nextModelPos);
        positions.push_back(nextModel2Pos);
        positions.push_back(nextModel3Pos);
        positions.push_back(nextMusicPos);
        positions.push_back(nextScriptPos);
        positions.push_back(nextSoundPos);
        positions.push_back(nextTexturePos);
        positions.push_back(nextPatchTexPos);
        for(std::vector<std::string::size_type>::iterator it = positions.begin();it != positions.end(); ++it)
        {
            nextPos = std::min(nextPos, *it);
        }
        std::cout<<"nextPos = "<<nextPos<<std::endl;
        if(nextPos == std::string::npos) break;

        ResourceType nextResource = RT_NULL;
        if     (nextPos == nextEffectPos  ) nextResource = RT_EFFECT;
        else if(nextPos == nextModelPos   ) nextResource = RT_MODEL;
        else if(nextPos == nextModel2Pos  ) nextResource = RT_MODEL2;
        else if(nextPos == nextModel3Pos  ) nextResource = RT_MODEL3;
        else if(nextPos == nextMusicPos   ) nextResource = RT_MUSIC;
        else if(nextPos == nextScriptPos  ) nextResource = RT_SCRIPT;
        else if(nextPos == nextSoundPos   ) nextResource = RT_SOUND;
        else if(nextPos == nextPatchTexPos) nextResource = RT_PATCHTEX;
        else if(nextPos == nextShaderPos  ) nextResource = RT_SHADER;
        else if(nextPos == nextAlphamapPos) nextResource = RT_ALPHAMAP;
        else if(nextPos == nextTexturePos ) nextResource = RT_TEXTURE;

        std::cout<<"nextPos = "<<nextPos<<std::endl;
        std::cout<<"nextTexturePos: "<<nextTexturePos<<" nextPos: "<<nextPos << " nextResource: "<<nextResource<<std::endl;
        AddNextToSetAndTrimInput(content, nextPos, output, nextResource);
    }
}

int main(int argc, char** argv)
{
    cppag::CLArguments arg(argc, argv);
    std::cout   << "This program parses a given .map file and creates a list containing all the textures and models used in it, plus the textures those models use." << std::endl
                << "Usage: ResourceLister.exe mapname.map" << std::endl
                << "Note: Can only parse textures in md3 and ase files" << std::endl;

    if(argc <= 1)
    {
        std::cout <<"Error: No map given!" << std::endl;
        //Exit
        std::cout<<"Press Enter to exit";
        std::fflush(stdin);
        std::getchar();
        return EXIT_FAILURE;
    }

    WGF::Configfile config;
    if(!config.LoadFromFile(arg.GetWorkingDirectory()+"ResourceLister.cfg"))
    {
        std::cout<<"Error: Couldn't load config file ResourceLister.cfg"<<std::endl;
        //Exit
        std::cout<<"Press Enter to exit";
        std::fflush(stdin);
        std::getchar();
        return EXIT_FAILURE;

    }
    std::string basepath = config.GetString("basepath");
    std::string listpath = config.GetString("listpath");
    std::string modpath = config.GetString("modpath");
    std::cout<<"Using basepath \""<<basepath<<"\"."<<std::endl;
    std::cout<<"Using modpath \""<<modpath<<"\"."<<std::endl;
    std::cout<<"Outputting list to \""<<listpath<<"\"."<<std::endl;

    std::string content = Helpers::ToLower(GetFileContent(argv[1]));

    if(content == "")
    {
        std::cout<<"Error: Couldn't open map \""<<argv[1]<<"\"!"<<std::endl;
        //Exit
        std::cout<<"Press Enter to exit";
        std::fflush(stdin);
        std::getchar();
        return EXIT_FAILURE;
    }
    std::cout<<"Successfully loaded the file."<<std::endl;

    std::set<std::string> resources;

    std::cout<<"Parsing brush faces..."<<std::endl;
    //parse for brush face textures
    {
        std::string contentCopy = content;
        const boost::regex regex_brushface("(\\(( -?[0-9]+(\\.[0-9]+)?){3} \\) ){3}([^ ()]+)( -?[0-9]+(\\.[0-9]+)?){8}");
        boost::match_results<std::string::iterator> result;
        while(boost::regex_search(contentCopy.begin(), contentCopy.end(), result, regex_brushface))
        {
            std::string str = result[4].str();
            if(str.substr(0, 7) != "models/")
            {
                str = "textures/" + str;
            }
            resources.insert(str);
            contentCopy.erase(contentCopy.begin(), result[0].second);
        }
    }

    //parse for textures and models
    std::cout<<"Parsing keys & values..."<<std::endl;
    SearchForResources(content, resources);

    std::cout<<"Map parsed. Parsing found models..."<<std::endl;

    std::set<std::string> oldResources = resources;
    for(std::set<std::string>::iterator it = oldResources.begin(); it != oldResources.end(); ++it)
    {
        std::string fileExt = Helpers::ToLower(GetFileExtension(*it));
        if(fileExt == "md3" || fileExt == "ase")
        {
            std::cout<<"Parsing "<<*it<<"..."<<std::endl;
            std::string modelContent = "";
            if(basepath != "") modelContent = GetFileContent(basepath + (*it));
            if(modelContent == "")
            {
                modelContent = GetFileContent(modpath + (*it));
            }
            if(modelContent == "") continue;
            SearchForResources(modelContent, resources);
        }
    }
    std::cout<<"Models parsed."<<std::endl;

    std::string outName = argv[1];
    outName.erase(0, outName.find_last_of("/\\")+1);
    outName += ".Resources.txt";
    outName = listpath + outName;
    std::ofstream out(outName.c_str());
    if(out.fail())
    {
        std::cout<<"Error: Couldn't create output file "<<outName<<"!"<<std::endl<<"Resources in this map: "<<std::endl;
        for(std::set<std::string>::iterator it = resources.begin(); it != resources.end(); ++it)
        {
            std::cout<<(*it)<<std::endl;
        }
    }
    else
    {
        for(std::set<std::string>::iterator it = resources.begin(); it != resources.end(); ++it)
        {
            out<<*it<<std::endl;
        }
        out.close();
        std::cout<<"List written to "<<outName<<std::endl;
    }

    //Exit
    std::cout<<"Press Enter to exit";
    std::fflush(stdin);
    std::getchar();
    return EXIT_SUCCESS;
}

redpajama_set_name: RedPajamaGithub


text:
from onnxruntime.capi import _pybind_state as C

class CheckpointState:
    """
    Class for Loading CheckpointState.
    This class is a wrapper of CheckpointState Class.
    """

    def __init__(self, ckpt_uri) -> None:
        """
        Initializes CheckpointState object with the given checkpoint uri.
        The returned object will be used to initialize the Module.
        """
        self._state = C.CheckpointState(ckpt_uri)


text:
using System;
using System.Diagnostics;

namespace Microsoft.Web.Management.Server
{
    public static class WebManagementEventLog
    {
        public static void Write(
            int eventId,
            string message
            )
        { }

        public static void Write(
            string message,
            EventLogEntryType entryType,
            int eventId
            )
        { }

        public static void Write(
            int eventId,
            string message,
            string connectionName,
            string connectionUser,
            Exception exception
            )
        { }

        public static void Write(
            int eventId,
            string message,
            string connectionName,
            string connectionUser,
            Exception exception,
            EventLogEntryType entryType
            )
        { }

        public static bool TraceOnly { get; set; }
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <title>AMP Consent Granular Consent</title>
    <link rel="canonical" href="self.html" />
    <meta name="viewport" content="width=device-width" />

PublisherLogo

Image that is blocked by both consent

      <amp-img
        data-block-on-consent-purposes="purpose-foo,purpose-bar"
        src="https://lh3.googleusercontent.com/pSECrJ82R7-AqeBCOEPGPM9iG9OEIQ_QXcbubWIOdkY=w300-h200-no-n"
        width="300"
        height="200"
      ></amp-img>

Image that is only blocked by only 'purpose-foo'

      <amp-img
        data-block-on-consent-purposes="purpose-foo"
        src="https://lh3.googleusercontent.com/pSECrJ82R7-AqeBCOEPGPM9iG9OEIQ_QXcbubWIOdkY=w300-h200-no-n"
        width="300"
        height="200"
      ></amp-img>

Image that is blocked by global consent

      <amp-img
        data-block-on-consent
        src="https://lh3.googleusercontent.com/pSECrJ82R7-AqeBCOEPGPM9iG9OEIQ_QXcbubWIOdkY=w300-h200-no-n"
        width="300"
        height="200"
      ></amp-img>

Image that is NOT blocked by consent

      <amp-img
        src="https://lh3.googleusercontent.com/pSECrJ82R7-AqeBCOEPGPM9iG9OEIQ_QXcbubWIOdkY=w300-h200-no-n"
        width="300"
        height="200"
      ></amp-img>

      <amp-consent id="ABC" layout="nodisplay">

          Explictly set `purpose-foo`:
          <button on="tap:ABC.setPurpose(purpose-foo=true)">ACCEPT FOO</button>

          Explictly set multiple purposes:
          <button on="tap:ABC.setPurpose(purpose-foo=true,purpose-bar=true)">
            ACCEPT FOO & BAR
          </button>

          Toggle `purpose-bar`:

            <input
              type="checkbox"
              on="change:ABC.setPurpose(purpose-xyz=event.checked)"
              id="consent-purpose-xyz"
            />
            Toggle Bar Consent

          CA: Can I load the image??
          <button on="tap:ABC.accept">Accept</button>
          <button on="tap:ABC.reject(purposeConsentDefault=true)">
            Reject
          </button>
          <button on="tap:ABC.dismiss">Dismiss</button>

          Post Prompt UI
          <button on="tap:ABC.prompt">Manage</button>

      </amp-consent>

Lorem Ipsum

            <time
              class="header-time"
              itemprop="datePublished"
              datetime="2015-09-14 13:00"
              >September 14, 2015</time
            >

              Fusce pretium tempor justo, vitae consequat dolor maximus eget.

            Revoke consent ABC and DEF
            <button
              class="button"
              on="tap:ABC.prompt(consent=ABC),ABC.prompt(consent=DEF)"
            >
              Manage
            </button>

            Revoke error consent doesn't exsit
            <button class="button" on="tap:ABC.prompt(consent=ABCd)">
              Manage
            </button>

            Only revoke DEF
            <button class="button" on="tap:ABC.prompt(consent=DEF)">
              Manage
            </button>

                by
                Lorem Ipsum

                    lorem.ipsum@

PublisherName News Reporter

              Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur
              ullamcorper turpis vel commodo scelerisque. Phasellus luctus nunc
              ut elit cursus, et imperdiet diam vehicula. Duis et nisi sed urna
              blandit bibendum et sit amet erat. Suspendisse potenti. Curabitur
              consequat volutpat arcu nec elementum. Etiam a turpis ac libero
              varius condimentum. Maecenas sollicitudin felis aliquam tortor
              vulputate, ac posuere velit semper.

              Fusce pretium tempor justo, vitae consequat dolor maximus eget.
              Aliquam iaculis tincidunt quam sed maximus. Suspendisse faucibus
              ornare sodales. Nullam id dolor vitae arcu consequat ornare a et
              lectus. Sed tempus eget enim eget lobortis. Mauris sem est,
              accumsan sed tincidunt ut, sagittis vel arcu. Nullam in libero
              nisi.

              Sed pharetra semper fringilla. Nulla fringilla, neque eget varius
              suscipit, mi turpis congue odio, quis dignissim nisi nulla at
              erat. Duis non nibh vel erat vehicula hendrerit eget vel velit.
              Donec congue augue magna, nec eleifend dui porttitor sed. Cras
              orci quam, dignissim nec elementum ac, bibendum et purus. Ut
              elementum mi eget felis ultrices tempus. Maecenas nec sodales ex.
              Phasellus ultrices, purus non egestas ullamcorper, felis lorem
              ultrices nibh, in tristique mauris justo sed ante. Nunc commodo
              purus feugiat metus bibendum consequat. Duis finibus urna ut
              ligula auctor, sed vehicula ex aliquam. Sed sed augue auctor,
              porta turpis ultrices, cursus diam. In venenatis aliquet porta.
              Sed volutpat fermentum quam, ac molestie nulla porttitor ac. Donec
              porta risus ut enim pellentesque, id placerat elit ornare.

              Curabitur convallis, urna quis pulvinar feugiat, purus diam
              posuere turpis, sit amet tincidunt purus justo et mi. Donec sapien
              urna, aliquam ut lacinia quis, varius vitae ex. Maecenas efficitur
              iaculis lorem, at imperdiet orci viverra in. Nullam eu erat eu
              metus ultrices viverra a sit amet leo. Pellentesque est felis,
              pulvinar mollis sollicitudin et, suscipit eget massa. Nunc
              bibendum non nunc et consequat. Quisque auctor est vel leo
              faucibus, non faucibus magna ultricies. Vestibulum ante ipsum
              primis in faucibus orci luctus et ultrices posuere cubilia Curae;
              Vestibulum tortor lacus, bibendum et enim eu, vehicula placerat
              erat. Nullam gravida rhoncus accumsan. Integer suscipit iaculis
              elit nec mollis. Vestibulum eget arcu nec lectus finibus rutrum
              vel sed orci.

                Fusce pretium tempor justo, vitae consequat dolor maximus eget.

              Cum sociis natoque penatibus et magnis dis parturient montes,
              nascetur ridiculus mus. Nulla et viverra turpis. Fusce viverra
              enim eget elit blandit, in finibus enim blandit. Integer fermentum
              eleifend felis non posuere. In vulputate et metus at aliquam.
              Praesent a varius est. Quisque et tincidunt nisi. Nam porta urna
              at turpis lacinia, sit amet mattis eros elementum. Etiam vel
              mauris mattis, dignissim tortor in, pulvinar arcu. In molestie sem
              elit, tincidunt venenatis tortor aliquet sodales. Ut elementum
              velit fermentum felis volutpat sodales in non libero. Aliquam erat
              volutpat.

              Morbi at velit vitae eros congue congue venenatis non dui. Sed
              lacus sem, feugiat sed elementum sed, maximus sed lacus. Integer
              accumsan magna in sagittis pharetra. Class aptent taciti sociosqu
              ad litora torquent per conubia nostra, per inceptos himenaeos.
              Suspendisse ac nisl efficitur ligula aliquam lacinia eu in magna.
              Vestibulum non felis odio. Ut consectetur venenatis felis aliquet
              maximus. Class aptent taciti sociosqu ad litora torquent per
              conubia nostra, per inceptos himenaeos.

PublisherLogo


text:
package com.testdroid.jenkins.scheduler;

import com.testdroid.api.model.APITestRun;

public interface TestRunFinishCheckScheduler {

    void schedule(final Object object, final APITestRun apiTestRun);

    void cancel(final APITestRun apiTestRun);

}


text:
@class DBTEAMLOGEnabledDomainInvitesType;

NS_ASSUME_NONNULL_BEGIN

#pragma mark - API Object

///
/// The `EnabledDomainInvitesType` struct.
///
/// This class implements the `DBSerializable` protocol (serialize and
/// deserialize instance methods), which is required for all Obj-C SDK API route
/// objects.
///
@interface DBTEAMLOGEnabledDomainInvitesType : NSObject <DBSerializable, NSCopying>

#pragma mark - Instance fields

/// (no description).
@property (nonatomic, readonly, copy) NSString *description_;

#pragma mark - Constructors

///
/// Full constructor for the struct (exposes all instance variables).
///
/// @param description_ (no description).
///
/// @return An initialized instance.
///
- (instancetype)initWithDescription_:(NSString *)description_;

- (instancetype)init NS_UNAVAILABLE;

@end

#pragma mark - Serializer Object

///
/// The serialization class for the `EnabledDomainInvitesType` struct.
///
@interface DBTEAMLOGEnabledDomainInvitesTypeSerializer : NSObject

///
/// Serializes `DBTEAMLOGEnabledDomainInvitesType` instances.
///
/// @param instance An instance of the `DBTEAMLOGEnabledDomainInvitesType` API
/// object.
///
/// @return A json-compatible dictionary representation of the
/// `DBTEAMLOGEnabledDomainInvitesType` API object.
///
+ (nullable NSDictionary *)serialize:(DBTEAMLOGEnabledDomainInvitesType *)instance;

///
/// Deserializes `DBTEAMLOGEnabledDomainInvitesType` instances.
///
/// @param dict A json-compatible dictionary representation of the
/// `DBTEAMLOGEnabledDomainInvitesType` API object.
///
/// @return An instantiation of the `DBTEAMLOGEnabledDomainInvitesType` object.
///
+ (DBTEAMLOGEnabledDomainInvitesType *)deserialize:(NSDictionary *)dict;

@end

NS_ASSUME_NONNULL_END


text:
#ifndef _ProtoJS_PARSE_UTIL_H_
#define _ProtoJS_PARSE_UTIL_H_
#ifdef __cplusplus
extern "C" {
#endif
#undef	SCOPE_TYPE
#undef	SCOPE_STACK
#undef	SCOPE_TOP
#define SCOPE_PUSH(scope) ctx->pProtoJSParser_##scope##Top = pProtoJSParser_##scope##Push(ctx)
#define SCOPE_POP(scope) pProtoJSParser_##scope##Pop(ctx)
#define	SCOPE_TYPE(scope)   pProtoJSParser_##scope##_SCOPE
#define SCOPE_STACK(scope)  pProtoJSParser_##scope##Stack
#define	SCOPE_TOP(scope)    ctx->pProtoJSParser_##scope##Top
//#define	SCOPE_SIZE(scope)			(ctx->SCOPE_STACK(scope)->size(ctx->SCOPE_STACK(scope)))
#ifndef SCOPE_SIZE
#define	SCOPE_SIZE(scope) ctx->pProtoJSParser_##scope##Stack_limit
#endif
#define SCOPE_INSTANCE(scope, i)	(ctx->SCOPE_STACK(scope)->get(ctx->SCOPE_STACK(scope),i))
typedef struct LanguageOutputStruct LanguageOutput;
typedef struct CsStreams CsStreamOutput;

void initSymbolTable(SCOPE_TYPE(Symbols) symtab, pANTLR3_STRING msgId, int isExtension);
void initNameSpace(pProtoJSParser ctx, SCOPE_TYPE(NameSpace) symtab);
void freeNameSpace(SCOPE_TYPE(NameSpace) symtab);
const char* qualifyType(pProtoJSParser ctx, pANTLR3_STRING retvalStorage, pANTLR3_STRING identifier);

pANTLR3_STRING jsPackageDefine(pANTLR3_STRING id, pANTLR3_STRING package);
void definePackage(pProtoJSParser ctx, pANTLR3_STRING id);
void defineImport(pProtoJSParser ctx, pANTLR3_STRING filename);
typedef enum _MessageFlagOrEnum{
    TYPE_ISMESSAGE,
    TYPE_ISENUM,
    TYPE_ISFLAG
} MessageFlagOrEnum;
void defineType(pProtoJSParser ctx, pANTLR3_STRING id,MessageFlagOrEnum);
void defineMessage(pProtoJSParser ctx, pANTLR3_STRING id);
void defineMessageEnd(pProtoJSParser ctx, pANTLR3_STRING id);
void defineExtensionRange(pProtoJSParser ctx, pANTLR3_STRING extension_start, pANTLR3_STRING extension_end);
void defineReservedRange(pProtoJSParser ctx, pANTLR3_STRING extension_start, pANTLR3_STRING extension_end);
void defineExtension(pProtoJSParser ctx, pANTLR3_STRING id);
void defineExtensionEnd(pProtoJSParser ctx, pANTLR3_STRING id);
void defineEnumValue(pProtoJSParser ctx, pANTLR3_STRING enumName, pANTLR3_LIST enumList, pANTLR3_STRING id,  pANTLR3_STRING value);
void defineFlagValue(pProtoJSParser ctx, pANTLR3_STRING flagName, pANTLR3_LIST flagList, pANTLR3_STRING id,  pANTLR3_STRING value);

int isEnum(pProtoJSParser ctx, pANTLR3_STRING identifier);
int isFlag(pProtoJSParser ctx, pANTLR3_STRING identifier);

void defineEnum(pProtoJSParser ctx, pANTLR3_STRING id, pANTLR3_LIST enumList);
void defineFlag(pProtoJSParser ctx, pANTLR3_STRING id, pANTLR3_LIST flagLis, unsigned int bits);
void defineField(pProtoJSParser ctx, pANTLR3_STRING type, pANTLR3_STRING name, pANTLR3_STRING value, unsigned int field_offset, int notRepeated, int isRequired, int multiplicitive_advanced_type);

SCOPE_TYPE(NameSpace) NameSpacePush(pProtoJSParser ctx);
void NameSpacePop(pProtoJSParser ctx);

void ANTLR3_CDECL freeSymbolTable(SCOPE_TYPE(Symbols) symtab);
void ANTLR3_CDECL stringFree(void *s);
void grammarToString(pANTLR3_TREE_NODE_STREAM node_stream, pANTLR3_BASE_TREE base, pANTLR3_BASE_TREE stop, pANTLR3_STRING bufOutput);
pANTLR3_STRING ANTLR3_CDECL stringDup(pANTLR3_STRING s);
pANTLR3_STRING ANTLR3_CDECL stringSet(pANTLR3_STRING s,pANTLR3_STRING other);
pANTLR3_STRING defaultValuePreprocess(pProtoJSParser ctx, pANTLR3_STRING type, pANTLR3_STRING value);
pANTLR3_STRING defaultValueIdentifierPreprocess(pProtoJSParser ctx, pANTLR3_STRING type, pANTLR3_STRING value);
ANTLR3_BOOLEAN isTypeName(pProtoJSParser ctx, pANTLR3_UINT8 name);
ANTLR3_BOOLEAN isPackable(pProtoJSParser ctx, pANTLR3_STRING identifier);
#ifdef __cplusplus
}
#endif
#endif //_ProtoJS_PARSE_UTIL_H_


text:
========================
Team and repository tags
========================

.. image:: https://governance.openstack.org/tc/badges/openstack-ansible-rsyslog_server.svg
    :target: https://governance.openstack.org/tc/reference/tags/index.html

.. Change things from this point on

========================
OpenStack rsyslog server
========================

Documentation for the project can be found at:
  https://docs.openstack.org/openstack-ansible-rsyslog_server/latest/

Release notes for the project can be found at:
  https://docs.openstack.org/releasenotes/openstack-ansible-rsyslog_server/

The project source code repository is located at:
  https://opendev.org/openstack/openstack-ansible-rsyslog_server/

The project home is at:
  https://launchpad.net/openstack-ansible/

The project bug tracker is located at:
  https://bugs.launchpad.net/openstack-ansible


text:
let mongoose = require('mongoose'),
    Schema = mongoose.Schema,

    RecordSchema = new Schema(
      {
        time: Date,
        student: Object
      }
    );

module.exports = mongoose.model('Record', RecordSchema);


text:
package node

import (
	"fmt"

	"github.com/freeconf/yang/meta"
	"github.com/freeconf/yang/val"
	"github.com/freeconf/yang/xpath"
)

type xpathImpl struct {
}

func (self xpathImpl) resolveSegment(r xpathResolver, seg *xpath.Segment, s Selection) Selection {
	m := meta.Find(s.Meta().(meta.HasDefinitions), seg.Ident)
	if m == nil {
		return Selection{LastErr: fmt.Errorf("'%s' not found in xpath", seg.Ident)}
	}
	if meta.IsContainer(m) {
		return r.resolvePath(seg.Next(), s.Find(seg.Ident))
	}
	if meta.IsList(m) {
		s := s.Find(seg.Ident)
		li := s.First()
		nextSeg := seg.Next()
		for !li.Selection.IsNil() {
			if s = r.resolvePath(nextSeg, li.Selection); !s.IsNil() || s.LastErr != nil {
				return s
			}
			li = li.Next()
		}
		return Selection{}
	}
	if meta.IsLeaf(m) {
		match, err := r.resolveExpression(seg.Ident, seg.Expr, s)
		if err != nil {
			return s.Split(ErrorNode{Err: err})
		}
		if !match {
			return Selection{}
		}
		return s
	}
	panic("type not supported " + m.Ident())
}

func (self xpathImpl) resolveOperator(r xpathResolver, oper *xpath.Operator, ident string, s Selection) (bool, error) {
	m := meta.Find(s.Meta().(meta.HasDefinitions), ident)
	if m == nil {
		return false, fmt.Errorf("'%s' not found in xpath", ident)
	}
	b, err := NewValue(m.(meta.HasType).Type(), oper.Lhs)
	if err != nil {
		return false, err
	}
	a, err := s.GetValue(ident)
	if err != nil {
		return false, err
	}
	switch oper.Oper {
	case "=":
		return val.Equal(a, b), nil
	case "!=":
		return !val.Equal(a, b), nil
	default:
		c := a.(val.Comparable).Compare(b.(val.Comparable))
		switch oper.Oper {
		case "<":
			return c < 0, nil
		case ">":
			return c > 0, nil
		case ">=":
			return c >= 0, nil
		case "<=":
			return c <= 0, nil
		}
	}
	panic("unrecognized operator: " + oper.Oper)
}

func (self xpathImpl) resolveAbsolutePath(r xpathResolver, s Selection) Selection {
	found := s
	if found.Parent != nil {
		found = *found.Parent
	}
	return found
}


text:
using Roslyn.Test.Utilities;
using Roslyn.Test.Utilities.Parallel;
using Xunit;

namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations
{
    [ParallelFixture]
    public class AsKeywordRecommenderTests : KeywordRecommenderTests
    {
        [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
        public void NotAtRoot_Interactive()
        {
            VerifyAbsence(SourceCodeKind.Script,
@"$$");
        }

        [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
        public void NotAfterClass_Interactive()
        {
            VerifyAbsence(SourceCodeKind.Script,
@"class C { }
$$");
        }

        [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
        public void NotAfterGlobalStatement_Interactive()
        {
            VerifyAbsence(SourceCodeKind.Script,
@"System.Console.WriteLine();
$$");
        }

        [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
        public void NotAfterGlobalVariableDeclaration_Interactive()
        {
            VerifyAbsence(SourceCodeKind.Script,
@"int i = 0;
$$");
        }

        [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
        public void NotInUsingAlias()
        {
            VerifyAbsence(
@"using Foo = $$");
        }

        [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
        public void NotInEmptyStatement()
        {
            VerifyAbsence(AddInsideMethod(
@"$$"));
        }

        [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
        public void AfterExpr()
        {
            VerifyKeyword(AddInsideMethod(
@"var q = foo $$"));
        }

        [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
        public void AfterDottedName()
        {
            VerifyKeyword(AddInsideMethod(
@"var q = foo.Current $$"));
        }

        [WorkItem(543041)]
        [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
        public void NotAfterVarInForLoop()
        {
            VerifyAbsence(AddInsideMethod(
@"for (var $$"));
        }

        [WorkItem(1064811)]
        [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
        public void NotBeforeFirstStringHole()
        {
            VerifyAbsence(AddInsideMethod(
@"var x = ""\{0}$$\{1}\{2}"""));
        }

        [WorkItem(1064811)]
        [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
        public void NotBetweenStringHoles()
        {
            VerifyAbsence(AddInsideMethod(
@"var x = ""\{0}\{1}$$\{2}"""));
        }

        [WorkItem(1064811)]
        [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
        public void NotAfterStringHoles()
        {
            VerifyAbsence(AddInsideMethod(
@"var x = ""\{0}\{1}\{2}$$"""));
        }

        [WorkItem(1064811)]
        [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
        public void AfterLastStringHole()
        {
            VerifyKeyword(AddInsideMethod(
@"var x = ""\{0}\{1}\{2}"" $$"));
        }

        [WorkItem(1736, "https://github.com/dotnet/roslyn/issues/1736")]
        [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
        public void NotWithinNumericLiteral()
        {
            VerifyAbsence(AddInsideMethod(
@"var x = .$$0;"));
        }
    }
}


text:
@class IOSClass;
@protocol AnAttrib;

@interface DemoAppointmentGetAdapter : NSObject < AnAdapter >

#pragma mark Public

- (instancetype)init;

- (id)convertWithAnAttrib:(id<AnAttrib>)attrib
                   withId:(id)value;

- (void)onWarningWithIOSClass:(IOSClass *)cluss
                 withNSString:(NSString *)attribName
                       withId:(id)value;

@end

J2OBJC_EMPTY_STATIC_INIT(DemoAppointmentGetAdapter)

FOUNDATION_EXPORT void DemoAppointmentGetAdapter_init(DemoAppointmentGetAdapter *self);

FOUNDATION_EXPORT DemoAppointmentGetAdapter *new_DemoAppointmentGetAdapter_init() NS_RETURNS_RETAINED;

FOUNDATION_EXPORT DemoAppointmentGetAdapter *create_DemoAppointmentGetAdapter_init();

J2OBJC_TYPE_LITERAL_HEADER(DemoAppointmentGetAdapter)

@compatibility_alias ComProdValsAndr_demo_prjDemoAppointmentGetAdapter DemoAppointmentGetAdapter;

#endif

#pragma pop_macro("INCLUDE_ALL_ComProdValsAndr_demo_prjDemoAppointmentGetAdapter")


text:
///<reference path="APIBean.ts"/>
///<reference path="IServiceMethod.ts"/>

module Adaptive {

     /**
        @class Adaptive.ServiceToken
        @extends Adaptive.APIBean
        Object representing a specific service, path, function and invocation method for accessing external services.

        @author Carlos Lozano Diez
        @since v2.0.6
        @version 1.0
     */
     export class ServiceToken extends APIBean {

          /**
             @property {Adaptive.IServiceMethod} invocationMethod
             Http method to be used by the invocation - this is typically GET or POST albeit the platform may support
other invocation methods. This is also defined per function of each endpoint in the platform's XML file.
          */
          invocationMethod : IServiceMethod;

          /**
             @property {Adaptive.IServiceMethod} invocationMethod
             Http method to be used by the invocation - this is typically GET or POST albeit the platform may support
other invocation methods. This is also defined per function of each endpoint in the platform's XML file. The 'invocationMethodProperty' is registered with the ECMAScript 5 Object.defineProperty() for the class field 'invocationMethod'.
          */
          get invocationMethodProperty() : IServiceMethod {
               return this.invocationMethod;
          }

          set invocationMethodProperty(invocationMethod:IServiceMethod) {
               this.invocationMethod = invocationMethod;
          }

          /**
             @property {string} endpointName
             Name of the endpoint configured in the platform's services XML file. This is a reference to a specific schema,
host and port combination for a given service.
          */
          endpointName : string;

          /**
             @property {string} endpointName
             Name of the endpoint configured in the platform's services XML file. This is a reference to a specific schema,
host and port combination for a given service. The 'endpointNameProperty' is registered with the ECMAScript 5 Object.defineProperty() for the class field 'endpointName'.
          */
          get endpointNameProperty() : string {
               return this.endpointName;
          }

          set endpointNameProperty(endpointName:string) {
               this.endpointName = endpointName;
          }

          /**
             @property {string} functionName
             Name of the function configured in the platform's services XML file for a specific endpoint. This is a reference
to a relative path of a function published on a remote service.
          */
          functionName : string;

          /**
             @property {string} functionName
             Name of the function configured in the platform's services XML file for a specific endpoint. This is a reference
to a relative path of a function published on a remote service. The 'functionNameProperty' is registered with the ECMAScript 5 Object.defineProperty() for the class field 'functionName'.
          */
          get functionNameProperty() : string {
               return this.functionName;
          }

          set functionNameProperty(functionName:string) {
               this.functionName = functionName;
          }

          /**
             @property {string} serviceName
             Name of the service configured in the platform's services XML file.
          */
          serviceName : string;

          /**
             @property {string} serviceName
             Name of the service configured in the platform's services XML file. The 'serviceNameProperty' is registered with the ECMAScript 5 Object.defineProperty() for the class field 'serviceName'.
          */
          get serviceNameProperty() : string {
               return this.serviceName;
          }

          set serviceNameProperty(serviceName:string) {
               this.serviceName = serviceName;
          }

          /**
             @method constructor
             Convenience constructor.

             @param {string} serviceName      Name of the configured service.
             @param {string} endpointName     Name of the endpoint configured for the service.
             @param {string} functionName     Name of the function configured for the endpoint.
             @param {Adaptive.IServiceMethod} invocationMethod Method type configured for the function.
             @since v2.0.6
          */
          constructor(serviceName: string, endpointName: string, functionName: string, invocationMethod: IServiceMethod) {
               super();
               this.serviceName = serviceName;
               this.endpointName = endpointName;
               this.functionName = functionName;
               this.invocationMethod = invocationMethod;
          }

          /**
             @method
             Get token's invocation method type.

             @return {Adaptive.IServiceMethod} Invocation method type.
             @since v2.0.6
          */
          getInvocationMethod() : IServiceMethod {
               return this.invocationMethod;
          }

          /**
             @method
             Sets the invocation method type.

             @param {Adaptive.IServiceMethod} invocationMethod Method type.
             @since v2.0.6
          */
          setInvocationMethod(invocationMethod: IServiceMethod) {
               this.invocationMethod = invocationMethod;
          }

          /**
             @method
             Get token's endpoint name.

             @return {string} Endpoint name.
             @since v2.0.6
          */
          getEndpointName() : string {
               return this.endpointName;
          }

          /**
             @method
             Set the endpoint name.

             @param {string} endpointName Endpoint name.
             @since v2.0.6
          */
          setEndpointName(endpointName: string) {
               this.endpointName = endpointName;
          }

          /**
             @method
             Get token's function name.

             @return {string} Function name.
             @since v2.0.6
          */
          getFunctionName() : string {
               return this.functionName;
          }

          /**
             @method
             Sets the function name.

             @param {string} functionName Function name.
             @since v2.0.6
          */
          setFunctionName(functionName: string) {
               this.functionName = functionName;
          }

          /**
             @method
             Get token's service name.

             @return {string} Service name.
             @since v2.0.6
          */
          getServiceName() : string {
               return this.serviceName;
          }

          /**
             @method
             Sets token's service name.

             @param {string} serviceName Service name.
             @since v2.0.6
          */
          setServiceName(serviceName: string) {
               this.serviceName = serviceName;
          }

          /**
             @method
             @static
             Convert JSON parsed object to typed equivalent.
             @param {Object} object JSON parsed structure of type Adaptive.ServiceToken.
             @return {Adaptive.ServiceToken} Wrapped object instance.
          */
          static toObject(object : any) : ServiceToken {
               var result : ServiceToken = new ServiceToken(null, null, null, null);

               if (object != null ) {
                    // Assign values to bean fields.
                    result.serviceName = object.serviceName;
                    result.endpointName = object.endpointName;
                    result.functionName = object.functionName;
                    result.invocationMethod = IServiceMethod.toObject(object.invocationMethod);

               }
               return result;
          }

          /**
             @method
             @static
             Convert JSON parsed object array to typed equivalent.
             @param {Object} object JSON parsed structure of type Adaptive.ServiceToken[].
             @return {Adaptive.ServiceToken[]} Wrapped object array instance.
          */
          static toObjectArray(object : any) : ServiceToken[] {
               var resultArray : Array<ServiceToken> = new Array<ServiceToken>();
               if (object != null) {
                    for (var i = 0; i < object.length; i++) {
                         resultArray.push(ServiceToken.toObject(object[i]));
                    }
               }
               return resultArray;
          }

     }
}

/**
------------------------------------| Engineered with ♥ in Barcelona, Catalonia |--------------------------------------
*/


text:
require 'aws-sdk-ecr'
require 'json'
require 'base64'

module Awful
  class ECR < Cli
    no_commands do
      def ecr
        @ecr ||= Aws::ECR::Client.new
      end

      ## get array of image_tag hashes in form expected by get methods
      def image_tags(*tags)
        tags.map do |tag|
          {image_tag: tag}
        end
      end

      def describe_images(repository, tag_status = nil)
        paginate(:image_details) do |next_token|
          ecr.describe_images(
            repository_name: repository,
            filter: { tag_status: tag_status },
            next_token: next_token,
          )
        end
      end
    end

    desc 'ls', 'list repositories'
    method_option :long, aliases: '-l', type: :boolean, default: false, desc: 'long listing'
    def ls
      repos = ecr.describe_repositories.map(&:repositories).flatten
      if options[:long]
        print_table repos.map { |r| [r.repository_name, r.registry_id, r.repository_arn] }.sort
      else
        puts repos.map(&:repository_name).sort
      end
    end

    desc 'create REPO', 'create a repository'
    def create(repository)
      ecr.create_repository(repository_name: repository)
    end

    desc 'delete REPO', 'delete a repository'
    method_option :force, aliases: '-f', type: :boolean, default: false, desc: 'Force the deletion of the repository if it contains images'
    def delete(repository)
      if yes? "Really delete repository #{repository}?", :yellow
        ecr.delete_repository(repository_name: repository, force: options[:force])
      end
    end

    desc 'auth [REGISTRIES]', 'dump authorization details for registries (or default)'
    def auth(*registries)
      registries = nil if registries.empty?
      ecr.get_authorization_token(registry_ids: registries).authorization_data.output do |auths|
        auths.each do |auth|
          puts YAML.dump(stringify_keys(auth.to_h))
        end
      end
    end

    desc 'login [REGISTRIES]', 'run docker login for registry'
    method_option :email,                type: :string,  default: nil,    desc: 'Email for docker login command'
    method_option :print, aliases: '-p', type: :boolean, default: false,  desc: 'Print docker login command instead of running it'
    def login(*registries)
      cmd = options[:print] ? :puts : :system
      registries = nil if registries.empty?
      email = options[:email] ? "-e #{options[:email]}" : ''  # -e deprecated as of 1.14, here for older docker clients
      ecr.get_authorization_token(registry_ids: registries).authorization_data.output do |auths|
        auths.each do |auth|
          user, pass = Base64.decode64(auth.authorization_token).split(':')
          send(cmd, "docker login -u #{user} -p #{pass} #{email} #{auth.proxy_endpoint}")
        end
      end
    end

    desc 'images REPO', 'list images for repo'
    method_option :untagged, aliases: '-u', type: :boolean, default: false, desc: 'show only untagged images'
    def images(repo)
      filter = { tag_status: options[:untagged] ? :UNTAGGED : :TAGGED }
      print_table ecr.describe_images(repository_name: repo, filter: filter).map(&:image_details).flatten.map { |i|
        [ i.image_pushed_at, i.image_tags.sort_by(&:size).join(' ') ]
      }.sort.reverse
    end

    desc 'get REPO TAG[S]', 'get image details for all given TAGS'
    def get(repository, *tags)
      ecr.batch_get_image(repository_name: repository, image_ids: image_tags(*tags)).images.output do |imgs|
        imgs.each do |img|
          puts YAML.dump(stringify_keys(img.to_h))
        end
      end
    end

    desc 'inspect REPO TAGS', 'get first history element from manifest'
    def inspect(repository, *tags)
      ecr.batch_get_image(repository_name: repository, image_ids: image_tags(*tags)).images.output do |imgs|
        imgs.map do |img|
          JSON.parse(JSON.parse(img.image_manifest)['history'].first['v1Compatibility'])
        end.output do |list|
          puts YAML.dump(list)
        end
      end
    end

    desc 'date REPO TAGS', 'get created date for given tags'
    def date(repository, *tags)
      ecr.batch_get_image(repository_name: repository, image_ids: image_tags(*tags)).images.output do |imgs|
        imgs.map do |img|
          parse_created(img)
        end.output do |dates|
          puts dates
        end
      end
    end

    desc 'exists REPO TAG', 'test if repo with given tag exists in registry'
    def exists(repository, tag)
      imgs = ecr.batch_get_image(repository_name: repository, image_ids: image_tags(tag)).images
      (imgs.empty? ? false : true).output(&method(:puts))
    end

    desc 'reap REPO DAYS', 'reap old images for repo'
    method_option :batch,   aliases: '-b', type: :numeric, default: 10,    desc: 'batch size to get and delete'
    method_option :dry_run, aliases: '-d', type: :boolean, default: false, desc: 'dry run, do not delete, implies verbose'
    method_option :verbose, aliases: '-v', type: :boolean, default: false, desc: 'print images to be deleted'
    def reap(repository, days, token: nil)
      verbose = options[:verbose] || options[:dry_run]
      next_token = token
      now = Time.now.utc

      deleted = failures = 0
      loop do
        response = ecr.describe_images(repository_name: repository, next_token: next_token, max_results: options[:batch])

        old_images = response.image_details.select do |image|
          date = image.image_pushed_at.utc
          age = ((now - date)/(24*60*60)).to_i
          if age > days.to_i
            puts "#{date} #{age} #{image.image_digest} #{image.image_tags}" if verbose
            true
          else
            false
          end
        end

        ## delete old images
        unless options[:dry_run] || old_images.empty?
          r = ecr.batch_delete_image(
            repository_name: repository,
            image_ids: old_images.map { |i| {image_digest: i.image_digest} }
          )
          deleted  += r.image_ids.count
          failures += r.failures.count
        end

        next_token = response.next_token
        break unless next_token
      end

      puts "deleted: #{deleted}, failures: #{failures}"
    end
  end
end


text:
package org.quicktheories.impl;

import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.OptionalLong;

public final class Precursor {

  private static final int INITIAL_SIZE = 32;

  private ByteBuffer buffer = ByteBuffer.allocate(1);
  private final List<Constraint> constraints;

  public Precursor() {
    this.buffer = ByteBuffer.allocate(INITIAL_SIZE);
    this.constraints = new ArrayList<>();
  }

  public boolean isEmpty() {
    return buffer.position() == 0;
  }

  public byte[] bytes() {
    return Arrays.copyOf(buffer.array(),buffer.position());
  }

  void store(long l, Constraint constraint) {
    addToBuffer(l);
    storeConstraints(constraint);
  }

  public long[] current() {
    long[] out = longArraySizedForBuffer();
    ByteBuffer view = buffer.duplicate();
    view.position(0);
    view.asLongBuffer().get(out);
    return out;
  }

  public long[] maxLimit() {
    long[] max = longArraySizedForBuffer();
    for (int i = 0; i != constraints.size(); i++) {
      max[i] = constraints.get(i).max();
    }
    return max;
  }

  public long[] minLimit() {
    long[] max = longArraySizedForBuffer();
    for (int i = 0; i != constraints.size(); i++) {
      max[i] = constraints.get(i).min();
    }
    return max;
  }

  public long[] shrinkTarget() {
    long[] max = longArraySizedForBuffer();
    for (int i = 0; i != constraints.size(); i++) {
      max[i] = constraints.get(i).shrinkTarget().orElse(constraints.get(i).min());
    }
    return max;
  }

  public OptionalLong shrinkTarget(int index) {
    return constraints.get(index).shrinkTarget();
  }

  public  long min(int index) {
    return constraints.get(index).min();
  }

  public long max(int index) {
    return constraints.get(index).max();
  }

  private long[] longArraySizedForBuffer() {
    return new long[buffer.position() / Long.BYTES];
  }

  private void addToBuffer(long l) {
    checkBufferSize(Long.BYTES);
    buffer.putLong(l);
  }

  private void storeConstraints(Constraint constraints) {
    this.constraints.add(constraints);
  }

  public void combine(Precursor other) {
    byte[] bs = other.bytes();
    checkBufferSize(bs.length);
    buffer.put(bs, 0, bs.length);
    constraints.addAll(other.constraints);
  }

  private void checkBufferSize(int required) {
    if (buffer.remaining() < required) {
      int growStep = buffer.capacity()  * 2;
      ByteBuffer tmp =  ByteBuffer.allocate(buffer.capacity() + Math.max(required,growStep));
      tmp.put(bytes());
      buffer = tmp;
    }
  }

}


text:
@implementation DDPageControlViewController

@synthesize scrollView ;

- (void)dealloc
{
	[scrollView release], scrollView = nil ;

	[super dealloc] ;
}

- (void)viewDidLoad
{
	[super viewDidLoad] ;

	int numberOfPages = 10 ;

	// define the scroll view content size and enable paging
	[scrollView setPagingEnabled: YES] ;
	[scrollView setContentSize: CGSizeMake(scrollView.bounds.size.width * numberOfPages, scrollView.bounds.size.height)] ;

	// programmatically add the page control
	pageControl = [[DDPageControl alloc] init] ;
	[pageControl setCenter: CGPointMake(self.view.center.x, self.view.bounds.size.height-30.0f)] ;
	[pageControl setNumberOfPages: numberOfPages] ;
	[pageControl setCurrentPage: 0] ;
	[pageControl addTarget: self action: @selector(pageControlClicked:) forControlEvents: UIControlEventValueChanged] ;
	[pageControl setDefersCurrentPageDisplay: YES] ;
	[pageControl setType: DDPageControlTypeOnFullOffEmpty] ;
	[pageControl setOnColor: [UIColor colorWithWhite: 0.9f alpha: 1.0f]] ;
	[pageControl setOffColor: [UIColor colorWithWhite: 0.7f alpha: 1.0f]] ;
	[pageControl setIndicatorDiameter: 15.0f] ;
	[pageControl setIndicatorSpace: 15.0f] ;
	[self.view addSubview: pageControl] ;
	[pageControl release] ;

	UILabel *pageLabel ;
	CGRect pageFrame ;
	UIColor *color ;
	char aLetter ;
	for (int i = 0 ; i < numberOfPages ; i++)
	{
		// determine the frame of the current page
		pageFrame = CGRectMake(i * scrollView.bounds.size.width, 0.0f, scrollView.bounds.size.width, scrollView.bounds.size.height) ;

		// create a page as a simple UILabel
		pageLabel = [[UILabel alloc] initWithFrame: pageFrame] ;

		// add it to the scroll view
		[scrollView addSubview: pageLabel] ;
		[pageLabel release] ;

		// determine and set its (random) background color
		color = [UIColor colorWithRed: (CGFloat)arc4random()/ARC4RANDOM_MAX green: (CGFloat)arc4random()/ARC4RANDOM_MAX blue: (CGFloat)arc4random()/ARC4RANDOM_MAX alpha: 1.0f] ;
		[pageLabel setBackgroundColor: color] ;

		// set some label properties
		[pageLabel setFont: [UIFont boldSystemFontOfSize: 200.0f]] ;
		[pageLabel setTextAlignment: UITextAlignmentCenter] ;
		[pageLabel setTextColor: [UIColor darkTextColor]] ;

		// set the label's text as the letter corresponding to the current page index
		aLetter = (char)((i+65)-(i/26)*26) ;	// the capitalized alphabet characters are in the range 65-90
		[pageLabel setText: [NSString stringWithFormat: @"%c", aLetter]] ;
	}
}

- (void)viewDidUnload
{

}

#pragma mark -
#pragma mark DDPageControl triggered actions

- (void)pageControlClicked:(id)sender
{
	DDPageControl *thePageControl = (DDPageControl *)sender ;

	// we need to scroll to the new index
	[scrollView setContentOffset: CGPointMake(scrollView.bounds.size.width * thePageControl.currentPage, scrollView.contentOffset.y) animated: YES] ;
}

#pragma mark -
#pragma mark UIScrollView delegate methods

- (void)scrollViewDidScroll:(UIScrollView *)aScrollView
{
	CGFloat pageWidth = scrollView.bounds.size.width ;
    float fractionalPage = scrollView.contentOffset.x / pageWidth ;
	NSInteger nearestNumber = lround(fractionalPage) ;

	if (pageControl.currentPage != nearestNumber)
	{
		pageControl.currentPage = nearestNumber ;

		// if we are dragging, we want to update the page control directly during the drag
		if (scrollView.dragging)
			[pageControl updateCurrentPageDisplay] ;
	}
}

- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)aScrollView
{
	// if we are animating (triggered by clicking on the page control), we update the page control
	[pageControl updateCurrentPageDisplay] ;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
	return (interfaceOrientation == UIInterfaceOrientationPortrait) ;
}

- (void)didReceiveMemoryWarning
{
	[super didReceiveMemoryWarning] ;
}

@end


text:
import pymongo
import re

from django.http import HttpResponse

from tastypie import fields
from tastypie.exceptions import BadRequest
from tastypie.utils.mime import build_content_type

from backend.db import db
from backend.db import dehydrate_survey

from .resources import MongoDBResource, Document
from .serializers import CSVSerializer

class VocabResource( MongoDBResource ):
    """
        VocabResource is used to access the mecical vocabulary,
        and query for autocomplete purposes.

        Parameters
        ----------
        MongoDBResource : MongoDBResource

        Attributes
        ----------
        id : string
            A string comprising of the Mongo ID.
        term : string
            A string containing the medical term.
        group : string
            Unused as of now, a string defining the medical dictionary
            the term is from.  (For KEEP, we have 'snomed' as our group)
    """

    id      = fields.CharField( attribute='_id' )
    term    = fields.CharField( attribute='term' )
    group   = fields.CharField( attribute='group' )

    class Meta:
        collection = 'vocab'
        resource_name = 'vocab'
        #authorization = Authorization()
        object_class = Document
        serializer = CSVSerializer()

        list_allowed_methods = [ 'get' ]

        include_resource_uri = False

        filtering = {
            'term': ( 'istartswith', )
        }

    def build_filters( self, filters=None ):
        """
            This API will only be used to get terms that start with
            requested string.  Require filter to be in API call.

            Parameters
            ----------
            filters : string, optional

            Returns
            -------
            String
        """

        if 'term__istartswith' not in filters:
            return BadRequest
        return super( VocabResource, self ).build_filters( filters )

    def create_response( self, request, data, response_class=HttpResponse, **response_kwargs ):
        '''
            This is templated from backend.api.RepoResource create_response.
        '''

        desired_format = self.determine_format(request)

        serialized = self.serialize(request, data, desired_format)
        response = response_class( content=serialized,
                                   content_type=build_content_type(desired_format),
                                   **response_kwargs )

        return response

    def get_list( self, request, **kwargs ):

        startWith = request.GET['term__istartswith']
        startRegex = re.compile( ('^' + startWith), re.IGNORECASE)
        cursor = db.vocab.find( { 'term': startRegex } )\
                         .limit( 10 )\
                         .sort( 'term', pymongo.ASCENDING )
        return self.create_response( request, dehydrate_survey( cursor ) )


text:
package net.dmulloy2.sworntickets.commands;

import net.dmulloy2.sworntickets.SwornTickets;
import net.dmulloy2.sworntickets.types.Permission;

/**
 * @author dmulloy2
 */

public class CmdCancel extends SwornTicketsCommand {

	public CmdCancel(SwornTickets plugin) {
		super(plugin);
		this.name = "cancel";
		this.description = "Cancel ticket creation";
		this.permission = Permission.CMD_OPEN;
		this.mustBePlayer = true;
	}

	@Override
	public void perform() {
		String description = plugin.getPending().get(player);
		if (description == null) {
			err("You must use &c/ticket open &4first!");
			return;
		}

		plugin.getPending().remove(player);
		sendpMessage("Ticket creation cancelled!");
	}
}


text:
using Carbon.Net.Dns;

namespace Carbon.Platform.Hosting
{
    public class UpdateDomainRecordRequest
    {
        public UpdateDomainRecordRequest(long id, IRecord value)
        {
            Ensure.IsValidId(id);
            Ensure.NotNull(value, nameof(value));

            Id = id;
            Value = value;
        }

        public long Id { get; }

        public IRecord Value { get; }
    }
}


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>iframe2</title>

iframe2

    调用Iframe1的info函数


text:
<?php

namespace craft\records;

use craft\db\ActiveRecord;
use yii\db\ActiveQueryInterface;

/**
 * Class Field record.
 *
 * @property int $id ID
 * @property int $groupId Group ID
 * @property string $name Name
 * @property string $handle Handle
 * @property string $context Context
 * @property string $instructions Instructions
 * @property bool $translatable Translatable
 * @property string $translationMethod Translation method
 * @property string $translationKeyFormat Translation key format
 * @property string $type Type
 * @property array $settings Settings
 * @property FieldGroup $group Group
 * @author Pixel & Tonic, Inc. <support@pixelandtonic.com>
 * @since 3.0
 */
class Field extends ActiveRecord
{
    // Properties
    // =========================================================================

    /**
     * @var string|null
     */
    private $_oldHandle;

    // Public Methods
    // =========================================================================

    /**
     * Initializes the application component.
     */
    public function init()
    {
        parent::init();

        // Store the old handle in case it's ever requested.
        $this->on(self::EVENT_AFTER_FIND, [$this, 'storeOldHandle']);
    }

    /**
     * Store the old handle.
     */
    public function storeOldHandle()
    {
        $this->_oldHandle = $this->handle;
    }

    /**
     * Returns the old handle.
     *
     * @return string|null
     */
    public function getOldHandle()
    {
        return $this->_oldHandle;
    }

    /**
     * @inheritdoc
     * @return string
     */
    public static function tableName(): string
    {
        return '{{%fields}}';
    }

    /**
     * Returns the field's group.
     *
     * @return ActiveQueryInterface The relational query object.
     */
    public function getGroup(): ActiveQueryInterface
    {
        return $this->hasOne(FieldGroup::class, ['id' => 'groupId']);
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>{% if error %}{{ error }}{% else %}{{ event.title }}{% endif %}</title>
    <link rel="stylesheet" href="{{ static('main/css/event-video.css') }}" />

  {% if error %}

ERROR: {{ error }}

  {% else %}
    {% if warning and not no_warning %}

Warning: {{ warning }}

    {% endif %}

    {% if event %}
      {% if event.is_pending() %}

        Event is currently in a pending state meaning it will soon be made available.

      {% elif video %}
        {{ video | safe }}
        {% if embedded and not no_footer %}

View on Air Mozilla

        {% endif %}
      {% else %}

        {% if event.is_upcoming() %}

        {% endif %}

        {{ show_thumbnail(event, '896x504') }}
      {% endif %}

    {% endif %}
  {% endif %}

  {% javascript 'event_video' %}


text:
//
//  LuaLoader.java
//  TemplateApp
//
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

// This corresponds to the name of the Lua library,
// e.g. [Lua] require "plugin.library"
package plugin.notifications;

import android.app.Activity;
import android.util.Log;
import com.naef.jnlua.LuaState;
import com.naef.jnlua.JavaFunction;
import com.naef.jnlua.NamedJavaFunction;
import com.ansca.corona.Bridge;
import com.ansca.corona.CoronaActivity;
import com.ansca.corona.CoronaEnvironment;
import com.ansca.corona.CoronaLua;
import com.ansca.corona.CoronaRuntime;

/**
 * Implements the Lua interface for a Corona plugin.
 *

 * Only one instance of this class will be created by Corona for the lifetime of the application.
 * This instance will be re-used for every new Corona activity that gets created.
 */
public class LuaLoader implements JavaFunction {
	/** This corresponds to the event name, e.g. [Lua] event.name */
	private static final String EVENT_NAME = "pluginlibraryevent";

	/**
	 * Creates a new Lua interface to this plugin.
	 *

	 * Note that a new LuaLoader instance will not be created for every CoronaActivity instance.
	 * That is, only one instance of this class will be created for the lifetime of the application process.
	 * This gives a plugin the option to do operations in the background while the CoronaActivity is destroyed.
	 */
	public LuaLoader() {
	}

	/**
	 * Called when this plugin is being loaded via the Lua require() function.
	 *

	 * Note that this method will be called everytime a new CoronaActivity has been launched.
	 * This means that you'll need to re-initialize this plugin here.
	 *

	 * Warning! This method is not called on the main UI thread.
	 * @param L Reference to the Lua state that the require() function was called from.
	 * @return Returns the number of values that the require() function will return.
	 *

	 *         Expected to return 1, the library that the require() function is loading.
	 */
	@Override
	public int invoke(LuaState L) {
		// Register this plugin into Lua with the following functions.
		NamedJavaFunction[] luaFunctions = new NamedJavaFunction[] {
			new ScheduleNotificationWrapper(),
			new CancelNotificationWrapper(),
			new RegisterForPushNotificationsWrapper()
		};
		String libName = L.toString( 1 );
		L.register(libName, luaFunctions);

		// Returning 1 indicates that the Lua require() function will return the above Lua library.
		return 1;
	}

	protected int scheduleNotification(LuaState L) {
		return Bridge.scheduleNotification(L, 1);
	}

	protected int cancelNotification(LuaState L) {
		if (L.isNone(1)) {
			Bridge.cancelAllNotifications();
		} else {
			int id = Double.valueOf(L.toNumber(-1)).intValue();
			Bridge.cancelNotification(id);
		}
		return 0;
	}

	/** Implements the library.init() Lua function. */
	private class ScheduleNotificationWrapper implements NamedJavaFunction {
		/**
		 * Gets the name of the Lua function as it would appear in the Lua script.
		 * @return Returns the name of the custom Lua function.
		 */
		@Override
		public String getName() {
			return "scheduleNotification";
		}

		/**
		 * This method is called when the Lua function is called.
		 *

		 * Warning! This method is not called on the main UI thread.
		 * @param luaState Reference to the Lua state.
		 *                 Needed to retrieve the Lua function's parameters and to return values back to Lua.
		 * @return Returns the number of values to be returned by the Lua function.
		 */
		@Override
		public int invoke(LuaState L) {
			return scheduleNotification(L);
		}
	}

	/** Implements the library.show() Lua function. */
	private class CancelNotificationWrapper implements NamedJavaFunction {
		/**
		 * Gets the name of the Lua function as it would appear in the Lua script.
		 * @return Returns the name of the custom Lua function.
		 */
		@Override
		public String getName() {
			return "cancelNotification";
		}

		/**
		 * This method is called when the Lua function is called.
		 *

		 * Warning! This method is not called on the main UI thread.
		 * @param luaState Reference to the Lua state.
		 *                 Needed to retrieve the Lua function's parameters and to return values back to Lua.
		 * @return Returns the number of values to be returned by the Lua function.
		 */
		@Override
		public int invoke(LuaState L) {
			return cancelNotification(L);
		}
	}

	private class RegisterForPushNotificationsWrapper implements NamedJavaFunction {
		@Override
		public String getName() {
			return "registerForPushNotifications";
		}

		@Override
		public int invoke(LuaState L) {
			return 0;
		}
	}
}


text:
function Repository(name, info) {
	this.name = name;
	this.type = info.type;
	this.settings = info.settings;
}


text:
/**
 *
 */
package de.saxsys.treasurehunting.game.views;

import org.junit.Test;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;

import play.test.Helpers;

/**
 * This {@link Test} tests the following aspects for the game index page.
 *
 *

 *
Successful and error prone behavior of the user for starting a game in
 * single player mode.

 *

 *
 * @author stefan.illgen
 *
 */
public class IndexPageTest {

	/**
	 * Tests successful start of a single player game.
	 */
	@Test
	public void startSPGameSuccessFirefox() {
		Helpers.running(Helpers.testServer(3333, Helpers.fakeApplication()),
				Helpers.FIREFOX, new StartSPGameSuccessCompositeCallback());
	}

	/**
	 * Tests successful start of a single player game.
	 */
	@Test
	public void startSPGameSuccessChrome() {
		System.setProperty("webdriver.chrome.driver",
				"test/de/saxsys/treasurehunting/webdrivers/chromedriver.exe");
		Helpers.running(Helpers.testServer(3333, Helpers.fakeApplication()),
				ChromeDriver.class, new StartSPGameSuccessCompositeCallback());
	}

	/**
	 * Tests successful start of a single player game.
	 */
	@Test
	public void startSPGameSuccessIE() {
		System.setProperty("webdriver.ie.driver",
				"test/de/saxsys/treasurehunting/webdrivers/IEDriverServer.exe");
		Helpers.running(Helpers.testServer(3333, Helpers.fakeApplication()),
				InternetExplorerDriver.class, new StartSPGameSuccessCompositeCallback());
	}

	/**
	 * Tests error prone start of a single player game.
	 */
	@Test
	public void startSPGameErrorFirefox() {
		Helpers.running(Helpers.testServer(3333, Helpers.fakeApplication()),
				Helpers.FIREFOX, new StartSPGameErrorCompositeCallback());
	}

	/**
	 * Tests error prone start of a single player game.
	 */
	@Test
	public void startSPGameErrorChrome() {
		System.setProperty("webdriver.chrome.driver",
				"test/de/saxsys/treasurehunting/webdrivers/chromedriver.exe");
		Helpers.running(Helpers.testServer(3333, Helpers.fakeApplication()),
				ChromeDriver.class, new StartSPGameErrorCompositeCallback());
	}

	/**
	 * Tests error prone start of a single player game.
	 */
	@Test
	public void startSPGameErrorIE() {
		System.setProperty("webdriver.ie.driver",
				"test/de/saxsys/treasurehunting/webdrivers/IEDriverServer.exe");
		Helpers.running(Helpers.testServer(3333, Helpers.fakeApplication()),
				InternetExplorerDriver.class, new StartSPGameErrorCompositeCallback());
	}

}