text:
package sql

// Copyright (c) Microsoft and contributors.  All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

import (
	"context"
	"github.com/Azure/go-autorest/autorest"
	"github.com/Azure/go-autorest/autorest/azure"
	"github.com/Azure/go-autorest/autorest/validation"
	"net/http"
)

// JobCredentialsClient is the the Azure SQL Database management API provides a RESTful set of web services that
// interact with Azure SQL Database services to manage your databases. The API enables you to create, retrieve, update,
// and delete databases.
type JobCredentialsClient struct {
	BaseClient
}

// NewJobCredentialsClient creates an instance of the JobCredentialsClient client.
func NewJobCredentialsClient(subscriptionID string) JobCredentialsClient {
	return NewJobCredentialsClientWithBaseURI(DefaultBaseURI, subscriptionID)
}

// NewJobCredentialsClientWithBaseURI creates an instance of the JobCredentialsClient client.
func NewJobCredentialsClientWithBaseURI(baseURI string, subscriptionID string) JobCredentialsClient {
	return JobCredentialsClient{NewWithBaseURI(baseURI, subscriptionID)}
}

// CreateOrUpdate creates or updates a job credential.
// Parameters:
// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value
// from the Azure Resource Manager API or the portal.
// serverName - the name of the server.
// jobAgentName - the name of the job agent.
// credentialName - the name of the credential.
// parameters - the requested job credential state.
func (client JobCredentialsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, serverName string, jobAgentName string, credentialName string, parameters JobCredential) (result JobCredential, err error) {
	if err := validation.Validate([]validation.Validation{
		{TargetValue: parameters,
			Constraints: []validation.Constraint{{Target: "parameters.JobCredentialProperties", Name: validation.Null, Rule: false,
				Chain: []validation.Constraint{{Target: "parameters.JobCredentialProperties.Username", Name: validation.Null, Rule: true, Chain: nil},
					{Target: "parameters.JobCredentialProperties.Password", Name: validation.Null, Rule: true, Chain: nil},
				}}}}}); err != nil {
		return result, validation.NewError("sql.JobCredentialsClient", "CreateOrUpdate", err.Error())
	}

	req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, serverName, jobAgentName, credentialName, parameters)
	if err != nil {
		err = autorest.NewErrorWithError(err, "sql.JobCredentialsClient", "CreateOrUpdate", nil, "Failure preparing request")
		return
	}

	resp, err := client.CreateOrUpdateSender(req)
	if err != nil {
		result.Response = autorest.Response{Response: resp}
		err = autorest.NewErrorWithError(err, "sql.JobCredentialsClient", "CreateOrUpdate", resp, "Failure sending request")
		return
	}

	result, err = client.CreateOrUpdateResponder(resp)
	if err != nil {
		err = autorest.NewErrorWithError(err, "sql.JobCredentialsClient", "CreateOrUpdate", resp, "Failure responding to request")
	}

	return
}

// CreateOrUpdatePreparer prepares the CreateOrUpdate request.
func (client JobCredentialsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, serverName string, jobAgentName string, credentialName string, parameters JobCredential) (*http.Request, error) {
	pathParameters := map[string]interface{}{
		"credentialName":    autorest.Encode("path", credentialName),
		"jobAgentName":      autorest.Encode("path", jobAgentName),
		"resourceGroupName": autorest.Encode("path", resourceGroupName),
		"serverName":        autorest.Encode("path", serverName),
		"subscriptionId":    autorest.Encode("path", client.SubscriptionID),
	}

	const APIVersion = "2017-03-01-preview"
	queryParameters := map[string]interface{}{
		"api-version": APIVersion,
	}

	preparer := autorest.CreatePreparer(
		autorest.AsContentType("application/json; charset=utf-8"),
		autorest.AsPut(),
		autorest.WithBaseURL(client.BaseURI),
		autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/jobAgents/{jobAgentName}/credentials/{credentialName}", pathParameters),
		autorest.WithJSON(parameters),
		autorest.WithQueryParameters(queryParameters))
	return preparer.Prepare((&http.Request{}).WithContext(ctx))
}

// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the
// http.Response Body if it receives an error.
func (client JobCredentialsClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) {
	return autorest.SendWithSender(client, req,
		azure.DoRetryWithRegistration(client.Client))
}

// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always
// closes the http.Response Body.
func (client JobCredentialsClient) CreateOrUpdateResponder(resp *http.Response) (result JobCredential, err error) {
	err = autorest.Respond(
		resp,
		client.ByInspecting(),
		azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated),
		autorest.ByUnmarshallingJSON(&result),
		autorest.ByClosing())
	result.Response = autorest.Response{Response: resp}
	return
}

// Delete deletes a job credential.
// Parameters:
// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value
// from the Azure Resource Manager API or the portal.
// serverName - the name of the server.
// jobAgentName - the name of the job agent.
// credentialName - the name of the credential.
func (client JobCredentialsClient) Delete(ctx context.Context, resourceGroupName string, serverName string, jobAgentName string, credentialName string) (result autorest.Response, err error) {
	req, err := client.DeletePreparer(ctx, resourceGroupName, serverName, jobAgentName, credentialName)
	if err != nil {
		err = autorest.NewErrorWithError(err, "sql.JobCredentialsClient", "Delete", nil, "Failure preparing request")
		return
	}

	resp, err := client.DeleteSender(req)
	if err != nil {
		result.Response = resp
		err = autorest.NewErrorWithError(err, "sql.JobCredentialsClient", "Delete", resp, "Failure sending request")
		return
	}

	result, err = client.DeleteResponder(resp)
	if err != nil {
		err = autorest.NewErrorWithError(err, "sql.JobCredentialsClient", "Delete", resp, "Failure responding to request")
	}

	return
}

// DeletePreparer prepares the Delete request.
func (client JobCredentialsClient) DeletePreparer(ctx context.Context, resourceGroupName string, serverName string, jobAgentName string, credentialName string) (*http.Request, error) {
	pathParameters := map[string]interface{}{
		"credentialName":    autorest.Encode("path", credentialName),
		"jobAgentName":      autorest.Encode("path", jobAgentName),
		"resourceGroupName": autorest.Encode("path", resourceGroupName),
		"serverName":        autorest.Encode("path", serverName),
		"subscriptionId":    autorest.Encode("path", client.SubscriptionID),
	}

	const APIVersion = "2017-03-01-preview"
	queryParameters := map[string]interface{}{
		"api-version": APIVersion,
	}

	preparer := autorest.CreatePreparer(
		autorest.AsDelete(),
		autorest.WithBaseURL(client.BaseURI),
		autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/jobAgents/{jobAgentName}/credentials/{credentialName}", pathParameters),
		autorest.WithQueryParameters(queryParameters))
	return preparer.Prepare((&http.Request{}).WithContext(ctx))
}

// DeleteSender sends the Delete request. The method will close the
// http.Response Body if it receives an error.
func (client JobCredentialsClient) DeleteSender(req *http.Request) (*http.Response, error) {
	return autorest.SendWithSender(client, req,
		azure.DoRetryWithRegistration(client.Client))
}

// DeleteResponder handles the response to the Delete request. The method always
// closes the http.Response Body.
func (client JobCredentialsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) {
	err = autorest.Respond(
		resp,
		client.ByInspecting(),
		azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent),
		autorest.ByClosing())
	result.Response = resp
	return
}

// Get gets a jobs credential.
// Parameters:
// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value
// from the Azure Resource Manager API or the portal.
// serverName - the name of the server.
// jobAgentName - the name of the job agent.
// credentialName - the name of the credential.
func (client JobCredentialsClient) Get(ctx context.Context, resourceGroupName string, serverName string, jobAgentName string, credentialName string) (result JobCredential, err error) {
	req, err := client.GetPreparer(ctx, resourceGroupName, serverName, jobAgentName, credentialName)
	if err != nil {
		err = autorest.NewErrorWithError(err, "sql.JobCredentialsClient", "Get", nil, "Failure preparing request")
		return
	}

	resp, err := client.GetSender(req)
	if err != nil {
		result.Response = autorest.Response{Response: resp}
		err = autorest.NewErrorWithError(err, "sql.JobCredentialsClient", "Get", resp, "Failure sending request")
		return
	}

	result, err = client.GetResponder(resp)
	if err != nil {
		err = autorest.NewErrorWithError(err, "sql.JobCredentialsClient", "Get", resp, "Failure responding to request")
	}

	return
}

// GetPreparer prepares the Get request.
func (client JobCredentialsClient) GetPreparer(ctx context.Context, resourceGroupName string, serverName string, jobAgentName string, credentialName string) (*http.Request, error) {
	pathParameters := map[string]interface{}{
		"credentialName":    autorest.Encode("path", credentialName),
		"jobAgentName":      autorest.Encode("path", jobAgentName),
		"resourceGroupName": autorest.Encode("path", resourceGroupName),
		"serverName":        autorest.Encode("path", serverName),
		"subscriptionId":    autorest.Encode("path", client.SubscriptionID),
	}

	const APIVersion = "2017-03-01-preview"
	queryParameters := map[string]interface{}{
		"api-version": APIVersion,
	}

	preparer := autorest.CreatePreparer(
		autorest.AsGet(),
		autorest.WithBaseURL(client.BaseURI),
		autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/jobAgents/{jobAgentName}/credentials/{credentialName}", pathParameters),
		autorest.WithQueryParameters(queryParameters))
	return preparer.Prepare((&http.Request{}).WithContext(ctx))
}

// GetSender sends the Get request. The method will close the
// http.Response Body if it receives an error.
func (client JobCredentialsClient) GetSender(req *http.Request) (*http.Response, error) {
	return autorest.SendWithSender(client, req,
		azure.DoRetryWithRegistration(client.Client))
}

// GetResponder handles the response to the Get request. The method always
// closes the http.Response Body.
func (client JobCredentialsClient) GetResponder(resp *http.Response) (result JobCredential, err error) {
	err = autorest.Respond(
		resp,
		client.ByInspecting(),
		azure.WithErrorUnlessStatusCode(http.StatusOK),
		autorest.ByUnmarshallingJSON(&result),
		autorest.ByClosing())
	result.Response = autorest.Response{Response: resp}
	return
}

// ListByAgent gets a list of jobs credentials.
// Parameters:
// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value
// from the Azure Resource Manager API or the portal.
// serverName - the name of the server.
// jobAgentName - the name of the job agent.
func (client JobCredentialsClient) ListByAgent(ctx context.Context, resourceGroupName string, serverName string, jobAgentName string) (result JobCredentialListResultPage, err error) {
	result.fn = client.listByAgentNextResults
	req, err := client.ListByAgentPreparer(ctx, resourceGroupName, serverName, jobAgentName)
	if err != nil {
		err = autorest.NewErrorWithError(err, "sql.JobCredentialsClient", "ListByAgent", nil, "Failure preparing request")
		return
	}

	resp, err := client.ListByAgentSender(req)
	if err != nil {
		result.jclr.Response = autorest.Response{Response: resp}
		err = autorest.NewErrorWithError(err, "sql.JobCredentialsClient", "ListByAgent", resp, "Failure sending request")
		return
	}

	result.jclr, err = client.ListByAgentResponder(resp)
	if err != nil {
		err = autorest.NewErrorWithError(err, "sql.JobCredentialsClient", "ListByAgent", resp, "Failure responding to request")
	}

	return
}

