text:
namespace Microsoft.Azure.CognitiveServices.Search.WebSearch
{
    using Microsoft.Rest;
    using Microsoft.Rest.Serialization;
    using Models;
    using Newtonsoft.Json;
    using System.Collections;
    using System.Collections.Generic;
    using System.Net;
    using System.Net.Http;

    /// <summary>
    /// The Web Search API lets you send a search query to Bing and get back
    /// search results that include links to webpages, images, and more.
    /// </summary>
    public partial class WebSearchAPI : ServiceClient<WebSearchAPI>, IWebSearchAPI
    {
        /// <summary>
        /// The base URI of the service.
        /// </summary>
        public System.Uri BaseUri { get; set; }

        /// <summary>
        /// Gets or sets json serialization settings.
        /// </summary>
        public JsonSerializerSettings SerializationSettings { get; private set; }

        /// <summary>
        /// Gets or sets json deserialization settings.
        /// </summary>
        public JsonSerializerSettings DeserializationSettings { get; private set; }

        /// <summary>
        /// Subscription credentials which uniquely identify client subscription.
        /// </summary>
        public ServiceClientCredentials Credentials { get; private set; }

        /// <summary>
        /// Gets the IWeb.
        /// </summary>
        public virtual IWeb Web { get; private set; }

        /// <summary>
        /// Initializes a new instance of the WebSearchAPI class.
        /// </summary>
        /// <param name='handlers'>
        /// Optional. The delegating handlers to add to the http client pipeline.
        /// </param>
        protected WebSearchAPI(params DelegatingHandler[] handlers) : base(handlers)
        {
            Initialize();
        }

        /// <summary>
        /// Initializes a new instance of the WebSearchAPI class.
        /// </summary>
        /// <param name='rootHandler'>
        /// Optional. The http client handler used to handle http transport.
        /// </param>
        /// <param name='handlers'>
        /// Optional. The delegating handlers to add to the http client pipeline.
        /// </param>
        protected WebSearchAPI(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers)
        {
            Initialize();
        }

        /// <summary>
        /// Initializes a new instance of the WebSearchAPI class.
        /// </summary>
        /// <param name='baseUri'>
        /// Optional. The base URI of the service.
        /// </param>
        /// <param name='handlers'>
        /// Optional. The delegating handlers to add to the http client pipeline.
        /// </param>
        /// <exception cref="System.ArgumentNullException">
        /// Thrown when a required parameter is null
        /// </exception>
        protected WebSearchAPI(System.Uri baseUri, params DelegatingHandler[] handlers) : this(handlers)
        {
            if (baseUri == null)
            {
                throw new System.ArgumentNullException("baseUri");
            }
            BaseUri = baseUri;
        }

