text:
package alpha

import (
	"context"
	"crypto/sha256"
	"encoding/json"
	"fmt"
	"time"

	"google.golang.org/api/googleapi"
	"github.com/GoogleCloudPlatform/declarative-resource-client-library/dcl"
)

type CertificateTemplate struct {
	Name                  *string                                   `json:"name"`
	PredefinedValues      *CertificateTemplatePredefinedValues      `json:"predefinedValues"`
	IdentityConstraints   *CertificateTemplateIdentityConstraints   `json:"identityConstraints"`
	PassthroughExtensions *CertificateTemplatePassthroughExtensions `json:"passthroughExtensions"`
	Description           *string                                   `json:"description"`
	CreateTime            *string                                   `json:"createTime"`
	UpdateTime            *string                                   `json:"updateTime"`
	Labels                map[string]string                         `json:"labels"`
	Project               *string                                   `json:"project"`
	Location              *string                                   `json:"location"`
}

func (r *CertificateTemplate) String() string {
	return dcl.SprintResource(r)
}

// The enum CertificateTemplatePassthroughExtensionsKnownExtensionsEnum.
type CertificateTemplatePassthroughExtensionsKnownExtensionsEnum string

// CertificateTemplatePassthroughExtensionsKnownExtensionsEnumRef returns a *CertificateTemplatePassthroughExtensionsKnownExtensionsEnum with the value of string s
// If the empty string is provided, nil is returned.
func CertificateTemplatePassthroughExtensionsKnownExtensionsEnumRef(s string) *CertificateTemplatePassthroughExtensionsKnownExtensionsEnum {
	v := CertificateTemplatePassthroughExtensionsKnownExtensionsEnum(s)
	return &v
}

func (v CertificateTemplatePassthroughExtensionsKnownExtensionsEnum) Validate() error {
	if string(v) == "" {
		// Empty enum is okay.
		return nil
	}
	for _, s := range []string{"KNOWN_CERTIFICATE_EXTENSION_UNSPECIFIED", "BASE_KEY_USAGE", "EXTENDED_KEY_USAGE", "CA_OPTIONS", "POLICY_IDS", "AIA_OCSP_SERVERS"} {
		if string(v) == s {
			return nil
		}
	}
	return &dcl.EnumInvalidError{
		Enum:  "CertificateTemplatePassthroughExtensionsKnownExtensionsEnum",
		Value: string(v),
		Valid: []string{},
	}
}

type CertificateTemplatePredefinedValues struct {
	empty                bool                                                      `json:"-"`
	KeyUsage             *CertificateTemplatePredefinedValuesKeyUsage              `json:"keyUsage"`
	CaOptions            *CertificateTemplatePredefinedValuesCaOptions             `json:"caOptions"`
	PolicyIds            []CertificateTemplatePredefinedValuesPolicyIds            `json:"policyIds"`
	AiaOcspServers       []string                                                  `json:"aiaOcspServers"`
	AdditionalExtensions []CertificateTemplatePredefinedValuesAdditionalExtensions `json:"additionalExtensions"`
}

type jsonCertificateTemplatePredefinedValues CertificateTemplatePredefinedValues

func (r *CertificateTemplatePredefinedValues) UnmarshalJSON(data []byte) error {
	var res jsonCertificateTemplatePredefinedValues
	if err := json.Unmarshal(data, &res); err != nil {
		return err
	}

	var m map[string]interface{}
	json.Unmarshal(data, &m)

	if len(m) == 0 {
		*r = *EmptyCertificateTemplatePredefinedValues
	} else {

		r.KeyUsage = res.KeyUsage

		r.CaOptions = res.CaOptions

		r.PolicyIds = res.PolicyIds

		r.AiaOcspServers = res.AiaOcspServers

		r.AdditionalExtensions = res.AdditionalExtensions

	}
	return nil
}

// This object is used to assert a desired state where this CertificateTemplatePredefinedValues is
// empty. Go lacks global const objects, but this object should be treated
// as one. Modifying this object will have undesirable results.
var EmptyCertificateTemplatePredefinedValues *CertificateTemplatePredefinedValues = &CertificateTemplatePredefinedValues{empty: true}

func (r *CertificateTemplatePredefinedValues) Empty() bool {
	return r.empty
}

func (r *CertificateTemplatePredefinedValues) String() string {
	return dcl.SprintResource(r)
}

func (r *CertificateTemplatePredefinedValues) HashCode() string {
	// Placeholder for a more complex hash method that handles ordering, etc
	// Hash resource body for easy comparison later
	hash := sha256.New().Sum([]byte(r.String()))
	return fmt.Sprintf("%x", hash)
}

type CertificateTemplatePredefinedValuesKeyUsage struct {
	empty                    bool                                                                  `json:"-"`
	BaseKeyUsage             *CertificateTemplatePredefinedValuesKeyUsageBaseKeyUsage              `json:"baseKeyUsage"`
	ExtendedKeyUsage         *CertificateTemplatePredefinedValuesKeyUsageExtendedKeyUsage          `json:"extendedKeyUsage"`
	UnknownExtendedKeyUsages []CertificateTemplatePredefinedValuesKeyUsageUnknownExtendedKeyUsages `json:"unknownExtendedKeyUsages"`
}

type jsonCertificateTemplatePredefinedValuesKeyUsage CertificateTemplatePredefinedValuesKeyUsage

func (r *CertificateTemplatePredefinedValuesKeyUsage) UnmarshalJSON(data []byte) error {
	var res jsonCertificateTemplatePredefinedValuesKeyUsage
	if err := json.Unmarshal(data, &res); err != nil {
		return err
	}

	var m map[string]interface{}
	json.Unmarshal(data, &m)

	if len(m) == 0 {
		*r = *EmptyCertificateTemplatePredefinedValuesKeyUsage
	} else {

		r.BaseKeyUsage = res.BaseKeyUsage

		r.ExtendedKeyUsage = res.ExtendedKeyUsage

		r.UnknownExtendedKeyUsages = res.UnknownExtendedKeyUsages

	}
	return nil
}

// This object is used to assert a desired state where this CertificateTemplatePredefinedValuesKeyUsage is
// empty. Go lacks global const objects, but this object should be treated
// as one. Modifying this object will have undesirable results.
var EmptyCertificateTemplatePredefinedValuesKeyUsage *CertificateTemplatePredefinedValuesKeyUsage = &CertificateTemplatePredefinedValuesKeyUsage{empty: true}

func (r *CertificateTemplatePredefinedValuesKeyUsage) Empty() bool {
	return r.empty
}

func (r *CertificateTemplatePredefinedValuesKeyUsage) String() string {
	return dcl.SprintResource(r)
}

func (r *CertificateTemplatePredefinedValuesKeyUsage) HashCode() string {
	// Placeholder for a more complex hash method that handles ordering, etc
	// Hash resource body for easy comparison later
	hash := sha256.New().Sum([]byte(r.String()))
	return fmt.Sprintf("%x", hash)
}

type CertificateTemplatePredefinedValuesKeyUsageBaseKeyUsage struct {
	empty             bool  `json:"-"`
	DigitalSignature  *bool `json:"digitalSignature"`
	ContentCommitment *bool `json:"contentCommitment"`
	KeyEncipherment   *bool `json:"keyEncipherment"`
	DataEncipherment  *bool `json:"dataEncipherment"`
	KeyAgreement      *bool `json:"keyAgreement"`
	CertSign          *bool `json:"certSign"`
	CrlSign           *bool `json:"crlSign"`
	EncipherOnly      *bool `json:"encipherOnly"`
	DecipherOnly      *bool `json:"decipherOnly"`
}

type jsonCertificateTemplatePredefinedValuesKeyUsageBaseKeyUsage CertificateTemplatePredefinedValuesKeyUsageBaseKeyUsage

func (r *CertificateTemplatePredefinedValuesKeyUsageBaseKeyUsage) UnmarshalJSON(data []byte) error {
	var res jsonCertificateTemplatePredefinedValuesKeyUsageBaseKeyUsage
	if err := json.Unmarshal(data, &res); err != nil {
		return err
	}

	var m map[string]interface{}
	json.Unmarshal(data, &m)

	if len(m) == 0 {
		*r = *EmptyCertificateTemplatePredefinedValuesKeyUsageBaseKeyUsage
	} else {

		r.DigitalSignature = res.DigitalSignature

		r.ContentCommitment = res.ContentCommitment

		r.KeyEncipherment = res.KeyEncipherment

		r.DataEncipherment = res.DataEncipherment

		r.KeyAgreement = res.KeyAgreement

		r.CertSign = res.CertSign

		r.CrlSign = res.CrlSign

		r.EncipherOnly = res.EncipherOnly

		r.DecipherOnly = res.DecipherOnly

	}
	return nil
}

// This object is used to assert a desired state where this CertificateTemplatePredefinedValuesKeyUsageBaseKeyUsage is
// empty. Go lacks global const objects, but this object should be treated
// as one. Modifying this object will have undesirable results.
var EmptyCertificateTemplatePredefinedValuesKeyUsageBaseKeyUsage *CertificateTemplatePredefinedValuesKeyUsageBaseKeyUsage = &CertificateTemplatePredefinedValuesKeyUsageBaseKeyUsage{empty: true}

func (r *CertificateTemplatePredefinedValuesKeyUsageBaseKeyUsage) Empty() bool {
	return r.empty
}

func (r *CertificateTemplatePredefinedValuesKeyUsageBaseKeyUsage) String() string {
	return dcl.SprintResource(r)
}

func (r *CertificateTemplatePredefinedValuesKeyUsageBaseKeyUsage) HashCode() string {
	// Placeholder for a more complex hash method that handles ordering, etc
	// Hash resource body for easy comparison later
	hash := sha256.New().Sum([]byte(r.String()))
	return fmt.Sprintf("%x", hash)
}

type CertificateTemplatePredefinedValuesKeyUsageExtendedKeyUsage struct {
	empty           bool  `json:"-"`
	ServerAuth      *bool `json:"serverAuth"`
	ClientAuth      *bool `json:"clientAuth"`
	CodeSigning     *bool `json:"codeSigning"`
	EmailProtection *bool `json:"emailProtection"`
	TimeStamping    *bool `json:"timeStamping"`
	OcspSigning     *bool `json:"ocspSigning"`
}

type jsonCertificateTemplatePredefinedValuesKeyUsageExtendedKeyUsage CertificateTemplatePredefinedValuesKeyUsageExtendedKeyUsage

func (r *CertificateTemplatePredefinedValuesKeyUsageExtendedKeyUsage) UnmarshalJSON(data []byte) error {
	var res jsonCertificateTemplatePredefinedValuesKeyUsageExtendedKeyUsage
	if err := json.Unmarshal(data, &res); err != nil {
		return err
	}

	var m map[string]interface{}
	json.Unmarshal(data, &m)

	if len(m) == 0 {
		*r = *EmptyCertificateTemplatePredefinedValuesKeyUsageExtendedKeyUsage
	} else {

		r.ServerAuth = res.ServerAuth

		r.ClientAuth = res.ClientAuth

		r.CodeSigning = res.CodeSigning

		r.EmailProtection = res.EmailProtection

		r.TimeStamping = res.TimeStamping

		r.OcspSigning = res.OcspSigning

	}
	return nil
}

