text:
<?php

/*
 * GENERATED CODE WARNING
 * Generated by gapic-generator-php from the file
 * https://github.com/googleapis/googleapis/blob/master/google/cloud/domains/v1beta1/domains.proto
 * Updates to the above are reflected here through a refresh process.
 *
 * @experimental
 */

namespace Google\Cloud\Domains\V1beta1\Gapic;

use Google\ApiCore\ApiException;
use Google\ApiCore\CredentialsWrapper;
use Google\ApiCore\GapicClientTrait;

use Google\ApiCore\LongRunning\OperationsClient;
use Google\ApiCore\OperationResponse;

use Google\ApiCore\PathTemplate;

use Google\ApiCore\RequestParamsHeaderDescriptor;
use Google\ApiCore\RetrySettings;
use Google\ApiCore\Transport\TransportInterface;
use Google\ApiCore\ValidationException;
use Google\Auth\FetchAuthTokenInterface;
use Google\Cloud\Domains\V1beta1\AuthorizationCode;
use Google\Cloud\Domains\V1beta1\ConfigureContactSettingsRequest;

use Google\Cloud\Domains\V1beta1\ConfigureDnsSettingsRequest;
use Google\Cloud\Domains\V1beta1\ConfigureManagementSettingsRequest;
use Google\Cloud\Domains\V1beta1\ContactSettings;
use Google\Cloud\Domains\V1beta1\DeleteRegistrationRequest;
use Google\Cloud\Domains\V1beta1\DnsSettings;
use Google\Cloud\Domains\V1beta1\ExportRegistrationRequest;
use Google\Cloud\Domains\V1beta1\GetRegistrationRequest;
use Google\Cloud\Domains\V1beta1\ListRegistrationsRequest;
use Google\Cloud\Domains\V1beta1\ListRegistrationsResponse;
use Google\Cloud\Domains\V1beta1\ManagementSettings;
use Google\Cloud\Domains\V1beta1\RegisterDomainRequest;
use Google\Cloud\Domains\V1beta1\Registration;
use Google\Cloud\Domains\V1beta1\ResetAuthorizationCodeRequest;
use Google\Cloud\Domains\V1beta1\RetrieveAuthorizationCodeRequest;
use Google\Cloud\Domains\V1beta1\RetrieveRegisterParametersRequest;
use Google\Cloud\Domains\V1beta1\RetrieveRegisterParametersResponse;
use Google\Cloud\Domains\V1beta1\RetrieveTransferParametersRequest;
use Google\Cloud\Domains\V1beta1\RetrieveTransferParametersResponse;
use Google\Cloud\Domains\V1beta1\SearchDomainsRequest;
use Google\Cloud\Domains\V1beta1\SearchDomainsResponse;
use Google\Cloud\Domains\V1beta1\TransferDomainRequest;
use Google\Cloud\Domains\V1beta1\UpdateRegistrationRequest;
use Google\LongRunning\Operation;
use Google\Protobuf\FieldMask;
use Google\Type\Money;

/**
 * Service Description: The Cloud Domains API enables management and configuration of domain names.
 *
 * This class provides the ability to make remote calls to the backing service through method
 * calls that map to API methods. Sample code to get started:
 *
 * ```
 * $domainsClient = new DomainsClient();
 * try {
 *     $formattedRegistration = $domainsClient->registrationName('[PROJECT]', '[LOCATION]', '[REGISTRATION]');
 *     $updateMask = new FieldMask();
 *     $operationResponse = $domainsClient->configureContactSettings($formattedRegistration, $updateMask);
 *     $operationResponse->pollUntilComplete();
 *     if ($operationResponse->operationSucceeded()) {
 *         $result = $operationResponse->getResult();
 *     // doSomethingWith($result)
 *     } else {
 *         $error = $operationResponse->getError();
 *         // handleError($error)
 *     }
 *     // Alternatively:
 *     // start the operation, keep the operation name, and resume later
 *     $operationResponse = $domainsClient->configureContactSettings($formattedRegistration, $updateMask);
 *     $operationName = $operationResponse->getName();
 *     // ... do other work
 *     $newOperationResponse = $domainsClient->resumeOperation($operationName, 'configureContactSettings');
 *     while (!$newOperationResponse->isDone()) {
 *         // ... do other work
 *         $newOperationResponse->reload();
 *     }
 *     if ($newOperationResponse->operationSucceeded()) {
 *         $result = $newOperationResponse->getResult();
 *     // doSomethingWith($result)
 *     } else {
 *         $error = $newOperationResponse->getError();
 *         // handleError($error)
 *     }
 * } finally {
 *     $domainsClient->close();
 * }
 * ```
 *
 * Many parameters require resource names to be formatted in a particular way. To
 * assist with these names, this class includes a format method for each type of
 * name, and additionally a parseName method to extract the individual identifiers
 * contained within formatted names that are returned by the API.
 *
 * @experimental
 */
class DomainsGapicClient
{
    use GapicClientTrait;

    /**
     * The name of the service.
     */
    const SERVICE_NAME = 'google.cloud.domains.v1beta1.Domains';

    /**
     * The default address of the service.
     */
    const SERVICE_ADDRESS = 'domains.googleapis.com';

    /**
     * The default port of the service.
     */
    const DEFAULT_SERVICE_PORT = 443;

    /**
     * The name of the code generator, to be included in the agent header.
     */
    const CODEGEN_NAME = 'gapic';

    /**
     * The default scopes required by the service.
     */
    public static $serviceScopes = [
        'https://www.googleapis.com/auth/cloud-platform',
    ];

    private static $locationNameTemplate;

    private static $registrationNameTemplate;

    private static $pathTemplateMap;

    private $operationsClient;

    private static function getClientDefaults()
    {
        return [
            'serviceName' => self::SERVICE_NAME,
            'apiEndpoint' => self::SERVICE_ADDRESS . ':' . self::DEFAULT_SERVICE_PORT,
            'clientConfig' => __DIR__ . '/../resources/domains_client_config.json',
            'descriptorsConfigPath' => __DIR__ . '/../resources/domains_descriptor_config.php',
            'gcpApiConfigPath' => __DIR__ . '/../resources/domains_grpc_config.json',
            'credentialsConfig' => [
                'defaultScopes' => self::$serviceScopes,
            ],
            'transportConfig' => [
                'rest' => [
                    'restClientConfigPath' => __DIR__ . '/../resources/domains_rest_client_config.php',
                ],
            ],
        ];
    }

    private static function getLocationNameTemplate()
    {
        if (self::$locationNameTemplate == null) {
            self::$locationNameTemplate = new PathTemplate('projects/{project}/locations/{location}');
        }

        return self::$locationNameTemplate;
    }

    private static function getRegistrationNameTemplate()
    {
        if (self::$registrationNameTemplate == null) {
            self::$registrationNameTemplate = new PathTemplate('projects/{project}/locations/{location}/registrations/{registration}');
        }

        return self::$registrationNameTemplate;
    }

    private static function getPathTemplateMap()
    {
        if (self::$pathTemplateMap == null) {
            self::$pathTemplateMap = [
                'location' => self::getLocationNameTemplate(),
                'registration' => self::getRegistrationNameTemplate(),
            ];
        }

        return self::$pathTemplateMap;
    }

    /**
     * Formats a string containing the fully-qualified path to represent a location
     * resource.
     *
     * @param string $project
     * @param string $location
     *
     * @return string The formatted location resource.
     *
     * @experimental
     */
    public static function locationName($project, $location)
    {
        return self::getLocationNameTemplate()->render([
            'project' => $project,
            'location' => $location,
        ]);
    }

    /**
     * Formats a string containing the fully-qualified path to represent a registration
     * resource.
     *
     * @param string $project
     * @param string $location
     * @param string $registration
     *
     * @return string The formatted registration resource.
     *
     * @experimental
     */
    public static function registrationName($project, $location, $registration)
    {
        return self::getRegistrationNameTemplate()->render([
            'project' => $project,
            'location' => $location,
            'registration' => $registration,
        ]);
    }

    /**
     * Parses a formatted name string and returns an associative array of the components in the name.
     * The following name formats are supported:
     * Template: Pattern
     * - location: projects/{project}/locations/{location}
     * - registration: projects/{project}/locations/{location}/registrations/{registration}
     *
     * The optional $template argument can be supplied to specify a particular pattern,
     * and must match one of the templates listed above. If no $template argument is
     * provided, or if the $template argument does not match one of the templates
     * listed, then parseName will check each of the supported templates, and return
     * the first match.
     *
     * @param string $formattedName The formatted name string
     * @param string $template      Optional name of template to match
     *
     * @return array An associative array from name component IDs to component values.
     *
     * @throws ValidationException If $formattedName could not be matched.
     *
     * @experimental
     */
    public static function parseName($formattedName, $template = null)
    {
        $templateMap = self::getPathTemplateMap();
        if ($template) {
            if (!isset($templateMap[$template])) {
                throw new ValidationException("Template name $template does not exist");
            }

            return $templateMap[$template]->match($formattedName);
        }

        foreach ($templateMap as $templateName => $pathTemplate) {
            try {
                return $pathTemplate->match($formattedName);
            } catch (ValidationException $ex) {
                // Swallow the exception to continue trying other path templates
            }
        }

        throw new ValidationException("Input did not match any known format. Input: $formattedName");
    }

    /**
     * Return an OperationsClient object with the same endpoint as $this.
     *
     * @return OperationsClient
     *
     * @experimental
     */
    public function getOperationsClient()
    {
        return $this->operationsClient;
    }

    /**
     * Resume an existing long running operation that was previously started by a long
     * running API method. If $methodName is not provided, or does not match a long
     * running API method, then the operation can still be resumed, but the
     * OperationResponse object will not deserialize the final response.
     *
     * @param string $operationName The name of the long running operation
     * @param string $methodName    The name of the method used to start the operation
     *
     * @return OperationResponse
     *
     * @experimental
     */
    public function resumeOperation($operationName, $methodName = null)
    {
        $options = isset($this->descriptors[$methodName]['longRunning']) ? $this->descriptors[$methodName]['longRunning'] : [];
        $operation = new OperationResponse($operationName, $this->getOperationsClient(), $options);
        $operation->reload();
        return $operation;
    }