        /// <summary>
        /// Initializes a new instance of the WebSearchAPI class.
        /// </summary>
        /// <param name='baseUri'>
        /// Optional. The base URI of the service.
        /// </param>
        /// <param name='rootHandler'>
        /// Optional. The http client handler used to handle http transport.
        /// </param>
        /// <param name='handlers'>
        /// Optional. The delegating handlers to add to the http client pipeline.
        /// </param>
        /// <exception cref="System.ArgumentNullException">
        /// Thrown when a required parameter is null
        /// </exception>
        protected WebSearchAPI(System.Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
        {
            if (baseUri == null)
            {
                throw new System.ArgumentNullException("baseUri");
            }
            BaseUri = baseUri;
        }

        /// <summary>
        /// Initializes a new instance of the WebSearchAPI class.
        /// </summary>
        /// <param name='credentials'>
        /// Required. Subscription credentials which uniquely identify client subscription.
        /// </param>
        /// <param name='handlers'>
        /// Optional. The delegating handlers to add to the http client pipeline.
        /// </param>
        /// <exception cref="System.ArgumentNullException">
        /// Thrown when a required parameter is null
        /// </exception>
        public WebSearchAPI(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
        {
            if (credentials == null)
            {
                throw new System.ArgumentNullException("credentials");
            }
            Credentials = credentials;
            if (Credentials != null)
            {
                Credentials.InitializeServiceClient(this);
            }
        }

        /// <summary>
        /// Initializes a new instance of the WebSearchAPI class.
        /// </summary>
        /// <param name='credentials'>
        /// Required. Subscription credentials which uniquely identify client subscription.
        /// </param>
        /// <param name='rootHandler'>
        /// Optional. The http client handler used to handle http transport.
        /// </param>
        /// <param name='handlers'>
        /// Optional. The delegating handlers to add to the http client pipeline.
        /// </param>
        /// <exception cref="System.ArgumentNullException">
        /// Thrown when a required parameter is null
        /// </exception>
        public WebSearchAPI(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
        {
            if (credentials == null)
            {
                throw new System.ArgumentNullException("credentials");
            }
            Credentials = credentials;
            if (Credentials != null)
            {
                Credentials.InitializeServiceClient(this);
            }
        }

        /// <summary>
        /// Initializes a new instance of the WebSearchAPI class.
        /// </summary>
        /// <param name='baseUri'>
        /// Optional. The base URI of the service.
        /// </param>
        /// <param name='credentials'>
        /// Required. Subscription credentials which uniquely identify client subscription.
        /// </param>
        /// <param name='handlers'>
        /// Optional. The delegating handlers to add to the http client pipeline.
        /// </param>
        /// <exception cref="System.ArgumentNullException">
        /// Thrown when a required parameter is null
        /// </exception>
        public WebSearchAPI(System.Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
        {
            if (baseUri == null)
            {
                throw new System.ArgumentNullException("baseUri");
            }
            if (credentials == null)
            {
                throw new System.ArgumentNullException("credentials");
            }
            BaseUri = baseUri;
            Credentials = credentials;
            if (Credentials != null)
            {
                Credentials.InitializeServiceClient(this);
            }
        }

        /// <summary>
        /// Initializes a new instance of the WebSearchAPI class.
        /// </summary>
        /// <param name='baseUri'>
        /// Optional. The base URI of the service.
        /// </param>
        /// <param name='credentials'>
        /// Required. Subscription credentials which uniquely identify client subscription.
        /// </param>
        /// <param name='rootHandler'>
        /// Optional. The http client handler used to handle http transport.
        /// </param>
        /// <param name='handlers'>
        /// Optional. The delegating handlers to add to the http client pipeline.
        /// </param>
        /// <exception cref="System.ArgumentNullException">
        /// Thrown when a required parameter is null
        /// </exception>
        public WebSearchAPI(System.Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
        {
            if (baseUri == null)
            {
                throw new System.ArgumentNullException("baseUri");
            }
            if (credentials == null)
            {
                throw new System.ArgumentNullException("credentials");
            }
            BaseUri = baseUri;
            Credentials = credentials;
            if (Credentials != null)
            {
                Credentials.InitializeServiceClient(this);
            }
        }

        /// <summary>
        /// An optional partial-method to perform custom initialization.
        ///</summary>
        partial void CustomInitialize();
        /// <summary>
        /// Initializes client properties.
        /// </summary>
        private void Initialize()
        {
            Web = new Web(this);
            BaseUri = new System.Uri("https://api.cognitive.microsoft.com/bing/v7.0");
            SerializationSettings = new JsonSerializerSettings
            {
                Formatting = Newtonsoft.Json.Formatting.Indented,
                DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
                DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
                NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
                ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
                ContractResolver = new ReadOnlyJsonContractResolver(),
                Converters = new  List<JsonConverter>
                    {
                        new Iso8601TimeSpanConverter()
                    }
            };
            DeserializationSettings = new JsonSerializerSettings
            {
                DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
                DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
                NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
                ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
                ContractResolver = new ReadOnlyJsonContractResolver(),
                Converters = new List<JsonConverter>
                    {
                        new Iso8601TimeSpanConverter()
                    }
            };
            SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<WebWebGrouping>("_type"));
            DeserializationSettings.Converters.Add(new  PolymorphicDeserializeJsonConverter<WebWebGrouping>("_type"));
            SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<ResponseBase>("_type"));
            DeserializationSettings.Converters.Add(new  PolymorphicDeserializeJsonConverter<ResponseBase>("_type"));
            CustomInitialize();
        }
    }
}


text:
import sys
from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar, Union, cast
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.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.tracing.decorator_async import distributed_trace_async
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling

from ... import models as _models
from ..._vendor import _convert_request
from ...operations._deleted_services_operations import (
    build_get_by_name_request,
    build_list_by_subscription_request,
    build_purge_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 DeletedServicesOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.apimanagement.aio.ApiManagementClient`'s
        :attr:`deleted_services` 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_subscription(self, **kwargs: Any) -> AsyncIterable["_models.DeletedServiceContract"]:
        """Lists all soft-deleted services available for undelete for the given subscription.

        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: An iterator like instance of either DeletedServiceContract or the result of
         cls(response)
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.apimanagement.models.DeletedServiceContract]
        :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.DeletedServicesCollection]

        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(
                    subscription_id=self._config.subscription_id,
                    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("DeletedServicesCollection", 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}/providers/Microsoft.ApiManagement/deletedservices"}  # type: ignore

    @distributed_trace_async
    async def get_by_name(self, service_name: str, location: str, **kwargs: Any) -> _models.DeletedServiceContract:
        """Get soft-deleted Api Management Service by name.

        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param location: The location of the deleted API Management service. Required.
        :type location: str
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: DeletedServiceContract or the result of cls(response)
        :rtype: ~azure.mgmt.apimanagement.models.DeletedServiceContract
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _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.DeletedServiceContract]

        request = build_get_by_name_request(
            service_name=service_name,
            location=location,
            subscription_id=self._config.subscription_id,
            api_version=api_version,
            template_url=self.get_by_name.metadata["url"],
            headers=_headers,
            params=_params,
        )
        request = _convert_request(request)
        request.url = self._client.format_url(request.url)  # type: ignore

        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)

        deserialized = self._deserialize("DeletedServiceContract", pipeline_response)

        if cls:
            return cls(pipeline_response, deserialized, {})

        return deserialized

    get_by_name.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.ApiManagement/locations/{location}/deletedservices/{serviceName}"}  # type: ignore

    async def _purge_initial(
        self, service_name: str, location: str, **kwargs: Any
    ) -> Optional[_models.DeletedServiceContract]:
        error_map = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _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[Optional[_models.DeletedServiceContract]]

        request = build_purge_request(
            service_name=service_name,
            location=location,
            subscription_id=self._config.subscription_id,
            api_version=api_version,
            template_url=self._purge_initial.metadata["url"],
            headers=_headers,
            params=_params,
        )
        request = _convert_request(request)
        request.url = self._client.format_url(request.url)  # type: ignore

        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, 202, 204]:
            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)

        deserialized = None
        if response.status_code == 202:
            deserialized = self._deserialize("DeletedServiceContract", pipeline_response)

        if cls:
            return cls(pipeline_response, deserialized, {})

        return deserialized

    _purge_initial.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.ApiManagement/locations/{location}/deletedservices/{serviceName}"}  # type: ignore

    @distributed_trace_async
    async def begin_purge(self, service_name: str, location: str, **kwargs: Any) -> AsyncLROPoller[None]:
        """Purges Api Management Service (deletes it with no option to undelete).

        :param service_name: The name of the API Management service. Required.
        :type service_name: str
        :param location: The location of the deleted API Management service. Required.
        :type location: str
        :keyword callable cls: A custom type or function that will be passed the direct response
        :keyword str continuation_token: A continuation token to restart a poller from a saved state.
        :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
         this operation to not poll, or pass in your own initialized polling object for a personal
         polling strategy.
        :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
        :keyword int polling_interval: Default waiting time between two polls for LRO operations if no
         Retry-After header is present.
        :return: An instance of AsyncLROPoller that returns either DeletedServiceContract or the result
         of cls(response)
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.apimanagement.models.DeletedServiceContract]
        :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[None]
        polling = kwargs.pop("polling", True)  # type: Union[bool, AsyncPollingMethod]
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token = kwargs.pop("continuation_token", None)  # type: Optional[str]
        if cont_token is None:
            raw_result = await self._purge_initial(  # type: ignore
                service_name=service_name,
                location=location,
                api_version=api_version,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):
            deserialized = self._deserialize("DeletedServiceContract", pipeline_response)
            if cls:
                return cls(pipeline_response, deserialized, {})
            return deserialized

        if polling is True:
            polling_method = cast(
                AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs)
            )  # type: AsyncPollingMethod
        elif polling is False:
            polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else:
            polling_method = polling
        if cont_token:
            return AsyncLROPoller.from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)

    begin_purge.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.ApiManagement/locations/{location}/deletedservices/{serviceName}"}  # type: ignore

redpajama_set_name: RedPajamaGithub


text:
// Copyright (c) 2014-2022 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/

#ifndef TAO_PEGTL_INTERNAL_MARKER_HPP
#define TAO_PEGTL_INTERNAL_MARKER_HPP

#include "../config.hpp"
#include "../rewind_mode.hpp"

namespace TAO_PEGTL_NAMESPACE::internal
{
   template< typename Iterator, rewind_mode M >
   class [[nodiscard]] marker
   {
   public:
      static constexpr rewind_mode next_rewind_mode = M;

      explicit marker( const Iterator& /*unused*/ ) noexcept
      {}

      marker( const marker& ) = delete;
      marker( marker&& ) = delete;

      ~marker() = default;

      marker& operator=( const marker& ) = delete;
      marker& operator=( marker&& ) = delete;

      [[nodiscard]] bool operator()( const bool result ) const noexcept
      {
         return result;
      }
   };

   template< typename Iterator >
   class [[nodiscard]] marker< Iterator, rewind_mode::required >
   {
   public:
      static constexpr rewind_mode next_rewind_mode = rewind_mode::active;

      explicit marker( Iterator& i ) noexcept
         : m_saved( i ),
           m_input( &i )
      {}

      marker( const marker& ) = delete;
      marker( marker&& ) = delete;

      ~marker()
      {
         if( m_input != nullptr ) {
            ( *m_input ) = m_saved;
         }
      }

      marker& operator=( const marker& ) = delete;
      marker& operator=( marker&& ) = delete;

      [[nodiscard]] bool operator()( const bool result ) noexcept
      {
         if( result ) {
            m_input = nullptr;
            return true;
         }
         return false;
      }

      [[nodiscard]] const Iterator& iterator() const noexcept
      {
         return m_saved;
      }

   private:
      const Iterator m_saved;
      Iterator* m_input;
   };

}  // namespace TAO_PEGTL_NAMESPACE::internal

#endif


text:
from .catalog import (
    AttributesConfig,
    Catalog,
    CatalogAttribute,
    CompletionConfig,
    MerchantCenterLink,
    MerchantCenterLinkingConfig,
    ProductLevelConfig,
)
from .catalog_service import (
    AddCatalogAttributeRequest,
    GetAttributesConfigRequest,
    GetCompletionConfigRequest,
    GetDefaultBranchRequest,
    GetDefaultBranchResponse,
    ListCatalogsRequest,
    ListCatalogsResponse,
    RemoveCatalogAttributeRequest,
    ReplaceCatalogAttributeRequest,
    SetDefaultBranchRequest,
    UpdateAttributesConfigRequest,
    UpdateCatalogRequest,
    UpdateCompletionConfigRequest,
)
from .common import (
    AttributeConfigLevel,
    Audience,
    ColorInfo,
    Condition,
    CustomAttribute,
    FulfillmentInfo,
    Image,
    Interval,
    LocalInventory,
    PriceInfo,
    Rating,
    RecommendationsFilteringOption,
    Rule,
    SearchSolutionUseCase,
    SolutionType,
    UserInfo,
)
from .completion_service import CompleteQueryRequest, CompleteQueryResponse
from .control import Control
from .control_service import (
    CreateControlRequest,
    DeleteControlRequest,
    GetControlRequest,
    ListControlsRequest,
    ListControlsResponse,
    UpdateControlRequest,
)
from .export_config import (
    BigQueryOutputResult,
    ExportErrorsConfig,
    ExportMetadata,
    ExportProductsResponse,
    ExportUserEventsResponse,
    OutputResult,
)
from .import_config import (
    BigQuerySource,
    CompletionDataInputConfig,
    GcsSource,
    ImportCompletionDataRequest,
    ImportCompletionDataResponse,
    ImportErrorsConfig,
    ImportMetadata,
    ImportProductsRequest,
    ImportProductsResponse,
    ImportUserEventsRequest,
    ImportUserEventsResponse,
    ProductInlineSource,
    ProductInputConfig,
    UserEventImportSummary,
    UserEventInlineSource,
    UserEventInputConfig,
)
from .model import Model
from .model_service import (
    CreateModelMetadata,
    CreateModelRequest,
    DeleteModelRequest,
    ListModelsRequest,
    ListModelsResponse,
    PauseModelRequest,
    ResumeModelRequest,
    TuneModelMetadata,
    TuneModelRequest,
    TuneModelResponse,
    UpdateModelRequest,
)
from .prediction_service import PredictRequest, PredictResponse
from .product import Product
from .product_service import (
    AddFulfillmentPlacesMetadata,
    AddFulfillmentPlacesRequest,
    AddFulfillmentPlacesResponse,
    AddLocalInventoriesMetadata,
    AddLocalInventoriesRequest,
    AddLocalInventoriesResponse,
    CreateProductRequest,
    DeleteProductRequest,
    GetProductRequest,
    ListProductsRequest,
    ListProductsResponse,
    RemoveFulfillmentPlacesMetadata,
    RemoveFulfillmentPlacesRequest,
    RemoveFulfillmentPlacesResponse,
    RemoveLocalInventoriesMetadata,
    RemoveLocalInventoriesRequest,
    RemoveLocalInventoriesResponse,
    SetInventoryMetadata,
    SetInventoryRequest,
    SetInventoryResponse,
    UpdateProductRequest,
)
from .promotion import Promotion
from .purge_config import (
    PurgeMetadata,
    PurgeProductsMetadata,
    PurgeProductsRequest,
    PurgeProductsResponse,
    PurgeUserEventsRequest,
    PurgeUserEventsResponse,
)
from .search_service import SearchRequest, SearchResponse
from .serving_config import ServingConfig
from .serving_config_service import (
    AddControlRequest,
    CreateServingConfigRequest,
    DeleteServingConfigRequest,
    GetServingConfigRequest,
    ListServingConfigsRequest,
    ListServingConfigsResponse,
    RemoveControlRequest,
    UpdateServingConfigRequest,
)
from .user_event import CompletionDetail, ProductDetail, PurchaseTransaction, UserEvent
from .user_event_service import (
    CollectUserEventRequest,
    RejoinUserEventsMetadata,
    RejoinUserEventsRequest,
    RejoinUserEventsResponse,
    WriteUserEventRequest,
)

__all__ = (
    "AttributesConfig",
    "Catalog",
    "CatalogAttribute",
    "CompletionConfig",
    "MerchantCenterLink",
    "MerchantCenterLinkingConfig",
    "ProductLevelConfig",
    "AddCatalogAttributeRequest",
    "GetAttributesConfigRequest",
    "GetCompletionConfigRequest",
    "GetDefaultBranchRequest",
    "GetDefaultBranchResponse",
    "ListCatalogsRequest",
    "ListCatalogsResponse",
    "RemoveCatalogAttributeRequest",
    "ReplaceCatalogAttributeRequest",
    "SetDefaultBranchRequest",
    "UpdateAttributesConfigRequest",
    "UpdateCatalogRequest",
    "UpdateCompletionConfigRequest",
    "Audience",
    "ColorInfo",
    "Condition",
    "CustomAttribute",
    "FulfillmentInfo",
    "Image",
    "Interval",
    "LocalInventory",
    "PriceInfo",
    "Rating",
    "Rule",
    "UserInfo",
    "AttributeConfigLevel",
    "RecommendationsFilteringOption",
    "SearchSolutionUseCase",
    "SolutionType",
    "CompleteQueryRequest",
    "CompleteQueryResponse",
    "Control",
    "CreateControlRequest",
    "DeleteControlRequest",
    "GetControlRequest",
    "ListControlsRequest",
    "ListControlsResponse",
    "UpdateControlRequest",
    "BigQueryOutputResult",
    "ExportErrorsConfig",
    "ExportMetadata",
    "ExportProductsResponse",
    "ExportUserEventsResponse",
    "OutputResult",
    "BigQuerySource",
    "CompletionDataInputConfig",
    "GcsSource",
    "ImportCompletionDataRequest",
    "ImportCompletionDataResponse",
    "ImportErrorsConfig",
    "ImportMetadata",
    "ImportProductsRequest",
    "ImportProductsResponse",
    "ImportUserEventsRequest",
    "ImportUserEventsResponse",
    "ProductInlineSource",
    "ProductInputConfig",
    "UserEventImportSummary",
    "UserEventInlineSource",
    "UserEventInputConfig",
    "Model",
    "CreateModelMetadata",
    "CreateModelRequest",
    "DeleteModelRequest",
    "ListModelsRequest",
    "ListModelsResponse",
    "PauseModelRequest",
    "ResumeModelRequest",
    "TuneModelMetadata",
    "TuneModelRequest",
    "TuneModelResponse",
    "UpdateModelRequest",
    "PredictRequest",
    "PredictResponse",
    "Product",
    "AddFulfillmentPlacesMetadata",
    "AddFulfillmentPlacesRequest",
    "AddFulfillmentPlacesResponse",
    "AddLocalInventoriesMetadata",
    "AddLocalInventoriesRequest",
    "AddLocalInventoriesResponse",
    "CreateProductRequest",
    "DeleteProductRequest",
    "GetProductRequest",
    "ListProductsRequest",
    "ListProductsResponse",
    "RemoveFulfillmentPlacesMetadata",
    "RemoveFulfillmentPlacesRequest",
    "RemoveFulfillmentPlacesResponse",
    "RemoveLocalInventoriesMetadata",
    "RemoveLocalInventoriesRequest",
    "RemoveLocalInventoriesResponse",
    "SetInventoryMetadata",
    "SetInventoryRequest",
    "SetInventoryResponse",
    "UpdateProductRequest",
    "Promotion",
    "PurgeMetadata",
    "PurgeProductsMetadata",
    "PurgeProductsRequest",
    "PurgeProductsResponse",
    "PurgeUserEventsRequest",
    "PurgeUserEventsResponse",
    "SearchRequest",
    "SearchResponse",
    "ServingConfig",
    "AddControlRequest",
    "CreateServingConfigRequest",
    "DeleteServingConfigRequest",
    "GetServingConfigRequest",
    "ListServingConfigsRequest",
    "ListServingConfigsResponse",
    "RemoveControlRequest",
    "UpdateServingConfigRequest",
    "CompletionDetail",
    "ProductDetail",
    "PurchaseTransaction",
    "UserEvent",
    "CollectUserEventRequest",
    "RejoinUserEventsMetadata",
    "RejoinUserEventsRequest",
    "RejoinUserEventsResponse",
    "WriteUserEventRequest",
)


text:
package net.runelite.api.events;

import lombok.Value;

/**
 * An event where the client has joined or left a clan chat.
 */
@Value
public class ClanChanged
{
	/**
	 * Whether or not the client is now in a clan chat.
	 */
	private boolean joined;
}


text:
using System;
using System.Collections.Specialized;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.Cache;
using System.Threading;
using System.Threading.Tasks;
using eZet.EveLib.Core;
using eZet.EveLib.Core.Cache;
using eZet.EveLib.Core.RequestHandlers;
using eZet.EveLib.Core.Serializers;
using eZet.EveLib.Core.Util;
using eZet.EveLib.EveCrestModule.Exceptions;
using eZet.EveLib.EveCrestModule.Models;
using eZet.EveLib.EveCrestModule.Models.Shared;
using eZet.EveLib.EveCrestModule.RequestHandlers.eZet.EveLib.Core.RequestHandlers;

namespace eZet.EveLib.EveCrestModule.RequestHandlers {
    /// <summary>
    ///     Performs requests on the Eve Online CREST API.
    /// </summary>
    public class CachedCrestRequestHandler : ICachedCrestRequestHandler, IDisposable {
        /// <summary>
        ///     The default public max concurrent requests
        /// </summary>
        public const int DefaultPublicMaxConcurrentRequests = 30;

        /// <summary>
        ///     The default authed max concurrent requests
        /// </summary>
        public const int DefaultAuthedMaxConcurrentRequests = 10;

        /// <summary>
        ///     The defualt charset
        /// </summary>
        public const string DefaultCharset = "utf-8";

        /// <summary>
        ///     The token type
        /// </summary>
        public const string TokenType = "Bearer";

        private readonly TraceSource _trace = new TraceSource("EveLib", SourceLevels.All);
        private int _authedMaxConcurrentRequests;
        private SemaphoreSlim _authedPool;
        private int _publicMaxConcurrentRequests;
        private SemaphoreSlim _publicPool;

        /// <summary>
        ///     Creates a new CachedCrestRequestHandler
        /// </summary>
        /// <param name="serializer"></param>
        public CachedCrestRequestHandler(ISerializer serializer) {
            Serializer = serializer;
            PublicMaxConcurrentRequests = DefaultPublicMaxConcurrentRequests;
            AuthedMaxConcurrentRequests = DefaultAuthedMaxConcurrentRequests;
            _publicPool = new SemaphoreSlim(PublicMaxConcurrentRequests, PublicMaxConcurrentRequests);
            _authedPool = new SemaphoreSlim(AuthedMaxConcurrentRequests, AuthedMaxConcurrentRequests);
            UserAgent = Config.UserAgent;
            Charset = DefaultCharset;
            Cache = Config.CacheFactory("EveCrestCache");
            CacheLevel = CacheLevel.Default;
        }

        /// <summary>
        ///     Gets or sets the cache mode.
        /// </summary>
        /// <value>The cache mode.</value>
        public CacheLevel CacheLevel { get; set; }

        /// <summary>
        ///     Gets or sets the cache used by this request handler
        /// </summary>
        /// <value>The cache.</value>
        public IEveLibCache Cache { get; set; }

        /// <summary>
        ///     Gets or sets the size of the public burst.
        /// </summary>
        /// <value>The size of the public burst.</value>
        public int PublicMaxConcurrentRequests {
            get { return _publicMaxConcurrentRequests; }
            set {
                _publicMaxConcurrentRequests = value;
                _publicPool = new SemaphoreSlim(value, value);
            }
        }

        /// <summary>
        ///     Gets or sets the size of the authed burst.
        /// </summary>
        /// <value>The size of the authed burst.</value>
        public int AuthedMaxConcurrentRequests {
            get { return _authedMaxConcurrentRequests; }
            set {
                _authedMaxConcurrentRequests = value;
                _authedPool = new SemaphoreSlim(value, value);
            }
        }

        /// <summary>
        ///     Sets or gets whether to throw a DeprecatedResourceException when requesting a deprecated resource. This will help
        ///     discover outdated models.
        /// </summary>
        public bool ThrowOnDeprecated { get; set; }

        /// <summary>
        ///     Sets or gets whether to throw a NotImplementedException when requesting a resource model with no ContentType. Used
        ///     for debugging.
        /// </summary>
        public bool ThrowOnMissingContentType { get; set; }

        /// <summary>
        ///     Gets or sets the serializer used to deserialize CREST errors.
        /// </summary>
        public ISerializer Serializer { get; set; }

        /// <summary>
        ///     Gets or sets the x requested with.
        /// </summary>
        /// <value>The x requested with.</value>
        public string XRequestedWith { get; set; }

        /// <summary>
        ///     Gets or sets the user agent.
        /// </summary>
        /// <value>The user agent.</value>
        public string UserAgent { get; set; }

        /// <summary>
        ///     Gets or sets the charset.
        /// </summary>
        /// <value>The charset.</value>
        public string Charset { get; set; }

        /// <summary>
        ///     post as an asynchronous operation.
        /// </summary>
        /// <param name="uri">The URI.</param>
        /// <param name="accessToken">The access token.</param>
        /// <param name="postData">The post data.</param>
        /// <returns>Task<System.String>.</returns>
        public async Task<string> PostAsync(Uri uri, string accessToken, string postData) {
            var request = HttpRequestHelper.CreateRequest(uri);
            request.Method = WebRequestMethods.Http.Post;
            request.ContentType = "application/json";
            string retval = null;
            request.Headers.Add(HttpRequestHeader.Authorization, TokenType + " " + accessToken);
            HttpRequestHelper.AddPostData(request, postData);

            var response = await requestAsync(request, accessToken);
            if (response.StatusCode == HttpStatusCode.Created) {
                retval = response.GetResponseHeader("Location");
            }
            return retval;
        }

        /// <summary>
        ///     put as an asynchronous operation.
        /// </summary>
        /// <param name="uri">The URI.</param>
        /// <param name="accessToken">The access token.</param>
        /// <param name="postData">The post data.</param>
        /// <returns>Task<System.Boolean>.</returns>
        public async Task<bool> PutAsync(Uri uri, string accessToken, string postData) {
            var request = HttpRequestHelper.CreateRequest(uri);
            request.Method = WebRequestMethods.Http.Put;
            request.ContentType = "application/json";
            request.Headers.Add(HttpRequestHeader.Authorization, TokenType + " " + accessToken);
            HttpRequestHelper.AddPostData(request, postData);
            var response = await requestAsync(request, accessToken);
            var retval = response.StatusCode == HttpStatusCode.OK;
            return retval;
        }

        /// <summary>
        ///     delete as an asynchronous operation.
        /// </summary>
        /// <param name="uri">The URI.</param>
        /// <param name="accessToken">The access token.</param>
        /// <returns>Task<System.Boolean>.</returns>
        public async Task<bool> DeleteAsync(Uri uri, string accessToken) {
            var request = HttpRequestHelper.CreateRequest(uri);
            request.Method = "DELETE";
            request.ContentType = "application/json";
            var response = await requestAsync(request, accessToken);
            var retval = response.StatusCode == HttpStatusCode.OK;
            return retval;
        }

        /// <summary>
        ///     options as an asynchronous operation.
        /// </summary>
        /// <param name="uri">The URI.</param>
        /// <returns>Task<CrestOptions>.</returns>
        public async Task<CrestOptions> OptionsAsync(Uri uri) {
            var request = HttpRequestHelper.CreateRequest(uri);
            request.Method = "OPTIONS";
            var response = await requestAsync(request, null).ConfigureAwait(false);
            var content = await HttpRequestHelper.GetResponseContentAsync(response).ConfigureAwait(false);
            var result = Serializer.Deserialize<CrestOptions>(content);
            result.ResponseHeaders = response.Headers;
            result.Uri = uri;
            return result;
        }

        /// <summary>
        ///     head as an asynchronous operation.
        /// </summary>
        /// <param name="uri">The URI.</param>
        /// <param name="accessToken">The access token.</param>
        /// <returns>Task.</returns>
        public async Task<WebHeaderCollection> HeadAsync(Uri uri, string accessToken) {
            var request = HttpRequestHelper.CreateRequest(uri);
            request.Method = WebRequestMethods.Http.Head;
            var response = await requestAsync(request, accessToken).ConfigureAwait(false);
            return response.Headers;
            //var content = await HttpRequestHelper.GetResponseContentAsync(response).ConfigureAwait(false);
            //var result = Serializer.Deserialize<CrestOptions>(content);
        }

        /// <summary>
        ///     get as an asynchronous operation.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="uri">The URI.</param>
        /// <param name="accessToken">The access token.</param>
        /// <returns>Task<T>.</returns>
        public async Task<T> GetAsync<T>(Uri uri, string accessToken)
            where T : class, ICrestResource<T> {
            string responseContent = null;

            if (CacheLevel == CacheLevel.Default || CacheLevel == CacheLevel.CacheOnly)
                responseContent = await Cache.LoadAsync(uri).ConfigureAwait(false);
            var cached = responseContent != null;
            T result;
            if (cached) {
                result = Serializer.Deserialize<T>(responseContent);
                result.IsFromCache = true;
                return result;
            }
            if (CacheLevel == CacheLevel.CacheOnly) return default(T);

            // set up request
            var request = HttpRequestHelper.CreateRequest(uri);
            request.Accept = ContentTypes.Get<T>(ThrowOnMissingContentType) + ";";
            request.CachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.Default);
            request.Method = WebRequestMethods.Http.Get;
            _trace.TraceEvent(TraceEventType.Error, 0, "Initiating Request: " + uri);
            var response = await requestAsync(request, accessToken).ConfigureAwait(false);

            // handle response
            var header = response.Headers;
            responseContent = await HttpRequestHelper.GetResponseContentAsync(response).ConfigureAwait(false);
            if (CacheLevel == CacheLevel.Default || CacheLevel == CacheLevel.Refresh)
                await Cache.StoreAsync(uri, getCacheExpirationTime(header), responseContent).ConfigureAwait(false);
            result = Serializer.Deserialize<T>(responseContent);
            result.ResponseHeaders = header;
            result.Uri = uri;
            return result;
        }

        /// <summary>
        ///     request as an asynchronous operation.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <param name="accessToken">The access token.</param>
        /// <returns>Task<HttpWebResponse>.</returns>
        /// <exception cref="DeprecatedResourceException">The CREST resource is deprecated.</exception>
        /// <exception cref="EveCrestException">
        ///     Undefined error
        ///     or
        ///     or
        /// </exception>
        private async Task<HttpWebResponse> requestAsync(HttpWebRequest request, string accessToken) {
            var mode = accessToken == null ? CrestMode.Public : CrestMode.Authenticated;
            HttpWebResponse response;
            if (!string.IsNullOrEmpty(Charset)) request.Accept = request.Accept + " " + Charset;
            if (!string.IsNullOrEmpty(XRequestedWith)) request.Headers.Add("X-Requested-With", XRequestedWith);
            if (!string.IsNullOrEmpty(UserAgent)) request.UserAgent = UserAgent;
            try {
                if (mode == CrestMode.Authenticated) {
                    request.Headers.Add(HttpRequestHeader.Authorization, TokenType + " " + accessToken);
                    await _authedPool.WaitAsync().ConfigureAwait(false);
                }
                else {
                    await _publicPool.WaitAsync().ConfigureAwait(false);
                }
                response = await HttpRequestHelper.GetResponseAsync(request).ConfigureAwait(false);
                //if (response.StatusCode != HttpStatusCode.OK && response.StatusCode != HttpStatusCode.Created && response.StatusCode != HttpStatusCode.Accepted) {
                //    await throwCrestException(response);
                //}
                var deprecated = response.GetResponseHeader("X-Deprecated");
                if (!string.IsNullOrEmpty(deprecated)) {
                    _trace.TraceEvent(TraceEventType.Warning, 0,
                        "This CREST resource is deprecated. Please update to the newest EveLib version or notify the developers.");
                    if (ThrowOnDeprecated) {
                        throw new DeprecatedResourceException("The CREST resource is deprecated.", response);
                    }
                }
            }
            catch (Exception exception) {
                var e = exception as WebException;
                if (e == null) throw;
                _trace.TraceEvent(TraceEventType.Error, 0, "CREST Request Failed.");
                if (e.Response == null) {
                    throw new EveCrestException(e.Message, e);
                }
                response = (HttpWebResponse) e.Response;

                var responseStream = response.GetResponseStream();
                if (responseStream == null) throw new EveCrestException("Undefined error", e);
                using (var reader = new StreamReader(responseStream)) {
                    var responseContent = reader.ReadToEnd();
                    if (response.StatusCode == HttpStatusCode.InternalServerError ||
                        response.StatusCode == HttpStatusCode.BadGateway)
                        throw new EveCrestException(responseContent, e);
                    var error = Serializer.Deserialize<CrestError>(responseContent);
                    if (error == null) throw new EveCrestException("Undefined error", e);
                    _trace.TraceEvent(TraceEventType.Verbose, 0, "Message: {0}, Key: {1}",
                        "Exception Type: {2}, Ref ID: {3}", error.Message, error.Key, error.ExceptionType,
                        error.RefId);
                    throw new EveCrestException(error.Message, e, error.Key, error.ExceptionType, error.RefId);
                }
            }
            finally {
                // release semaphores
                if (mode == CrestMode.Authenticated) _authedPool.Release();
                else _publicPool.Release();
            }
            return response;
        }

/*
        /// <summary>
        ///     Throws the crest exception.
        /// </summary>
        /// <param name="response">The response.</param>
        /// <returns>Task.</returns>
        /// <exception cref="EveCrestException">null</exception>
        private async Task throwCrestException(HttpWebResponse response) {
            var responseContent = await HttpRequestHelper.GetResponseContentAsync(response);
            var error = Serializer.Deserialize<CrestError>(responseContent);
            _trace.TraceEvent(TraceEventType.Verbose, 0, "Message: {0}, Key: {1}",
                "Exception Type: {2}, Ref ID: {3}", error.Message, error.Key, error.ExceptionType,
                error.RefId);
            throw new EveCrestException(error.Message, null, error.Key, error.ExceptionType, error.RefId);
        }
*/

        /// <summary>
        ///     Gets the cache expiration time.
        /// </summary>
        /// <param name="header">The header.</param>
        /// <returns>DateTime.</returns>
        private static DateTime getCacheExpirationTime(NameValueCollection header) {
            var cache = header.Get("Cache-Control");
            if (cache == null) return DateTime.UtcNow;
            var str = cache.Substring(cache.IndexOf('=') + 1);
            var sec = int.Parse(str);
            return DateTime.UtcNow.AddSeconds(sec);
        }

        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        public void Dispose() {
            Dispose(true);
             GC.SuppressFinalize(this);
        }

        /// <summary>
        /// Releases unmanaged and - optionally - managed resources.
        /// </summary>
        /// <param name="finalize"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
        protected virtual void Dispose(bool finalize) {
            _authedPool.Dispose();
            _publicPool.Dispose();
        }
    }
}


text:
A File Opener Plugin for Cordova. (Forked from original to enable use of Open In-Feature on iOS)

__This plugin is not longer maintained.__

==========================
This plugin will open a file on your device file system with its default application.

Current Version: 0.0.1
----------------

Requirements
-------------
- Android 4 or higher / iOS 6 or higher / WP8
- Cordova 3.0 or higher

Installation
-------------
    cordova plugin add https://github.com/napolitano/cordova-plugin-file-opener3.git

Usage
------
    cordova.plugins.fileOpener3.open(
        filePath,
        fileMIMEType,
        {
            error : function(){ },
            success : function(){ }
        }
    );

Examples
--------
Open an APK install dialog:

    cordova.plugins.fileOpener3.open(
        '/sdcard/Download/gmail.apk',
        'application/vnd.android.package-archive'
    );

Open a PDF document with the default PDF reader and optional callback object:

    cordova.plugins.fileOpener3.open(
        '/sdcard/Download/starwars.pdf', // You can also use a Cordova-style file uri: cdvfile://localhost/persistent/Download/starwars.pdf
        'application/pdf',
        {
            error : function(e) {
                console.log('Error status: ' + e.status + ' - Error message: ' + e.message);
            },
            success : function () {
                console.log('file opened successfully');
            }
        }
    );

Notes
------

- For properly opening _any_ file, you must already have a suitable reader for that particular file type installed on your device. Otherwise this will not work.

- [It is reported](https://github.com/napolitano/cordova-plugin-file-opener3/issues/2#issuecomment-41295793) that in iOS, you might need to remove `<preference name="iosPersistentFileLocation" value="Library" />` from your `config.xml`

- If you are wondering what MIME-type should you pass as the second argument to `open` function, [here is a list of all known MIME-types](http://svn.apache.org/viewvc/httpd/httpd/trunk/docs/conf/mime.types?view=co)

Additional Android Functions
-----------------------------
####The following functions are available in Android platform

###.uninstall(_packageId, callbackContext_)
Uninstall a package with its id.

    cordova.plugins.fileOpener3.uninstall('com.zynga.FarmVille2CountryEscape', {
        error : function(e) {
            console.log('Error status: ' + e.status + ' - Error message: ' + e.message);
        },
        success : function() {
            console.log('Uninstall intent activity started.');
        }
    });

###.appIsInstalled(_packageId, callbackContext_)
Check if an app is already installed.

    cordova.plugins.fileOpener3.appIsInstalled('com.adobe.reader', {
        success : function(res) {
            if (res.status === 0) {
                console.log('Adobe Reader is not installed.');
            } else {
                console.log('Adobe Reader is installed.')
            }
        }
    });

Original Plugin Contributors
----------------------------
[@Gillardo](https://github.com/Gillardo/), [@TankOs](https://github.com/TankOs), [@Rovi23](https://github.com/Rovi23), [@josemanuelbd](https://github.com/josemanuelbd), [@ielcoro](https://github.com/ielcoro)

LICENSE
--------
The MIT License (MIT)

Copyright (c) 2015 Axel Napolitano, Napolitano Business Solutions - axel@napolitano.de

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


text:
title: "Direct sunlight and bokeh"
excerpt: "PaperFaces portrait of Thomas D. drawn with Paper by 53 on an iPad."
image:
  path: &image /assets/images/paperfaces-thomas-d-twitter-lg.jpg
  feature: *image
  teaser: /assets/images/paperfaces-thomas-d-twitter-teaser.jpg
  thumb: /assets/images/paperfaces-thomas-d-twitter-150.jpg
tags: [portrait, illustration, Paper by 53, blend]
last_modified_at: 2017-01-17T14:26:35-05:00
---

PaperFaces portrait commission.

{% include boilerplate/paperfaces-4.md %}

Work in progress screen captures Made with Paper.


text:
package org.jboss.resteasy.plugins.guice;

import static org.jboss.resteasy.test.TestPortProvider.generateBaseUrl;

import com.google.inject.Binder;
import com.google.inject.Guice;
import com.google.inject.Module;

import org.jboss.resteasy.client.ProxyFactory;
import org.jboss.resteasy.core.Dispatcher;
import org.jboss.resteasy.test.EmbeddedContainer;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.ext.ParamConverter;
import javax.ws.rs.ext.ParamConverterProvider;
import javax.ws.rs.ext.Provider;

import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.Arrays;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

public class GuiceContextTest
{
   private Dispatcher dispatcher;

   @Before
   public void beforeClass() throws Exception
   {
      dispatcher = EmbeddedContainer.start().getDispatcher();
   }

   @After
   public void afterClass() throws Exception
   {
      EmbeddedContainer.stop();
   }

   @Test
   public void testMethodInjection()
   {
      final Module module = new Module()
      {
         @Override
         public void configure(final Binder binder)
         {
            binder.bind(MethodTestResource.class);
         }
      };
      final ModuleProcessor processor = new ModuleProcessor(dispatcher.getRegistry(), dispatcher.getProviderFactory());
      processor.processInjector(Guice.createInjector(module));
      final TestResource resource = ProxyFactory.create(TestResource.class, generateBaseUrl());
      Assert.assertEquals("method", resource.getName());
      dispatcher.getRegistry().removeRegistrations(MethodTestResource.class);
   }

   @Test
   public void testFieldInjection()
   {
      final Module module = new Module()
      {
         @Override
         public void configure(final Binder binder)
         {
            binder.bind(FieldTestResource.class);
         }
      };
      final ModuleProcessor processor = new ModuleProcessor(dispatcher.getRegistry(), dispatcher.getProviderFactory());
      processor.processInjector(Guice.createInjector(module));
      final TestResource resource = ProxyFactory.create(TestResource.class, generateBaseUrl());
      Assert.assertEquals("field", resource.getName());
      dispatcher.getRegistry().removeRegistrations(FieldTestResource.class);
   }

   @Test
   public void testArbitraryInjection()
   {
      final Module module = new Module()
      {
         public void configure(final Binder binder)
         {
            // currently the order is important, this test does not fail, if we bind the classes in revers order
            binder.bind(ConversionTestResource.class);
            binder.bind(IntarrayConverterProvider.class);
         }
      };
      final ModuleProcessor processor = new ModuleProcessor(dispatcher.getRegistry(), dispatcher.getProviderFactory());
      processor.processInjector(Guice.createInjector(module));
      ProxyFactory.create(TestResource.class, generateBaseUrl());
   }

   //@Test // not (yet) supprted
   public void testConstructorInjection()
   {
      final Module module = new Module()
      {
         @Override
         public void configure(final Binder binder)
         {
            binder.bind(ConstructorTestResource.class);
         }
      };
      final ModuleProcessor processor = new ModuleProcessor(dispatcher.getRegistry(), dispatcher.getProviderFactory());
      processor.processInjector(Guice.createInjector(module));
      final TestResource resource = ProxyFactory.create(TestResource.class, generateBaseUrl());
      Assert.assertEquals("constructor", resource.getName());
      dispatcher.getRegistry().removeRegistrations(ConstructorTestResource.class);
   }

   @Path("test")
   public interface TestResource
   {
      @GET
      public String getName();
   }

   @Path("test")
   public static class MethodTestResource
   {
      @GET
      public String getName(final @Context UriInfo uriInfo)
      {
         Assert.assertNotNull(uriInfo);
         return "method";
      }
   }

   @Path("test")
   public static class FieldTestResource
   {
      private
      @Context
      UriInfo uriInfo;

      @GET
      public String getName()
      {
         Assert.assertNotNull(uriInfo);
         return "field";
      }
   }

   @Path("test")
   public static class ConstructorTestResource
   {
      private final UriInfo uriInfo;

      public ConstructorTestResource(@Context final UriInfo uriInfo)
      {
         this.uriInfo = uriInfo;
      }

      @GET
      public String getName()
      {
         Assert.assertNotNull(uriInfo);
         return "field";
      }
   }

   @Path("test")
   public static class ConversionTestResource
   {
      @QueryParam("values") Intarray intarray;

      @GET
      public String getName()
      {
         return intarray == null ? "[]" : String.valueOf(intarray.sum());
      }
   }

   public static class Intarray
   {
      private int[] values;

      public Intarray() {}

      public Intarray(int[] values)
      {
         this.values = values;
      }

      @Override
      public String toString()
      {
         return values == null ? "[]" : Arrays.asList(values).toString();
      }

      public int[] getValues()
      {
         return values;
      }

      public void setValues(int[] values)
      {
         this.values = values;
      }

      public int sum()
      {
         if (values == null)
         {
            return 0;
         }
         int sum = 0;
         for (int value : values)
         {
            sum += value;
         }
         return sum;
      }
   }

   @Provider
   public static class IntarrayConverterProvider implements ParamConverterProvider
   {
      @Override
      public <T> ParamConverter<T> getConverter(final Class<T> tClass, Type type, Annotation[] annotations)
      {
         return  tClass == Intarray.class ?
            new ParamConverter<T>()
            {
               @Override
               // for simplicity, does not take "[" and "]" into account
               public T fromString(String s)
               {
                  String[] strings = s.split("\\s*,\\s*");
                  int[] values = new int[strings.length];
                  for (int i = 0; i < strings.length; i++)
                  {
                     values[i] = Integer.valueOf(strings[i]);
                  }
                  return tClass.cast(new Intarray(values));
               }

               @Override
               public String toString(T t)
               {
                  return t.toString();
               }
            } : null;
      }
   }

}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.wangzhe.service;

import com.wangzhe.beans.ConfigParam;
import com.wangzhe.beans.ProxyBean;
import com.wangzhe.util.ArrayUtils;
import com.wangzhe.util.Commons;
import com.wangzhe.util.FileUtils;
import com.wangzhe.ui.HomeController;
import com.wangzhe.util.Constants;
import com.wangzhe.util.ContainerUtils;
import static com.wangzhe.util.HttpUtil.USERAGENT_KEY;
import com.wangzhe.util.NumberUtils;
import com.wangzhe.util.ProxyHttpUtil;
import com.wangzhe.util.RegexUtil;
import java.io.File;
import java.net.HttpURLConnection;
import java.net.Proxy;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
import javafx.application.Platform;

/**
 *
 * @author ocq
 */
public abstract class MailAddrGraber extends AbstractWebSiteOperater {

    protected String mailAddrRelatedPath = "log/" + classSimpleName + "邮箱对应公司信息";
    protected String progressFilePath = "log/" + classSimpleName + "进度";
    //连续多少次找不到结果就结束线程
    protected int maxTryTimeForNoResult = 20;
    protected int currentTryTimeForNoResult = 0;
    public static boolean isStop = false;
//    private static MailAddrGraber instance;
    private static final int CLICK_SUB_URL_DEEP = 3;
    /**
     * 报错邮箱的文件名
     */
    protected String fileName = getClass().getSimpleName() + "的邮箱列表";

    public MailAddrGraber() {
    }

//    public static MailAddrGraber getInstance() {
//        if (instance == null) {
//            instance = new MailAddrGraber();
//        }
//        return instance;
//    }
    /**
     * 开始挖掘入口
     *
     * @param cp.getGrabIds()
     */
    public void startGrab(ConfigParam cp) {

        if (cp.getGrabIds() == null || cp.getGrabIds().size() < 1) {
            return;
        }
        if (cp.getGrabUrls() == null || cp.getGrabUrls().length == 0) {
            cp.setGrabUrls(new String[]{"http://www.baidu.com/"});
        }

        log.info("挖掘中....1");
        int successSiteNum = 0;

//        getProxyFromUrl();
//        getProxyFromFile();
        List<String> urlList = new ArrayList<>();
        ///下面的所有请求都是代理请求,可以把遍历做得简单点,但是为了日后考虑,现在分开
        //遍历每个代理,每个代理去打开一批网址
//        for (String domainUrl : urlList) {
        currentTryTimeForNoResult = 0;//成功次数
        int validProxyNum = 0;
        long time1 = System.currentTimeMillis();
        List<ProxyBean> successProxyList = new ArrayList<>();
        log.info("挖掘中...." + proxyList.size());
        appendLog("开始挖掘.....");
        String[] mailAddrs = getMailAddr(cp);

        //遍历代理
      /*  for (int i = 0; i < proxyList.size(); i++) {
         if (isStop) {
         break;
         }
         if (currentTryTimeForNoResult > cp.getMaxNum()) {
         break;
         }
         proxyBean = proxyList.get(i);
         log.info("使用第" + (i + 1) + "个代理ip");
         appendLog("使用第" + (i + 1) + "个代理ip");
         doHttpGet2("https://www.alipay.com/");
         if (webpageContent != null) {
         saveProxyToFile("重新检验有效代理");
         }
         if (validProxyNum != 0) {
         successSiteNum++;
         log.info(Arrays.toString(cp.getGrabUrls()) + "域名点击任务完成执行完成,使用了的有效代理数量为" + validProxyNum);
         }
         //        }//网站 for end
         log.info("所有网站执行完成,成功数量为" + successSiteNum);
         return;
         }*/
    }

    /**
     * 获取并保存邮箱地址
     *
     * @param i 循环的下标
     * @param requestUrl 请求地址
     * @param cp
     */
    protected void getAndSaveMailAddr(int i, final String requestUrl, ConfigParam cp) {
        appendLog("开始分析用户:" + i + "的邮箱地址");
        final List<String> emails = getEmailFromWebpageContent();
        if (emails != null && emails.size() > 0) {
            writeToTxtFile(emails);
            writeToTxtFile(emails.toString() + "---" + requestUrl, mailAddrRelatedPath);
        }
        final int sleepTime = NumberUtils.getRandomNum(cp.getMinSpeed(), cp.getMaxSpeed());
        Commons.sleep(sleepTime);
        appendLog("休眠" + sleepTime + "毫秒秒后继续挖掘.....");
    }

    /**
     *
     * @param cp
     * @return mail address
     */
    protected abstract String[] getMailAddr(ConfigParam cp);

    /**
     * 获取并保存邮箱
     *
     * @return
     */
    protected List<String> getEmailFromWebpageContent() {
        //([^::@,,\s>\]\"']{2,}@.*.com)//email\\]([^\\[]*)\\[/emai
        //(<[^>(?:email)]*?>)
        return RegexUtil.getList(Constants.MAIL_ADDR_REGEX, webpageContent);
    }

    protected void writeToTxtFile(List<String> emails) {
        writeToTxtFile(emails, fileName);
    }

    protected void writeToTxtFile(List<String> emails, String fileName) {
        if (emails != null) {
            final List<String> repeatEmail = ContainerUtils.removeRepeat(emails);
            final String mailAddrMsg = "即将保存的邮箱数量" + repeatEmail.size() + ",邮箱是:" + repeatEmail;
            log.info(mailAddrMsg);
            appendLog(mailAddrMsg);
            FileUtils.writeToTxtFile(fileName, repeatEmail);
        }
    }

    protected void writeToTxtFile(String content, String fileName) {
        if (content != null) {
            FileUtils.writeToTxtFile(fileName, content);
        }
    }

    @Override
    protected boolean addPublishResult(String publishResultUrl, int status) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    ///////////////////////////////////////////////////////////////////代理点击器实现
    @Override
    protected HttpURLConnection getFixedTimeHttpUrlConnect(String requestUrl, String referUrl) throws Exception {
        getHttpUrlConnect(requestUrl, referUrl);
        setTimeOut(10 * 1000, 10 * 1000);
        return connent;
    }

    @Override
    protected void setDefaultHeader(String referUrl) {
        super.setDefaultHeader(referUrl);
        connent.setRequestProperty(USERAGENT_KEY, ProxyHttpUtil.USERAGENT);
//        connent.setRequestProperty(USERAGENT_KEY, HttpUtil.USERAGENT_IE);
//        connent.setRequestProperty(REFERER_KEY, myReferUrl);
    }

//    @Override
//    protected HttpURLConnection getHttpUrlConnect(String requestUrl, String referUrl) throws Exception {
//
//        if (proxyBean == null) {
//            connent = (HttpURLConnection) new URL(appendUrlToDomain(requestUrl)).openConnection();
////            return null;
//        } else {
//            setProxyRequest();
//
//            log.info("Thread" + Thread.currentThread().getId() + ":取到的代理是:" + proxyBean.getHost() + ":" + proxyBean.getPort());
//            Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyBean.getHost(), proxyBean.getPort()));
//            connent = (HttpURLConnection) new URL(appendUrlToDomain(requestUrl)).openConnection(proxy);
//        }
////        if (proxyBean == null) {
////            return null;
////        }
////        Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyBean.getHost(), proxyBean.getPort()));
////        connent = (HttpURLConnection) new URL(appendUrlToDomain(requestUrl)).openConnection(proxy);
//
//        setDefaultHeader(referUrl);
//        return connent;
//    }
//    protected void setProxyRequest() {
//        System.setProperty("proxyType", "4");
//        //通知Java您要通过代理进行连接
//        System.setProperty("proxySet", "true");
//        //指定代理所在的服务器
//        System.setProperty("proxyHost", proxyBean.getHost());
//        //指定代理监听的端口
//        System.setProperty("proxyPort", Integer.toString(proxyBean.getPort()));
//    }
    private final static String myReferUrl = "http://www.wangdaituiguangbao.com/daohang.htm";
    final int sleepTime = 2;
    static String fileString;
    public static String waitObj;
    //(\d+.\d+.\d+.\d+)	(\d+)
    //(\d+.\d+.\d+.\d+)	\s*(\d+)
    public static List<ProxyBean> proxyList = new ArrayList<>();

    //http://www.xici.net.co/
    public static String[] getProxyPageUrls = new String[]{
        "http://www.xici.net.co/nn/",
        "http://www.xici.net.co/nt/",
        "http://www.xici.net.co/wn/",
        "http://www.xici.net.co/wt/",
        "http://www.xici.net.co/qq/"};

    /**
     * 从文件读取代理ip
     */
    public void getProxyFromFile() {
        List<String> proxys = FileUtils.readTxtFileList("有效代理.txt");
//        proxys = ContainerUtils.removeRepeat(proxys);
        if (proxys.size() > 0) {
            String[] infos = proxys.get(0).split("\t");
//            if (infos.length > 4) {
            int i = 0;
            for (String proxyStr : proxys) {
                i++;
                infos = proxyStr.split("\t");
//                log.info(infos[0] + "\t" + Integer.valueOf(infos[1]) + "\t" + infos[3] + "\t" + infos[4]);
                //过滤匿名代理
                if (infos.length > 4) {
                    proxyList.add(new ProxyBean(infos[0], Integer.valueOf(infos[1]), infos[3], infos[4], Proxy.Type.SOCKS));

                } else {
                    proxyList.add(new ProxyBean(infos[0], Integer.valueOf(infos[1])));
                }

//                }
            }
            if (proxyList.size() > 0) {
                return;
            }

        }

        //从文件读取
//        webpageContent = FileUtils.readTxtFile("代理ip.txt");s
        webpageContent = FileUtils.readTxtFile("有效代理.txt");
        log.info("代理文件内容" + webpageContent);
        getProxyFromWebPageContent();
        log.info("");

    }

    /**
     * 从网络读取代理ip
     */
    public void getProxyFromUrl() {

        int maxPage = 0;
        try {
            for (String getProxyPageUrl : getProxyPageUrls) {

                //打开栏目页,计算最大分页数
                //从网页读取
                getProxyPageUrl = getProxyPageUrl.concat(String.valueOf(1));
                doHttpGet(getProxyPageUrl);
                getProxyFromWebPageContent();
                String maxPageStr = RegexUtil.getFirstString(">(\\d+)[^<]*?]*?class=[\"']{0,1}next_page", webpageContent);
                if (maxPageStr != null) {
                    maxPage = Integer.valueOf(maxPageStr);
                } else {
                    maxPage = 200;
                }

                ///////////遍历所有分页
                for (int page = 2; page <= maxPage + 2; page++) {
                    getProxyPageUrl = getProxyPageUrl.replaceAll("\\d+", String.valueOf(page));
                    doHttpGet(getProxyPageUrl);
                    getProxyFromWebPageContent();
                }
            }
        } finally {//无论发生什么异常,我都保存一下

            StringBuilder sb = new StringBuilder(2000);
            //写到本地文件
            for (ProxyBean proxyBean : proxyList) {
                sb.append(proxyBean.getHost()).append("\t").append(proxyBean.getPort()).append("\r\n");
            }
            File proxyFile = new File("代理ip.txt");
            FileUtils.saveTxtFile(proxyFile, sb.toString());
        }

    }

    protected void getProxyFromWebPageContent() throws NumberFormatException {
//        Map<String, String> proxyMap = null;
        //(\d+.\d+.\d+.\d+)\t(\d+)
//        if (webpageContent != null && !webpageContent.contains("")) {
//            proxyMap = RegexUtil.getMap("(\\d+.\\d+.\\d+.\\d+)\\t(\\d+)", webpageContent);
//        } else {
//            proxyMap = RegexUtil.getMap("(\\d+.\\d+.\\d+.\\d+)	\\s*(\\d+)	", webpageContent);
//        }
//        for (String key : proxyMap.keySet()) {
//            proxyList.add(new ProxyBean(key, Integer.valueOf(proxyMap.get(key))));
//        }
        String[][] proxyListTemp = null;
        //由于端口不同也可以,所以用list
        if (webpageContent != null && !webpageContent.contains("") && !webpageContent.contains("代理")) {
            proxyListTemp = RegexUtil.getArray2("(\\d+.\\d+.\\d+.\\d+):(\\d+)", webpageContent);
            if (proxyListTemp == null || proxyListTemp.length == 0) {
                proxyListTemp = RegexUtil.getArray2("(\\d+.\\d+.\\d+.\\d+)\\t(\\d+)", webpageContent);
            }

        } else {
            if (proxyListTemp == null || proxyListTemp.length == 0) {
                proxyListTemp = RegexUtil.getArray2("(\\d+.\\d+.\\d+.\\d+)	\\s*[\\s\\S]*?>(\\d+)	", webpageContent);
            }
            if (proxyListTemp == null || proxyListTemp.length == 0) {
                proxyListTemp = RegexUtil.getArray2("(\\d+.\\d+.\\d+.\\d+)	\\s*[\\s\\S]*?>(\\d+)	", webpageContent);
            }
            if (proxyListTemp == null || proxyListTemp.length == 0) {
                proxyListTemp = RegexUtil.getArray2("(\\d+.\\d+.\\d+.\\d+):(\\d+)", webpageContent);
            }
            //(\d+.\d+.\d+.\d+) (\d+)
        }
        if (proxyListTemp == null) {
            return;
        }

        for (String[] proxyText : proxyListTemp) {
//            String[][] proxyMapTemp = RegexUtil.getArray2("(\\d+.\\d+.\\d+.\\d+)\\t(\\d+)", proxyText);
            if (ArrayUtils.isEmpty(proxyText)) {
                continue;
            }
            //过滤验证代理
            if (proxyText.length > 2) {
                continue;
            }

            try {
                proxyList.add(new ProxyBean(proxyText[0], Integer.valueOf(proxyText[1])));
            } catch (Exception e) {
            }
        }

    }
    public static String webPageHtml;

    public void getProxyByNeizhiLiuLanQi() {
        while (true) {

            FutureTask<Map<String, Object>> futureTask = new FutureTask(new Callable<Map<String, Object>>() {
                @Override
                public Map<String, Object> call() throws Exception {

                    return null;
                }
            });
            Platform.runLater(futureTask);
            Commons.sleepSecond(60 * 10);
        }
    }

    int tryTime = 0;//成功次数

    private void saveProxyToFile(String fileName) {
        StringBuilder sb = new StringBuilder();
        sb.append(proxyBean.getHost()).append("\t").append(proxyBean.getPort());

        FileUtils.writeToTxtFile(fileName, sb.toString());
    }

    private void getProxyFromNeiZhiliulanqi(String webPageHtml) throws NumberFormatException {
        try {
            webpageContent = webPageHtml;
            getProxyFromWebPageContent();

        } finally {//无论发生什么异常,我都保存一下

            StringBuilder sb = new StringBuilder(2000);
            //写到本地文件
            for (ProxyBean proxyBean : proxyList) {
                sb.append(proxyBean.getHost()).append("\t").append(proxyBean.getPort()).append("\r\n");
            }
            File proxyFile = new File("代理ip.txt");

            FileUtils.writeToFile("D:\\CloudsSaaS\\自动抓取代理ip.txt", sb.toString());

            proxyList.clear();
        }
    }

    public static void main(String[] args) {
//        new UrlClicker().click(null, 100);
    }

    @Override
    protected void updateStatusToDB() {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    protected void updateAnonymousStatusToDB() {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    protected void updateSuccessInfoToDB() {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public void delSiteEmailRefer() {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    public void appendLog(String msg) {
        Platform.runLater(() -> {
            HomeController.instance.fx_txtareaLog.appendText(msg + "\r\n");
        });

    }

    public void clearLog() {
        if (HomeController.instance.fx_txtareaLog.getText().length() > 1000) {
            Platform.runLater(() -> {
                HomeController.instance.fx_txtareaLog.setText("");
            });
        }
    }

    @Override
    public void setSiteUrl(String siteUrl) {
        super.setSiteUrl(siteUrl);
    }
    //根据list判断是否需要继续运行线程爬取
    protected boolean isRun(List<String> companyUrls) {
        if (Commons.isEmpty(companyUrls)) {
            currentTryTimeForNoResult++;
            if (currentTryTimeForNoResult > maxTryTimeForNoResult) {
                return false;
            }
        } else {
            currentTryTimeForNoResult = 0;
        }
        return true;
    }
}


text:
 "use strict";

/**
 * Main WoT Framework
 */
var Framework = require('../lib/framework');

/**
 * Main Server Modules
 */
var CoapBroker = require("../lib/coapServer/server")
  , Router = require("../lib/coapServer/router")
  , RequestHandlers = require("../lib/coapServer/requestHandlers");

/**
 * Util Modules
 */
var merge = require('utils-merge');

/**
 * CoAP URL Router
 */
var coapHandlers = {
   "/object/([A-Za-z0-9-]+)/send": RequestHandlers.sendProxyingWebSocket,
   "/object/([A-Za-z0-9-]+)/viewer": RequestHandlers.viewer,
   "/object/([A-Za-z0-9-]+)/status": RequestHandlers.status
};

/*
 * Prototype and Class
 */
var Server = function () {
  this.server = null;
  this.callbacks = {
    ondata: function() { return 0; },
    onnewthing: function() { return 0; },
    onstart: function() { return 0; }
  };
};

/**
 * Event Callback System
 */
Server.prototype.onNewThing = function(thing) {
  // Call framework APIs
  this.registerThing(thing);
  this.callbacks['onnewthing'](thing);
};

/**
 * Event callback factory
 */
Server.prototype.onData = function(payload) {
  // Call framework APIs
  //console.log('<DATA> ' + payload.data);
  this.callbacks['ondata'](payload);
};

/**
 * Event callback factory
 */
Server.prototype.onStart = function(payload) {
  this.callbacks['onstart'](payload);
};

/**
 * Create an WoT server.
 *
 * @return {Object}
 * @api public
 */
function createServer(options) {
  var instance = new Server();
  return merge(instance, options);
}

/**
 * Start a CoAP server.
 *
 * @return {None}
 * @api public
 */
Server.prototype.start = function(options) {
  var port = process.env.PORT ? parseInt(process.env.PORT) : 8000;
  var host = process.env.HOST ? String(process.env.HOST) : 'localhost';
  var endpoints = [];

  if (options && options.endpoints) {
    endpoints = options.endpoints;
  } else if (typeof process.env.ENDPOINT === 'string') {
    endpoints.push(process.env.ENDPOINT);
  }

  if (options && options.ondata && typeof options.ondata === 'function')
    this.callbacks['ondata'] = options.ondata;

  if (options && options.onnewthing && typeof options.onnewthing === 'function')
    this.callbacks['onnewthing'] = options.onnewthing;

  if (options && options.onstart && typeof options.onstart === 'function')
    this.callbacks['onstart'] = options.onstart;

  var server = new CoapBroker({
    port: port,
    host: host,
    endpoints: endpoints
  });
  var router = new Router();

  // Events callback factory
  server.on('newThing', this.onNewThing.bind(this));
  server.on('data', this.onData.bind(this));
  server.on('start', this.onStart.bind(this));

  server.startAsProxy(router.route, coapHandlers);

  this.server = server;
};

/**
 * Shutdown the CoAP server.
 *
 * @param cb {Function} The complete callback
 * @return {}
 * @api public
 */
Server.prototype.shutdown = function(cb) {
  if (this.server)
    this.server.shutdown(cb);
}

/**
 * Create the server instance.
 */
var coapBrokerImpl = createServer({});

/**
 * Combined server with framework instance.
 */
var coapServer = new Framework({
  server: coapBrokerImpl
});

if (typeof(module) != "undefined" && typeof(exports) != "undefined")
  module.exports = coapServer;

/**
 * Start the server.
 */
if (!module.parent)
  coapServer.start();


text:
<!DOCTYPE html>

    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>mne.viz.plot_csd — MNE 0.17.1 documentation</title>
    <link rel="stylesheet" href="../_static/bootstrap-sphinx.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <link rel="stylesheet" type="text/css" href="../_static/gallery.css" />
    <link rel="stylesheet" type="text/css" href="../_static/reset-syntax.css" />

    <link rel="shortcut icon" href="../_static/favicon.ico"/>
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />

    <link rel="stylesheet" href="../_static/style.css " type="text/css" />
    <link rel="stylesheet" href="../_static/font-awesome.css" type="text/css" />
    <link rel="stylesheet" href="../_static/flag-icon.css" type="text/css" />

  <link rel="canonical" href="https://mne.tools/stable/index.html" />

        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".nav-collapse">

        </button>

        0.17.1

Install

Documentation

API

Glossary

Examples

Contribute

  Site

  <button type="button" class="btn btn-primary navbar-btn dropdown-toggle" id="dropdownMenu1" data-toggle="dropdown">
    v0.17.1

  </button>

Development

v0.17 (stable)

v0.16

v0.15

v0.14

v0.13

v0.12

v0.11

<form class="navbar-form navbar-right" action="../search.html" method="get">

  <input type="text" name="q" class="form-control" placeholder="Search" />

  <input type="hidden" name="check_keywords" value="yes" />
  <input type="hidden" name="area" value="default" />
</form>

mne.viz.plot_csd

<form action="../search.html" method="get">

  <input type="text" name="q" class="form-control" placeholder="Search" />

  <input type="hidden" name="check_keywords" value="yes" />
  <input type="hidden" name="area" value="default" />
</form>

mne.viz.plot_csd¶

mne.viz.plot_csd(csd, info=None, mode='csd', colorbar=True, cmap=None, n_cols=None, show=True)[source]¶

Plot CSD matrices.

A sub-plot is created for each frequency. If an info object is passed to
the function, different channel types are plotted in different figures.

<col class="field-name" />
<col class="field-body" />

Parameters:

csd : instance of CrossSpectralDensity

The CSD matrix to plot.

info: instance of Info | None

To split the figure by channel-type, provide the measurement info.
By default, the CSD matrix is plotted as a whole.

mode : 'csd' | 'coh'

Whether to plot the cross-spectral density ('csd', the default), or
the coherence ('coh') between the channels.

colorbar : bool

Whether to show a colorbar. Defaults to True.

cmap : str | None

The matplotlib colormap to use. Defaults to None, which means the
colormap will default to matplotlib's default.

n_cols : int | None

CSD matrices are plotted in a grid. This parameter controls how
many matrix to plot side by side before starting a new row. By
default, a number will be chosen to make the grid as square as
possible.

show : bool

Whether to show the figure. Defaults to True.

Returns:

fig : list of matplotlib figures

The figures created by this function.

GitHub

·

Mailing list

·

Gitter

·

What's new

·

Cite MNE

Back to top

© Copyright 2012-2019, MNE Developers. Last updated on 2019-02-22.


text:
<?php
/*
Plugin Name: WP Migrate DB Pro Multisite Tools
Plugin URI: http://deliciousbrains.com/wp-migrate-db-pro/
Description: An extension to WP Migrate DB Pro, supporting Multisite migrations.
Author: Delicious Brains
Version: 1.1.1
Author URI: http://deliciousbrains.com
Network: True
*/

// Copyright (c) 2015 Delicious Brains. All rights reserved.
//
// Released under the GPL license
// http://www.opensource.org/licenses/gpl-license.php
//
// **********************************************************************
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// **********************************************************************

require_once 'version.php';
$GLOBALS['wpmdb_meta']['wp-migrate-db-pro-multisite-tools']['folder'] = basename( plugin_dir_path( __FILE__ ) );

/**
 * Populate the $wpmdbpro_multisite_tools global with an instance of the WPMDBPro_Multisite_Tools class and return it.
 *
 * @param bool $cli
 *
 * @return WPMDBPro_Multisite_Tools The one true global instance of the WPMDBPro_Multisite_Tools class.
 */
function wp_migrate_db_pro_multisite_tools( $cli = false ) {
	global $wpmdbpro_multisite_tools;

	if ( ! class_exists( 'WPMDBPro_Addon' ) ) {
		return false;
	}

	// Allows hooks to bypass the regular admin / ajax checks to force load the addon (required for the CLI addon).
	$force_load = apply_filters( 'wp_migrate_db_pro_multisite_tools_force_load', false );

	if ( false === $force_load && ! is_null( $wpmdbpro_multisite_tools ) ) {
		return $wpmdbpro_multisite_tools;
	}

	if ( false === $force_load && ( ! function_exists( 'wp_migrate_db_pro_loaded' ) || ! wp_migrate_db_pro_loaded() || ( is_multisite() && wp_is_large_network() ) ) ) {
		return false;
	}

	load_plugin_textdomain( 'wp-migrate-db-pro-multisite-tools', false, dirname( plugin_basename( __FILE__ ) ) . '/languages/' );

	require_once dirname( __FILE__ ) . '/class/wpmdbpro-multisite-tools.php';

	if ( $cli ) {
		require_once dirname( __FILE__ ) . '/class/cli/wpmdbpro-multisite-tools-cli.php';

		$wpmdbpro_multisite_tools = new WPMDBPro_Multisite_Tools_CLI( __FILE__ );
	} else {
		$wpmdbpro_multisite_tools = new WPMDBPro_Multisite_Tools( __FILE__ );
	}

	return $wpmdbpro_multisite_tools;
}

/**
 * By default load plugin on admin pages, a little later than WP Migrate DB Pro.
 */
add_action( 'admin_init', 'wp_migrate_db_pro_multisite_tools', 20 );

/**
 * Loads up an instance of the WPMDBPro_Multisite_Tools class, allowing Multisite Tools functionality to be used during CLI migrations.
 */
function wp_migrate_db_pro_multisite_tools_before_cli_load() {
	// Force load the Multisite Tools addon
	add_filter( 'wp_migrate_db_pro_multisite_tools_force_load', '__return_true' );

	wp_migrate_db_pro_multisite_tools( true );
}

add_action( 'wp_migrate_db_pro_cli_before_load', 'wp_migrate_db_pro_multisite_tools_before_cli_load' );


text:
using System;

namespace DecoratorPattern
{
    internal class CoffeeConcreteComponent : IComponent
    {
        public void DoSomething()
        {
            Console.Write("Coffee");
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<widget id="com.ionicframework.ionictutorial966603" version="0.0.1" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">
  <name>mend</name>
  <description>Realtime Home Services Locator</description>
  <author href="https://google.com/">RNATA</author>
  <content src="index.html"/>
  <access origin="*"/>
  <icon src="resources/ios/icon/icon.png"/>
  <allow-navigation href="*"/>
  <allow-intent href="http://*/*"/>
  <allow-intent href="https://*/*"/>
  <allow-intent href="tel:*"/>
  <allow-intent href="sms:*"/>
  <allow-intent href="mailto:*"/>
  <allow-intent href="geo:*"/>
  <platform name="android">
    <allow-intent href="market:*"/>
  </platform>
  <platform name="ios">
    <allow-intent href="itms:*"/>
    <allow-intent href="itms-apps:*"/>
    <icon src="resources/ios/icon/icon.png" width="57" height="57"/>
    <icon src="resources/ios/icon/icon-40.png" width="40" height="40"/>
    <icon src="resources/ios/icon/icon-50.png" width="50" height="50"/>
    <icon src="resources/ios/icon/icon-small.png" width="29" height="29"/>
    <splash src="resources/ios/splash/Default-568h@2x~iphone.png" width="640" height="1136"/>
    <splash src="resources/ios/splash/Default-667h.png" width="750" height="1334"/>
    <splash src="resources/ios/splash/Default-736h.png" width="1242" height="2208"/>
    <splash src="resources/ios/splash/Default-Landscape-736h.png" width="2208" height="1242"/>
    <splash src="resources/ios/splash/Default-Landscape@2x~ipad.png" width="2048" height="1536"/>
    <splash src="resources/ios/splash/Default-Landscape@~ipadpro.png" width="2732" height="2048"/>
    <splash src="resources/ios/splash/Default-Landscape~ipad.png" width="1024" height="768"/>
    <splash src="resources/ios/splash/Default-Portrait@2x~ipad.png" width="1536" height="2048"/>
    <splash src="resources/ios/splash/Default-Portrait@~ipadpro.png" width="2048" height="2732"/>
    <splash src="resources/ios/splash/Default-Portrait~ipad.png" width="768" height="1024"/>
    <splash src="resources/ios/splash/Default@2x~iphone.png" width="640" height="960"/>
    <splash src="resources/ios/splash/Default~iphone.png" width="320" height="480"/>
  </platform>
  <preference name="Orientation" value="portrait"/>
  <preference name="webviewbounce" value="false"/>
  <preference name="UIWebViewBounce" value="false"/>
  <preference name="DisallowOverscroll" value="false"/>
  <preference name="android-minSdkVersion" value="16"/>
  <preference name="BackupWebStorage" value="none"/>
  <preference name="SplashMaintainAspectRatio" value="true"/>
  <preference name="FadeSplashScreenDuration" value="300"/>
  <preference name="SplashShowOnlyFirstTime" value="true"/>
  <feature name="StatusBar">
    <param name="ios-package" onload="true" value="CDVStatusBar"/>
  </feature>
  <plugin name="ionic-plugin-keyboard" spec="~2.2.1"/>
  <plugin name="cordova-plugin-whitelist" spec="1.3.1"/>
  <plugin name="cordova-plugin-console" spec="1.0.5"/>
  <plugin name="cordova-plugin-statusbar" spec="2.2.1"/>
  <plugin name="cordova-plugin-device" spec="1.1.4"/>
  <plugin name="cordova-plugin-splashscreen" spec="~4.0.1"/>
</widget>


text:
from aisikl.events import action_event
from .actionablecontrol import ActionableControl

class Button(ActionableControl):
    def __init__(self, dialog, id, type, parent_id, properties, element):
        super().__init__(dialog, id, type, parent_id, properties, element)
        self.image = properties.get('img')
        self.confirm_question = element.get('confirmquestion')
        self.access_key = element.get('accesskey')
        if isinstance(self.access_key, list):
            self.access_key = ' '.join(self.access_key)  # BeautifulSoup :(

    def _ais_setAccessKey(self, value):
        self.access_key = value
    def _ais_setImage(self, value):
        self.image = value
    def _ais_setConfirmQuestion(self, value):
        self.confirm_question = value

    def click(self):
        self.log('action', 'Clicking {}'.format(self.id))

        if self.try_execute_action(): return

        ev = action_event(self, None, self.id)
        # TODO: We should technically ask confirm_question before firing
        # (if ev.listening is True), but we probably don't care.
        self.dialog.app.send_events(ev)

        # Note that showPopupMenus() is unsupported. Use menu items directly.


text:
using System;
using System.Collections.Generic;
using Twilio;
using Twilio.Rest.Preview.DeployedDevices.Fleet

public class Example
{
    public static void Main(string[] args)
    {
        // Get your Account SID and Auth Token from https://twilio.com/console
        // To set up environmental variables, see http://twil.io/secure
        const string accountSid = Environment.GetEnvironmentVariable("TWILIO_ACCOUNT_SID");
        const string authToken = Environment.GetEnvironmentVariable("TWILIO_AUTH_TOKEN");
        TwilioClient.Init(accountSid, authToken);

        const string fleetSid = "FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
        const string deviceSid = "THXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
        const bool wasDeleted = DeviceResource.Delete(fleetSid, deviceSid);

        Console.WriteLine(wasDeleted);
    }
}