// This object is used to assert a desired state where this CertificateTemplatePredefinedValuesKeyUsageExtendedKeyUsage is
// empty. Go lacks global const objects, but this object should be treated
// as one. Modifying this object will have undesirable results.
var EmptyCertificateTemplatePredefinedValuesKeyUsageExtendedKeyUsage *CertificateTemplatePredefinedValuesKeyUsageExtendedKeyUsage = &CertificateTemplatePredefinedValuesKeyUsageExtendedKeyUsage{empty: true}

func (r *CertificateTemplatePredefinedValuesKeyUsageExtendedKeyUsage) Empty() bool {
	return r.empty
}

func (r *CertificateTemplatePredefinedValuesKeyUsageExtendedKeyUsage) String() string {
	return dcl.SprintResource(r)
}

func (r *CertificateTemplatePredefinedValuesKeyUsageExtendedKeyUsage) HashCode() string {
	// Placeholder for a more complex hash method that handles ordering, etc
	// Hash resource body for easy comparison later
	hash := sha256.New().Sum([]byte(r.String()))
	return fmt.Sprintf("%x", hash)
}

type CertificateTemplatePredefinedValuesKeyUsageUnknownExtendedKeyUsages struct {
	empty        bool    `json:"-"`
	ObjectIdPath []int64 `json:"objectIdPath"`
}

type jsonCertificateTemplatePredefinedValuesKeyUsageUnknownExtendedKeyUsages CertificateTemplatePredefinedValuesKeyUsageUnknownExtendedKeyUsages

func (r *CertificateTemplatePredefinedValuesKeyUsageUnknownExtendedKeyUsages) UnmarshalJSON(data []byte) error {
	var res jsonCertificateTemplatePredefinedValuesKeyUsageUnknownExtendedKeyUsages
	if err := json.Unmarshal(data, &res); err != nil {
		return err
	}

	var m map[string]interface{}
	json.Unmarshal(data, &m)

	if len(m) == 0 {
		*r = *EmptyCertificateTemplatePredefinedValuesKeyUsageUnknownExtendedKeyUsages
	} else {

		r.ObjectIdPath = res.ObjectIdPath

	}
	return nil
}

// This object is used to assert a desired state where this CertificateTemplatePredefinedValuesKeyUsageUnknownExtendedKeyUsages is
// empty. Go lacks global const objects, but this object should be treated
// as one. Modifying this object will have undesirable results.
var EmptyCertificateTemplatePredefinedValuesKeyUsageUnknownExtendedKeyUsages *CertificateTemplatePredefinedValuesKeyUsageUnknownExtendedKeyUsages = &CertificateTemplatePredefinedValuesKeyUsageUnknownExtendedKeyUsages{empty: true}

func (r *CertificateTemplatePredefinedValuesKeyUsageUnknownExtendedKeyUsages) Empty() bool {
	return r.empty
}

func (r *CertificateTemplatePredefinedValuesKeyUsageUnknownExtendedKeyUsages) String() string {
	return dcl.SprintResource(r)
}

func (r *CertificateTemplatePredefinedValuesKeyUsageUnknownExtendedKeyUsages) HashCode() string {
	// Placeholder for a more complex hash method that handles ordering, etc
	// Hash resource body for easy comparison later
	hash := sha256.New().Sum([]byte(r.String()))
	return fmt.Sprintf("%x", hash)
}

type CertificateTemplatePredefinedValuesCaOptions struct {
	empty               bool   `json:"-"`
	IsCa                *bool  `json:"isCa"`
	MaxIssuerPathLength *int64 `json:"maxIssuerPathLength"`
}

type jsonCertificateTemplatePredefinedValuesCaOptions CertificateTemplatePredefinedValuesCaOptions

func (r *CertificateTemplatePredefinedValuesCaOptions) UnmarshalJSON(data []byte) error {
	var res jsonCertificateTemplatePredefinedValuesCaOptions
	if err := json.Unmarshal(data, &res); err != nil {
		return err
	}

	var m map[string]interface{}
	json.Unmarshal(data, &m)

	if len(m) == 0 {
		*r = *EmptyCertificateTemplatePredefinedValuesCaOptions
	} else {

		r.IsCa = res.IsCa

		r.MaxIssuerPathLength = res.MaxIssuerPathLength

	}
	return nil
}

// This object is used to assert a desired state where this CertificateTemplatePredefinedValuesCaOptions is
// empty. Go lacks global const objects, but this object should be treated
// as one. Modifying this object will have undesirable results.
var EmptyCertificateTemplatePredefinedValuesCaOptions *CertificateTemplatePredefinedValuesCaOptions = &CertificateTemplatePredefinedValuesCaOptions{empty: true}

func (r *CertificateTemplatePredefinedValuesCaOptions) Empty() bool {
	return r.empty
}

func (r *CertificateTemplatePredefinedValuesCaOptions) String() string {
	return dcl.SprintResource(r)
}

func (r *CertificateTemplatePredefinedValuesCaOptions) HashCode() string {
	// Placeholder for a more complex hash method that handles ordering, etc
	// Hash resource body for easy comparison later
	hash := sha256.New().Sum([]byte(r.String()))
	return fmt.Sprintf("%x", hash)
}

type CertificateTemplatePredefinedValuesPolicyIds struct {
	empty        bool    `json:"-"`
	ObjectIdPath []int64 `json:"objectIdPath"`
}

type jsonCertificateTemplatePredefinedValuesPolicyIds CertificateTemplatePredefinedValuesPolicyIds

func (r *CertificateTemplatePredefinedValuesPolicyIds) UnmarshalJSON(data []byte) error {
	var res jsonCertificateTemplatePredefinedValuesPolicyIds
	if err := json.Unmarshal(data, &res); err != nil {
		return err
	}

	var m map[string]interface{}
	json.Unmarshal(data, &m)

	if len(m) == 0 {
		*r = *EmptyCertificateTemplatePredefinedValuesPolicyIds
	} else {

		r.ObjectIdPath = res.ObjectIdPath

	}
	return nil
}

// This object is used to assert a desired state where this CertificateTemplatePredefinedValuesPolicyIds is
// empty. Go lacks global const objects, but this object should be treated
// as one. Modifying this object will have undesirable results.
var EmptyCertificateTemplatePredefinedValuesPolicyIds *CertificateTemplatePredefinedValuesPolicyIds = &CertificateTemplatePredefinedValuesPolicyIds{empty: true}

func (r *CertificateTemplatePredefinedValuesPolicyIds) Empty() bool {
	return r.empty
}

func (r *CertificateTemplatePredefinedValuesPolicyIds) String() string {
	return dcl.SprintResource(r)
}

func (r *CertificateTemplatePredefinedValuesPolicyIds) HashCode() string {
	// Placeholder for a more complex hash method that handles ordering, etc
	// Hash resource body for easy comparison later
	hash := sha256.New().Sum([]byte(r.String()))
	return fmt.Sprintf("%x", hash)
}

type CertificateTemplatePredefinedValuesAdditionalExtensions struct {
	empty    bool                                                             `json:"-"`
	ObjectId *CertificateTemplatePredefinedValuesAdditionalExtensionsObjectId `json:"objectId"`
	Critical *bool                                                            `json:"critical"`
	Value    *string                                                          `json:"value"`
}

type jsonCertificateTemplatePredefinedValuesAdditionalExtensions CertificateTemplatePredefinedValuesAdditionalExtensions

func (r *CertificateTemplatePredefinedValuesAdditionalExtensions) UnmarshalJSON(data []byte) error {
	var res jsonCertificateTemplatePredefinedValuesAdditionalExtensions
	if err := json.Unmarshal(data, &res); err != nil {
		return err
	}

	var m map[string]interface{}
	json.Unmarshal(data, &m)

	if len(m) == 0 {
		*r = *EmptyCertificateTemplatePredefinedValuesAdditionalExtensions
	} else {

		r.ObjectId = res.ObjectId

		r.Critical = res.Critical

		r.Value = res.Value

	}
	return nil
}

// This object is used to assert a desired state where this CertificateTemplatePredefinedValuesAdditionalExtensions is
// empty. Go lacks global const objects, but this object should be treated
// as one. Modifying this object will have undesirable results.
var EmptyCertificateTemplatePredefinedValuesAdditionalExtensions *CertificateTemplatePredefinedValuesAdditionalExtensions = &CertificateTemplatePredefinedValuesAdditionalExtensions{empty: true}

func (r *CertificateTemplatePredefinedValuesAdditionalExtensions) Empty() bool {
	return r.empty
}

func (r *CertificateTemplatePredefinedValuesAdditionalExtensions) String() string {
	return dcl.SprintResource(r)
}

func (r *CertificateTemplatePredefinedValuesAdditionalExtensions) HashCode() string {
	// Placeholder for a more complex hash method that handles ordering, etc
	// Hash resource body for easy comparison later
	hash := sha256.New().Sum([]byte(r.String()))
	return fmt.Sprintf("%x", hash)
}

type CertificateTemplatePredefinedValuesAdditionalExtensionsObjectId struct {
	empty        bool    `json:"-"`
	ObjectIdPath []int64 `json:"objectIdPath"`
}

type jsonCertificateTemplatePredefinedValuesAdditionalExtensionsObjectId CertificateTemplatePredefinedValuesAdditionalExtensionsObjectId

func (r *CertificateTemplatePredefinedValuesAdditionalExtensionsObjectId) UnmarshalJSON(data []byte) error {
	var res jsonCertificateTemplatePredefinedValuesAdditionalExtensionsObjectId
	if err := json.Unmarshal(data, &res); err != nil {
		return err
	}

	var m map[string]interface{}
	json.Unmarshal(data, &m)

	if len(m) == 0 {
		*r = *EmptyCertificateTemplatePredefinedValuesAdditionalExtensionsObjectId
	} else {

		r.ObjectIdPath = res.ObjectIdPath

	}
	return nil
}

// This object is used to assert a desired state where this CertificateTemplatePredefinedValuesAdditionalExtensionsObjectId is
// empty. Go lacks global const objects, but this object should be treated
// as one. Modifying this object will have undesirable results.
var EmptyCertificateTemplatePredefinedValuesAdditionalExtensionsObjectId *CertificateTemplatePredefinedValuesAdditionalExtensionsObjectId = &CertificateTemplatePredefinedValuesAdditionalExtensionsObjectId{empty: true}

func (r *CertificateTemplatePredefinedValuesAdditionalExtensionsObjectId) Empty() bool {
	return r.empty
}

func (r *CertificateTemplatePredefinedValuesAdditionalExtensionsObjectId) String() string {
	return dcl.SprintResource(r)
}

func (r *CertificateTemplatePredefinedValuesAdditionalExtensionsObjectId) HashCode() string {
	// Placeholder for a more complex hash method that handles ordering, etc
	// Hash resource body for easy comparison later
	hash := sha256.New().Sum([]byte(r.String()))
	return fmt.Sprintf("%x", hash)
}

type CertificateTemplateIdentityConstraints struct {
	empty                           bool                                                 `json:"-"`
	CelExpression                   *CertificateTemplateIdentityConstraintsCelExpression `json:"celExpression"`
	AllowSubjectPassthrough         *bool                                                `json:"allowSubjectPassthrough"`
	AllowSubjectAltNamesPassthrough *bool                                                `json:"allowSubjectAltNamesPassthrough"`
}

type jsonCertificateTemplateIdentityConstraints CertificateTemplateIdentityConstraints