    /**
     * Constructor.
     *
     * @param array $options {
     *     Optional. Options for configuring the service API wrapper.
     *
     *     @type string $serviceAddress
     *           **Deprecated**. This option will be removed in a future major release. Please
     *           utilize the `$apiEndpoint` option instead.
     *     @type string $apiEndpoint
     *           The address of the API remote host. May optionally include the port, formatted
     *           as "<uri>:<port>". Default 'domains.googleapis.com:443'.
     *     @type string|array|FetchAuthTokenInterface|CredentialsWrapper $credentials
     *           The credentials to be used by the client to authorize API calls. This option
     *           accepts either a path to a credentials file, or a decoded credentials file as a
     *           PHP array.
     *           *Advanced usage*: In addition, this option can also accept a pre-constructed
     *           {@see \Google\Auth\FetchAuthTokenInterface} object or
     *           {@see \Google\ApiCore\CredentialsWrapper} object. Note that when one of these
     *           objects are provided, any settings in $credentialsConfig will be ignored.
     *     @type array $credentialsConfig
     *           Options used to configure credentials, including auth token caching, for the
     *           client. For a full list of supporting configuration options, see
     *           {@see \Google\ApiCore\CredentialsWrapper::build()} .
     *     @type bool $disableRetries
     *           Determines whether or not retries defined by the client configuration should be
     *           disabled. Defaults to `false`.
     *     @type string|array $clientConfig
     *           Client method configuration, including retry settings. This option can be either
     *           a path to a JSON file, or a PHP array containing the decoded JSON data. By
     *           default this settings points to the default client config file, which is
     *           provided in the resources folder.
     *     @type string|TransportInterface $transport
     *           The transport used for executing network requests. May be either the string
     *           `rest` or `grpc`. Defaults to `grpc` if gRPC support is detected on the system.
     *           *Advanced usage*: Additionally, it is possible to pass in an already
     *           instantiated {@see \Google\ApiCore\Transport\TransportInterface} object. Note
     *           that when this object is provided, any settings in $transportConfig, and any
     *           $serviceAddress setting, will be ignored.
     *     @type array $transportConfig
     *           Configuration options that will be used to construct the transport. Options for
     *           each supported transport type should be passed in a key for that transport. For
     *           example:
     *           $transportConfig = [
     *               'grpc' => [...],
     *               'rest' => [...],
     *           ];
     *           See the {@see \Google\ApiCore\Transport\GrpcTransport::build()} and
     *           {@see \Google\ApiCore\Transport\RestTransport::build()} methods for the
     *           supported options.
     *     @type callable $clientCertSource
     *           A callable which returns the client cert as a string. This can be used to
     *           provide a certificate and private key to the transport layer for mTLS.
     * }
     *
     * @throws ValidationException
     *
     * @experimental
     */
    public function __construct(array $options = [])
    {
        $clientOptions = $this->buildClientOptions($options);
        $this->setClientOptions($clientOptions);
        $this->operationsClient = $this->createOperationsClient($clientOptions);
    }

    /**
     * Updates a `Registration`'s contact settings. Some changes require
     * confirmation by the domain's registrant contact .
     *
     * Sample code:
     * ```
     * $domainsClient = new DomainsClient();
     * try {
     *     $formattedRegistration = $domainsClient->registrationName('[PROJECT]', '[LOCATION]', '[REGISTRATION]');
     *     $updateMask = new FieldMask();
     *     $operationResponse = $domainsClient->configureContactSettings($formattedRegistration, $updateMask);
     *     $operationResponse->pollUntilComplete();
     *     if ($operationResponse->operationSucceeded()) {
     *         $result = $operationResponse->getResult();
     *     // doSomethingWith($result)
     *     } else {
     *         $error = $operationResponse->getError();
     *         // handleError($error)
     *     }
     *     // Alternatively:
     *     // start the operation, keep the operation name, and resume later
     *     $operationResponse = $domainsClient->configureContactSettings($formattedRegistration, $updateMask);
     *     $operationName = $operationResponse->getName();
     *     // ... do other work
     *     $newOperationResponse = $domainsClient->resumeOperation($operationName, 'configureContactSettings');
     *     while (!$newOperationResponse->isDone()) {
     *         // ... do other work
     *         $newOperationResponse->reload();
     *     }
     *     if ($newOperationResponse->operationSucceeded()) {
     *         $result = $newOperationResponse->getResult();
     *     // doSomethingWith($result)
     *     } else {
     *         $error = $newOperationResponse->getError();
     *         // handleError($error)
     *     }
     * } finally {
     *     $domainsClient->close();
     * }
     * ```
     *
     * @param string    $registration Required. The name of the `Registration` whose contact settings are being updated,
     *                                in the format `projects/*/locations/*/registrations/*`.
     * @param FieldMask $updateMask   Required. The field mask describing which fields to update as a comma-separated list.
     *                                For example, if only the registrant contact is being updated, the
     *                                `update_mask` is `"registrant_contact"`.
     * @param array     $optionalArgs {
     *     Optional.
     *
     *     @type ContactSettings $contactSettings
     *           Fields of the `ContactSettings` to update.
     *     @type int[] $contactNotices
     *           The list of contact notices that the caller acknowledges. The notices
     *           needed here depend on the values specified in `contact_settings`.
     *           For allowed values, use constants defined on {@see \Google\Cloud\Domains\V1beta1\ContactNotice}
     *     @type bool $validateOnly
     *           Validate the request without actually updating the contact settings.
     *     @type RetrySettings|array $retrySettings
     *           Retry settings to use for this call. Can be a {@see RetrySettings} object, or an
     *           associative array of retry settings parameters. See the documentation on
     *           {@see RetrySettings} for example usage.
     * }
     *
     * @return \Google\ApiCore\OperationResponse
     *
     * @throws ApiException if the remote call fails
     *
     * @experimental
     */
    public function configureContactSettings($registration, $updateMask, array $optionalArgs = [])
    {
        $request = new ConfigureContactSettingsRequest();
        $requestParamHeaders = [];
        $request->setRegistration($registration);
        $request->setUpdateMask($updateMask);
        $requestParamHeaders['registration'] = $registration;
        if (isset($optionalArgs['contactSettings'])) {
            $request->setContactSettings($optionalArgs['contactSettings']);
        }

        if (isset($optionalArgs['contactNotices'])) {
            $request->setContactNotices($optionalArgs['contactNotices']);
        }

        if (isset($optionalArgs['validateOnly'])) {
            $request->setValidateOnly($optionalArgs['validateOnly']);
        }

        $requestParams = new RequestParamsHeaderDescriptor($requestParamHeaders);
        $optionalArgs['headers'] = isset($optionalArgs['headers']) ? array_merge($requestParams->getHeader(), $optionalArgs['headers']) : $requestParams->getHeader();
        return $this->startOperationsCall('ConfigureContactSettings', $optionalArgs, $request, $this->getOperationsClient())->wait();
    }

    /**
     * Updates a `Registration`'s DNS settings.
     *
     * Sample code:
     * ```
     * $domainsClient = new DomainsClient();
     * try {
     *     $formattedRegistration = $domainsClient->registrationName('[PROJECT]', '[LOCATION]', '[REGISTRATION]');
     *     $updateMask = new FieldMask();
     *     $operationResponse = $domainsClient->configureDnsSettings($formattedRegistration, $updateMask);
     *     $operationResponse->pollUntilComplete();
     *     if ($operationResponse->operationSucceeded()) {
     *         $result = $operationResponse->getResult();
     *     // doSomethingWith($result)
     *     } else {
     *         $error = $operationResponse->getError();
     *         // handleError($error)
     *     }
     *     // Alternatively:
     *     // start the operation, keep the operation name, and resume later
     *     $operationResponse = $domainsClient->configureDnsSettings($formattedRegistration, $updateMask);
     *     $operationName = $operationResponse->getName();
     *     // ... do other work
     *     $newOperationResponse = $domainsClient->resumeOperation($operationName, 'configureDnsSettings');
     *     while (!$newOperationResponse->isDone()) {
     *         // ... do other work
     *         $newOperationResponse->reload();
     *     }
     *     if ($newOperationResponse->operationSucceeded()) {
     *         $result = $newOperationResponse->getResult();
     *     // doSomethingWith($result)
     *     } else {
     *         $error = $newOperationResponse->getError();
     *         // handleError($error)
     *     }
     * } finally {
     *     $domainsClient->close();
     * }
     * ```
     *
     * @param string    $registration Required. The name of the `Registration` whose DNS settings are being updated,
     *                                in the format `projects/*/locations/*/registrations/*`.
     * @param FieldMask $updateMask   Required. The field mask describing which fields to update as a comma-separated list.
     *                                For example, if only the name servers are being updated for an existing
     *                                Custom DNS configuration, the `update_mask` is
     *                                `"custom_dns.name_servers"`.
     *
     *                                When changing the DNS provider from one type to another, pass the new
     *                                provider's field name as part of the field mask. For example, when changing
     *                                from a Google Domains DNS configuration to a Custom DNS configuration, the
     *                                `update_mask` is `"custom_dns"`. //
     * @param array     $optionalArgs {
     *     Optional.
     *
     *     @type DnsSettings $dnsSettings
     *           Fields of the `DnsSettings` to update.
     *     @type bool $validateOnly
     *           Validate the request without actually updating the DNS settings.
     *     @type RetrySettings|array $retrySettings
     *           Retry settings to use for this call. Can be a {@see RetrySettings} object, or an
     *           associative array of retry settings parameters. See the documentation on
     *           {@see RetrySettings} for example usage.
     * }
     *
     * @return \Google\ApiCore\OperationResponse
     *
     * @throws ApiException if the remote call fails
     *
     * @experimental
     */
    public function configureDnsSettings($registration, $updateMask, array $optionalArgs = [])
    {
        $request = new ConfigureDnsSettingsRequest();
        $requestParamHeaders = [];
        $request->setRegistration($registration);
        $request->setUpdateMask($updateMask);
        $requestParamHeaders['registration'] = $registration;
        if (isset($optionalArgs['dnsSettings'])) {
            $request->setDnsSettings($optionalArgs['dnsSettings']);
        }

        if (isset($optionalArgs['validateOnly'])) {
            $request->setValidateOnly($optionalArgs['validateOnly']);
        }

        $requestParams = new RequestParamsHeaderDescriptor($requestParamHeaders);
        $optionalArgs['headers'] = isset($optionalArgs['headers']) ? array_merge($requestParams->getHeader(), $optionalArgs['headers']) : $requestParams->getHeader();
        return $this->startOperationsCall('ConfigureDnsSettings', $optionalArgs, $request, $this->getOperationsClient())->wait();
    }

    /**
     * Updates a `Registration`'s management settings.
     *
     * Sample code:
     * ```
     * $domainsClient = new DomainsClient();
     * try {
     *     $formattedRegistration = $domainsClient->registrationName('[PROJECT]', '[LOCATION]', '[REGISTRATION]');
     *     $updateMask = new FieldMask();
     *     $operationResponse = $domainsClient->configureManagementSettings($formattedRegistration, $updateMask);
     *     $operationResponse->pollUntilComplete();
     *     if ($operationResponse->operationSucceeded()) {
     *         $result = $operationResponse->getResult();
     *     // doSomethingWith($result)
     *     } else {
     *         $error = $operationResponse->getError();
     *         // handleError($error)
     *     }
     *     // Alternatively:
     *     // start the operation, keep the operation name, and resume later
     *     $operationResponse = $domainsClient->configureManagementSettings($formattedRegistration, $updateMask);
     *     $operationName = $operationResponse->getName();
     *     // ... do other work
     *     $newOperationResponse = $domainsClient->resumeOperation($operationName, 'configureManagementSettings');
     *     while (!$newOperationResponse->isDone()) {
     *         // ... do other work
     *         $newOperationResponse->reload();
     *     }
     *     if ($newOperationResponse->operationSucceeded()) {
     *         $result = $newOperationResponse->getResult();
     *     // doSomethingWith($result)
     *     } else {
     *         $error = $newOperationResponse->getError();
     *         // handleError($error)
     *     }
     * } finally {
     *     $domainsClient->close();
     * }
     * ```
     *
     * @param string    $registration Required. The name of the `Registration` whose management settings are being updated,
     *                                in the format `projects/*/locations/*/registrations/*`.
     * @param FieldMask $updateMask   Required. The field mask describing which fields to update as a comma-separated list.
     *                                For example, if only the transfer lock is being updated, the `update_mask`
     *                                is `"transfer_lock_state"`.
     * @param array     $optionalArgs {
     *     Optional.
     *
     *     @type ManagementSettings $managementSettings
     *           Fields of the `ManagementSettings` to update.
     *     @type RetrySettings|array $retrySettings
     *           Retry settings to use for this call. Can be a {@see RetrySettings} object, or an
     *           associative array of retry settings parameters. See the documentation on
     *           {@see RetrySettings} for example usage.
     * }
     *
     * @return \Google\ApiCore\OperationResponse
     *
     * @throws ApiException if the remote call fails
     *
     * @experimental
     */
    public function configureManagementSettings($registration, $updateMask, array $optionalArgs = [])
    {
        $request = new ConfigureManagementSettingsRequest();
        $requestParamHeaders = [];
        $request->setRegistration($registration);
        $request->setUpdateMask($updateMask);
        $requestParamHeaders['registration'] = $registration;
        if (isset($optionalArgs['managementSettings'])) {
            $request->setManagementSettings($optionalArgs['managementSettings']);
        }

        $requestParams = new RequestParamsHeaderDescriptor($requestParamHeaders);
        $optionalArgs['headers'] = isset($optionalArgs['headers']) ? array_merge($requestParams->getHeader(), $optionalArgs['headers']) : $requestParams->getHeader();
        return $this->startOperationsCall('ConfigureManagementSettings', $optionalArgs, $request, $this->getOperationsClient())->wait();
    }