// ListByAgentPreparer prepares the ListByAgent request.
func (client JobCredentialsClient) ListByAgentPreparer(ctx context.Context, resourceGroupName string, serverName string, jobAgentName string) (*http.Request, error) {
	pathParameters := map[string]interface{}{
		"jobAgentName":      autorest.Encode("path", jobAgentName),
		"resourceGroupName": autorest.Encode("path", resourceGroupName),
		"serverName":        autorest.Encode("path", serverName),
		"subscriptionId":    autorest.Encode("path", client.SubscriptionID),
	}

	const APIVersion = "2017-03-01-preview"
	queryParameters := map[string]interface{}{
		"api-version": APIVersion,
	}

	preparer := autorest.CreatePreparer(
		autorest.AsGet(),
		autorest.WithBaseURL(client.BaseURI),
		autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/jobAgents/{jobAgentName}/credentials", pathParameters),
		autorest.WithQueryParameters(queryParameters))
	return preparer.Prepare((&http.Request{}).WithContext(ctx))
}

// ListByAgentSender sends the ListByAgent request. The method will close the
// http.Response Body if it receives an error.
func (client JobCredentialsClient) ListByAgentSender(req *http.Request) (*http.Response, error) {
	return autorest.SendWithSender(client, req,
		azure.DoRetryWithRegistration(client.Client))
}

// ListByAgentResponder handles the response to the ListByAgent request. The method always
// closes the http.Response Body.
func (client JobCredentialsClient) ListByAgentResponder(resp *http.Response) (result JobCredentialListResult, err error) {
	err = autorest.Respond(
		resp,
		client.ByInspecting(),
		azure.WithErrorUnlessStatusCode(http.StatusOK),
		autorest.ByUnmarshallingJSON(&result),
		autorest.ByClosing())
	result.Response = autorest.Response{Response: resp}
	return
}

// listByAgentNextResults retrieves the next set of results, if any.
func (client JobCredentialsClient) listByAgentNextResults(lastResults JobCredentialListResult) (result JobCredentialListResult, err error) {
	req, err := lastResults.jobCredentialListResultPreparer()
	if err != nil {
		return result, autorest.NewErrorWithError(err, "sql.JobCredentialsClient", "listByAgentNextResults", nil, "Failure preparing next results request")
	}
	if req == nil {
		return
	}
	resp, err := client.ListByAgentSender(req)
	if err != nil {
		result.Response = autorest.Response{Response: resp}
		return result, autorest.NewErrorWithError(err, "sql.JobCredentialsClient", "listByAgentNextResults", resp, "Failure sending next results request")
	}
	result, err = client.ListByAgentResponder(resp)
	if err != nil {
		err = autorest.NewErrorWithError(err, "sql.JobCredentialsClient", "listByAgentNextResults", resp, "Failure responding to next results request")
	}
	return
}

// ListByAgentComplete enumerates all values, automatically crossing page boundaries as required.
func (client JobCredentialsClient) ListByAgentComplete(ctx context.Context, resourceGroupName string, serverName string, jobAgentName string) (result JobCredentialListResultIterator, err error) {
	result.page, err = client.ListByAgent(ctx, resourceGroupName, serverName, jobAgentName)
	return
}


text:
module FightTheMelons #:nodoc:
  module Helpers #:nodoc:

  	# Some of the most used variables so you can setup them per application or
    # per controller instead of everytime you use one of the helpers.
    module FormMultipleSelectHelperConfiguration
      # Class used in the ul tag that wraps all the checkboxes.
      attr_accessor :outer_class
      module_function :outer_class, :outer_class=

      # Class used in the li tag that wraps each checkbox.
      attr_accessor :inner_class
      module_function :inner_class, :inner_class=

      # Prefix of the level class added to the inner class in the tree methods.
      attr_accessor :level_class
      module_function :level_class, :level_class=

      # Class for the alternate elements. Added to inner class.
      attr_accessor :alternate_class
      module_function :alternate_class, :alternate_class=

      # Determines if the methods will alternate the classes of the checkboxes.
      attr_accessor :alternate
      module_function :alternate, :alternate=

      # Establish the position of the checkbox with respect the label.
      attr_accessor :position
      module_function :position, :position=

      # Establish the name of the tags used to wrap the elements.
      attr_accessor :list_tags
      module_function :list_tags, :list_tags=

      # Default value for alternate is false.
      self.alternate = false

      # Default value for alternate_class is 'alt'.
      self.alternate_class = 'alt'

      # Default value for position is ':right'
      self.position = :right

      # Default value for list_tags is ['ul', 'li']
      self.list_tags = ['ul', 'li']
    end

    # Provides a number of methods for turning different kinds of containers
    # into checkboxes lists.
    module FormMultipleSelectHelper
      include ERB::Util
      include ActionView::Helpers::FormTagHelper
      include ActionView::Helpers::TagHelper
      include ActionView::Helpers

      # There is another content_tag in ActionView::Helpers::InstanceTag, but
      # we want the one in ActionView::Helpers::TagHelper.
      alias av_content_tag content_tag

      # Returns a list of checkboxes using
      # checkboxes_from_collection_for_multiple_select to generate the list of
      # checkboxes.
      #
      # If a <tt>:selected_items</tt> option is provided it will be used as
      # selection. <tt>:selected_items</tt> array should be an array of values
      # to be matched with the ones provided by <tt>value_method</tt>.
      #
      # The option <tt>:outer_class</tt> specifies the HTML class of the ul
      # element that wraps the checkbox list.
      def collection_multiple_select(
        object, method, collection, value_method, text_method, options = {}
      )
        InstanceTag.new(
          object, method, self, options.delete(:object)
        ).to_collection_multiple_select_tag(
          "#{object}[#{method}]", collection, value_method, text_method, options
        )
      end

      # Same as collection_multiple_select but without an associated object.
      def collection_multiple_select_tag(
        name, collection, value_method, text_method, options = {}
      )
        multiple_select_with_path(name, options) do |selected_items|
          checkboxes_from_collection_for_multiple_select(name, collection,
            value_method, text_method, selected_items, options
          )
        end
      end

      # Create a list of checkboxes. See checkboxes_for_multiple_select for the
      # required format of the choices parameter.
      #
      # If a <tt>:selected_items</tt> option is provided it will be used as
      # selection. <tt>:selected_items</tt> array should be an array of values
      # to be matched with the ones provided by <tt>method</tt>.
      #
      # The option <tt>:outer_class</tt> specifies the HTML class of the HTML
      # element that wraps the checkbox list.
      def multiple_select(object, method, container, options = {})
        InstanceTag.new(
          object, method, self, options.delete(:object)
        ).to_multiple_select_tag("#{object}[#{method}]", container, options)
      end

      # Same as multiple_select but without an associated object.
      def multiple_select_tag(name, container, options = {})
        multiple_select_with_path(name, options) do |selected_items|
          checkboxes_for_multiple_select(
            name, container, selected_items, options
          )
        end
      end

      # Create a list of hierarchical checkboxes for the provides object and
      # method.
      # The hierarchy must respond to <tt>:child_method</tt> to get the direct
      # children of the actual node. The default value is <tt>children</tt>.
      #
      # If a <tt>:selected_items</tt> option is provided it will be used as
      # selection. <tt>:selected_items</tt> array should be an array of values
      # to be matched with the ones provided by <tt>value_method</tt>.
      #
      # The option <tt>:outer_class</tt> specifies the HTML class of the ul
      # element that wraps the checkbox hierarchy.
      def tree_multiple_select(object, method, nodes, value_method, text_method, options = {})
        InstanceTag.new(
          object, method, self, options.delete(:object)
        ).to_tree_multiple_select_tag(
          "#{object}[#{method}]", nodes, value_method, text_method, options
        )
      end

      # Same as tree_multiple_select but without an associated object.
      def tree_multiple_select_tag(
        name, nodes, value_method, text_method, options = {}
      )
        multiple_select_with_path(name, options) do |selected_items|
          checkboxes_from_tree_for_multiple_select(
            name, nodes, value_method, text_method, selected_items, options
          )
        end
      end

      # Returns a string of checkboxes that have been compiled iterating over
      # the <tt>collection</tt> and assigning the result of a call to the
      # <tt>value_method</tt> as the option value and the <tt>text_method</tt>
      # as the label text. If <tt>selected_items</tt> is specified, the element
      # returning a match on <tt>value_method</tt> will get the selected
      # attribute in its checkbox. See checkboxes_for_multiple_select for the
      # allowed options in the hash.
      def checkboxes_from_collection_for_multiple_select(
        name, collection, value_method, text_method, selected_items = [],
        options = {}
      )
        coll = (collection or [])

        checkboxes_for_multiple_select(
          name,
          coll.map { |item| [item.send(text_method), item.send(value_method)] },
          selected_items, options
        )
      end

      # Returns a string of checkboxes that have been compiling descending the
      # <tt>node</tt> and assigning the result of a call to the
      # <tt>value_method</tt> as the option value and the <tt>text_method</tt>
      # as the label text. If <tt>selected_items</tt> is specified, the element
      # returning a match on <tt>value_method</tt> will get the selected
      # attribute in its checkbox.
      #
      # The option <tt>:depth</tt> specifies the maximum depth of the nodes to
      # show. It defaults to infinity.
      #
      # The option <tt>:level_class</tt> is a CSS class prefix that will be
      # applied to the checkbox li element suffixing it with the actual depth.
      #
      # The option <tt>:initial_level</tt> is the value that will be used as suffix
      # for <tt>level_class</tt> option. It defaults to 0.
      #
      # The option <tt>:child_method</tt> allows access to an array of direct
      # children of the actual method. It defaults to "children".
      #
      # See checkboxes_for_multiple_select for more allowed options.
      def checkboxes_from_tree_for_multiple_select(
        name, nodes, value_method, text_method, selected_items = [],
        options = {}
      )
        depth = (options[:depth] or -1)
        level_class = (options[:level_class] or
          FormMultipleSelectHelperConfiguration.level_class)
        initial_level = (options[:initial_level] or 0)
        child_method = (options[:child_method] or :children)
        inner_class = (options[:inner_class] or
          FormMultipleSelectHelperConfiguration.inner_class)
        alternate = options[:alternate].nil? ?
          FormMultipleSelectHelperConfiguration.alternate :
          options[:alternate]
        alt = (options[:initial_alternate] or false) if alternate

        root_options = options.dup
        if level_class
          root_options[:inner_class] =
            "#{inner_class} #{level_class}#{initial_level}".strip
        end
        root_options[:initial_alternate] = alt if alternate

        child_options = {
          :depth => depth - 1,
          :initial_level => initial_level + 1,
          :inner_class => inner_class,
        }
        child_options = options.merge(child_options)
        child_options[:initial_alternate] = !alt if alternate

        checkboxes = nodes.map do |node|
          parent = checkbox_for_multiple_select(
            name,
            [node.send(text_method), node.send(value_method)],
            selected_items, alt, root_options
          ) do
            children = node.send(child_method)
            branch = if not (depth == 0 || children.size == 0)
	            "\n" + av_content_tag(
	              FormMultipleSelectHelperConfiguration.list_tags[0],
	              checkboxes_from_tree_for_multiple_select(
                    name, children, value_method, text_method, selected_items,
                    child_options
                  )
                )
              else
                ''
              end

            if alternate
              alt = alt ? (not children.size%2 == 0) : (children.size%2 == 0)
              root_options[:initial_alternate] = alt
              child_options[:initial_alternate] = !alt
            end

            branch
          end
        end

        checkboxes.join("\n")
      end

      # Accepts a container (hash, array, enumerable, your type) and returns a
      # string of checkbox tags. Given a container where the elements respond to
      # first and last (such a two-element array), the "last" serve as checkbox
      # values and the "first" as label text. Hashes are turned into this form
      # automatically, so the keys beceome "firsts" and the values become
      # "lasts". If <tt>selected_items</tt> is not empty, the matching
      # elements will get the selected attribute in its checkbox.
      #
      # The <tt>:alternate</tt> option determines if the classes of the items
      # should alternate. The default value for <tt>:alternate</tt> is
      # <tt>false</tt>.
      #
      # The <tt>:initial_alternate</tt> option specifies if the first element
      # should have the alternate style or not. By default the first element
      # does not have the alternate style.
      #
      # If the option <tt>:position</tt> is provided the specified
      # position is used (<tt>:left</tt> or <tt>:right</tt>), otherwise the
      # default <tt>:right</tt> position is used.
      #
      # The <tt>:inner_class</tt> option specifies the base class of the HTML
      # element that surrounds the checkbox and the label.
      #
      # The <tt>:disabled</tt> option specifies if the checkbox will be rendered
      # disabled or not. Disabled can be <tt>true</tt>, <tt>false</tt> or an
      # array of values that will be disabled. By default the checkbox will not
      # be disabled.
      def checkboxes_for_multiple_select(
        name, container, selected_items = [], options = {}
      )
        container = container.to_a if Hash === container
        ialternate = options[:alternate].nil? ?
          FormMultipleSelectHelperConfiguration.alternate :
          options[:alternate]
        alt = (options[:initial_alternate] or false)

        checkboxes = container.map do |item|
          cbfms = checkbox_for_multiple_select(
            name, item, selected_items, alt, options
          )
          alt = !alt if ialternate
          cbfms
        end

        checkboxes.join("\n")
      end

    protected

      # Common body for multiple_select, collection_multiple_select and
      # tree_multiple_select.
      def multiple_select_with_path(name, options, &block)
        val = value(object) if respond_to? :value
        selected_items = options.has_key?(:selected_items) ? options[:selected_items] : val
        selected_items ||= []
        outer_class = (options[:outer_class] or
          FormMultipleSelectHelperConfiguration.outer_class)

        checkboxes = yield(selected_items)

        av_content_tag(
          FormMultipleSelectHelperConfiguration.list_tags[0],
          checkboxes,
          :class => outer_class
        ) << "\n" << hidden_field_tag("#{name}[]", '', :id => nil)
      end

    private

      # Accepts an item and returns a checkbox tag. If the item respond to first
      # and last (such a two element array), the "last" serve as checkbox value
      # and the "first" as label text. If the item is included in the
      # <tt>selected_items</tt> its checkbox will be selected. The
      # <tt>is_alternate</tt> determines if the checkbox will use the alternate
      # class name or not.
      #
      # If the option <tt>:position</tt> is provided the specified
      # position is used (<tt>:left</tt> or <tt>:right</tt>), otherwise the
      # default <tt>:right</tt> position is used.
      #
      # The <tt>:inner_class</tt> option specifies the base class of the li that
      # surrounds the checkbox and the label.
      #
      # The <tt>:alternate_class</tt> option allow to specify
      # a additional class that will be used in the element if
      # <tt>is_alternate</tt> is <tt>true</tt>.
      #
      # The <tt>:disabled</tt> option specifies if the checkbox will be rendered
      # disabled or not. Disabled can be <tt>true</tt>, <tt>false</tt> or an
      # array of values that will be disabled. By default the checkbox will not
      # be disabled.
      def checkbox_for_multiple_select(
        name, item, selected_items = [], is_alternate = false, options = {}
      )
        position = (options[:position] or
          FormMultipleSelectHelperConfiguration.position)
        inner_class = (options[:inner_class] or
          FormMultipleSelectHelperConfiguration.inner_class)
        alternate_class = (options[:alternate_class] or
          FormMultipleSelectHelperConfiguration.alternate_class)
        is_disabled = (options[:disabled] or false)

        if !item.is_a?(String) and item.respond_to?(:first) and item.respond_to?(:last)
          is_selected = selected_items.include?(item.last)
          is_disabled = is_disabled.include?(item.last) if is_disabled.respond_to?(:include?)
          item_id = idfy("#{name}#{item.last}")
          cbt = check_box_tag("#{name}[]", html_escape(item.last.to_s), is_selected, :id => item_id, :disabled => is_disabled)
          lbt = av_content_tag('label', html_escape(item.first.to_s), :for => item_id)
        else
          is_selected = selected_items.include?(item)
          is_disabled = is_disabled.include?(item) if is_disabled.respond_to?(:include?)
          item_id = idfy("#{name}#{item.to_s}")
          cbt = check_box_tag("#{name}[]", html_escape(item.to_s), is_selected, :id => item_id, :disabled => is_disabled)
          lbt = av_content_tag('label', html_escape(item.to_s), :for => item_id)
        end

        item_class = is_alternate ? "#{inner_class} #{alternate_class}".strip : inner_class

        extra = block_given? ? yield : ''

        av_content_tag(
          FormMultipleSelectHelperConfiguration.list_tags[1],
          position == :left ? lbt + cbt + extra : cbt + lbt + extra,
          :class => item_class
        )
      end

      # Convert the string <tt>name</tt> provided into a HTML 4.01 valid
      # identifier. If <tt>name</tt> does not start with a letter it will be
      # prepend an 'x' character. All characters outside the posible characters
      # for a HTML identifier are replaced by an underscore ("_"). The only
      # valid characters are letters, digits, hyphens ("-"), underscores ("_"),
      # colons (":") and periods ("."). See
      # http://www.w3.org/TR/html4/types.html#type-name for more information.
      def idfy(name)
        name = 'x' + name unless /^[a-zA-Z]/ =~ name
        name.scan(/[-a-zA-Z0-9_:.]+/).join('_')
      end
    end
  end
