text:
// Code generated by go-swagger; DO NOT EDIT.

package storage

// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command

import (
	"context"
	"net/http"
	"time"

	"github.com/go-openapi/errors"
	"github.com/go-openapi/runtime"
	cr "github.com/go-openapi/runtime/client"
	"github.com/go-openapi/strfmt"
	"github.com/go-openapi/swag"
)

// NewTopMetricsFileCollectionGetParams creates a new TopMetricsFileCollectionGetParams object,
// with the default timeout for this client.
//
// Default values are not hydrated, since defaults are normally applied by the API server side.
//
// To enforce default values in parameter, use SetDefaults or WithDefaults.
func NewTopMetricsFileCollectionGetParams() *TopMetricsFileCollectionGetParams {
	return &TopMetricsFileCollectionGetParams{
		timeout: cr.DefaultTimeout,
	}
}

// NewTopMetricsFileCollectionGetParamsWithTimeout creates a new TopMetricsFileCollectionGetParams object
// with the ability to set a timeout on a request.
func NewTopMetricsFileCollectionGetParamsWithTimeout(timeout time.Duration) *TopMetricsFileCollectionGetParams {
	return &TopMetricsFileCollectionGetParams{
		timeout: timeout,
	}
}

// NewTopMetricsFileCollectionGetParamsWithContext creates a new TopMetricsFileCollectionGetParams object
// with the ability to set a context for a request.
func NewTopMetricsFileCollectionGetParamsWithContext(ctx context.Context) *TopMetricsFileCollectionGetParams {
	return &TopMetricsFileCollectionGetParams{
		Context: ctx,
	}
}

// NewTopMetricsFileCollectionGetParamsWithHTTPClient creates a new TopMetricsFileCollectionGetParams object
// with the ability to set a custom HTTPClient for a request.
func NewTopMetricsFileCollectionGetParamsWithHTTPClient(client *http.Client) *TopMetricsFileCollectionGetParams {
	return &TopMetricsFileCollectionGetParams{
		HTTPClient: client,
	}
}

/*
TopMetricsFileCollectionGetParams contains all the parameters to send to the API endpoint

	for the top metrics file collection get operation.

	Typically these are written to a http.Request.
*/
type TopMetricsFileCollectionGetParams struct {

	/* Fields.

	   Specify the fields to return.
	*/
	FieldsQueryParameter []string

	/* IopsErrorLowerBound.

	   Filter by iops.error.lower_bound
	*/
	IopsErrorLowerBoundQueryParameter *int64

	/* IopsErrorUpperBound.

	   Filter by iops.error.upper_bound
	*/
	IopsErrorUpperBoundQueryParameter *int64

	/* IopsRead.

	   Filter by iops.read
	*/
	IopsReadQueryParameter *int64

	/* IopsWrite.

	   Filter by iops.write
	*/
	IopsWriteQueryParameter *int64

	/* MaxRecords.

	   Limit the number of records returned.
	*/
	MaxRecordsQueryParameter *int64

	/* MaxRecordsPerVolume.

	   Max records per volume.
	*/
	MaxRecordsPerVolumeQueryParameter *int64

	/* OrderBy.

	   Order results by specified fields and optional [asc|desc] direction. Default direction is 'asc' for ascending.
	*/
	OrderByQueryParameter []string

	/* Path.

	   Filter by path
	*/
	PathQueryParameter *string

	/* ReturnRecords.

	   The default is true for GET calls.  When set to false, only the number of records is returned.

	   Default: true
	*/
	ReturnRecordsQueryParameter *bool

	/* ReturnTimeout.

	   The number of seconds to allow the call to execute before returning.  When iterating over a collection, the default is 15 seconds.  ONTAP returns earlier if either max records or the end of the collection is reached.

	   Default: 15
	*/
	ReturnTimeoutQueryParameter *int64

	/* SvmName.

	   Filter by svm.name
	*/
	SVMNameQueryParameter *string

	/* SvmUUID.

	   Filter by svm.uuid
	*/
	SVMUUIDQueryParameter *string

	/* ThroughputErrorLowerBound.

	   Filter by throughput.error.lower_bound
	*/
	ThroughputErrorLowerBoundQueryParameter *int64

	/* ThroughputErrorUpperBound.

	   Filter by throughput.error.upper_bound
	*/
	ThroughputErrorUpperBoundQueryParameter *int64

	/* ThroughputRead.

	   Filter by throughput.read
	*/
	ThroughputReadQueryParameter *int64

	/* ThroughputWrite.

	   Filter by throughput.write
	*/
	ThroughputWriteQueryParameter *int64

	/* TopMetric.

	   IO activity type

	   Default: "iops.read"
	*/
	TopMetricQueryParameter *string

	/* VolumeName.

	   Filter by volume.name
	*/
	VolumeNameQueryParameter *string

	/* VolumeUUID.

	   Volume UUID
	*/
	VolumeUUIDPathParameter string

	timeout    time.Duration
	Context    context.Context
	HTTPClient *http.Client
}

// WithDefaults hydrates default values in the top metrics file collection get params (not the query body).
//
// All values with no default are reset to their zero value.
func (o *TopMetricsFileCollectionGetParams) WithDefaults() *TopMetricsFileCollectionGetParams {
	o.SetDefaults()
	return o
}

// SetDefaults hydrates default values in the top metrics file collection get params (not the query body).
//
// All values with no default are reset to their zero value.
func (o *TopMetricsFileCollectionGetParams) SetDefaults() {
	var (
		returnRecordsQueryParameterDefault = bool(true)

		returnTimeoutQueryParameterDefault = int64(15)

		topMetricQueryParameterDefault = string("iops.read")
	)

	val := TopMetricsFileCollectionGetParams{
		ReturnRecordsQueryParameter: &returnRecordsQueryParameterDefault,
		ReturnTimeoutQueryParameter: &returnTimeoutQueryParameterDefault,
		TopMetricQueryParameter:     &topMetricQueryParameterDefault,
	}

	val.timeout = o.timeout
	val.Context = o.Context
	val.HTTPClient = o.HTTPClient
	*o = val
}

// WithTimeout adds the timeout to the top metrics file collection get params
func (o *TopMetricsFileCollectionGetParams) WithTimeout(timeout time.Duration) *TopMetricsFileCollectionGetParams {
	o.SetTimeout(timeout)
	return o
}

// SetTimeout adds the timeout to the top metrics file collection get params
func (o *TopMetricsFileCollectionGetParams) SetTimeout(timeout time.Duration) {
	o.timeout = timeout
}

// WithContext adds the context to the top metrics file collection get params
func (o *TopMetricsFileCollectionGetParams) WithContext(ctx context.Context) *TopMetricsFileCollectionGetParams {
	o.SetContext(ctx)
	return o
}

// SetContext adds the context to the top metrics file collection get params
func (o *TopMetricsFileCollectionGetParams) SetContext(ctx context.Context) {
	o.Context = ctx
}

// WithHTTPClient adds the HTTPClient to the top metrics file collection get params
func (o *TopMetricsFileCollectionGetParams) WithHTTPClient(client *http.Client) *TopMetricsFileCollectionGetParams {
	o.SetHTTPClient(client)
	return o
}

// SetHTTPClient adds the HTTPClient to the top metrics file collection get params
func (o *TopMetricsFileCollectionGetParams) SetHTTPClient(client *http.Client) {
	o.HTTPClient = client
}

// WithFieldsQueryParameter adds the fields to the top metrics file collection get params
func (o *TopMetricsFileCollectionGetParams) WithFieldsQueryParameter(fields []string) *TopMetricsFileCollectionGetParams {
	o.SetFieldsQueryParameter(fields)
	return o
}

// SetFieldsQueryParameter adds the fields to the top metrics file collection get params
func (o *TopMetricsFileCollectionGetParams) SetFieldsQueryParameter(fields []string) {
	o.FieldsQueryParameter = fields
}

// WithIopsErrorLowerBoundQueryParameter adds the iopsErrorLowerBound to the top metrics file collection get params
func (o *TopMetricsFileCollectionGetParams) WithIopsErrorLowerBoundQueryParameter(iopsErrorLowerBound *int64) *TopMetricsFileCollectionGetParams {
	o.SetIopsErrorLowerBoundQueryParameter(iopsErrorLowerBound)
	return o
}

// SetIopsErrorLowerBoundQueryParameter adds the iopsErrorLowerBound to the top metrics file collection get params
func (o *TopMetricsFileCollectionGetParams) SetIopsErrorLowerBoundQueryParameter(iopsErrorLowerBound *int64) {
	o.IopsErrorLowerBoundQueryParameter = iopsErrorLowerBound
}

// WithIopsErrorUpperBoundQueryParameter adds the iopsErrorUpperBound to the top metrics file collection get params
func (o *TopMetricsFileCollectionGetParams) WithIopsErrorUpperBoundQueryParameter(iopsErrorUpperBound *int64) *TopMetricsFileCollectionGetParams {
	o.SetIopsErrorUpperBoundQueryParameter(iopsErrorUpperBound)
	return o
}

// SetIopsErrorUpperBoundQueryParameter adds the iopsErrorUpperBound to the top metrics file collection get params
func (o *TopMetricsFileCollectionGetParams) SetIopsErrorUpperBoundQueryParameter(iopsErrorUpperBound *int64) {
	o.IopsErrorUpperBoundQueryParameter = iopsErrorUpperBound
}

// WithIopsReadQueryParameter adds the iopsRead to the top metrics file collection get params
func (o *TopMetricsFileCollectionGetParams) WithIopsReadQueryParameter(iopsRead *int64) *TopMetricsFileCollectionGetParams {
	o.SetIopsReadQueryParameter(iopsRead)
	return o
}

// SetIopsReadQueryParameter adds the iopsRead to the top metrics file collection get params
func (o *TopMetricsFileCollectionGetParams) SetIopsReadQueryParameter(iopsRead *int64) {
	o.IopsReadQueryParameter = iopsRead
}

// WithIopsWriteQueryParameter adds the iopsWrite to the top metrics file collection get params
func (o *TopMetricsFileCollectionGetParams) WithIopsWriteQueryParameter(iopsWrite *int64) *TopMetricsFileCollectionGetParams {
	o.SetIopsWriteQueryParameter(iopsWrite)
	return o
}

// SetIopsWriteQueryParameter adds the iopsWrite to the top metrics file collection get params
func (o *TopMetricsFileCollectionGetParams) SetIopsWriteQueryParameter(iopsWrite *int64) {
	o.IopsWriteQueryParameter = iopsWrite
}

// WithMaxRecordsQueryParameter adds the maxRecords to the top metrics file collection get params
func (o *TopMetricsFileCollectionGetParams) WithMaxRecordsQueryParameter(maxRecords *int64) *TopMetricsFileCollectionGetParams {
	o.SetMaxRecordsQueryParameter(maxRecords)
	return o
}

// SetMaxRecordsQueryParameter adds the maxRecords to the top metrics file collection get params
func (o *TopMetricsFileCollectionGetParams) SetMaxRecordsQueryParameter(maxRecords *int64) {
	o.MaxRecordsQueryParameter = maxRecords
}

// WithMaxRecordsPerVolumeQueryParameter adds the maxRecordsPerVolume to the top metrics file collection get params
func (o *TopMetricsFileCollectionGetParams) WithMaxRecordsPerVolumeQueryParameter(maxRecordsPerVolume *int64) *TopMetricsFileCollectionGetParams {
	o.SetMaxRecordsPerVolumeQueryParameter(maxRecordsPerVolume)
	return o
}

// SetMaxRecordsPerVolumeQueryParameter adds the maxRecordsPerVolume to the top metrics file collection get params
func (o *TopMetricsFileCollectionGetParams) SetMaxRecordsPerVolumeQueryParameter(maxRecordsPerVolume *int64) {
	o.MaxRecordsPerVolumeQueryParameter = maxRecordsPerVolume
}

// WithOrderByQueryParameter adds the orderBy to the top metrics file collection get params
func (o *TopMetricsFileCollectionGetParams) WithOrderByQueryParameter(orderBy []string) *TopMetricsFileCollectionGetParams {
	o.SetOrderByQueryParameter(orderBy)
	return o
}

// SetOrderByQueryParameter adds the orderBy to the top metrics file collection get params
func (o *TopMetricsFileCollectionGetParams) SetOrderByQueryParameter(orderBy []string) {
	o.OrderByQueryParameter = orderBy
}

// WithPathQueryParameter adds the path to the top metrics file collection get params
func (o *TopMetricsFileCollectionGetParams) WithPathQueryParameter(path *string) *TopMetricsFileCollectionGetParams {
	o.SetPathQueryParameter(path)
	return o
}