    /**
     * Deletes a `Registration` resource.
     *
     * This method works on any `Registration` resource using [Subscription or
     * Commitment billing](https://cloud.google.com/domains/pricing#billing-models), provided that the
     * resource was created at least 1 day in the past.
     *
     * For `Registration` resources using
     * [Monthly billing](https://cloud.google.com/domains/pricing#billing-models), this method works if:
     *
     * * `state` is `EXPORTED` with `expire_time` in the past
     * * `state` is `REGISTRATION_FAILED`
     * * `state` is `TRANSFER_FAILED`
     *
     * When an active registration is successfully deleted, you can continue to
     * use the domain in [Google Domains](https://domains.google/) until it
     * expires. The calling user becomes the domain's sole owner in Google
     * Domains, and permissions for the domain are subsequently managed there. The
     * domain does not renew automatically unless the new owner sets up billing in
     * Google Domains.
     *
     * Sample code:
     * ```
     * $domainsClient = new DomainsClient();
     * try {
     *     $formattedName = $domainsClient->registrationName('[PROJECT]', '[LOCATION]', '[REGISTRATION]');
     *     $operationResponse = $domainsClient->deleteRegistration($formattedName);
     *     $operationResponse->pollUntilComplete();
     *     if ($operationResponse->operationSucceeded()) {
     *         // operation succeeded and returns no value
     *     } else {
     *         $error = $operationResponse->getError();
     *         // handleError($error)
     *     }
     *     // Alternatively:
     *     // start the operation, keep the operation name, and resume later
     *     $operationResponse = $domainsClient->deleteRegistration($formattedName);
     *     $operationName = $operationResponse->getName();
     *     // ... do other work
     *     $newOperationResponse = $domainsClient->resumeOperation($operationName, 'deleteRegistration');
     *     while (!$newOperationResponse->isDone()) {
     *         // ... do other work
     *         $newOperationResponse->reload();
     *     }
     *     if ($newOperationResponse->operationSucceeded()) {
     *         // operation succeeded and returns no value
     *     } else {
     *         $error = $newOperationResponse->getError();
     *         // handleError($error)
     *     }
     * } finally {
     *     $domainsClient->close();
     * }
     * ```
     *
     * @param string $name         Required. The name of the `Registration` to delete,
     *                             in the format `projects/*/locations/*/registrations/*`.
     * @param array  $optionalArgs {
     *     Optional.
     *
     *     @type RetrySettings|array $retrySettings
     *           Retry settings to use for this call. Can be a {@see RetrySettings} object, or an
     *           associative array of retry settings parameters. See the documentation on
     *           {@see RetrySettings} for example usage.
     * }
     *
     * @return \Google\ApiCore\OperationResponse
     *
     * @throws ApiException if the remote call fails
     *
     * @experimental
     */
    public function deleteRegistration($name, array $optionalArgs = [])
    {
        $request = new DeleteRegistrationRequest();
        $requestParamHeaders = [];
        $request->setName($name);
        $requestParamHeaders['name'] = $name;
        $requestParams = new RequestParamsHeaderDescriptor($requestParamHeaders);
        $optionalArgs['headers'] = isset($optionalArgs['headers']) ? array_merge($requestParams->getHeader(), $optionalArgs['headers']) : $requestParams->getHeader();
        return $this->startOperationsCall('DeleteRegistration', $optionalArgs, $request, $this->getOperationsClient())->wait();
    }

    /**
     * Exports a `Registration` resource, such that it is no longer managed by
     * Cloud Domains.
     *
     * When an active domain is successfully exported, you can continue to use the
     * domain in [Google Domains](https://domains.google/) until it expires. The
     * calling user becomes the domain's sole owner in Google Domains, and
     * permissions for the domain are subsequently managed there. The domain does
     * not renew automatically unless the new owner sets up billing in Google
     * Domains.
     *
     * Sample code:
     * ```
     * $domainsClient = new DomainsClient();
     * try {
     *     $formattedName = $domainsClient->registrationName('[PROJECT]', '[LOCATION]', '[REGISTRATION]');
     *     $operationResponse = $domainsClient->exportRegistration($formattedName);
     *     $operationResponse->pollUntilComplete();
     *     if ($operationResponse->operationSucceeded()) {
     *         $result = $operationResponse->getResult();
     *     // doSomethingWith($result)
     *     } else {
     *         $error = $operationResponse->getError();
     *         // handleError($error)
     *     }
     *     // Alternatively:
     *     // start the operation, keep the operation name, and resume later
     *     $operationResponse = $domainsClient->exportRegistration($formattedName);
     *     $operationName = $operationResponse->getName();
     *     // ... do other work
     *     $newOperationResponse = $domainsClient->resumeOperation($operationName, 'exportRegistration');
     *     while (!$newOperationResponse->isDone()) {
     *         // ... do other work
     *         $newOperationResponse->reload();
     *     }
     *     if ($newOperationResponse->operationSucceeded()) {
     *         $result = $newOperationResponse->getResult();
     *     // doSomethingWith($result)
     *     } else {
     *         $error = $newOperationResponse->getError();
     *         // handleError($error)
     *     }
     * } finally {
     *     $domainsClient->close();
     * }
     * ```
     *
     * @param string $name         Required. The name of the `Registration` to export,
     *                             in the format `projects/*/locations/*/registrations/*`.
     * @param array  $optionalArgs {
     *     Optional.
     *
     *     @type RetrySettings|array $retrySettings
     *           Retry settings to use for this call. Can be a {@see RetrySettings} object, or an
     *           associative array of retry settings parameters. See the documentation on
     *           {@see RetrySettings} for example usage.
     * }
     *
     * @return \Google\ApiCore\OperationResponse
     *
     * @throws ApiException if the remote call fails
     *
     * @experimental
     */
    public function exportRegistration($name, array $optionalArgs = [])
    {
        $request = new ExportRegistrationRequest();
        $requestParamHeaders = [];
        $request->setName($name);
        $requestParamHeaders['name'] = $name;
        $requestParams = new RequestParamsHeaderDescriptor($requestParamHeaders);
        $optionalArgs['headers'] = isset($optionalArgs['headers']) ? array_merge($requestParams->getHeader(), $optionalArgs['headers']) : $requestParams->getHeader();
        return $this->startOperationsCall('ExportRegistration', $optionalArgs, $request, $this->getOperationsClient())->wait();
    }

    /**
     * Gets the details of a `Registration` resource.
     *
     * Sample code:
     * ```
     * $domainsClient = new DomainsClient();
     * try {
     *     $formattedName = $domainsClient->registrationName('[PROJECT]', '[LOCATION]', '[REGISTRATION]');
     *     $response = $domainsClient->getRegistration($formattedName);
     * } finally {
     *     $domainsClient->close();
     * }
     * ```
     *
     * @param string $name         Required. The name of the `Registration` to get, in the format
     *                             `projects/*/locations/*/registrations/*`.
     * @param array  $optionalArgs {
     *     Optional.
     *
     *     @type RetrySettings|array $retrySettings
     *           Retry settings to use for this call. Can be a {@see RetrySettings} object, or an
     *           associative array of retry settings parameters. See the documentation on
     *           {@see RetrySettings} for example usage.
     * }
     *
     * @return \Google\Cloud\Domains\V1beta1\Registration
     *
     * @throws ApiException if the remote call fails
     *
     * @experimental
     */
    public function getRegistration($name, array $optionalArgs = [])
    {
        $request = new GetRegistrationRequest();
        $requestParamHeaders = [];
        $request->setName($name);
        $requestParamHeaders['name'] = $name;
        $requestParams = new RequestParamsHeaderDescriptor($requestParamHeaders);
        $optionalArgs['headers'] = isset($optionalArgs['headers']) ? array_merge($requestParams->getHeader(), $optionalArgs['headers']) : $requestParams->getHeader();
        return $this->startCall('GetRegistration', Registration::class, $optionalArgs, $request)->wait();
    }

    /**
     * Lists the `Registration` resources in a project.
     *
     * Sample code:
     * ```
     * $domainsClient = new DomainsClient();
     * try {
     *     $formattedParent = $domainsClient->locationName('[PROJECT]', '[LOCATION]');
     *     // Iterate over pages of elements
     *     $pagedResponse = $domainsClient->listRegistrations($formattedParent);
     *     foreach ($pagedResponse->iteratePages() as $page) {
     *         foreach ($page as $element) {
     *             // doSomethingWith($element);
     *         }
     *     }
     *     // Alternatively:
     *     // Iterate through all elements
     *     $pagedResponse = $domainsClient->listRegistrations($formattedParent);
     *     foreach ($pagedResponse->iterateAllElements() as $element) {
     *         // doSomethingWith($element);
     *     }
     * } finally {
     *     $domainsClient->close();
     * }
     * ```
     *
     * @param string $parent       Required. The project and location from which to list `Registration`s, specified in
     *                             the format `projects/*/locations/*`.
     * @param array  $optionalArgs {
     *     Optional.
     *
     *     @type int $pageSize
     *           The maximum number of resources contained in the underlying API
     *           response. The API may return fewer values in a page, even if
     *           there are additional values to be retrieved.
     *     @type string $pageToken
     *           A page token is used to specify a page of values to be returned.
     *           If no page token is specified (the default), the first page
     *           of values will be returned. Any page token used here must have
     *           been generated by a previous call to the API.
     *     @type string $filter
     *           Filter expression to restrict the `Registration`s returned.
     *
     *           The expression must specify the field name, a comparison operator, and the
     *           value that you want to use for filtering. The value must be a string, a
     *           number, a boolean, or an enum value. The comparison operator should be one
     *           of =, !=, >, <, >=, <=, or : for prefix or wildcard matches.
     *
     *           For example, to filter to a specific domain name, use an expression like
     *           `domainName="example.com"`. You can also check for the existence of a
     *           field; for example, to find domains using custom DNS settings, use an
     *           expression like `dnsSettings.customDns:*`.
     *
     *           You can also create compound filters by combining expressions with the
     *           `AND` and `OR` operators. For example, to find domains that are suspended
     *           or have specific issues flagged, use an expression like
     *           `(state=SUSPENDED) OR (issue:*)`.
     *     @type RetrySettings|array $retrySettings
     *           Retry settings to use for this call. Can be a {@see RetrySettings} object, or an
     *           associative array of retry settings parameters. See the documentation on
     *           {@see RetrySettings} for example usage.
     * }
     *
     * @return \Google\ApiCore\PagedListResponse
     *
     * @throws ApiException if the remote call fails
     *
     * @experimental
     */
    public function listRegistrations($parent, array $optionalArgs = [])
    {
        $request = new ListRegistrationsRequest();
        $requestParamHeaders = [];
        $request->setParent($parent);
        $requestParamHeaders['parent'] = $parent;
        if (isset($optionalArgs['pageSize'])) {
            $request->setPageSize($optionalArgs['pageSize']);
        }

        if (isset($optionalArgs['pageToken'])) {
            $request->setPageToken($optionalArgs['pageToken']);
        }

        if (isset($optionalArgs['filter'])) {
            $request->setFilter($optionalArgs['filter']);
        }

        $requestParams = new RequestParamsHeaderDescriptor($requestParamHeaders);
        $optionalArgs['headers'] = isset($optionalArgs['headers']) ? array_merge($requestParams->getHeader(), $optionalArgs['headers']) : $requestParams->getHeader();
        return $this->getPagedListResponse('ListRegistrations', $optionalArgs, ListRegistrationsResponse::class, $request);
    }