end

module ActionView #:nodoc:
  module Helpers #:nodoc:
    class InstanceTag #:nodoc:
      include FightTheMelons::Helpers::FormMultipleSelectHelper
      include FightTheMelons::Helpers

      def to_multiple_select_tag(name, container, options)
        multiple_select_with_path(name, options) do |selected_items|
          checkboxes_for_multiple_select(
            name, container, selected_items, options
          )
        end
      end

      def to_collection_multiple_select_tag(name, collection, value_method, text_method, options)
        multiple_select_with_path(name, options) do |selected_items|
          checkboxes_from_collection_for_multiple_select(
            name, collection, value_method, text_method, selected_items, options
          )
        end
      end

      def to_tree_multiple_select_tag(name, nodes, value_method, text_method, options)
        multiple_select_with_path(name, options) do |selected_items|
          checkboxes_from_tree_for_multiple_select(
            name, nodes, value_method, text_method, selected_items, options
          )
        end
      end
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Magento\Backend\Model\Session;

/**
 * Class QuoteTest
 */
class QuoteTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $storeManagerMock;

    /**
     * @var \Magento\Sales\Model\OrderFactory|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $orderFactoryMock;

    /**
     * @var \Magento\Framework\Stdlib\Cookie\CookieMetadataFactory|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $cookieMetadataFactoryMock;

    /**
     * @var \Magento\Framework\Stdlib\CookieManager|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $cookieManagerMock;

    /**
     * @var \Magento\Framework\Session\StorageInterface|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $storageMock;

    /**
     * @var \Magento\Framework\Session\ValidatorInterface|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $validatorMock;

    /**
     * @var \Magento\Framework\Session\SaveHandlerInterface|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $saveHandlerMock;

    /**
     * @var \Magento\Framework\Session\Config\ConfigInterface|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $sessionConfigMock;

    /**
     * @var \Magento\Framework\Session\SidResolverInterface|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $sidResolverMock;

    /**
     * @var \Magento\Framework\App\Request\Http|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $requestMock;

    /**
     * @var \Magento\Customer\Api\CustomerRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $customerRepositoryMock;

    /**
     * @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $scopeConfigMock;

    /**
     * @var \Magento\Sales\Model\QuoteFactory|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $quoteRepositoryMock;

    /**
     * @var \Magento\Backend\Model\Session\Quote|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $quote;

    /**
     * @var \Magento\Customer\Api\GroupManagementInterface|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $groupManagementMock;

    /**
     * Set up
     *
     * @return void
     */
    protected function setUp()
    {
        $this->customerRepositoryMock = $this->getMockForAbstractClass(
            'Magento\Customer\Api\CustomerRepositoryInterface',
            [],
            '',
            false,
            true,
            true,
            ['getCustomer']
        );
        $this->groupManagementMock = $this->getMockForAbstractClass(
            'Magento\Customer\Api\GroupManagementInterface',
            [],
            '',
            false,
            true,
            true,
            ['getDefaultGroup']
        );

        $this->scopeConfigMock = $this->getMockForAbstractClass(
            'Magento\Framework\App\Config\ScopeConfigInterface',
            [],
            '',
            false,
            true,
            true,
            ['getValue']
        );
        $this->quoteRepositoryMock = $this->getMock(
            'Magento\Sales\Model\QuoteRepository',
            ['create', 'save', 'get'],
            [],
            '',
            false
        );

        $this->requestMock = $this->getMock(
            'Magento\Framework\App\Request\Http',
            [],
            [],
            '',
            false
        );
        $this->sidResolverMock = $this->getMockForAbstractClass(
            'Magento\Framework\Session\SidResolverInterface',
            [],
            '',
            false
        );
        $this->sessionConfigMock = $this->getMockForAbstractClass(
            'Magento\Framework\Session\Config\ConfigInterface',
            [],
            '',
            false
        );
        $this->saveHandlerMock = $this->getMockForAbstractClass(
            'Magento\Framework\Session\SaveHandlerInterface',
            [],
            '',
            false
        );
        $this->validatorMock = $this->getMockForAbstractClass(
            'Magento\Framework\Session\ValidatorInterface',
            [],
            '',
            false
        );
        $this->storageMock = $this->getMockForAbstractClass(
            'Magento\Framework\Session\StorageInterface',
            [],
            '',
            false
        );
        $this->cookieManagerMock = $this->getMock('Magento\Framework\Stdlib\CookieManagerInterface');
        $this->cookieMetadataFactoryMock = $this->getMock(
            'Magento\Framework\Stdlib\Cookie\CookieMetadataFactory',
            [],
            [],
            '',
            false
        );
        $this->orderFactoryMock = $this->getMock(
            'Magento\Sales\Model\OrderFactory',
            [],
            [],
            '',
            false
        );
        $this->storeManagerMock = $this->getMockForAbstractClass(
            'Magento\Store\Model\StoreManagerInterface',
            [],
            '',
            false
        );

        $this->quote = $this->getMock(
            'Magento\Backend\Model\Session\Quote',
            ['getStoreId', 'getQuoteId', 'setQuoteId', 'hasCustomerId', 'getCustomerId'],
            [
                'request' => $this->requestMock,
                'sidResolver' => $this->sidResolverMock,
                'sessionConfig' => $this->sessionConfigMock,
                'saveHandler' => $this->saveHandlerMock,
                'validator' => $this->validatorMock,
                'storage' => $this->storageMock,
                'cookieManager' => $this->cookieManagerMock,
                'cookieMetadataFactory' => $this->cookieMetadataFactoryMock,
                'customerRepository' => $this->customerRepositoryMock,
                'quoteRepository' => $this->quoteRepositoryMock,
                'orderFactory' => $this->orderFactoryMock,
                'storeManager' => $this->storeManagerMock,
                'groupManagement' => $this->groupManagementMock
            ],
            '',
            true
        );
    }

    /**
     * Run test getQuote method
     *
     * @return void
     */
    public function testGetQuote()
    {
        $storeId = 10;
        $quoteId = 22;
        $customerGroupId = 77;
        $customerId = 66;

        $quoteMock = $this->getMock(
            'Magento\Sales\Model\Quote',
            [
                'setStoreId',
                'setCustomerGroupId',
                'setIsActive',
                'getId',
                'assignCustomer',
                'setIgnoreOldQty',
                'setIsSuperMode',
                '__wakeup'
            ],
            [],
            '',
            false
        );

        $defaultGroup = $this->getMockBuilder('Magento\Customer\Api\Data\GroupInterface')
            ->getMock();
        $defaultGroup->expects($this->any())
            ->method('getId')
            ->will($this->returnValue($customerGroupId));
        $this->groupManagementMock->expects($this->any())
            ->method('getDefaultGroup')
            ->will($this->returnValue($defaultGroup));

        $this->quoteRepositoryMock->expects($this->once())
            ->method('create')
            ->will($this->returnValue($quoteMock));
        $this->quote->expects($this->any())
            ->method('getStoreId')
            ->will($this->returnValue($storeId));
        $quoteMock->expects($this->once())
            ->method('setStoreId')
            ->with($storeId);
        $this->quote->expects($this->any())
            ->method('getQuoteId')
            ->will($this->returnValue(null));
        $quoteMock->expects($this->once())
            ->method('setCustomerGroupId')
            ->with($customerGroupId)
            ->will($this->returnSelf());
        $quoteMock->expects($this->once())
            ->method('setIsActive')
            ->with(false)
            ->will($this->returnSelf());
        $this->quoteRepositoryMock->expects($this->once())
            ->method('save')
            ->with($quoteMock);
        $quoteMock->expects($this->once())
            ->method('getId')
            ->will($this->returnValue($quoteId));
        $this->quote->expects($this->any())
            ->method('setQuoteId')
            ->with($quoteId);
        $this->quote->expects($this->any())
            ->method('getCustomerId')
            ->will($this->returnValue($customerId));
        $dataCustomerMock = $this->getMockBuilder('Magento\Customer\Api\Data\CustomerInterface')
            ->disableOriginalConstructor()
            ->getMock();
        $this->customerRepositoryMock->expects($this->once())
            ->method('getById')
            ->with($customerId)
            ->willReturn($dataCustomerMock);
        $quoteMock->expects($this->once())
            ->method('assignCustomer')
            ->with($dataCustomerMock);
        $quoteMock->expects($this->once())
            ->method('setIgnoreOldQty')
            ->with(true);
        $quoteMock->expects($this->once())
            ->method('setIsSuperMode')
            ->with(true);

        $this->assertEquals($quoteMock, $this->quote->getQuote());
    }

    /**
     * Run test getQuote method
     *
     * @return void
     */
    public function testGetQuoteGet()
    {
        $storeId = 10;
        $quoteId = 22;
        $customerId = 66;

        $quoteMock = $this->getMock(
            'Magento\Sales\Model\Quote',
            [
                'setStoreId',
                'setCustomerGroupId',
                'setIsActive',
                'getId',
                'assignCustomer',
                'setIgnoreOldQty',
                'setIsSuperMode',
                '__wakeup'
            ],
            [],
            '',
            false
        );

        $this->quoteRepositoryMock->expects($this->once())
            ->method('create')
            ->will($this->returnValue($quoteMock));
        $this->quote->expects($this->any())
            ->method('getStoreId')
            ->will($this->returnValue($storeId));
        $quoteMock->expects($this->once())
            ->method('setStoreId')
            ->with($storeId);
        $this->quote->expects($this->any())
            ->method('getQuoteId')
            ->will($this->returnValue($quoteId));
        $this->quoteRepositoryMock->expects($this->once())
            ->method('get')
            ->with($quoteId)
            ->willReturn($quoteMock);
        $this->quote->expects($this->any())
            ->method('setQuoteId')
            ->with($quoteId);
        $this->quote->expects($this->any())
            ->method('getCustomerId')
            ->will($this->returnValue($customerId));
        $dataCustomerMock = $this->getMockBuilder('Magento\Customer\Api\Data\CustomerInterface')
            ->disableOriginalConstructor()
            ->getMock();
        $this->customerRepositoryMock->expects($this->once())
            ->method('getById')
            ->with($customerId)
            ->willReturn($dataCustomerMock);
        $quoteMock->expects($this->once())
            ->method('assignCustomer')
            ->with($dataCustomerMock);
        $quoteMock->expects($this->once())
            ->method('setIgnoreOldQty')
            ->with(true);
        $quoteMock->expects($this->once())
            ->method('setIsSuperMode')
            ->with(true);

        $this->assertEquals($quoteMock, $this->quote->getQuote());
    }
}


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