func (r *CertificateTemplateIdentityConstraints) UnmarshalJSON(data []byte) error {
	var res jsonCertificateTemplateIdentityConstraints
	if err := json.Unmarshal(data, &res); err != nil {
		return err
	}

	var m map[string]interface{}
	json.Unmarshal(data, &m)

	if len(m) == 0 {
		*r = *EmptyCertificateTemplateIdentityConstraints
	} else {

		r.CelExpression = res.CelExpression

		r.AllowSubjectPassthrough = res.AllowSubjectPassthrough

		r.AllowSubjectAltNamesPassthrough = res.AllowSubjectAltNamesPassthrough

	}
	return nil
}

// This object is used to assert a desired state where this CertificateTemplateIdentityConstraints is
// empty. Go lacks global const objects, but this object should be treated
// as one. Modifying this object will have undesirable results.
var EmptyCertificateTemplateIdentityConstraints *CertificateTemplateIdentityConstraints = &CertificateTemplateIdentityConstraints{empty: true}

func (r *CertificateTemplateIdentityConstraints) Empty() bool {
	return r.empty
}

func (r *CertificateTemplateIdentityConstraints) String() string {
	return dcl.SprintResource(r)
}

func (r *CertificateTemplateIdentityConstraints) HashCode() string {
	// Placeholder for a more complex hash method that handles ordering, etc
	// Hash resource body for easy comparison later
	hash := sha256.New().Sum([]byte(r.String()))
	return fmt.Sprintf("%x", hash)
}

type CertificateTemplateIdentityConstraintsCelExpression struct {
	empty       bool    `json:"-"`
	Expression  *string `json:"expression"`
	Title       *string `json:"title"`
	Description *string `json:"description"`
	Location    *string `json:"location"`
}

type jsonCertificateTemplateIdentityConstraintsCelExpression CertificateTemplateIdentityConstraintsCelExpression

func (r *CertificateTemplateIdentityConstraintsCelExpression) UnmarshalJSON(data []byte) error {
	var res jsonCertificateTemplateIdentityConstraintsCelExpression
	if err := json.Unmarshal(data, &res); err != nil {
		return err
	}

	var m map[string]interface{}
	json.Unmarshal(data, &m)

	if len(m) == 0 {
		*r = *EmptyCertificateTemplateIdentityConstraintsCelExpression
	} else {

		r.Expression = res.Expression

		r.Title = res.Title

		r.Description = res.Description

		r.Location = res.Location

	}
	return nil
}

// This object is used to assert a desired state where this CertificateTemplateIdentityConstraintsCelExpression is
// empty. Go lacks global const objects, but this object should be treated
// as one. Modifying this object will have undesirable results.
var EmptyCertificateTemplateIdentityConstraintsCelExpression *CertificateTemplateIdentityConstraintsCelExpression = &CertificateTemplateIdentityConstraintsCelExpression{empty: true}

func (r *CertificateTemplateIdentityConstraintsCelExpression) Empty() bool {
	return r.empty
}

func (r *CertificateTemplateIdentityConstraintsCelExpression) String() string {
	return dcl.SprintResource(r)
}

func (r *CertificateTemplateIdentityConstraintsCelExpression) HashCode() string {
	// Placeholder for a more complex hash method that handles ordering, etc
	// Hash resource body for easy comparison later
	hash := sha256.New().Sum([]byte(r.String()))
	return fmt.Sprintf("%x", hash)
}

type CertificateTemplatePassthroughExtensions struct {
	empty                bool                                                           `json:"-"`
	KnownExtensions      []CertificateTemplatePassthroughExtensionsKnownExtensionsEnum  `json:"knownExtensions"`
	AdditionalExtensions []CertificateTemplatePassthroughExtensionsAdditionalExtensions `json:"additionalExtensions"`
}

type jsonCertificateTemplatePassthroughExtensions CertificateTemplatePassthroughExtensions

func (r *CertificateTemplatePassthroughExtensions) UnmarshalJSON(data []byte) error {
	var res jsonCertificateTemplatePassthroughExtensions
	if err := json.Unmarshal(data, &res); err != nil {
		return err
	}

	var m map[string]interface{}
	json.Unmarshal(data, &m)

	if len(m) == 0 {
		*r = *EmptyCertificateTemplatePassthroughExtensions
	} else {

		r.KnownExtensions = res.KnownExtensions

		r.AdditionalExtensions = res.AdditionalExtensions

	}
	return nil
}

// This object is used to assert a desired state where this CertificateTemplatePassthroughExtensions is
// empty. Go lacks global const objects, but this object should be treated
// as one. Modifying this object will have undesirable results.
var EmptyCertificateTemplatePassthroughExtensions *CertificateTemplatePassthroughExtensions = &CertificateTemplatePassthroughExtensions{empty: true}

func (r *CertificateTemplatePassthroughExtensions) Empty() bool {
	return r.empty
}

func (r *CertificateTemplatePassthroughExtensions) String() string {
	return dcl.SprintResource(r)
}

func (r *CertificateTemplatePassthroughExtensions) HashCode() string {
	// Placeholder for a more complex hash method that handles ordering, etc
	// Hash resource body for easy comparison later
	hash := sha256.New().Sum([]byte(r.String()))
	return fmt.Sprintf("%x", hash)
}

type CertificateTemplatePassthroughExtensionsAdditionalExtensions struct {
	empty        bool    `json:"-"`
	ObjectIdPath []int64 `json:"objectIdPath"`
}

type jsonCertificateTemplatePassthroughExtensionsAdditionalExtensions CertificateTemplatePassthroughExtensionsAdditionalExtensions

func (r *CertificateTemplatePassthroughExtensionsAdditionalExtensions) UnmarshalJSON(data []byte) error {
	var res jsonCertificateTemplatePassthroughExtensionsAdditionalExtensions
	if err := json.Unmarshal(data, &res); err != nil {
		return err
	}

	var m map[string]interface{}
	json.Unmarshal(data, &m)

	if len(m) == 0 {
		*r = *EmptyCertificateTemplatePassthroughExtensionsAdditionalExtensions
	} else {

		r.ObjectIdPath = res.ObjectIdPath

	}
	return nil
}

// This object is used to assert a desired state where this CertificateTemplatePassthroughExtensionsAdditionalExtensions is
// empty. Go lacks global const objects, but this object should be treated
// as one. Modifying this object will have undesirable results.
var EmptyCertificateTemplatePassthroughExtensionsAdditionalExtensions *CertificateTemplatePassthroughExtensionsAdditionalExtensions = &CertificateTemplatePassthroughExtensionsAdditionalExtensions{empty: true}

func (r *CertificateTemplatePassthroughExtensionsAdditionalExtensions) Empty() bool {
	return r.empty
}

func (r *CertificateTemplatePassthroughExtensionsAdditionalExtensions) String() string {
	return dcl.SprintResource(r)
}

func (r *CertificateTemplatePassthroughExtensionsAdditionalExtensions) HashCode() string {
	// Placeholder for a more complex hash method that handles ordering, etc
	// Hash resource body for easy comparison later
	hash := sha256.New().Sum([]byte(r.String()))
	return fmt.Sprintf("%x", hash)
}

// Describe returns a simple description of this resource to ensure that automated tools
// can identify it.
func (r *CertificateTemplate) Describe() dcl.ServiceTypeVersion {
	return dcl.ServiceTypeVersion{
		Service: "privateca",
		Type:    "CertificateTemplate",
		Version: "alpha",
	}
}

func (r *CertificateTemplate) ID() (string, error) {
	if err := extractCertificateTemplateFields(r); err != nil {
		return "", err
	}
	nr := r.urlNormalized()
	params := map[string]interface{}{
		"name":                   dcl.ValueOrEmptyString(nr.Name),
		"predefined_values":      dcl.ValueOrEmptyString(nr.PredefinedValues),
		"identity_constraints":   dcl.ValueOrEmptyString(nr.IdentityConstraints),
		"passthrough_extensions": dcl.ValueOrEmptyString(nr.PassthroughExtensions),
		"description":            dcl.ValueOrEmptyString(nr.Description),
		"create_time":            dcl.ValueOrEmptyString(nr.CreateTime),
		"update_time":            dcl.ValueOrEmptyString(nr.UpdateTime),
		"labels":                 dcl.ValueOrEmptyString(nr.Labels),
		"project":                dcl.ValueOrEmptyString(nr.Project),
		"location":               dcl.ValueOrEmptyString(nr.Location),
	}
	return dcl.Nprintf("projects/{{project}}/locations/{{location}}/certificateTemplates/{{name}}", params), nil
}

const CertificateTemplateMaxPage = -1

type CertificateTemplateList struct {
	Items []*CertificateTemplate

	nextToken string

	pageSize int32

	resource *CertificateTemplate
}

func (l *CertificateTemplateList) HasNext() bool {
	return l.nextToken != ""
}

func (l *CertificateTemplateList) Next(ctx context.Context, c *Client) error {
	ctx, cancel := context.WithTimeout(ctx, c.Config.TimeoutOr(0*time.Second))
	defer cancel()

	if !l.HasNext() {
		return fmt.Errorf("no next page")
	}
	items, token, err := c.listCertificateTemplate(ctx, l.resource, l.nextToken, l.pageSize)
	if err != nil {
		return err
	}
	l.Items = items
	l.nextToken = token
	return err
}

func (c *Client) ListCertificateTemplate(ctx context.Context, project, location string) (*CertificateTemplateList, error) {
	ctx = dcl.ContextWithRequestID(ctx)
	ctx, cancel := context.WithTimeout(ctx, c.Config.TimeoutOr(0*time.Second))
	defer cancel()

	return c.ListCertificateTemplateWithMaxResults(ctx, project, location, CertificateTemplateMaxPage)

}

func (c *Client) ListCertificateTemplateWithMaxResults(ctx context.Context, project, location string, pageSize int32) (*CertificateTemplateList, error) {
	ctx, cancel := context.WithTimeout(ctx, c.Config.TimeoutOr(0*time.Second))
	defer cancel()

	// Create a resource object so that we can use proper url normalization methods.
	r := &CertificateTemplate{
		Project:  &project,
		Location: &location,
	}
	items, token, err := c.listCertificateTemplate(ctx, r, "", pageSize)
	if err != nil {
		return nil, err
	}
	return &CertificateTemplateList{
		Items:     items,
		nextToken: token,
		pageSize:  pageSize,
		resource:  r,
	}, nil
}

func (c *Client) GetCertificateTemplate(ctx context.Context, r *CertificateTemplate) (*CertificateTemplate, error) {
	ctx = dcl.ContextWithRequestID(ctx)
	ctx, cancel := context.WithTimeout(ctx, c.Config.TimeoutOr(0*time.Second))
	defer cancel()

	// This is *purposefully* supressing errors.
	// This function is used with url-normalized values + not URL normalized values.
	// URL Normalized values will throw unintentional errors, since those values are not of the proper parent form.
	extractCertificateTemplateFields(r)

	b, err := c.getCertificateTemplateRaw(ctx, r)
	if err != nil {
		if dcl.IsNotFound(err) {
			return nil, &googleapi.Error{
				Code:    404,
				Message: err.Error(),
			}
		}
		return nil, err
	}
	result, err := unmarshalCertificateTemplate(b, c, r)
	if err != nil {
		return nil, err
	}
	result.Project = r.Project
	result.Location = r.Location
	result.Name = r.Name

	c.Config.Logger.InfoWithContextf(ctx, "Retrieved raw result state: %v", result)
	c.Config.Logger.InfoWithContextf(ctx, "Canonicalizing with specified state: %v", r)
	result, err = canonicalizeCertificateTemplateNewState(c, result, r)
	if err != nil {
		return nil, err
	}
	if err := postReadExtractCertificateTemplateFields(result); err != nil {
		return result, err
	}
	c.Config.Logger.InfoWithContextf(ctx, "Created result state: %v", result)

	return result, nil
}

