text:
import dataclasses
import json  # type: ignore
import re
from typing import Callable, Dict, List, Optional, Sequence, Tuple, Union
import warnings

from google.api_core import gapic_v1, path_template, rest_helpers, rest_streaming
from google.api_core import exceptions as core_exceptions
from google.api_core import retry as retries
from google.auth import credentials as ga_credentials  # type: ignore
from google.auth.transport.grpc import SslCredentials  # type: ignore
from google.auth.transport.requests import AuthorizedSession  # type: ignore
from google.protobuf import json_format
import grpc  # type: ignore
from requests import __version__ as requests_version

try:
    OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault]
except AttributeError:  # pragma: NO COVER
    OptionalRetry = Union[retries.Retry, object]  # type: ignore

from google.cloud.compute_v1.types import compute

from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO
from .base import RegionSecurityPoliciesTransport

DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
    gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
    grpc_version=None,
    rest_version=requests_version,
)

class RegionSecurityPoliciesRestInterceptor:
    """Interceptor for RegionSecurityPolicies.

    Interceptors are used to manipulate requests, request metadata, and responses
    in arbitrary ways.
    Example use cases include:
    * Logging
    * Verifying requests according to service or custom semantics
    * Stripping extraneous information from responses

    These use cases and more can be enabled by injecting an
    instance of a custom subclass when constructing the RegionSecurityPoliciesRestTransport.

    .. code-block:: python
        class MyCustomRegionSecurityPoliciesInterceptor(RegionSecurityPoliciesRestInterceptor):
            def pre_delete(request, metadata):
                logging.log(f"Received request: {request}")
                return request, metadata

            def post_delete(response):
                logging.log(f"Received response: {response}")

            def pre_get(request, metadata):
                logging.log(f"Received request: {request}")
                return request, metadata

            def post_get(response):
                logging.log(f"Received response: {response}")

            def pre_insert(request, metadata):
                logging.log(f"Received request: {request}")
                return request, metadata

            def post_insert(response):
                logging.log(f"Received response: {response}")

            def pre_list(request, metadata):
                logging.log(f"Received request: {request}")
                return request, metadata

            def post_list(response):
                logging.log(f"Received response: {response}")

            def pre_patch(request, metadata):
                logging.log(f"Received request: {request}")
                return request, metadata

            def post_patch(response):
                logging.log(f"Received response: {response}")

        transport = RegionSecurityPoliciesRestTransport(interceptor=MyCustomRegionSecurityPoliciesInterceptor())
        client = RegionSecurityPoliciesClient(transport=transport)

    """

    def pre_delete(
        self,
        request: compute.DeleteRegionSecurityPolicyRequest,
        metadata: Sequence[Tuple[str, str]],
    ) -> Tuple[compute.DeleteRegionSecurityPolicyRequest, Sequence[Tuple[str, str]]]:
        """Pre-rpc interceptor for delete

        Override in a subclass to manipulate the request or metadata
        before they are sent to the RegionSecurityPolicies server.
        """
        return request, metadata

    def post_delete(self, response: compute.Operation) -> compute.Operation:
        """Post-rpc interceptor for delete

        Override in a subclass to manipulate the response
        after it is returned by the RegionSecurityPolicies server but before
        it is returned to user code.
        """
        return response

    def pre_get(
        self,
        request: compute.GetRegionSecurityPolicyRequest,
        metadata: Sequence[Tuple[str, str]],
    ) -> Tuple[compute.GetRegionSecurityPolicyRequest, Sequence[Tuple[str, str]]]:
        """Pre-rpc interceptor for get

        Override in a subclass to manipulate the request or metadata
        before they are sent to the RegionSecurityPolicies server.
        """
        return request, metadata

    def post_get(self, response: compute.SecurityPolicy) -> compute.SecurityPolicy:
        """Post-rpc interceptor for get

        Override in a subclass to manipulate the response
        after it is returned by the RegionSecurityPolicies server but before
        it is returned to user code.
        """
        return response

    def pre_insert(
        self,
        request: compute.InsertRegionSecurityPolicyRequest,
        metadata: Sequence[Tuple[str, str]],
    ) -> Tuple[compute.InsertRegionSecurityPolicyRequest, Sequence[Tuple[str, str]]]:
        """Pre-rpc interceptor for insert

        Override in a subclass to manipulate the request or metadata
        before they are sent to the RegionSecurityPolicies server.
        """
        return request, metadata

    def post_insert(self, response: compute.Operation) -> compute.Operation:
        """Post-rpc interceptor for insert

        Override in a subclass to manipulate the response
        after it is returned by the RegionSecurityPolicies server but before
        it is returned to user code.
        """
        return response

    def pre_list(
        self,
        request: compute.ListRegionSecurityPoliciesRequest,
        metadata: Sequence[Tuple[str, str]],
    ) -> Tuple[compute.ListRegionSecurityPoliciesRequest, Sequence[Tuple[str, str]]]:
        """Pre-rpc interceptor for list

        Override in a subclass to manipulate the request or metadata
        before they are sent to the RegionSecurityPolicies server.
        """
        return request, metadata

    def post_list(
        self, response: compute.SecurityPolicyList
    ) -> compute.SecurityPolicyList:
        """Post-rpc interceptor for list

        Override in a subclass to manipulate the response
        after it is returned by the RegionSecurityPolicies server but before
        it is returned to user code.
        """
        return response

    def pre_patch(
        self,
        request: compute.PatchRegionSecurityPolicyRequest,
        metadata: Sequence[Tuple[str, str]],
    ) -> Tuple[compute.PatchRegionSecurityPolicyRequest, Sequence[Tuple[str, str]]]:
        """Pre-rpc interceptor for patch

        Override in a subclass to manipulate the request or metadata
        before they are sent to the RegionSecurityPolicies server.
        """
        return request, metadata

    def post_patch(self, response: compute.Operation) -> compute.Operation:
        """Post-rpc interceptor for patch

        Override in a subclass to manipulate the response
        after it is returned by the RegionSecurityPolicies server but before
        it is returned to user code.
        """
        return response