namespace Arbitrader.GW2API.Model
{
    public class CraftStep : AcquisitionStep
    {
        public Dictionary<Item, IEnumerable<AcquisitionStep>> IngredientSteps { get; set; }

        public CraftStep(Recipe recipe, int count) : base(recipe.OutputItem, count)
        {
            IngredientSteps = new Dictionary<Item, IEnumerable<AcquisitionStep>>();

            foreach (var ingredient in recipe.Ingredients)
                IngredientSteps.Add(ingredient.Key, ingredient.Key.GetAcquisitionSteps(ingredient.Value * count));
        }

        public override int? GetBestPrice()
        {
            return GetBestSteps()?.Select(s => s.GetBestPrice())?.Sum();
        }

        public override IEnumerable<AcquisitionStep> GetBestSteps()
        {
            foreach (var ingredient in IngredientSteps)
                yield return ingredient.Value.MinimizeOn(s => s.GetBestPrice());
        }

        public override string ToString()
        {
            return ToString("");
        }

        public override string ToString(string prepend)
        {
            var sb = new StringBuilder($"{prepend}{base.ToString()} | Action: Craft");

            foreach (var step in GetBestSteps())
                sb.Append($"\r\n{step.ToString($"{prepend}  ")}");

            return sb.ToString();
        }
    }
}


text:
define(function () {
    'use strict'

    return {
        /**
         * Define a a test-double using requirejs-define, as a jasmine spy
         * Using either methods explicitly stated or implicit (requires module to exist)
         *
         * @param {string} requiredModule - ID of module to define test double for
         * @param {array|null} requiredMethods - Array of methods to define, null means mimic real object
         * @param {string} DOUBLES_PREFIX - e.g. 'double/'
         */
        defineDouble: function defineDouble(requiredModule, requiredMethods, DOUBLES_PREFIX) {
            if (null === requiredMethods) {
                define(DOUBLES_PREFIX + requiredModule, [requiredModule], function (module) {
                    return jasmine.createSpyObj(requiredModule, Object.keys(module));
                });
            } else if (requiredMethods.length > 0) {
                define(DOUBLES_PREFIX + requiredModule, function () {
                    return jasmine.createSpyObj(requiredModule, requiredMethods);
                });
            } else {
                define(DOUBLES_PREFIX + requiredModule, function () {
                    return jasmine.createSpy(requiredModule);
                });
            }
        }
    }
});


text:
package org.apache.isis.viewer.html.task;

import org.apache.isis.applib.profiles.Localization;
import org.apache.isis.core.commons.debug.DebugBuilder;
import org.apache.isis.core.metamodel.adapter.ObjectAdapter;
import org.apache.isis.core.metamodel.facets.object.bounded.BoundedFacetUtils;
import org.apache.isis.core.metamodel.facets.object.parseable.InvalidEntryException;
import org.apache.isis.core.metamodel.facets.object.parseable.ParseableFacet;
import org.apache.isis.core.metamodel.facets.object.parseable.TextEntryParseException;
import org.apache.isis.core.metamodel.spec.ObjectSpecification;
import org.apache.isis.core.progmodel.facets.value.password.PasswordValueFacet;
import org.apache.isis.core.runtime.system.context.IsisContext;
import org.apache.isis.viewer.html.component.Page;
import org.apache.isis.viewer.html.context.Context;
import org.apache.isis.viewer.html.request.Request;

/**
 * Represents a task that the user is working through. Is used for both editing
 * objects and setting up parameters for an action method.
 */
public abstract class Task {

    private static int nextID = 1;
    private int[] boundaries;
    private final String description;
    protected final String[] errors;
    protected String error;
    private final String[] entryText;
    protected final ObjectAdapter[] initialState;
    private final String name;
    protected final String[] names;
    protected final String[] descriptions;
    protected final boolean[] optional;
    protected final boolean[] readOnly;
    protected final int numberOfEntries;
    private int step;
    private final String targetId;
    protected final ObjectSpecification[] fieldSpecifications;
    protected final int[] noLines;
    protected final boolean[] wraps;
    protected final int[] maxLength;
    protected final int[] typicalLength;
    protected final int id = nextID++;

    public Task(final Context context, final String name, final String description, final ObjectAdapter target, final int noFields) {
        this.name = name;
        this.description = description;
        targetId = context.mapObject(target);

        initialState = new ObjectAdapter[noFields];
        names = new String[noFields];
        descriptions = new String[noFields];
        optional = new boolean[noFields];
        readOnly = new boolean[noFields];
        fieldSpecifications = new ObjectSpecification[noFields];

        numberOfEntries = noFields;
        entryText = new String[noFields];
        errors = new String[noFields];

        noLines = new int[noFields];
        wraps = new boolean[noFields];
        maxLength = new int[noFields];
        typicalLength = new int[noFields];
    }

    public void init(final Context context) {
        for (int i = 0; i < entryText.length; i++) {
            final ObjectAdapter obj = initialState[i];
            if (obj == null) {
                entryText[i] = "";
            } else if (obj.getSpecification().getFacet(PasswordValueFacet.class) != null) {
                final PasswordValueFacet facet = obj.getSpecification().getFacet(PasswordValueFacet.class);
                entryText[i] = facet.getEditText(obj);
            } else if (obj.getSpecification().isParseable()) {
                entryText[i] = obj.titleString();
            } else if (obj.getSpecification().isNotCollection()) {
                if (readOnly[i]) {
                    entryText[i] = (obj).titleString();
                } else {
                    entryText[i] = context.mapObject(obj);
                }
            } else if (obj.getSpecification().isParentedOrFreeCollection()) {
                entryText[i] = (obj).titleString();
            }
        }

        divyUpWork();
    }

    public abstract ObjectAdapter completeTask(Context context, Page page);

    private void copyForThisStep(final Object[] source, final Object[] destination) {
        for (int i = 0; i < noOfEntriesInThisStep(); i++) {
            destination[i] = source[firstEntryInThisStep() + i];
        }
    }

    private void copyForThisStep(final boolean[] source, final boolean[] destination) {
        for (int i = 0; i < noOfEntriesInThisStep(); i++) {
            destination[i] = source[firstEntryInThisStep() + i];
        }
    }

    private void copyForThisStep(final int[] source, final int[] destination) {
        for (int i = 0; i < noOfEntriesInThisStep(); i++) {
            destination[i] = source[firstEntryInThisStep() + i];
        }
    }

    public void checkInstances(final Context context, final ObjectAdapter[] objects) {
    }

    public void debug(final DebugBuilder debug) {
        debug.indent();
        debug.appendln("name", name);
        debug.appendln("number of steps ", numberOfSteps());
        debug.appendln("current step", step);
        debug.appendln("target", targetId);
        debug.appendln("steps (" + (boundaries.length - 1) + ")");
        debug.indent();
        for (int i = 0; i < boundaries.length - 1; i++) {
            debug.appendln("    " + (i + 1) + ". " + boundaries[i] + " - " + (boundaries[i + 1] - 1));
        }
        debug.unindent();
        debug.appendln("fields (" + names.length + ")");
        debug.indent();
        for (int i = 0; i < names.length; i++) {
            final String status = (readOnly[i] ? "R" : "-") + (optional[i] ? "O" : "M") + (errors[i] == null ? "-" : "E");
            debug.appendln("    " + i + "  " + names[i] + " (" + status + "):  " + fieldSpecifications[i].getFullIdentifier() + " -> " + entryText[i]);
        }
        debug.unindent();
        debug.unindent();
    }

    private void divyUpWork() {
        if (numberOfEntries == 0) {
            boundaries = new int[2];
        } else {
            final int[] b = new int[numberOfEntries + 2];
            int count = 0;
            b[count++] = 0;

            ObjectSpecification type = fieldSpecifications[0];
            boolean direct = simpleField(type, 0);

            for (int i = 1; i < numberOfEntries; i++) {
                type = fieldSpecifications[i];
                if (true || direct && (simpleField(type, i))) {
                    continue;
                }
                b[count++] = i;
                direct = simpleField(type, i);
            }
            b[count++] = numberOfEntries;
            boundaries = new int[count];
            System.arraycopy(b, 0, boundaries, 0, count);
        }
    }