// SetPathQueryParameter adds the path to the top metrics file collection get params
func (o *TopMetricsFileCollectionGetParams) SetPathQueryParameter(path *string) {
	o.PathQueryParameter = path
}

// WithReturnRecordsQueryParameter adds the returnRecords to the top metrics file collection get params
func (o *TopMetricsFileCollectionGetParams) WithReturnRecordsQueryParameter(returnRecords *bool) *TopMetricsFileCollectionGetParams {
	o.SetReturnRecordsQueryParameter(returnRecords)
	return o
}

// SetReturnRecordsQueryParameter adds the returnRecords to the top metrics file collection get params
func (o *TopMetricsFileCollectionGetParams) SetReturnRecordsQueryParameter(returnRecords *bool) {
	o.ReturnRecordsQueryParameter = returnRecords
}

// WithReturnTimeoutQueryParameter adds the returnTimeout to the top metrics file collection get params
func (o *TopMetricsFileCollectionGetParams) WithReturnTimeoutQueryParameter(returnTimeout *int64) *TopMetricsFileCollectionGetParams {
	o.SetReturnTimeoutQueryParameter(returnTimeout)
	return o
}

// SetReturnTimeoutQueryParameter adds the returnTimeout to the top metrics file collection get params
func (o *TopMetricsFileCollectionGetParams) SetReturnTimeoutQueryParameter(returnTimeout *int64) {
	o.ReturnTimeoutQueryParameter = returnTimeout
}

// WithSVMNameQueryParameter adds the svmName to the top metrics file collection get params
func (o *TopMetricsFileCollectionGetParams) WithSVMNameQueryParameter(svmName *string) *TopMetricsFileCollectionGetParams {
	o.SetSVMNameQueryParameter(svmName)
	return o
}

// SetSVMNameQueryParameter adds the svmName to the top metrics file collection get params
func (o *TopMetricsFileCollectionGetParams) SetSVMNameQueryParameter(svmName *string) {
	o.SVMNameQueryParameter = svmName
}

// WithSVMUUIDQueryParameter adds the svmUUID to the top metrics file collection get params
func (o *TopMetricsFileCollectionGetParams) WithSVMUUIDQueryParameter(svmUUID *string) *TopMetricsFileCollectionGetParams {
	o.SetSVMUUIDQueryParameter(svmUUID)
	return o
}

// SetSVMUUIDQueryParameter adds the svmUuid to the top metrics file collection get params
func (o *TopMetricsFileCollectionGetParams) SetSVMUUIDQueryParameter(svmUUID *string) {
	o.SVMUUIDQueryParameter = svmUUID
}

// WithThroughputErrorLowerBoundQueryParameter adds the throughputErrorLowerBound to the top metrics file collection get params
func (o *TopMetricsFileCollectionGetParams) WithThroughputErrorLowerBoundQueryParameter(throughputErrorLowerBound *int64) *TopMetricsFileCollectionGetParams {
	o.SetThroughputErrorLowerBoundQueryParameter(throughputErrorLowerBound)
	return o
}

// SetThroughputErrorLowerBoundQueryParameter adds the throughputErrorLowerBound to the top metrics file collection get params
func (o *TopMetricsFileCollectionGetParams) SetThroughputErrorLowerBoundQueryParameter(throughputErrorLowerBound *int64) {
	o.ThroughputErrorLowerBoundQueryParameter = throughputErrorLowerBound
}

// WithThroughputErrorUpperBoundQueryParameter adds the throughputErrorUpperBound to the top metrics file collection get params
func (o *TopMetricsFileCollectionGetParams) WithThroughputErrorUpperBoundQueryParameter(throughputErrorUpperBound *int64) *TopMetricsFileCollectionGetParams {
	o.SetThroughputErrorUpperBoundQueryParameter(throughputErrorUpperBound)
	return o
}

// SetThroughputErrorUpperBoundQueryParameter adds the throughputErrorUpperBound to the top metrics file collection get params
func (o *TopMetricsFileCollectionGetParams) SetThroughputErrorUpperBoundQueryParameter(throughputErrorUpperBound *int64) {
	o.ThroughputErrorUpperBoundQueryParameter = throughputErrorUpperBound
}

// WithThroughputReadQueryParameter adds the throughputRead to the top metrics file collection get params
func (o *TopMetricsFileCollectionGetParams) WithThroughputReadQueryParameter(throughputRead *int64) *TopMetricsFileCollectionGetParams {
	o.SetThroughputReadQueryParameter(throughputRead)
	return o
}

// SetThroughputReadQueryParameter adds the throughputRead to the top metrics file collection get params
func (o *TopMetricsFileCollectionGetParams) SetThroughputReadQueryParameter(throughputRead *int64) {
	o.ThroughputReadQueryParameter = throughputRead
}

// WithThroughputWriteQueryParameter adds the throughputWrite to the top metrics file collection get params
func (o *TopMetricsFileCollectionGetParams) WithThroughputWriteQueryParameter(throughputWrite *int64) *TopMetricsFileCollectionGetParams {
	o.SetThroughputWriteQueryParameter(throughputWrite)
	return o
}

// SetThroughputWriteQueryParameter adds the throughputWrite to the top metrics file collection get params
func (o *TopMetricsFileCollectionGetParams) SetThroughputWriteQueryParameter(throughputWrite *int64) {
	o.ThroughputWriteQueryParameter = throughputWrite
}

// WithTopMetricQueryParameter adds the topMetric to the top metrics file collection get params
func (o *TopMetricsFileCollectionGetParams) WithTopMetricQueryParameter(topMetric *string) *TopMetricsFileCollectionGetParams {
	o.SetTopMetricQueryParameter(topMetric)
	return o
}

// SetTopMetricQueryParameter adds the topMetric to the top metrics file collection get params
func (o *TopMetricsFileCollectionGetParams) SetTopMetricQueryParameter(topMetric *string) {
	o.TopMetricQueryParameter = topMetric
}

// WithVolumeNameQueryParameter adds the volumeName to the top metrics file collection get params
func (o *TopMetricsFileCollectionGetParams) WithVolumeNameQueryParameter(volumeName *string) *TopMetricsFileCollectionGetParams {
	o.SetVolumeNameQueryParameter(volumeName)
	return o
}

// SetVolumeNameQueryParameter adds the volumeName to the top metrics file collection get params
func (o *TopMetricsFileCollectionGetParams) SetVolumeNameQueryParameter(volumeName *string) {
	o.VolumeNameQueryParameter = volumeName
}

// WithVolumeUUIDPathParameter adds the volumeUUID to the top metrics file collection get params
func (o *TopMetricsFileCollectionGetParams) WithVolumeUUIDPathParameter(volumeUUID string) *TopMetricsFileCollectionGetParams {
	o.SetVolumeUUIDPathParameter(volumeUUID)
	return o
}

// SetVolumeUUIDPathParameter adds the volumeUuid to the top metrics file collection get params
func (o *TopMetricsFileCollectionGetParams) SetVolumeUUIDPathParameter(volumeUUID string) {
	o.VolumeUUIDPathParameter = volumeUUID
}