    /**
     * Registers a new domain name and creates a corresponding `Registration`
     * resource.
     *
     * Call `RetrieveRegisterParameters` first to check availability of the domain
     * name and determine parameters like price that are needed to build a call to
     * this method.
     *
     * A successful call creates a `Registration` resource in state
     * `REGISTRATION_PENDING`, which resolves to `ACTIVE` within 1-2
     * minutes, indicating that the domain was successfully registered. If the
     * resource ends up in state `REGISTRATION_FAILED`, it indicates that the
     * domain was not registered successfully, and you can safely delete the
     * resource and retry registration.
     *
     * Sample code:
     * ```
     * $domainsClient = new DomainsClient();
     * try {
     *     $formattedParent = $domainsClient->locationName('[PROJECT]', '[LOCATION]');
     *     $registration = new Registration();
     *     $yearlyPrice = new Money();
     *     $operationResponse = $domainsClient->registerDomain($formattedParent, $registration, $yearlyPrice);
     *     $operationResponse->pollUntilComplete();
     *     if ($operationResponse->operationSucceeded()) {
     *         $result = $operationResponse->getResult();
     *     // doSomethingWith($result)
     *     } else {
     *         $error = $operationResponse->getError();
     *         // handleError($error)
     *     }
     *     // Alternatively:
     *     // start the operation, keep the operation name, and resume later
     *     $operationResponse = $domainsClient->registerDomain($formattedParent, $registration, $yearlyPrice);
     *     $operationName = $operationResponse->getName();
     *     // ... do other work
     *     $newOperationResponse = $domainsClient->resumeOperation($operationName, 'registerDomain');
     *     while (!$newOperationResponse->isDone()) {
     *         // ... do other work
     *         $newOperationResponse->reload();
     *     }
     *     if ($newOperationResponse->operationSucceeded()) {
     *         $result = $newOperationResponse->getResult();
     *     // doSomethingWith($result)
     *     } else {
     *         $error = $newOperationResponse->getError();
     *         // handleError($error)
     *     }
     * } finally {
     *     $domainsClient->close();
     * }
     * ```
     *
     * @param string       $parent       Required. The parent resource of the `Registration`. Must be in the
     *                                   format `projects/*/locations/*`.
     * @param Registration $registration Required. The complete `Registration` resource to be created.
     * @param Money        $yearlyPrice  Required. Yearly price to register or renew the domain.
     *                                   The value that should be put here can be obtained from
     *                                   RetrieveRegisterParameters or SearchDomains calls.
     * @param array        $optionalArgs {
     *     Optional.
     *
     *     @type int[] $domainNotices
     *           The list of domain notices that you acknowledge. Call
     *           `RetrieveRegisterParameters` to see the notices that need acknowledgement.
     *           For allowed values, use constants defined on {@see \Google\Cloud\Domains\V1beta1\DomainNotice}
     *     @type int[] $contactNotices
     *           The list of contact notices that the caller acknowledges. The notices
     *           needed here depend on the values specified in
     *           `registration.contact_settings`.
     *           For allowed values, use constants defined on {@see \Google\Cloud\Domains\V1beta1\ContactNotice}
     *     @type bool $validateOnly
     *           When true, only validation is performed, without actually registering
     *           the domain. Follows:
     *           https://cloud.google.com/apis/design/design_patterns#request_validation
     *     @type RetrySettings|array $retrySettings
     *           Retry settings to use for this call. Can be a {@see RetrySettings} object, or an
     *           associative array of retry settings parameters. See the documentation on
     *           {@see RetrySettings} for example usage.
     * }
     *
     * @return \Google\ApiCore\OperationResponse
     *
     * @throws ApiException if the remote call fails
     *
     * @experimental
     */
    public function registerDomain($parent, $registration, $yearlyPrice, array $optionalArgs = [])
    {
        $request = new RegisterDomainRequest();
        $requestParamHeaders = [];
        $request->setParent($parent);
        $request->setRegistration($registration);
        $request->setYearlyPrice($yearlyPrice);
        $requestParamHeaders['parent'] = $parent;
        if (isset($optionalArgs['domainNotices'])) {
            $request->setDomainNotices($optionalArgs['domainNotices']);
        }

        if (isset($optionalArgs['contactNotices'])) {
            $request->setContactNotices($optionalArgs['contactNotices']);
        }

        if (isset($optionalArgs['validateOnly'])) {
            $request->setValidateOnly($optionalArgs['validateOnly']);
        }

        $requestParams = new RequestParamsHeaderDescriptor($requestParamHeaders);
        $optionalArgs['headers'] = isset($optionalArgs['headers']) ? array_merge($requestParams->getHeader(), $optionalArgs['headers']) : $requestParams->getHeader();
        return $this->startOperationsCall('RegisterDomain', $optionalArgs, $request, $this->getOperationsClient())->wait();
    }

    /**
     * Resets the authorization code of the `Registration` to a new random string.
     *
     * You can call this method only after 60 days have elapsed since the initial
     * domain registration.
     *
     * Sample code:
     * ```
     * $domainsClient = new DomainsClient();
     * try {
     *     $formattedRegistration = $domainsClient->registrationName('[PROJECT]', '[LOCATION]', '[REGISTRATION]');
     *     $response = $domainsClient->resetAuthorizationCode($formattedRegistration);
     * } finally {
     *     $domainsClient->close();
     * }
     * ```
     *
     * @param string $registration Required. The name of the `Registration` whose authorization code is being reset,
     *                             in the format `projects/*/locations/*/registrations/*`.
     * @param array  $optionalArgs {
     *     Optional.
     *
     *     @type RetrySettings|array $retrySettings
     *           Retry settings to use for this call. Can be a {@see RetrySettings} object, or an
     *           associative array of retry settings parameters. See the documentation on
     *           {@see RetrySettings} for example usage.
     * }
     *
     * @return \Google\Cloud\Domains\V1beta1\AuthorizationCode
     *
     * @throws ApiException if the remote call fails
     *
     * @experimental
     */
    public function resetAuthorizationCode($registration, array $optionalArgs = [])
    {
        $request = new ResetAuthorizationCodeRequest();
        $requestParamHeaders = [];
        $request->setRegistration($registration);
        $requestParamHeaders['registration'] = $registration;
        $requestParams = new RequestParamsHeaderDescriptor($requestParamHeaders);
        $optionalArgs['headers'] = isset($optionalArgs['headers']) ? array_merge($requestParams->getHeader(), $optionalArgs['headers']) : $requestParams->getHeader();
        return $this->startCall('ResetAuthorizationCode', AuthorizationCode::class, $optionalArgs, $request)->wait();
    }

    /**
     * Gets the authorization code of the `Registration` for the purpose of
     * transferring the domain to another registrar.
     *
     * You can call this method only after 60 days have elapsed since the initial
     * domain registration.
     *
     * Sample code:
     * ```
     * $domainsClient = new DomainsClient();
     * try {
     *     $formattedRegistration = $domainsClient->registrationName('[PROJECT]', '[LOCATION]', '[REGISTRATION]');
     *     $response = $domainsClient->retrieveAuthorizationCode($formattedRegistration);
     * } finally {
     *     $domainsClient->close();
     * }
     * ```
     *
     * @param string $registration Required. The name of the `Registration` whose authorization code is being retrieved,
     *                             in the format `projects/*/locations/*/registrations/*`.
     * @param array  $optionalArgs {
     *     Optional.
     *
     *     @type RetrySettings|array $retrySettings
     *           Retry settings to use for this call. Can be a {@see RetrySettings} object, or an
     *           associative array of retry settings parameters. See the documentation on
     *           {@see RetrySettings} for example usage.
     * }
     *
     * @return \Google\Cloud\Domains\V1beta1\AuthorizationCode
     *
     * @throws ApiException if the remote call fails
     *
     * @experimental
     */
    public function retrieveAuthorizationCode($registration, array $optionalArgs = [])
    {
        $request = new RetrieveAuthorizationCodeRequest();
        $requestParamHeaders = [];
        $request->setRegistration($registration);
        $requestParamHeaders['registration'] = $registration;
        $requestParams = new RequestParamsHeaderDescriptor($requestParamHeaders);
        $optionalArgs['headers'] = isset($optionalArgs['headers']) ? array_merge($requestParams->getHeader(), $optionalArgs['headers']) : $requestParams->getHeader();
        return $this->startCall('RetrieveAuthorizationCode', AuthorizationCode::class, $optionalArgs, $request)->wait();
    }

    /**
     * Gets parameters needed to register a new domain name, including price and
     * up-to-date availability. Use the returned values to call `RegisterDomain`.
     *
     * Sample code:
     * ```
     * $domainsClient = new DomainsClient();
     * try {
     *     $domainName = 'domain_name';
     *     $formattedLocation = $domainsClient->locationName('[PROJECT]', '[LOCATION]');
     *     $response = $domainsClient->retrieveRegisterParameters($domainName, $formattedLocation);
     * } finally {
     *     $domainsClient->close();
     * }
     * ```
     *
     * @param string $domainName   Required. The domain name. Unicode domain names must be expressed in Punycode format.
     * @param string $location     Required. The location. Must be in the format `projects/*/locations/*`.
     * @param array  $optionalArgs {
     *     Optional.
     *
     *     @type RetrySettings|array $retrySettings
     *           Retry settings to use for this call. Can be a {@see RetrySettings} object, or an
     *           associative array of retry settings parameters. See the documentation on
     *           {@see RetrySettings} for example usage.
     * }
     *
     * @return \Google\Cloud\Domains\V1beta1\RetrieveRegisterParametersResponse
     *
     * @throws ApiException if the remote call fails
     *
     * @experimental
     */
    public function retrieveRegisterParameters($domainName, $location, array $optionalArgs = [])
    {
        $request = new RetrieveRegisterParametersRequest();
        $requestParamHeaders = [];
        $request->setDomainName($domainName);
        $request->setLocation($location);
        $requestParamHeaders['location'] = $location;
        $requestParams = new RequestParamsHeaderDescriptor($requestParamHeaders);
        $optionalArgs['headers'] = isset($optionalArgs['headers']) ? array_merge($requestParams->getHeader(), $optionalArgs['headers']) : $requestParams->getHeader();
        return $this->startCall('RetrieveRegisterParameters', RetrieveRegisterParametersResponse::class, $optionalArgs, $request)->wait();
    }