@dataclasses.dataclass
class RegionSecurityPoliciesRestStub:
    _session: AuthorizedSession
    _host: str
    _interceptor: RegionSecurityPoliciesRestInterceptor

class RegionSecurityPoliciesRestTransport(RegionSecurityPoliciesTransport):
    """REST backend transport for RegionSecurityPolicies.

    The RegionSecurityPolicies API.

    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 JSON representations of protocol buffers over HTTP/1.1

    NOTE: This REST transport functionality is currently in a beta
    state (preview). We welcome your feedback via an issue in this
    library's source repository. Thank you!
    """

    def __init__(
        self,
        *,
        host: str = "compute.googleapis.com",
        credentials: Optional[ga_credentials.Credentials] = None,
        credentials_file: Optional[str] = None,
        scopes: Optional[Sequence[str]] = None,
        client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None,
        quota_project_id: Optional[str] = None,
        client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
        always_use_jwt_access: Optional[bool] = False,
        url_scheme: str = "https",
        interceptor: Optional[RegionSecurityPoliciesRestInterceptor] = None,
        api_audience: Optional[str] = None,
    ) -> None:
        """Instantiate the transport.

        NOTE: This REST transport functionality is currently in a beta
        state (preview). We welcome your feedback via a GitHub issue in
        this library's repository. Thank you!

         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.

             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 list of scopes. This argument is
                 ignored if ``channel`` is provided.
             client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client
                 certificate to configure mutual TLS HTTP channel. It is ignored
                 if ``channel`` 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 are developing
                 your own client library.
             always_use_jwt_access (Optional[bool]): Whether self signed JWT should
                 be used for service account credentials.
             url_scheme: the protocol scheme for the API endpoint.  Normally
                 "https", but for testing or local servers,
                 "http" can be specified.
        """
        # Run the base constructor
        # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc.
        # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the
        # credentials object
        maybe_url_match = re.match("^(?P<scheme>http(?:s)?://)?(?P<host>.*)$", host)
        if maybe_url_match is None:
            raise ValueError(
                f"Unexpected hostname structure: {host}"
            )  # pragma: NO COVER

        url_match_items = maybe_url_match.groupdict()

        host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host

        super().__init__(
            host=host,
            credentials=credentials,
            client_info=client_info,
            always_use_jwt_access=always_use_jwt_access,
            api_audience=api_audience,
        )
        self._session = AuthorizedSession(
            self._credentials, default_host=self.DEFAULT_HOST
        )
        if client_cert_source_for_mtls:
            self._session.configure_mtls_channel(client_cert_source_for_mtls)
        self._interceptor = interceptor or RegionSecurityPoliciesRestInterceptor()
        self._prep_wrapped_messages(client_info)

    class _Delete(RegionSecurityPoliciesRestStub):
        def __hash__(self):
            return hash("Delete")

        __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {}

        @classmethod
        def _get_unset_required_fields(cls, message_dict):
            return {
                k: v
                for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
                if k not in message_dict
            }

        def __call__(
            self,
            request: compute.DeleteRegionSecurityPolicyRequest,
            *,
            retry: OptionalRetry = gapic_v1.method.DEFAULT,
            timeout: Optional[float] = None,
            metadata: Sequence[Tuple[str, str]] = (),
        ) -> compute.Operation:
            r"""Call the delete method over HTTP.

            Args:
                request (~.compute.DeleteRegionSecurityPolicyRequest):
                    The request object. A request message for
                RegionSecurityPolicies.Delete. See the
                method description for details.

                retry (google.api_core.retry.Retry): Designation of what errors, if any,
                    should be retried.
                timeout (float): The timeout for this request.
                metadata (Sequence[Tuple[str, str]]): Strings which should be
                    sent along with the request as metadata.

            Returns:
                ~.compute.Operation:
                    Represents an Operation resource. Google Compute Engine
                has three Operation resources: \*
                `Global </compute/docs/reference/rest/v1/globalOperations>`__
                \*
                `Regional </compute/docs/reference/rest/v1/regionOperations>`__
                \*
                `Zonal </compute/docs/reference/rest/v1/zoneOperations>`__
                You can use an operation resource to manage asynchronous
                API requests. For more information, read Handling API
                responses. Operations can be global, regional or zonal.
                - For global operations, use the ``globalOperations``
                resource. - For regional operations, use the
                ``regionOperations`` resource. - For zonal operations,
                use the ``zonalOperations`` resource. For more
                information, read Global, Regional, and Zonal Resources.

            """

            http_options: List[Dict[str, str]] = [
                {
                    "method": "delete",
                    "uri": "/compute/v1/projects/{project}/regions/{region}/securityPolicies/{security_policy}",
                },
            ]
            request, metadata = self._interceptor.pre_delete(request, metadata)
            pb_request = compute.DeleteRegionSecurityPolicyRequest.pb(request)
            transcoded_request = path_template.transcode(http_options, pb_request)

            uri = transcoded_request["uri"]
            method = transcoded_request["method"]

            # Jsonify the query params
            query_params = json.loads(
                json_format.MessageToJson(
                    transcoded_request["query_params"],
                    including_default_value_fields=False,
                    use_integers_for_enums=False,
                )
            )
            query_params.update(self._get_unset_required_fields(query_params))

            # Send the request
            headers = dict(metadata)
            headers["Content-Type"] = "application/json"
            response = getattr(self._session, method)(
                "{host}{uri}".format(host=self._host, uri=uri),
                timeout=timeout,
                headers=headers,
                params=rest_helpers.flatten_query_params(query_params, strict=True),
            )

            # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
            # subclass.
            if response.status_code >= 400:
                raise core_exceptions.from_http_response(response)

            # Return the response
            resp = compute.Operation()
            pb_resp = compute.Operation.pb(resp)

            json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
            resp = self._interceptor.post_delete(resp)
            return resp

    class _Get(RegionSecurityPoliciesRestStub):
        def __hash__(self):
            return hash("Get")

        __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {}

        @classmethod
        def _get_unset_required_fields(cls, message_dict):
            return {
                k: v
                for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
                if k not in message_dict
            }

        def __call__(
            self,
            request: compute.GetRegionSecurityPolicyRequest,
            *,
            retry: OptionalRetry = gapic_v1.method.DEFAULT,
            timeout: Optional[float] = None,
            metadata: Sequence[Tuple[str, str]] = (),
        ) -> compute.SecurityPolicy:
            r"""Call the get method over HTTP.

            Args:
                request (~.compute.GetRegionSecurityPolicyRequest):
                    The request object. A request message for
                RegionSecurityPolicies.Get. See the
                method description for details.

                retry (google.api_core.retry.Retry): Designation of what errors, if any,
                    should be retried.
                timeout (float): The timeout for this request.
                metadata (Sequence[Tuple[str, str]]): Strings which should be
                    sent along with the request as metadata.

            Returns:
                ~.compute.SecurityPolicy:
                    Represents a Google Cloud Armor
                security policy resource. Only external
                backend services that use load balancers
                can reference a security policy. For
                more information, see Google Cloud Armor
                security policy overview.

            """

            http_options: List[Dict[str, str]] = [
                {
                    "method": "get",
                    "uri": "/compute/v1/projects/{project}/regions/{region}/securityPolicies/{security_policy}",
                },
            ]
            request, metadata = self._interceptor.pre_get(request, metadata)
            pb_request = compute.GetRegionSecurityPolicyRequest.pb(request)
            transcoded_request = path_template.transcode(http_options, pb_request)

            uri = transcoded_request["uri"]
            method = transcoded_request["method"]

            # Jsonify the query params
            query_params = json.loads(
                json_format.MessageToJson(
                    transcoded_request["query_params"],
                    including_default_value_fields=False,
                    use_integers_for_enums=False,
                )
            )
            query_params.update(self._get_unset_required_fields(query_params))

            # Send the request
            headers = dict(metadata)
            headers["Content-Type"] = "application/json"
            response = getattr(self._session, method)(
                "{host}{uri}".format(host=self._host, uri=uri),
                timeout=timeout,
                headers=headers,
                params=rest_helpers.flatten_query_params(query_params, strict=True),
            )

            # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
            # subclass.
            if response.status_code >= 400:
                raise core_exceptions.from_http_response(response)

            # Return the response
            resp = compute.SecurityPolicy()
            pb_resp = compute.SecurityPolicy.pb(resp)

            json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
            resp = self._interceptor.post_get(resp)
            return resp

    class _Insert(RegionSecurityPoliciesRestStub):
        def __hash__(self):
            return hash("Insert")

        __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {}

        @classmethod
        def _get_unset_required_fields(cls, message_dict):
            return {
                k: v
                for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
                if k not in message_dict
            }

        def __call__(
            self,
            request: compute.InsertRegionSecurityPolicyRequest,
            *,
            retry: OptionalRetry = gapic_v1.method.DEFAULT,
            timeout: Optional[float] = None,
            metadata: Sequence[Tuple[str, str]] = (),
        ) -> compute.Operation:
            r"""Call the insert method over HTTP.

            Args:
                request (~.compute.InsertRegionSecurityPolicyRequest):
                    The request object. A request message for
                RegionSecurityPolicies.Insert. See the
                method description for details.

                retry (google.api_core.retry.Retry): Designation of what errors, if any,
                    should be retried.
                timeout (float): The timeout for this request.
                metadata (Sequence[Tuple[str, str]]): Strings which should be
                    sent along with the request as metadata.

            Returns:
                ~.compute.Operation:
                    Represents an Operation resource. Google Compute Engine
                has three Operation resources: \*
                `Global </compute/docs/reference/rest/v1/globalOperations>`__
                \*
                `Regional </compute/docs/reference/rest/v1/regionOperations>`__
                \*
                `Zonal </compute/docs/reference/rest/v1/zoneOperations>`__
                You can use an operation resource to manage asynchronous
                API requests. For more information, read Handling API
                responses. Operations can be global, regional or zonal.
                - For global operations, use the ``globalOperations``
                resource. - For regional operations, use the
                ``regionOperations`` resource. - For zonal operations,
                use the ``zonalOperations`` resource. For more
                information, read Global, Regional, and Zonal Resources.

            """

            http_options: List[Dict[str, str]] = [
                {
                    "method": "post",
                    "uri": "/compute/v1/projects/{project}/regions/{region}/securityPolicies",
                    "body": "security_policy_resource",
                },
            ]
            request, metadata = self._interceptor.pre_insert(request, metadata)
            pb_request = compute.InsertRegionSecurityPolicyRequest.pb(request)
            transcoded_request = path_template.transcode(http_options, pb_request)

            # Jsonify the request body

            body = json_format.MessageToJson(
                transcoded_request["body"],
                including_default_value_fields=False,
                use_integers_for_enums=False,
            )
            uri = transcoded_request["uri"]
            method = transcoded_request["method"]

            # Jsonify the query params
            query_params = json.loads(
                json_format.MessageToJson(
                    transcoded_request["query_params"],
                    including_default_value_fields=False,
                    use_integers_for_enums=False,
                )
            )
            query_params.update(self._get_unset_required_fields(query_params))

            # Send the request
            headers = dict(metadata)
            headers["Content-Type"] = "application/json"
            response = getattr(self._session, method)(
                "{host}{uri}".format(host=self._host, uri=uri),
                timeout=timeout,
                headers=headers,
                params=rest_helpers.flatten_query_params(query_params, strict=True),
                data=body,
            )

            # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
            # subclass.
            if response.status_code >= 400:
                raise core_exceptions.from_http_response(response)

            # Return the response
            resp = compute.Operation()
            pb_resp = compute.Operation.pb(resp)

            json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
            resp = self._interceptor.post_insert(resp)
            return resp

    class _List(RegionSecurityPoliciesRestStub):
        def __hash__(self):
            return hash("List")

        __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {}

        @classmethod
        def _get_unset_required_fields(cls, message_dict):
            return {
                k: v
                for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
                if k not in message_dict
            }

        def __call__(
            self,
            request: compute.ListRegionSecurityPoliciesRequest,
            *,
            retry: OptionalRetry = gapic_v1.method.DEFAULT,
            timeout: Optional[float] = None,
            metadata: Sequence[Tuple[str, str]] = (),
        ) -> compute.SecurityPolicyList:
            r"""Call the list method over HTTP.

            Args:
                request (~.compute.ListRegionSecurityPoliciesRequest):
                    The request object. A request message for
                RegionSecurityPolicies.List. See the
                method description for details.

                retry (google.api_core.retry.Retry): Designation of what errors, if any,
                    should be retried.
                timeout (float): The timeout for this request.
                metadata (Sequence[Tuple[str, str]]): Strings which should be
                    sent along with the request as metadata.

            Returns:
                ~.compute.SecurityPolicyList:

            """

            http_options: List[Dict[str, str]] = [
                {
                    "method": "get",
                    "uri": "/compute/v1/projects/{project}/regions/{region}/securityPolicies",
                },
            ]
            request, metadata = self._interceptor.pre_list(request, metadata)
            pb_request = compute.ListRegionSecurityPoliciesRequest.pb(request)
            transcoded_request = path_template.transcode(http_options, pb_request)

            uri = transcoded_request["uri"]
            method = transcoded_request["method"]

            # Jsonify the query params
            query_params = json.loads(
                json_format.MessageToJson(
                    transcoded_request["query_params"],
                    including_default_value_fields=False,
                    use_integers_for_enums=False,
                )
            )
            query_params.update(self._get_unset_required_fields(query_params))

            # Send the request
            headers = dict(metadata)
            headers["Content-Type"] = "application/json"
            response = getattr(self._session, method)(
                "{host}{uri}".format(host=self._host, uri=uri),
                timeout=timeout,
                headers=headers,
                params=rest_helpers.flatten_query_params(query_params, strict=True),
            )

            # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
            # subclass.
            if response.status_code >= 400:
                raise core_exceptions.from_http_response(response)

            # Return the response
            resp = compute.SecurityPolicyList()
            pb_resp = compute.SecurityPolicyList.pb(resp)

            json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
            resp = self._interceptor.post_list(resp)
            return resp

    class _Patch(RegionSecurityPoliciesRestStub):
        def __hash__(self):
            return hash("Patch")

        __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {}

        @classmethod
        def _get_unset_required_fields(cls, message_dict):
            return {
                k: v
                for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
                if k not in message_dict
            }

        def __call__(
            self,
            request: compute.PatchRegionSecurityPolicyRequest,
            *,
            retry: OptionalRetry = gapic_v1.method.DEFAULT,
            timeout: Optional[float] = None,
            metadata: Sequence[Tuple[str, str]] = (),
        ) -> compute.Operation:
            r"""Call the patch method over HTTP.

            Args:
                request (~.compute.PatchRegionSecurityPolicyRequest):
                    The request object. A request message for
                RegionSecurityPolicies.Patch. See the
                method description for details.

                retry (google.api_core.retry.Retry): Designation of what errors, if any,
                    should be retried.
                timeout (float): The timeout for this request.
                metadata (Sequence[Tuple[str, str]]): Strings which should be
                    sent along with the request as metadata.

            Returns:
                ~.compute.Operation:
                    Represents an Operation resource. Google Compute Engine
                has three Operation resources: \*
                `Global </compute/docs/reference/rest/v1/globalOperations>`__
                \*
                `Regional </compute/docs/reference/rest/v1/regionOperations>`__
                \*
                `Zonal </compute/docs/reference/rest/v1/zoneOperations>`__
                You can use an operation resource to manage asynchronous
                API requests. For more information, read Handling API
                responses. Operations can be global, regional or zonal.
                - For global operations, use the ``globalOperations``
                resource. - For regional operations, use the
                ``regionOperations`` resource. - For zonal operations,
                use the ``zonalOperations`` resource. For more
                information, read Global, Regional, and Zonal Resources.

            """

            http_options: List[Dict[str, str]] = [
                {
                    "method": "patch",
                    "uri": "/compute/v1/projects/{project}/regions/{region}/securityPolicies/{security_policy}",
                    "body": "security_policy_resource",
                },
            ]
            request, metadata = self._interceptor.pre_patch(request, metadata)
            pb_request = compute.PatchRegionSecurityPolicyRequest.pb(request)
            transcoded_request = path_template.transcode(http_options, pb_request)

            # Jsonify the request body

            body = json_format.MessageToJson(
                transcoded_request["body"],
                including_default_value_fields=False,
                use_integers_for_enums=False,
            )
            uri = transcoded_request["uri"]
            method = transcoded_request["method"]

            # Jsonify the query params
            query_params = json.loads(
                json_format.MessageToJson(
                    transcoded_request["query_params"],
                    including_default_value_fields=False,
                    use_integers_for_enums=False,
                )
            )
            query_params.update(self._get_unset_required_fields(query_params))

            # Send the request
            headers = dict(metadata)
            headers["Content-Type"] = "application/json"
            response = getattr(self._session, method)(
                "{host}{uri}".format(host=self._host, uri=uri),
                timeout=timeout,
                headers=headers,
                params=rest_helpers.flatten_query_params(query_params, strict=True),
                data=body,
            )

            # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
            # subclass.
            if response.status_code >= 400:
                raise core_exceptions.from_http_response(response)

            # Return the response
            resp = compute.Operation()
            pb_resp = compute.Operation.pb(resp)

            json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
            resp = self._interceptor.post_patch(resp)
            return resp

    @property
    def delete(
        self,
    ) -> Callable[[compute.DeleteRegionSecurityPolicyRequest], compute.Operation]:
        # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
        # In C++ this would require a dynamic_cast
        return self._Delete(self._session, self._host, self._interceptor)  # type: ignore

    @property
    def get(
        self,
    ) -> Callable[[compute.GetRegionSecurityPolicyRequest], compute.SecurityPolicy]:
        # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
        # In C++ this would require a dynamic_cast
        return self._Get(self._session, self._host, self._interceptor)  # type: ignore

    @property
    def insert(
        self,
    ) -> Callable[[compute.InsertRegionSecurityPolicyRequest], compute.Operation]:
        # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
        # In C++ this would require a dynamic_cast
        return self._Insert(self._session, self._host, self._interceptor)  # type: ignore

    @property
    def list(
        self,
    ) -> Callable[
        [compute.ListRegionSecurityPoliciesRequest], compute.SecurityPolicyList
    ]:
        # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
        # In C++ this would require a dynamic_cast
        return self._List(self._session, self._host, self._interceptor)  # type: ignore

    @property
    def patch(
        self,
    ) -> Callable[[compute.PatchRegionSecurityPolicyRequest], compute.Operation]:
        # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
        # In C++ this would require a dynamic_cast
        return self._Patch(self._session, self._host, self._interceptor)  # type: ignore

    @property
    def kind(self) -> str:
        return "rest"

    def close(self):
        self._session.close()