    protected boolean simpleField(final ObjectSpecification specification, final int i) {
        return readOnly[i] || (specification.isNotCollection() && BoundedFacetUtils.isBoundedSet(specification));
    }

    private int firstEntryInThisStep() {
        return boundaries[step];
    }

    public String getDescription() {
        return description;
    }

    public String getError() {
        return error;
    }

    /**
     * Returns an array of errors, one for each element in the task.
     */
    public String[] getErrors() {
        final String[] array = new String[noOfEntriesInThisStep()];
        copyForThisStep(errors, array);
        return array;
    }

    public String[] getFieldDescriptions() {
        final String[] array = new String[noOfEntriesInThisStep()];
        copyForThisStep(descriptions, array);
        return array;
    }

    public String[] getEntryText() {
        final String[] array = new String[noOfEntriesInThisStep()];
        copyForThisStep(entryText, array);
        return array;
    }

    public String getName() {
        return name;
    }

    public String[] getNames() {
        final String[] array = new String[noOfEntriesInThisStep()];
        copyForThisStep(names, array);
        return array;
    }

    public ObjectAdapter[][] getOptions(final Context context) {
        return getOptions(context, firstEntryInThisStep(), noOfEntriesInThisStep());
    }

    protected ObjectAdapter[][] getOptions(final Context context, final int from, final int len) {
        return new ObjectAdapter[len][];
    }

    protected ObjectAdapter[] getEntries(final Context context) {
        final ObjectAdapter[] entries = new ObjectAdapter[entryText.length];
        for (int i = 0; i < entries.length; i++) {
            if (entryText == null || readOnly[i]) {
                continue;
            }
            final ObjectSpecification fieldSpecification = fieldSpecifications[i];
            if (fieldSpecification.isParseable()) {
                final ParseableFacet parser = fieldSpecification.getFacet(ParseableFacet.class);
                try {
                    Localization localization = IsisContext.getLocalization();
                    entries[i] = parser.parseTextEntry(initialState[i], entryText[i], localization);
                } catch (final InvalidEntryException e) {
                    errors[i] = e.getMessage();
                } catch (final TextEntryParseException e) {
                    errors[i] = e.getMessage();
                }
            } else if (fieldSpecification.isNotCollection() && entryText[i] != null) {
                if (entryText[i].equals("null")) {
                    entries[i] = null;
                } else {
                    entries[i] = context.getMappedObject(entryText[i]);
                }
            }
        }
        return entries;
    }

    public String getId() {
        return "" + id;
    }

    public boolean[] getOptional() {
        final boolean[] array = new boolean[noOfEntriesInThisStep()];
        copyForThisStep(optional, array);
        return array;
    }

    public int[] getNoLines() {
        final int[] array = new int[noOfEntriesInThisStep()];
        copyForThisStep(noLines, array);
        return array;
    }

    public boolean[] getWraps() {
        final boolean[] array = new boolean[noOfEntriesInThisStep()];
        copyForThisStep(wraps, array);
        return array;
    }

    public int[] getMaxLength() {
        final int[] array = new int[noOfEntriesInThisStep()];
        copyForThisStep(maxLength, array);
        return array;
    }

    public int[] getTypicalLength() {
        final int[] array = new int[noOfEntriesInThisStep()];
        copyForThisStep(typicalLength, array);
        return array;
    }

    public boolean[] getReadOnly() {
        final boolean[] array = new boolean[noOfEntriesInThisStep()];
        copyForThisStep(readOnly, array);
        return array;
    }

    public int getStep() {
        return step;
    }

    public ObjectAdapter getTarget(final Context context) {
        return context.getMappedObject(targetId);
    }

    public String[] getTrail() {
        final String[] trail = new String[boundaries.length - 1];
        for (int i = 0; i < trail.length; i++) {
            trail[i] = "step " + i;
        }
        return trail;
    }

    public ObjectSpecification[] getTypes() {
        final ObjectSpecification[] array = new ObjectSpecification[noOfEntriesInThisStep()];
        copyForThisStep(fieldSpecifications, array);
        return array;
    }

    public boolean isEditing() {
        return false;
    }

    public void nextStep() {
        step++;
    }

    private int noOfEntriesInThisStep() {
        return boundaries[step + 1] - boundaries[step];
    }

    public int numberOfSteps() {
        return boundaries.length - 1;
    }

    public void previousStep() {
        step--;
    }

    public void setFromFields(final Request request, final Context context) {
        int fldNo = 0;
        for (int i = boundaries[step]; i < boundaries[step + 1]; i++) {
            String textEntry = request.getFieldEntry(fldNo++);
            if (readOnly[i]) {
                continue;
            }
            final ObjectSpecification spec = fieldSpecifications[i];
            // deal with check boxes specially: expect 'true' if checked and no
            // entry if not checked, hence
            // need to set as 'false'
            if (spec.isOfType(IsisContext.getSpecificationLoader().loadSpecification(boolean.class)) || spec.isOfType(IsisContext.getSpecificationLoader().loadSpecification(Boolean.class))) {
                if (textEntry == null || !textEntry.equals("true")) {
                    textEntry = "false";
                }
            }
            entryText[i] = textEntry;
            try {
                errors[i] = null;
                setFromField(context, i, spec, textEntry);
                if (!optional[i] && (textEntry == null || textEntry.equals(""))) {
                    errors[i] = "Field required";
                }
            } catch (final InvalidEntryException e) {
                errors[i] = e.getMessage();
            } catch (final TextEntryParseException e) {
                errors[i] = e.getMessage();
            }
        }
    }

    private void setFromField(final Context context, final int i, final ObjectSpecification spec, final String textEntry) {
        if (spec.isParseable()) {
            if (textEntry == null) {
                return;
            }
            // REVIEW this block uses the existing adapter as it contains the
            // regex needed. This needs to
            // be reviewed in line with Dan's proposed changes to the reflector.
            final ObjectAdapter valueAdapter = initialState[i];
            final ParseableFacet parser = spec.getFacet(ParseableFacet.class);
            Localization localization = IsisContext.getLocalization();
            parser.parseTextEntry(valueAdapter, textEntry, localization);
            // REVIEW what do we do when an exception is thrown - a parse fails?
        }
    }

    public abstract void checkForValidity(Context context);

}


text:
"use strict";
const fs = require('fs');
const path = require('path');

function mkdirSyncRecursively(dir, mode) {
    try {
        var result = fs.mkdirSync(dir, mode);
    }
    catch(e) {
        if(e.code === 'ENOENT') {
            mkdirSyncRecursively(path.dirname(dir), mode);  // if does not exists, create all parents recursively
            mkdirSyncRecursively(dir, mode);   // retry
        }
    }
}

function createDirectoryIfNotExists(dir) {
	try {
		fs.accessSync(dir, fs.F_OK);
	}
	catch(e) {
		// create directory if not exists
		mkdirSyncRecursively(dir, '0755');
	}
}

module.exports = {
    mkdirSyncRecursively: mkdirSyncRecursively,
    createDirectoryIfNotExists: createDirectoryIfNotExists
};


text:
namespace NEventStore
{
    using System;
    using NEventStore.Persistence;

    /// <summary>
    ///     Indicates the ability to store and retreive a stream of events.
    /// </summary>
    /// <remarks>
    ///     Instances of this class must be designed to be multi-thread safe such that they can be shared between threads.
    /// </remarks>
    public interface IStoreEvents : IDisposable
    {
        /// <summary>
        ///     Gets a reference to the underlying persistence engine which allows direct access to persistence operations.
        /// </summary>
        IPersistStreams Advanced { get; }

        /// <summary>
        ///     Creates a new stream.
        /// </summary>
        /// <param name="bucketId">The value which uniquely identifies bucket the stream belongs to.</param>
        /// <param name="streamId">The value which uniquely identifies the stream within the bucket to be created.</param>
        /// <returns>An empty stream.</returns>
        IEventStream CreateStream(string bucketId, string streamId);

        /// <summary>
        ///     Reads the stream indicated from the minimum revision specified up to the maximum revision specified or creates
        ///     an empty stream if no commits are found and a minimum revision of zero is provided.
        /// </summary>
        /// <param name="bucketId">The value which uniquely identifies bucket the stream belongs to.</param>
        /// <param name="streamId">The value which uniquely identifies the stream in the bucket from which the events will be read.</param>
        /// <param name="minRevision">The minimum revision of the stream to be read.</param>
        /// <param name="maxRevision">The maximum revision of the stream to be read.</param>
        /// <returns>A series of committed events represented as a stream.</returns>
        /// <exception cref="StorageException" />
        /// <exception cref="StorageUnavailableException" />
        /// <exception cref="StreamNotFoundException" />
        IEventStream OpenStream(string bucketId, string streamId, int minRevision, int maxRevision);

        /// <summary>
        ///     Reads the stream indicated from the point of the snapshot forward until the maximum revision specified.
        /// </summary>
        /// <param name="snapshot">The snapshot of the stream to be read.</param>
        /// <param name="maxRevision">The maximum revision of the stream to be read.</param>
        /// <returns>A series of committed events represented as a stream.</returns>
        /// <exception cref="StorageException" />
        /// <exception cref="StorageUnavailableException" />
        IEventStream OpenStream(ISnapshot snapshot, int maxRevision);
    }
}


text:
import { Dependencies, DependencyManifest, DependenciesMeta } from '@pnpm/types'
import pickBy from 'ramda/src/pickBy'

export interface WantedDependency {
  alias: string
  pref: string // package reference
  dev: boolean
  optional: boolean
  injected?: boolean
}

export function getNonDevWantedDependencies (pkg: Pick<DependencyManifest, 'bundleDependencies' | 'optionalDependencies' | 'dependencies' | 'dependenciesMeta'>) {
  const bd = pkg.bundleDependencies ?? pkg.bundleDependencies
  const bundledDeps = new Set(Array.isArray(bd) ? bd : [])
  const filterDeps = getNotBundledDeps.bind(null, bundledDeps)
  return getWantedDependenciesFromGivenSet(
    filterDeps({ ...pkg.optionalDependencies, ...pkg.dependencies }),
    {
      dependenciesMeta: pkg.dependenciesMeta ?? {},
      devDependencies: {},
      optionalDependencies: pkg.optionalDependencies ?? {},
    }
  )
}

function getWantedDependenciesFromGivenSet (
  deps: Dependencies,
  opts: {
    devDependencies: Dependencies
    optionalDependencies: Dependencies
    dependenciesMeta: DependenciesMeta
  }
): WantedDependency[] {
  if (!deps) return []
  return Object.entries(deps).map(([alias, pref]) => ({
    alias,
    dev: !!opts.devDependencies[alias],
    injected: opts.dependenciesMeta[alias]?.injected,
    optional: !!opts.optionalDependencies[alias],
    pref,
  }))
}

function getNotBundledDeps (bundledDeps: Set<string>, deps: Dependencies): Record<string, string> {
  return pickBy((_, depName) => !bundledDeps.has(depName), deps)
}


text:
namespace Codisa.InterwayDocs.Business
{
    public partial class OutgoingBook
    {

        #region OnDeserialized actions

        /*/// <summary>
        /// This method is called on a newly deserialized object
        /// after deserialization is complete.
        /// </summary>
        protected override void OnDeserialized()
        {
            base.OnDeserialized();
            // add your custom OnDeserialized actions here.
        }*/