    /**
     * Gets parameters needed to transfer a domain name from another registrar to
     * Cloud Domains. For domains managed by Google Domains, transferring to Cloud
     * Domains is not supported.
     *
     *
     * Use the returned values to call `TransferDomain`.
     *
     * Sample code:
     * ```
     * $domainsClient = new DomainsClient();
     * try {
     *     $domainName = 'domain_name';
     *     $formattedLocation = $domainsClient->locationName('[PROJECT]', '[LOCATION]');
     *     $response = $domainsClient->retrieveTransferParameters($domainName, $formattedLocation);
     * } finally {
     *     $domainsClient->close();
     * }
     * ```
     *
     * @param string $domainName   Required. The domain name. Unicode domain names must be expressed in Punycode format.
     * @param string $location     Required. The location. Must be in the format `projects/*/locations/*`.
     * @param array  $optionalArgs {
     *     Optional.
     *
     *     @type RetrySettings|array $retrySettings
     *           Retry settings to use for this call. Can be a {@see RetrySettings} object, or an
     *           associative array of retry settings parameters. See the documentation on
     *           {@see RetrySettings} for example usage.
     * }
     *
     * @return \Google\Cloud\Domains\V1beta1\RetrieveTransferParametersResponse
     *
     * @throws ApiException if the remote call fails
     *
     * @experimental
     */
    public function retrieveTransferParameters($domainName, $location, array $optionalArgs = [])
    {
        $request = new RetrieveTransferParametersRequest();
        $requestParamHeaders = [];
        $request->setDomainName($domainName);
        $request->setLocation($location);
        $requestParamHeaders['location'] = $location;
        $requestParams = new RequestParamsHeaderDescriptor($requestParamHeaders);
        $optionalArgs['headers'] = isset($optionalArgs['headers']) ? array_merge($requestParams->getHeader(), $optionalArgs['headers']) : $requestParams->getHeader();
        return $this->startCall('RetrieveTransferParameters', RetrieveTransferParametersResponse::class, $optionalArgs, $request)->wait();
    }

    /**
     * Searches for available domain names similar to the provided query.
     *
     * Availability results from this method are approximate; call
     * `RetrieveRegisterParameters` on a domain before registering to confirm
     * availability.
     *
     * Sample code:
     * ```
     * $domainsClient = new DomainsClient();
     * try {
     *     $query = 'query';
     *     $formattedLocation = $domainsClient->locationName('[PROJECT]', '[LOCATION]');
     *     $response = $domainsClient->searchDomains($query, $formattedLocation);
     * } finally {
     *     $domainsClient->close();
     * }
     * ```
     *
     * @param string $query        Required. String used to search for available domain names.
     * @param string $location     Required. The location. Must be in the format `projects/*/locations/*`.
     * @param array  $optionalArgs {
     *     Optional.
     *
     *     @type RetrySettings|array $retrySettings
     *           Retry settings to use for this call. Can be a {@see RetrySettings} object, or an
     *           associative array of retry settings parameters. See the documentation on
     *           {@see RetrySettings} for example usage.
     * }
     *
     * @return \Google\Cloud\Domains\V1beta1\SearchDomainsResponse
     *
     * @throws ApiException if the remote call fails
     *
     * @experimental
     */
    public function searchDomains($query, $location, array $optionalArgs = [])
    {
        $request = new SearchDomainsRequest();
        $requestParamHeaders = [];
        $request->setQuery($query);
        $request->setLocation($location);
        $requestParamHeaders['location'] = $location;
        $requestParams = new RequestParamsHeaderDescriptor($requestParamHeaders);
        $optionalArgs['headers'] = isset($optionalArgs['headers']) ? array_merge($requestParams->getHeader(), $optionalArgs['headers']) : $requestParams->getHeader();
        return $this->startCall('SearchDomains', SearchDomainsResponse::class, $optionalArgs, $request)->wait();
    }

    /**
     * Transfers a domain name from another registrar to Cloud Domains.  For
     * domains managed by Google Domains, transferring to Cloud Domains is not
     * supported.
     *
     *
     * Before calling this method, go to the domain's current registrar to unlock
     * the domain for transfer and retrieve the domain's transfer authorization
     * code. Then call `RetrieveTransferParameters` to confirm that the domain is
     * unlocked and to get values needed to build a call to this method.
     *
     * A successful call creates a `Registration` resource in state
     * `TRANSFER_PENDING`. It can take several days to complete the transfer
     * process. The registrant can often speed up this process by approving the
     * transfer through the current registrar, either by clicking a link in an
     * email from the registrar or by visiting the registrar's website.
     *
     * A few minutes after transfer approval, the resource transitions to state
     * `ACTIVE`, indicating that the transfer was successful. If the transfer is
     * rejected or the request expires without being approved, the resource can
     * end up in state `TRANSFER_FAILED`. If transfer fails, you can safely delete
     * the resource and retry the transfer.
     *
     * Sample code:
     * ```
     * $domainsClient = new DomainsClient();
     * try {
     *     $formattedParent = $domainsClient->locationName('[PROJECT]', '[LOCATION]');
     *     $registration = new Registration();
     *     $yearlyPrice = new Money();
     *     $operationResponse = $domainsClient->transferDomain($formattedParent, $registration, $yearlyPrice);
     *     $operationResponse->pollUntilComplete();
     *     if ($operationResponse->operationSucceeded()) {
     *         $result = $operationResponse->getResult();
     *     // doSomethingWith($result)
     *     } else {
     *         $error = $operationResponse->getError();
     *         // handleError($error)
     *     }
     *     // Alternatively:
     *     // start the operation, keep the operation name, and resume later
     *     $operationResponse = $domainsClient->transferDomain($formattedParent, $registration, $yearlyPrice);
     *     $operationName = $operationResponse->getName();
     *     // ... do other work
     *     $newOperationResponse = $domainsClient->resumeOperation($operationName, 'transferDomain');
     *     while (!$newOperationResponse->isDone()) {
     *         // ... do other work
     *         $newOperationResponse->reload();
     *     }
     *     if ($newOperationResponse->operationSucceeded()) {
     *         $result = $newOperationResponse->getResult();
     *     // doSomethingWith($result)
     *     } else {
     *         $error = $newOperationResponse->getError();
     *         // handleError($error)
     *     }
     * } finally {
     *     $domainsClient->close();
     * }
     * ```
     *
     * @param string       $parent       Required. The parent resource of the `Registration`. Must be in the
     *                                   format `projects/*/locations/*`.
     * @param Registration $registration Required. The complete `Registration` resource to be created.
     *
     *                                   You can leave `registration.dns_settings` unset to import the
     *                                   domain's current DNS configuration from its current registrar. Use this
     *                                   option only if you are sure that the domain's current DNS service
     *                                   does not cease upon transfer, as is often the case for DNS services
     *                                   provided for free by the registrar.
     * @param Money        $yearlyPrice  Required. Acknowledgement of the price to transfer or renew the domain for one year.
     *                                   Call `RetrieveTransferParameters` to obtain the price, which you must
     *                                   acknowledge.
     * @param array        $optionalArgs {
     *     Optional.
     *
     *     @type int[] $contactNotices
     *           The list of contact notices that you acknowledge. The notices
     *           needed here depend on the values specified in
     *           `registration.contact_settings`.
     *           For allowed values, use constants defined on {@see \Google\Cloud\Domains\V1beta1\ContactNotice}
     *     @type AuthorizationCode $authorizationCode
     *           The domain's transfer authorization code. You can obtain this from the
     *           domain's current registrar.
     *     @type bool $validateOnly
     *           Validate the request without actually transferring the domain.
     *     @type RetrySettings|array $retrySettings
     *           Retry settings to use for this call. Can be a {@see RetrySettings} object, or an
     *           associative array of retry settings parameters. See the documentation on
     *           {@see RetrySettings} for example usage.
     * }
     *
     * @return \Google\ApiCore\OperationResponse
     *
     * @throws ApiException if the remote call fails
     *
     * @experimental
     */
    public function transferDomain($parent, $registration, $yearlyPrice, array $optionalArgs = [])
    {
        $request = new TransferDomainRequest();
        $requestParamHeaders = [];
        $request->setParent($parent);
        $request->setRegistration($registration);
        $request->setYearlyPrice($yearlyPrice);
        $requestParamHeaders['parent'] = $parent;
        if (isset($optionalArgs['contactNotices'])) {
            $request->setContactNotices($optionalArgs['contactNotices']);
        }

        if (isset($optionalArgs['authorizationCode'])) {
            $request->setAuthorizationCode($optionalArgs['authorizationCode']);
        }

        if (isset($optionalArgs['validateOnly'])) {
            $request->setValidateOnly($optionalArgs['validateOnly']);
        }

        $requestParams = new RequestParamsHeaderDescriptor($requestParamHeaders);
        $optionalArgs['headers'] = isset($optionalArgs['headers']) ? array_merge($requestParams->getHeader(), $optionalArgs['headers']) : $requestParams->getHeader();
        return $this->startOperationsCall('TransferDomain', $optionalArgs, $request, $this->getOperationsClient())->wait();
    }

    /**
     * Updates select fields of a `Registration` resource, notably `labels`. To
     * update other fields, use the appropriate custom update method:
     *
     * * To update management settings, see `ConfigureManagementSettings`
     * * To update DNS configuration, see `ConfigureDnsSettings`
     * * To update contact information, see `ConfigureContactSettings`
     *
     * Sample code:
     * ```
     * $domainsClient = new DomainsClient();
     * try {
     *     $updateMask = new FieldMask();
     *     $operationResponse = $domainsClient->updateRegistration($updateMask);
     *     $operationResponse->pollUntilComplete();
     *     if ($operationResponse->operationSucceeded()) {
     *         $result = $operationResponse->getResult();
     *     // doSomethingWith($result)
     *     } else {
     *         $error = $operationResponse->getError();
     *         // handleError($error)
     *     }
     *     // Alternatively:
     *     // start the operation, keep the operation name, and resume later
     *     $operationResponse = $domainsClient->updateRegistration($updateMask);
     *     $operationName = $operationResponse->getName();
     *     // ... do other work
     *     $newOperationResponse = $domainsClient->resumeOperation($operationName, 'updateRegistration');
     *     while (!$newOperationResponse->isDone()) {
     *         // ... do other work
     *         $newOperationResponse->reload();
     *     }
     *     if ($newOperationResponse->operationSucceeded()) {
     *         $result = $newOperationResponse->getResult();
     *     // doSomethingWith($result)
     *     } else {
     *         $error = $newOperationResponse->getError();
     *         // handleError($error)
     *     }
     * } finally {
     *     $domainsClient->close();
     * }
     * ```
     *
     * @param FieldMask $updateMask   Required. The field mask describing which fields to update as a comma-separated list.
     *                                For example, if only the labels are being updated, the `update_mask` is
     *                                `"labels"`.
     * @param array     $optionalArgs {
     *     Optional.
     *
     *     @type Registration $registration
     *           Fields of the `Registration` to update.
     *     @type RetrySettings|array $retrySettings
     *           Retry settings to use for this call. Can be a {@see RetrySettings} object, or an
     *           associative array of retry settings parameters. See the documentation on
     *           {@see RetrySettings} for example usage.
     * }
     *
     * @return \Google\ApiCore\OperationResponse
     *
     * @throws ApiException if the remote call fails
     *
     * @experimental
     */
    public function updateRegistration($updateMask, array $optionalArgs = [])
    {
        $request = new UpdateRegistrationRequest();
        $requestParamHeaders = [];
        $request->setUpdateMask($updateMask);
        if (isset($optionalArgs['registration'])) {
            $request->setRegistration($optionalArgs['registration']);
        }

        $requestParams = new RequestParamsHeaderDescriptor($requestParamHeaders);
        $optionalArgs['headers'] = isset($optionalArgs['headers']) ? array_merge($requestParams->getHeader(), $optionalArgs['headers']) : $requestParams->getHeader();
        return $this->startOperationsCall('UpdateRegistration', $optionalArgs, $request, $this->getOperationsClient())->wait();
    }
}


