text:
module Azure::Dns::Mgmt::V2016_04_01
  #
  # The DNS Management Client.
  #
  class RecordSets
    include MsRestAzure

    #
    # Creates and initializes a new instance of the RecordSets class.
    # @param client service class for accessing basic functionality.
    #
    def initialize(client)
      @client = client
    end

    # @return [DnsManagementClient] reference to the DnsManagementClient
    attr_reader :client

    #
    # Updates a record set within a DNS zone.
    #
    # @param resource_group_name [String] The name of the resource group. The name
    # is case insensitive.
    # @param zone_name [String] The name of the DNS zone (without a terminating
    # dot).
    # @param relative_record_set_name [String] The name of the record set, relative
    # to the name of the zone.
    # @param record_type [RecordType] The type of DNS record in this record set.
    # Possible values include: 'A', 'AAAA', 'CNAME', 'MX', 'NS', 'PTR', 'SOA',
    # 'SRV', 'TXT'
    # @param parameters [RecordSet] Parameters supplied to the Update operation.
    # @param if_match [String] The etag of the record set. Omit this value to
    # always overwrite the current record set. Specify the last-seen etag value to
    # prevent accidentally overwritting concurrent changes.
    # @param custom_headers [Hash{String => String}] A hash of custom headers that
    # will be added to the HTTP request.
    #
    # @return [RecordSet] operation results.
    #
    def update(resource_group_name, zone_name, relative_record_set_name, record_type, parameters, if_match:nil, custom_headers:nil)
      response = update_async(resource_group_name, zone_name, relative_record_set_name, record_type, parameters, if_match:if_match, custom_headers:custom_headers).value!
      response.body unless response.nil?
    end

    #
    # Updates a record set within a DNS zone.
    #
    # @param resource_group_name [String] The name of the resource group. The name
    # is case insensitive.
    # @param zone_name [String] The name of the DNS zone (without a terminating
    # dot).
    # @param relative_record_set_name [String] The name of the record set, relative
    # to the name of the zone.
    # @param record_type [RecordType] The type of DNS record in this record set.
    # Possible values include: 'A', 'AAAA', 'CNAME', 'MX', 'NS', 'PTR', 'SOA',
    # 'SRV', 'TXT'
    # @param parameters [RecordSet] Parameters supplied to the Update operation.
    # @param if_match [String] The etag of the record set. Omit this value to
    # always overwrite the current record set. Specify the last-seen etag value to
    # prevent accidentally overwritting concurrent changes.
    # @param custom_headers [Hash{String => String}] A hash of custom headers that
    # will be added to the HTTP request.
    #
    # @return [MsRestAzure::AzureOperationResponse] HTTP response information.
    #
    def update_with_http_info(resource_group_name, zone_name, relative_record_set_name, record_type, parameters, if_match:nil, custom_headers:nil)
      update_async(resource_group_name, zone_name, relative_record_set_name, record_type, parameters, if_match:if_match, custom_headers:custom_headers).value!
    end

    #
    # Updates a record set within a DNS zone.
    #
    # @param resource_group_name [String] The name of the resource group. The name
    # is case insensitive.
    # @param zone_name [String] The name of the DNS zone (without a terminating
    # dot).
    # @param relative_record_set_name [String] The name of the record set, relative
    # to the name of the zone.
    # @param record_type [RecordType] The type of DNS record in this record set.
    # Possible values include: 'A', 'AAAA', 'CNAME', 'MX', 'NS', 'PTR', 'SOA',
    # 'SRV', 'TXT'
    # @param parameters [RecordSet] Parameters supplied to the Update operation.
    # @param if_match [String] The etag of the record set. Omit this value to
    # always overwrite the current record set. Specify the last-seen etag value to
    # prevent accidentally overwritting concurrent changes.
    # @param [Hash{String => String}] A hash of custom headers that will be added
    # to the HTTP request.
    #
    # @return [Concurrent::Promise] Promise object which holds the HTTP response.
    #
    def update_async(resource_group_name, zone_name, relative_record_set_name, record_type, parameters, if_match:nil, custom_headers:nil)
      fail ArgumentError, 'resource_group_name is nil' if resource_group_name.nil?
      fail ArgumentError, "'resource_group_name' should satisfy the constraint - 'MaxLength': '90'" if !resource_group_name.nil? && resource_group_name.length > 90
      fail ArgumentError, "'resource_group_name' should satisfy the constraint - 'MinLength': '1'" if !resource_group_name.nil? && resource_group_name.length < 1
      fail ArgumentError, "'resource_group_name' should satisfy the constraint - 'Pattern': '^[-\w\._\(\)]+$'" if !resource_group_name.nil? && resource_group_name.match(Regexp.new('^^[-\w\._\(\)]+$$')).nil?
      fail ArgumentError, 'zone_name is nil' if zone_name.nil?
      fail ArgumentError, 'relative_record_set_name is nil' if relative_record_set_name.nil?
      fail ArgumentError, 'record_type is nil' if record_type.nil?
      fail ArgumentError, 'parameters is nil' if parameters.nil?
      fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil?
      fail ArgumentError, "'@client.api_version' should satisfy the constraint - 'MinLength': '1'" if !@client.api_version.nil? && @client.api_version.length < 1
      fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil?
      fail ArgumentError, "'@client.subscription_id' should satisfy the constraint - 'MinLength': '1'" if !@client.subscription_id.nil? && @client.subscription_id.length < 1

      request_headers = {}
      request_headers['Content-Type'] = 'application/json; charset=utf-8'

      # Set Headers
      request_headers['x-ms-client-request-id'] = SecureRandom.uuid
      request_headers['If-Match'] = if_match unless if_match.nil?
      request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?

      # Serialize Request
      request_mapper = Azure::Dns::Mgmt::V2016_04_01::Models::RecordSet.mapper()
      request_content = @client.serialize(request_mapper,  parameters)
      request_content = request_content != nil ? JSON.generate(request_content, quirks_mode: true) : nil

      path_template = 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/{recordType}/{relativeRecordSetName}'

      request_url = @base_url || @client.base_url

      options = {
          middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
          path_params: {'resourceGroupName' => resource_group_name,'zoneName' => zone_name,'recordType' => record_type,'subscriptionId' => @client.subscription_id},
          skip_encoding_path_params: {'relativeRecordSetName' => relative_record_set_name},
          query_params: {'api-version' => @client.api_version},
          body: request_content,
          headers: request_headers.merge(custom_headers || {}),
          base_url: request_url
      }
      promise = @client.make_request_async(:patch, path_template, options)

      promise = promise.then do |result|
        http_response = result.response
        status_code = http_response.status
        response_content = http_response.body
        unless status_code == 200
          error_model = JSON.load(response_content)
          fail MsRestAzure::AzureOperationError.new(result.request, http_response, error_model)
        end

        result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
        # Deserialize Response
        if status_code == 200
          begin
            parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
            result_mapper = Azure::Dns::Mgmt::V2016_04_01::Models::RecordSet.mapper()
            result.body = @client.deserialize(result_mapper, parsed_response)
          rescue Exception => e
            fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
          end
        end

        result
      end

      promise.execute
    end

    #
    # Creates or updates a record set within a DNS zone.
    #
    # @param resource_group_name [String] The name of the resource group. The name
    # is case insensitive.
    # @param zone_name [String] The name of the DNS zone (without a terminating
    # dot).
    # @param relative_record_set_name [String] The name of the record set, relative
    # to the name of the zone.
    # @param record_type [RecordType] The type of DNS record in this record set.
    # Record sets of type SOA can be updated but not created (they are created when
    # the DNS zone is created). Possible values include: 'A', 'AAAA', 'CNAME',
    # 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT'
    # @param parameters [RecordSet] Parameters supplied to the CreateOrUpdate
    # operation.
    # @param if_match [String] The etag of the record set. Omit this value to
    # always overwrite the current record set. Specify the last-seen etag value to
    # prevent accidentally overwritting any concurrent changes.
    # @param if_none_match [String] Set to '*' to allow a new record set to be
    # created, but to prevent updating an existing record set. Other values will be
    # ignored.
    # @param custom_headers [Hash{String => String}] A hash of custom headers that
    # will be added to the HTTP request.
    #
    # @return [RecordSet] operation results.
    #
    def create_or_update(resource_group_name, zone_name, relative_record_set_name, record_type, parameters, if_match:nil, if_none_match:nil, custom_headers:nil)
      response = create_or_update_async(resource_group_name, zone_name, relative_record_set_name, record_type, parameters, if_match:if_match, if_none_match:if_none_match, custom_headers:custom_headers).value!
      response.body unless response.nil?
    end

    #
    # Creates or updates a record set within a DNS zone.
    #
    # @param resource_group_name [String] The name of the resource group. The name
    # is case insensitive.
    # @param zone_name [String] The name of the DNS zone (without a terminating
    # dot).
    # @param relative_record_set_name [String] The name of the record set, relative
    # to the name of the zone.
    # @param record_type [RecordType] The type of DNS record in this record set.
    # Record sets of type SOA can be updated but not created (they are created when
    # the DNS zone is created). Possible values include: 'A', 'AAAA', 'CNAME',
    # 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT'
    # @param parameters [RecordSet] Parameters supplied to the CreateOrUpdate
    # operation.
    # @param if_match [String] The etag of the record set. Omit this value to
    # always overwrite the current record set. Specify the last-seen etag value to
    # prevent accidentally overwritting any concurrent changes.
    # @param if_none_match [String] Set to '*' to allow a new record set to be
    # created, but to prevent updating an existing record set. Other values will be
    # ignored.
    # @param custom_headers [Hash{String => String}] A hash of custom headers that
    # will be added to the HTTP request.
    #
    # @return [MsRestAzure::AzureOperationResponse] HTTP response information.
    #
    def create_or_update_with_http_info(resource_group_name, zone_name, relative_record_set_name, record_type, parameters, if_match:nil, if_none_match:nil, custom_headers:nil)
      create_or_update_async(resource_group_name, zone_name, relative_record_set_name, record_type, parameters, if_match:if_match, if_none_match:if_none_match, custom_headers:custom_headers).value!
    end

    #
    # Creates or updates a record set within a DNS zone.
    #
    # @param resource_group_name [String] The name of the resource group. The name
    # is case insensitive.
    # @param zone_name [String] The name of the DNS zone (without a terminating
    # dot).
    # @param relative_record_set_name [String] The name of the record set, relative
    # to the name of the zone.
    # @param record_type [RecordType] The type of DNS record in this record set.
    # Record sets of type SOA can be updated but not created (they are created when
    # the DNS zone is created). Possible values include: 'A', 'AAAA', 'CNAME',
    # 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT'
    # @param parameters [RecordSet] Parameters supplied to the CreateOrUpdate
    # operation.
    # @param if_match [String] The etag of the record set. Omit this value to
    # always overwrite the current record set. Specify the last-seen etag value to
    # prevent accidentally overwritting any concurrent changes.
    # @param if_none_match [String] Set to '*' to allow a new record set to be
    # created, but to prevent updating an existing record set. Other values will be
    # ignored.
    # @param [Hash{String => String}] A hash of custom headers that will be added
    # to the HTTP request.
    #
    # @return [Concurrent::Promise] Promise object which holds the HTTP response.
    #
    def create_or_update_async(resource_group_name, zone_name, relative_record_set_name, record_type, parameters, if_match:nil, if_none_match:nil, custom_headers:nil)
      fail ArgumentError, 'resource_group_name is nil' if resource_group_name.nil?
      fail ArgumentError, "'resource_group_name' should satisfy the constraint - 'MaxLength': '90'" if !resource_group_name.nil? && resource_group_name.length > 90
      fail ArgumentError, "'resource_group_name' should satisfy the constraint - 'MinLength': '1'" if !resource_group_name.nil? && resource_group_name.length < 1
      fail ArgumentError, "'resource_group_name' should satisfy the constraint - 'Pattern': '^[-\w\._\(\)]+$'" if !resource_group_name.nil? && resource_group_name.match(Regexp.new('^^[-\w\._\(\)]+$$')).nil?
      fail ArgumentError, 'zone_name is nil' if zone_name.nil?
      fail ArgumentError, 'relative_record_set_name is nil' if relative_record_set_name.nil?
      fail ArgumentError, 'record_type is nil' if record_type.nil?
      fail ArgumentError, 'parameters is nil' if parameters.nil?
      fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil?
      fail ArgumentError, "'@client.api_version' should satisfy the constraint - 'MinLength': '1'" if !@client.api_version.nil? && @client.api_version.length < 1
      fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil?
      fail ArgumentError, "'@client.subscription_id' should satisfy the constraint - 'MinLength': '1'" if !@client.subscription_id.nil? && @client.subscription_id.length < 1

      request_headers = {}
      request_headers['Content-Type'] = 'application/json; charset=utf-8'

      # Set Headers
      request_headers['x-ms-client-request-id'] = SecureRandom.uuid
      request_headers['If-Match'] = if_match unless if_match.nil?
      request_headers['If-None-Match'] = if_none_match unless if_none_match.nil?
      request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?

      # Serialize Request
      request_mapper = Azure::Dns::Mgmt::V2016_04_01::Models::RecordSet.mapper()
      request_content = @client.serialize(request_mapper,  parameters)
      request_content = request_content != nil ? JSON.generate(request_content, quirks_mode: true) : nil

      path_template = 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/{recordType}/{relativeRecordSetName}'

      request_url = @base_url || @client.base_url

      options = {
          middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
          path_params: {'resourceGroupName' => resource_group_name,'zoneName' => zone_name,'recordType' => record_type,'subscriptionId' => @client.subscription_id},
          skip_encoding_path_params: {'relativeRecordSetName' => relative_record_set_name},
          query_params: {'api-version' => @client.api_version},
          body: request_content,
          headers: request_headers.merge(custom_headers || {}),
          base_url: request_url
      }
      promise = @client.make_request_async(:put, path_template, options)

      promise = promise.then do |result|
        http_response = result.response
        status_code = http_response.status
        response_content = http_response.body
        unless status_code == 201 || status_code == 200
          error_model = JSON.load(response_content)
          fail MsRestAzure::AzureOperationError.new(result.request, http_response, error_model)
        end

        result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
        # Deserialize Response
        if status_code == 201
          begin
            parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
            result_mapper = Azure::Dns::Mgmt::V2016_04_01::Models::RecordSet.mapper()
            result.body = @client.deserialize(result_mapper, parsed_response)
          rescue Exception => e
            fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
          end
        end
        # Deserialize Response
        if status_code == 200
          begin
            parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
            result_mapper = Azure::Dns::Mgmt::V2016_04_01::Models::RecordSet.mapper()
            result.body = @client.deserialize(result_mapper, parsed_response)
          rescue Exception => e
            fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
          end
        end

        result
      end

      promise.execute
    end

    #
    # Deletes a record set from a DNS zone. This operation cannot be undone.
    #
    # @param resource_group_name [String] The name of the resource group. The name
    # is case insensitive.
    # @param zone_name [String] The name of the DNS zone (without a terminating
    # dot).
    # @param relative_record_set_name [String] The name of the record set, relative
    # to the name of the zone.
    # @param record_type [RecordType] The type of DNS record in this record set.
    # Record sets of type SOA cannot be deleted (they are deleted when the DNS zone
    # is deleted). Possible values include: 'A', 'AAAA', 'CNAME', 'MX', 'NS',
    # 'PTR', 'SOA', 'SRV', 'TXT'
    # @param if_match [String] The etag of the record set. Omit this value to
    # always delete the current record set. Specify the last-seen etag value to
    # prevent accidentally deleting any concurrent changes.
    # @param custom_headers [Hash{String => String}] A hash of custom headers that
    # will be added to the HTTP request.
    #
    #
    def delete(resource_group_name, zone_name, relative_record_set_name, record_type, if_match:nil, custom_headers:nil)
      response = delete_async(resource_group_name, zone_name, relative_record_set_name, record_type, if_match:if_match, custom_headers:custom_headers).value!
      nil
    end

    #
    # Deletes a record set from a DNS zone. This operation cannot be undone.
    #
    # @param resource_group_name [String] The name of the resource group. The name
    # is case insensitive.
    # @param zone_name [String] The name of the DNS zone (without a terminating
    # dot).
    # @param relative_record_set_name [String] The name of the record set, relative
    # to the name of the zone.
    # @param record_type [RecordType] The type of DNS record in this record set.
    # Record sets of type SOA cannot be deleted (they are deleted when the DNS zone
    # is deleted). Possible values include: 'A', 'AAAA', 'CNAME', 'MX', 'NS',
    # 'PTR', 'SOA', 'SRV', 'TXT'
    # @param if_match [String] The etag of the record set. Omit this value to
    # always delete the current record set. Specify the last-seen etag value to
    # prevent accidentally deleting any concurrent changes.
    # @param custom_headers [Hash{String => String}] A hash of custom headers that
    # will be added to the HTTP request.
    #
    # @return [MsRestAzure::AzureOperationResponse] HTTP response information.
    #
    def delete_with_http_info(resource_group_name, zone_name, relative_record_set_name, record_type, if_match:nil, custom_headers:nil)
      delete_async(resource_group_name, zone_name, relative_record_set_name, record_type, if_match:if_match, custom_headers:custom_headers).value!
    end

    #
    # Deletes a record set from a DNS zone. This operation cannot be undone.
    #
    # @param resource_group_name [String] The name of the resource group. The name
    # is case insensitive.
    # @param zone_name [String] The name of the DNS zone (without a terminating
    # dot).
    # @param relative_record_set_name [String] The name of the record set, relative
    # to the name of the zone.
    # @param record_type [RecordType] The type of DNS record in this record set.
    # Record sets of type SOA cannot be deleted (they are deleted when the DNS zone
    # is deleted). Possible values include: 'A', 'AAAA', 'CNAME', 'MX', 'NS',
    # 'PTR', 'SOA', 'SRV', 'TXT'
    # @param if_match [String] The etag of the record set. Omit this value to
    # always delete the current record set. Specify the last-seen etag value to
    # prevent accidentally deleting any concurrent changes.
    # @param [Hash{String => String}] A hash of custom headers that will be added
    # to the HTTP request.
    #
    # @return [Concurrent::Promise] Promise object which holds the HTTP response.
    #
    def delete_async(resource_group_name, zone_name, relative_record_set_name, record_type, if_match:nil, custom_headers:nil)
      fail ArgumentError, 'resource_group_name is nil' if resource_group_name.nil?
      fail ArgumentError, "'resource_group_name' should satisfy the constraint - 'MaxLength': '90'" if !resource_group_name.nil? && resource_group_name.length > 90
      fail ArgumentError, "'resource_group_name' should satisfy the constraint - 'MinLength': '1'" if !resource_group_name.nil? && resource_group_name.length < 1
      fail ArgumentError, "'resource_group_name' should satisfy the constraint - 'Pattern': '^[-\w\._\(\)]+$'" if !resource_group_name.nil? && resource_group_name.match(Regexp.new('^^[-\w\._\(\)]+$$')).nil?
      fail ArgumentError, 'zone_name is nil' if zone_name.nil?
      fail ArgumentError, 'relative_record_set_name is nil' if relative_record_set_name.nil?
      fail ArgumentError, 'record_type is nil' if record_type.nil?
      fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil?
      fail ArgumentError, "'@client.api_version' should satisfy the constraint - 'MinLength': '1'" if !@client.api_version.nil? && @client.api_version.length < 1
      fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil?
      fail ArgumentError, "'@client.subscription_id' should satisfy the constraint - 'MinLength': '1'" if !@client.subscription_id.nil? && @client.subscription_id.length < 1

      request_headers = {}
      request_headers['Content-Type'] = 'application/json; charset=utf-8'

      # Set Headers
      request_headers['x-ms-client-request-id'] = SecureRandom.uuid
      request_headers['If-Match'] = if_match unless if_match.nil?
      request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
      path_template = 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/{recordType}/{relativeRecordSetName}'

      request_url = @base_url || @client.base_url

      options = {
          middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
          path_params: {'resourceGroupName' => resource_group_name,'zoneName' => zone_name,'recordType' => record_type,'subscriptionId' => @client.subscription_id},
          skip_encoding_path_params: {'relativeRecordSetName' => relative_record_set_name},
          query_params: {'api-version' => @client.api_version},
          headers: request_headers.merge(custom_headers || {}),
          base_url: request_url
      }
      promise = @client.make_request_async(:delete, path_template, options)

      promise = promise.then do |result|
        http_response = result.response
        status_code = http_response.status
        response_content = http_response.body
        unless status_code == 204 || status_code == 200
          error_model = JSON.load(response_content)
          fail MsRestAzure::AzureOperationError.new(result.request, http_response, error_model)
        end

        result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?

        result
      end

      promise.execute
    end

    #
    # Gets a record set.
    #
    # @param resource_group_name [String] The name of the resource group. The name
    # is case insensitive.
    # @param zone_name [String] The name of the DNS zone (without a terminating
    # dot).
    # @param relative_record_set_name [String] The name of the record set, relative
    # to the name of the zone.
    # @param record_type [RecordType] The type of DNS record in this record set.
    # Possible values include: 'A', 'AAAA', 'CNAME', 'MX', 'NS', 'PTR', 'SOA',
    # 'SRV', 'TXT'
    # @param custom_headers [Hash{String => String}] A hash of custom headers that
    # will be added to the HTTP request.
    #
    # @return [RecordSet] operation results.
    #
    def get(resource_group_name, zone_name, relative_record_set_name, record_type, custom_headers:nil)
      response = get_async(resource_group_name, zone_name, relative_record_set_name, record_type, custom_headers:custom_headers).value!
      response.body unless response.nil?
    end

    #
    # Gets a record set.
    #
    # @param resource_group_name [String] The name of the resource group. The name
    # is case insensitive.
    # @param zone_name [String] The name of the DNS zone (without a terminating
    # dot).
    # @param relative_record_set_name [String] The name of the record set, relative
    # to the name of the zone.
    # @param record_type [RecordType] The type of DNS record in this record set.
    # Possible values include: 'A', 'AAAA', 'CNAME', 'MX', 'NS', 'PTR', 'SOA',
    # 'SRV', 'TXT'
    # @param custom_headers [Hash{String => String}] A hash of custom headers that
    # will be added to the HTTP request.
    #
    # @return [MsRestAzure::AzureOperationResponse] HTTP response information.
    #
    def get_with_http_info(resource_group_name, zone_name, relative_record_set_name, record_type, custom_headers:nil)
      get_async(resource_group_name, zone_name, relative_record_set_name, record_type, custom_headers:custom_headers).value!
    end

    #
    # Gets a record set.
    #
    # @param resource_group_name [String] The name of the resource group. The name
    # is case insensitive.
    # @param zone_name [String] The name of the DNS zone (without a terminating
    # dot).
    # @param relative_record_set_name [String] The name of the record set, relative
    # to the name of the zone.
    # @param record_type [RecordType] The type of DNS record in this record set.
    # Possible values include: 'A', 'AAAA', 'CNAME', 'MX', 'NS', 'PTR', 'SOA',
    # 'SRV', 'TXT'
    # @param [Hash{String => String}] A hash of custom headers that will be added
    # to the HTTP request.
    #
    # @return [Concurrent::Promise] Promise object which holds the HTTP response.
    #
    def get_async(resource_group_name, zone_name, relative_record_set_name, record_type, custom_headers:nil)
      fail ArgumentError, 'resource_group_name is nil' if resource_group_name.nil?
      fail ArgumentError, "'resource_group_name' should satisfy the constraint - 'MaxLength': '90'" if !resource_group_name.nil? && resource_group_name.length > 90
      fail ArgumentError, "'resource_group_name' should satisfy the constraint - 'MinLength': '1'" if !resource_group_name.nil? && resource_group_name.length < 1
      fail ArgumentError, "'resource_group_name' should satisfy the constraint - 'Pattern': '^[-\w\._\(\)]+$'" if !resource_group_name.nil? && resource_group_name.match(Regexp.new('^^[-\w\._\(\)]+$$')).nil?
      fail ArgumentError, 'zone_name is nil' if zone_name.nil?
      fail ArgumentError, 'relative_record_set_name is nil' if relative_record_set_name.nil?
      fail ArgumentError, 'record_type is nil' if record_type.nil?
      fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil?
      fail ArgumentError, "'@client.api_version' should satisfy the constraint - 'MinLength': '1'" if !@client.api_version.nil? && @client.api_version.length < 1
      fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil?
      fail ArgumentError, "'@client.subscription_id' should satisfy the constraint - 'MinLength': '1'" if !@client.subscription_id.nil? && @client.subscription_id.length < 1

      request_headers = {}
      request_headers['Content-Type'] = 'application/json; charset=utf-8'

      # Set Headers
      request_headers['x-ms-client-request-id'] = SecureRandom.uuid
      request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
      path_template = 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/{recordType}/{relativeRecordSetName}'

      request_url = @base_url || @client.base_url

      options = {
          middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
          path_params: {'resourceGroupName' => resource_group_name,'zoneName' => zone_name,'recordType' => record_type,'subscriptionId' => @client.subscription_id},
          skip_encoding_path_params: {'relativeRecordSetName' => relative_record_set_name},
          query_params: {'api-version' => @client.api_version},
          headers: request_headers.merge(custom_headers || {}),
          base_url: request_url
      }
      promise = @client.make_request_async(:get, path_template, options)

      promise = promise.then do |result|
        http_response = result.response
        status_code = http_response.status
        response_content = http_response.body
        unless status_code == 200
          error_model = JSON.load(response_content)
          fail MsRestAzure::AzureOperationError.new(result.request, http_response, error_model)
        end

        result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
        # Deserialize Response
        if status_code == 200
          begin
            parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
            result_mapper = Azure::Dns::Mgmt::V2016_04_01::Models::RecordSet.mapper()
            result.body = @client.deserialize(result_mapper, parsed_response)
          rescue Exception => e
            fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
          end
        end

        result
      end

      promise.execute
    end

    #
    # Lists the record sets of a specified type in a DNS zone.
    #
    # @param resource_group_name [String] The name of the resource group. The name
    # is case insensitive.
    # @param zone_name [String] The name of the DNS zone (without a terminating
    # dot).
    # @param record_type [RecordType] The type of record sets to enumerate.
    # Possible values include: 'A', 'AAAA', 'CNAME', 'MX', 'NS', 'PTR', 'SOA',
    # 'SRV', 'TXT'
    # @param top [Integer] The maximum number of record sets to return. If not
    # specified, returns up to 100 record sets.
    # @param recordsetnamesuffix [String] The suffix label of the record set name
    # that has to be used to filter the record set enumerations. If this parameter
    # is specified, Enumeration will return only records that end with
    # .<recordSetNameSuffix>
    # @param custom_headers [Hash{String => String}] A hash of custom headers that
    # will be added to the HTTP request.
    #
    # @return [Array<RecordSet>] operation results.
    #
    def list_by_type(resource_group_name, zone_name, record_type, top:nil, recordsetnamesuffix:nil, custom_headers:nil)
      first_page = list_by_type_as_lazy(resource_group_name, zone_name, record_type, top:top, recordsetnamesuffix:recordsetnamesuffix, custom_headers:custom_headers)
      first_page.get_all_items
    end

    #
    # Lists the record sets of a specified type in a DNS zone.
    #
    # @param resource_group_name [String] The name of the resource group. The name
    # is case insensitive.
    # @param zone_name [String] The name of the DNS zone (without a terminating
    # dot).
    # @param record_type [RecordType] The type of record sets to enumerate.
    # Possible values include: 'A', 'AAAA', 'CNAME', 'MX', 'NS', 'PTR', 'SOA',
    # 'SRV', 'TXT'
    # @param top [Integer] The maximum number of record sets to return. If not
    # specified, returns up to 100 record sets.
    # @param recordsetnamesuffix [String] The suffix label of the record set name
    # that has to be used to filter the record set enumerations. If this parameter
    # is specified, Enumeration will return only records that end with
    # .<recordSetNameSuffix>
    # @param custom_headers [Hash{String => String}] A hash of custom headers that
    # will be added to the HTTP request.
    #
    # @return [MsRestAzure::AzureOperationResponse] HTTP response information.
    #
    def list_by_type_with_http_info(resource_group_name, zone_name, record_type, top:nil, recordsetnamesuffix:nil, custom_headers:nil)
      list_by_type_async(resource_group_name, zone_name, record_type, top:top, recordsetnamesuffix:recordsetnamesuffix, custom_headers:custom_headers).value!
    end

    #
    # Lists the record sets of a specified type in a DNS zone.
    #
    # @param resource_group_name [String] The name of the resource group. The name
    # is case insensitive.
    # @param zone_name [String] The name of the DNS zone (without a terminating
    # dot).
    # @param record_type [RecordType] The type of record sets to enumerate.
    # Possible values include: 'A', 'AAAA', 'CNAME', 'MX', 'NS', 'PTR', 'SOA',
    # 'SRV', 'TXT'
    # @param top [Integer] The maximum number of record sets to return. If not
    # specified, returns up to 100 record sets.
    # @param recordsetnamesuffix [String] The suffix label of the record set name
    # that has to be used to filter the record set enumerations. If this parameter
    # is specified, Enumeration will return only records that end with
    # .<recordSetNameSuffix>
    # @param [Hash{String => String}] A hash of custom headers that will be added
    # to the HTTP request.
    #
    # @return [Concurrent::Promise] Promise object which holds the HTTP response.
    #
    def list_by_type_async(resource_group_name, zone_name, record_type, top:nil, recordsetnamesuffix:nil, custom_headers:nil)
      fail ArgumentError, 'resource_group_name is nil' if resource_group_name.nil?
      fail ArgumentError, "'resource_group_name' should satisfy the constraint - 'MaxLength': '90'" if !resource_group_name.nil? && resource_group_name.length > 90
      fail ArgumentError, "'resource_group_name' should satisfy the constraint - 'MinLength': '1'" if !resource_group_name.nil? && resource_group_name.length < 1
      fail ArgumentError, "'resource_group_name' should satisfy the constraint - 'Pattern': '^[-\w\._\(\)]+$'" if !resource_group_name.nil? && resource_group_name.match(Regexp.new('^^[-\w\._\(\)]+$$')).nil?
      fail ArgumentError, 'zone_name is nil' if zone_name.nil?
      fail ArgumentError, 'record_type is nil' if record_type.nil?
      fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil?
      fail ArgumentError, "'@client.api_version' should satisfy the constraint - 'MinLength': '1'" if !@client.api_version.nil? && @client.api_version.length < 1
      fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil?
      fail ArgumentError, "'@client.subscription_id' should satisfy the constraint - 'MinLength': '1'" if !@client.subscription_id.nil? && @client.subscription_id.length < 1

      request_headers = {}
      request_headers['Content-Type'] = 'application/json; charset=utf-8'

      # Set Headers
      request_headers['x-ms-client-request-id'] = SecureRandom.uuid
      request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
      path_template = 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/{recordType}'

      request_url = @base_url || @client.base_url

      options = {
          middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
          path_params: {'resourceGroupName' => resource_group_name,'zoneName' => zone_name,'recordType' => record_type,'subscriptionId' => @client.subscription_id},
          query_params: {'$top' => top,'$recordsetnamesuffix' => recordsetnamesuffix,'api-version' => @client.api_version},
          headers: request_headers.merge(custom_headers || {}),
          base_url: request_url
      }
      promise = @client.make_request_async(:get, path_template, options)

      promise = promise.then do |result|
        http_response = result.response
        status_code = http_response.status
        response_content = http_response.body
        unless status_code == 200
          error_model = JSON.load(response_content)
          fail MsRestAzure::AzureOperationError.new(result.request, http_response, error_model)
        end

        result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
        # Deserialize Response
        if status_code == 200
          begin
            parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
            result_mapper = Azure::Dns::Mgmt::V2016_04_01::Models::RecordSetListResult.mapper()
            result.body = @client.deserialize(result_mapper, parsed_response)
          rescue Exception => e
            fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
          end
        end

        result
      end

      promise.execute
    end

    #
    # Lists all record sets in a DNS zone.
    #
    # @param resource_group_name [String] The name of the resource group. The name
    # is case insensitive.
    # @param zone_name [String] The name of the DNS zone (without a terminating
    # dot).
    # @param top [Integer] The maximum number of record sets to return. If not
    # specified, returns up to 100 record sets.
    # @param recordsetnamesuffix [String] The suffix label of the record set name
    # that has to be used to filter the record set enumerations. If this parameter
    # is specified, Enumeration will return only records that end with
    # .<recordSetNameSuffix>
    # @param custom_headers [Hash{String => String}] A hash of custom headers that
    # will be added to the HTTP request.
    #
    # @return [Array<RecordSet>] operation results.
    #
    def list_by_dns_zone(resource_group_name, zone_name, top:nil, recordsetnamesuffix:nil, custom_headers:nil)
      first_page = list_by_dns_zone_as_lazy(resource_group_name, zone_name, top:top, recordsetnamesuffix:recordsetnamesuffix, custom_headers:custom_headers)
      first_page.get_all_items
    end

    #
    # Lists all record sets in a DNS zone.
    #
    # @param resource_group_name [String] The name of the resource group. The name
    # is case insensitive.
    # @param zone_name [String] The name of the DNS zone (without a terminating
    # dot).
    # @param top [Integer] The maximum number of record sets to return. If not
    # specified, returns up to 100 record sets.
    # @param recordsetnamesuffix [String] The suffix label of the record set name
    # that has to be used to filter the record set enumerations. If this parameter
    # is specified, Enumeration will return only records that end with
    # .<recordSetNameSuffix>
    # @param custom_headers [Hash{String => String}] A hash of custom headers that
    # will be added to the HTTP request.
    #
    # @return [MsRestAzure::AzureOperationResponse] HTTP response information.
    #
    def list_by_dns_zone_with_http_info(resource_group_name, zone_name, top:nil, recordsetnamesuffix:nil, custom_headers:nil)
      list_by_dns_zone_async(resource_group_name, zone_name, top:top, recordsetnamesuffix:recordsetnamesuffix, custom_headers:custom_headers).value!
    end

    #
    # Lists all record sets in a DNS zone.
    #
    # @param resource_group_name [String] The name of the resource group. The name
    # is case insensitive.
    # @param zone_name [String] The name of the DNS zone (without a terminating
    # dot).
    # @param top [Integer] The maximum number of record sets to return. If not
    # specified, returns up to 100 record sets.
    # @param recordsetnamesuffix [String] The suffix label of the record set name
    # that has to be used to filter the record set enumerations. If this parameter
    # is specified, Enumeration will return only records that end with
    # .<recordSetNameSuffix>
    # @param [Hash{String => String}] A hash of custom headers that will be added
    # to the HTTP request.
    #
    # @return [Concurrent::Promise] Promise object which holds the HTTP response.
    #
    def list_by_dns_zone_async(resource_group_name, zone_name, top:nil, recordsetnamesuffix:nil, custom_headers:nil)
      fail ArgumentError, 'resource_group_name is nil' if resource_group_name.nil?
      fail ArgumentError, "'resource_group_name' should satisfy the constraint - 'MaxLength': '90'" if !resource_group_name.nil? && resource_group_name.length > 90
      fail ArgumentError, "'resource_group_name' should satisfy the constraint - 'MinLength': '1'" if !resource_group_name.nil? && resource_group_name.length < 1
      fail ArgumentError, "'resource_group_name' should satisfy the constraint - 'Pattern': '^[-\w\._\(\)]+$'" if !resource_group_name.nil? && resource_group_name.match(Regexp.new('^^[-\w\._\(\)]+$$')).nil?
      fail ArgumentError, 'zone_name is nil' if zone_name.nil?
      fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil?
      fail ArgumentError, "'@client.api_version' should satisfy the constraint - 'MinLength': '1'" if !@client.api_version.nil? && @client.api_version.length < 1
      fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil?
      fail ArgumentError, "'@client.subscription_id' should satisfy the constraint - 'MinLength': '1'" if !@client.subscription_id.nil? && @client.subscription_id.length < 1

      request_headers = {}
      request_headers['Content-Type'] = 'application/json; charset=utf-8'

      # Set Headers
      request_headers['x-ms-client-request-id'] = SecureRandom.uuid
      request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
      path_template = 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/recordsets'

      request_url = @base_url || @client.base_url

      options = {
          middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
          path_params: {'resourceGroupName' => resource_group_name,'zoneName' => zone_name,'subscriptionId' => @client.subscription_id},
          query_params: {'$top' => top,'$recordsetnamesuffix' => recordsetnamesuffix,'api-version' => @client.api_version},
          headers: request_headers.merge(custom_headers || {}),
          base_url: request_url
      }
      promise = @client.make_request_async(:get, path_template, options)

      promise = promise.then do |result|
        http_response = result.response
        status_code = http_response.status
        response_content = http_response.body
        unless status_code == 200
          error_model = JSON.load(response_content)
          fail MsRestAzure::AzureOperationError.new(result.request, http_response, error_model)
        end

        result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
        # Deserialize Response
        if status_code == 200
          begin
            parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
            result_mapper = Azure::Dns::Mgmt::V2016_04_01::Models::RecordSetListResult.mapper()
            result.body = @client.deserialize(result_mapper, parsed_response)
          rescue Exception => e
            fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
          end
        end

        result
      end

      promise.execute
    end

    #
    # Lists the record sets of a specified type in a DNS zone.
    #
    # @param next_page_link [String] The NextLink from the previous successful call
    # to List operation.
    # @param custom_headers [Hash{String => String}] A hash of custom headers that
    # will be added to the HTTP request.
    #
    # @return [RecordSetListResult] operation results.
    #
    def list_by_type_next(next_page_link, custom_headers:nil)
      response = list_by_type_next_async(next_page_link, custom_headers:custom_headers).value!
      response.body unless response.nil?
    end

    #
    # Lists the record sets of a specified type in a DNS zone.
    #
    # @param next_page_link [String] The NextLink from the previous successful call
    # to List operation.
    # @param custom_headers [Hash{String => String}] A hash of custom headers that
    # will be added to the HTTP request.
    #
    # @return [MsRestAzure::AzureOperationResponse] HTTP response information.
    #
    def list_by_type_next_with_http_info(next_page_link, custom_headers:nil)
      list_by_type_next_async(next_page_link, custom_headers:custom_headers).value!
    end

    #
    # Lists the record sets of a specified type in a DNS zone.
    #
    # @param next_page_link [String] The NextLink from the previous successful call
    # to List operation.
    # @param [Hash{String => String}] A hash of custom headers that will be added
    # to the HTTP request.
    #
    # @return [Concurrent::Promise] Promise object which holds the HTTP response.
    #
    def list_by_type_next_async(next_page_link, custom_headers:nil)
      fail ArgumentError, 'next_page_link is nil' if next_page_link.nil?

      request_headers = {}
      request_headers['Content-Type'] = 'application/json; charset=utf-8'

      # Set Headers
      request_headers['x-ms-client-request-id'] = SecureRandom.uuid
      request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
      path_template = '{nextLink}'

      request_url = @base_url || @client.base_url

      options = {
          middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
          skip_encoding_path_params: {'nextLink' => next_page_link},
          headers: request_headers.merge(custom_headers || {}),
          base_url: request_url
      }
      promise = @client.make_request_async(:get, path_template, options)

      promise = promise.then do |result|
        http_response = result.response
        status_code = http_response.status
        response_content = http_response.body
        unless status_code == 200
          error_model = JSON.load(response_content)
          fail MsRestAzure::AzureOperationError.new(result.request, http_response, error_model)
        end

        result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
        # Deserialize Response
        if status_code == 200
          begin
            parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
            result_mapper = Azure::Dns::Mgmt::V2016_04_01::Models::RecordSetListResult.mapper()
            result.body = @client.deserialize(result_mapper, parsed_response)
          rescue Exception => e
            fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
          end
        end

        result
      end

      promise.execute
    end

    #
    # Lists all record sets in a DNS zone.
    #
    # @param next_page_link [String] The NextLink from the previous successful call
    # to List operation.
    # @param custom_headers [Hash{String => String}] A hash of custom headers that
    # will be added to the HTTP request.
    #
    # @return [RecordSetListResult] operation results.
    #
    def list_by_dns_zone_next(next_page_link, custom_headers:nil)
      response = list_by_dns_zone_next_async(next_page_link, custom_headers:custom_headers).value!
      response.body unless response.nil?
    end

    #
    # Lists all record sets in a DNS zone.
    #
    # @param next_page_link [String] The NextLink from the previous successful call
    # to List operation.
    # @param custom_headers [Hash{String => String}] A hash of custom headers that
    # will be added to the HTTP request.
    #
    # @return [MsRestAzure::AzureOperationResponse] HTTP response information.
    #
    def list_by_dns_zone_next_with_http_info(next_page_link, custom_headers:nil)
      list_by_dns_zone_next_async(next_page_link, custom_headers:custom_headers).value!
    end

    #
    # Lists all record sets in a DNS zone.
    #
    # @param next_page_link [String] The NextLink from the previous successful call
    # to List operation.
    # @param [Hash{String => String}] A hash of custom headers that will be added
    # to the HTTP request.
    #
    # @return [Concurrent::Promise] Promise object which holds the HTTP response.
    #
    def list_by_dns_zone_next_async(next_page_link, custom_headers:nil)
      fail ArgumentError, 'next_page_link is nil' if next_page_link.nil?

      request_headers = {}
      request_headers['Content-Type'] = 'application/json; charset=utf-8'

      # Set Headers
      request_headers['x-ms-client-request-id'] = SecureRandom.uuid
      request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
      path_template = '{nextLink}'

      request_url = @base_url || @client.base_url

      options = {
          middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
          skip_encoding_path_params: {'nextLink' => next_page_link},
          headers: request_headers.merge(custom_headers || {}),
          base_url: request_url
      }
      promise = @client.make_request_async(:get, path_template, options)

      promise = promise.then do |result|
        http_response = result.response
        status_code = http_response.status
        response_content = http_response.body
        unless status_code == 200
          error_model = JSON.load(response_content)
          fail MsRestAzure::AzureOperationError.new(result.request, http_response, error_model)
        end

        result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
        # Deserialize Response
        if status_code == 200
          begin
            parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
            result_mapper = Azure::Dns::Mgmt::V2016_04_01::Models::RecordSetListResult.mapper()
            result.body = @client.deserialize(result_mapper, parsed_response)
          rescue Exception => e
            fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
          end
        end

        result
      end

      promise.execute
    end

    #
    # Lists the record sets of a specified type in a DNS zone.
    #
    # @param resource_group_name [String] The name of the resource group. The name
    # is case insensitive.
    # @param zone_name [String] The name of the DNS zone (without a terminating
    # dot).
    # @param record_type [RecordType] The type of record sets to enumerate.
    # Possible values include: 'A', 'AAAA', 'CNAME', 'MX', 'NS', 'PTR', 'SOA',
    # 'SRV', 'TXT'
    # @param top [Integer] The maximum number of record sets to return. If not
    # specified, returns up to 100 record sets.
    # @param recordsetnamesuffix [String] The suffix label of the record set name
    # that has to be used to filter the record set enumerations. If this parameter
    # is specified, Enumeration will return only records that end with
    # .<recordSetNameSuffix>
    # @param custom_headers [Hash{String => String}] A hash of custom headers that
    # will be added to the HTTP request.
    #
    # @return [RecordSetListResult] which provide lazy access to pages of the
    # response.
    #
    def list_by_type_as_lazy(resource_group_name, zone_name, record_type, top:nil, recordsetnamesuffix:nil, custom_headers:nil)
      response = list_by_type_async(resource_group_name, zone_name, record_type, top:top, recordsetnamesuffix:recordsetnamesuffix, custom_headers:custom_headers).value!
      unless response.nil?
        page = response.body
        page.next_method = Proc.new do |next_page_link|
          list_by_type_next_async(next_page_link, custom_headers:custom_headers)
        end
        page
      end
    end

    #
    # Lists all record sets in a DNS zone.
    #
    # @param resource_group_name [String] The name of the resource group. The name
    # is case insensitive.
    # @param zone_name [String] The name of the DNS zone (without a terminating
    # dot).
    # @param top [Integer] The maximum number of record sets to return. If not
    # specified, returns up to 100 record sets.
    # @param recordsetnamesuffix [String] The suffix label of the record set name
    # that has to be used to filter the record set enumerations. If this parameter
    # is specified, Enumeration will return only records that end with
    # .<recordSetNameSuffix>
    # @param custom_headers [Hash{String => String}] A hash of custom headers that
    # will be added to the HTTP request.
    #
    # @return [RecordSetListResult] which provide lazy access to pages of the
    # response.
    #
    def list_by_dns_zone_as_lazy(resource_group_name, zone_name, top:nil, recordsetnamesuffix:nil, custom_headers:nil)
      response = list_by_dns_zone_async(resource_group_name, zone_name, top:top, recordsetnamesuffix:recordsetnamesuffix, custom_headers:custom_headers).value!
      unless response.nil?
        page = response.body
        page.next_method = Proc.new do |next_page_link|
          list_by_dns_zone_next_async(next_page_link, custom_headers:custom_headers)
        end
        page
      end
    end

  end