func (c *Client) DeleteCertificateTemplate(ctx context.Context, r *CertificateTemplate) error {
	ctx = dcl.ContextWithRequestID(ctx)
	ctx, cancel := context.WithTimeout(ctx, c.Config.TimeoutOr(0*time.Second))
	defer cancel()

	if r == nil {
		return fmt.Errorf("CertificateTemplate resource is nil")
	}
	c.Config.Logger.InfoWithContext(ctx, "Deleting CertificateTemplate...")
	deleteOp := deleteCertificateTemplateOperation{}
	return deleteOp.do(ctx, r, c)
}

// DeleteAllCertificateTemplate deletes all resources that the filter functions returns true on.
func (c *Client) DeleteAllCertificateTemplate(ctx context.Context, project, location string, filter func(*CertificateTemplate) bool) error {
	listObj, err := c.ListCertificateTemplate(ctx, project, location)
	if err != nil {
		return err
	}

	err = c.deleteAllCertificateTemplate(ctx, filter, listObj.Items)
	if err != nil {
		return err
	}
	for listObj.HasNext() {
		err = listObj.Next(ctx, c)
		if err != nil {
			return nil
		}
		err = c.deleteAllCertificateTemplate(ctx, filter, listObj.Items)
		if err != nil {
			return err
		}
	}
	return nil
}

func (c *Client) ApplyCertificateTemplate(ctx context.Context, rawDesired *CertificateTemplate, opts ...dcl.ApplyOption) (*CertificateTemplate, error) {
	ctx, cancel := context.WithTimeout(ctx, c.Config.TimeoutOr(0*time.Second))
	defer cancel()

	ctx = dcl.ContextWithRequestID(ctx)
	var resultNewState *CertificateTemplate
	err := dcl.Do(ctx, func(ctx context.Context) (*dcl.RetryDetails, error) {
		newState, err := applyCertificateTemplateHelper(c, ctx, rawDesired, opts...)
		resultNewState = newState
		if err != nil {
			// If the error is 409, there is conflict in resource update.
			// Here we want to apply changes based on latest state.
			if dcl.IsConflictError(err) {
				return &dcl.RetryDetails{}, dcl.OperationNotDone{Err: err}
			}
			return nil, err
		}
		return nil, nil
	}, c.Config.RetryProvider)
	return resultNewState, err
}

func applyCertificateTemplateHelper(c *Client, ctx context.Context, rawDesired *CertificateTemplate, opts ...dcl.ApplyOption) (*CertificateTemplate, error) {
	c.Config.Logger.InfoWithContext(ctx, "Beginning ApplyCertificateTemplate...")
	c.Config.Logger.InfoWithContextf(ctx, "User specified desired state: %v", rawDesired)

	// 1.1: Validation of user-specified fields in desired state.
	if err := rawDesired.validate(); err != nil {
		return nil, err
	}

	if err := extractCertificateTemplateFields(rawDesired); err != nil {
		return nil, err
	}

	initial, desired, fieldDiffs, err := c.certificateTemplateDiffsForRawDesired(ctx, rawDesired, opts...)
	if err != nil {
		return nil, fmt.Errorf("failed to create a diff: %w", err)
	}

	diffs, err := convertFieldDiffsToCertificateTemplateDiffs(c.Config, fieldDiffs, opts)
	if err != nil {
		return nil, err
	}

	// TODO(magic-modules-eng): 2.2 Feasibility check (all updates are feasible so far).

	// 2.3: Lifecycle Directive Check
	var create bool
	lp := dcl.FetchLifecycleParams(opts)
	if initial == nil {
		if dcl.HasLifecycleParam(lp, dcl.BlockCreation) {
			return nil, dcl.ApplyInfeasibleError{Message: fmt.Sprintf("Creation blocked by lifecycle params: %#v.", desired)}
		}
		create = true
	} else if dcl.HasLifecycleParam(lp, dcl.BlockAcquire) {
		return nil, dcl.ApplyInfeasibleError{
			Message: fmt.Sprintf("Resource already exists - apply blocked by lifecycle params: %#v.", initial),
		}
	} else {
		for _, d := range diffs {
			if d.RequiresRecreate {
				return nil, dcl.ApplyInfeasibleError{
					Message: fmt.Sprintf("infeasible update: (%v) would require recreation", d),
				}
			}
			if dcl.HasLifecycleParam(lp, dcl.BlockModification) {
				return nil, dcl.ApplyInfeasibleError{Message: fmt.Sprintf("Modification blocked, diff (%v) unresolvable.", d)}
			}
		}
	}

	// 2.4 Imperative Request Planning
	var ops []certificateTemplateApiOperation
	if create {
		ops = append(ops, &createCertificateTemplateOperation{})
	} else {
		for _, d := range diffs {
			ops = append(ops, d.UpdateOp)
		}
	}
	c.Config.Logger.InfoWithContextf(ctx, "Created plan: %#v", ops)

	// 2.5 Request Actuation
	for _, op := range ops {
		c.Config.Logger.InfoWithContextf(ctx, "Performing operation %T %+v", op, op)
		if err := op.do(ctx, desired, c); err != nil {
			c.Config.Logger.InfoWithContextf(ctx, "Failed operation %T %+v: %v", op, op, err)
			return nil, err
		}
		c.Config.Logger.InfoWithContextf(ctx, "Finished operation %T %+v", op, op)
	}
	return applyCertificateTemplateDiff(c, ctx, desired, rawDesired, ops, opts...)
}

func applyCertificateTemplateDiff(c *Client, ctx context.Context, desired *CertificateTemplate, rawDesired *CertificateTemplate, ops []certificateTemplateApiOperation, opts ...dcl.ApplyOption) (*CertificateTemplate, error) {
	// 3.1, 3.2a Retrieval of raw new state & canonicalization with desired state
	c.Config.Logger.InfoWithContext(ctx, "Retrieving raw new state...")
	rawNew, err := c.GetCertificateTemplate(ctx, desired)
	if err != nil {
		return nil, err
	}
	// Get additional values from the first response.
	// These values should be merged into the newState above.
	if len(ops) > 0 {
		lastOp := ops[len(ops)-1]
		if o, ok := lastOp.(*createCertificateTemplateOperation); ok {
			if r, hasR := o.FirstResponse(); hasR {

				c.Config.Logger.InfoWithContext(ctx, "Retrieving raw new state from operation...")

				fullResp, err := unmarshalMapCertificateTemplate(r, c, rawDesired)
				if err != nil {
					return nil, err
				}

				rawNew, err = canonicalizeCertificateTemplateNewState(c, rawNew, fullResp)
				if err != nil {
					return nil, err
				}
			}
		}
	}

	c.Config.Logger.InfoWithContextf(ctx, "Canonicalizing with raw desired state: %v", rawDesired)
	// 3.2b Canonicalization of raw new state using raw desired state
	newState, err := canonicalizeCertificateTemplateNewState(c, rawNew, rawDesired)
	if err != nil {
		return rawNew, err
	}

	c.Config.Logger.InfoWithContextf(ctx, "Created canonical new state: %v", newState)
	// 3.3 Comparison of the new state and raw desired state.
	// TODO(magic-modules-eng): EVENTUALLY_CONSISTENT_UPDATE
	newDesired, err := canonicalizeCertificateTemplateDesiredState(rawDesired, newState)
	if err != nil {
		return newState, err
	}

	if err := postReadExtractCertificateTemplateFields(newState); err != nil {
		return newState, err
	}

	// Need to ensure any transformations made here match acceptably in differ.
	if err := postReadExtractCertificateTemplateFields(newDesired); err != nil {
		return newState, err
	}

	c.Config.Logger.InfoWithContextf(ctx, "Diffing using canonicalized desired state: %v", newDesired)
	newDiffs, err := diffCertificateTemplate(c, newDesired, newState)
	if err != nil {
		return newState, err
	}

	if len(newDiffs) == 0 {
		c.Config.Logger.InfoWithContext(ctx, "No diffs found. Apply was successful.")
	} else {
		c.Config.Logger.InfoWithContextf(ctx, "Found diffs: %v", newDiffs)
		diffMessages := make([]string, len(newDiffs))
		for i, d := range newDiffs {
			diffMessages[i] = fmt.Sprintf("%v", d)
		}
		return newState, dcl.DiffAfterApplyError{Diffs: diffMessages}
	}
	c.Config.Logger.InfoWithContext(ctx, "Done Apply.")
	return newState, nil
}


text:
import {roundedRect} from './Game';

export default class Player {
    constructor() {
        this.physics = {
            terminalVelocity: 7,
            gravity: 1,
            friction: 0.9
        };
        this.mouseDown = false;

        this.x = 20;
        this.y = 0;
        this.width = 30;
        this.height = 15;
        this.speed = 0;
        this.rotation = 0;
        this.acceleration = .6;
        this.topSpeed = 7;

        this.name = '';
        this.color = '';
        this.ID = null;
        this.totalDistance = 0;
        this.maxDistance = 0;
        this.isPlaying = false;
        this.isAlive = false;
        this.canceled = false;
        this.wins = 0;
        this.copter = Math.floor(Math.random() * 3)+1; //Get random copter
    }

    update(delta, fps) {
        delta = delta*fps / 3;
        if(this.mouseDown === true) {
            this.speed -= this.acceleration;
            if (this.speed < -this.topSpeed) this.speed = -this.topSpeed;
            this.rotation -= 0.0075;
            if (this.rotation < -0.25) this.rotation = -0.25;
        } else {
            this.speed = (this.speed + this.physics.gravity) * this.physics.friction;
            if(this.speed > this.physics.terminalVelocity) this.speed = this.physics.terminalVelocity;
            this.rotation += 0.015;
            if (this.rotation > 0.15) this.rotation = 0.15;
        }

        this.y += this.speed * delta;

        this.totalDistance += this.topSpeed * delta;
        if (this.maxDistance < this.totalDistance) {
            this.maxDistance = this.totalDistance;
        }
    }

    navigate(direction) {
        this.mouseDown = direction;
    }
};

redpajama_set_name: RedPajamaGithub


text:
package com.facebook.swift.codec.metadata;

import static com.facebook.swift.codec.metadata.ThriftFieldMetadata.isTypePredicate;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.Maps.uniqueIndex;

import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.Collection;
import java.util.List;
import java.util.SortedMap;

import javax.annotation.concurrent.Immutable;

import com.facebook.swift.codec.ThriftStruct;
import com.facebook.swift.codec.ThriftUnion;
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.collect.Collections2;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSortedMap;
import com.google.common.reflect.TypeToken;

@Immutable
public class ThriftStructMetadata
{
    public static enum MetadataType {

        STRUCT, UNION;

        public Class<? extends Annotation> getAnnotationType() {
            return annotationFor(this);
        }

        public static Class<? extends Annotation> annotationFor(final MetadataType metadataType) {
            switch (metadataType) {
                case STRUCT:
                    return ThriftStruct.class;
                case UNION:
                    return ThriftUnion.class;
                default:
                    throw new IllegalArgumentException("illegal argument in annotationFor: " + metadataType);
            }
        }