        #endregion

    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Phyllosticta valerianae-tripteris f. minor Unamuno

### Remarks
null


text:
using System;
using osu.Framework.Allocation;
using osu.Framework.Extensions.Color4Extensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Cursor;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Localisation;
using osu.Game.Graphics.Sprites;
using osu.Game.Graphics.UserInterface;
using osu.Game.Overlays;
using osuTK;
using osuTK.Graphics;

namespace osu.Game.Screens.Edit.Components.RadioButtons
{
    public class EditorRadioButton : OsuButton, IHasTooltip
    {
        /// <summary>
        /// Invoked when this <see cref="EditorRadioButton"/> has been selected.
        /// </summary>
        public Action<RadioButton> Selected;

        public readonly RadioButton Button;

        private Color4 defaultBackgroundColour;
        private Color4 defaultIconColour;
        private Color4 selectedBackgroundColour;
        private Color4 selectedIconColour;

        private Drawable icon;

        [Resolved(canBeNull: true)]
        private EditorBeatmap editorBeatmap { get; set; }

        public EditorRadioButton(RadioButton button)
        {
            Button = button;

            Text = button.Label;
            Action = button.Select;

            RelativeSizeAxes = Axes.X;
        }

        [BackgroundDependencyLoader]
        private void load(OverlayColourProvider colourProvider)
        {
            defaultBackgroundColour = colourProvider.Background3;
            selectedBackgroundColour = colourProvider.Background1;

            defaultIconColour = defaultBackgroundColour.Darken(0.5f);
            selectedIconColour = selectedBackgroundColour.Lighten(0.5f);

            Add(icon = (Button.CreateIcon?.Invoke() ?? new Circle()).With(b =>
            {
                b.Blending = BlendingParameters.Additive;
                b.Anchor = Anchor.CentreLeft;
                b.Origin = Anchor.CentreLeft;
                b.Size = new Vector2(20);
                b.X = 10;
            }));
        }

        protected override void LoadComplete()
        {
            base.LoadComplete();

            Button.Selected.ValueChanged += selected =>
            {
                updateSelectionState();
                if (selected.NewValue)
                    Selected?.Invoke(Button);
            };

            editorBeatmap?.HasTiming.BindValueChanged(hasTiming => Button.Selected.Disabled = !hasTiming.NewValue, true);

            Button.Selected.BindDisabledChanged(disabled => Enabled.Value = !disabled, true);
            updateSelectionState();
        }

        private void updateSelectionState()
        {
            if (!IsLoaded)
                return;

            BackgroundColour = Button.Selected.Value ? selectedBackgroundColour : defaultBackgroundColour;
            icon.Colour = Button.Selected.Value ? selectedIconColour : defaultIconColour;
        }

        protected override SpriteText CreateText() => new OsuSpriteText
        {
            Depth = -1,
            Origin = Anchor.CentreLeft,
            Anchor = Anchor.CentreLeft,
            X = 40f
        };

        public LocalisableString TooltipText => Enabled.Value ? string.Empty : "Add at least one timing point first!";
    }
}


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

namespace Tools.VisualStudio
{
    class SolutionDirectory : SolutionItem
    {
    }
}


text:
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>W29093_text</title>
        <link rel="stylesheet" type="text/css" href="style.css" />

                «

    <p class="styleSans11.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">TABLE OF CONTENTS

    <p class="styleSans8.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">

    <p class="styleSans8.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">

    <p class="styleSans8.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">III.

    <p class="styleSans8.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">vam

    <p class="styleSans8.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">

    <p class="styleSans8.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">IX.

    <p class="styleSans8.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">


text:
<?php

namespace Magmanite\Db\Driver;

use \Magmanite\Db\Exception\DriverException;

/**
 * MySQL DBAL driver
 *
 * @author Hendri Kurniawan <hendri@kurniawan.id.au>
 */
class Mysql extends \Magmanite\Db\Driver\AbstractDriver {
// -----------------------------------------------------------------------------
// Implements abstract methods from AbstractDriver class
// -----------------------------------------------------------------------------
    /**
     * (non-PHPdoc)
     * @see \Magmanite\Db\Driver\AbstractDriver::_connect()
     */
    protected function _connect(\Magmanite\Db\Dsn $dsn) {
        try {
            $res = @new \mysqli(
                $dsn->getDatabaseServerHost(),
                $dsn->getUsername(),
                $dsn->getPassword(),
                $dsn->getDatabaseName(),
                $dsn->getDatabaseServerPort());

            if ($res->connect_error) {
                throw new DriverException('Cannot connect to database: '
                    . $res->connect_error . ' (' . $res->connect_errno . ')');
            }

            return $res;
        } catch (\Exception $e) {
            if ($e instanceof DriverException) {
                throw $e;
            }

            throw new DriverException('Cannot connect to database: '
                . $e->getMessage(), DriverException::CANNOT_CONNECT);
        }
    }

    /**
     * (non-PHPdoc)
     * @see \Magmanite\Db\Driver\AbstractDriver::_disconnect()
     */
    protected function _disconnect($dbh) {
        if (!($dbh instanceof \mysqli)) {
            throw new DriverException('Unknown DBH.', DriverException::INVALID_DATABASE_CONNECTION);
        }

        try {
            $dbh->close();
        } catch (\Exception $e) {
            throw new DriverException('Cannot close database connection: '
                . $e->getMessage(), DriverException::CANNOT_CONNECT);
        }
    }

    /**
     * (non-PHPdoc)
     * @see \Magmanite\Db\Driver\AbstractDriver::_query()
     */
    protected function _query($dbh, $sql) {
        try {
            $result = $dbh->query($sql, MYSQLI_STORE_RESULT);

            if ($result === false) {
                return new \Magmanite\Db\Result\Mysql(null, false, false, $dbh->errno, $dbh->error);
            }

            return new \Magmanite\Db\Result\Mysql($this, $result);
        } catch (\Exception $e) {
            throw new DriverException(
                'Cannot query database: ' . $e->getMessage(),
                DriverException::CANNOT_QUERY_DATABASE,
                $e);
        }
    }

    /**
     * (non-PHPdoc)
     * @see \Magmanite\Db\Driver\AbstractDriver::_queryUnbuffered()
     */
    protected function _queryUnbuffered($dbh, $sql) {
        try {
            $result = $dbh->query($sql, MYSQLI_USE_RESULT);

            if ($result === false) {
                return new \Magmanite\Db\Result\Mysql(null, false, true, $dbh->errno, $dbh->error);
            }

            return new \Magmanite\Db\Result\Mysql($this, $result, true);
        } catch (\Exception $e) {
            throw new DriverException(
                'Cannot query database: ' . $e->getMessage(),
                DriverException::CANNOT_QUERY_DATABASE,
                $e);
        }
    }

    /**
     * (non-PHPdoc)
     * @see \Magmanite\Db\Driver\AbstractDriver::_escape()
     */
    protected function _escape($dbh, $value) {
        return $dbh->real_escape_string($value);
    }
// -----------------------------------------------------------------------------
}


text:
package io.cattle.platform.schema.processor;

import io.github.ibuildthecloud.gdapi.model.impl.SchemaImpl;

public class SchemaOverlayImpl extends SchemaImpl {

    private static final long serialVersionUID = -7324841846559047697L;

    boolean resourceFieldsExplicit;
    boolean resourceActionsExplicit;
    boolean collectionActionsExplicit;
    boolean collectionFieldsExplicit;
    boolean collectionFiltersExplicit;

    public boolean isResourceFieldsExplicit() {
        return resourceFieldsExplicit;
    }

    public void setResourceFieldsExplicit(boolean resourceFieldsExplicit) {
        this.resourceFieldsExplicit = resourceFieldsExplicit;
    }

    public boolean isResourceActionsExplicit() {
        return resourceActionsExplicit;
    }

    public void setResourceActionsExplicit(boolean resourceActionsExplicit) {
        this.resourceActionsExplicit = resourceActionsExplicit;
    }

    public boolean isCollectionActionsExplicit() {
        return collectionActionsExplicit;
    }

    public void setCollectionActionsExplicit(boolean collectionActionsExplicit) {
        this.collectionActionsExplicit = collectionActionsExplicit;
    }

    public boolean isCollectionFieldsExplicit() {
        return collectionFieldsExplicit;
    }

    public void setCollectionFieldsExplicit(boolean collectionFieldsExplicit) {
        this.collectionFieldsExplicit = collectionFieldsExplicit;
    }

    public boolean isCollectionFiltersExplicit() {
        return collectionFiltersExplicit;
    }

    public void setCollectionFiltersExplicit(boolean collectionFiltersExplicit) {
        this.collectionFiltersExplicit = collectionFiltersExplicit;
    }

}


text:
import { Component, OnInit, ViewEncapsulation, ChangeDetectionStrategy } from '@angular/core';

import { LoggerService } from 'app/core/shared/services/logger.service';

@Component({
  templateUrl: './page-not-found.component.html',
  styleUrls: [ './page-not-found.component.scss' ],
  encapsulation: ViewEncapsulation.Emulated,
  changeDetection: ChangeDetectionStrategy.Default
})
export class PageNotFoundComponent implements OnInit {

  constructor(private logger: LoggerService) { }

  ngOnInit() {
    this.logger.log('[Layout.PageNotFoundComponent] Initialized!', this);
  }

}


text:
#include <gtest/gtest.h>
#include <array>
#include <memory>
#include "Map.hpp"

struct MapTest : public ::testing::Test {
  std::shared_ptr<Map> setmap = std::make_shared<Map>();
};

/**
 *@brief This test will verify if the size of the map is 10-by-10, and for each
 * map, it can laod them properly
 */
TEST_F(MapTest, LoadMapSwitchTest) {
  EXPECT_EQ(10, (setmap->getGridmap(1)).size());
  EXPECT_FALSE((setmap->getGridmap(1)).empty());
  EXPECT_FALSE((setmap->getGridmap(2)).empty());
  EXPECT_FALSE((setmap->getGridmap(3)).empty());
  EXPECT_FALSE((setmap->getGridmap(4)).empty());
}

/**
 *@brief This test will verify if it can set the start node
 */
TEST_F(MapTest, SetstartTest) {
  EXPECT_EQ(std::make_pair(2, 3), setmap->SetStart(2, 3));
}

/**
 *@brief This test will verify if it can set the goal node
 */
TEST_F(MapTest, SetgoalTest) {
  EXPECT_EQ(std::make_pair(4, 6), setmap->SetGoal(4, 6));
}


text:
class CreateTangPlans < ActiveRecord::Migration
  def change
    create_table :tang_plans do |t|
      t.string :stripe_id
      t.integer :amount
      t.string :currency
      t.string :interval
      t.integer :interval_count
      t.string :name
      t.string :statement_descriptor
      t.integer :trial_period_days
      t.integer :order
      t.boolean :highlight, null: false, default: false
      t.text :features
      t.text :description