end


text:
Weddings & LoveStories

Lifestyle

Family

redpajama_set_name: RedPajamaGithub


text:
require 'formula'

class Pgtap < Formula
  desc "Unit testing framework for PostgreSQL"
  homepage 'http://pgtap.org/'
  url 'http://api.pgxn.org/dist/pgtap/0.94.0/pgtap-0.94.0.zip'
  sha1 '58c04a57d79345c18525ed4aee9db058964408a1'
  head 'https://github.com/theory/pgtap.git'

  # Not :postgresql, because we need to install into its share directory.
  depends_on 'postgresql'

  skip_clean 'share'

  resource 'Test::Harness' do
    url 'http://cpan.metacpan.org/authors/id/L/LE/LEONT/Test-Harness-3.30.tar.gz'
    sha1 '5f7cc2392accaf47100cf2a57c5513c3fa29b1dc'
  end

  resource 'TAP::Parser::SourceHandler::pgTAP' do
    url 'http://cpan.metacpan.org/authors/id/D/DW/DWHEELER/TAP-Parser-SourceHandler-pgTAP-3.29.tar.gz'
    sha1 '8cf6dc2ec833b896a0638390a33e2c477a58e020'
  end

  def install
    # Make sure modules can find just-installed dependencies.
    arch  = %x(perl -MConfig -E 'print $Config{archname}')
    plib  = "#{lib}/perl5"
    ENV['PERL5LIB'] = "#{plib}:#{plib}/#{arch}:#{lib}:#{lib}/#{arch}"

    resource('Test::Harness').stage do
      system 'perl', 'Makefile.PL', "INSTALL_BASE=#{prefix}",
             "INSTALLSITEMAN1DIR=#{man1}", "INSTALLSITEMAN3DIR=#{man3}"
      system 'make'
      system 'make', 'install'
    end

    resource('TAP::Parser::SourceHandler::pgTAP').stage do
      system 'perl', 'Build.PL', "--install_base", prefix, '--install_path',
             "bindoc=#{man1}", '--install_path', "libdoc=#{man3}"
      system './Build'
      system './Build', 'install'
    end

    pg_config = "#{Formula["postgresql"].opt_bin}/pg_config"
    system "make", "PG_CONFIG=#{pg_config}"
    system "make", "PG_CONFIG=#{pg_config}", "install"
  end
