text:
import datetime
import sys
from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar
import urllib.parse

from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import (
    ClientAuthenticationError,
    HttpResponseError,
    ResourceExistsError,
    ResourceNotFoundError,
    ResourceNotModifiedError,
    map_error,
)
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat

from ... import models as _models
from ..._vendor import _convert_request
from ...operations._reports_operations import (
    build_list_by_api_request,
    build_list_by_geo_request,
    build_list_by_operation_request,
    build_list_by_product_request,
    build_list_by_request_request,
    build_list_by_subscription_request,
    build_list_by_time_request,
    build_list_by_user_request,
)
from .._vendor import ApiManagementClientMixinABC

if sys.version_info >= (3, 8):
    from typing import Literal  # pylint: disable=no-name-in-module, ungrouped-imports
else:
    from typing_extensions import Literal  # type: ignore  # pylint: disable=ungrouped-imports
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]

class ReportsOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`reports` attribute.
    """

    models = _models

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace
    def list_by_api(
        self,
        resource_group_name: str,
        service_name: str,
        filter: str,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        orderby: Optional[str] = None,
        **kwargs: Any
    ) -> AsyncIterable["_models.ReportRecordContract"]:
        """Lists report records by API.

        :param resource_group_name: The name of the resource group. Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param filter: The filter to apply on the operation. Required.
        :type filter: str
        :param top: Number of records to return. Default value is None.
        :type top: int
        :param skip: Number of records to skip. Default value is None.
        :type skip: int
        :param orderby: OData order by query option. Default value is None.
        :type orderby: str
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: An iterator like instance of either ReportRecordContract or the result of
         cls(response)
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.ReportRecordContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version = kwargs.pop(
            "api_version", _params.pop("api-version", self._config.api_version)
        )  # type: Literal["2021-08-01"]
        cls = kwargs.pop("cls", None)  # type: ClsType[_models.ReportCollection]

        error_map = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                request = build_list_by_api_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    subscription_id=self._config.subscription_id,
                    filter=filter,
                    top=top,
                    skip=skip,
                    orderby=orderby,
                    api_version=api_version,
                    template_url=self.list_by_api.metadata["url"],
                    headers=_headers,
                    params=_params,
                )
                request = _convert_request(request)
                request.url = self._client.format_url(request.url)  # type: ignore

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                request = _convert_request(request)
                request.url = self._client.format_url(request.url)  # type: ignore
                request.method = "GET"
            return request

        async def extract_data(pipeline_response):
            deserialized = self._deserialize("ReportCollection", pipeline_response)
            list_of_elem = deserialized.value
            if cls:
                list_of_elem = cls(list_of_elem)
            return deserialized.next_link or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            request = prepare_request(next_link)

            pipeline_response = await self._client._pipeline.run(  # type: ignore # pylint: disable=protected-access
                request, stream=False, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    list_by_api.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/reports/byApi"}  # type: ignore

    @distributed_trace
    def list_by_user(
        self,
        resource_group_name: str,
        service_name: str,
        filter: str,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        orderby: Optional[str] = None,
        **kwargs: Any
    ) -> AsyncIterable["_models.ReportRecordContract"]:
        """Lists report records by User.

        :param resource_group_name: The name of the resource group. Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param filter: |   Field     |     Usage     |     Supported operators     |     Supported
         functions     |
|-------------|-------------|-------------|-------------|
| timestamp |
         filter | ge, le |     |
| displayName | select, orderBy |     |     |
| userId |
         select, filter | eq |     |
| apiRegion | filter | eq |     |
| productId | filter |
         eq |     |
| subscriptionId | filter | eq |     |
| apiId | filter | eq |     |

| operationId | filter | eq |     |
| callCountSuccess | select, orderBy |     |
         |
| callCountBlocked | select, orderBy |     |     |
| callCountFailed | select,
         orderBy |     |     |
| callCountOther | select, orderBy |     |     |
|
         callCountTotal | select, orderBy |     |     |
| bandwidth | select, orderBy |     |     |

| cacheHitsCount | select |     |     |
| cacheMissCount | select |     |     |

| apiTimeAvg | select, orderBy |     |     |
| apiTimeMin | select |     |     |

| apiTimeMax | select |     |     |
| serviceTimeAvg | select |     |     |
|
         serviceTimeMin | select |     |     |
| serviceTimeMax | select |     |     |
.
         Required.
        :type filter: str
        :param top: Number of records to return. Default value is None.
        :type top: int
        :param skip: Number of records to skip. Default value is None.
        :type skip: int
        :param orderby: OData order by query option. Default value is None.
        :type orderby: str
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: An iterator like instance of either ReportRecordContract or the result of
         cls(response)
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.ReportRecordContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version = kwargs.pop(
            "api_version", _params.pop("api-version", self._config.api_version)
        )  # type: Literal["2021-08-01"]
        cls = kwargs.pop("cls", None)  # type: ClsType[_models.ReportCollection]

        error_map = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                request = build_list_by_user_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    subscription_id=self._config.subscription_id,
                    filter=filter,
                    top=top,
                    skip=skip,
                    orderby=orderby,
                    api_version=api_version,
                    template_url=self.list_by_user.metadata["url"],
                    headers=_headers,
                    params=_params,
                )
                request = _convert_request(request)
                request.url = self._client.format_url(request.url)  # type: ignore

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                request = _convert_request(request)
                request.url = self._client.format_url(request.url)  # type: ignore
                request.method = "GET"
            return request

        async def extract_data(pipeline_response):
            deserialized = self._deserialize("ReportCollection", pipeline_response)
            list_of_elem = deserialized.value
            if cls:
                list_of_elem = cls(list_of_elem)
            return deserialized.next_link or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            request = prepare_request(next_link)

            pipeline_response = await self._client._pipeline.run(  # type: ignore # pylint: disable=protected-access
                request, stream=False, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    list_by_user.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/reports/byUser"}  # type: ignore

    @distributed_trace
    def list_by_operation(
        self,
        resource_group_name: str,
        service_name: str,
        filter: str,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        orderby: Optional[str] = None,
        **kwargs: Any
    ) -> AsyncIterable["_models.ReportRecordContract"]:
        """Lists report records by API Operations.

        :param resource_group_name: The name of the resource group. Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param filter: |   Field     |     Usage     |     Supported operators     |     Supported
         functions     |
|-------------|-------------|-------------|-------------|
| timestamp |
         filter | ge, le |     |
| displayName | select, orderBy |     |     |
| apiRegion |
         filter | eq |     |
| userId | filter | eq |     |
| productId | filter | eq |     |

| subscriptionId | filter | eq |     |
| apiId | filter | eq |     |
|
         operationId | select, filter | eq |     |
| callCountSuccess | select, orderBy |     |
         |
| callCountBlocked | select, orderBy |     |     |
| callCountFailed | select,
         orderBy |     |     |
| callCountOther | select, orderBy |     |     |
|
         callCountTotal | select, orderBy |     |     |
| bandwidth | select, orderBy |     |     |

| cacheHitsCount | select |     |     |
| cacheMissCount | select |     |     |

| apiTimeAvg | select, orderBy |     |     |
| apiTimeMin | select |     |     |

| apiTimeMax | select |     |     |
| serviceTimeAvg | select |     |     |
|
         serviceTimeMin | select |     |     |
| serviceTimeMax | select |     |     |
.
         Required.
        :type filter: str
        :param top: Number of records to return. Default value is None.
        :type top: int
        :param skip: Number of records to skip. Default value is None.
        :type skip: int
        :param orderby: OData order by query option. Default value is None.
        :type orderby: str
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: An iterator like instance of either ReportRecordContract or the result of
         cls(response)
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.ReportRecordContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version = kwargs.pop(
            "api_version", _params.pop("api-version", self._config.api_version)
        )  # type: Literal["2021-08-01"]
        cls = kwargs.pop("cls", None)  # type: ClsType[_models.ReportCollection]

        error_map = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                request = build_list_by_operation_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    subscription_id=self._config.subscription_id,
                    filter=filter,
                    top=top,
                    skip=skip,
                    orderby=orderby,
                    api_version=api_version,
                    template_url=self.list_by_operation.metadata["url"],
                    headers=_headers,
                    params=_params,
                )
                request = _convert_request(request)
                request.url = self._client.format_url(request.url)  # type: ignore

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                request = _convert_request(request)
                request.url = self._client.format_url(request.url)  # type: ignore
                request.method = "GET"
            return request

        async def extract_data(pipeline_response):
            deserialized = self._deserialize("ReportCollection", pipeline_response)
            list_of_elem = deserialized.value
            if cls:
                list_of_elem = cls(list_of_elem)
            return deserialized.next_link or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            request = prepare_request(next_link)

            pipeline_response = await self._client._pipeline.run(  # type: ignore # pylint: disable=protected-access
                request, stream=False, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    list_by_operation.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/reports/byOperation"}  # type: ignore

    @distributed_trace
    def list_by_product(
        self,
        resource_group_name: str,
        service_name: str,
        filter: str,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        orderby: Optional[str] = None,
        **kwargs: Any
    ) -> AsyncIterable["_models.ReportRecordContract"]:
        """Lists report records by Product.

        :param resource_group_name: The name of the resource group. Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param filter: |   Field     |     Usage     |     Supported operators     |     Supported
         functions     |
|-------------|-------------|-------------|-------------|
| timestamp |
         filter | ge, le |     |
| displayName | select, orderBy |     |     |
| apiRegion |
         filter | eq |     |
| userId | filter | eq |     |
| productId | select, filter | eq
         |     |
| subscriptionId | filter | eq |     |
| callCountSuccess | select, orderBy |
         |     |
| callCountBlocked | select, orderBy |     |     |
| callCountFailed |
         select, orderBy |     |     |
| callCountOther | select, orderBy |     |     |
|
         callCountTotal | select, orderBy |     |     |
| bandwidth | select, orderBy |     |     |

| cacheHitsCount | select |     |     |
| cacheMissCount | select |     |     |

| apiTimeAvg | select, orderBy |     |     |
| apiTimeMin | select |     |     |

| apiTimeMax | select |     |     |
| serviceTimeAvg | select |     |     |
|
         serviceTimeMin | select |     |     |
| serviceTimeMax | select |     |     |
.
         Required.
        :type filter: str
        :param top: Number of records to return. Default value is None.
        :type top: int
        :param skip: Number of records to skip. Default value is None.
        :type skip: int
        :param orderby: OData order by query option. Default value is None.
        :type orderby: str
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: An iterator like instance of either ReportRecordContract or the result of
         cls(response)
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.ReportRecordContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version = kwargs.pop(
            "api_version", _params.pop("api-version", self._config.api_version)
        )  # type: Literal["2021-08-01"]
        cls = kwargs.pop("cls", None)  # type: ClsType[_models.ReportCollection]

        error_map = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                request = build_list_by_product_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    subscription_id=self._config.subscription_id,
                    filter=filter,
                    top=top,
                    skip=skip,
                    orderby=orderby,
                    api_version=api_version,
                    template_url=self.list_by_product.metadata["url"],
                    headers=_headers,
                    params=_params,
                )
                request = _convert_request(request)
                request.url = self._client.format_url(request.url)  # type: ignore

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                request = _convert_request(request)
                request.url = self._client.format_url(request.url)  # type: ignore
                request.method = "GET"
            return request

        async def extract_data(pipeline_response):
            deserialized = self._deserialize("ReportCollection", pipeline_response)
            list_of_elem = deserialized.value
            if cls:
                list_of_elem = cls(list_of_elem)
            return deserialized.next_link or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            request = prepare_request(next_link)

            pipeline_response = await self._client._pipeline.run(  # type: ignore # pylint: disable=protected-access
                request, stream=False, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    list_by_product.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/reports/byProduct"}  # type: ignore

    @distributed_trace
    def list_by_geo(
        self,
        resource_group_name: str,
        service_name: str,
        filter: str,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        **kwargs: Any
    ) -> AsyncIterable["_models.ReportRecordContract"]:
        """Lists report records by geography.

        :param resource_group_name: The name of the resource group. Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param filter: |   Field     |     Usage     |     Supported operators     |     Supported
         functions     |
|-------------|-------------|-------------|-------------|
| timestamp |
         filter | ge, le |     |
| country | select |     |     |
| region | select |     |
         |
| zip | select |     |     |
| apiRegion | filter | eq |     |
| userId |
         filter | eq |     |
| productId | filter | eq |     |
| subscriptionId | filter | eq
         |     |
| apiId | filter | eq |     |
| operationId | filter | eq |     |
|
         callCountSuccess | select |     |     |
| callCountBlocked | select |     |     |
|
         callCountFailed | select |     |     |
| callCountOther | select |     |     |
|
         bandwidth | select, orderBy |     |     |
| cacheHitsCount | select |     |     |
|
         cacheMissCount | select |     |     |
| apiTimeAvg | select |     |     |
|
         apiTimeMin | select |     |     |
| apiTimeMax | select |     |     |
|
         serviceTimeAvg | select |     |     |
| serviceTimeMin | select |     |     |
|
         serviceTimeMax | select |     |     |
. Required.
        :type filter: str
        :param top: Number of records to return. Default value is None.
        :type top: int
        :param skip: Number of records to skip. Default value is None.
        :type skip: int
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: An iterator like instance of either ReportRecordContract or the result of
         cls(response)
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.ReportRecordContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version = kwargs.pop(
            "api_version", _params.pop("api-version", self._config.api_version)
        )  # type: Literal["2021-08-01"]
        cls = kwargs.pop("cls", None)  # type: ClsType[_models.ReportCollection]

        error_map = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                request = build_list_by_geo_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    subscription_id=self._config.subscription_id,
                    filter=filter,
                    top=top,
                    skip=skip,
                    api_version=api_version,
                    template_url=self.list_by_geo.metadata["url"],
                    headers=_headers,
                    params=_params,
                )
                request = _convert_request(request)
                request.url = self._client.format_url(request.url)  # type: ignore

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                request = _convert_request(request)
                request.url = self._client.format_url(request.url)  # type: ignore
                request.method = "GET"
            return request

        async def extract_data(pipeline_response):
            deserialized = self._deserialize("ReportCollection", pipeline_response)
            list_of_elem = deserialized.value
            if cls:
                list_of_elem = cls(list_of_elem)
            return deserialized.next_link or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            request = prepare_request(next_link)

            pipeline_response = await self._client._pipeline.run(  # type: ignore # pylint: disable=protected-access
                request, stream=False, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    list_by_geo.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/reports/byGeo"}  # type: ignore

    @distributed_trace
    def list_by_subscription(
        self,
        resource_group_name: str,
        service_name: str,
        filter: str,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        orderby: Optional[str] = None,
        **kwargs: Any
    ) -> AsyncIterable["_models.ReportRecordContract"]:
        """Lists report records by subscription.

        :param resource_group_name: The name of the resource group. Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param filter: |   Field     |     Usage     |     Supported operators     |     Supported
         functions     |
|-------------|-------------|-------------|-------------|
| timestamp |
         filter | ge, le |     |
| displayName | select, orderBy |     |     |
| apiRegion |
         filter | eq |     |
| userId | select, filter | eq |     |
| productId | select,
         filter | eq |     |
| subscriptionId | select, filter | eq |     |
| callCountSuccess
         | select, orderBy |     |     |
| callCountBlocked | select, orderBy |     |     |
|
         callCountFailed | select, orderBy |     |     |
| callCountOther | select, orderBy |     |
         |
| callCountTotal | select, orderBy |     |     |
| bandwidth | select, orderBy |
         |     |
| cacheHitsCount | select |     |     |
| cacheMissCount | select |     |
         |
| apiTimeAvg | select, orderBy |     |     |
| apiTimeMin | select |     |     |

| apiTimeMax | select |     |     |
| serviceTimeAvg | select |     |     |
|
         serviceTimeMin | select |     |     |
| serviceTimeMax | select |     |     |
.
         Required.
        :type filter: str
        :param top: Number of records to return. Default value is None.
        :type top: int
        :param skip: Number of records to skip. Default value is None.
        :type skip: int
        :param orderby: OData order by query option. Default value is None.
        :type orderby: str
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: An iterator like instance of either ReportRecordContract or the result of
         cls(response)
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.ReportRecordContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version = kwargs.pop(
            "api_version", _params.pop("api-version", self._config.api_version)
        )  # type: Literal["2021-08-01"]
        cls = kwargs.pop("cls", None)  # type: ClsType[_models.ReportCollection]

        error_map = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                request = build_list_by_subscription_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    subscription_id=self._config.subscription_id,
                    filter=filter,
                    top=top,
                    skip=skip,
                    orderby=orderby,
                    api_version=api_version,
                    template_url=self.list_by_subscription.metadata["url"],
                    headers=_headers,
                    params=_params,
                )
                request = _convert_request(request)
                request.url = self._client.format_url(request.url)  # type: ignore

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                request = _convert_request(request)
                request.url = self._client.format_url(request.url)  # type: ignore
                request.method = "GET"
            return request

        async def extract_data(pipeline_response):
            deserialized = self._deserialize("ReportCollection", pipeline_response)
            list_of_elem = deserialized.value
            if cls:
                list_of_elem = cls(list_of_elem)
            return deserialized.next_link or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            request = prepare_request(next_link)

            pipeline_response = await self._client._pipeline.run(  # type: ignore # pylint: disable=protected-access
                request, stream=False, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    list_by_subscription.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/reports/bySubscription"}  # type: ignore

    @distributed_trace
    def list_by_time(
        self,
        resource_group_name: str,
        service_name: str,
        filter: str,
        interval: datetime.timedelta,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        orderby: Optional[str] = None,
        **kwargs: Any
    ) -> AsyncIterable["_models.ReportRecordContract"]:
        """Lists report records by Time.

        :param resource_group_name: The name of the resource group. Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param filter: |   Field     |     Usage     |     Supported operators     |     Supported
         functions     |
|-------------|-------------|-------------|-------------|
| timestamp |
         filter, select | ge, le |     |
| interval | select |     |     |
| apiRegion |
         filter | eq |     |
| userId | filter | eq |     |
| productId | filter | eq |     |

| subscriptionId | filter | eq |     |
| apiId | filter | eq |     |
|
         operationId | filter | eq |     |
| callCountSuccess | select |     |     |
|
         callCountBlocked | select |     |     |
| callCountFailed | select |     |     |
|
         callCountOther | select |     |     |
| bandwidth | select, orderBy |     |     |
|
         cacheHitsCount | select |     |     |
| cacheMissCount | select |     |     |
|
         apiTimeAvg | select |     |     |
| apiTimeMin | select |     |     |
| apiTimeMax |
         select |     |     |
| serviceTimeAvg | select |     |     |
| serviceTimeMin |
         select |     |     |
| serviceTimeMax | select |     |     |
. Required.
        :type filter: str
        :param interval: By time interval. Interval must be multiple of 15 minutes and may not be zero.
         The value should be in ISO  8601 format (http://en.wikipedia.org/wiki/ISO_8601#Durations).This
         code can be used to convert TimeSpan to a valid interval string: XmlConvert.ToString(new
         TimeSpan(hours, minutes, seconds)). Required.
        :type interval: ~datetime.timedelta
        :param top: Number of records to return. Default value is None.
        :type top: int
        :param skip: Number of records to skip. Default value is None.
        :type skip: int
        :param orderby: OData order by query option. Default value is None.
        :type orderby: str
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: An iterator like instance of either ReportRecordContract or the result of
         cls(response)
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.ReportRecordContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version = kwargs.pop(
            "api_version", _params.pop("api-version", self._config.api_version)
        )  # type: Literal["2021-08-01"]
        cls = kwargs.pop("cls", None)  # type: ClsType[_models.ReportCollection]

        error_map = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                request = build_list_by_time_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    subscription_id=self._config.subscription_id,
                    filter=filter,
                    interval=interval,
                    top=top,
                    skip=skip,
                    orderby=orderby,
                    api_version=api_version,
                    template_url=self.list_by_time.metadata["url"],
                    headers=_headers,
                    params=_params,
                )
                request = _convert_request(request)
                request.url = self._client.format_url(request.url)  # type: ignore

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                request = _convert_request(request)
                request.url = self._client.format_url(request.url)  # type: ignore
                request.method = "GET"
            return request

        async def extract_data(pipeline_response):
            deserialized = self._deserialize("ReportCollection", pipeline_response)
            list_of_elem = deserialized.value
            if cls:
                list_of_elem = cls(list_of_elem)
            return deserialized.next_link or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            request = prepare_request(next_link)

            pipeline_response = await self._client._pipeline.run(  # type: ignore # pylint: disable=protected-access
                request, stream=False, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    list_by_time.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/reports/byTime"}  # type: ignore

    @distributed_trace
    def list_by_request(
        self,
        resource_group_name: str,
        service_name: str,
        filter: str,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        **kwargs: Any
    ) -> AsyncIterable["_models.RequestReportRecordContract"]:
        """Lists report records by Request.

        :param resource_group_name: The name of the resource group. Required.
        :type resource_group_name: str
        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param filter: |   Field     |     Usage     |     Supported operators     |     Supported
         functions     |
|-------------|-------------|-------------|-------------|
| timestamp |
         filter | ge, le |     |
| apiId | filter | eq |     |
| operationId | filter | eq |
         |
| productId | filter | eq |     |
| userId | filter | eq |     |
| apiRegion |
         filter | eq |     |
| subscriptionId | filter | eq |     |
. Required.
        :type filter: str
        :param top: Number of records to return. Default value is None.
        :type top: int
        :param skip: Number of records to skip. Default value is None.
        :type skip: int
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: An iterator like instance of either RequestReportRecordContract or the result of
         cls(response)
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.RequestReportRecordContract]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version = kwargs.pop(
            "api_version", _params.pop("api-version", self._config.api_version)
        )  # type: Literal["2021-08-01"]
        cls = kwargs.pop("cls", None)  # type: ClsType[_models.RequestReportCollection]

        error_map = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                request = build_list_by_request_request(
                    resource_group_name=resource_group_name,
                    service_name=service_name,
                    subscription_id=self._config.subscription_id,
                    filter=filter,
                    top=top,
                    skip=skip,
                    api_version=api_version,
                    template_url=self.list_by_request.metadata["url"],
                    headers=_headers,
                    params=_params,
                )
                request = _convert_request(request)
                request.url = self._client.format_url(request.url)  # type: ignore

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                request = _convert_request(request)
                request.url = self._client.format_url(request.url)  # type: ignore
                request.method = "GET"
            return request

        async def extract_data(pipeline_response):
            deserialized = self._deserialize("RequestReportCollection", pipeline_response)
            list_of_elem = deserialized.value
            if cls:
                list_of_elem = cls(list_of_elem)
            return None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            request = prepare_request(next_link)

            pipeline_response = await self._client._pipeline.run(  # type: ignore # pylint: disable=protected-access
                request, stream=False, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    list_by_request.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/reports/byRequest"}  # type: ignore


text:
'use strict';

exports.__esModule = true;

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; };

var _invariant = require('invariant');

var _invariant2 = _interopRequireDefault(_invariant);

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _getRouteParams = require('./getRouteParams');

var _getRouteParams2 = _interopRequireDefault(_getRouteParams);

var _ContextUtils = require('./ContextUtils');

var _RouteUtils = require('./RouteUtils');

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var _React$PropTypes = _react2.default.PropTypes;
var array = _React$PropTypes.array;
var func = _React$PropTypes.func;
var object = _React$PropTypes.object;

/**
 * A <RouterContext> renders the component tree for a given router state
 * and sets the history object and the current location in context.
 */

var RouterContext = _react2.default.createClass({
  displayName: 'RouterContext',

  mixins: [(0, _ContextUtils.ContextProvider)('router')],

  propTypes: {
    router: object.isRequired,
    location: object.isRequired,
    routes: array.isRequired,
    params: object.isRequired,
    components: array.isRequired,
    createElement: func.isRequired
  },

  getDefaultProps: function getDefaultProps() {
    return {
      createElement: _react2.default.createElement
    };
  },

  childContextTypes: {
    router: object.isRequired
  },

  getChildContext: function getChildContext() {
    return {
      router: this.props.router
    };
  },
  createElement: function createElement(component, props) {
    return component == null ? null : this.props.createElement(component, props);
  },
  render: function render() {
    var _this = this;

    var _props = this.props;
    var location = _props.location;
    var routes = _props.routes;
    var params = _props.params;
    var components = _props.components;
    var router = _props.router;

    var element = null;

    if (components) {
      element = components.reduceRight(function (element, components, index) {
        if (components == null) return element; // Don't create new children; use the grandchildren.

        var route = routes[index];
        var routeParams = (0, _getRouteParams2.default)(route, params);
        var props = {
          location: location,
          params: params,
          route: route,
          router: router,
          routeParams: routeParams,
          routes: routes
        };

        if ((0, _RouteUtils.isReactChildren)(element)) {
          props.children = element;
        } else if (element) {
          for (var prop in element) {
            if (Object.prototype.hasOwnProperty.call(element, prop)) props[prop] = element[prop];
          }
        }

        if ((typeof components === 'undefined' ? 'undefined' : _typeof(components)) === 'object') {
          var elements = {};

          for (var key in components) {
            if (Object.prototype.hasOwnProperty.call(components, key)) {
              // Pass through the key as a prop to createElement to allow
              // custom createElement functions to know which named component
              // they're rendering, for e.g. matching up to fetched data.
              elements[key] = _this.createElement(components[key], _extends({
                key: key }, props));
            }
          }

          return elements;
        }

        return _this.createElement(components, props);
      }, element);
    }

    !(element === null || element === false || _react2.default.isValidElement(element)) ? process.env.NODE_ENV !== 'production' ? (0, _invariant2.default)(false, 'The root route must render a single element') : (0, _invariant2.default)(false) : void 0;

    return element;
  }
});

exports.default = RouterContext;
module.exports = exports['default'];

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Data;
using System.Data.Common;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using Pivotal.Data.GemFireXD;
using AdoNetTest.BIN.BusinessObjects;

namespace AdoNetTest.BIN.JoinQuery
{
    /// <summary>
    /// Performs inner join query on related tables that are partitioned on their
    /// primary key
    /// </summary>
    class InnerJoinQueryOnPrimaryKeyPartionedTables : GFXDTest
    {
        public InnerJoinQueryOnPrimaryKeyPartionedTables(ManualResetEvent resetEvent)
            : base(resetEvent)
        {
        }

        public override void Run(object context)
        {
            String schemaName = DbHelper.GetRandomString(5);

            try
            {
                DbDefault.CreateDB(schemaName, DbCreateType.PKPartition);
                Command.CommandText = DbDefault.GetInnerJoinSelectStatement(
                    schemaName, Relation.ORDER_CUSTOMER, null);
                DataTable dt = new DataTable();
                Log(Command.CommandText);
                DataAdapter.Fill(dt);

                if (dt.Rows.Count <= 0)
                    Fail("Failed to perform join query");
            }
            catch (Exception e)
            {
                Fail(e);
            }
            finally
            {
                try
                {
                    DbDefault.DropDB(schemaName);
                }
                catch (Exception e)
                {
                    Log(e);
                }

                base.Run(context);
            }
        }
    }
}


text:
import { Injectable } from '@angular/core';

import { handleParams } from '../models/utils';

/**
 * Implement this class-interface to create an handler for translated values.
 */
@Injectable() export abstract class L10nTranslationHandler {

    /**
     * This method must contain the logic to parse the translated value.
     * @param key The key that has been requested
     * @param params The parameters passed along with the key
     * @param value The translated value
     * @return The parsed value
     */
    public abstract parseValue(key: string, params: any, value: any): string | any;

}

@Injectable() export class L10nDefaultTranslationHandler implements L10nTranslationHandler {

    public parseValue(key: string, params: any, value: any): string | any {
        if (params) return handleParams(value, params);
        return value;
    }

}


text:
@extends ('main')
@section ('title') Home @endsection

@section ('content')
{{-- Latest News --}}

{{-- Latest Comments --}}

{{-- Latest Blogs --}}

{{-- Latest Reviews --}}
@endsection


text:
//-----------------------------------------------------------------------
// <copyright file="TaskExtensions.cs" company="Akka.NET Project">
//     Copyright (C) 2009-2016 Lightbend Inc. <http://www.lightbend.com>
//     Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------

using System;
using System.Threading.Tasks;

namespace Akka.Util.Internal
{
    /// <summary>
    /// TBD
    /// </summary>
    public static class TaskExtensions
    {
        /// <summary>
        /// TBD
        /// </summary>
        /// <typeparam name="TTask">TBD</typeparam>
        /// <typeparam name="TResult">TBD</typeparam>
        /// <param name="task">TBD</param>
        /// <returns>TBD</returns>
        public static Task<TResult> CastTask<TTask, TResult>(this Task<TTask> task)
        {
            if (task.IsCompleted)
                return Task.FromResult((TResult) (object)task.Result);
            var tcs = new TaskCompletionSource<TResult>();
            if (task.IsFaulted)
                tcs.SetException(task.Exception);
            else
                task.ContinueWith(_ =>
                {
                    if (task.IsFaulted || task.Exception != null)
                        tcs.SetException(task.Exception);
                    else if (task.IsCanceled)
                        tcs.SetCanceled();
                    else
                        try
                        {
                            tcs.SetResult((TResult) (object) task.Result);
                        }
                        catch (Exception e)
                        {
                            tcs.SetException(e);
                        }
                }, TaskContinuationOptions.ExecuteSynchronously);
            return tcs.Task;
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
 Copyright Duke Comprehensive Cancer Center and SemanticBits

 Distributed under the OSI-approved BSD 3-Clause License.
 See  http://ncip.github.com/c3pr/LICENSE.txt for details.
-->
<pa:Id root="2.16.840.1.113883.3.26.4.5.2" identifierName="Study Site identifier" extension="27435" xmlns:pa="http://pa.services.coppa.nci.nih.gov"/>


text:
from blinker import Namespace

_signals = Namespace()

get_cloners = _signals.signal('get_cloners', """
Expected to return one or more ``EventCloner`` subclasses implementing
a cloning operation for something within an event.
""")

management_url = _signals.signal('management-url', """
Expected to return a URL for the event management page of the plugin.
This is used when someone who does not have event management access wants
to go to the event management area. He is then redirected to one of the URLs
returned by plugins, i.e. it is not guaranteed that the user ends up on a
specific plugin's management page. The signal should return None if the current
user (available via ``session.user``) cannot access the management area.
The *sender* is the event object.
""")

image_created = _signals.signal('image-uploaded', """
Called when a new image is created.  The *sender* object is the new ``ImageFile``.
The user who uploaded the image is passed in the ``user`` kwarg.
""")

image_deleted = _signals.signal('image-deleted', """
Called when an image is deleted.  The *sender* object is the ``ImageFile`` that is
about to be deleted.  The user who uploaded the image is passed in the ``user``
kwarg.
""")


text:
// -*- C++ -*-
// Module:  Log4CPLUS
// File:    stringhelper.h
// Created: 3/2003
// Author:  Tad E. Smith
//
//
// Copyright 2003-2015 Tad E. Smith
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/** @file */

#ifndef LOG4CPLUS_HELPERS_STRINGHELPER_HEADER_
#define LOG4CPLUS_HELPERS_STRINGHELPER_HEADER_

#include <log4cplus/config.hxx>

#if defined (LOG4CPLUS_HAVE_PRAGMA_ONCE)
#pragma once
#endif

#include <log4cplus/tstring.h>

#include <algorithm>
#include <limits>

namespace log4cplus {
    namespace helpers {

        /**
         * Returns s in upper case.
         */
        LOG4CPLUS_EXPORT log4cplus::tstring toUpper(const log4cplus::tstring& s);
        LOG4CPLUS_EXPORT tchar toUpper(tchar);

        /**
         * Returns s in lower case.
         */
        LOG4CPLUS_EXPORT log4cplus::tstring toLower(const log4cplus::tstring& s);
        LOG4CPLUS_EXPORT tchar toLower(tchar);

        /**
         * Tokenize s using c as the delimiter and
         * put the resulting tokens in _result.  If
         * collapseTokens is false, multiple adjacent delimiters
         * will result in zero length tokens.
         *
         * Example:
         *

         *   string s = // Set string with '.' as delimiters
         *   list<log4cplus::tstring> tokens;
         *   tokenize(s, '.', back_insert_iterator<list<string> >(tokens));
         *

         */
        template <class StringType, class OutputIter>
        inline
        void
        tokenize(const StringType& s, typename StringType::value_type c,
            OutputIter result, bool collapseTokens = true)
        {
            typedef typename StringType::size_type size_type;
            size_type const slen = s.length();
            size_type first = 0;
            size_type i = 0;
            for (i=0; i < slen; ++i)
            {
                if (s[i] == c)
                {
                    *result = StringType (s, first, i - first);
                    ++result;
                    if (collapseTokens)
                        while (i+1 < slen && s[i+1] == c)
                            ++i;
                    first = i + 1;
                }
            }
            if (first != i)
                *result = StringType (s, first, i - first);
        }

        template <typename intType, typename stringType, bool isSigned>
        struct ConvertIntegerToStringHelper;

        template <typename intType, typename charType>
        struct ConvertIntegerToStringHelper<intType, charType, true>
        {
            static inline
            void
            step1 (charType * & it, intType & value)
            {
                // The sign of the result of the modulo operator is
                // implementation defined. That's why we work with
                // positive counterpart instead.  Also, in twos
                // complement arithmetic the smallest negative number
                // does not have positive counterpart; the range is
                // asymetric.  That's why we handle the case of value
                // == min() specially here.
                if (LOG4CPLUS_UNLIKELY (
                    value == (std::numeric_limits<intType>::min) ()))
                {
                    intType const r = value / 10;
                    intType const a = (-r) * 10;
                    intType const mod = -(a + value);
                    value = -r;

                    *(it - 1)
                        = static_cast<charType>(LOG4CPLUS_TEXT('0') + mod);
                    --it;
                }
                else
                    value = -value;
            }

            static inline
            bool
            is_negative (intType val)
            {
                return val < 0;
            }
        };

        template <typename intType, typename charType>
        struct ConvertIntegerToStringHelper<intType, charType, false>
        {
            static inline
            void
            step1 (charType * &, intType &)
            {
                // This will never be called for unsigned types.
            }

            static inline
            bool
            is_negative (intType)
            {
                return false;
            }
        };

        template <class stringType, class intType>
        inline
        void
        convertIntegerToString (stringType & str, intType value)
        {
            typedef std::numeric_limits<intType> intTypeLimits;
            typedef typename stringType::value_type charType;
            typedef ConvertIntegerToStringHelper<intType, charType,
                intTypeLimits::is_signed> HelperType;

            charType buffer[intTypeLimits::digits10 + 2];
            // We define buffer_size from buffer using sizeof operator
            // to apease HP aCC compiler.
            const std::size_t buffer_size
                = sizeof (buffer) / sizeof (charType);

            charType * it = &buffer[buffer_size];
            charType const * const buf_end = &buffer[buffer_size];

            if (LOG4CPLUS_UNLIKELY (value == 0))
            {
                --it;
                *it = LOG4CPLUS_TEXT('0');
            }
            else
            {
                bool const negative = HelperType::is_negative (value);
                if (negative)
                    HelperType::step1 (it, value);

                for (; value != 0; --it)
                {
                    intType mod = value % 10;
                    value = value / 10;
                    *(it - 1) = static_cast<charType>(LOG4CPLUS_TEXT('0')
                        + mod);
                }

                if (negative)
                {
                    --it;
                    *it = LOG4CPLUS_TEXT('-');
                }
            }

            str.assign (static_cast<charType const *>(it), buf_end);
        }

        template<class intType>
        inline
        tstring
        convertIntegerToString (intType value)
        {
            tstring result;
            convertIntegerToString (result, value);
            return result;
        }

        template<class intType>
        inline
        std::string
        convertIntegerToNarrowString (intType value)
        {
            std::string result;
            convertIntegerToString (result, value);
            return result;
        }

        //! Join a list of items into a string.
        template <typename Iterator>
        inline
        void
        join (tstring & result, Iterator start, Iterator last, tstring const & sep)
        {
            if (start != last)
                result = *start++;

            for (; start != last; ++start)
            {
                result += sep;
                result += *start;
            }
        }

    } // namespace helpers

} // namespace log4cplus

#endif // LOG4CPLUS_HELPERS_STRINGHELPER_HEADER_


text:
<?php defined('BASEPATH') OR exit('No direct script access allowed');
/**
 * Admin_groups controller
 *
 * @author		PyroCMS Dev Team
 * @package	 PyroCMS\Core\Modules\Navigation\Controllers
 */
class Admin_groups extends Admin_Controller
{

	/**
	 * The current active section.
	 *
	 * @var int
	 */
	protected $section = 'groups';

	/**
	 * The array containing the rules for the navigation groups.
	 *
	 * @var array
	 */
	private $validation_rules = array(
		array(
			'field' => 'title',
			'label' => 'lang:global:title',
			'rules' => 'trim|required|max_length[50]'
		),
		array(
			'field' => 'abbrev',
			'label' => 'lang:nav_abbrev_label',
			'rules' => 'trim|required|max_length[50]'
		)
	);

	/**
	 * Constructor method
	 */
	public function __construct()
	{
		// Call the parent's contstructor
		parent::__construct();

		// Load the required classes
		$this->load->model('navigation_m');
		$this->load->library('form_validation');
		$this->lang->load('navigation');

		// Set the validation rules
		$this->form_validation->set_rules($this->validation_rules);
	}

	/**
	 * Index method, redirects back to navigation/index.
	 */
	public function index()
	{
		redirect('admin/navigation');
	}

	/**
	 * Create a new navigation group.
	 */
	public function create()
	{
		// Validate
		if ($this->form_validation->run())
		{
			// Insert the new group
			if ($id = $this->navigation_m->insert_group($_POST) > 0)
			{
				$this->session->set_flashdata('success', $this->lang->line('nav:group_add_success'));
				// Fire an event. A new navigation group has been created.
				Events::trigger('navigation_group_created', $id);
			}
			else
			{
				$this->session->set_flashdata('error', $this->lang->line('nav:group_add_error'));
			}

			// Redirect the user
			redirect('admin/navigation/index');
		}

		// Loop through each rule
		foreach ($this->validation_rules as $rule)
		{
			$navigation_group[$rule['field']] = $this->input->post($rule['field']);
		}

		// Render the view
		$this->template
			->title($this->module_details['name'], lang('nav:group_label'), lang('nav:group_create_title'))
			->set('navigation_group', $navigation_group)
			->append_js('module::navigation.js')
			->build('admin/groups/create');
	}

	/**
	 * Delete a navigation group (or delete multiple ones).
	 *
	 * @param int $id The id of the group.
	 */
	public function delete($id = 0)
	{
		$deleted_ids = false;

		// Delete one
		if ($id)
		{
			if ($this->navigation_m->delete_group($id))
			{
				$deleted_ids[] = $id;
				$this->navigation_m->delete_link(array('navigation_group_id' => $id));
			}
		}

		// Delete multiple
		else
		{
			foreach (array_keys($this->input->post('delete')) as $id)
			{
				if ($this->navigation_m->delete_group($id))
				{
					$deleted_ids[] = $id;
					$this->navigation_m->delete_link(array('navigation_group_id' => $id));
				}
			}
		}

		// Fire an event. One or more navigation groups have been deleted.
		if ( ! empty($deleted_ids))
		{
			Events::trigger('navigation_group_deleted', $deleted_ids);
		}

		// Set the message and redirect
		$this->session->set_flashdata('success', $this->lang->line('nav:group_mass_delete_success'));
		redirect('admin/navigation/index');
	}
}


text:
require 'test_helper'

class Admin::ApplicationControllerTest < ActionController::TestCase
end


text:
DisplayName allows you to name your component. This name is used by React in debugging messages.

## Rule Details

The following patterns are considered warnings:

```jsx
var Hello = createReactClass({
  render: function() {
    return <div>Hello {this.props.name}</div>;
  }
});
```

The following patterns are **not** considered warnings:

```jsx
var Hello = createReactClass({
  displayName: 'Hello',
  render: function() {
    return <div>Hello {this.props.name}</div>;
  }
});
```

## Rule Options

```js
...
"react/display-name": [<enabled>, { "ignoreTranspilerName": <boolean> }]
...
```

### `ignoreTranspilerName`

When `true` the rule will ignore the name set by the transpiler and require a `displayName` property in this case.

The following patterns are considered okay and do **not** cause warnings:

```jsx
var Hello = createReactClass({
  displayName: 'Hello',

  render: function() {
    return <div>Hello {this.props.name}</div>;
  }
});
module.exports = Hello;
```

```jsx
export default class Hello extends React.Component {
  render() {
    return <div>Hello {this.props.name}</div>;
  }
}
Hello.displayName = 'Hello';
```

```jsx
export default function Hello({ name }) {
  return <div>Hello {name}</div>;
}
Hello.displayName = 'Hello';
```

The following patterns will cause warnings:

```jsx
var Hello = createReactClass({
  render: function() {
    return <div>Hello {this.props.name}</div>;
  }
});
module.exports = Hello;
```

```jsx
export default class Hello extends React.Component {
  render() {
    return <div>Hello {this.props.name}</div>;
  }
}
```

```jsx
module.exports = createReactClass({
  render: function() {
    return <div>Hello {this.props.name}</div>;
  }
});
```

```jsx
export default class extends React.Component {
  render() {
    return <div>Hello {this.props.name}</div>;
  }
}
```

```jsx
function HelloComponent() {
  return createReactClass({
    render: function() {
      return <div>Hello {this.props.name}</div>;
    }
  });
}
module.exports = HelloComponent();
```

## About component detection

For this rule to work we need to detect React components, this could be very hard since components could be declared in a lot of ways.

For now we should detect components created with:

* `createReactClass()`
* an ES6 class that inherit from `React.Component` or `Component`
* a stateless function that return JSX or the result of a `React.createElement` call.


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

namespace RSG
{
    /// <summary>
    /// Bind to a property of an object or an element in a list or an array.
    /// Receive notifications when the value changes, or when the value of a nested binding changes.
    /// </summary>
    public interface IBinding
    {
        /// <summary>
        /// Stream of property changing events.
        /// </summary>
        IObservable<BoundPropertyChangingEventArgs> PropertyChangingEventStream { get; }

        /// <summary>
        /// Stream of property changed events.
        /// </summary>
        IObservable<BoundPropertyChangedEventArgs> PropertyChangedEventStream { get; }

        /// <summary>
        /// Stream of collection changed events.
        /// </summary>
        IObservable<BoundCollectionChangedEventArgs> CollectionChangedEventStream { get; }

        /// <summary>
        /// The binding to the value of the property or array/list element.
        /// </summary>
        IValueBinding ValueBinding { get; }

        /// <summary>
        /// The type of the binding.
        /// </summary>
        Type BindingType { get; }

        /// <summary>
        /// Retreive the value.
        /// </summary>
        object GetValue();

        /// <summary>
        /// Set the value.
        /// </summary>
        void SetValue(object newValue);

        /// <summary>
        /// Reattach the property to the property in the specified object.
        /// </summary>
        void Connect(object parentObject);

        /// <summary>
        /// Disconnected events from the binding.
        /// </summary>
        void Disconnect();

        /// <summary>
        /// Find a binding nested in the tree of property bidnings.
        /// </summary>
        IBinding FindNestedBinding(string bindingName);
    }
}


text:
package com.orientechnologies.orient.core.exception;

public class OConfigurationException extends OCoreException {

  private static final long serialVersionUID = -8486291378415776372L;

  public OConfigurationException(OConfigurationException exception) {
    super(exception);
  }

  public OConfigurationException(String message) {
    super(message);
  }
}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;

namespace wwwplatform.Models.ViewModels
{
    public class ComposeEmailMessageModel
    {
        public string attachments { get; set; }

        [DataType(DataType.Html), AllowHtml]
        public string body { get; set; }

        public string subject { get; set; }
    }
}


text:
import React, { Component } from 'react';
import {
    Text,
    TouchableWithoutFeedback,
    Image
} from 'react-native';
import { connect } from 'react-redux';
import { Card, CardSection } from './common';

class EventItem extends Component {
    renderLecturers() {
        let lecturersArray = JSON.parse(this.props.eventLecturers);
        let lecturersString = '';
        for (let lecturer in lecturersArray) {
            lecturersString = lecturersString + lecturersArray[lecturer];
            if ((parseInt(lecturer) + 1) !== lecturersArray.length) {  // Check if it's NOT the last iteration
                lecturersString = lecturersString + ', ';
            }
        }
        return lecturersString;
    }

    titleTextFlex() {
        // TODO: Sometimes this is not working especially when going from 'lanscape' to 'portrait' (see Issue #28)
        if (this.props.orientation === 'PORTRAIT') {
            return ({ flexGrow: -1, flex: 12 });
        } else if (this.props.orientation === 'LANDSCAPE') {
            return ({ flex: -1, flexGrow: 12 });
        }
    }

    render() {
        return (
            <TouchableWithoutFeedback>
                <Card>
                    <CardSection>
                        <Image source={require('../assets/images/clock.png')} style={styles.imageTitle} />
                        <Text style={[styles.titleText, this.titleTextFlex()]}>
                            {this.props.eventSlot}
                        </Text>
                    </CardSection>
                    <CardSection>
                        <Image source={require('../assets/images/subject.png')} style={styles.imageTitle} />
                        <Text style={[styles.titleText, this.titleTextFlex()]}>
                            {this.props.eventName}
                        </Text>
                    </CardSection>
                    <CardSection>
                        <Image source={require('../assets/images/house.png')} style={styles.imageTitle} />
                        <Text style={[styles.titleText, this.titleTextFlex()]}>
                            {this.props.eventRoom}
                        </Text>
                    </CardSection>
                    <CardSection>
                        <Image source={require('../assets/images/person.png')} style={styles.imageTitle} />
                        <Text style={[styles.titleText, this.titleTextFlex()]}>
                            {this.renderLecturers()}
                        </Text>
                    </CardSection>
                    <CardSection>
                        <Image source={require('../assets/images/note.png')} style={styles.imageTitle} />
                        <Text style={[styles.titleText, this.titleTextFlex()]}>
                            {this.props.eventNote}
                        </Text>
                    </CardSection>
                </Card>
            </TouchableWithoutFeedback>
        );
    }
}

const styles = {
    cardSection: {
        flex: 1,
        flexDirection: "column"
    },
    titleText: {
        fontSize: 19
    },
    imageTitle: {
        height: 21,
        width: 21,
        marginRight: 11
    }
};

const mapStateToProps = state => {
    return {
        orientation: state.timetable.orientation
    }
};

export default connect(mapStateToProps, {})(EventItem);


text:
#ifndef VERVE_PREDICTIVE_MODEL_H
#define VERVE_PREDICTIVE_MODEL_H

#include "Globals.h"
#include "Observation.h"
#include "RBFInputData.h"

// PREDICTIVE MODEL STATE REPRESENTATION (currently, METHOD 1 is used):
// METHOD 1. predictive model uses a state-action representation
//		(takes obs and action inputs).  This is more standard.
// METHOD 2. predictive model just uses a state representation
//		(takes only an obs input); since the policy eventually
//		becomes predictable, presumably the next state will
//		become predictable.

namespace verve
{
	class Population;
	class RBFPopulation;

	/// A PredictiveModel learns a predictive model of the environment
	/// dynamics (transitions) from direct experience.  Given some
	/// Observation and action, it outputs the predicted next Observation
	/// and reward.  It is trained using prediction errors computed from
	/// the actual next Observation and reward.
	class PredictiveModel
	{
	public:
		/// Sets up the RLModule to work with the given type of
		/// Observation.  Applies initial noise to trainable Connection
		/// weights.
		VERVE_DECL PredictiveModel(const Observation& obs,
			bool isDynamicRBFEnabled, unsigned int numActions);

		VERVE_DECL virtual ~PredictiveModel();

		/// Resets temporary dynamics without affecting learned parameters.
		VERVE_DECL virtual void VERVE_CALL resetShortTermMemory();

		/// Predicts the current Observation and reward based on the
		/// previous Observation and action.  This also trains the predictors
		/// based on the given actual current Observation and actual
		/// current reward.  On the first step the predicted Observation
		/// and reward will simply be set equal to the actual Observation
		/// and reward.
		VERVE_DECL virtual void VERVE_CALL predictAndTrain(
			const Observation& actualPrevObs,
			unsigned int prevAction, const Observation& actualCurrentObs,
			const real actualCurrentReward, Observation& predCurrentObs,
			real& predCurrentReward, real& predUncertainty);

		/// Predicts the next Observation and reward based on the given
		/// current Observation and action.  Long-term changes occur here
		/// only if 'allowDynamicRBFs' is true.
		VERVE_DECL virtual void VERVE_CALL predict(
			const Observation& actualCurrentObs,
			unsigned int currentAction, Observation& predNextObs,
			real& predNextReward, real& predUncertainty,
			bool allowDynamicRBFCreation);

		/// Updates all step size-dependent factors using the new step size.
		VERVE_DECL virtual void VERVE_CALL changeStepSize(real newValue);

		/// Sets the TD learning rate for the value function and policy.
		/// The time constant (which must be greater than zero) specifies
		/// how many seconds it takes for the value function's prediction
		/// errors to be reduced to 37% of their initial values.  The
		/// policy learning multiplier combined with the value function's
		/// learning rate determines the policy's learning rate (the
		/// multiplier usually ranges from 1-100).
		VERVE_DECL virtual void VERVE_CALL setDeltaLearningRate(
			real timeConstant, real stepSize);

		/// Returns the most recent combined mean squared error for
		/// Observation and reward predictions.
		VERVE_DECL virtual real VERVE_CALL getPredictionMSE();

	protected:
		/// A convenient data structure used to pass data to the
		/// state-action representation.
		RBFInputData mStateActionInputData;

		/// An array used to store the discrete Observation data used
		/// for training.  Instead of keeping discrete data as integer
		/// values, it must be converted to reals within [-1, 1] before
		/// being used for training.
		real* mDiscObsTrainingData;

		/// The state-action representation Population.
		RBFPopulation* mStateActionRepresentation;

		/// The discrete Observation prediction Population.
		Population* mDiscObsPredPopulation;

		/// The continuous Observation prediction Population.
		Population* mContObsPredPopulation;

		/// The reward prediction Population.
		Population* mRewardPredPopulation;

		/// The uncertainty prediction Population.
		Population* mUncertaintyPredPopulation;

		/// A list of all Populations.
		std::vector<Population*> mAllPopulations;

		/// The latest MSE for Observation and reward predictions.
		real mLatestPredMSE;

		/// A time constant that determines the delta rule learning rate.
		real mDeltaLearningTimeConstant;

		/// A precomputed value used for the delta rule learning rate.
		real mDeltaLearningFactor;
	};
}

#endif


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//
// File: StringNative.cpp
//

//
// Purpose: The implementation of the String class.
//

//

#include "common.h"

#include "object.h"
#include "utilcode.h"
#include "excep.h"
#include "frames.h"
#include "field.h"
#include "vars.hpp"
#include "stringnative.h"
#include "comutilnative.h"
#include "metasig.h"
#include "excep.h"

// Compile the string functionality with these pragma flags (equivalent of the command line /Ox flag)
// Compiling this functionality differently gives us significant throughout gain in some cases.
#if defined(_MSC_VER) && defined(_TARGET_X86_)
#pragma optimize("tgy", on)
#endif

/*==================================GETCHARAT===================================
**Returns the character at position index.  Thows IndexOutOfRangeException as
**appropriate.
**This method is not actually used. JIT will generate code for indexer method on string class.
**
==============================================================================*/
FCIMPL2(FC_CHAR_RET, COMString::GetCharAt, StringObject* str, INT32 index) {
    FCALL_CONTRACT;

    FC_GC_POLL_NOT_NEEDED();
    VALIDATEOBJECT(str);
    if (str == NULL) {
        FCThrow(kNullReferenceException);
    }
    _ASSERTE(str->GetMethodTable() == g_pStringClass);

    if (index >=0 && index < (INT32)str->GetStringLength()) {
        //Return the appropriate character.
        return str->GetBuffer()[index];
    }

    FCThrow(kIndexOutOfRangeException);
}
FCIMPLEND

/*==================================LENGTH=================================== */

FCIMPL1(INT32, COMString::Length, StringObject* str) {
    FCALL_CONTRACT;

    FC_GC_POLL_NOT_NEEDED();
    if (str == NULL)
        FCThrow(kNullReferenceException);

    FCUnique(0x11);
    return str->GetStringLength();
}
FCIMPLEND

FCIMPL2(FC_BOOL_RET, COMString::FCTryGetTrailByte, StringObject* thisRefUNSAFE, UINT8 *pbData)
{
    FCALL_CONTRACT;

    STRINGREF thisRef = ObjectToSTRINGREF(thisRefUNSAFE);
    FC_RETURN_BOOL(thisRef->GetTrailByte(pbData));
}
FCIMPLEND

FCIMPL2(VOID, COMString::FCSetTrailByte, StringObject* thisRefUNSAFE, UINT8 bData)
{
    FCALL_CONTRACT;

    STRINGREF thisRef = ObjectToSTRINGREF(thisRefUNSAFE);
    HELPER_METHOD_FRAME_BEGIN_1(thisRef);

    thisRef->SetTrailByte(bData);

    HELPER_METHOD_FRAME_END();
}
FCIMPLEND

// Revert to command line compilation flags
#if defined(_MSC_VER) && defined(_TARGET_X86_)
#pragma optimize ("", on)
#endif