// WriteToRequest writes these params to a swagger request
func (o *TopMetricsFileCollectionGetParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error {

	if err := r.SetTimeout(o.timeout); err != nil {
		return err
	}
	var res []error

	if o.FieldsQueryParameter != nil {

		// binding items for fields
		joinedFields := o.bindParamFields(reg)

		// query array param fields
		if err := r.SetQueryParam("fields", joinedFields...); err != nil {
			return err
		}
	}

	if o.IopsErrorLowerBoundQueryParameter != nil {

		// query param iops.error.lower_bound
		var qrIopsErrorLowerBound int64

		if o.IopsErrorLowerBoundQueryParameter != nil {
			qrIopsErrorLowerBound = *o.IopsErrorLowerBoundQueryParameter
		}
		qIopsErrorLowerBound := swag.FormatInt64(qrIopsErrorLowerBound)
		if qIopsErrorLowerBound != "" {

			if err := r.SetQueryParam("iops.error.lower_bound", qIopsErrorLowerBound); err != nil {
				return err
			}
		}
	}

	if o.IopsErrorUpperBoundQueryParameter != nil {

		// query param iops.error.upper_bound
		var qrIopsErrorUpperBound int64

		if o.IopsErrorUpperBoundQueryParameter != nil {
			qrIopsErrorUpperBound = *o.IopsErrorUpperBoundQueryParameter
		}
		qIopsErrorUpperBound := swag.FormatInt64(qrIopsErrorUpperBound)
		if qIopsErrorUpperBound != "" {

			if err := r.SetQueryParam("iops.error.upper_bound", qIopsErrorUpperBound); err != nil {
				return err
			}
		}
	}

	if o.IopsReadQueryParameter != nil {

		// query param iops.read
		var qrIopsRead int64

		if o.IopsReadQueryParameter != nil {
			qrIopsRead = *o.IopsReadQueryParameter
		}
		qIopsRead := swag.FormatInt64(qrIopsRead)
		if qIopsRead != "" {

			if err := r.SetQueryParam("iops.read", qIopsRead); err != nil {
				return err
			}
		}
	}

	if o.IopsWriteQueryParameter != nil {

		// query param iops.write
		var qrIopsWrite int64

		if o.IopsWriteQueryParameter != nil {
			qrIopsWrite = *o.IopsWriteQueryParameter
		}
		qIopsWrite := swag.FormatInt64(qrIopsWrite)
		if qIopsWrite != "" {

			if err := r.SetQueryParam("iops.write", qIopsWrite); err != nil {
				return err
			}
		}
	}

	if o.MaxRecordsQueryParameter != nil {

		// query param max_records
		var qrMaxRecords int64

		if o.MaxRecordsQueryParameter != nil {
			qrMaxRecords = *o.MaxRecordsQueryParameter
		}
		qMaxRecords := swag.FormatInt64(qrMaxRecords)
		if qMaxRecords != "" {

			if err := r.SetQueryParam("max_records", qMaxRecords); err != nil {
				return err
			}
		}
	}

	if o.MaxRecordsPerVolumeQueryParameter != nil {

		// query param max_records_per_volume
		var qrMaxRecordsPerVolume int64

		if o.MaxRecordsPerVolumeQueryParameter != nil {
			qrMaxRecordsPerVolume = *o.MaxRecordsPerVolumeQueryParameter
		}
		qMaxRecordsPerVolume := swag.FormatInt64(qrMaxRecordsPerVolume)
		if qMaxRecordsPerVolume != "" {

			if err := r.SetQueryParam("max_records_per_volume", qMaxRecordsPerVolume); err != nil {
				return err
			}
		}
	}

	if o.OrderByQueryParameter != nil {

		// binding items for order_by
		joinedOrderBy := o.bindParamOrderBy(reg)

		// query array param order_by
		if err := r.SetQueryParam("order_by", joinedOrderBy...); err != nil {
			return err
		}
	}

	if o.PathQueryParameter != nil {

		// query param path
		var qrPath string

		if o.PathQueryParameter != nil {
			qrPath = *o.PathQueryParameter
		}
		qPath := qrPath
		if qPath != "" {

			if err := r.SetQueryParam("path", qPath); err != nil {
				return err
			}
		}
	}

	if o.ReturnRecordsQueryParameter != nil {

		// query param return_records
		var qrReturnRecords bool

		if o.ReturnRecordsQueryParameter != nil {
			qrReturnRecords = *o.ReturnRecordsQueryParameter
		}
		qReturnRecords := swag.FormatBool(qrReturnRecords)
		if qReturnRecords != "" {

			if err := r.SetQueryParam("return_records", qReturnRecords); err != nil {
				return err
			}
		}
	}

	if o.ReturnTimeoutQueryParameter != nil {

		// query param return_timeout
		var qrReturnTimeout int64

		if o.ReturnTimeoutQueryParameter != nil {
			qrReturnTimeout = *o.ReturnTimeoutQueryParameter
		}
		qReturnTimeout := swag.FormatInt64(qrReturnTimeout)
		if qReturnTimeout != "" {

			if err := r.SetQueryParam("return_timeout", qReturnTimeout); err != nil {
				return err
			}
		}
	}

	if o.SVMNameQueryParameter != nil {

		// query param svm.name
		var qrSvmName string

		if o.SVMNameQueryParameter != nil {
			qrSvmName = *o.SVMNameQueryParameter
		}
		qSvmName := qrSvmName
		if qSvmName != "" {

			if err := r.SetQueryParam("svm.name", qSvmName); err != nil {
				return err
			}
		}
	}

	if o.SVMUUIDQueryParameter != nil {

		// query param svm.uuid
		var qrSvmUUID string

		if o.SVMUUIDQueryParameter != nil {
			qrSvmUUID = *o.SVMUUIDQueryParameter
		}
		qSvmUUID := qrSvmUUID
		if qSvmUUID != "" {

			if err := r.SetQueryParam("svm.uuid", qSvmUUID); err != nil {
				return err
			}
		}
	}

	if o.ThroughputErrorLowerBoundQueryParameter != nil {

		// query param throughput.error.lower_bound
		var qrThroughputErrorLowerBound int64

		if o.ThroughputErrorLowerBoundQueryParameter != nil {
			qrThroughputErrorLowerBound = *o.ThroughputErrorLowerBoundQueryParameter
		}
		qThroughputErrorLowerBound := swag.FormatInt64(qrThroughputErrorLowerBound)
		if qThroughputErrorLowerBound != "" {

			if err := r.SetQueryParam("throughput.error.lower_bound", qThroughputErrorLowerBound); err != nil {
				return err
			}
		}
	}

	if o.ThroughputErrorUpperBoundQueryParameter != nil {

		// query param throughput.error.upper_bound
		var qrThroughputErrorUpperBound int64

		if o.ThroughputErrorUpperBoundQueryParameter != nil {
			qrThroughputErrorUpperBound = *o.ThroughputErrorUpperBoundQueryParameter
		}
		qThroughputErrorUpperBound := swag.FormatInt64(qrThroughputErrorUpperBound)
		if qThroughputErrorUpperBound != "" {

			if err := r.SetQueryParam("throughput.error.upper_bound", qThroughputErrorUpperBound); err != nil {
				return err
			}
		}
	}

	if o.ThroughputReadQueryParameter != nil {

		// query param throughput.read
		var qrThroughputRead int64

		if o.ThroughputReadQueryParameter != nil {
			qrThroughputRead = *o.ThroughputReadQueryParameter
		}
		qThroughputRead := swag.FormatInt64(qrThroughputRead)
		if qThroughputRead != "" {

			if err := r.SetQueryParam("throughput.read", qThroughputRead); err != nil {
				return err
			}
		}
	}

	if o.ThroughputWriteQueryParameter != nil {

		// query param throughput.write
		var qrThroughputWrite int64

		if o.ThroughputWriteQueryParameter != nil {
			qrThroughputWrite = *o.ThroughputWriteQueryParameter
		}
		qThroughputWrite := swag.FormatInt64(qrThroughputWrite)
		if qThroughputWrite != "" {

			if err := r.SetQueryParam("throughput.write", qThroughputWrite); err != nil {
				return err
			}
		}
	}

	if o.TopMetricQueryParameter != nil {

		// query param top_metric
		var qrTopMetric string

		if o.TopMetricQueryParameter != nil {
			qrTopMetric = *o.TopMetricQueryParameter
		}
		qTopMetric := qrTopMetric
		if qTopMetric != "" {

			if err := r.SetQueryParam("top_metric", qTopMetric); err != nil {
				return err
			}
		}
	}

	if o.VolumeNameQueryParameter != nil {

		// query param volume.name
		var qrVolumeName string

		if o.VolumeNameQueryParameter != nil {
			qrVolumeName = *o.VolumeNameQueryParameter
		}
		qVolumeName := qrVolumeName
		if qVolumeName != "" {

			if err := r.SetQueryParam("volume.name", qVolumeName); err != nil {
				return err
			}
		}
	}

	// path param volume.uuid
	if err := r.SetPathParam("volume.uuid", o.VolumeUUIDPathParameter); err != nil {
		return err
	}

	if len(res) > 0 {
		return errors.CompositeValidationError(res...)
	}
	return nil
}

// bindParamTopMetricsFileCollectionGet binds the parameter fields
func (o *TopMetricsFileCollectionGetParams) bindParamFields(formats strfmt.Registry) []string {
	fieldsIR := o.FieldsQueryParameter

	var fieldsIC []string
	for _, fieldsIIR := range fieldsIR { // explode []string

		fieldsIIV := fieldsIIR // string as string
		fieldsIC = append(fieldsIC, fieldsIIV)
	}

	// items.CollectionFormat: "csv"
	fieldsIS := swag.JoinByFormat(fieldsIC, "csv")

	return fieldsIS
}

// bindParamTopMetricsFileCollectionGet binds the parameter order_by
func (o *TopMetricsFileCollectionGetParams) bindParamOrderBy(formats strfmt.Registry) []string {
	orderByIR := o.OrderByQueryParameter

	var orderByIC []string
	for _, orderByIIR := range orderByIR { // explode []string

		orderByIIV := orderByIIR // string as string
		orderByIC = append(orderByIC, orderByIIV)
	}

	// items.CollectionFormat: "csv"
	orderByIS := swag.JoinByFormat(orderByIC, "csv")

	return orderByIS
}


text:
import glob
import sys

def main():
    hits_dir = sys.argv[1]
    input_files = [inp for inp in glob.glob(hits_dir + '/input*') if '.txt' not in inp]
    inputs = ['urls\n']
    for input_file in input_files:
        with open(input_file) as fh:
            inputs.extend(fh.readlines()[1:])

    with open(hits_dir + '/input', 'w') as fh:
        fh.writelines(inputs)

if __name__ == '__main__':
    main()

redpajama_set_name: RedPajamaGithub


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Syll. fung. (Abellini) 5: 878 (1887)

#### Original name
Agaricus interceptus Berk.

### Remarks
null


text:
if [ "$SANITIZER" = undefined ]; then
    export CFLAGS="$CFLAGS -fsanitize=unsigned-integer-overflow -fno-sanitize-recover=unsigned-integer-overflow"
    export CXXFLAGS="$CXXFLAGS -fsanitize=unsigned-integer-overflow -fno-sanitize-recover=unsigned-integer-overflow"
fi

export V=1

./autogen.sh \
    --disable-shared \
    --without-debug \
    --without-ftp \
    --without-http \
    --without-legacy \
    --without-python
make -j$(nproc)

cd fuzz
make clean-corpus
make fuzz.o

for fuzzer in html regexp schema uri xml xpath; do
    make $fuzzer.o
    # Link with $CXX
    $CXX $CXXFLAGS \
        $fuzzer.o fuzz.o \
        -o $OUT/$fuzzer \
        $LIB_FUZZING_ENGINE \
        ../.libs/libxml2.a -Wl,-Bstatic -lz -llzma -Wl,-Bdynamic

    [ -e seed/$fuzzer ] || make seed/$fuzzer.stamp
    zip -j $OUT/${fuzzer}_seed_corpus.zip seed/$fuzzer/*
done

cp *.dict *.options $OUT/


text:
'''
_(requires Nodel v2.2 or higher; recipe Mk 2 rev. 3)_

To get started from scratch, use the **Create Frontend from sample** Action.

This **Frontend** / **Dashboard** makes use of the following files:

   * `content/index.xml` (*): a landing page (see here for viewing/copying)
   * `content/css/custom.css`: custom CSS (see here for viewing/copying)
   * `content/js/custom.js`: custom Javascript (see here for viewing/copying)
   * `content/img/background.jpg`
   * `content/img/logo.png`

(*) required, more than one allowed

You can **drag & drop** content into the editor for convenience, including certain binary files (e.g. graphics, etc.).

To switch to your Frontend / Dashboard, use the **Nav** / **UI** menu or use `/index.xml` URL suffix for node.

'''

import xml.etree.ElementTree as ET # XML parsing
import os                          # working directory
from java.io import File           # reading files
from org.nodel.io import Stream    # reading files
from org.nodel import SimpleName   # for Node names
from org.nodel.core import Nodel   # for host path

param_suggestedNode = Parameter({'title': 'Suggested Node',
                                 'desc': 'A suggestion can be made when remote bindings are created. The then need to be confirm and saved',
                                 'schema': {'type': 'string', 'format': 'node'}})

param_localOnlySignals = Parameter({'title': 'Local only signals',
                                    'desc': 'No remote bindings are configured for these. Comma-separated list of signals',
                                    'schema': {'type': 'string'}})

param_localOnlyActions = Parameter({'title': 'Local only actions',
                                    'desc': 'No remote bindings are configured for these. Comma-separated list of signals',
                                    'schema': {'type': 'string'}})

local_event_Clock = LocalEvent({"title": "Clock", "group": "General", "schema": {"type": "string" }})
timer_clock = Timer(lambda: local_event_Clock.emit(date_now()), 1)

localOnlySignals = set()
localOnlyActions = set()

# the node's working directory
workingDir = os.getcwd()

schemaMap = {} # taken from 'schema.json'
               # For example:
               #
               # { 'status_signal': {'type': 'object', 'properties': ... },
               #   'meter': {'type': 'number'},
               #   ...
               # }

def main():
  # split the local only actions and signals
  [localOnlySignals.add(SimpleName(name)) for name in (param_localOnlySignals or '').split(',')]
  [localOnlyActions.add(SimpleName(name)) for name in (param_localOnlyActions or '').split(',')]

  # parse the index
  indexFile = os.path.join(workingDir, 'content', 'index.xml')
  if not os.path.exists(indexFile):
    return console.warn('No "content/index.xml" file exists; please use "Create from sample" Action')

  schemasFile = os.path.join(workingDir, 'content', 'schemas.json')
  if os.path.exists(schemasFile):
    loadSchemas(Stream.readFully(File(schemasFile)))

  loadIndexFile(indexFile)

def loadSchemas(json):
  schemas = json_decode(json)

  keys = list()
  for key in schemas:
    schemaMap[key] = schemas[key]
    keys.append(key)

  if len(keys) > 0:
    print 'Loaded schemas: %s' % ', '.join(keys)

  else:
    console.warn('(no schema mapping info was present)')

def loadIndexFile(xmlFile):
  xml = ET.parse(xmlFile)

  def explore(group, e):
    eType = e.tag
    join = e.get('join')             # shorthand for <... action=... event=...">
    eActionNormal = e.get('action') or join
    eActionOn = e.get('action-on')   # these are for
    eActionOff = e.get('action-off') # momentary buttons
    eEvent = e.get('event') or join
    title = e.get('title')

    # compose a group name (if possible)
    if title == None and eType == 'title':
      title = e.text

    if title in ['row', 'column']:
      title = None

    if title == None:
      thisGroup = group

    elif group == '':
      thisGroup = title

    else:
      thisGroup = '%s - %s' % (group, title)

    # the default schema to use if '_action' or '_signal' is not used
    defaultSchema = schemaMap.get(eType)

    def tryAction(eAction):
      if eAction != None and lookup_local_action(eAction) == None:
        # an action is specified

        # is it local only?
        if SimpleName(eAction) in localOnlyActions:
          handler = lambda arg: None

        else:
          remoteAction = create_remote_action(eAction, suggestedNode=param_suggestedNode)
          handler = lambda arg: remoteAction.call(arg)

        action = Action(eAction, handler,
                        {'group': thisGroup, 'order': next_seq(), 'schema': schemaMap.get('%s_action' % eType, defaultSchema)})

    tryAction(eActionNormal)
    tryAction(eActionOn)
    tryAction(eActionOff)

    if eEvent != None and lookup_local_event(eEvent) == None:
      # an event is specified

      event = Event(eEvent,
                    {'group': thisGroup, 'order': next_seq(), 'schema': schemaMap.get('%s_signal' % eType, defaultSchema)})

      # is it local only?
      if not SimpleName(eEvent) in localOnlySignals:
        def remoteEventHandler(arg=None):
          event.emit(arg)

        remoteEvent = create_remote_event(eEvent, remoteEventHandler, suggestedNode=param_suggestedNode)

    for i in e:
      explore(thisGroup, i)

  explore('', xml.getroot())

Nodel.getHostPath()

@local_action({'title': 'Create Frontend from sample and restart (will not overwrite existing)' })
def CreateFromSample():
  # this is "embedded" (and updated) with each version of Nodel
  sampleFile = File(os.path.join(Nodel.getHostPath(), '.nodel', 'webui_cache', 'index-sample.xml'))
  contentDir = File(_node.getRoot(), 'content')
  dstFile = File(contentDir, 'index.xml')

  if dstFile.exists():
    return console.warn('index.xml file already exists!')

  if not contentDir.exists() and not contentDir.mkdirs():
    return console.error('Could not create directory %s' % contentDir)

  Stream.writeFully(dstFile, Stream.readFully(sampleFile))

  console.info('"content/index.xml" created successfully from sample. Please edit to suit your needs. Restarting node...')
  _node.restart()


text:
@interface CMYKFadeFromWhiteAnimator ()
{
	CGFloat rgb;
	CGFloat a;

	NSTimeInterval time;
}

@end

@implementation CMYKFadeFromWhiteAnimator

- (void)updateWithInterval:(NSTimeInterval)timeInterval
{
	QX3DObject *target = self.target;

	CMYKRenderableSquare *square = [target.renderables firstObject];
	square.color = [UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:1.0 - (time * 2.0)];

	time += timeInterval;

	if (time > 0.5 && time < 100.0)
	{
		time = 110.0;
		[self performSelector:@selector(detachTargetFromScene:) withObject:self.target afterDelay:0.01];
	}
}

- (void)detachTargetFromScene:(id)detachThis
{
	QX3DObject *target = detachThis;
	[target detach];
}

@end


text:
<?php

     require_once('funciones.php');

	  if (!empty($_POST['nombre']))
    {
        $nombre = $_POST['nombre'];
		$pais = $_POST['pais'];

        $UniversiadadRepetido = mysql_query("SELECT * FROM `universidad` WHERE universidad.nombre_universidad ='$nombre' and universidad.Id_pais in (SELECT Id_pais FROM pais WHERE pais.Nombre_pais ='$pais') LIMIT 1");
        $Universidad_="";

     while($row =mysql_fetch_array($UniversiadadRepetido)){
        $Universidad_ =$row['nombre_universidad'];
        }

     if($UniversiadadRepetido=$Universidad_){
       echo mensajes('Universidad ya creada ','verde');
       }
       else{
        $query = "INSERT INTO universidad(Nombre_universidad,Id_Pais) VALUES('$nombre','$pais')";
        mysql_query($query);
        if($query){
        //echo '<META HTTP-EQUIV="REFRESH" CONTENT="2">' ;
        echo mensajes('Universidad ingresada con Exito','verde');
        }
    }
    }

    else{
        echo mensajes('requisitos en blanco','rojo');
    }

?>


text:
package com.aspose.cloud.sdk.storage.model;

import java.lang.reflect.Type;
import java.util.Date;
import java.util.regex.Pattern;

import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;

public class DateDeserializer implements JsonDeserializer<Date> {

	@Override
	public Date deserialize(JsonElement dateStr, Type typeOfSrc, JsonDeserializationContext context) throws JsonParseException {

		//Convert JSON Date to Java Date where server is returning Date in this format /Date(1415106133000+0000)/
		String jsonDate = dateStr.getAsString();
		if(jsonDate.startsWith("/Date(")) {
			jsonDate = jsonDate.replace("/Date(", "");
		}
		if(jsonDate.endsWith(")/")) {
			jsonDate = jsonDate.replace(")/", "");
		}
		//Separate time zone from actual date
		if(jsonDate.contains("+")) {
			String[] splitedDateParts = jsonDate.split(Pattern.quote("+"));
			if(splitedDateParts.length >= 1) {
				jsonDate = splitedDateParts[0];
			}
		}

		long datetimestamp = Long.parseLong(jsonDate);
	    Date date = new Date(datetimestamp);

		return date;
	}

}


text:
(function() {
  var Configurator, Factory, Package, configDir, createPackage, dir, expect, getConfig, path;

  expect = require('chai').expect;

  path = require('path');

  Factory = require('../../../../lib/Package/Factory');

  Package = require('../../../../lib/Package/Package');

  Configurator = require('../../../../lib/Config/Configurator');

  dir = path.resolve(__dirname + '/../../../data/package');

  configDir = dir + '/config';

  getConfig = function(name) {
    return (new Configurator(configDir + '/' + name + '.json')).load();
  };

  createPackage = function(name) {
    return Factory.create(dir, getConfig(name).packages.application);
  };

  describe('Package/Factory', function() {
    return describe('#create()', function() {
      it('shoult create empty package', function() {
        var pckg;
        pckg = createPackage('empty');
        expect(pckg).to.be.an["instanceof"](Package);
        expect(pckg.basePath).to.be.equal(dir);
        expect(pckg.skip).to.be["false"];
        expect(pckg.base).to.be["null"];
        expect(pckg.target).to.be["null"];
        expect(pckg.style).to.be["null"];
        expect(pckg.modules).to.be.eql([]);
        return expect(pckg.run).to.be.eql([]);
      });
      it('should create package with result application path', function() {
        var pckg;
        pckg = createPackage('advanced/config');
        return expect(pckg.target).to.be.equal(dir + '/public/application.js');
      });
      it('should create package with styles', function() {
        var pckg;
        pckg = createPackage('styles/styles');
        return expect(pckg.style).to.be.eql({
          "in": dir + '/css/style.less',
          out: dir + '/public/style.css',
          dependencies: null
        });
      });
      it('should create package without styles because there is no in file', function() {
        var pckg;
        pckg = createPackage('styles/no-in');
        return expect(pckg.style).to.be["null"];
      });
      it('should create package without styles because there is no out file', function() {
        var pckg;
        pckg = createPackage('styles/no-out');
        return expect(pckg.style).to.be["null"];
      });
      it('should create package with run section from libraries', function() {
        var pckg;
        pckg = createPackage('libraries');
        return expect(pckg.run).to.be.eql([dir + '/libs/begin/1.js', dir + '/libs/begin/2.js', dir + '/libs/end/1.js', dir + '/libs/end/2.js']);
      });
      it('should create package with modules to run', function() {
        var pckg;
        pckg = createPackage('run');
        expect(pckg.modules).to.be.eql([dir + '/app/Application.coffee', dir + '/app/controllers/Menu.js']);
        return expect(pckg.run).to.be.eql(['/app/Application', '/app/controllers/Menu.js']);
      });
      return it('should create package with modules and libraries in run section', function() {
        var pckg;
        pckg = createPackage('run-and-libraries');
        expect(pckg.modules).to.be.eql([dir + '/app/Application.coffee', dir + '/app/controllers/Menu.js']);
        return expect(pckg.run).to.be.eql([dir + '/libs/begin/1.js', dir + '/libs/begin/2.js', '/app/Application', '/app/controllers/Menu.js', dir + '/libs/end/1.js', dir + '/libs/end/2.js']);
      });
    });
  });

}).call(this);


text:
package com.intellij.psi.impl.file.impl;

import com.intellij.AppTopics;
import com.intellij.ProjectTopics;
import com.intellij.injected.editor.DocumentWindow;
import com.intellij.injected.editor.VirtualFileWindow;
import com.intellij.lang.Language;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.extensions.Extensions;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.fileEditor.FileDocumentManagerAdapter;
import com.intellij.openapi.fileTypes.*;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.project.DumbService;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ex.ProjectEx;
import com.intellij.openapi.roots.*;
import com.intellij.openapi.roots.ex.ProjectRootManagerEx;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.vfs.*;
import com.intellij.openapi.vfs.impl.BulkVirtualFileListenerAdapter;
import com.intellij.psi.*;
import com.intellij.psi.impl.PsiFileEx;
import com.intellij.psi.impl.PsiManagerImpl;
import com.intellij.psi.impl.PsiTreeChangeEventImpl;
import com.intellij.psi.impl.file.PsiDirectoryFactory;
import com.intellij.psi.impl.smartPointers.SmartPointerManagerImpl;
import com.intellij.psi.impl.source.PsiFileImpl;
import com.intellij.psi.impl.source.resolve.FileContextUtil;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.search.SearchScope;
import com.intellij.util.ConcurrencyUtil;
import com.intellij.util.FileContentUtil;
import com.intellij.util.containers.ConcurrentFactoryMap;
import com.intellij.util.containers.ConcurrentHashMap;
import com.intellij.util.containers.ConcurrentWeakValueHashMap;
import com.intellij.util.messages.MessageBusConnection;
import gnu.trove.THashMap;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;

import java.io.IOException;
import java.io.Writer;
import java.util.*;
import java.util.concurrent.ConcurrentMap;

public class FileManagerImpl implements FileManager {
  private static final Logger LOG = Logger.getInstance("#com.intellij.psi.impl.file.impl.FileManagerImpl");

  private final PsiManagerImpl myManager;

  private final FileTypeManager myFileTypeManager;

  private final ProjectRootManager myProjectRootManager;
  private ProjectFileIndex myProjectFileIndex = null;

  private final ConcurrentMap<VirtualFile, PsiDirectory> myVFileToPsiDirMap = new ConcurrentHashMap<VirtualFile, PsiDirectory>();
  private final ConcurrentWeakValueHashMap<VirtualFile, FileViewProvider> myVFileToViewProviderMap = new ConcurrentWeakValueHashMap<VirtualFile, FileViewProvider>();

  private final Map<VirtualFile, GlobalSearchScope> myDefaultUseScopesCache = new ConcurrentFactoryMap<VirtualFile, GlobalSearchScope>() {
    @Override
    protected GlobalSearchScope create(VirtualFile key) {
      GlobalSearchScope scope = getInherentResolveScope(key);
      for (ResolveScopeEnlarger enlarger : ResolveScopeEnlarger.EP_NAME.getExtensions()) {
        final SearchScope extra = enlarger.getAdditionalResolveScope(key, myManager.getProject());
        if (extra != null) {
          scope = scope.union(extra);
        }
      }

      return scope;
    }
  };

  private boolean myInitialized = false;
  private boolean myDisposed = false;

  private final FileDocumentManager myFileDocumentManager;
  private final MessageBusConnection myConnection;

  public FileManagerImpl(PsiManagerImpl manager,
                         FileTypeManager fileTypeManager,
                         FileDocumentManager fileDocumentManager,
                         ProjectRootManager projectRootManager) {
    myFileTypeManager = fileTypeManager;
    myManager = manager;
    myConnection = manager.getProject().getMessageBus().connect();

    myFileDocumentManager = fileDocumentManager;
    myProjectRootManager = projectRootManager;

    myConnection.subscribe(DumbService.DUMB_MODE, new DumbService.DumbModeListener() {

      public void enteredDumbMode() {
        recalcAllViewProviders();
      }

      public void exitDumbMode() {
        recalcAllViewProviders();
      }
    });

    manager.registerRunnableToRunOnChange(new Runnable() {
      @Override
      public void run() {
        myDefaultUseScopesCache.clear();
      }
    });
  }

  public void processQueue() {
    myVFileToViewProviderMap.processQueue();
  }

  @TestOnly
  public ConcurrentWeakValueHashMap<VirtualFile, FileViewProvider> getVFileToViewProviderMap() {
    return myVFileToViewProviderMap;
  }

  private void recalcAllViewProviders() {
    handleFileTypesChange(new FileTypesChanged() {
      protected void updateMaps() {
        for (final FileViewProvider provider : myVFileToViewProviderMap.values()) {
          if (!provider.getVirtualFile().isValid()) {
            continue;
          }

          for (Language language : provider.getLanguages()) {
            final PsiFile psi = provider.getPsi(language);
            if (psi instanceof PsiFileImpl) {
              ((PsiFileImpl)psi).clearCaches();
            }
          }
        }
        removeInvalidFilesAndDirs(false);
      }
    });
  }

  public void dispose() {
    if (myInitialized) {
      myConnection.disconnect();
    }
    myDisposed = true;
  }

  public void cleanupForNextTest() {
    myVFileToViewProviderMap.clear();
    myVFileToPsiDirMap.clear();
    processQueue();
  }

  @NotNull
  public FileViewProvider findViewProvider(@NotNull final VirtualFile file) {
    FileViewProvider viewProvider = getFromInjected(file);
    if (viewProvider != null) return viewProvider;
    viewProvider = myVFileToViewProviderMap.get(file);
    if(viewProvider == null) {
      viewProvider = ConcurrencyUtil.cacheOrGet(myVFileToViewProviderMap, file, createFileViewProvider(file, true));
    }
    return viewProvider;
  }

  public FileViewProvider findCachedViewProvider(@NotNull final VirtualFile file) {
    FileViewProvider viewProvider = getFromInjected(file);
    if (viewProvider != null) return viewProvider;
    return myVFileToViewProviderMap.get(file);
  }

  private FileViewProvider getFromInjected(VirtualFile file) {
    if (file instanceof VirtualFileWindow) {
      DocumentWindow document = ((VirtualFileWindow)file).getDocumentWindow();
      PsiFile psiFile = PsiDocumentManager.getInstance(myManager.getProject()).getCachedPsiFile(document);
      if (psiFile == null) return null;
      return psiFile.getViewProvider();
    }
    return null;
  }

  public void setViewProvider(@NotNull final VirtualFile virtualFile, final FileViewProvider fileViewProvider) {
    if (!(virtualFile instanceof VirtualFileWindow)) {
      if (fileViewProvider == null) {
        myVFileToViewProviderMap.remove(virtualFile);
      }
      else {
        myVFileToViewProviderMap.put(virtualFile, fileViewProvider);
      }
    }
  }

  @NotNull
  public FileViewProvider createFileViewProvider(@NotNull final VirtualFile file, boolean physical) {
    Language language = getLanguage(file);
    final FileViewProviderFactory factory = language == null
                                            ? FileTypeFileViewProviders.INSTANCE.forFileType(file.getFileType())
                                            : LanguageFileViewProviders.INSTANCE.forLanguage(language);
    FileViewProvider viewProvider = factory == null ? null : factory.createFileViewProvider(file, language, myManager, physical);

    return viewProvider == null ? new SingleRootFileViewProvider(myManager, file, physical) : viewProvider;
  }

  @Nullable
  private Language getLanguage(final VirtualFile file) {
    final FileType fileType = file.getFileType();
    Project project = myManager.getProject();
    if (fileType instanceof LanguageFileType) {
      return LanguageSubstitutors.INSTANCE.substituteLanguage(((LanguageFileType)fileType).getLanguage(), file, project);
    }
    // Define language for binary file
    final ContentBasedClassFileProcessor[] processors = Extensions.getExtensions(ContentBasedClassFileProcessor.EP_NAME);
    for (ContentBasedClassFileProcessor processor : processors) {
      Language language = processor.obtainLanguageForFile(file);
      if (language != null) {
        return language;
      }
    }

    return null;
  }

  public void runStartupActivity() {
    LOG.assertTrue(!myInitialized);
    myDisposed = false;
    myInitialized = true;

    myProjectFileIndex = myProjectRootManager.getFileIndex();

    myConnection.subscribe(VirtualFileManager.VFS_CHANGES, new BulkVirtualFileListenerAdapter(new MyVirtualFileListener()));

    myConnection.subscribe(AppTopics.FILE_TYPES, new FileTypeListener() {
      public void beforeFileTypesChanged(FileTypeEvent event) {}

      public void fileTypesChanged(FileTypeEvent e) {
        handleFileTypesChange(new FileTypesChanged() {
          protected void updateMaps() {
            removeInvalidFilesAndDirs(true);
          }
        });
      }
    });

    myConnection.subscribe(ProjectTopics.PROJECT_ROOTS, new MyModuleRootListener());
    myConnection.subscribe(AppTopics.FILE_DOCUMENT_SYNC, new MyFileDocumentManagerAdapter());
  }

  private abstract class FileTypesChanged implements Runnable {
    protected abstract void updateMaps();

    public void run() {
      PsiTreeChangeEventImpl event = new PsiTreeChangeEventImpl(myManager);
      event.setPropertyName(PsiTreeChangeEvent.PROP_FILE_TYPES);
      myManager.beforePropertyChange(event);

      updateMaps();

      event = new PsiTreeChangeEventImpl(myManager);
      event.setPropertyName(PsiTreeChangeEvent.PROP_FILE_TYPES);
      myManager.propertyChanged(event);
    }
  }

  private boolean myProcessingFileTypesChange = false;
  private void handleFileTypesChange(final FileTypesChanged runnable) {
    if (myProcessingFileTypesChange) return;
    myProcessingFileTypesChange = true;
    try {
      ApplicationManager.getApplication().runWriteAction(runnable);
    }
    finally {
      myProcessingFileTypesChange = false;
    }
  }

  private void dispatchPendingEvents() {
    if (!myInitialized) {
      LOG.error("Project is not yet initialized");
    }
    if (myDisposed) {
      LOG.error("Project is already disposed");
    }

    myConnection.deliverImmediately();
  }

  @TestOnly
  public void checkConsistency() {
    HashMap<VirtualFile, FileViewProvider> fileToViewProvider = new HashMap<VirtualFile, FileViewProvider>(myVFileToViewProviderMap);
    myVFileToViewProviderMap.clear();
    for (VirtualFile vFile : fileToViewProvider.keySet()) {
      final FileViewProvider fileViewProvider = fileToViewProvider.get(vFile);

      LOG.assertTrue(vFile.isValid());
      PsiFile psiFile1 = findFile(vFile);
      if (psiFile1 != null && fileViewProvider != null && fileViewProvider.isPhysical()) { // might get collected
        PsiFile psi = fileViewProvider.getPsi(fileViewProvider.getBaseLanguage());
        assert psi != null : fileViewProvider +"; "+fileViewProvider.getBaseLanguage()+"; "+psiFile1;
        assert psiFile1.getClass().equals(psi.getClass()) : psiFile1 +"; "+psi + "; "+psiFile1.getClass() +"; "+psi.getClass();
      }
    }

    HashMap<VirtualFile, PsiDirectory> fileToPsiDirMap = new HashMap<VirtualFile, PsiDirectory>(myVFileToPsiDirMap);
    myVFileToPsiDirMap.clear();

    for (VirtualFile vFile : fileToPsiDirMap.keySet()) {
      LOG.assertTrue(vFile.isValid());
      PsiDirectory psiDir1 = findDirectory(vFile);
      LOG.assertTrue(psiDir1 != null);

      VirtualFile parent = vFile.getParent();
      if (parent != null) {
        LOG.assertTrue(myVFileToPsiDirMap.containsKey(parent));
      }
    }
  }

  @Nullable
  public PsiFile findFile(@NotNull VirtualFile vFile) {
    if (vFile.isDirectory()) return null;
    final ProjectEx project = (ProjectEx)myManager.getProject();
    if (project.isDefault()) return null;

    ApplicationManager.getApplication().assertReadAccessAllowed();
    if (!vFile.isValid()) {
      LOG.error("Invalid file: " + vFile);
      return null;
    }

    dispatchPendingEvents();
    final FileViewProvider viewProvider = findViewProvider(vFile);
    return viewProvider.getPsi(viewProvider.getBaseLanguage());
  }

  @Nullable
  public PsiFile getCachedPsiFile(@NotNull VirtualFile vFile) {
    ApplicationManager.getApplication().assertReadAccessAllowed();
    LOG.assertTrue(vFile.isValid());
    LOG.assertTrue(!myDisposed);
    if (!myInitialized) return null;

    dispatchPendingEvents();

    return getCachedPsiFileInner(vFile);
  }

  @NotNull
  public GlobalSearchScope getResolveScope(@NotNull PsiElement element) {
    ProgressManager.checkCanceled();

    VirtualFile vFile;
    final Project project = myManager.getProject();
    final PsiFile contextFile;
    if (element instanceof PsiDirectory) {
      vFile = ((PsiDirectory)element).getVirtualFile();
      contextFile = null;
    }
    else {
      final PsiFile containingFile = element.getContainingFile();
      if (containingFile instanceof PsiCodeFragment) {
        final GlobalSearchScope forcedScope = ((PsiCodeFragment)containingFile).getForcedResolveScope();
        if (forcedScope != null) {
          return forcedScope;
        }
        final PsiElement context = containingFile.getContext();
        if (context == null) {
          return GlobalSearchScope.allScope(project);
        }
        return getResolveScope(context);
      }

      contextFile = containingFile != null ? FileContextUtil.getContextFile(containingFile) : null;
      if (contextFile == null) {
        return GlobalSearchScope.allScope(project);
      }
      else if (contextFile instanceof FileResolveScopeProvider) {
        return ((FileResolveScopeProvider) contextFile).getFileResolveScope();
      }
      vFile = contextFile.getOriginalFile().getVirtualFile();
    }
    if (vFile == null || contextFile == null) {
      return GlobalSearchScope.allScope(project);
    }

    return getDefaultResolveScope(project, contextFile, vFile);
  }

  public GlobalSearchScope getDefaultResolveScope(final VirtualFile vFile) {
    final Project project = myManager.getProject();
    final PsiFile psiFile = PsiManager.getInstance(project).findFile(vFile);
    assert psiFile != null;
    return getDefaultResolveScope(project, psiFile, vFile);
  }

  private GlobalSearchScope getDefaultResolveScope(@NotNull final Project project, @NotNull PsiFile psiFile, @NotNull final VirtualFile vFile) {
    return myDefaultUseScopesCache.get(vFile);
  }

  private GlobalSearchScope getInherentResolveScope(VirtualFile vFile) {
    ProjectFileIndex projectFileIndex = myProjectRootManager.getFileIndex();
    Module module = projectFileIndex.getModuleForFile(vFile);
    if (module != null) {
      boolean includeTests = projectFileIndex.isInTestSourceContent(vFile) ||
                             !projectFileIndex.isContentJavaSourceFile(vFile);
      return GlobalSearchScope.moduleWithDependenciesAndLibrariesScope(module, includeTests);
    }
    else {
      // resolve references in libraries in context of all modules which contain it
      List<Module> modulesLibraryUsedIn = new ArrayList<Module>();
      List<OrderEntry> orderEntries = projectFileIndex.getOrderEntriesForFile(vFile);

      for (OrderEntry entry : orderEntries) {
        ProgressManager.checkCanceled();

        if (entry instanceof JdkOrderEntry) {
          return ((ProjectRootManagerEx)myProjectRootManager).getScopeForJdk((JdkOrderEntry)entry);
        }

        if (entry instanceof LibraryOrderEntry || entry instanceof ModuleOrderEntry) {
          modulesLibraryUsedIn.add(entry.getOwnerModule());
        }
      }

      return ((ProjectRootManagerEx)myProjectRootManager).getScopeForLibraryUsedIn(modulesLibraryUsedIn);
    }
  }

  @NotNull
  public GlobalSearchScope getUseScope(@NotNull PsiElement element) {
    VirtualFile vFile;
    final GlobalSearchScope allScope = GlobalSearchScope.allScope(myManager.getProject());
    if (element instanceof PsiDirectory) {
      vFile = ((PsiDirectory)element).getVirtualFile();
    }
    else {
      final PsiFile containingFile = element.getContainingFile();
      if (containingFile == null) return allScope;
      final VirtualFile virtualFile = containingFile.getVirtualFile();
      if (virtualFile == null) return allScope;
      vFile = virtualFile.getParent();
    }

    if (vFile == null) return allScope;
    ProjectFileIndex projectFileIndex = myProjectRootManager.getFileIndex();
    Module module = projectFileIndex.getModuleForFile(vFile);
    if (module != null) {
      boolean isTest = projectFileIndex.isInTestSourceContent(vFile);
      return isTest
             ? GlobalSearchScope.moduleTestsWithDependentsScope(module)
             : GlobalSearchScope.moduleWithDependentsScope(module);
    }
    else {
      final PsiFile f = element.getContainingFile();
      final VirtualFile vf = f == null ? null : f.getVirtualFile();

      return f == null || vf == null || vf.isDirectory() || allScope.contains(vf)
             ? allScope : GlobalSearchScope.fileScope(f).uniteWith(allScope);
    }
  }

  @Nullable
  private PsiFile createFileCopyWithNewName(VirtualFile vFile, String name) {
    // TODO[ik] remove this. Event handling and generation must be in view providers mechanism since we
    // need to track changes in _all_ psi views (e.g. namespace changes in XML)
    final FileTypeManager instance = FileTypeManager.getInstance();
    if(instance.isFileIgnored(name)) return null;
    final FileType fileTypeByFileName = instance.getFileTypeByFileName(name);
    final Document document = FileDocumentManager.getInstance().getDocument(vFile);
    return PsiFileFactory.getInstance(myManager.getProject()).createFileFromText(name, fileTypeByFileName,
                                                                                document != null ? document.getCharsSequence() : "", vFile.getModificationStamp(),
                                                                                true, false);
  }

  @Nullable
  public PsiDirectory findDirectory(@NotNull VirtualFile vFile) {
    LOG.assertTrue(myInitialized, "Access to psi files should be performed only after startup activity");
    LOG.assertTrue(!myDisposed, "Access to psi files should not be performed after disposal");

    ApplicationManager.getApplication().assertReadAccessAllowed();
    if (!vFile.isValid()) {
      LOG.error("File is not valid:" + vFile.getName());
    }

    if (!vFile.isDirectory()) return null;
    dispatchPendingEvents();

    return findDirectoryImpl(vFile);
  }

  private PsiDirectory findDirectoryImpl(final VirtualFile vFile) {
    PsiDirectory psiDir = myVFileToPsiDirMap.get(vFile);
    if (psiDir != null) return psiDir;

    if (myProjectRootManager.getFileIndex().isIgnored(vFile)) return null;

    VirtualFile parent = vFile.getParent();
    if (parent != null) { //?
      findDirectoryImpl(parent);// need to cache parent directory - used for firing events
    }

    psiDir = PsiDirectoryFactory.getInstance(myManager.getProject()).createDirectory(vFile);
    return ConcurrencyUtil.cacheOrGet(myVFileToPsiDirMap, vFile, psiDir);
  }

  @Nullable
  private PsiFile getCachedPsiFileInner(VirtualFile file) {
    final FileViewProvider fileViewProvider = myVFileToViewProviderMap.get(file);
    return fileViewProvider instanceof SingleRootFileViewProvider
           ? ((SingleRootFileViewProvider)fileViewProvider).getCachedPsi(fileViewProvider.getBaseLanguage()) : null;
  }

  public List<PsiFile> getAllCachedFiles() {
    List<PsiFile> files = new ArrayList<PsiFile>();
    for (FileViewProvider provider : myVFileToViewProviderMap.values()) {
      if (provider instanceof SingleRootFileViewProvider) {
        files.add(((SingleRootFileViewProvider)provider).getCachedPsi(provider.getBaseLanguage()));
      }
    }
    return files;
  }

  private void removeInvalidFilesAndDirs(boolean useFind) {
    Map<VirtualFile, PsiDirectory> fileToPsiDirMap = new THashMap<VirtualFile, PsiDirectory>(myVFileToPsiDirMap);
    if (useFind) {
      myVFileToPsiDirMap.clear();
    }
    for (Iterator<VirtualFile> iterator = fileToPsiDirMap.keySet().iterator(); iterator.hasNext();) {
      VirtualFile vFile = iterator.next();
      if (!vFile.isValid()) {
        iterator.remove();
      }
      else {
        PsiDirectory psiDir = findDirectory(vFile);
        if (psiDir == null) {
          iterator.remove();
        }
      }
    }
    myVFileToPsiDirMap.clear();
    myVFileToPsiDirMap.putAll(fileToPsiDirMap);

    // note: important to update directories map first - findFile uses findDirectory!
    Map<VirtualFile, FileViewProvider> fileToPsiFileMap = new THashMap<VirtualFile, FileViewProvider>(myVFileToViewProviderMap);
    if (useFind) {
      myVFileToViewProviderMap.clear();
    }
    for (Iterator<VirtualFile> iterator = fileToPsiFileMap.keySet().iterator(); iterator.hasNext();) {
      VirtualFile vFile = iterator.next();

      if (!vFile.isValid()) {
        iterator.remove();
        continue;
      }

      if (useFind) {
        FileViewProvider view = fileToPsiFileMap.get(vFile);
        if (view == null) { // soft ref. collected
          iterator.remove();
          continue;
        }
        PsiFile psiFile1 = findFile(vFile);
        if (psiFile1 == null) {
          iterator.remove();
          continue;
        }

        PsiFile psi = view.getPsi(view.getBaseLanguage());
        if (psi == null || !psiFile1.getClass().equals(psi.getClass()) ||
             psiFile1.getViewProvider().getBaseLanguage() != view.getBaseLanguage() // e.g. JSP <-> JSPX
           ) {
          iterator.remove();
        }
        else if (psi instanceof PsiFileImpl) {
          ((PsiFileImpl)psi).clearCaches();
        }
      }
    }
    myVFileToViewProviderMap.clear();
    myVFileToViewProviderMap.putAll(fileToPsiFileMap);
  }

  public void reloadFromDisk(@NotNull PsiFile file) {
    reloadFromDisk(file, false);
  }

  private void reloadFromDisk(PsiFile file, boolean ignoreDocument) {
    VirtualFile vFile = file.getVirtualFile();
    assert vFile != null;

    if (!(file instanceof PsiBinaryFile)) {
      FileDocumentManager fileDocumentManager = myFileDocumentManager;
      Document document = fileDocumentManager.getCachedDocument(vFile);
      if (document != null && !ignoreDocument){
        fileDocumentManager.reloadFromDisk(document);
      }
      else{
        PsiTreeChangeEventImpl event = new PsiTreeChangeEventImpl(myManager);
        event.setParent(file);
        event.setFile(file);
        if (file instanceof PsiFileImpl && ((PsiFileImpl)file).isContentsLoaded()) {
          event.setOffset(0);
          event.setOldLength(file.getTextLength());
        }
        myManager.beforeChildrenChange(event);

        if (file instanceof PsiFileEx) {
          ((PsiFileEx)file).onContentReload();
        }

        myManager.childrenChanged(event);
      }
    }
  }

  private class MyVirtualFileListener extends VirtualFileAdapter {
    public void contentsChanged(final VirtualFileEvent event) {
      // handled by FileDocumentManagerListener
    }

    public void fileCreated(VirtualFileEvent event) {
      final VirtualFile vFile = event.getFile();

      ApplicationManager.getApplication().runWriteAction(
        new ExternalChangeAction() {
          public void run() {
            VirtualFile parent = vFile.getParent();
            PsiDirectory parentDir = parent == null ? null : myVFileToPsiDirMap.get(parent);
            if (parentDir == null) return; // do not notifyListeners event if parent directory was never accessed via PSI

            if (!vFile.isDirectory()) {
              PsiFile psiFile = findFile(vFile);
              if (psiFile != null && psiFile.getProject() == myManager.getProject()) {
                PsiTreeChangeEventImpl treeEvent = new PsiTreeChangeEventImpl(myManager);
                treeEvent.setParent(parentDir);
                myManager.beforeChildAddition(treeEvent);
                treeEvent.setChild(psiFile);
                myManager.childAdded(treeEvent);
              }
            }
            else {
              PsiDirectory psiDir = findDirectory(vFile);
              if (psiDir != null && psiDir.getProject() == myManager.getProject()) {
                PsiTreeChangeEventImpl treeEvent = new PsiTreeChangeEventImpl(myManager);
                treeEvent.setParent(parentDir);
                myManager.beforeChildAddition(treeEvent);
                treeEvent.setChild(psiDir);
                myManager.childAdded(treeEvent);
              }
            }
          }
        }
      );
    }

    public void beforeFileDeletion(VirtualFileEvent event) {
      final VirtualFile vFile = event.getFile();

      VirtualFile parent = vFile.getParent();
      final PsiDirectory parentDir = parent == null ? null : myVFileToPsiDirMap.get(parent);
      if (parentDir == null) return; // do not notify listeners if parent directory was never accessed via PSI

      ApplicationManager.getApplication().runWriteAction(
        new ExternalChangeAction() {
          public void run() {
            if (!vFile.isDirectory()) {
              PsiFile psiFile = getCachedPsiFile(vFile);
              if (psiFile != null) {
                PsiTreeChangeEventImpl treeEvent = new PsiTreeChangeEventImpl(myManager);
                treeEvent.setParent(parentDir);
                treeEvent.setChild(psiFile);
                myManager.beforeChildRemoval(treeEvent);
              }
            }
            else {
              PsiDirectory psiDir = findDirectory(vFile);
              if (psiDir != null) {
                PsiTreeChangeEventImpl treeEvent = new PsiTreeChangeEventImpl(myManager);
                treeEvent.setParent(parentDir);
                treeEvent.setChild(psiDir);
                myManager.beforeChildRemoval(treeEvent);
              }
            }
          }
        }
      );
    }

    public void fileDeleted(final VirtualFileEvent event) {
      final VirtualFile vFile = event.getFile();

      VirtualFile parent = event.getParent();
      final PsiDirectory parentDir = parent == null ? null : myVFileToPsiDirMap.get(parent);

      final PsiFile psiFile = getCachedPsiFileInner(vFile);
      if (psiFile != null) {
        myVFileToViewProviderMap.remove(vFile);

        if (parentDir != null) {
          ApplicationManager.getApplication().runWriteAction(new ExternalChangeAction() {
            public void run() {
              PsiTreeChangeEventImpl treeEvent = new PsiTreeChangeEventImpl(myManager);
              treeEvent.setParent(parentDir);
              treeEvent.setChild(psiFile);
              myManager.childRemoved(treeEvent);
            }
          });
        }
      }
      else {
        final PsiDirectory psiDir = myVFileToPsiDirMap.get(vFile);
        if (psiDir != null) {
          removeInvalidFilesAndDirs(false);

          if (parentDir != null) {
            ApplicationManager.getApplication().runWriteAction(new ExternalChangeAction() {
              public void run() {
                PsiTreeChangeEventImpl treeEvent = new PsiTreeChangeEventImpl(myManager);
                treeEvent.setParent(parentDir);
                treeEvent.setChild(psiDir);
                myManager.childRemoved(treeEvent);
              }
            });
          }
        }
      }
    }

    public void beforePropertyChange(final VirtualFilePropertyEvent event) {
      final VirtualFile vFile = event.getFile();
      final String propertyName = event.getPropertyName();

      VirtualFile parent = vFile.getParent();
      final PsiDirectory parentDir = parent == null ? null : myVFileToPsiDirMap.get(parent);
      if (parentDir == null) return; // do not notifyListeners event if parent directory was never accessed via PSI

      ApplicationManager.getApplication().runWriteAction(
        new ExternalChangeAction() {
          public void run() {
            PsiTreeChangeEventImpl treeEvent = new PsiTreeChangeEventImpl(myManager);
            treeEvent.setParent(parentDir);

            if (VirtualFile.PROP_NAME.equals(propertyName)) {
              final String newName = (String)event.getNewValue();

              if (vFile.isDirectory()) {
                PsiDirectory psiDir = findDirectory(vFile);
                if (psiDir != null) {
                  if (!myFileTypeManager.isFileIgnored(newName)) {
                    treeEvent.setChild(psiDir);
                    treeEvent.setPropertyName(PsiTreeChangeEvent.PROP_DIRECTORY_NAME);
                    treeEvent.setOldValue(vFile.getName());
                    treeEvent.setNewValue(newName);
                    myManager.beforePropertyChange(treeEvent);
                  }
                  else {
                    treeEvent.setChild(psiDir);
                    myManager.beforeChildRemoval(treeEvent);
                  }
                }
                else {
                  if (!isExcludeRoot(vFile) && !myFileTypeManager.isFileIgnored(newName)) {
                    myManager.beforeChildAddition(treeEvent);
                  }
                }
              }
              else {
                final FileViewProvider viewProvider = findViewProvider(vFile);
                PsiFile psiFile = viewProvider.getPsi(viewProvider.getBaseLanguage());
                PsiFile psiFile1 = createFileCopyWithNewName(vFile, newName);

                if (psiFile != null) {
                  if (psiFile1 == null) {
                    treeEvent.setChild(psiFile);
                    myManager.beforeChildRemoval(treeEvent);
                  }
                  else if (!psiFile1.getClass().equals(psiFile.getClass())) {
                    treeEvent.setOldChild(psiFile);
                    myManager.beforeChildReplacement(treeEvent);
                  }
                  else {
                    treeEvent.setChild(psiFile);
                    treeEvent.setPropertyName(PsiTreeChangeEvent.PROP_FILE_NAME);
                    treeEvent.setOldValue(vFile.getName());
                    treeEvent.setNewValue(newName);
                    myManager.beforePropertyChange(treeEvent);
                  }
                }
                else {
                  if (psiFile1 != null) {
                    myManager.beforeChildAddition(treeEvent);
                  }
                }
              }
            }
            else if (VirtualFile.PROP_WRITABLE.equals(propertyName)) {
              PsiFile psiFile = getCachedPsiFileInner(vFile);
              if (psiFile == null) return;

              treeEvent.setElement(psiFile);
              treeEvent.setPropertyName(PsiTreeChangeEvent.PROP_WRITABLE);
              treeEvent.setOldValue(event.getOldValue());
              treeEvent.setNewValue(event.getNewValue());
              myManager.beforePropertyChange(treeEvent);
            }
          }
        }
      );
    }

    private boolean isExcludeRoot(VirtualFile file) {
      VirtualFile parent = file.getParent();
      if (parent == null) return false;

      Module module = myProjectRootManager.getFileIndex().getModuleForFile(parent);
      if (module == null) return false;
      VirtualFile[] excludeRoots = ModuleRootManager.getInstance(module).getExcludeRoots();
      for (VirtualFile root : excludeRoots) {
        if (root.equals(file)) return true;
      }
      return false;
    }

    public void propertyChanged(final VirtualFilePropertyEvent event) {
      final String propertyName = event.getPropertyName();
      final VirtualFile vFile = event.getFile();

      final FileViewProvider oldFileViewProvider = findViewProvider(vFile);
      final PsiFile oldPsiFile;
      if (oldFileViewProvider instanceof SingleRootFileViewProvider) {
        oldPsiFile = ((SingleRootFileViewProvider)oldFileViewProvider).getCachedPsi(oldFileViewProvider.getBaseLanguage());
      }
      else {
        oldPsiFile = null;
      }

      VirtualFile parent = vFile.getParent();
      final PsiDirectory parentDir = parent == null ? null : myVFileToPsiDirMap.get(parent);
      if (parentDir == null) {
        boolean fire = VirtualFile.PROP_NAME.equals(propertyName) && vFile.isDirectory();
        if (fire) {
          PsiDirectory psiDir = myVFileToPsiDirMap.get(vFile);
          fire = psiDir != null;
        }
        if (!fire) return; // do not fire event if parent directory was never accessed via PSI
      }

      if (oldPsiFile != null && oldPsiFile.isPhysical()) {
        SmartPointerManagerImpl.fastenBelts(oldPsiFile);
      }
      ApplicationManager.getApplication().runWriteAction(
        new ExternalChangeAction() {
          public void run() {
            PsiTreeChangeEventImpl treeEvent = new PsiTreeChangeEventImpl(myManager);
            treeEvent.setParent(parentDir);

            if (VirtualFile.PROP_NAME.equals(propertyName)) {
              if (vFile.isDirectory()) {
                PsiDirectory psiDir = myVFileToPsiDirMap.get(vFile);
                if (psiDir != null) {
                  if (myFileTypeManager.isFileIgnored(vFile)) {
                    removeFilesAndDirsRecursively(vFile);

                    treeEvent.setChild(psiDir);
                    myManager.childRemoved(treeEvent);
                  }
                  else {
                    treeEvent.setElement(psiDir);
                    treeEvent.setPropertyName(PsiTreeChangeEvent.PROP_DIRECTORY_NAME);
                    treeEvent.setOldValue(event.getOldValue());
                    treeEvent.setNewValue(event.getNewValue());
                    myManager.propertyChanged(treeEvent);
                  }
                }
                else {
                  PsiDirectory psiDir1 = findDirectory(vFile);
                  if (psiDir1 != null) {
                    treeEvent.setChild(psiDir1);
                    myManager.childAdded(treeEvent);
                  }
                }
              }
              else {
                final FileViewProvider fileViewProvider = createFileViewProvider(vFile, true);
                final PsiFile newPsiFile = fileViewProvider.getPsi(fileViewProvider.getBaseLanguage());
                if(oldPsiFile != null) {
                  if (newPsiFile == null) {
                    myVFileToViewProviderMap.remove(vFile);

                    treeEvent.setChild(oldPsiFile);
                    myManager.childRemoved(treeEvent);
                  }
                  else if (!newPsiFile.getClass().equals(oldPsiFile.getClass()) ||
                           newPsiFile.getFileType() != myFileTypeManager.getFileTypeByFileName((String)event.getOldValue()) ||
                           languageDialectChanged(newPsiFile, (String)event.getOldValue()) ||
                           !oldFileViewProvider.getLanguages().equals(fileViewProvider.getLanguages()) ||
                           FileContentUtil.FORCE_RELOAD_REQUESTOR.equals(event.getRequestor())
                    ) {
                    myVFileToViewProviderMap.put(vFile, fileViewProvider);

                    treeEvent.setOldChild(oldPsiFile);
                    treeEvent.setNewChild(newPsiFile);
                    myManager.childReplaced(treeEvent);
                  }
                  else {
                    treeEvent.setElement(oldPsiFile);
                    treeEvent.setPropertyName(PsiTreeChangeEvent.PROP_FILE_NAME);
                    treeEvent.setOldValue(event.getOldValue());
                    treeEvent.setNewValue(event.getNewValue());
                    myManager.propertyChanged(treeEvent);
                  }
                }
                else if (newPsiFile != null) {
                  myVFileToViewProviderMap.put(vFile, fileViewProvider);
                  treeEvent.setChild(newPsiFile);
                  myManager.childAdded(treeEvent);
                }
              }
            }
            else if (VirtualFile.PROP_WRITABLE.equals(propertyName)) {
              if (oldPsiFile == null) return;

              treeEvent.setElement(oldPsiFile);
              treeEvent.setPropertyName(PsiTreeChangeEvent.PROP_WRITABLE);
              treeEvent.setOldValue(event.getOldValue());
              treeEvent.setNewValue(event.getNewValue());
              myManager.propertyChanged(treeEvent);
            }
            else if (VirtualFile.PROP_ENCODING.equals(propertyName)) {
              if (oldPsiFile == null) return;

              treeEvent.setElement(oldPsiFile);
              treeEvent.setPropertyName(VirtualFile.PROP_ENCODING);
              treeEvent.setOldValue(event.getOldValue());
              treeEvent.setNewValue(event.getNewValue());
              myManager.propertyChanged(treeEvent);
            }
          }
        }
      );
    }

    public void beforeFileMovement(VirtualFileMoveEvent event) {
      final VirtualFile vFile = event.getFile();

      final PsiDirectory oldParentDir = findDirectory(event.getOldParent());
      final PsiDirectory newParentDir = findDirectory(event.getNewParent());
      if (oldParentDir == null && newParentDir == null) return;
      if (myFileTypeManager.isFileIgnored(vFile)) return;

      ApplicationManager.getApplication().runWriteAction(
        new ExternalChangeAction() {
          public void run() {
            PsiTreeChangeEventImpl treeEvent = new PsiTreeChangeEventImpl(myManager);

            boolean isExcluded = vFile.isDirectory() && myProjectFileIndex.isIgnored(vFile);
            if (oldParentDir != null && !isExcluded) {
              if (newParentDir != null) {
                treeEvent.setOldParent(oldParentDir);
                treeEvent.setNewParent(newParentDir);
                if (vFile.isDirectory()) {
                  PsiDirectory psiDir = findDirectory(vFile);
                  treeEvent.setChild(psiDir);
                }
                else {
                  PsiFile psiFile = findFile(vFile);
                  treeEvent.setChild(psiFile);
                }
                myManager.beforeChildMovement(treeEvent);
              }
              else {
                treeEvent.setParent(oldParentDir);
                if (vFile.isDirectory()) {
                  PsiDirectory psiDir = findDirectory(vFile);
                  treeEvent.setChild(psiDir);
                }
                else {
                  PsiFile psiFile = findFile(vFile);
                  treeEvent.setChild(psiFile);
                }
                myManager.beforeChildRemoval(treeEvent);
              }
            }
            else {
              LOG.assertTrue(newParentDir != null); // checked above
              treeEvent.setParent(newParentDir);
              myManager.beforeChildAddition(treeEvent);
            }
          }
        }
      );
    }

    public void fileMoved(VirtualFileMoveEvent event) {
      final VirtualFile vFile = event.getFile();

      final PsiDirectory oldParentDir = findDirectory(event.getOldParent());
      final PsiDirectory newParentDir = findDirectory(event.getNewParent());
      if (oldParentDir == null && newParentDir == null) return;

      final PsiElement oldElement = vFile.isDirectory() ? myVFileToPsiDirMap.get(vFile) : getCachedPsiFileInner(vFile);
      removeInvalidFilesAndDirs(true);
      final FileViewProvider viewProvider = findViewProvider(vFile);
      final PsiElement newElement;
      final FileViewProvider newViewProvider;
      if (!vFile.isDirectory()){
        newViewProvider = createFileViewProvider(vFile, true);
        newElement = newViewProvider.getPsi(viewProvider.getBaseLanguage());
      }
      else {
        newElement = findDirectory(vFile);
        newViewProvider = null;
      }

      if (oldElement == null && newElement == null) return;

      ApplicationManager.getApplication().runWriteAction(
        new ExternalChangeAction() {
          public void run() {
            PsiTreeChangeEventImpl treeEvent = new PsiTreeChangeEventImpl(myManager);
            if (oldElement == null) {
              myVFileToViewProviderMap.put(vFile, newViewProvider);
              treeEvent.setParent(newParentDir);
              treeEvent.setChild(newElement);
              myManager.childAdded(treeEvent);
            }
            else {
              if (newElement == null) {
                myVFileToViewProviderMap.remove(vFile);
                treeEvent.setParent(oldParentDir);
                treeEvent.setChild(oldElement);
                myManager.childRemoved(treeEvent);
              }
              else {
                if (oldElement.getClass().equals(newElement.getClass())) {
                  treeEvent.setOldParent(oldParentDir);
                  treeEvent.setNewParent(newParentDir);
                  treeEvent.setChild(newElement);
                  myManager.childMoved(treeEvent);
                }
                else {
                  myVFileToViewProviderMap.put(vFile, newViewProvider);
                  PsiTreeChangeEventImpl treeRemoveEvent = new PsiTreeChangeEventImpl(myManager);
                  treeRemoveEvent.setParent(oldParentDir);
                  treeRemoveEvent.setChild(oldElement);
                  myManager.childRemoved(treeRemoveEvent);
                  PsiTreeChangeEventImpl treeAddEvent = new PsiTreeChangeEventImpl(myManager);
                  treeAddEvent.setParent(newParentDir);
                  treeAddEvent.setChild(newElement);
                  myManager.childAdded(treeAddEvent);
                }
              }
            }
          }
        }
      );
    }

    private void removeFilesAndDirsRecursively(VirtualFile vFile) {
      if (vFile.isDirectory()) {
        myVFileToPsiDirMap.remove(vFile);

        VirtualFile[] children = vFile.getChildren();
        for (VirtualFile child : children) {
          removeFilesAndDirsRecursively(child);
        }
      }
      else myVFileToViewProviderMap.remove(vFile);
    }
  }

  // When file is renamed so that extension changes then language dialect might change and thus psiFile should be invalidated
  private static boolean languageDialectChanged(final PsiFile newPsiFile, String oldFileName) {
    return newPsiFile != null && !FileUtil.getExtension(newPsiFile.getName()).equals(FileUtil.getExtension(oldFileName));
  }

  private class MyModuleRootListener implements ModuleRootListener {
    private VirtualFile[] myOldContentRoots = null;
    private volatile int depthCounter = 0;
    public void beforeRootsChange(final ModuleRootEvent event) {
      if (!myInitialized) return;
      if (event.isCausedByFileTypesChange()) return;
      ApplicationManager.getApplication().runWriteAction(
        new ExternalChangeAction() {
          public void run() {
            depthCounter++;
            if (depthCounter > 1) return;

            PsiTreeChangeEventImpl treeEvent = new PsiTreeChangeEventImpl(myManager);
            treeEvent.setPropertyName(PsiTreeChangeEvent.PROP_ROOTS);
            final VirtualFile[] contentRoots = myProjectRootManager.getContentRoots();
            LOG.assertTrue(myOldContentRoots == null);
            myOldContentRoots = contentRoots;
            treeEvent.setOldValue(contentRoots);
            myManager.beforePropertyChange(treeEvent);
          }
        }
      );
    }

    public void rootsChanged(final ModuleRootEvent event) {
      dispatchPendingEvents();

      if (!myInitialized) return;
      if (event.isCausedByFileTypesChange()) return;
      ApplicationManager.getApplication().runWriteAction(
        new ExternalChangeAction() {
          public void run() {
            depthCounter--;
            assert depthCounter >= 0 : depthCounter;
            if (depthCounter > 0) return;

            removeInvalidFilesAndDirs(true);

            PsiTreeChangeEventImpl treeEvent = new PsiTreeChangeEventImpl(myManager);
            treeEvent.setPropertyName(PsiTreeChangeEvent.PROP_ROOTS);
            final VirtualFile[] contentRoots = myProjectRootManager.getContentRoots();
            treeEvent.setNewValue(contentRoots);
            LOG.assertTrue(myOldContentRoots != null);
            treeEvent.setOldValue(myOldContentRoots);
            myOldContentRoots = null;
            myManager.propertyChanged(treeEvent);
          }
        }
      );
    }
  }

  @SuppressWarnings({"HardCodedStringLiteral"})
  public void dumpFilesWithContentLoaded(Writer out) throws IOException {
    out.write("Files with content loaded cached in FileManagerImpl:\n");
    Set<VirtualFile> vFiles = myVFileToViewProviderMap.keySet();
    for (VirtualFile fileCacheEntry : vFiles) {
      final FileViewProvider view = myVFileToViewProviderMap.get(fileCacheEntry);
      PsiFile psiFile = view.getPsi(view.getBaseLanguage());
      if (psiFile instanceof PsiFileImpl && ((PsiFileImpl)psiFile).isContentsLoaded()) {
        out.write(fileCacheEntry.getPresentableUrl());
        out.write("\n");
      }
    }
  }

  private class MyFileDocumentManagerAdapter extends FileDocumentManagerAdapter {
    public void fileWithNoDocumentChanged(VirtualFile file) {
      final PsiFile psiFile = getCachedPsiFileInner(file);
      if (psiFile != null) {
        ApplicationManager.getApplication().runWriteAction(
          new ExternalChangeAction() {
            public void run() {
              reloadFromDisk(psiFile, true); // important to ignore document which might appear already!
            }
          }
        );
      }
    }
  }
}


text:
import { log, GoogleAnalyticsEvent } from "./logger";
import { Action } from "./Webamp";

function logEventFromAction(action: Action): GoogleAnalyticsEvent | null {
  switch (action.type) {
    case "IS_PLAYING": {
      return { category: "Media", action: "IsPlaying" };
    }
    case "PAUSE": {
      return { category: "Media", action: "Pause" };
    }
    case "STOP": {
      return { category: "Media", action: "Stop" };
    }
    case "TOGGLE_REPEAT":
      return { category: "Media", action: "ToggleRepeat" };
    case "TOGGLE_SHUFFLE":
      return { category: "Media", action: "ToggleShuffle" };
    case "TOGGLE_DOUBLESIZE_MODE":
      return { category: "Display", action: "ToggleDoublesizeMode" };
    case "TOGGLE_VISUALIZER_STYLE":
      return { category: "Display", action: "ToggleVisualizerStyle" };
    case "SET_SKIN_DATA":
      return { category: "Display", action: "SetSkinData" };
    case "CLOSE_WINAMP":
      return { category: "Display", action: "CloseWinamp" };
    case "OPEN_WINAMP":
      return { category: "Display", action: "OpenWinamp" };
    case "SET_MILKDROP_DESKTOP":
      return { category: "Milkdrop", action: "SetMilkdropDesktop" };
    case "SET_MILKDROP_FULLSCREEN":
      return { category: "Milkdrop", action: "SetMilkdropFullscreen" };
    case "TOGGLE_PRESET_OVERLAY":
      return { category: "Milkdrop", action: "TogglePresetOverlay" };
    case "TOGGLE_RANDOMIZE_PRESETS":
      return { category: "Milkdrop", action: "ToggleRandomizePresets" };
    case "TOGGLE_PRESET_CYCLING":
      return { category: "Milkdrop", action: "TogglePresetCycling" };
    case "CLICKED_TRACK":
      return { category: "Playlist", action: "ClickedTrack" };
    case "CTRL_CLICKED_TRACK":
      return { category: "Playlist", action: "CtrlClickedTrack" };
    case "SHIFT_CLICKED_TRACK":
      return { category: "Playlist", action: "ShiftClickedTrack" };
    case "SELECT_ALL":
      return { category: "Playlist", action: "SelectAll" };
    case "SELECT_ZERO":
      return { category: "Playlist", action: "SelectZero" };
    case "INVERT_SELECTION":
      return { category: "Playlist", action: "InvertSelection" };
    /* This is triggered programatically when you load a new track
    case "REMOVE_ALL_TRACKS":
      return {
        category: "Playlist",
        action: "RemoveAllTracks",
      };
    */
    case "REVERSE_LIST":
      return { category: "Playlist", action: "ReverseList" };
    case "RANDOMIZE_LIST":
      return { category: "Playlist", action: "RandomizeList" };
    case "ENABLE_MILKDROP":
      return { category: "Windows", action: "EnableMilkdrop" };
    case "TOGGLE_WINDOW_SHADE_MODE":
      return {
        category: "Windows",
        action: "ToggleWindowShadeMode",
        label: action.windowId,
      };
    case "TOGGLE_WINDOW":
      return {
        category: "Windows",
        action: "ToggleWindow",
        label: action.windowId,
      };
    case "CLOSE_WINDOW":
      return {
        category: "Windows",
        action: "CloseWindow",
        label: action.windowId,
      };
    case "SET_WINDOW_VISIBILITY":
      return {
        category: "Windows",
        action: "CloseWindow",
        label: `${action.windowId}:${action.hidden ? "hidden" : "visibile"}`,
      };
    case "MAIN_CONTEXT_MENU_OPENED":
      return { category: "ContextMenu", action: "MainContextMenuOpened" };
    case "DROPPED_FILES":
      return {
        category: "DroppedFiles",
        action: action.windowId,
        label: action.firstFileName ?? "[UNKNOWN]",
        value: action.count,
      };
    case "OPENED_FILES":
      return {
        category: "OpenedFiles",
        action: action.expectedType,
        label: action.firstFileName ?? "[UNKNOWN]",
        value: action.count,
      };
    case "TOGGLE_LLAMA_MODE":
      return { category: "Hotkeys", action: "ToggledLlamaMode" };
  }
  return null;
}