end


text:
package units_generator.schema_validator.exceptions;

public class InvalidUnitTypeCount extends InvalidSchema {

	/**
	 *
	 */
	private static final long serialVersionUID = 3880236362226475719L;

	public InvalidUnitTypeCount(String unitTypeName, long count, String context) {
		super("\"" + unitTypeName + "\" unit type found " + count
				+ " times in schema, but there should be exactly one", context);
	}
}


text:
#include <stdio.h>
#include <stdlib.h>
#include <glib.h>
#include <glib/gstdio.h>

/* Represents a word-frequency pair. */
typedef struct {
    gint freq;
    gchar *word;
} Pair;

/* Compares two key-value pairs by frequency. */
gint compare_pair (gpointer v1, gpointer v2, gpointer user_data)
{
    Pair *p1 = (Pair *) v1;
    Pair *p2 = (Pair *) v2;
    return p1->freq - p2->freq;
}

/* Iterator that prints pairs. */
void pair_printor (gpointer value, gpointer user_data)
{
    Pair *pair = (Pair *) value;
    printf ("%d\t %s\n", pair->freq, pair->word);
}

/* Iterator that prints keys and values. */
void printor (gpointer key, gpointer value, gpointer user_data)
{
    printf (user_data, key, * (gint *) value);
}