__all__ = ("RegionSecurityPoliciesRestTransport",)


text:
package com.scangarella.pipe.example.pipe;

import com.scangarella.pipe.stereotype.Pipe;

/**
 * An example pipe to make a string lowercase
 */
public class LowercasePipe extends Pipe<String, String> {

    /**
     * Makes the string lowercase.
     * @param s The initial string
     * @return The string's lowercase brethren.
     */
    @Override
    public String ingest(String s) {
        return s.toLowerCase();
    }
}

redpajama_set_name: RedPajamaGithub


text:
using System;

namespace Cadoscopia.DatabaseServices
{
    public class ModificationOutsideTransactionException : ApplicationException
    {
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Tomato.CQRS.Infrastructure
{
    /// <summary>
    /// 查询执行器工厂
    /// </summary>
    public interface IQueryExecutorFactory
    {
        /// <summary>
        /// 创建查询执行器
        /// </summary>
        /// <param name="queryType">查询类型</param>
        /// <typeparam name="TResult">查询结果类型</typeparam>
        /// <returns>查询执行器</returns>
        IQueryExecutor<IQuery<TResult>, TResult> Create<TResult>(Type queryType);
    }
}


text:
/*
 * uart.c
 *
 *  Created on: 30/mag/2014
 *      Author: giacky98
 */

#include "stm32f4xx.h"
#include "stm32f4xx_hal_rcc.h"
#include "stm32f4xx_hal_uart.h"
#include "stm32f4xx_hal_gpio.h"

#include "uart.h"

UART_HandleTypeDef handle_UART;

void UART_init(int baud)
{
	__USART6_CLK_ENABLE();

	__GPIOA_CLK_ENABLE();

	GPIO_InitTypeDef GPIO_InitStruct;

	GPIO_InitStruct.Pin = GPIO_PIN_11 | GPIO_PIN_12;
	GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
	GPIO_InitStruct.Pull = GPIO_NOPULL;
	GPIO_InitStruct.Speed = GPIO_SPEED_LOW;
	GPIO_InitStruct.Alternate = GPIO_AF8_USART6;
	HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);