export const loggerMiddleware =
  () => (next: (action: Action) => void) => (action: Action) => {
    const event = logEventFromAction(action);
    if (event != null) {
      log(event);
    }
    return next(action);
  };


text:
package eus.ixa.ixa.pipe.nerc.train;

import opennlp.tools.namefind.TokenNameFinderModel;
import opennlp.tools.util.TrainingParameters;

/**
 * This interface defines the feature creation, the training method and the
 * evaluation of the trained model.
 * @author ragerri
 * @version 2014-07-11
 */
public interface Trainer {

  /**
   * Generate {@link TokenNameFinderModel} models.
   * @param params
   *          the training parameters file
   * @return the model
   */
  TokenNameFinderModel train(TrainingParameters params);

}


text:
#import <Foundation/NSObject.h>

@class NSArray;

@interface NSHost : NSObject {
   NSString *_name;
   NSArray  *_addresses;
}

+(BOOL)isHostCacheEnabled;
+(void)setHostCacheEnabled:(BOOL)value;
+(void)flushHostCache;

+(NSHost *)currentHost;

+(NSHost *)hostWithName:(NSString *)name;
+(NSHost *)hostWithAddress:(NSString *)address;

-(BOOL)isEqualToHost:(NSHost *)host;

-(NSArray *)names;
-(NSString *)name;