/* Iterator that add key-value pairs to a sequence. */
void accumulator (gpointer key, gpointer value, gpointer user_data)
{
    GSequence *seq = (GSequence *) user_data;
    Pair *pair = g_new(Pair, 1);
    pair->word = (gchar *) key;
    pair->freq = * (gint *) value;

    g_sequence_insert_sorted (seq,
			      (gpointer) pair,
			      (GCompareDataFunc) compare_pair,
			      NULL);
}

/* Increments the frequency associated with key. */
void incr (GHashTable* hash, gchar *key)
{
    gint *val = (gint *) g_hash_table_lookup (hash, key);

    if (val == NULL) {
	gint *val1 = g_new (gint, 1);
	*val1 = 1;
	g_hash_table_insert (hash, key, val1);
    } else {
	*val += 1;
    }
}

void free_hash(gpointer key, gpointer value, gpointer user_data)
{
    //g_free(key); //somehow the keys and the array are interconnected
    g_free(value);
}

void free_seq (gpointer value, gpointer user_data)
{
    g_free((Pair *) value);
}

int main (int argc, char** argv)
{
    gchar *filename;

    // open the file
    if (argc > 1) {
	filename = argv[1];
    } else {
	filename = "emma.txt";
    }

    FILE *fp = g_fopen(filename, "r");
    if (fp == NULL) {
	perror (filename);
	exit (-10);
    }

    /* string array is a (two-L) NULL terminated array of pointers to
       (one-L) NUL terminated strings */
    gchar **array;
    gchar line[128];
    GHashTable* hash = g_hash_table_new(g_str_hash, g_str_equal);
    int i;

    // read lines from the file and build the hash table
    while (1) {
	gchar *res = fgets (line, sizeof(line), fp);
	if (res == NULL) break;

	array = g_strsplit(line, " ", 0);
	for (i=0; array[i] != NULL; i++) {
	    incr(hash, array[i]);
	}
    g_strfreev(array);//free the array after each line not sure how this is causing the IVR errors
    //must be through its interaction with key...???
    }

    fclose (fp);

    // print the hash table
    // g_hash_table_foreach (hash,  (GHFunc) printor, "Word %s freq %d\n");

    // iterate the hash table and build the sequence
    GSequence *seq = g_sequence_new (NULL);
    g_hash_table_foreach (hash,  (GHFunc) accumulator, (gpointer) seq);

    // iterate the sequence and print the pairs
    g_sequence_foreach (seq,  (GFunc) pair_printor, NULL);

    g_hash_table_foreach(hash, (GHFunc) free_hash, NULL);//iterate through hash table and call free_hash on each
    g_sequence_foreach(seq, (GFunc) free_seq, NULL);//iterate through sequence and free each
    g_hash_table_destroy (hash);
    g_sequence_free (seq);
    return 0;
}