        public static MetadataType metadataTypeFor(final Class<?> annotation) {
            for (final MetadataType metadataType : MetadataType.values()) {
                if (annotationFor(metadataType).equals(annotation)) {
                    return metadataType;
                }
            }
            throw new IllegalArgumentException("illegal argument in metadataTypeFor: " + annotation);
        }
    }

    public static Class<?> findStructClass(final Type javaType) {
        final Class<?> rawType = TypeToken.of(javaType).getRawType();
        for (final Class<?> assignableType : TypeToken.of(rawType).getTypes().rawTypes()) {
            for (final MetadataType metadataType : MetadataType.values()) {
                if (assignableType.isAnnotationPresent(metadataType.getAnnotationType())) {
                    return assignableType;
                }
            }
        }
        return null;
    }

    public static MetadataType getMetadataType(Class<?> structClass) throws IllegalStateException {
        MetadataType result = null;
        for (MetadataType metadataType : MetadataType.values()) {
            if (structClass.isAnnotationPresent(metadataType.getAnnotationType())) {
                if (result == null) {
                    result = metadataType;
                } else {
                    final String msg = String.format(
                        "%s is annotated with @%s, however there is also a @%s annotation " +
                        "which is not allowed (thrift does not support polymorphic data types)",
                        structClass.toString(),
                        result.getAnnotationType().getSimpleName(),
                        metadataType.getAnnotationType().getSimpleName()
                    );
                    throw new IllegalStateException(msg);
                }
            }
        }
        if (result == null) {
            throw new IllegalStateException(
                "No metadata annotations were found on %s" + structClass.toString());
        }
        return result;
    }

    private final String structName;

    private final MetadataType metadataType;
    private final Optional<ThriftMethodInjection> builderMethod;
    private final ImmutableList<String> documentation;

    private final SortedMap<Short, ThriftFieldMetadata> fields;

    private final Optional<ThriftConstructorInjection> constructorInjection;

    private final List<ThriftMethodInjection> methodInjections;
    private final Type structType;
    private final Class<?> structClass;
    private final Type builderType;

    public ThriftStructMetadata(
            String structName,
            Type structType,
            Type builderType,
            MetadataType metadataType,
            Optional<ThriftMethodInjection> builderMethod,
            List<String> documentation,
            List<ThriftFieldMetadata> fields,
            Optional<ThriftConstructorInjection> constructorInjection,
            List<ThriftMethodInjection> methodInjections)
    {
        this.builderType = builderType;
        this.builderMethod = checkNotNull(builderMethod, "builderMethod is null");
        this.structName = checkNotNull(structName, "structName is null");
        this.metadataType = checkNotNull(metadataType, "metadataType is null");
        this.structType = checkNotNull(structType, "structType is null");
        this.structClass = findStructClass(this.structType);
        this.constructorInjection = checkNotNull(constructorInjection, "constructorInjection is null");
        this.documentation = ImmutableList.copyOf(checkNotNull(documentation, "documentation is null"));
        this.fields = ImmutableSortedMap.copyOf(uniqueIndex(checkNotNull(fields, "fields is null"), new Function<ThriftFieldMetadata, Short>()
        {
            @Override
            public Short apply(ThriftFieldMetadata input)
            {
                return input.getId();
            }
        }));
        this.methodInjections = ImmutableList.copyOf(checkNotNull(methodInjections, "methodInjections is null"));
    }

    public String getStructName()
    {
        return structName;
    }

    public Type getStructType()
    {
        return structType;
    }

    public Class<?> getStructClass()
    {
        return structClass;
    }

    public Type getBuilderType()
    {
        return builderType;
    }

    public Class<?> getBuilderClass()
    {
        return builderType == null ? null : TypeToken.of(builderType).getRawType();
    }

    public MetadataType getMetadataType()
    {
        return metadataType;
    }

    public Optional<ThriftMethodInjection> getBuilderMethod()
    {
        return builderMethod;
    }

    public ThriftFieldMetadata getField(int id)
    {
        return fields.get((short) id);
    }

    public ImmutableList<String> getDocumentation()
    {
        return documentation;
    }

    public Collection<ThriftFieldMetadata> getFields(FieldKind type)
    {
        return Collections2.filter(getFields(), isTypePredicate(type));
    }

    public Collection<ThriftFieldMetadata> getFields()
    {
        return fields.values();
    }

    public Optional<ThriftConstructorInjection> getConstructorInjection()
    {
        return constructorInjection;
    }

    public List<ThriftMethodInjection> getMethodInjections()
    {
        return methodInjections;
    }

    public boolean isException()
    {
        return Exception.class.isAssignableFrom(getStructClass());
    }

    public boolean isUnion()
    {
        return !isException() && getMetadataType() == MetadataType.UNION;
    }

    public boolean isStruct()
    {
        return !isException() && getMetadataType() == MetadataType.STRUCT;
    }

    @Override
    public String toString()
    {
        final StringBuilder sb = new StringBuilder();
        sb.append("ThriftStructMetadata");
        sb.append("{structName='").append(structName).append('\'');
        sb.append(", structType=").append(structType);
        sb.append(", builderType=").append(builderType);
        sb.append(", builderMethod=").append(builderMethod);
        sb.append(", fields=").append(fields);
        sb.append(", constructorInjection=").append(constructorInjection);
        sb.append(", methodInjections=").append(methodInjections);
        sb.append('}');
        return sb.toString();
    }
}


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

package messages

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

import (
	"net/http"
	"time"

	"golang.org/x/net/context"

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

	strfmt "github.com/go-openapi/strfmt"

	"github.com/olebedev/go-tgbot/models"
)

// NewEditMessageCaptionParams creates a new EditMessageCaptionParams object
// with the default values initialized.
func NewEditMessageCaptionParams() *EditMessageCaptionParams {
	var ()
	return &EditMessageCaptionParams{

		timeout: cr.DefaultTimeout,
	}
}

// NewEditMessageCaptionParamsWithTimeout creates a new EditMessageCaptionParams object
// with the default values initialized, and the ability to set a timeout on a request
func NewEditMessageCaptionParamsWithTimeout(timeout time.Duration) *EditMessageCaptionParams {
	var ()
	return &EditMessageCaptionParams{

		timeout: timeout,
	}
}

// NewEditMessageCaptionParamsWithContext creates a new EditMessageCaptionParams object
// with the default values initialized, and the ability to set a context for a request
func NewEditMessageCaptionParamsWithContext(ctx context.Context) *EditMessageCaptionParams {
	var ()
	return &EditMessageCaptionParams{

		Context: ctx,
	}
}

// NewEditMessageCaptionParamsWithHTTPClient creates a new EditMessageCaptionParams object
// with the default values initialized, and the ability to set a custom HTTPClient for a request
func NewEditMessageCaptionParamsWithHTTPClient(client *http.Client) *EditMessageCaptionParams {
	var ()
	return &EditMessageCaptionParams{
		HTTPClient: client,
	}
}