-(NSArray *)addresses;
-(NSString *)address;

@end


text:
package org.olat.course.assessment.model;

import java.io.Serializable;
import java.util.List;

/**
 *
 * Initial date: 20.11.2013<br>
 * @author srosse, stephane.rosse@frentix.com, http://www.frentix.com
 *
 */
public class BulkAssessmentDatas implements Serializable {

	private static final long serialVersionUID = 8109609348537626355L;
	private List<BulkAssessmentRow> rows;
	private String returnFiles;
	private String dataBackupFile;
	private BulkAssessmentColumnSettings columnsSettings;

	public BulkAssessmentColumnSettings getColumnsSettings() {
		return columnsSettings;
	}

	public void setColumnsSettings(BulkAssessmentColumnSettings columnsSettings) {
		this.columnsSettings = columnsSettings;
	}

	public int getRowsSize() {
		return rows == null ? 0 : rows.size();
	}

	public List<BulkAssessmentRow> getRows() {
		return rows;
	}

	public void setRows(List<BulkAssessmentRow> rows) {
		this.rows = rows;
	}

	public String getReturnFiles() {
		return returnFiles;
	}

	public void setReturnFiles(String returnFiles) {
		this.returnFiles = returnFiles;
	}

	public String getDataBackupFile() {
		return dataBackupFile;
	}