//does not leak any memory, however there is something funky going on where
//the program is trying to read something after it has been freed.


text:
@interface ChooseCommodityCell : UITableViewCell
@property (nonatomic, strong) PropertyChoose *propertyChoose;
@property (nonatomic, strong) UIButton *delBtn;
+ (instancetype)cellWithTableView:(UITableView *)tableView;
@end


text: Small javascript experiment


text:
'use strict';

const fs = require('fs');
const path = require('path');
const {spawn} = require('child_process');

const AWS = require('aws-sdk');
const copyDir = require('copy-dir');
const del = require('del');
const globby = require('globby');
const gulp = require('gulp');
const replace = require('gulp-replace');

const {version} = require('./package.json');

const kitPattern = './src/kits/*.js';

const shell = async (command, dir = './') => {
    const p = path.join('/', dir);
    console.log(`\x1b[33m${p}\x1b[0m$ ${command}`);
    const [, cmd, args] = (/^(\w+)\s*([^]*)/g).exec(command);
    return new Promise((resolve, reject) => {
        let child = spawn(cmd, args.split(' '), {
            cwd: dir,
        });
        child.stdout.on('data', (data) => {
            console.log(`${data} `.trim());
        });
        child.stderr.on('data', (data) => {
            if (String(data).match(/error/g)) {
                console.log(`\x1b[31m${data}\x1b[0m`);
            }
        });
        child.on('error', reject);
        child.on('exit', resolve);
    });
};