text:
layout: "fluid/docs_base"
version: "4.20.0"
versionHref: "/docs/native"
path: ""
category: native
id: "native-page-transitions"
title: "Native Page Transitions"
header_sub_title: "Class in module "
doc: "Native Page Transitions"
docType: "class"
---

Native Page Transitions

  Improve this doc

The Native Page Transitions plugin uses native hardware acceleration to animate your transitions between views. You have complete control over the type of transition, the duration, and direction.

Repo:

    https://github.com/Telerik-Verified-Plugins/NativePageTransitions

Installation

Install the Cordova and Ionic Native plugins:

$ ionic cordova plugin add com.telerik.plugins.nativepagetransitions
$ npm install --save @ionic-native/native-page-transitions@4

Add this plugin to your app's module

Supported platforms

Android

iOS

Windows Phone 8

Usage

import { NativePageTransitions, NativeTransitionOptions } from '@ionic-native/native-page-transitions';

constructor(private nativePageTransitions: NativePageTransitions) { }

...

// example of adding a transition when a page/modal closes
ionViewWillLeave() {

 let options: NativeTransitionOptions = {
    direction: 'up',
    duration: 500,
    slowdownfactor: 3,
    slidePixels: 20,
    iosdelay: 100,
    androiddelay: 150,
    fixedPixelsTop: 0,
    fixedPixelsBottom: 60
   };

 this.nativePageTransitions.slide(options)
   .then(onSuccess)
   .catch(onError);

}

// example of adding a transition when pushing a new page
openPage(page: any) {

  this.nativePageTransitions.slide(options);
  this.navCtrl.push(page);

}

Instance Members

slide(options)

Perform a slide animation

    Param
    Type
    Details

      options

      NativeTransitionOptions

Options for the transition

  Returns: Promise<any>

flip(options)

Perform a flip animation

    Param
    Type
    Details

      options

      NativeTransitionOptions

Options for the transition

  Returns: Promise<any>

fade(options)

  Platforms:iOS Android

Perform a fade animation

    Param
    Type
    Details

      options

      NativeTransitionOptions

Options for the transition

  Returns: Promise<any>

drawer(options)

  Platforms:iOS Android

Perform a slide animation

    Param
    Type
    Details

      options

      NativeTransitionOptions

Options for the transition

  Returns: Promise<any>

curl(options)

  Platforms:iOS

Perform a slide animation

    Param
    Type
    Details

      options

      NativeTransitionOptions

Options for the transition

  Returns: Promise<any>

executePendingTransition()

Execute pending transition

  Returns: Promise<any>

cancelPendingTransition()

Cancel pending transition

  Returns: Promise<any>

redpajama_set_name: RedPajamaGithub


text:
#include<stdio.h>
#include<time.h>
#include<fstream>
#include<chrono>
#include<errno.h>

#include<sensor_msgs/CompressedImage.h>

#include<transcoders.h>

using namespace rospilot;

int main(int argc, char **argv)
{
    // XXX: Assumes that the input image 1600x1200
    PixelFormat pixelFormat = PIX_FMT_YUV420P;
    JpegDecoder *jpegDecoder = new FFmpegJpegDecoder(1600, 1200, pixelFormat);

    sensor_msgs::CompressedImage image;
    image.format = "jpeg";

    std::string path(argv[1]);
    std::fstream f(path, std::ifstream::binary | std::ios_base::in);
    if (!f) {
        std::cout << "Failed to open " << path << std::endl;
        return 1;
    }
    f.seekg(0, f.end);
    int length = f.tellg();
    f.seekg(0, f.beg);
    char *buffer = new char[length];
    f.read(buffer, length);
    f.close();
    for (int i = 0; i < length; i++) {
        image.data.push_back(buffer[i]);
    }
    delete buffer;

    sensor_msgs::CompressedImage images[10];
    for (int i = 0; i < 10; i++) {
        images[i] = image;
    }

    int junk = 0;
    std::chrono::steady_clock::time_point start = std::chrono::steady_clock::now();
    for (int i = 0; i < 10; i++) {
        jpegDecoder->decodeInPlace(&images[i]);
        // Make sure there's a side effect
        junk += images[i].data.size();
    }
    std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now();
    double us = std::chrono::duration_cast<std::chrono::microseconds>(end - start).count() / 1000000.0;
    std::cout << "FFmpeg FPS " << 10 / us << std::endl;
    std::cout << "check: " << junk << std::endl;

    delete jpegDecoder;
    jpegDecoder = new TurboJpegDecoder(1600, 1200, pixelFormat);
    for (int i = 0; i < 10; i++) {
        images[i] = image;
    }
    junk = 0;
    start = std::chrono::steady_clock::now();
    for (int i = 0; i < 10; i++) {
        jpegDecoder->decodeInPlace(&images[i]);
        // Make sure there's a side effect
        junk += images[i].data.size();
    }
    end = std::chrono::steady_clock::now();
    us = std::chrono::duration_cast<std::chrono::microseconds>(end - start).count() / 1000000.0;
    std::cout << "TurboJpeg FPS " << 10 / us << std::endl;
    std::cout << "check: " << junk << std::endl;

    delete jpegDecoder;
    return 0;
}


text:
import { Component, Input, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'sd-tab',
  template: `
    <div [hidden]="!active" class="pane">
      <ng-content></ng-content>
    </div>
  `
})
export class TabComponent {
  @Input() title: string;
  @Input() active = false;
  @Output() present: EventEmitter<any> = new EventEmitter(true);
}


text:
module Julia
  module LibJulia
    require 'julia/libjulia/finder'

    def self.load_lib
      require 'julia/libjulia/finder'
      lib_path = Finder.find_libjulia
      Fiddle::Handle.new(lib_path[0], Fiddle::Handle::RTLD_LAZY | Fiddle::Handle::RTLD_GLOBAL)
    end

    def self.handle
      # NOTE: Julia.init redefine this method.
      #       See julia/init.rb for the detail.
      Julia.init
      handle
    end

    module_function def method_missing(name, *args, **kwargs, &block)
      ::Julia.init
      if respond_to?(name)
        __send__(name, *args, **kwargs, &block)
      else
        super
      end
    end
  end
end


text:
import React from 'react';
import { storiesOf } from '@storybook/react';
import ProgressBar from './ProgressBar';

storiesOf('ProgressBar', module)
  .add('Normal', () => (
    <ProgressBar value={5} />
  ))
  .add('MaxValue', () => (
    <ProgressBar value={5} maxValue={20} />
  ))
  .add('Segmented', () => (
    <ProgressBar value={7} segmented />
  ));


text:
require 'solidus_core'
require 'solidus_backend'

require 'solidus_support'
require 'solidus_avatax_certified/engine'
require 'solidus_avatax_certified/exceptions'
require 'solidus_avatax_certified/version'
require 'spree/avatax/config'
require 'deface'
require 'avatax'


text:
copyright:
  years: 2015, 2016

---