	public void setDataBackupFile(String dataBackupFile) {
		this.dataBackupFile = dataBackupFile;
	}
}


text:
require 'spree_core'
require 'spree_workshop/engine'


text:
package com.cloudray.scalapress.plugin.search.tags

import org.scalatest.{OneInstancePerTest, FunSuite}
import org.scalatest.mock.MockitoSugar

/** @author Stephen Samuel */
class TagsWidgetTest extends FunSuite with OneInstancePerTest with MockitoSugar {

    test("render tags adds spans") {
        val tags = Seq("eastwood", "morricone")
        val actual = new TagsWidget()._renderTags(tags)
        assert(Seq(eastwood, morricone) === actual)
    }
}


text:
namespace zetasql {
namespace {

TEST(PrepareCompletionReqTest, Empty) {
  const std::string body;
  const ExecuteQueryCompletionRequest got = PrepareCompletionReq(body, 0);
  EXPECT_TRUE(got.body.empty());
  EXPECT_EQ(got.cursor_position, 0);
  EXPECT_EQ(got.word_start, 0);
  EXPECT_EQ(got.word_end, 0);
  EXPECT_TRUE(got.word.empty());
}

TEST(PrepareCompletionReqTest, SingleWord) {
  const std::string body = "SELECT";

  {
    const ExecuteQueryCompletionRequest got = PrepareCompletionReq(body, 0);
    EXPECT_EQ(got.body, "SELECT");
    EXPECT_EQ(got.cursor_position, 0);
    EXPECT_EQ(got.word_start, 0);
    EXPECT_EQ(got.word_end, 0);
    EXPECT_TRUE(got.word.empty());
  }

  {
    const ExecuteQueryCompletionRequest got = PrepareCompletionReq(body, 4);
    EXPECT_EQ(got.body, "SELECT");
    EXPECT_EQ(got.cursor_position, 4);
    EXPECT_EQ(got.word_start, 0);
    EXPECT_EQ(got.word_end, 4);
    EXPECT_EQ(got.word, "SELE");
  }

  {
    const ExecuteQueryCompletionRequest got = PrepareCompletionReq(body, 6);
    EXPECT_EQ(got.body, "SELECT");
    EXPECT_EQ(got.cursor_position, 6);
    EXPECT_EQ(got.word_start, 0);
    EXPECT_EQ(got.word_end, 6);
    EXPECT_EQ(got.word, "SELECT");
  }
}

TEST(PrepareCompletionReqTest, Middle) {
  const std::string body = "Hello world test";

  {
    const ExecuteQueryCompletionRequest got = PrepareCompletionReq(body, 9);
    EXPECT_EQ(got.body, "Hello world test");
    EXPECT_EQ(got.cursor_position, 9);
    EXPECT_EQ(got.word_start, 6);
    EXPECT_EQ(got.word_end, 9);
    EXPECT_EQ(got.word, "wor");
  }

  {
    const ExecuteQueryCompletionRequest got = PrepareCompletionReq(body, 11);
    EXPECT_EQ(got.body, "Hello world test");
    EXPECT_EQ(got.cursor_position, 11);
    EXPECT_EQ(got.word_start, 6);
    EXPECT_EQ(got.word_end, 11);
    EXPECT_EQ(got.word, "world");
  }
}

}  // namespace
}  // namespace zetasql