// copy ./src/kits/ to ./
gulp.task('prepublish', () => {
    gulp.src(globby.sync([kitPattern]))
        // makes sure require statements still work correctly
        .pipe(replace(
            'require(\'.',
            'require(\'./src/kits/.'))
        .pipe(gulp.dest('./'));
});

gulp.task('clean', () => {
    // finds the path of all js files at the top level which have the same
    // name as the kits found in ./src/kits/
    const kits = globby.sync([kitPattern])
        .map((path) => path.replace(/.+?(\w+\.js)$/g, '$1'));

    return del([
        ...kits,
        './dist',
        './coverage',
        './npm-debug.log',
        './package-lock.json',
    ]);
});

// push new version to github.com/okwolo/dl
gulp.task('push', async () => {
    if (!fs.existsSync('./dist')) {
        console.log('err: ./dist does not exist');
    }
    await shell('rm -rf ./dl');
    await shell('git clone https://github.com/okwolo/dl');
    // also copies gzipped versions to root to have access to size
    copyDir.sync('./dist', './dl');
    const dir = `./dl/${version}`;
    if (!fs.existsSync(dir)) {
        console.log('creating', dir);
        fs.mkdirSync(dir);
    }
    copyDir.sync('./dist', `./dl/${version}`, (stat, p) => {
        return path.extname(p) === '.js';
    });
    await shell('git add --all', './dl');
    await shell(`git commit -m v${version}`, './dl');
    await shell('git push origin master', './dl');
    await shell('rm -rf ./dl');
});

// upload new published version to website
gulp.task('publish', async () => {
    if (!fs.existsSync('secret.json')) {
        console.error('couldn\'t read config file (secret.json)');
        return;
    }

    AWS.config.loadFromPath('secret.json');

    const s3 = new AWS.S3({
        apiVersion: '2018-1-1',
        params: {
            Bucket: 'aws-dl-okwolo-cr5ts',
        },
    });

    const kitNames = globby.sync([kitPattern])
        .map((path) => path.replace(/.+?(\w+)\.js$/g, '$1'));

    const files = [];
    kitNames.forEach((kit) => {
        const bundle = fs.readFileSync(`./dist/${kit}.js`, 'utf8');
        const bundleMin = fs.readFileSync(`./dist/${kit}.min.js`, 'utf8');

        files.push({
            content: bundle,
            path: `${kit}.js`,
        });
        files.push({
            content: bundleMin,
            path: `${kit}.min.js`,
        });

        files.push({
            content: bundle,
            path: `${version}/${kit}.js`,
        });
        files.push({
            content: bundleMin,
            path: `${version}/${kit}.min.js`,
        });
    });

    return Promise.all(files.map(({content, path}) => {
        return new Promise((resolve, reject) => {
            s3.upload({
                Key: path,
                Body: content,
                ContentEncoding: 'utf8',
                ContentType: 'application/javascript',
                ACL: 'public-read',
            }, (err, data) => {
                if (err) {
                    console.error(`error uploading ${path}`);
                    reject(err);
                }
                console.log(`uploaded ${path}`);
                resolve(data);
            });
        });
    }));
});


text:
package org.eugene.service.prime.generic;

import org.eugene.service.prime.PrimeChecker;

public class GenericPrimeChecker implements PrimeChecker {

    public static final String PROVIDER_NAME = "eugene.generic.primechecker";

    @Override
    public String getName() {
        return PROVIDER_NAME;
    }

    @Override
    public boolean isPrime(long n) {
        if (n <= 1) {
            return false;
        }
        if (n <= 2) {
            return true;
        }
        if (n % 2 == 0) {
            return false;
        }
        for (long i = 3; i < n; i++) {
            if (n % i == 0) {
                return false;
            }
        }
        return true;
    }
}


text:
import {AppStateService} from "../providers/app-state/app-state.service";
import {ConfirmPage, PlatformStateService, RegistrationPage, RegStateKey, RegStateService,} from "front-end-common";
import {Component, ViewChild} from "@angular/core";
import {Nav, Platform} from "ionic-angular";
import {HomePage} from "../pages/home/home";
import {LocEditPage} from "../pages/loc-edit/loc-edit";
import {LocTypeListPage} from "../pages/loc-type-list/loc-type-list";
import {StatusBar} from "@ionic-native/status-bar";
import {StatusPage} from "../pages/status/status";
import {filter, find} from "rxjs/operators";

@Component({
  templateUrl: 'app.html'
})
export class MyApp {
  @ViewChild(Nav) nav: Nav;

  rootPage: any;

  pages: Array<{title: string, component: any}>;

  constructor(
    public platform: Platform,
    public statusBar: StatusBar,
    public appStateService: AppStateService,
    public platformStateService: PlatformStateService,
    private regStateService: RegStateService,
  ) {

    console.log("App is constructing");

    /** Populates the Menu. */
    this.pages = [
      { title: 'Map', component: HomePage },
      { title: 'Loc Types', component: LocTypeListPage },
      { title: 'Edit', component: LocEditPage },
      { title: 'Status', component: StatusPage },
    ];

  }

  initializeApp() {
    this.platform.ready().then(() => {
      console.log("Platform ready");

      // Okay, so the platform is ready and our plugins are available.
      // Here you can do any higher level native things you might need.
      if (this.platformStateService.isNativeMode()) {
        /* Since this is a cordova native statusbar, only set style if not within a browser (local). */
        this.statusBar.styleDefault();
      }

      this.setupRegStateResponse();
    });
  };

  /**
   * Triggers the check of a Registration State to make sure our Access Token is ready.
   *
   * If registration/confirmation are required, we provide the pages from within our navigation scheme;
   * those pages will feed back into changes of the Registration State that we pick up via the stream.
   */
  private setupRegStateResponse(): void {

    const regStateObservable = this.regStateService.requestRegState(
      "com.clueride.mobiloc"
    );

    /* Handle Registration -- generally, a one-time occurrence, but there are re-tries. */
    regStateObservable.pipe(
      filter(regState => regState.state === RegStateKey.REGISTRATION_REQUIRED)
    ).subscribe(regState => {
      console.log("We need to show the Registration Page");
      this.nav.setRoot(RegistrationPage)
        .then()
        .catch(error => console.error("Did not get Registration Page", error));
    });

    /* Handle Profile Confirmation -- generally, a one-time occurrence, but there are re-tries. */
    regStateObservable.pipe(
      filter(regState => regState.state === RegStateKey.CONFIRMATION_REQUIRED)
    ).subscribe( regState => {
        console.log("We need to show the Confirmation Page");
        this.nav.setRoot(ConfirmPage)
          .then()
          .catch(error => console.error("Did not get Registration Page", error));
      }
    );

    /* Handle Active Session -- typical case. */
    regStateObservable.pipe(
      find(regState => regState.state === RegStateKey.ACTIVE)
    ).subscribe(regState => {
        console.log("Active by the grace of", regState.source );

        /* Proceed with the application. */
        this.appStateService.registrationIsNowActive();
      }
    );

  }

  /** This is how the Menu is able to change pages. */
  openPage(page) {
    // Reset the content nav to have just this page
    // we wouldn't want the back button to show in this scenario
    this.nav.setRoot(page.component);
  }

  ngOnInit() {
    this.initializeApp();
    console.log("App is initialized");
  }

}


text:
namespace scheduler {

class MockObserver : public TaskQueueSelector::Observer {
 public:
  MockObserver() {}
  virtual ~MockObserver() {}

  MOCK_METHOD0(OnTaskQueueEnabled, void());

 private:
  DISALLOW_COPY_AND_ASSIGN(MockObserver);
};

class PrioritizingTaskQueueSelectorForTest
    : public PrioritizingTaskQueueSelector {
 public:
  PrioritizingTaskQueueSelectorForTest() {}
  ~PrioritizingTaskQueueSelectorForTest() override {}

  using PrioritizingTaskQueueSelector::DisableQueueInternal;
};

class PrioritizingTaskQueueSelectorTest : public testing::Test {
 public:
  PrioritizingTaskQueueSelectorTest()
      : test_closure_(
            base::Bind(&PrioritizingTaskQueueSelectorTest::TestFunction)) {}
  ~PrioritizingTaskQueueSelectorTest() override {}

  std::vector<base::PendingTask> GetTasks(int count) {
    std::vector<base::PendingTask> tasks;
    for (int i = 0; i < count; i++) {
      base::PendingTask task = base::PendingTask(FROM_HERE, test_closure_);
      task.sequence_num = i;
      tasks.push_back(task);
    }
    return tasks;
  }

  void PushTasks(const std::vector<base::PendingTask>& tasks,
                 const size_t queue_indices[]) {
    for (size_t i = 0; i < tasks.size(); i++) {
      task_queues_[queue_indices[i]]->push(tasks[i]);
    }
  }

  std::vector<size_t> PopTasks() {
    std::vector<size_t> order;
    size_t chosen_queue_index;
    while (selector_.SelectWorkQueueToService(&chosen_queue_index)) {
      order.push_back(chosen_queue_index);
      task_queues_[chosen_queue_index]->pop();
    }
    return order;
  }

  static void TestFunction() {}

 protected:
  void SetUp() final {
    std::vector<const base::TaskQueue*> const_task_queues;
    for (size_t i = 0; i < kTaskQueueCount; i++) {
      scoped_ptr<base::TaskQueue> task_queue(new base::TaskQueue());
      const_task_queues.push_back(task_queue.get());
      task_queues_.push_back(task_queue.release());
    }
    selector_.RegisterWorkQueues(const_task_queues);
    for (size_t i = 0; i < kTaskQueueCount; i++)
      EXPECT_TRUE(selector_.IsQueueEnabled(i)) << i;
  }