	handle_UART.Instance = USART6;
	handle_UART.Init.BaudRate = baud;
	handle_UART.Init.WordLength = UART_WORDLENGTH_8B;
	handle_UART.Init.StopBits = UART_STOPBITS_1;
	handle_UART.Init.Parity = UART_PARITY_NONE;
	handle_UART.Init.Mode = UART_MODE_TX_RX;
	handle_UART.Init.HwFlowCtl = UART_HWCONTROL_NONE;
	handle_UART.Init.OverSampling = UART_OVERSAMPLING_16;
	HAL_UART_Init(&handle_UART);
}

void UART_putc(uint8_t c)
{
	HAL_UART_Transmit(&handle_UART, &c, 1, 22000);
}

uint8_t UART_getc(void)
{
	uint8_t data;

	HAL_UART_Receive(&handle_UART, &data, 1, 22000);

	return data;
}

int UART_available(void)
{
	return 0;
}


text:
Login

            <form role="form" >

                    User name:
                    <input type="text" class="form-control" id="name" placeholder="Enter user name">

                    Password:
                    <input type="password" class="form-control" id="pwd" placeholder="Enter password">

                <button type="button" id="submit-button" class="btn btn-default">Login</button>

            </form>


text:
The eassiest way to develop and play Real-Time-Strategy Game.

![](https://github.com/syuhei176/webrts/workflows/Test/badge.svg)

[![Netlify Status](https://api.netlify.com/api/v1/badges/00c86221-d9c3-4d09-b4a9-5ae796157a09/deploy-status)](https://app.netlify.com/sites/rts/deploys)

## Demo

http://rts.netlify.app

## Development

under construction


text:
#include "CodeEditor.h"
#include "Languages.h"

#include <scintilla/SciLexer.h>

CodeEditor::CodeEditor(entry_ref* fileRef)
	: BScintillaView(fileRef->name, 0, true, true, B_NO_BORDER)
{
	fFile = BFile(fileRef, B_READ_WRITE);
	fFileEntry = BEntry(fileRef);

	Load();

	// TODO Read color schemes from XML
  	// We need to set font names explicitly, otherwise Scintilla
  	// won't allocate styled fonts
  	SendMessage(SCI_STYLESETFONT, STYLE_DEFAULT, (sptr_t) "DejaVu Sans Mono");
	SendMessage(SCI_STYLESETFORE, 0, 0x808080);	// White space
	SendMessage(SCI_STYLESETFONT, 1, (sptr_t) "DejaVu Sans Mono");
	SendMessage(SCI_STYLESETFORE, 1, 0x007F00);	// Comment
	SendMessage(SCI_STYLESETITALIC, 1, 1);	// Comment
	SendMessage(SCI_STYLESETFONT, 2, (sptr_t) "DejaVu Sans Mono");
	SendMessage(SCI_STYLESETFORE, 2, 0x007F00);	// Line comment
	SendMessage(SCI_STYLESETITALIC, 2, 1);	// Line comment
	SendMessage(SCI_STYLESETFONT, 3, (sptr_t) "DejaVu Sans Mono");
	SendMessage(SCI_STYLESETFORE, 3, 0x3F703F);	// Doc comment
	SendMessage(SCI_STYLESETITALIC, 3, 1);	// Doc comment
	SendMessage(SCI_STYLESETFORE, 4, 0x7F7F00);	// Number
	SendMessage(SCI_STYLESETFONT, 5, (sptr_t) "DejaVu Sans Mono");	// Keyword
	SendMessage(SCI_STYLESETFORE, 5, 0x7F0000);	// Keyword
	SendMessage(SCI_STYLESETBOLD, 5, 1);	// Keyword
	SendMessage(SCI_STYLESETFONT, SCE_C_WORD2, (sptr_t) "DejaVu Sans Mono"); // Keyword
	SendMessage(SCI_STYLESETFORE, SCE_C_WORD2, 0x7F0000);	// Keyword
	SendMessage(SCI_STYLESETBOLD, SCE_C_WORD2, 1);	// Keyword
	SendMessage(SCI_STYLESETFORE, 6, 0x7F007F);	// String
	SendMessage(SCI_STYLESETFORE, 7, 0x7F007F);	// Character
	SendMessage(SCI_STYLESETFORE, 8, 0x804080);	// UUID
	SendMessage(SCI_STYLESETFORE, 9, 0x007F7F);	// Preprocessor
	SendMessage(SCI_STYLESETFONT, 10, (sptr_t) "DejaVu Sans Mono");
	SendMessage(SCI_STYLESETFORE, 10, 0x000000);	// Operators
	SendMessage(SCI_STYLESETBOLD, 10, 1);	// Operators

	SendMessage(SCI_SETMARGINTYPEN, 0, (long int)SC_MARGIN_NUMBER);
	SendMessage(SCI_SETMARGINWIDTHN, 0, 30);

	// Get language definition
	BString name(fileRef->name), ext;
	name.CopyInto(ext, name.FindLast('.') + 1, name.Length());
	language_data* lang = language_for_extension(ext);
	if (lang != NULL) {
		SendMessage(SCI_SETLEXER, lang->sclex_id, 0);
		SendMessage(SCI_SETKEYWORDS, 0, (sptr_t)lang->keywords);
		SendMessage(SCI_SETKEYWORDS, 1, (sptr_t)lang->types);
	}

	SendMessage(SCI_SETTABWIDTH, 4, 0);
	SendMessage(SCI_SETINDENTATIONGUIDES, SC_IV_REAL, 0);
}

BView*
CodeEditor::View()
{
	return this;
}

status_t
CodeEditor::Load()
{
	off_t size;
	fFile.GetSize(&size);
	fFile.Seek(0, SEEK_SET);

	char* buffer = new char[size + 1];
	off_t len = fFile.Read(buffer, size);

	buffer[size] = '\0';
	SetText(buffer);
	delete[] buffer;
	SendMessage(SCI_SETSAVEPOINT, 0, 0);

	ContentsSaved(); // Clear "modified" state
	return (len == size) ? B_OK : B_ERROR;
}

status_t
CodeEditor::Save()
{
	off_t size = SendMessage(SCI_GETLENGTH, 0, 0);
	fFile.SetSize(size);
	fFile.Seek(0, SEEK_SET);

	char* buffer = new char[size + 1];
	GetText(0, size + 1, buffer);
	off_t len = fFile.Write(buffer, size);
	delete[] buffer;
	SendMessage(SCI_SETSAVEPOINT, 0, 0);
	fFile.Flush();

	ContentsSaved();
	return (len == size) ? B_OK : B_ERROR;
}

void
CodeEditor::GoToLine(int32 line)
{
	SendMessage(SCI_GOTOLINE, line, 0);
}

void
CodeEditor::NotificationReceived(SCNotification* n)
{
	if (n->nmhdr.code == SCN_MODIFIED && n->modificationType & SC_PERFORMED_USER)
		ContentsModified();
}


text:
'use strict';

describe('kinetics-problems.kel kelCtrl', function () {
    beforeEach(module('kinetics-problems'));
    beforeEach(module('kinetics-problems.kel'));

    var ctrl, scope;
    // inject the $controller and $rootScope services
    // in the beforeEach block
    beforeEach(inject(function ($controller, $rootScope) {
        // Create a new scope that's a child of the $rootScope
        scope = $rootScope.$new();
        // Create the controller
        ctrl = $controller('KelCtrl', {
            $scope: scope
        });
    }));
    it('should exist....',
        function () {
            //spec body
            expect(ctrl).toBeDefined();
        });
});

describe("Problem service", function () {
    var Problem;

    beforeEach(module('kinetics-problems'));

    beforeEach(inject(function (_Problem_) {
        Problem = _Problem_;
    }));

    describe("Calculate Kel function", function () {
        it("should return a patient age",
            function () {
                expect(Problem.kel(0.1, 25).dose).toBeGreaterThan(1);
            });
    });

});


text:
<?php

if ( ! class_exists( 'ITSEC_Backup_Setup' ) ) {

	class ITSEC_Backup_Setup {

		private
			$defaults;

		public function __construct() {

			global $itsec_setup_action, $itsec_globals;

			$this->defaults = array(
				'enabled'   => false,
				'interval'  => 3,
				'all_sites' => false,
				'method'    => 1,
				'location'  => $itsec_globals['ithemes_backup_dir'],
				'last_run'  => 0,
				'zip'       => true,
				'exclude'   => array(
					'itsec_log',
					'itsec_temp',
					'itsec_lockouts',
				),
				'retain'    => 0,
			);

			if ( isset( $itsec_setup_action ) ) {

				switch ( $itsec_setup_action ) {

					case 'activate':
						$this->execute_activate();
						break;
					case 'upgrade':
						$this->execute_upgrade();
						break;
					case 'deactivate':
						$this->execute_deactivate();
						break;
					case 'uninstall':
						$this->execute_uninstall();
						break;

				}

			} else {
				wp_die( 'error' );
			}

		}

		/**
		 * Execute module activation.
		 *
		 * @since 4.0
		 *
		 * @return void
		 */
		public function execute_activate() {

			$options = get_site_option( 'itsec_backup' );

			if ( $options === false ) {

				add_site_option( 'itsec_backup', $this->defaults );

			}

		}

		/**
		 * Execute module deactivation
		 *
		 * @return void
		 */
		public function execute_deactivate() {
		}

		/**
		 * Execute module uninstall
		 *
		 * @return void
		 */
		public function execute_uninstall() {

			$this->execute_deactivate();

			delete_site_option( 'itsec_backup' );

		}

		/**
		 * Execute module upgrade
		 *
		 * @return void
		 */
		public function execute_upgrade() {

			global $itsec_old_version;

			if ( $itsec_old_version < 4000 ) {

				global $itsec_bwps_options;

				$current_options = get_site_option( 'itsec_backup' );

				if ( $current_options === false ) {
					$current_options = $this->defaults;
				}

				$current_options['enabled']  = isset( $itsec_bwps_options['backup_enabled'] ) && $itsec_bwps_options['backup_enabled'] == 1 ? true : false;
				$current_options['interval'] = isset( $itsec_bwps_options['backup_interval'] ) ? intval( $itsec_bwps_options['backup_interval'] ) : 1;

				update_site_option( 'itsec_backup', $current_options );

			}

		}

	}

}

new ITSEC_Backup_Setup();


text:
<?php

namespace Sdz\ATIBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class PersonnelType extends AbstractType
{
        /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('nom','text',array('required' =>true))
            ->add('noPieceIdent','text',array('required' =>true))
            ->add('poste','text',array('required' =>true))
            ->add('villeResidence','text',array('required' =>true))
        ;
    }

    /**
     * @param OptionsResolverInterface $resolver
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Sdz\ATIBundle\Entity\Personnel'
        ));
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'sdz_atibundle_personnel';
    }
}


text:
require 'spec_helper'

describe 'rundeck' do
  context 'supported operating systems' do
    %w(Debian RedHat).each do |osfamily|
      describe "rundeck::config::global::framework class without any parameters on #{osfamily}" do
        let(:params) { {} }
        let(:facts) do
          {
            :osfamily        => osfamily,
            :fqdn            => 'test.domain.com',
            :serialnumber    => 0,
            :rundeck_version => '',
            :puppetversion   => Puppet.version
          }
        end

        framework_details = {
          'framework.server.name' => 'test.domain.com',
          'framework.server.hostname' => 'test.domain.com',
          'framework.server.port' => '4440',
          'framework.server.url' => 'http://test.domain.com:4440',
          'framework.server.username' => 'admin',
          'framework.server.password' => 'admin',
          'framework.projects.dir' => '/var/lib/rundeck/projects',
          'framework.etc.dir' => '/etc/rundeck',
          'framework.var.dir' => '/var/lib/rundeck/var',
          'framework.tmp.dir' => '/var/lib/rundeck/var/tmp',
          'framework.logs.dir' => '/var/lib/rundeck/logs',
          'framework.libext.dir' => '/var/lib/rundeck/libext',
          'framework.ssh.keypath' => '/var/lib/rundeck/.ssh/id_rsa',
          'framework.ssh.user' => 'rundeck',
          'framework.ssh.timeout' => '0'
        }

        it { should contain_file('/etc/rundeck/framework.properties') }

        framework_details.each do |key, value|
          it 'should generate valid content for framework.properties' do
            content = catalogue.resource('file', '/etc/rundeck/framework.properties')[:content]
            expect(content).to include("#{key} = #{value}")
          end
        end
      end
    end
  end

  context 'add plugin configuration' do
    describe 'add plugin configuration for the logstash plugin' do
      let(:params) do
        {
          :framework_config => {
            'framework.plugin.StreamingLogWriter.LogstashPlugin.port' => '9700'
          }
        }
      end
      let(:facts) do
        {
          :osfamily        => 'Debian',
          :fqdn            => 'test.domain.com',
          :serialnumber    => 0,
          :rundeck_version => '',
          :puppetversion   => Puppet.version
        }
      end

      it 'should generate valid content for framework.properties' do
        content = catalogue.resource('file', '/etc/rundeck/framework.properties')[:content]
        expect(content).to include('framework.server.name = test.domain.com')
        expect(content).to include('framework.plugin.StreamingLogWriter.LogstashPlugin.port = 9700')
      end
    end
  end
end