text:
package ch.bfh.categorizer;

/**
 * Enum Sentiment Analysis
 */
public enum ModelLanguage {
    EN, DE
}


text:
import axios from 'axios';
import {reqhost} from './api'

export const getBlog = params => axios.get(`${reqhost}/blog`, { params });


text:
package io.spine.server.delivery;

import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableSet;
import io.spine.type.TypeUrl;
import org.checkerframework.checker.nullness.qual.Nullable;

import java.util.Set;

import static java.lang.String.format;

/**
 * An exception telling that the projection catch-up cannot be started, since some of the requested
 * entities are already catching up.
 */
public final class CatchUpAlreadyStartedException extends IllegalStateException {

    private static final long serialVersionUID = 0L;

    private final TypeUrl projectionStateType;
    private final @Nullable ImmutableSet<Object> requestedIds;

    CatchUpAlreadyStartedException(TypeUrl type, @Nullable Set<?> ids) {
        super();
        projectionStateType = type;
        requestedIds = ids == null ? null : ImmutableSet.copyOf(ids);
    }

    @Override
    public String getMessage() {
        var message = format(
                "Cannot start the catch-up for the `%s` Projection, `%s`. " +
                        "Another catch-up is already in progress.",
                projectionStateType, targetsAsString());
        return message;
    }

    /**
     * Returns the type URL of the projection for which the catch-up was requested.
     */
    public TypeUrl projectionStateType() {
        return projectionStateType;
    }

    /**
     * Returns the IDs of the targets which were asked to catch up.
     *
     * <p>If all the projection entities were specified as a target, returns an empty {@code Set}.
     */
    public ImmutableSet<Object> requestedIds() {
        return requestedIds == null? ImmutableSet.of() : requestedIds;
    }

    private String targetsAsString() {
        if (requestedIds == null) {
            return "[all instances]";
        }
        return Joiner.on(',')
                     .join(requestedIds);
    }
}