  const size_t kTaskQueueCount = 5;
  base::Closure test_closure_;
  PrioritizingTaskQueueSelectorForTest selector_;
  ScopedVector<base::TaskQueue> task_queues_;
};

TEST_F(PrioritizingTaskQueueSelectorTest, TestDefaultPriority) {
  std::vector<base::PendingTask> tasks = GetTasks(5);
  size_t queue_order[] = {4, 3, 2, 1, 0};
  PushTasks(tasks, queue_order);
  EXPECT_THAT(PopTasks(), testing::ElementsAre(4, 3, 2, 1, 0));
}

TEST_F(PrioritizingTaskQueueSelectorTest, TestHighPriority) {
  std::vector<base::PendingTask> tasks = GetTasks(5);
  size_t queue_order[] = {0, 1, 2, 3, 4};
  PushTasks(tasks, queue_order);
  selector_.SetQueuePriority(2, PrioritizingTaskQueueSelector::HIGH_PRIORITY);
  EXPECT_THAT(PopTasks(), testing::ElementsAre(2, 0, 1, 3, 4));
}

TEST_F(PrioritizingTaskQueueSelectorTest, TestBestEffortPriority) {
  std::vector<base::PendingTask> tasks = GetTasks(5);
  size_t queue_order[] = {0, 1, 2, 3, 4};
  PushTasks(tasks, queue_order);
  selector_.SetQueuePriority(
      0, PrioritizingTaskQueueSelector::BEST_EFFORT_PRIORITY);
  selector_.SetQueuePriority(2, PrioritizingTaskQueueSelector::HIGH_PRIORITY);
  EXPECT_THAT(PopTasks(), testing::ElementsAre(2, 1, 3, 4, 0));
}

TEST_F(PrioritizingTaskQueueSelectorTest, TestControlPriority) {
  std::vector<base::PendingTask> tasks = GetTasks(5);
  size_t queue_order[] = {0, 1, 2, 3, 4};
  PushTasks(tasks, queue_order);
  selector_.SetQueuePriority(4,
                             PrioritizingTaskQueueSelector::CONTROL_PRIORITY);
  EXPECT_TRUE(selector_.IsQueueEnabled(4));
  selector_.SetQueuePriority(2, PrioritizingTaskQueueSelector::HIGH_PRIORITY);
  EXPECT_TRUE(selector_.IsQueueEnabled(2));
  EXPECT_THAT(PopTasks(), testing::ElementsAre(4, 2, 0, 1, 3));
}

TEST_F(PrioritizingTaskQueueSelectorTest,
       TestDisableReturnsTrueIfQueueWasEnabled) {
  selector_.EnableQueue(1, PrioritizingTaskQueueSelector::NORMAL_PRIORITY);
  EXPECT_TRUE(selector_.DisableQueueInternal(1));
}

TEST_F(PrioritizingTaskQueueSelectorTest,
       TestDisableReturnsFalseIfQueueWasAlreadyDisabled) {
  selector_.DisableQueue(1);
  EXPECT_FALSE(selector_.DisableQueueInternal(1));
}

TEST_F(PrioritizingTaskQueueSelectorTest, TestDisableEnable) {
  MockObserver mock_observer;
  selector_.SetTaskQueueSelectorObserver(&mock_observer);

  std::vector<base::PendingTask> tasks = GetTasks(5);
  size_t queue_order[] = {0, 1, 2, 3, 4};
  PushTasks(tasks, queue_order);
  selector_.DisableQueue(2);
  EXPECT_FALSE(selector_.IsQueueEnabled(2));
  selector_.DisableQueue(4);
  EXPECT_FALSE(selector_.IsQueueEnabled(4));
  EXPECT_THAT(PopTasks(), testing::ElementsAre(0, 1, 3));

  EXPECT_CALL(mock_observer, OnTaskQueueEnabled()).Times(2);
  selector_.EnableQueue(2, PrioritizingTaskQueueSelector::BEST_EFFORT_PRIORITY);
  EXPECT_THAT(PopTasks(), testing::ElementsAre(2));
  selector_.EnableQueue(4, PrioritizingTaskQueueSelector::NORMAL_PRIORITY);
  EXPECT_THAT(PopTasks(), testing::ElementsAre(4));
}

TEST_F(PrioritizingTaskQueueSelectorTest, TestEmptyQueues) {
  size_t chosen_queue_index = 0;
  EXPECT_FALSE(selector_.SelectWorkQueueToService(&chosen_queue_index));

  // Test only disabled queues.
  std::vector<base::PendingTask> tasks = GetTasks(1);
  size_t queue_order[] = {0};
  PushTasks(tasks, queue_order);
  selector_.DisableQueue(0);
  EXPECT_FALSE(selector_.IsQueueEnabled(0));
  EXPECT_FALSE(selector_.SelectWorkQueueToService(&chosen_queue_index));
}

TEST_F(PrioritizingTaskQueueSelectorTest, TestDelay) {
  std::vector<base::PendingTask> tasks = GetTasks(5);
  tasks[0].delayed_run_time =
      base::TimeTicks() + base::TimeDelta::FromMilliseconds(200);
  tasks[3].delayed_run_time =
      base::TimeTicks() + base::TimeDelta::FromMilliseconds(100);
  size_t queue_order[] = {0, 1, 2, 3, 4};
  PushTasks(tasks, queue_order);
  EXPECT_THAT(PopTasks(), testing::ElementsAre(1, 2, 4, 3, 0));
}

TEST_F(PrioritizingTaskQueueSelectorTest, TestControlStarvesOthers) {
  std::vector<base::PendingTask> tasks = GetTasks(4);
  size_t queue_order[] = {0, 1, 2, 3};
  PushTasks(tasks, queue_order);
  selector_.SetQueuePriority(3,
                             PrioritizingTaskQueueSelector::CONTROL_PRIORITY);
  selector_.SetQueuePriority(2, PrioritizingTaskQueueSelector::HIGH_PRIORITY);
  selector_.SetQueuePriority(
      1, PrioritizingTaskQueueSelector::BEST_EFFORT_PRIORITY);
  for (int i = 0; i < 100; i++) {
    size_t chosen_queue_index = 0;
    EXPECT_TRUE(selector_.SelectWorkQueueToService(&chosen_queue_index));
    EXPECT_EQ(3ul, chosen_queue_index);
    // Don't remove task from queue to simulate all queues still being full.
  }
}

TEST_F(PrioritizingTaskQueueSelectorTest, TestHighPriorityDoesNotStarveNormal) {
  std::vector<base::PendingTask> tasks = GetTasks(3);
  size_t queue_order[] = {0, 1, 2};
  PushTasks(tasks, queue_order);
  selector_.SetQueuePriority(2, PrioritizingTaskQueueSelector::HIGH_PRIORITY);
  selector_.SetQueuePriority(
      1, PrioritizingTaskQueueSelector::BEST_EFFORT_PRIORITY);
  size_t counts[] = {0, 0, 0};
  for (int i = 0; i < 100; i++) {
    size_t chosen_queue_index = 0;
    EXPECT_TRUE(selector_.SelectWorkQueueToService(&chosen_queue_index));
    counts[chosen_queue_index]++;
    // Don't remove task from queue to simulate all queues still being full.
  }
  EXPECT_GT(counts[0], 0ul);        // Check high doesn't starve normal.
  EXPECT_GT(counts[2], counts[0]);  // Check high gets more chance to run.
  EXPECT_EQ(0ul, counts[1]);        // Check best effort is starved.
}

TEST_F(PrioritizingTaskQueueSelectorTest, TestBestEffortGetsStarved) {
  std::vector<base::PendingTask> tasks = GetTasks(2);
  size_t queue_order[] = {0, 1};
  PushTasks(tasks, queue_order);
  selector_.SetQueuePriority(
      0, PrioritizingTaskQueueSelector::BEST_EFFORT_PRIORITY);
  selector_.SetQueuePriority(1, PrioritizingTaskQueueSelector::NORMAL_PRIORITY);
  size_t chosen_queue_index = 0;
  for (int i = 0; i < 100; i++) {
    EXPECT_TRUE(selector_.SelectWorkQueueToService(&chosen_queue_index));
    EXPECT_EQ(1ul, chosen_queue_index);
    // Don't remove task from queue to simulate all queues still being full.
  }
  selector_.SetQueuePriority(1, PrioritizingTaskQueueSelector::HIGH_PRIORITY);
  for (int i = 0; i < 100; i++) {
    EXPECT_TRUE(selector_.SelectWorkQueueToService(&chosen_queue_index));
    EXPECT_EQ(1ul, chosen_queue_index);
    // Don't remove task from queue to simulate all queues still being full.
  }
  selector_.SetQueuePriority(1,
                             PrioritizingTaskQueueSelector::CONTROL_PRIORITY);
  for (int i = 0; i < 100; i++) {
    EXPECT_TRUE(selector_.SelectWorkQueueToService(&chosen_queue_index));
    EXPECT_EQ(1ul, chosen_queue_index);
    // Don't remove task from queue to simulate all queues still being full.
  }
}

}  // namespace scheduler


text:
This repository contains training code for the examples in the SIGGRAPH Asia 2020 paper "[Layered Neural Rendering for Retiming People in Video](https://retiming.github.io/)."

<img src='./img/teaser.gif' height="160px"/>

This is not an officially supported Google product.

## Prerequisites
- Linux
- Python 3.6+
- NVIDIA GPU + CUDA CuDNN

## Installation
This code has been tested with PyTorch 1.4 and Python 3.8.