# Ativando a autenticação do Google para apps iOS Objective C
{: #google-auth-ios}

Use o Google Sign-In para autenticar usuários em seu app Mobile Client Access iOS.

**Nota:** embora o Objective-C SDK permaneça totalmente suportado e ainda seja considerado o SDK primário para o {{site.data.keyword.Bluemix_notm}} Mobile Services, há planos para descontinuar esse SDK posteriormente este ano em favor do novo Swift SDK. Para novos aplicativos, é altamente recomendável usar o Swift SDK. As instruções nesta página se aplicam ao {{site.data.keyword.amashort}} client Objective-C SDK. Para obter instruções sobre como usar o Swift SDK, consulte [Ativando a autenticação do Google em apps iOS (Swift SDK)](https://console.{DomainName}/docs/services/mobileaccess/google-auth-ios-swift-sdk.html).

## Antes de Começar
{: #google-auth-ios-before}
Você deve ter:
* Um projeto do iOS em Xcode. Ele não precisa ser instrumentado com o {{site.data.keyword.amashort}} client SDK.
* Uma instância de um aplicativo {{site.data.keyword.Bluemix_notm}} que seja protegida pelo serviço {{site.data.keyword.amashort}}. Para obter mais informações sobre como criar um backend do {{site.data.keyword.Bluemix_notm}}, consulte [Introdução](index.html).

## Configurando um projeto do Google para a plataforma iOS
{: #google-auth-ios-project}
Para iniciar o uso do Google como provedor de identidade, crie um projeto no Console do desenvolvedor do Google para obter um identificador de cliente do Google.  Esse identificador de cliente é um identificador exclusivo para que o Google saiba qual aplicativo está tentando se conectar.   Se você já tiver o projeto do Google, poderá ignorar as etapas que descrevem a criação do projeto e iniciar com a inclusão de credenciais.

1. Crie um projeto no [Console do desenvolvedor do Google](https://console.developers.google.com).
Se você já tiver um projeto, poderá ignorar as etapas que descrevem a criação do projeto e iniciar com a inclusão de credenciais.
   1.    Abra o menu do novo projeto.

         ![image](images/FindProject.jpg)

   2.    Clique em **Criar um projeto**.

         ![image](images/CreateAProject.jpg)

1. Na lista **APIs sociais**, escolha **API do Google+**.

     ![image](images/chooseGooglePlus.jpg)

1. Clique em **Ativar** na próxima tela.

1. Selecione a guia **Tela de consentimento** e forneça o nome do produto mostrado aos usuários. Outros valores são opcionais. Clique em **Salvar**.

    ![image](images/consentScreen.png)

1. Na lista **Credenciais**, escolha o identificador de cliente OAuth.

     ![image](images/chooseCredentials.png)

1. Neste momento, será apresentada a você uma opção de tipo de aplicativo. Selecione **iOS**.

1. Forneça um nome significativo para seu cliente iOS. Especifique o ID do
pacote configurável do seu aplicativo iOS. Para descobrir o ID do pacote configurável do
seu aplicativo iOS, procure **Identificador de pacote configurável**
no arquivo `info.plist` ou na guia **Geral** do
projeto Xcode.

1. Anote o novo identificador de cliente do Google iOS. É necessário o valor ao configurar o aplicativo no {{site.data.keyword.Bluemix}}.

## Configurando o {{site.data.keyword.amashort}} para autenticação do Google
{: #google-auth-ios-config}

Agora que você tem um identificador de cliente do Google iOS, é possível ativar a autenticação do Google no painel do {{site.data.keyword.Bluemix_notm}}.

1. Abra seu app no painel do {{site.data.keyword.Bluemix_notm}}.

1. Clique em **Opções móveis** e anote a
**Rota** (`applicationRoute`) e o **GUID do
app** (`applicationGUID`). Eles serão necessários ao inicializar o SDK.

1. Clique no ladrilho {{site.data.keyword.amashort}}. O painel do {{site.data.keyword.amashort}} é carregado.

1. Clique no ladrilho **Google**.

1. Em **ID do aplicativo para iOS**, especifique o identificador de cliente do Google para iOS e clique em **Salvar**.

	Nota: além do identificador de cliente do Google, o valor reverso também é necessário para sua configuração do cliente (veja abaixo). Para acessar ambos os valores, faça download da plist de exemplo usando o ícone de lápis:
		![download do arquivo info.plist](images/download_plist.png)

## Configurando o {{site.data.keyword.amashort}} Google client SDK for iOS
{: #google-auth-ios-sdk}

### Instalando o {{site.data.keyword.amashort}} client SDK usando o CocoaPods
{: #google-auth-ios-sdk-cocoapods}

1. Navegue para seu projeto do iOS.

1. Edite o `Podfile` para incluir a linha a seguir:

	```
	pod 'IMFGoogleAuthentication'
	```

1. Salve o `Podfile` e execute `pod install` na
linha de comandos. O CocoaPods instala as dependências. Você verá o progresso e os componentes que foram incluídos.

  **Importante**: deve-se abrir agora o projeto usando o arquivo
`xcworkspace` que é gerado pelo CocoaPods. Normalmente, o nome é `{your-project-name}.xcworkspace`.

1. Execute `open {your-project-name}.xcworkspace` na linha de
comandos para abrir sua área de trabalho de projeto do iOS.

### Configurando o projeto do iOS para autenticação do Google
{: #google-auth-ios-googleauth}
Configure a integração do Google atualizando o arquivo `info.plist`. O
arquivo `info.plist` normalmente está na pasta `Arquivos de
apoio` em seu projeto Xcode. É possível editar o arquivo no editor de lista de propriedades ou com um editor de texto.

* Configure a integração do Google incluindo os esquemas de URL a seguir no
arquivo `info.plist`
	![info.plist file](images/ios-google-infoplist-settings.png)

	O primeiro Esquema de URL é uma versão reversa do identificador de cliente do Console do desenvolvedor do Google. Por exemplo, se o identificador de cliente for `123123-abcabc.apps.googleusercontent.com`, o Esquema de URL será: `com.googleusercontent.apps.123123-abcabc`.

	O segundo Esquema de URL é o ID do pacote configurável de seu aplicativo

* Utilize um editor de texto. Clique com o botão direito em
`info.plist` e selecione **Abrir como > Código fonte**. Inclua
o XML a seguir no arquivo:

	```XML
	<key>CFBundleURLTypes</key>
	<array>
		<dict>
			<key>CFBundleTypeRole</key>
			<string>Editor</string>
			<key>CFBundleURLSchemes</key>
			<array>
				<string>com.googleusercontent.apps.123123-abcabc</string>
			</array>
		</dict>
		<dict>
			<key>CFBundleTypeRole</key>
			<string>Editor</string>
			<key>CFBundleURLSchemes</key>
			<array>
				<string>com.ibm.HelloWorld</string>
			</array>
		</dict>
	</array>

	```
	Atualize ambos os Esquemas de URL.

	**Importante**: Não substitua qualquer propriedade existente
no arquivo `info.plist`. Se você tiver propriedades de sobreposição,
precisará mesclar as propriedades manualmente. Para obter mais informações, consulte
[Tentar
Sign-In para iOS](https://developers.google.com/identity/sign-in/ios/start).

## Inicializando o {{site.data.keyword.amashort}} client SDK
{: #google-auth-ios-initialize}

Para usar o {{site.data.keyword.amashort}} client SDK, inicialize-o passando os parâmetros applicationGUID e applicationRoute.

Um local comum, mas não obrigatório, para colocar o código de inicialização é o método `application:didFinishLaunchingWithOptions` de delegado do seu aplicativo.

1. Obtenha os valores applicationGUID e applicationRoute. No painel
{{site.data.keyword.Bluemix_notm}}, clique em seu app. Clique em **Opções de dispositivo móvel**. Os valores Application Route e Application GUID são exibidos.

1. Importe as estruturas necessárias na classe em que você deseja usar o {{site.data.keyword.amashort}} client SDK. Inclua os cabeçalhos a seguir:

	Objective-C:

	```Objective-C
	#import <IMFCore/IMFCore.h>
	#import <IMFGoogleAuthentication/IMFGoogleAuthenticationHandler.h>
	```

	Swift:

	O {{site.data.keyword.amashort}} client SDK é implementado com Objective-C. Pode ser necessário incluir um cabeçalho de ponte em seu projeto Swift para usar o SDK.

	1. Clique com o botão direito no projeto em Xcode e selecione **Novo arquivo...**
	2. Na categoria **Origem iOS**, selecione **Arquivo de cabeçalho**.
	3. Dê o nome `BridgingHeader.h`
	4. Inclua as importações a seguir em seu cabeçalho de ponte:

	```Objective-C
	#import <IMFCore/IMFCore.h>
	#import <IMFGoogleAuthentication/IMFGoogleAuthenticationHandler.h>
	```
	5. Clique em seu projeto em Xcode e selecione a guia **Configurações de compilação**.
	6. Procure por `Cabeçalho de ponte do Objective-C`.
	7. Configure o valor para o local do seu arquivo `BridgingHeader.h`, por exemplo: `$(SRCROOT)/MyApp/BridgingHeader.h`.
	8. Assegure-se de que seu cabeçalho de ponte esteja sendo selecionado pelo Xcode, compilando o seu projeto.

3. Use o código a seguir para inicializar o client SDK.  Substitua
*applicationRoute* e *applicationGUID* pelos valores de
**Rota** e **GUID do app** que você obteve das
**Opções móveis**.

	Objective-C:

	```Objective-C
	[[IMFClient sharedInstance]
			initializeWithBackendRoute:@"applicationRoute"
			backendGUID:@"applicationGUID"];
	```

	Swift:

	```Swift
	IMFClient.sharedInstance().initializeWithBackendRoute("applicationRoute",
	 							backendGUID: "applicationGUID")
	```

1. Registre o Manipulador de autenticação do Google incluindo o código a seguir no
método `application:didFinishLaunchingWithOptions` na delegação do seu
app. Inclua este código imediatamente após a inicialização do IMFClient:

	Objective-C:

	```Objective-C
	[[IMFGoogleAuthenticationHandler sharedInstance] registerWithDefaultDelegate];
	```

	Swift:

	```Swift
	IMFGoogleAuthenticationHandler.sharedInstance().registerWithDefaultDelegate()
	```

1. Inclua o código a seguir no delegado do app.

	Objective-C:

	```Objective-C
	- (void)applicationDidBecomeActive:(UIApplication *)application {
		[[IMFGoogleAuthenticationHandler sharedInstance] handleDidBecomeActive];
	}

	- (BOOL)application: (UIApplication *)application openURL: (NSURL *)url
					sourceApplication: (NSString *)sourceApplication annotation: (id)annotation {

		BOOL shouldHandleGoogleURL = [GPPURLHandler handleURL:url sourceApplication:sourceApplication annotation:annotation];

		[[IMFGoogleAuthenticationHandler sharedInstance] handleOpenURL:shouldHandleGoogleURL];
		return  shouldHandleGoogleURL;
	}
	```

	Swift:

	```Swift
	func application(application: UIApplication, openURL url: NSURL,
					sourceApplication: String?, annotation: AnyObject) -> Bool {

		let shouldHandleGoogleURL = GPPURLHandler.handleURL(url,
				sourceApplication: sourceApplication, annotation: annotation)

		IMFGoogleAuthenticationHandler.sharedInstance().handleOpenURL(shouldHandleGoogleURL)

		return shouldHandleGoogleURL;
	}
```

## Testando a autenticação
{: #google-auth-ios-testing}
Após a inicialização do client SDK, é possível começar a fazer solicitações para seu backend móvel.

### Antes de iniciar
{: #google-auth-ios-testing-before}
Deve-se estar usando o modelo do {{site.data.keyword.mobilefirstbp}} e já ter um recurso protegido pelo {{site.data.keyword.amashort}} no terminal `/protected`. Se for necessário configurar um terminal `/protected`, consulte [Protegendo recursos](https://console.{DomainName}/docs/services/mobileaccess/protecting-resources.html).

1. Tente enviar uma solicitação para o terminal protegido de seu backend móvel no navegador da área de trabalho abrindo `{applicationRoute}/protected`, por exemplo, `http://my-mobile-backend.mybluemix.net/protected`

1. O terminal `/protected` de um backend móvel criado com o Modelo MobileFirst Services está protegido com o {{site.data.keyword.amashort}}, portanto, ele só pode ser acessado por aplicativos móveis instrumentados com o {{site.data.keyword.amashort}} client SDK. Como resultado, você verá `Unauthorized` no navegador de sua área de trabalho.

1. Use seu aplicativo iOS para fazer solicitação para o mesmo terminal.

	Objective-C:

	```Objective-C
	NSString *requestPath = [NSString stringWithFormat:@"%@/protected",
								[[IMFClient sharedInstance] backendRoute]];

	IMFResourceRequest *request =  [IMFResourceRequest requestWithPath:requestPath
																method:@"GET"];

	[request sendWithCompletionHandler:^(IMFResponse *response, NSError *error) {
		if (error){
			NSLog(@"Error :: %@", [error description]);
		} else {
			NSLog(@"Response :: %@", [response responseText]);
			NSLog(@"%@", [[IMFAuthorizationManager sharedInstance] userIdentity]);
		}
	}];
	```

	Swift:

	```Swift
	let requestPath = IMFClient.sharedInstance().backendRoute + "/protected"

	let request = IMFResourceRequest(path: requestPath, method: "GET");
	request.sendWithCompletionHandler { (response, error) -> Void in
		if (nil != error){
			NSLog("Error :: %@", error.description)
		} else {
			NSLog("Response :: %@", response.responseText)
			NSLog("%@", IMFAuthorizationManager.sharedInstance().userIdentity)
		}
	};

	```

1. Execute seu aplicativo. Você verá um pop-up da tela de Login do Google

	![image](images/ios-google-login.png)

	Essa tela poderá parecer um pouco diferente se o app Facebook não estiver instalado em seu dispositivo, ou se você não estiver atualmente conectado ao Facebook.

1. Ao clicar em **OK** você está autorizando o {{site.data.keyword.amashort}} a usar sua identidade de usuário do Google para propósitos de autenticação.

1.	Sua solicitação deve ser bem-sucedida. Você deverá ver a saída a seguir no LogCat

	![image](images/ios-google-login-success.png)

	Também é possível incluir a funcionalidade de logout incluindo o código a seguir:

	Objective C:

	```Objective-C
	[[IMFGoogleAuthenticationHandler sharedInstance] logout : callBack]
	```

	Swift:

	```Swift
	IMFGoogleAuthenticationHandler.sharedInstance().logout(callBack)
	```

	Se você chamar esse código depois que um usuário estiver conectado ao Google e ele tentar efetuar login novamente, ele será solicitado a autorizar o {{site.data.keyword.amashort}} a usar o Google para propósitos de autenticação. Neste ponto, o usuário pode clicar no nome do usuário no canto superior direito da tela para selecionar e efetuar login com outro usuário.

	Passar `callBack` para a função de logout é opcional. Também é possível passar `nil`.


text:
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class InExactVariable {
  public void testMap() {
      HashMap<String, String> map = new HashMap<>();
      for (Integer integer2 : Arrays.asList(1, 2, 3, 4)) {
          String of = String.valueOf(integer2);
          map.putIfAbsent(of.trim(), of);
      }
      Object map1 = map;
      HashMap<String, String> map2 = new HashMap<>();
      for (Integer integer1 : Arrays.asList(1, 2, 3, 4)) {
          String valueOf = String.valueOf(integer1);
          map2.putIfAbsent(valueOf.trim(), valueOf);
      }
      Map<String, String> map3 = new HashMap<>();
      for (Integer integer : Arrays.asList(1, 2, 3, 4)) {
          String s = String.valueOf(integer);
          map3.putIfAbsent(s.trim(), s);
      }
  }

  public void testList() {
      List<String> result1 = new ArrayList<>();
      for (Integer integer5 : Arrays.asList(1, 2, 3, 4)) {
          String valueOf1 = String.valueOf(integer5);
          result1.add(valueOf1);
      }
      Object list1 = result1;
      List<String> result = new ArrayList<>();
      for (Integer integer4 : Arrays.asList(1, 2, 3, 4)) {
          String s1 = String.valueOf(integer4);
          result.add(s1);
      }
      Iterable<String> list2 = result;
      Collection<String> list3 = new ArrayList<>();
      for (Integer integer3 : Arrays.asList(1, 2, 3, 4)) {
          String value = String.valueOf(integer3);
          list3.add(value);
      }
      List<String> list4 = new ArrayList<>();
      for (Integer integer2 : Arrays.asList(1, 2, 3, 4)) {
          String of = String.valueOf(integer2);
          list4.add(of);
      }
      Collection<Object> list5 = new ArrayList<>();
      for (Integer integer1 : Arrays.asList(1, 2, 3, 4)) {
          String valueOf = String.valueOf(integer1);
          list5.add(valueOf);
      }
      List<String> list = new ArrayList<>();
      for (Integer integer : Arrays.asList(1, 2, 3, 4)) {
          String s = String.valueOf(integer);
          list.add(s);
      }
      Collection<?> list6 = list;
  }

  public void testPartition() {
      Map<Boolean, List<String>> map = new HashMap<>();
      map.put(false, new ArrayList<>());
      map.put(true, new ArrayList<>());
      for (Integer integer1 : Arrays.asList(1, 2, 3, 4)) {
          String s = String.valueOf(integer1);
          map.get(s.length() > 1).add(s);
      }
      Object map1 = map;
      Map<Boolean, List<String>> map2 = new HashMap<>();
      map2.put(false, new ArrayList<>());
      map2.put(true, new ArrayList<>());
      for (Integer integer : Arrays.asList(1, 2, 3, 4)) {
          String x = String.valueOf(integer);
          map2.get(x.length() > 1).add(x);
      }
  }

  public void testGroupingBy() {
      TreeMap<Integer, Set<String>> result = new TreeMap<>();
      for (Integer integer4 : Arrays.asList(1, 2, 3, 4)) {
          String s1 = String.valueOf(integer4);
          result.computeIfAbsent(s1.length(), k2 -> new HashSet<>()).add(s1);
      }
      Object map1 = result;
      TreeMap<Integer, Set<String>> map2 = new TreeMap<>();
      for (Integer integer3 : Arrays.asList(1, 2, 3, 4)) {
          String value = String.valueOf(integer3);
          map2.computeIfAbsent(value.length(), key1 -> new HashSet<>()).add(value);
      }
      NavigableMap<Integer, Set<String>> map3 = new TreeMap<>();
      for (Integer integer2 : Arrays.asList(1, 2, 3, 4)) {
          String of = String.valueOf(integer2);
          map3.computeIfAbsent(of.length(), k1 -> new HashSet<>()).add(of);
      }
      SortedMap<Integer, Set<String>> map4 = new TreeMap<>();
      for (Integer integer1 : Arrays.asList(1, 2, 3, 4)) {
          String valueOf = String.valueOf(integer1);
          map4.computeIfAbsent(valueOf.length(), key -> new HashSet<>()).add(valueOf);
      }
      TreeMap<Integer, Set<String>> map = new TreeMap<>();
      for (Integer integer : Arrays.asList(1, 2, 3, 4)) {
          String s = String.valueOf(integer);
          map.computeIfAbsent(s.length(), k -> new HashSet<>()).add(s);
      }
      Cloneable map5 = map;
  }
}


text:
package com.github.programmerr47.vkgroups.background.db.entries;

import android.provider.BaseColumns;

/**
 * @author Michael Spitsin
 * @since 2016-01-10
 */
class VkContract {

    static final String TEXT_TYPE = " TEXT";
    static final String INTEGER_TYPE = " INTEGER";
    static final String COMMA_SEP = ", ";
}


text:
class Component < ActiveRecord::Base

  #------- Plugin Behavior -------#
  acts_as_list :scope => :question

  #------- Associations -------#
  belongs_to :question
  belongs_to :user

  #------- Validations -------#
  validates_presence_of :question_id
  validates_presence_of :user_id
  validates_presence_of :value

end


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

namespace Succubus
{
    [Serializable]
    class SynchronizationStack
    {
        public List<SynchronizationFrame> Frames { get; set; }

        SynchronizationContext ctx;

        public SynchronizationStack(SynchronizationContext ctx)
        {
            Frames = new List<SynchronizationFrame>();
            this.ctx = ctx;
        }

        internal SynchronizationStack CloneFor(SynchronizationContext ctx)
        {
            SynchronizationStack stack = new SynchronizationStack(ctx);
            foreach (var frame in Frames)
            {
                stack.Frames.Add(frame.Clone());
            }
            return stack;
        }

        public bool ResolveFor(object message)
        {
            if (Frames == null || Frames.Count == 0) return false;

            bool unresolvedFrames = false;
            foreach (var frame in Frames)
            {
                if (frame.Resolved == true)
                {
                    continue;
                }

                if (frame.CanHandle(message) == false)
                {
                    unresolvedFrames = true;
                    continue;
                }

                if (ctx.responses.ContainsKey(message.GetType()) == false)
                {
                    ctx.responses.Add(message.GetType(), message);
                }

                if (frame.Satisfies(ctx.responses, out ctx.castMessages))
                {

                    SynchronizationFrame localFrame = frame;
                    new Thread(new ThreadStart(delegate()
                    {
                        switch (ctx.ContextType)
                        {
                            case ContextType.Transient:
                                localFrame.CallHandler(ctx.castMessages);
                                break;
                            case ContextType.Static:
                                localFrame.CallStaticHandler(ctx.castMessages);
                                break;
                            case ContextType.Deferred:
                                localFrame.CallDeferredHandler(ctx.castMessages);
                                break;
                        }

                    })).Start();
                    frame.Resolved = true;
                }
                else
                {
                    unresolvedFrames = true;
                }
            }

            if (unresolvedFrames == false)
            {
                // Finished resolving this context
                return true;
            }
            else return false;

        }

    }
}


text:
package org.neo4j.kernel.impl.store;

import org.act.temporalProperty.TemporalPropertyStore;
import org.act.temporalProperty.TemporalPropertyStoreFactory;
import org.act.temporalProperty.impl.MemTable;
import org.act.temporalProperty.query.TimeIntervalKey;
import org.act.temporalProperty.util.Slice;

import org.neo4j.kernel.configuration.Config;
import org.neo4j.kernel.lifecycle.LifecycleAdapter;
import org.neo4j.temporal.TemporalPropertyReadOperation;

import java.io.File;
import java.io.IOException;

/**
 * Created by song on 17-7-7.
 */
public class TemporalPropertyStoreAdapter extends LifecycleAdapter
{
    private File dbDir;
    private Config config;
    private TemporalPropertyStore nodeStore;
    private TemporalPropertyStore relStore;

    private static TemporalPropertyStoreAdapter instance;

    public static synchronized TemporalPropertyStoreAdapter getInstance( Config configs, File dbDir )
    {
        if ( null == instance )
        {
            instance = new TemporalPropertyStoreAdapter( configs, dbDir );
        }
        return instance;
    }

    public static synchronized TemporalPropertyStoreAdapter getInstance()
    {
        if ( null == instance )
        {
            throw new IllegalStateException( "temporal property storage not initialized!" );
        }
        else
        {
            return instance;
        }
    }

    private TemporalPropertyStoreAdapter( Config configs, File dbDir )
    {
        this.dbDir = dbDir;
        this.config = configs;
    }

    @Override
    public void init() throws Throwable
    {
        this.nodeStore = TemporalPropertyStoreFactory.newPropertyStore( resolveStoreDir( "temporal.node.properties" ) );
        this.relStore = TemporalPropertyStoreFactory.newPropertyStore( resolveStoreDir( "temporal.relationship.properties" ) );
    }

    @Override
    public void shutdown() throws Throwable
    {
        this.nodeStore.shutDown();
        this.relStore.shutDown();
    }

    private File resolveStoreDir( String folder ) throws IOException
    {
        File dir = new File( dbDir.getAbsolutePath(), folder );
        if ( dir.exists() )
        {
            if ( !dir.isDirectory() )
            {
                throw new IOException( folder + " is not a directory." );
            }
        }
        else
        {
            if ( !dir.mkdirs() )
            {
                throw new IOException( "create temporal.node.properties dir failed." );
            }
        }
        return dir;
    }

    public TemporalPropertyStore nodeStore()
    {
        return nodeStore;
    }

    public TemporalPropertyStore relStore()
    {
        return relStore;
    }

    public Slice getPoint( TemporalPropertyStore store, TemporalPropertyReadOperation query )
    {
        return store.getPointValue( query.getEntityId(), query.getProId(), query.getStart() );
    }

    public Object getRange( TemporalPropertyStore store, TemporalPropertyReadOperation query, MemTable oneEntityData )
    {
        return store.getRangeValue( query.getEntityId(), query.getProId(), query.getStart(), query.getEnd(), query.callBack(), oneEntityData );
    }

    public Object getAggrIndex( TemporalPropertyStore store, TemporalPropertyReadOperation query, MemTable oneEntityData )
    {
        return store.getByIndex( query.getIndexId(), query.getEntityId(), query.getProId(), query.getStart(), query.getEnd(), oneEntityData );
    }

    public void setValue( TemporalPropertyStore store, TimeIntervalKey intervalKey, Slice value )
    {
        store.setProperty( intervalKey, value );
    }

    public void flushAll()
    {
        if ( this.relStore != null )
        {
            this.relStore.flushMemTable2Disk();
            this.relStore.flushMetaInfo2Disk();
        }
        if ( this.nodeStore != null )
        {
            this.nodeStore.flushMemTable2Disk();
            this.nodeStore.flushMetaInfo2Disk();
        }
    }

    public TemporalPropertyStore getNodeStore()
    {
        return nodeStore;
    }

    public TemporalPropertyStore getRelStore()
    {
        return relStore;
    }
}