      t.timestamps null: false
    end
  end
end


text:
/*jshint node:true*/
/*global describe, before, it, after*/

"use strict";

var fs = require("fs");
var path = require("path");
var colors = require("colors");
var cwd = process.cwd();

var nexpect = require("nexpect");
var grunt = require("grunt");

describe("grunt-modernizr", function () {
	it("should find all available tests in project", function (done) {
		nexpect.spawn("grunt", ["modernizr"], {
			stripColors: true,
			verbose: true
		})
		.expect('Running "modernizr:dist" (modernizr) task')

		.expect("Enabled Extras")
		.expect(">> shiv")
		.expect(">> load")
		.expect(">> cssclasses")

		.expect("Looking for Modernizr references")

		.expect("in lib/modulizr.js")
		.expect(">> testallprops")
		.expect(">> prefixed")
		.expect(">> mq")
		.expect(">> testbundle")
		.expect(">> canvas")
		.expect(">> webgl")

		.expect("in test/css/indented-syntax.sass")
		.expect(">> canvastext")
		.expect(">> csstransforms3d")
		.expect(">> flexbox")
		.expect(">> cssgradients")
		.expect(">> opacity")
		.expect(">> indexedDB")
		.expect(">> backgroundsize")
		.expect(">> borderimage")
		.expect(">> borderradius")
		.expect(">> boxshadow")
		.expect(">> cssanimations")
		.expect(">> csscolumns")
		.expect(">> cssreflections")
		.expect(">> csstransitions")
		.expect(">> testallprops")
		.expect(">> prefixed")
		.expect(">> csstransforms")
		.expect(">> mq")
		.expect(">> hashchange")
		.expect(">> draganddrop")
		.expect(">> generatedcontent")
		.expect(">> svg")
		.expect(">> inlinesvg")
		.expect(">> smil")
		.expect(">> svgclippaths")
		.expect(">> input")
		.expect(">> inputtypes")
		.expect(">> touch")
		.expect(">> fontface")
		.expect(">> testbundle")
		.expect(">> respond")
		.expect(">> websockets")
		.expect(">> contextmenu")
		.expect(">> emoji")
		.expect(">> json")
		.expect(">> applicationcache")
		.expect(">> audio")
		.expect(">> canvas")
		.expect(">> geolocation")
		.expect(">> history")
		.expect(">> hsla")
		.expect(">> indexeddb")
		.expect(">> localstorage")
		.expect(">> multiplebgs")
		.expect(">> postmessage")
		.expect(">> scriptdefer")
		.expect(">> sessionstorage")
		.expect(">> textshadow")
		.expect(">> rgba")
		.expect(">> video")
		.expect(">> webgl")
		.expect(">> websqldatabase")
		.expect(">> webworkers")

		.expect("in test/css/vanilla.css")
		.expect(">> canvastext")
		.expect(">> csstransforms3d")
		.expect(">> flexbox")
		.expect(">> cssgradients")
		.expect(">> opacity")
		.expect(">> indexedDB")
		.expect(">> backgroundsize")
		.expect(">> borderimage")
		.expect(">> borderradius")
		.expect(">> boxshadow")
		.expect(">> cssanimations")
		.expect(">> csscolumns")
		.expect(">> cssreflections")
		.expect(">> csstransitions")
		.expect(">> testallprops")
		.expect(">> flexboxlegacy")
		.expect(">> prefixed")
		.expect(">> csstransforms")
		.expect(">> mq")
		.expect(">> hashchange")
		.expect(">> draganddrop")
		.expect(">> generatedcontent")
		.expect(">> svg")
		.expect(">> inlinesvg")
		.expect(">> smil")
		.expect(">> svgclippaths")
		.expect(">> input")
		.expect(">> inputtypes")
		.expect(">> touch")
		.expect(">> fontface")
		.expect(">> testbundle")
		.expect(">> respond")
		.expect(">> websockets")
		.expect(">> contextmenu")
		.expect(">> emoji")
		.expect(">> json")
		.expect(">> applicationcache")
		.expect(">> audio")
		.expect(">> canvas")
		.expect(">> geolocation")
		.expect(">> history")
		.expect(">> hsla")
		.expect(">> indexeddb")
		.expect(">> localstorage")
		.expect(">> multiplebgs")
		.expect(">> postmessage")
		.expect(">> scriptdefer")
		.expect(">> sessionstorage")
		.expect(">> textshadow")
		.expect(">> rgba")
		.expect(">> video")
		.expect(">> webgl")
		.expect(">> websqldatabase")
		.expect(">> webworkers")

		.expect("in test/js/amd.js")
		.expect(">> canvastext")
		.expect(">> csstransforms3d")
		.expect(">> flexbox")
		.expect(">> cssgradients")
		.expect(">> opacity")
		.expect(">> indexedDB")
		.expect(">> backgroundsize")
		.expect(">> borderimage")
		.expect(">> borderradius")
		.expect(">> boxshadow")
		.expect(">> cssanimations")
		.expect(">> csscolumns")
		.expect(">> cssreflections")
		.expect(">> csstransitions")
		.expect(">> testallprops")
		.expect(">> flexboxlegacy")
		.expect(">> prefixed")
		.expect(">> csstransforms")
		.expect(">> mq")
		.expect(">> hashchange")
		.expect(">> draganddrop")
		.expect(">> generatedcontent")
		.expect(">> svg")
		.expect(">> inlinesvg")
		.expect(">> smil")
		.expect(">> svgclippaths")
		.expect(">> input")
		.expect(">> inputtypes")
		.expect(">> touch")
		.expect(">> fontface")
		.expect(">> testbundle")
		.expect(">> respond")
		.expect(">> websockets")
		.expect(">> contextmenu")
		.expect(">> emoji")
		.expect(">> json")
		.expect(">> applicationcache")
		.expect(">> audio")
		.expect(">> canvas")
		.expect(">> geolocation")
		.expect(">> history")
		.expect(">> hsla")
		.expect(">> indexeddb")
		.expect(">> localstorage")
		.expect(">> multiplebgs")
		.expect(">> postmessage")
		.expect(">> scriptdefer")
		.expect(">> sessionstorage")
		.expect(">> textshadow")
		.expect(">> rgba")
		.expect(">> video")
		.expect(">> webgl")
		.expect(">> websqldatabase")
		.expect(">> webworkers")

		.expect("in test/js/vanilla.js")
		.expect(">> canvastext")
		.expect(">> csstransforms3d")
		.expect(">> flexbox")
		.expect(">> cssgradients")
		.expect(">> opacity")
		.expect(">> indexedDB")
		.expect(">> backgroundsize")
		.expect(">> borderimage")
		.expect(">> borderradius")
		.expect(">> boxshadow")
		.expect(">> cssanimations")
		.expect(">> csscolumns")
		.expect(">> cssreflections")
		.expect(">> csstransitions")
		.expect(">> testallprops")
		.expect(">> flexboxlegacy")
		.expect(">> prefixed")
		.expect(">> csstransforms")
		.expect(">> mq")
		.expect(">> hashchange")
		.expect(">> draganddrop")
		.expect(">> generatedcontent")
		.expect(">> svg")
		.expect(">> inlinesvg")
		.expect(">> smil")
		.expect(">> svgclippaths")
		.expect(">> input")
		.expect(">> inputtypes")
		.expect(">> touch")
		.expect(">> fontface")
		.expect(">> testbundle")
		.expect(">> respond")
		.expect(">> websockets")
		.expect(">> contextmenu")
		.expect(">> emoji")
		.expect(">> json")
		.expect(">> applicationcache")
		.expect(">> audio")
		.expect(">> canvas")
		.expect(">> geolocation")
		.expect(">> history")
		.expect(">> hsla")
		.expect(">> indexeddb")
		.expect(">> localstorage")
		.expect(">> multiplebgs")
		.expect(">> postmessage")
		.expect(">> scriptdefer")
		.expect(">> sessionstorage")
		.expect(">> textshadow")
		.expect(">> rgba")
		.expect(">> video")
		.expect(">> webgl")
		.expect(">> websqldatabase")
		.expect(">> webworkers")

		.expect("Downloading source files")

		.wait(">> Generating a custom Modernizr build")
		.expect(">> Uglifying")

		.expect(">> Wrote file to build/modernizr-custom.js")
		.run(done);
	});
});

describe("custom builds", function () {
	var Gruntfile = path.join(cwd, "Gruntfile.js");

	var pristine = fs.readFileSync(Gruntfile);
	var gruntfiles = path.join(cwd, "test", "gruntfiles");

	describe("community tests", function () {

		before(function (done) {
			nexpect.spawn("grunt", ["clean"])
			.run(function () {
				var override = fs.readFileSync(path.join(gruntfiles, "Gruntfile.test.js"));
				fs.writeFileSync(Gruntfile, override);

				done();
			});
		});

		it("should fetch community tests", function (done) {
			process.stdout.write("\n\n");

			nexpect.spawn("grunt", ["modernizr"], {
				stripColors: true,
				verbose: true
			})
			.expect('Running "modernizr:dist" (modernizr) task')

			.expect("Enabled Extras")
			.expect(">> shiv")
			.expect(">> load")
			.expect(">> cssclasses")

			.expect("Looking for Modernizr references")

			.expect("in lib/modulizr.js")
			.expect(">> testallprops")
			.expect(">> prefixed")
			.expect(">> mq")
			.expect(">> testbundle")
			.expect(">> canvas")
			.expect(">> webgl")

			.expect("in test/css/indented-syntax.sass")
			.expect(">> canvastext")
			.expect(">> csstransforms3d")
			.expect(">> flexbox")
			.expect(">> cssgradients")
			.expect(">> opacity")
			.expect(">> indexedDB")
			.expect(">> backgroundsize")
			.expect(">> borderimage")
			.expect(">> borderradius")
			.expect(">> boxshadow")
			.expect(">> cssanimations")
			.expect(">> csscolumns")
			.expect(">> cssreflections")
			.expect(">> csstransitions")
			.expect(">> testallprops")
			.expect(">> prefixed")
			.expect(">> csstransforms")
			.expect(">> mq")
			.expect(">> hashchange")
			.expect(">> draganddrop")
			.expect(">> generatedcontent")
			.expect(">> svg")
			.expect(">> inlinesvg")
			.expect(">> smil")
			.expect(">> svgclippaths")
			.expect(">> input")
			.expect(">> inputtypes")
			.expect(">> touch")
			.expect(">> fontface")
			.expect(">> testbundle")
			.expect(">> respond")
			.expect(">> websockets")
			.expect(">> battery")
			.expect(">> contextmenu")
			.expect(">> emoji")
			.expect(">> filereader")
			.expect(">> placeholder")
			.expect(">> json")
			.expect(">> scriptdefer")
			.expect(">> applicationcache")
			.expect(">> audio")
			.expect(">> canvas")
			.expect(">> geolocation")
			.expect(">> history")
			.expect(">> hsla")
			.expect(">> indexeddb")
			.expect(">> localstorage")
			.expect(">> multiplebgs")
			.expect(">> postmessage")
			.expect(">> sessionstorage")
			.expect(">> textshadow")
			.expect(">> rgba")
			.expect(">> video")
			.expect(">> webgl")
			.expect(">> websqldatabase")
			.expect(">> webworkers")

			.expect("in test/css/vanilla.css")
			.expect(">> canvastext")
			.expect(">> csstransforms3d")
			.expect(">> flexbox")
			.expect(">> cssgradients")
			.expect(">> opacity")
			.expect(">> indexedDB")
			.expect(">> backgroundsize")
			.expect(">> borderimage")
			.expect(">> borderradius")
			.expect(">> boxshadow")
			.expect(">> cssanimations")
			.expect(">> csscolumns")
			.expect(">> cssreflections")
			.expect(">> csstransitions")
			.expect(">> testallprops")
			.expect(">> flexboxlegacy")
			.expect(">> prefixed")
			.expect(">> csstransforms")
			.expect(">> mq")
			.expect(">> hashchange")
			.expect(">> draganddrop")
			.expect(">> generatedcontent")
			.expect(">> svg")
			.expect(">> inlinesvg")
			.expect(">> smil")
			.expect(">> svgclippaths")
			.expect(">> input")
			.expect(">> inputtypes")
			.expect(">> touch")
			.expect(">> fontface")
			.expect(">> testbundle")
			.expect(">> respond")
			.expect(">> websockets")
			.expect(">> battery")
			.expect(">> contextmenu")
			.expect(">> emoji")
			.expect(">> filereader")
			.expect(">> placeholder")
			.expect(">> json")
			.expect(">> scriptdefer")
			.expect(">> applicationcache")
			.expect(">> audio")
			.expect(">> canvas")
			.expect(">> geolocation")
			.expect(">> history")
			.expect(">> hsla")
			.expect(">> indexeddb")
			.expect(">> localstorage")
			.expect(">> multiplebgs")
			.expect(">> postmessage")
			.expect(">> sessionstorage")
			.expect(">> textshadow")
			.expect(">> rgba")
			.expect(">> video")
			.expect(">> webgl")
			.expect(">> websqldatabase")
			.expect(">> webworkers")

			.expect("in test/js/amd.js")
			.expect(">> canvastext")
			.expect(">> csstransforms3d")
			.expect(">> flexbox")
			.expect(">> cssgradients")
			.expect(">> opacity")
			.expect(">> indexedDB")
			.expect(">> backgroundsize")
			.expect(">> borderimage")
			.expect(">> borderradius")
			.expect(">> boxshadow")
			.expect(">> cssanimations")
			.expect(">> csscolumns")
			.expect(">> cssreflections")
			.expect(">> csstransitions")
			.expect(">> testallprops")
			.expect(">> flexboxlegacy")
			.expect(">> prefixed")
			.expect(">> csstransforms")
			.expect(">> mq")
			.expect(">> hashchange")
			.expect(">> draganddrop")
			.expect(">> generatedcontent")
			.expect(">> svg")
			.expect(">> inlinesvg")
			.expect(">> smil")
			.expect(">> svgclippaths")
			.expect(">> input")
			.expect(">> inputtypes")
			.expect(">> touch")
			.expect(">> fontface")
			.expect(">> testbundle")
			.expect(">> respond")
			.expect(">> websockets")
			.expect(">> battery")
			.expect(">> contextmenu")
			.expect(">> bgrepeatround")
			.expect(">> bgsizecover")
			.expect(">> emoji")
			.expect(">> placeholder")
			.expect(">> json")
			.expect(">> scriptdefer")
			.expect(">> csspositionsticky")
			.expect(">> applicationcache")
			.expect(">> audio")
			.expect(">> canvas")
			.expect(">> geolocation")
			.expect(">> history")
			.expect(">> hsla")
			.expect(">> indexeddb")
			.expect(">> localstorage")
			.expect(">> multiplebgs")
			.expect(">> postmessage")
			.expect(">> sessionstorage")
			.expect(">> textshadow")
			.expect(">> rgba")
			.expect(">> video")
			.expect(">> webgl")
			.expect(">> websqldatabase")
			.expect(">> webworkers")

			.expect("in test/js/vanilla.js")
			.expect(">> canvastext")
			.expect(">> csstransforms3d")
			.expect(">> flexbox")
			.expect(">> cssgradients")
			.expect(">> opacity")
			.expect(">> indexedDB")
			.expect(">> backgroundsize")
			.expect(">> borderimage")
			.expect(">> borderradius")
			.expect(">> boxshadow")
			.expect(">> cssanimations")
			.expect(">> csscolumns")
			.expect(">> cssreflections")
			.expect(">> csstransitions")
			.expect(">> testallprops")
			.expect(">> flexboxlegacy")
			.expect(">> prefixed")
			.expect(">> csstransforms")
			.expect(">> mq")
			.expect(">> hashchange")
			.expect(">> draganddrop")
			.expect(">> generatedcontent")
			.expect(">> svg")
			.expect(">> inlinesvg")
			.expect(">> smil")
			.expect(">> svgclippaths")
			.expect(">> input")
			.expect(">> inputtypes")
			.expect(">> touch")
			.expect(">> fontface")
			.expect(">> testbundle")
			.expect(">> respond")
			.expect(">> websockets")
			.expect(">> battery")
			.expect(">> contextmenu")
			.expect(">> bgrepeatround")
			.expect(">> bgsizecover")
			.expect(">> emoji")
			.expect(">> placeholder")
			.expect(">> json")
			.expect(">> scriptdefer")
			.expect(">> csspositionsticky")
			.expect(">> applicationcache")
			.expect(">> audio")
			.expect(">> canvas")
			.expect(">> geolocation")
			.expect(">> history")
			.expect(">> hsla")
			.expect(">> indexeddb")
			.expect(">> localstorage")
			.expect(">> multiplebgs")
			.expect(">> postmessage")
			.expect(">> sessionstorage")
			.expect(">> textshadow")
			.expect(">> rgba")
			.expect(">> video")
			.expect(">> webgl")
			.expect(">> websqldatabase")
			.expect(">> webworkers")

			.expect("Downloading source files")

			.wait(">> Generating a custom Modernizr build")
			.expect(">> Uglifying")

			.expect(">> Wrote file to build/modernizr-custom.js")
			.run(done);
		});

		after(function () {
			fs.writeFileSync(Gruntfile, pristine);
		});

	});

	describe("prefix test", function () {

		before(function (done) {
			nexpect.spawn("grunt", ["clean"])
			.run(function () {
				var override = fs.readFileSync(path.join(gruntfiles, "Gruntfile.cssclassprefix.js"));
				fs.writeFileSync(Gruntfile, override);

				done();
			});
		});

		it("should honor the specified prefix", function (done) {
			process.stdout.write("\n\n");

			nexpect.spawn("grunt", ["modernizr"], {
				stripColors: true,
				verbose: true
			})
			.expect("Running \"modernizr:dist\" (modernizr) task")

			.expect("Enabled Extras")
			.expect(">> shiv")
			.expect(">> load")
			.expect(">> cssclasses")

			.expect("Enabled Extensibility Options")
			.expect(">> cssclassprefix")

			.expect("Looking for Modernizr references")

			.expect("in test/css/vanilla.css")
			.expect(">> smil")
			.expect(">> input")
			.expect(">> cors")
			.expect(">> filereader")

			.expect("Downloading source files")

			.wait(">> Generating a custom Modernizr build")
			.expect(">> Skipping uglify")

			.expect(">> Wrote file to build/modernizr-custom.js")

			.run(done);
		});

		after(function () {
			fs.writeFileSync(Gruntfile, pristine);
		});

	});

});


text:
title: Prime Number List
localeTitle: Lista de números primos
---
## Lista de números primos

Esto es un talón. [Ayuda a nuestra comunidad a expandirla](https://github.com/freecodecamp/guides/tree/master/src/pages/mathematics/prime-number-list/index.md) .

[Esta guía rápida de estilo ayudará a asegurar que su solicitud de extracción sea aceptada](https://github.com/freecodecamp/guides/blob/master/README.md) .

#### Más información:


text:
<?php

/***************************************************************************
 *
 *	 This program is free software; you can redistribute it and/or modify
 *	 it under the terms of the GNU General Public License as published by
 *	 the Free Software Foundation; either version 2 of the License', or
 *	 ('at your option) any later version.
 *
 ***************************************************************************/

if (!defined('IN_PHPBB')) { die('Hacking attempt'); }

# Debug Level
define('DEBUG', 1); # Debugging off

# User Levels <- Do not change the values of USER or ADMIN
define('DELETED', -1);
define('ANONYMOUS', 1);

define('USER', 1);
define('ADMIN', 2);
define('MOD', 3);

# User related
define('USER_ACTIVATION_NONE', 0);
define('USER_ACTIVATION_SELF', 1);
define('USER_ACTIVATION_ADMIN', 2);

define('USER_AVATAR_NONE', 0);
define('USER_AVATAR_UPLOAD', 1);
define('USER_AVATAR_REMOTE', 2);
define('USER_AVATAR_GALLERY', 3);

# Group settings
define('GROUP_OPEN', 0);
define('GROUP_CLOSED', 1);
define('GROUP_HIDDEN', 2);

# Forum state
define('FORUM_UNLOCKED', 0);
define('FORUM_LOCKED', 1);
define('FORUM_WATCH_NOTIFIED', 1);
define('FORUM_WATCH_UN_NOTIFIED', 0);

# Forum types
define('FORUM_TYPE_REGULAR', 0);
define('FORUM_TYPE_GETLINK', 2);
define('FORUM_TYPE_EXTERNALLINK', 3);

# Topic status
define('TOPIC_UNLOCKED', 0);
define('TOPIC_LOCKED', 1);
define('TOPIC_MOVED', 2);
define('TOPIC_WATCH_NOTIFIED', 1);
define('TOPIC_WATCH_UN_NOTIFIED', 0);

# Topic types
define('POST_NORMAL', 0);
define('POST_STICKY', 1);
define('POST_ANNOUNCE', 2);
define('POST_GLOBAL_ANNOUNCE', 3);

# SQL codes
define('BEGIN_TRANSACTION', 1);
define('END_TRANSACTION', 2);

# Error codes
define('GENERAL_MESSAGE', 200);
define('GENERAL_ERROR', 202);
define('CRITICAL_MESSAGE', 203);
define('BB_CRITICAL_ERROR', 204);

# Private messaging
define('PRIVMSGS_READ_MAIL', 0);
define('PRIVMSGS_NEW_MAIL', 1);
define('PRIVMSGS_SENT_MAIL', 2);
define('PRIVMSGS_SAVED_IN_MAIL', 3);
define('PRIVMSGS_SAVED_OUT_MAIL', 4);
define('PRIVMSGS_UNREAD_MAIL', 5);

# URL PARAMETERS
define('POST_TOPIC_URL', 't');
define('POST_CAT_URL', 'c');
define('POST_FORUM_URL', 'f');
define('POST_USERS_URL', 'u');
define('POST_POST_URL', 'p');
define('POST_GROUPS_URL', 'g');

# Session parameters
define('SESSION_METHOD_COOKIE', 100);
define('SESSION_METHOD_GET', 101);

# Page numbers for session handling
define('PAGE_INDEX', 0);
define('PAGE_LOGIN', -1);
define('PAGE_SEARCH', -2);
define('PAGE_REGISTER', -3);
define('PAGE_PROFILE', -4);
#define('PAGE_VIEWONLINE', -6);
define('PAGE_VIEWMEMBERS', -7);
define('PAGE_FAQ', -8);
define('PAGE_POSTING', -9);
define('PAGE_PRIVMSGS', -10);
define('PAGE_GROUPCP', -11);
define('PAGE_TOPIC_OFFSET', 5000);

# Auth settings
define('AUTH_LIST_ALL', 0);
define('AUTH_ALL', 0);

define('AUTH_REG', 1);
define('AUTH_ACL', 2);
define('AUTH_MOD', 3);
define('AUTH_ADMIN', 5);

define('AUTH_VIEW', 1);
define('AUTH_READ', 2);
define('AUTH_POST', 3);
define('AUTH_REPLY', 4);
define('AUTH_EDIT', 5);
define('AUTH_DELETE', 6);
define('AUTH_ANNOUNCE', 7);
define('AUTH_STICKY', 8);
define('AUTH_POLLCREATE', 9);
define('AUTH_VOTE', 10);
define('AUTH_ATTACH', 11);
define('AUTH_DOWNLOAD', 20);

# Attachment Debug Mode
define('ATTACH_DEBUG', 0);	# Attachment Mod Debugging off
#define('ATTACH_DEBUG', 1);	# Attachment Mod Debugging on

# Download Modes
define('INLINE_LINK', 1);
define('PHYSICAL_LINK', 2);

# Categories
define('NONE_CAT', 0);
define('IMAGE_CAT', 1);
define('STREAM_CAT', 2);
define('SWF_CAT', 3);

# Pages
define('PAGE_UACP', -32);
define('PAGE_RULES', -33);

# Misc
define('MEGABYTE', 1024);
define('ADMIN_MAX_ATTACHMENTS', 50); # Maximum Attachments in Posts or PM's for Admin Users
define('THUMB_DIR', 'thumbs');
define('MODE_THUMBNAIL', 1);

# Forum Extension Group Permissions
define('GPERM_ALL', 0); # ALL FORUMS

# Quota Types
define('QUOTA_UPLOAD_LIMIT', 1);
define('QUOTA_PM_LIMIT', 2);

define('ATTACH_VERSION', '2.3.9');