- Install [PyTorch](http://pytorch.org) 1.4 and other dependencies.
  - For pip users, please type the command `pip install -r requirements.txt`.
  - For Conda users, you can create a new Conda environment using `conda env create -f environment.yml`.

## Data Processing
- Download the data for a video used in our paper (e.g. "reflection"):
```bash
bash ./datasets/download_data.sh reflection
```
- Or alternatively, download all the data by specifying `all`.
- Download the pretrained keypoint-to-UV model weights:
```bash
bash ./scripts/download_kp2uv_model.sh
```
The pretrained model will be saved at `./checkpoints/kp2uv/latest_net_Kp2uv.pth`.
- Generate the UV maps from the keypoints:
```bash
bash datasets/prepare_iuv.sh ./datasets/reflection
```
## Training
- To train a model on a video (e.g. "reflection"), run:
```bash
python train.py --name reflection --dataroot ./datasets/reflection --gpu_ids 0,1
```
- To view training results and loss plots, visit the URL http://localhost:8097.
Intermediate results are also at `./checkpoints/reflection/web/index.html`.

You can find more scripts in the `scripts` directory, e.g. `run_${VIDEO}.sh` which combines data processing, training, and saving layer results for a video.

**Note**:
- It is recommended to use >=2 GPUs, each with >=16GB memory.
- The training script first trains the low-resolution model for `--num_epochs` at `--batch_size`, and then trains the upsampling module for `--num_epochs_upsample` at `--batch_size_upsample`.
If you do not need the upsampled result, pass `--num_epochs_upsample 0`.
- Training the upsampling module requires ~2.5x memory as the low-resolution model, so set `batch_size_upsample` accordingly.
The provided scripts set the batch sizes appropriately for 2 GPUs with 16GB memory.
- GPU memory scales linearly with the number of layers.

## Saving layer results from a trained model
- Run the trained model:
```bash
python test.py --name reflection --dataroot ./datasets/reflection --do_upsampling
```
- The results (RGBA layers, videos) will be saved to `./results/reflection/test_latest/`.
- Passing `--do_upsampling` uses the results of the upsampling module. If the upsampling module hasn't been trained (`num_epochs_upsample=0`), then remove this flag.

## Custom video
To train on your own video, you will have to preprocess the data:
1. Extract the frames, e.g.
    ```
    mkdir ./datasets/my_video && cd ./datasets/my_video
    mkdir rgb && ffmpeg -i video.mp4 rgb/%04d.png
    ```
1. Resize the video to 256x448 and save the frames in `my_video/rgb_256`, and resize the video to 512x896 and save in `my_video/rgb_512`.
1. Run [AlphaPose and Pose Tracking](https://github.com/MVIG-SJTU/AlphaPose) on the frames. Save results as `my_video/keypoints.json`
1. Create `my_video/metadata.json` following [these instructions](docs/data.md).
1. If your video has camera motion, either (1) stabilize the video, or (2) maintain the camera motion by computing homographies and saving as `my_video/homographies.txt`.
See `scripts/run_cartwheel.sh` for a training example with camera motion, and see `./datasets/cartwheel/homographies.txt` for formatting.

**Note**: Videos that are suitable for our method have the following attributes:
- Static camera or limited camera motion that can be represented with a homography.
- Limited number of people, due to GPU memory limitations. We tested up to 7 people and 7 layers.
Multiple people can be grouped onto the same layer, though they cannot be individually retimed.
- People that move relative to the background (static people will be absorbed into the background layer).
- We tested a video length of up to 200 frames (~7 seconds).

## Citation
If you use this code for your research, please cite the following paper:
```
@inproceedings{lu2020,
  title={Layered Neural Rendering for Retiming People in Video},
  author={Lu, Erika and Cole, Forrester and Dekel, Tali and Xie, Weidi and Zisserman, Andrew and Salesin, David and Freeman, William T and Rubinstein, Michael},
  booktitle={SIGGRAPH Asia},
  year={2020}
}
```

## Acknowledgments
This code is based on [pytorch-CycleGAN-and-pix2pix](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix).


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Beitr. Kenntn. Pilze Mitteleur. 3: 120 (1987)

#### Original name
Lyophyllum raphanolens Romagn.

### Remarks
null


text:
sudo apt-get update
sudo curl -fsSL https://test.docker.com/ | sh

sudo docker swarm init --listen-addr 192.168.77.120:2377
sudo usermod -aG docker vagrant

# Setup the private pluralsight registry
echo "192.168.77.110  registry.swarm.dev" >> /etc/hosts

export DOCKER_REPO=registry.swarm.dev:5000
mkdir -p /etc/docker/certs.d/$DOCKER_REPO
cp /vagrant/ca.crt /etc/docker/certs.d/$DOCKER_REPO/ca.crt

curl -L https://github.com/docker/compose/releases/download/1.8.0-rc1/docker-compose-`uname -s`-`uname -m` > /usr/local/bin/docker-compose
chmod +x /usr/local/bin/docker-compose


text:
//*jshint parameters*
/*jshint curly:true, eqeqeq:true, strict:true, boss:true, laxcomma:true */

(function (attach) {
    'use strict';

    // - - -
    // # yEnc
    // ** A minimal yEnc [en|de]coder **
    var yEnc = function () {
        // ##### Private Variables
        var
            self = {}
            , reserved = [0, 10, 13, 61]
            ;

        // ##### Public Variables

        // ##### Private Methods

        // #### each()
        // >`@param obj [collection]` our source collection
        // >`@param iterator [function]` the function that will be called for each element in the collection
        // >`@param context [object]` the context our iterator should operate within
        //
        // essentially copied from underscore.js
        var each = function (obj, iterator, context) {
            var breaker = {};
            if (obj === null) {
                return;
            }
            if (Array.prototype.forEach && obj.forEach === Array.prototype.forEach) {
                obj.forEach(iterator, context);
            } else if (obj.length === +obj.length) {
                for (var i = 0, l = obj.length; i < l; i++) {
                    if (iterator.call(context, obj[i], i, obj) === breaker) {
                        return;
                    }
                }
            } else {
                for (var key in obj) {
                    if (obj.hasOwnProperty(key)) {
                        if (iterator.call(context, obj[key], key, obj) === breaker) {
                            return;
                        }
                    }
                }
            }
        };

        // #### toBytes()
        // >`@param source [array]` our source UTF-8 string
        //
        // toBytes takes a UTF8 string and returns an array of bytes (as integers)
        var toBytes = function (source) {
            var
                output = []
                , i = 0
                , j = 0
                , subchar
                ;
            for (; i < source.length; i++) {
                if (source.charCodeAt(i) <= 0x7F) {
                    output.push(source.charCodeAt(i));
                } else {
                    subchar = encodeURIComponent(source.charAt(i)).substr(1).split('%');
                    for (j = 0; j < subchar.length; j++) {
                        output.push(parseInt(subchar[j], 16));
                    }
                }
            }
            return output;
        };

        // #### fromBytes()
        // >`@param source [array]` our source array of integers
        //
        // fromBytes turns an array of bytes (as integers) into a UTF8 string
        var fromBytes = function (source) {
            var
                output = ''
                , i = 0
                ;

            for (; i < source.length; i++) {
                if (source[i] <= 127) {
                    if (source[i] === 37) {
                        output += "%25";
                    } else {
                        output += String.fromCharCode(source[i]);
                    }
                } else {
                    output += "%" + source[i].toString(16).toUpperCase();
                }
            }
            return decodeURIComponent(output);
        };

        // ##### Public Methods

        // #### yEnc.encode()
        // >`@param source [string]` the source string we will be encoding
        //
        // This is our encoding method for taking a text string and encoding it into the yEnc
        // format, the output string is a UTF-8 string
        self.encode = function (source) {
            var
                output = ''
                , bytes = []
                , converted
                ;

            bytes = toBytes(source);
            each(bytes, function (ele, i) {
                converted = (ele + 42) % 256;
                if (reserved.indexOf(converted) < 0) {
                    output += String.fromCharCode(converted);
                } else {
                    converted = (converted + 64) % 256;
                    output += "=" + String.fromCharCode(converted);
                }
            });

            return output;
        };

        // #### yEnc.decode()
        // >`@param source [string]` the source string we will be decoding
        //
        // This is our encoding method for taking a UTF-8 text string and decoding it into
        // the original text string
        self.decode = function (source) {
            var
                output = []
                , ck = false
                , bytes = []
                , i = 0
                , c
                ;

            for (i = 0; i < source.length; i++) {
                c = source.charCodeAt(i);
                // ignore newlines
                if (c === 13 || c === 10) {
                    continue;
                }
                // if we're an "=" and we haven't been flagged, set flag
                if (c === 61 && !ck) {
                    ck = true;
                    continue;
                }
                if (ck) {
                    ck = false;
                    c = c - 64;
                }
                if (c < 42 && c > 0) {
                    output.push(c + 214);
                } else {
                    output.push(c - 42);
                }
            }

            return fromBytes(output);
        };

        return self;
    }();

    // *exports for various module managers*
    if (typeof define !== 'undefined' && define.amd) {
        // require.js/amd
        define([], function () {
            return yEnc;
        });
    } else if (typeof module !== 'undefined' && module.exports) {
        // node.js
        module.exports = yEnc;
    } else if (attach !== undefined) {
        // user provided attachment
        attach.yEnc = yEnc;
    } else {
        // browser global
        this.yEnc = yEnc;
    }
})();


text:
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>49.0</apiVersion>
    <description>Util Prompt</description>
    <isExposed>false</isExposed>
    <masterLabel>Util Prompt</masterLabel>
</LightningComponentBundle>


text:
class PrefService;

namespace base {

class FilePath;
class SequencedTaskRunner;

// A class that allows convenient building of PrefService.
class BASE_PREFS_EXPORT PrefServiceFactory {
 public:
  PrefServiceFactory();
  virtual ~PrefServiceFactory();

  // Functions for setting the various parameters of the PrefService to build.
  void set_managed_prefs(const scoped_refptr<PrefStore>& managed_prefs) {
    managed_prefs_ = managed_prefs;
  }
  void set_supervised_user_prefs(
      const scoped_refptr<PrefStore>& supervised_user_prefs) {
    supervised_user_prefs_ = supervised_user_prefs;
  }
  void set_extension_prefs(const scoped_refptr<PrefStore>& extension_prefs) {
    extension_prefs_ = extension_prefs;
  }
  void set_command_line_prefs(
      const scoped_refptr<PrefStore>& command_line_prefs) {
    command_line_prefs_ = command_line_prefs;
  }
  void set_user_prefs(const scoped_refptr<PersistentPrefStore>& user_prefs) {
    user_prefs_ = user_prefs;
  }
  void set_recommended_prefs(
      const scoped_refptr<PrefStore>& recommended_prefs) {
    recommended_prefs_ = recommended_prefs;
  }

  // Sets up error callback for the PrefService.  A do-nothing default
  // is provided if this is not called.
  void set_read_error_callback(
      const base::Callback<void(PersistentPrefStore::PrefReadError)>&
          read_error_callback) {
    read_error_callback_ = read_error_callback;
  }

  // Specifies to use an actual file-backed user pref store.
  void SetUserPrefsFile(const base::FilePath& prefs_file,
                        base::SequencedTaskRunner* task_runner);

  void set_async(bool async) {
    async_ = async;
  }

  // Creates a PrefService object initialized with the parameters from
  // this factory.
  scoped_ptr<PrefService> Create(PrefRegistry* registry);

 protected:
  scoped_refptr<PrefStore> managed_prefs_;
  scoped_refptr<PrefStore> supervised_user_prefs_;
  scoped_refptr<PrefStore> extension_prefs_;
  scoped_refptr<PrefStore> command_line_prefs_;
  scoped_refptr<PersistentPrefStore> user_prefs_;
  scoped_refptr<PrefStore> recommended_prefs_;

  base::Callback<void(PersistentPrefStore::PrefReadError)> read_error_callback_;

  // Defaults to false.
  bool async_;

 private:
  DISALLOW_COPY_AND_ASSIGN(PrefServiceFactory);
};

}  // namespace base

#endif  // BASE_PREFS_PREF_SERVICE_FACTORY_H_


text:
import { Function20 } from "../../";

export = Function20;