/*EditMessageCaptionParams contains all the parameters to send to the API endpoint
for the edit message caption operation typically these are written to a http.Request
*/
type EditMessageCaptionParams struct {

	/*Body*/
	Body *models.EditMessageCaptionBody
	/*Token
	  bot's token to authorize the request

	*/
	Token *string

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

// WithTimeout adds the timeout to the edit message caption params
func (o *EditMessageCaptionParams) WithTimeout(timeout time.Duration) *EditMessageCaptionParams {
	o.SetTimeout(timeout)
	return o
}

// SetTimeout adds the timeout to the edit message caption params
func (o *EditMessageCaptionParams) SetTimeout(timeout time.Duration) {
	o.timeout = timeout
}

// WithContext adds the context to the edit message caption params
func (o *EditMessageCaptionParams) WithContext(ctx context.Context) *EditMessageCaptionParams {
	o.SetContext(ctx)
	return o
}

// SetContext adds the context to the edit message caption params
func (o *EditMessageCaptionParams) SetContext(ctx context.Context) {
	o.Context = ctx
}

// WithHTTPClient adds the HTTPClient to the edit message caption params
func (o *EditMessageCaptionParams) WithHTTPClient(client *http.Client) *EditMessageCaptionParams {
	o.SetHTTPClient(client)
	return o
}

// SetHTTPClient adds the HTTPClient to the edit message caption params
func (o *EditMessageCaptionParams) SetHTTPClient(client *http.Client) {
	o.HTTPClient = client
}

// WithBody adds the body to the edit message caption params
func (o *EditMessageCaptionParams) WithBody(body *models.EditMessageCaptionBody) *EditMessageCaptionParams {
	o.SetBody(body)
	return o
}

// SetBody adds the body to the edit message caption params
func (o *EditMessageCaptionParams) SetBody(body *models.EditMessageCaptionBody) {
	o.Body = body
}

// WithToken adds the token to the edit message caption params
func (o *EditMessageCaptionParams) WithToken(token *string) *EditMessageCaptionParams {
	o.SetToken(token)
	return o
}

// SetToken adds the token to the edit message caption params
func (o *EditMessageCaptionParams) SetToken(token *string) {
	o.Token = token
}

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

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

	if o.Body != nil {
		if err := r.SetBodyParam(o.Body); err != nil {
			return err
		}
	}

	if o.Token != nil {

		// path param token
		if err := r.SetPathParam("token", *o.Token); err != nil {
			return err
		}

	}

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


text:
  <ion-content
    has-footer="true"
    scroll="true"
    >

    <ion-refresher
     on-refresh="onRefresh()"
     >
    </ion-refresher>

    <ion-nav-view></ion-nav-view>

  </ion-content>

  <ion-footer-bar>

Footer

  </ion-footer-bar>


text:
namespace mate {

namespace {

// Base template - used only for non-member function pointers. Other types
// either go to one of the below specializations, or go here and fail to compile
// because of base::Bind().
template<typename T, typename Enable = void>
struct CallbackTraits {
  static v8::Local<v8::FunctionTemplate> CreateTemplate(
      v8::Isolate* isolate, T callback) {
    return CreateFunctionTemplate(isolate, base::Bind(callback));
  }
};

// Specialization for base::Callback.
template<typename T>
struct CallbackTraits<base::Callback<T> > {
  static v8::Local<v8::FunctionTemplate> CreateTemplate(
      v8::Isolate* isolate, const base::Callback<T>& callback) {
    return CreateFunctionTemplate(isolate, callback);
  }
};

// Specialization for member function pointers. We need to handle this case
// specially because the first parameter for callbacks to MFP should typically
// come from the the JavaScript "this" object the function was called on, not
// from the first normal parameter.
template<typename T>
struct CallbackTraits<T, typename std::enable_if<
                           std::is_member_function_pointer<T>::value>::type> {
  static v8::Local<v8::FunctionTemplate> CreateTemplate(
      v8::Isolate* isolate, T callback) {
    int flags = HolderIsFirstArgument;
    return CreateFunctionTemplate(isolate, base::Bind(callback), flags);
  }
};

// This specialization allows people to construct function templates directly if
// they need to do fancier stuff.
template<>
struct CallbackTraits<v8::Local<v8::FunctionTemplate> > {
  static v8::Local<v8::FunctionTemplate> CreateTemplate(
      v8::Local<v8::FunctionTemplate> templ) {
    return templ;
  }
};

}  // namespace

// ObjectTemplateBuilder provides a handy interface to creating
// v8::ObjectTemplate instances with various sorts of properties.
class ObjectTemplateBuilder {
 public:
  explicit ObjectTemplateBuilder(
      v8::Isolate* isolate,
      v8::Local<v8::ObjectTemplate> templ);
  ~ObjectTemplateBuilder();

  // It's against Google C++ style to return a non-const ref, but we take some
  // poetic license here in order that all calls to Set() can be via the '.'
  // operator and line up nicely.
  template<typename T>
  ObjectTemplateBuilder& SetValue(const base::StringPiece& name, T val) {
    return SetImpl(name, ConvertToV8(isolate_, val));
  }

  // In the following methods, T and U can be function pointer, member function
  // pointer, base::Callback, or v8::FunctionTemplate. Most clients will want to
  // use one of the first two options. Also see mate::CreateFunctionTemplate()
  // for creating raw function templates.
  template<typename T>
  ObjectTemplateBuilder& SetMethod(const base::StringPiece& name,
                                   T callback) {
    return SetImpl(name,
                   CallbackTraits<T>::CreateTemplate(isolate_, callback));
  }
  template<typename T>
  ObjectTemplateBuilder& SetProperty(const base::StringPiece& name,
                                     T getter) {
    return SetPropertyImpl(
        name,
        CallbackTraits<T>::CreateTemplate(isolate_, getter),
        v8::Local<v8::FunctionTemplate>());
  }
  template<typename T, typename U>
  ObjectTemplateBuilder& SetProperty(const base::StringPiece& name,
                                     T getter,
                                     U setter) {
    return SetPropertyImpl(
        name,
        CallbackTraits<T>::CreateTemplate(isolate_, getter),
        CallbackTraits<U>::CreateTemplate(isolate_, setter));
  }

  // Add "destroy" and "isDestroyed" methods.
  ObjectTemplateBuilder& MakeDestroyable();

  v8::Local<v8::ObjectTemplate> Build();

 private:
  ObjectTemplateBuilder& SetImpl(const base::StringPiece& name,
                                 v8::Local<v8::Data> val);
  ObjectTemplateBuilder& SetPropertyImpl(
      const base::StringPiece& name, v8::Local<v8::FunctionTemplate> getter,
      v8::Local<v8::FunctionTemplate> setter);

  v8::Isolate* isolate_;

  // ObjectTemplateBuilder should only be used on the stack.
  v8::Local<v8::ObjectTemplate> template_;
};

}  // namespace mate

#endif  // NATIVE_MATE_OBJECT_TEMPLATE_BUILDER_H_


text:
get_filename_component( MY_CURENT_DIR "${CMAKE_CURRENT_LIST_FILE}" PATH)
file( READ "${MY_CURENT_DIR}/README" DOCUMENTATION )

# ITK version 4.5 changed it from EXCLUDE_FROM_ALL to EXCLUDE_FROM_DEFAULT
set( _EXCLUDE "EXCLUDE_FROM_ALL" )
if (NOT "${ITK_VERSION_MAJOR}.${ITK_VERSION_MINOR}.${ITK_VERSION_MINOR_PATCH}" VERSION_LESS "4.5")
  set( _EXCLUDE "EXCLUDE_FROM_DEFAULT" )
endif()

# define the dependencies of the include module and the tests
itk_module(ITKTextureAnalysis
  DEPENDS
    ITKCommon
    ITKStatistics
    ITKMathematicalMorphology
  TEST_DEPENDS
    ITKTestKernel
    ITKMetaIO
    ITKNIFTI
    ITKPNG
  DESCRIPTION
    "${DOCUMENTATION}"
  ${_EXCLUDE}
)


text:
package org.apache.cassandra.locator;

import java.util.*;
import java.util.Map.Entry;

import org.apache.cassandra.locator.ReplicaCollection.Builder.Conflict;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.apache.cassandra.dht.Datacenters;
import org.apache.cassandra.dht.Range;
import org.apache.cassandra.exceptions.ConfigurationException;
import org.apache.cassandra.dht.Token;
import org.apache.cassandra.locator.TokenMetadata.Topology;
import org.apache.cassandra.schema.SchemaConstants;
import org.apache.cassandra.service.ClientWarn;
import org.apache.cassandra.service.StorageService;
import org.apache.cassandra.utils.FBUtilities;
import org.apache.cassandra.utils.Pair;

import com.google.common.collect.ImmutableMultimap;
import com.google.common.collect.Multimap;

/**
 *

 * This Replication Strategy takes a property file that gives the intended
 * replication factor in each datacenter.  The sum total of the datacenter
 * replication factor values should be equal to the keyspace replication
 * factor.
 *

 *

 * So for example, if the keyspace replication factor is 6, the
 * datacenter replication factors could be 3, 2, and 1 - so 3 replicas in
 * one datacenter, 2 in another, and 1 in another - totaling 6.
 *

 * This class also caches the Endpoints and invalidates the cache if there is a
 * change in the number of tokens.
 */
public class NetworkTopologyStrategy extends AbstractReplicationStrategy
{
    public static final String REPLICATION_FACTOR = "replication_factor";

    private final Map<String, ReplicationFactor> datacenters;
    private final ReplicationFactor aggregateRf;
    private static final Logger logger = LoggerFactory.getLogger(NetworkTopologyStrategy.class);

    public NetworkTopologyStrategy(String keyspaceName, TokenMetadata tokenMetadata, IEndpointSnitch snitch, Map<String, String> configOptions) throws ConfigurationException
    {
        super(keyspaceName, tokenMetadata, snitch, configOptions);

        int replicas = 0;
        int trans = 0;
        Map<String, ReplicationFactor> newDatacenters = new HashMap<>();
        if (configOptions != null)
        {
            for (Entry<String, String> entry : configOptions.entrySet())
            {
                String dc = entry.getKey();
                // prepareOptions should have transformed any "replication_factor" options by now
                if (dc.equalsIgnoreCase(REPLICATION_FACTOR))
                    throw new ConfigurationException(REPLICATION_FACTOR + " should not appear as an option at construction time for NetworkTopologyStrategy");
                ReplicationFactor rf = ReplicationFactor.fromString(entry.getValue());
                replicas += rf.allReplicas;
                trans += rf.transientReplicas();
                newDatacenters.put(dc, rf);
            }
        }

        datacenters = Collections.unmodifiableMap(newDatacenters);
        aggregateRf = ReplicationFactor.withTransient(replicas, trans);
        logger.info("Configured datacenter replicas are {}", FBUtilities.toString(datacenters));
    }

    /**
     * Endpoint adder applying the replication rules for a given DC.
     */
    private static final class DatacenterEndpoints
    {
        /** List accepted endpoints get pushed into. */
        EndpointsForRange.Builder replicas;

        /**
         * Racks encountered so far. Replicas are put into separate racks while possible.
         * For efficiency the set is shared between the instances, using the location pair (dc, rack) to make sure
         * clashing names aren't a problem.
         */
        Set<Pair<String, String>> racks;

        /** Number of replicas left to fill from this DC. */
        int rfLeft;
        int acceptableRackRepeats;
        int transients;

        DatacenterEndpoints(ReplicationFactor rf,
                            int rackCount,
                            int nodeCount,
                            EndpointsForRange.Builder replicas,
                            Set<Pair<String, String>> racks)
        {
            this.replicas = replicas;
            this.racks = racks;
            // If there aren't enough nodes in this DC to fill the RF, the number of nodes is the effective RF.
            this.rfLeft = Math.min(rf.allReplicas, nodeCount);
            // If there aren't enough racks in this DC to fill the RF, we'll still use at least one node from each rack,
            // and the difference is to be filled by the first encountered nodes.
            acceptableRackRepeats = rf.allReplicas - rackCount;

            // if we have fewer replicas than rf calls for, reduce transients accordingly
            int reduceTransients = rf.allReplicas - this.rfLeft;
            transients = Math.max(rf.transientReplicas() - reduceTransients, 0);
            ReplicationFactor.validate(rfLeft, transients);
        }

        /**
         * Attempts to add an endpoint to the replicas for this datacenter, adding to the replicas set if successful.
         * Returns true if the endpoint was added, and this datacenter does not require further replicas.
         */
        boolean addEndpointAndCheckIfDone(InetAddressAndPort ep, Pair<String,String> location, Range<Token> replicatedRange)
        {
            if (done())
                return false;

            if (replicas.endpoints().contains(ep))
                // Cannot repeat a node.
                return false;

            Replica replica = new Replica(ep, replicatedRange, rfLeft > transients);

            if (racks.add(location))
            {
                // New rack.
                --rfLeft;
                replicas.add(replica, Conflict.NONE);
                return done();
            }
            if (acceptableRackRepeats <= 0)
                // There must be rfLeft distinct racks left, do not add any more rack repeats.
                return false;

            replicas.add(replica, Conflict.NONE);
            // Added a node that is from an already met rack to match RF when there aren't enough racks.
            --acceptableRackRepeats;
            --rfLeft;
            return done();
        }

        boolean done()
        {
            assert rfLeft >= 0;
            return rfLeft == 0;
        }
    }

    /**
     * calculate endpoints in one pass through the tokens by tracking our progress in each DC.
     */
    @Override
    public EndpointsForRange calculateNaturalReplicas(Token searchToken, TokenMetadata tokenMetadata)
    {
        // we want to preserve insertion order so that the first added endpoint becomes primary
        ArrayList<Token> sortedTokens = tokenMetadata.sortedTokens();
        Token replicaEnd = TokenMetadata.firstToken(sortedTokens, searchToken);
        Token replicaStart = tokenMetadata.getPredecessor(replicaEnd);
        Range<Token> replicatedRange = new Range<>(replicaStart, replicaEnd);

        EndpointsForRange.Builder builder = new EndpointsForRange.Builder(replicatedRange);
        Set<Pair<String, String>> seenRacks = new HashSet<>();

        Topology topology = tokenMetadata.getTopology();
        // all endpoints in each DC, so we can check when we have exhausted all the members of a DC
        Multimap<String, InetAddressAndPort> allEndpoints = topology.getDatacenterEndpoints();
        // all racks in a DC so we can check when we have exhausted all racks in a DC
        Map<String, ImmutableMultimap<String, InetAddressAndPort>> racks = topology.getDatacenterRacks();
        assert !allEndpoints.isEmpty() && !racks.isEmpty() : "not aware of any cluster members";

        int dcsToFill = 0;
        Map<String, DatacenterEndpoints> dcs = new HashMap<>(datacenters.size() * 2);

        // Create a DatacenterEndpoints object for each non-empty DC.
        for (Map.Entry<String, ReplicationFactor> en : datacenters.entrySet())
        {
            String dc = en.getKey();
            ReplicationFactor rf = en.getValue();
            int nodeCount = sizeOrZero(allEndpoints.get(dc));

            if (rf.allReplicas <= 0 || nodeCount <= 0)
                continue;

            DatacenterEndpoints dcEndpoints = new DatacenterEndpoints(rf, sizeOrZero(racks.get(dc)), nodeCount, builder, seenRacks);
            dcs.put(dc, dcEndpoints);
            ++dcsToFill;
        }

        Iterator<Token> tokenIter = TokenMetadata.ringIterator(sortedTokens, searchToken, false);
        while (dcsToFill > 0 && tokenIter.hasNext())
        {
            Token next = tokenIter.next();
            InetAddressAndPort ep = tokenMetadata.getEndpoint(next);
            Pair<String, String> location = topology.getLocation(ep);
            DatacenterEndpoints dcEndpoints = dcs.get(location.left);
            if (dcEndpoints != null && dcEndpoints.addEndpointAndCheckIfDone(ep, location, replicatedRange))
                --dcsToFill;
        }
        return builder.build();
    }

    private int sizeOrZero(Multimap<?, ?> collection)
    {
        return collection != null ? collection.asMap().size() : 0;
    }

    private int sizeOrZero(Collection<?> collection)
    {
        return collection != null ? collection.size() : 0;
    }

    @Override
    public ReplicationFactor getReplicationFactor()
    {
        return aggregateRf;
    }

    public ReplicationFactor getReplicationFactor(String dc)
    {
        ReplicationFactor replicas = datacenters.get(dc);
        return replicas == null ? ReplicationFactor.ZERO : replicas;
    }

    public Set<String> getDatacenters()
    {
        return datacenters.keySet();
    }

    @Override
    public Collection<String> recognizedOptions()
    {
        // only valid options are valid DC names.
        return Datacenters.getValidDatacenters();
    }

    /**
     * Support datacenter auto-expansion for CASSANDRA-14303. This hook allows us to safely auto-expand
     * the "replication_factor" options out into the known datacenters. It is called via reflection from
     * {@link AbstractReplicationStrategy#prepareReplicationStrategyOptions(Class, Map, Map)}.
     *
     * @param options The proposed strategy options that will be potentially mutated
     * @param previousOptions Any previous strategy options in the case of an ALTER statement
     */
    protected static void prepareOptions(Map<String, String> options, Map<String, String> previousOptions)
    {
        String replication = options.remove(REPLICATION_FACTOR);

        if (replication == null && options.size() == 0)
        {
            // Support direct alters from SimpleStrategy to NTS
            replication = previousOptions.get(REPLICATION_FACTOR);
        }
        else if (replication != null)
        {
            // When datacenter auto-expansion occurs in e.g. an ALTER statement (meaning that the previousOptions
            // map is not empty) we choose not to alter existing datacenter replication levels for safety.
            previousOptions.entrySet().stream()
                           .filter(e -> !e.getKey().equals(REPLICATION_FACTOR)) // SimpleStrategy conversions
                           .forEach(e -> options.putIfAbsent(e.getKey(), e.getValue()));
        }

        if (replication != null) {
            ReplicationFactor defaultReplicas = ReplicationFactor.fromString(replication);
            Datacenters.getValidDatacenters()
                       .forEach(dc -> options.putIfAbsent(dc, defaultReplicas.toParseableString()));
        }

        options.values().removeAll(Collections.singleton("0"));
    }

    @Override
    protected void validateExpectedOptions() throws ConfigurationException
    {
        // Do not accept query with no data centers specified.
        if (this.configOptions.isEmpty())
        {
            throw new ConfigurationException("Configuration for at least one datacenter must be present");
        }

        // Validate the data center names
        super.validateExpectedOptions();
    }

    @Override
    public void validateOptions() throws ConfigurationException
    {
        for (Entry<String, String> e : this.configOptions.entrySet())
        {
            // prepareOptions should have transformed any "replication_factor" by now
            if (e.getKey().equalsIgnoreCase(REPLICATION_FACTOR))
                throw new ConfigurationException(REPLICATION_FACTOR + " should not appear as an option to NetworkTopologyStrategy");
            validateReplicationFactor(e.getValue());
        }
    }

    @Override
    public void maybeWarnOnOptions()
    {
        if (!SchemaConstants.isSystemKeyspace(keyspaceName))
        {
            ImmutableMultimap<String, InetAddressAndPort> dcsNodes = StorageService.instance.getTokenMetadata()
                                                                                .getDC2AllEndpoints(snitch);
            for (Entry<String, String> e : this.configOptions.entrySet())
            {

                String dc = e.getKey();
                ReplicationFactor rf = getReplicationFactor(dc);
                int nodeCount = dcsNodes.get(dc).size();
                // nodeCount==0 on many tests
                if (rf.fullReplicas > nodeCount && nodeCount != 0)
                {
                    String msg = "Your replication factor " + rf.fullReplicas
                                 + " for keyspace "
                                 + keyspaceName
                                 + " is higher than the number of nodes "
                                 + nodeCount
                                 + " for datacenter "
                                 + dc;
                    ClientWarn.instance.warn(msg);
                    logger.warn(msg);
                }
            }
        }
    }

    @Override
    public boolean hasSameSettings(AbstractReplicationStrategy other)
    {
        return super.hasSameSettings(other) && ((NetworkTopologyStrategy) other).datacenters.equals(datacenters);
    }
}


text:
package org.apache.beam.sdk.schemas;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

import java.util.stream.Collectors;
import org.apache.beam.sdk.schemas.FieldAccessDescriptor.FieldDescriptor;
import org.apache.beam.sdk.schemas.Schema.FieldType;
import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.ImmutableList;
import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.ImmutableSet;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

/** Tests for {@link FieldAccessDescriptor}. */
public class FieldAccessDescriptorTest {
  private static final Schema SIMPLE_SCHEMA =
      Schema.builder()
          .addStringField("field0")
          .addStringField("field1")
          .addInt32Field("field2")
          .addInt32Field("field3")
          .build();

  private static final Schema NESTED_SCHEMA1 =
      Schema.builder().addStringField("field0").addRowField("field1", SIMPLE_SCHEMA).build();

  private static final Schema NESTED_SCHEMA2 =
      Schema.builder().addStringField("field0").addRowField("field1", NESTED_SCHEMA1).build();

  private static final Schema NESTED_ARRAY_SCHEMA =
      Schema.builder()
          .addStringField("field0")
          .addArrayField("field1", FieldType.row(SIMPLE_SCHEMA))
          .build();

  private static final Schema NESTED_MAP_SCHEMA =
      Schema.builder()
          .addStringField("field0")
          .addMapField("field1", FieldType.STRING, FieldType.row(SIMPLE_SCHEMA))
          .build();

  // test all fields
  @Test
  public void testAllFields() {
    FieldAccessDescriptor fieldAccessDescriptor = FieldAccessDescriptor.withAllFields();
    assertTrue(fieldAccessDescriptor.resolve(SIMPLE_SCHEMA).getAllFields());
  }

  // test field names
  @Test
  public void testFieldNames() {
    FieldAccessDescriptor fieldAccessDescriptor =
        FieldAccessDescriptor.withFieldNames("field0", "field2").resolve(SIMPLE_SCHEMA);
    assertEquals(ImmutableList.of(0, 2), fieldAccessDescriptor.fieldIdsAccessed());
  }

  @Test
  public void testFieldIds() {
    FieldAccessDescriptor fieldAccessDescriptor =
        FieldAccessDescriptor.withFieldIds(1, 3).resolve(SIMPLE_SCHEMA);
    assertEquals(ImmutableList.of(1, 3), fieldAccessDescriptor.fieldIdsAccessed());
  }

  @Test
  public void testNestedFieldByName() {
    FieldAccessDescriptor fieldAccessDescriptor =
        FieldAccessDescriptor.withFieldNames("field1")
            .withNestedField("field1", FieldAccessDescriptor.withAllFields());
    fieldAccessDescriptor = fieldAccessDescriptor.resolve(NESTED_SCHEMA2);
    assertTrue(fieldAccessDescriptor.fieldIdsAccessed().isEmpty());
    assertEquals(1, fieldAccessDescriptor.nestedFieldsById().size());
    FieldAccessDescriptor nestedAccess = fieldAccessDescriptor.nestedFieldsById().get(1);
    assertTrue(nestedAccess.getAllFields());
  }

  @Test
  public void testNestedFieldById() {
    FieldAccessDescriptor fieldAccessDescriptor =
        FieldAccessDescriptor.withFieldNames("field1")
            .withNestedField(1, FieldAccessDescriptor.withAllFields());
    fieldAccessDescriptor = fieldAccessDescriptor.resolve(NESTED_SCHEMA2);
    assertTrue(fieldAccessDescriptor.fieldIdsAccessed().isEmpty());
    assertEquals(1, fieldAccessDescriptor.nestedFieldsById().size());
    FieldAccessDescriptor nestedAccess = fieldAccessDescriptor.nestedFieldsById().get(1);
    assertTrue(nestedAccess.getAllFields());
  }

  @Test
  public void testPartialAccessNestedField() {
    FieldAccessDescriptor level1 = FieldAccessDescriptor.withFieldNames("field2");
    FieldAccessDescriptor level2 =
        FieldAccessDescriptor.withFieldNames("field1").withNestedField("field1", level1);
    FieldAccessDescriptor level3 =
        FieldAccessDescriptor.withFieldNames("field1").withNestedField("field1", level2);

    FieldAccessDescriptor resolved = level3.resolve(NESTED_SCHEMA2);
    assertTrue(resolved.fieldIdsAccessed().isEmpty());
    assertEquals(1, resolved.nestedFieldsById().size());
    resolved = resolved.nestedFieldsById().get(1);
    assertTrue(resolved.fieldIdsAccessed().isEmpty());
    assertEquals(1, resolved.nestedFieldsById().size());
    resolved = resolved.nestedFieldsById().get(1);
    assertEquals(ImmutableList.of(2), resolved.fieldIdsAccessed());
  }

  @Test
  public void testArrayNestedField() {
    FieldAccessDescriptor level1 = FieldAccessDescriptor.withFieldNames("field2");
    FieldAccessDescriptor level2 =
        FieldAccessDescriptor.withFieldNames("field1").withNestedField("field1", level1);

    FieldAccessDescriptor resolved = level2.resolve(NESTED_ARRAY_SCHEMA);
    assertTrue(resolved.fieldIdsAccessed().isEmpty());
    assertEquals(1, resolved.nestedFieldsById().size());
    resolved = resolved.nestedFieldsById().get(1);
    assertEquals(ImmutableList.of(2), resolved.fieldIdsAccessed());
  }

  @Test
  public void testMapNestedField() {
    FieldAccessDescriptor level1 = FieldAccessDescriptor.withFieldNames("field2");
    FieldAccessDescriptor level2 =
        FieldAccessDescriptor.withFieldNames("field1").withNestedField("field1", level1);

    FieldAccessDescriptor resolved = level2.resolve(NESTED_MAP_SCHEMA);
    assertTrue(resolved.fieldIdsAccessed().isEmpty());
    assertEquals(1, resolved.nestedFieldsById().size());
    resolved = resolved.nestedFieldsById().get(1);
    assertEquals(ImmutableList.of(2), resolved.fieldIdsAccessed());
  }

  @Test
  public void testParseAllFields() {
    FieldAccessDescriptor fieldAccessDescriptor = FieldAccessDescriptor.withFieldNames("*");
    assertTrue(fieldAccessDescriptor.resolve(SIMPLE_SCHEMA).getAllFields());
  }

  @Test
  public void testParseNestedField() {
    FieldAccessDescriptor fieldAccessDescriptor =
        FieldAccessDescriptor.withFieldNames("field0", "field1.*").resolve(NESTED_SCHEMA2);
    assertEquals(1, fieldAccessDescriptor.getFieldsAccessed().size());
    assertEquals(
        "field0", fieldAccessDescriptor.getFieldsAccessed().iterator().next().getFieldName());
    assertEquals(1, fieldAccessDescriptor.nestedFieldsById().size());
    FieldAccessDescriptor nestedAccess = fieldAccessDescriptor.nestedFieldsById().get(1);
    assertTrue(nestedAccess.getAllFields());
  }

  @Test
  public void testParseSiblingFields() {
    FieldAccessDescriptor fieldAccessDescriptor =
        FieldAccessDescriptor.withFieldNames("field1.field0", "field1.field1")
            .resolve(NESTED_SCHEMA1);
    assertEquals(0, fieldAccessDescriptor.getFieldsAccessed().size());
    assertEquals(1, fieldAccessDescriptor.nestedFieldsById().size());
    FieldAccessDescriptor nestedAccess = fieldAccessDescriptor.nestedFieldsById().get(1);
    assertEquals(
        ImmutableSet.of(0, 1),
        nestedAccess.getFieldsAccessed().stream()
            .map(FieldDescriptor::getFieldId)
            .collect(Collectors.toSet()));
  }

  @Test
  public void testParseShortCircuit() {
    FieldAccessDescriptor fieldAccessDescriptor =
        FieldAccessDescriptor.withFieldNames("field0", "field1.field0", "field1")
            .resolve(NESTED_SCHEMA2);
    assertEquals(2, fieldAccessDescriptor.getFieldsAccessed().size());
    assertEquals(
        ImmutableSet.of(0, 1),
        fieldAccessDescriptor.getFieldsAccessed().stream()
            .map(FieldDescriptor::getFieldId)
            .collect(Collectors.toSet()));
    assertTrue(fieldAccessDescriptor.nestedFieldsById().isEmpty());
  }

  @Test
  public void testParseWildcardShortCircuit() {
    FieldAccessDescriptor fieldAccessDescriptor =
        FieldAccessDescriptor.withFieldNames("field0", "field1.field0", "field1.*")
            .resolve(NESTED_SCHEMA2);
    assertEquals(1, fieldAccessDescriptor.getFieldsAccessed().size());
    assertEquals(
        "field0", fieldAccessDescriptor.getFieldsAccessed().iterator().next().getFieldName());
    assertEquals(1, fieldAccessDescriptor.nestedFieldsById().size());
    FieldAccessDescriptor nestedAccess = fieldAccessDescriptor.nestedFieldsById().get(1);
    assertTrue(nestedAccess.getAllFields());
  }

  @Test
  public void testParsePartialAccessNestedField() {
    FieldAccessDescriptor fieldAccessDescriptor =
        FieldAccessDescriptor.withFieldNames("field1.field1.field2").resolve(NESTED_SCHEMA2);

    assertTrue(fieldAccessDescriptor.fieldIdsAccessed().isEmpty());
    assertEquals(1, fieldAccessDescriptor.nestedFieldsById().size());
    fieldAccessDescriptor = fieldAccessDescriptor.nestedFieldsById().get(1);
    assertTrue(fieldAccessDescriptor.fieldIdsAccessed().isEmpty());
    assertEquals(1, fieldAccessDescriptor.nestedFieldsById().size());
    fieldAccessDescriptor = fieldAccessDescriptor.nestedFieldsById().get(1);
    assertEquals(ImmutableList.of(2), fieldAccessDescriptor.fieldIdsAccessed());
  }

  @Test
  public void testParseArrayNestedField() {
    FieldAccessDescriptor fieldAccessDescriptor =
        FieldAccessDescriptor.withFieldNames("field1[].field2").resolve(NESTED_ARRAY_SCHEMA);

    assertTrue(fieldAccessDescriptor.fieldIdsAccessed().isEmpty());
    assertEquals(1, fieldAccessDescriptor.nestedFieldsById().size());
    fieldAccessDescriptor = fieldAccessDescriptor.nestedFieldsById().get(1);
    assertEquals(ImmutableList.of(2), fieldAccessDescriptor.fieldIdsAccessed());
  }

  @Test
  public void testParseMapNestedField() {
    FieldAccessDescriptor fieldAccessDescriptor =
        FieldAccessDescriptor.withFieldNames("field1{}.field2").resolve(NESTED_MAP_SCHEMA);

    assertTrue(fieldAccessDescriptor.fieldIdsAccessed().isEmpty());
    assertEquals(1, fieldAccessDescriptor.nestedFieldsById().size());
    fieldAccessDescriptor = fieldAccessDescriptor.nestedFieldsById().get(1);
    assertEquals(ImmutableList.of(2), fieldAccessDescriptor.fieldIdsAccessed());
  }

  private static final Schema DOUBLE_NESTED_ARRAY_SCHEMA =
      Schema.builder()
          .addArrayField("field0", FieldType.array(FieldType.row(SIMPLE_SCHEMA)))
          .build();

  @Test
  public void testParseDoubleArrayNestedField() {
    FieldAccessDescriptor fieldAccessDescriptor =
        FieldAccessDescriptor.withFieldNames("field0[][].field2")
            .resolve(DOUBLE_NESTED_ARRAY_SCHEMA);

    assertTrue(fieldAccessDescriptor.fieldIdsAccessed().isEmpty());
    assertEquals(1, fieldAccessDescriptor.nestedFieldsById().size());
    fieldAccessDescriptor = fieldAccessDescriptor.nestedFieldsById().get(0);
    assertEquals(ImmutableList.of(2), fieldAccessDescriptor.fieldIdsAccessed());
  }

  @Rule public ExpectedException thrown = ExpectedException.none();

  @Test
  public void testInvalidQualifier() {
    thrown.expect(IllegalArgumentException.class);
    FieldAccessDescriptor fieldAccessDescriptor =
        FieldAccessDescriptor.withFieldNames("field0[]{}.field2")
            .resolve(DOUBLE_NESTED_ARRAY_SCHEMA);
  }

  private static final Schema NESTED_ARRAY_MAP_SCHEMA =
      Schema.builder()
          .addArrayField("field0", FieldType.map(FieldType.STRING, FieldType.row(SIMPLE_SCHEMA)))
          .build();

  @Test
  public void testParseArrayMapNestedField() {
    FieldAccessDescriptor fieldAccessDescriptor =
        FieldAccessDescriptor.withFieldNames("field0[]{}.field2").resolve(NESTED_ARRAY_MAP_SCHEMA);

    assertTrue(fieldAccessDescriptor.fieldIdsAccessed().isEmpty());
    assertEquals(1, fieldAccessDescriptor.nestedFieldsById().size());
    fieldAccessDescriptor = fieldAccessDescriptor.nestedFieldsById().get(0);
    assertEquals(ImmutableList.of(2), fieldAccessDescriptor.fieldIdsAccessed());
  }

  @Test
  public void testFieldAccessIdsDefaultOrdering() {
    FieldAccessDescriptor fieldAccessDescriptor =
        FieldAccessDescriptor.withFieldNames("field3", "field2", "field1", "field0")
            .resolve(SIMPLE_SCHEMA);

    assertEquals(ImmutableList.of(0, 1, 2, 3), fieldAccessDescriptor.fieldIdsAccessed());
  }

  @Test
  public void testFieldInsertionOrdering() {
    FieldAccessDescriptor fieldAccessDescriptor =
        FieldAccessDescriptor.withFieldNames("field3", "field2", "field1", "field0")
            .withOrderByFieldInsertionOrder()
            .resolve(SIMPLE_SCHEMA);

    assertEquals(ImmutableList.of(3, 2, 1, 0), fieldAccessDescriptor.fieldIdsAccessed());
  }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>io.cluster</groupId>
    <artifactId>ClusterLib</artifactId>
    <version>1.0</version>
    <packaging>jar</packaging>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.7</maven.compiler.source>
        <maven.compiler.target>1.7</maven.compiler.target>
    </properties>
    <build>
        <finalName>cluster-master-${project.version}</finalName>
        <plugins>
            <!-- Make this jar executable -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <configuration>
                    <archive>
                        <manifest>
                            <addClasspath>true</addClasspath>
                            <mainClass>demo.TestServer</mainClass>
                            <classpathPrefix>lib/</classpathPrefix>
                        </manifest>
                    </archive>
                </configuration>
            </plugin>
            <!-- Copy project dependency -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <version>2.5.1</version>
                <executions>
                    <execution>
                        <id>copy-dependencies</id>
                        <phase>package</phase>
                        <goals>
                            <goal>copy-dependencies</goal>
                        </goals>
                        <configuration>
                            <!-- exclude junit, we need runtime dependency only -->
                            <includeScope>runtime</includeScope>
                            <outputDirectory>${project.build.directory}/lib/</outputDirectory>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

    <dependencies>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>2.7</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.7</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.6.2</version>
        </dependency>
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>16.0.1</version>
            <type>jar</type>
        </dependency>
        <dependency>
            <groupId>io.netty</groupId>
            <artifactId>netty-all</artifactId>
            <version>4.0.23.Final</version>
            <type>jar</type>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-configuration2</artifactId>
            <version>2.0</version>
            <type>jar</type>
        </dependency>
    </dependencies>
</project>


text:
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;

namespace LogMagic
{
   /// <summary>
   /// Helps to measure time
   /// </summary>
   public class TimeMeasure : IDisposable
   {
      private readonly Stopwatch _stopwatch = new Stopwatch();

      /// <summary>
      /// Creates a new intance of time measure and starts measuring execution time
      /// </summary>
      public TimeMeasure()
      {
         _stopwatch.Start();
      }

      /// <summary>
      /// Gets number of ticks elapsed from the time this measure was created
      /// </summary>
      public long ElapsedTicks => _stopwatch.Elapsed.Ticks;

      /// <summary>
      /// Gets time elapsed from the time this measure was created
      /// </summary>
      public TimeSpan Elapsed => _stopwatch.Elapsed;

      /// <summary>
      /// Stops time measure
      /// </summary>
      public virtual void Dispose()
      {
         _stopwatch.Stop();
      }
   }
}


text:
import click
import numpy as np
import rasterio as rio
from scipy import sparse

import pyamg
from pyamg.relaxation.smoothing import change_smoothers

from geoblend import blend
from geoblend.coefficients import matrix_from_mask
from geoblend.utilities import get_mask
from geoblend.solver import create_multilevel_solver

@click.command('geoblend')
@click.argument('srcpath', type=click.Path(exists=True))
@click.argument('refpath', type=click.Path(exists=True))
@click.argument('dstpath', type=click.Path(exists=False))
@click.option("--matrix")
@click.option("--gradient-multiplier", default=1.0, type=click.FLOAT)
def geoblend(srcpath, refpath, dstpath, matrix, gradient_multiplier):
    """
    Poisson blend the source image against the reference image.
    """

    mask = get_mask(srcpath)
    indices = np.nonzero(mask)

    with rio.drivers():
        with rio.open(srcpath) as src, rio.open(refpath) as ref:

            profile = src.profile

            if matrix:
                levels = load_multilevel_solver(matrix)
                ml = pyamg.multilevel.multilevel_solver(levels, coarse_solver='pinv2')
                change_smoothers(ml, 'gauss_seidel', 'gauss_seidel')
            else:
                mat = matrix_from_mask(mask)

                v = np.ones((mat.shape[0], 1))
                ml = pyamg.smoothed_aggregation_solver(mat, v, max_coarse=10)

            shape = src.shape

            with rio.open(dstpath, 'w', **profile) as dst:

                for bidx in range(1, 4):

                    source = src.read(bidx)
                    reference = ref.read(bidx)

                    arr = blend(source, reference, mask, ml, gradient_multiplier)
                    dst.write_band(bidx, arr)

if __name__ == '__main__':
    geoblend()