text:
package managedidentities

import (
	"context"
	"fmt"
	"math"
	"net/url"
	"time"

	"cloud.google.com/go/longrunning"
	lroauto "cloud.google.com/go/longrunning/autogen"
	managedidentitiespb "cloud.google.com/go/managedidentities/apiv1/managedidentitiespb"
	gax "github.com/googleapis/gax-go/v2"
	"google.golang.org/api/iterator"
	"google.golang.org/api/option"
	"google.golang.org/api/option/internaloption"
	gtransport "google.golang.org/api/transport/grpc"
	longrunningpb "google.golang.org/genproto/googleapis/longrunning"
	"google.golang.org/grpc"
	"google.golang.org/grpc/metadata"
	"google.golang.org/protobuf/proto"
)

var newClientHook clientHook

// CallOptions contains the retry settings for each method of Client.
type CallOptions struct {
	CreateMicrosoftAdDomain []gax.CallOption
	ResetAdminPassword      []gax.CallOption
	ListDomains             []gax.CallOption
	GetDomain               []gax.CallOption
	UpdateDomain            []gax.CallOption
	DeleteDomain            []gax.CallOption
	AttachTrust             []gax.CallOption
	ReconfigureTrust        []gax.CallOption
	DetachTrust             []gax.CallOption
	ValidateTrust           []gax.CallOption
}

func defaultGRPCClientOptions() []option.ClientOption {
	return []option.ClientOption{
		internaloption.WithDefaultEndpoint("managedidentities.googleapis.com:443"),
		internaloption.WithDefaultMTLSEndpoint("managedidentities.mtls.googleapis.com:443"),
		internaloption.WithDefaultAudience("https://managedidentities.googleapis.com/"),
		internaloption.WithDefaultScopes(DefaultAuthScopes()...),
		internaloption.EnableJwtWithScope(),
		option.WithGRPCDialOption(grpc.WithDefaultCallOptions(
			grpc.MaxCallRecvMsgSize(math.MaxInt32))),
	}
}

func defaultCallOptions() *CallOptions {
	return &CallOptions{
		CreateMicrosoftAdDomain: []gax.CallOption{},
		ResetAdminPassword:      []gax.CallOption{},
		ListDomains:             []gax.CallOption{},
		GetDomain:               []gax.CallOption{},
		UpdateDomain:            []gax.CallOption{},
		DeleteDomain:            []gax.CallOption{},
		AttachTrust:             []gax.CallOption{},
		ReconfigureTrust:        []gax.CallOption{},
		DetachTrust:             []gax.CallOption{},
		ValidateTrust:           []gax.CallOption{},
	}
}

// internalClient is an interface that defines the methods available from Managed Service for Microsoft Active Directory API.
type internalClient interface {
	Close() error
	setGoogleClientInfo(...string)
	Connection() *grpc.ClientConn
	CreateMicrosoftAdDomain(context.Context, *managedidentitiespb.CreateMicrosoftAdDomainRequest, ...gax.CallOption) (*CreateMicrosoftAdDomainOperation, error)
	CreateMicrosoftAdDomainOperation(name string) *CreateMicrosoftAdDomainOperation
	ResetAdminPassword(context.Context, *managedidentitiespb.ResetAdminPasswordRequest, ...gax.CallOption) (*managedidentitiespb.ResetAdminPasswordResponse, error)
	ListDomains(context.Context, *managedidentitiespb.ListDomainsRequest, ...gax.CallOption) *DomainIterator
	GetDomain(context.Context, *managedidentitiespb.GetDomainRequest, ...gax.CallOption) (*managedidentitiespb.Domain, error)
	UpdateDomain(context.Context, *managedidentitiespb.UpdateDomainRequest, ...gax.CallOption) (*UpdateDomainOperation, error)
	UpdateDomainOperation(name string) *UpdateDomainOperation
	DeleteDomain(context.Context, *managedidentitiespb.DeleteDomainRequest, ...gax.CallOption) (*DeleteDomainOperation, error)
	DeleteDomainOperation(name string) *DeleteDomainOperation
	AttachTrust(context.Context, *managedidentitiespb.AttachTrustRequest, ...gax.CallOption) (*AttachTrustOperation, error)
	AttachTrustOperation(name string) *AttachTrustOperation
	ReconfigureTrust(context.Context, *managedidentitiespb.ReconfigureTrustRequest, ...gax.CallOption) (*ReconfigureTrustOperation, error)
	ReconfigureTrustOperation(name string) *ReconfigureTrustOperation
	DetachTrust(context.Context, *managedidentitiespb.DetachTrustRequest, ...gax.CallOption) (*DetachTrustOperation, error)
	DetachTrustOperation(name string) *DetachTrustOperation
	ValidateTrust(context.Context, *managedidentitiespb.ValidateTrustRequest, ...gax.CallOption) (*ValidateTrustOperation, error)
	ValidateTrustOperation(name string) *ValidateTrustOperation
}

// Client is a client for interacting with Managed Service for Microsoft Active Directory API.
// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls.
//
// # API Overview
//
// The managedidentites.googleapis.com service implements the Google Cloud
// Managed Identites API for identity services
// (e.g. Microsoft Active Directory).
//
// The Managed Identities service provides methods to manage
// (create/read/update/delete) domains, reset managed identities admin password,
// add/remove domain controllers in GCP regions and add/remove VPC peering.
//
// # Data Model
//
// The Managed Identities service exposes the following resources:
//
//	Locations as global, named as follows:
//	projects/{project_id}/locations/global.
//
//	Domains, named as follows:
//	/projects/{project_id}/locations/global/domain/{domain_name}.
//
// The {domain_name} refers to fully qualified domain name in the customer
// project e.g. mydomain.myorganization.com (at http://mydomain.myorganization.com), with the following restrictions:
//
//	Must contain only lowercase letters, numbers, periods and hyphens.
//
//	Must start with a letter.
//
//	Must contain between 2-64 characters.
//
//	Must end with a number or a letter.
//
//	Must not start with period.
//
//	First segement length (mydomain form example above) shouldn't exceed
//	15 chars.
//
//	The last segment cannot be fully numeric.
//
//	Must be unique within the customer project.
type Client struct {
	// The internal transport-dependent client.
	internalClient internalClient

	// The call options for this service.
	CallOptions *CallOptions

	// LROClient is used internally to handle long-running operations.
	// It is exposed so that its CallOptions can be modified if required.
	// Users should not Close this client.
	LROClient *lroauto.OperationsClient
}

// Wrapper methods routed to the internal client.

// Close closes the connection to the API service. The user should invoke this when
// the client is no longer required.
func (c *Client) Close() error {
	return c.internalClient.Close()
}

// setGoogleClientInfo sets the name and version of the application in
// the `x-goog-api-client` header passed on each request. Intended for
// use by Google-written clients.
func (c *Client) setGoogleClientInfo(keyval ...string) {
	c.internalClient.setGoogleClientInfo(keyval...)
}

// Connection returns a connection to the API service.
//
// Deprecated: Connections are now pooled so this method does not always
// return the same resource.
func (c *Client) Connection() *grpc.ClientConn {
	return c.internalClient.Connection()
}

// CreateMicrosoftAdDomain creates a Microsoft AD domain.
func (c *Client) CreateMicrosoftAdDomain(ctx context.Context, req *managedidentitiespb.CreateMicrosoftAdDomainRequest, opts ...gax.CallOption) (*CreateMicrosoftAdDomainOperation, error) {
	return c.internalClient.CreateMicrosoftAdDomain(ctx, req, opts...)
}

// CreateMicrosoftAdDomainOperation returns a new CreateMicrosoftAdDomainOperation from a given name.
// The name must be that of a previously created CreateMicrosoftAdDomainOperation, possibly from a different process.
func (c *Client) CreateMicrosoftAdDomainOperation(name string) *CreateMicrosoftAdDomainOperation {
	return c.internalClient.CreateMicrosoftAdDomainOperation(name)
}

// ResetAdminPassword resets a domain's administrator password.
func (c *Client) ResetAdminPassword(ctx context.Context, req *managedidentitiespb.ResetAdminPasswordRequest, opts ...gax.CallOption) (*managedidentitiespb.ResetAdminPasswordResponse, error) {
	return c.internalClient.ResetAdminPassword(ctx, req, opts...)
}

// ListDomains lists domains in a project.
func (c *Client) ListDomains(ctx context.Context, req *managedidentitiespb.ListDomainsRequest, opts ...gax.CallOption) *DomainIterator {
	return c.internalClient.ListDomains(ctx, req, opts...)
}

// GetDomain gets information about a domain.
func (c *Client) GetDomain(ctx context.Context, req *managedidentitiespb.GetDomainRequest, opts ...gax.CallOption) (*managedidentitiespb.Domain, error) {
	return c.internalClient.GetDomain(ctx, req, opts...)
}

// UpdateDomain updates the metadata and configuration of a domain.
func (c *Client) UpdateDomain(ctx context.Context, req *managedidentitiespb.UpdateDomainRequest, opts ...gax.CallOption) (*UpdateDomainOperation, error) {
	return c.internalClient.UpdateDomain(ctx, req, opts...)
}

// UpdateDomainOperation returns a new UpdateDomainOperation from a given name.
// The name must be that of a previously created UpdateDomainOperation, possibly from a different process.
func (c *Client) UpdateDomainOperation(name string) *UpdateDomainOperation {
	return c.internalClient.UpdateDomainOperation(name)
}

// DeleteDomain deletes a domain.
func (c *Client) DeleteDomain(ctx context.Context, req *managedidentitiespb.DeleteDomainRequest, opts ...gax.CallOption) (*DeleteDomainOperation, error) {
	return c.internalClient.DeleteDomain(ctx, req, opts...)
}

// DeleteDomainOperation returns a new DeleteDomainOperation from a given name.
// The name must be that of a previously created DeleteDomainOperation, possibly from a different process.
func (c *Client) DeleteDomainOperation(name string) *DeleteDomainOperation {
	return c.internalClient.DeleteDomainOperation(name)
}

// AttachTrust adds an AD trust to a domain.
func (c *Client) AttachTrust(ctx context.Context, req *managedidentitiespb.AttachTrustRequest, opts ...gax.CallOption) (*AttachTrustOperation, error) {
	return c.internalClient.AttachTrust(ctx, req, opts...)
}

// AttachTrustOperation returns a new AttachTrustOperation from a given name.
// The name must be that of a previously created AttachTrustOperation, possibly from a different process.
func (c *Client) AttachTrustOperation(name string) *AttachTrustOperation {
	return c.internalClient.AttachTrustOperation(name)
}

// ReconfigureTrust updates the DNS conditional forwarder.
func (c *Client) ReconfigureTrust(ctx context.Context, req *managedidentitiespb.ReconfigureTrustRequest, opts ...gax.CallOption) (*ReconfigureTrustOperation, error) {
	return c.internalClient.ReconfigureTrust(ctx, req, opts...)
}

// ReconfigureTrustOperation returns a new ReconfigureTrustOperation from a given name.
// The name must be that of a previously created ReconfigureTrustOperation, possibly from a different process.
func (c *Client) ReconfigureTrustOperation(name string) *ReconfigureTrustOperation {
	return c.internalClient.ReconfigureTrustOperation(name)
}

// DetachTrust removes an AD trust.
func (c *Client) DetachTrust(ctx context.Context, req *managedidentitiespb.DetachTrustRequest, opts ...gax.CallOption) (*DetachTrustOperation, error) {
	return c.internalClient.DetachTrust(ctx, req, opts...)
}

// DetachTrustOperation returns a new DetachTrustOperation from a given name.
// The name must be that of a previously created DetachTrustOperation, possibly from a different process.
func (c *Client) DetachTrustOperation(name string) *DetachTrustOperation {
	return c.internalClient.DetachTrustOperation(name)
}

// ValidateTrust validates a trust state, that the target domain is reachable, and that the
// target domain is able to accept incoming trust requests.
func (c *Client) ValidateTrust(ctx context.Context, req *managedidentitiespb.ValidateTrustRequest, opts ...gax.CallOption) (*ValidateTrustOperation, error) {
	return c.internalClient.ValidateTrust(ctx, req, opts...)
}

// ValidateTrustOperation returns a new ValidateTrustOperation from a given name.
// The name must be that of a previously created ValidateTrustOperation, possibly from a different process.
func (c *Client) ValidateTrustOperation(name string) *ValidateTrustOperation {
	return c.internalClient.ValidateTrustOperation(name)
}

// gRPCClient is a client for interacting with Managed Service for Microsoft Active Directory API over gRPC transport.
//
// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls.
type gRPCClient struct {
	// Connection pool of gRPC connections to the service.
	connPool gtransport.ConnPool

	// flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE
	disableDeadlines bool

	// Points back to the CallOptions field of the containing Client
	CallOptions **CallOptions

	// The gRPC API client.
	client managedidentitiespb.ManagedIdentitiesServiceClient

	// LROClient is used internally to handle long-running operations.
	// It is exposed so that its CallOptions can be modified if required.
	// Users should not Close this client.
	LROClient **lroauto.OperationsClient

	// The x-goog-* metadata to be sent with each request.
	xGoogMetadata metadata.MD
}

// NewClient creates a new managed identities service client based on gRPC.
// The returned client must be Closed when it is done being used to clean up its underlying connections.
//
// # API Overview
//
// The managedidentites.googleapis.com service implements the Google Cloud
// Managed Identites API for identity services
// (e.g. Microsoft Active Directory).
//
// The Managed Identities service provides methods to manage
// (create/read/update/delete) domains, reset managed identities admin password,
// add/remove domain controllers in GCP regions and add/remove VPC peering.
//
// # Data Model
//
// The Managed Identities service exposes the following resources:
//
//	Locations as global, named as follows:
//	projects/{project_id}/locations/global.
//
//	Domains, named as follows:
//	/projects/{project_id}/locations/global/domain/{domain_name}.
//
// The {domain_name} refers to fully qualified domain name in the customer
// project e.g. mydomain.myorganization.com (at http://mydomain.myorganization.com), with the following restrictions:
//
//	Must contain only lowercase letters, numbers, periods and hyphens.
//
//	Must start with a letter.
//
//	Must contain between 2-64 characters.
//
//	Must end with a number or a letter.
//
//	Must not start with period.
//
//	First segement length (mydomain form example above) shouldn't exceed
//	15 chars.
//
//	The last segment cannot be fully numeric.
//
//	Must be unique within the customer project.
func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) {
	clientOpts := defaultGRPCClientOptions()
	if newClientHook != nil {
		hookOpts, err := newClientHook(ctx, clientHookParams{})
		if err != nil {
			return nil, err
		}
		clientOpts = append(clientOpts, hookOpts...)
	}

	disableDeadlines, err := checkDisableDeadlines()
	if err != nil {
		return nil, err
	}

	connPool, err := gtransport.DialPool(ctx, append(clientOpts, opts...)...)
	if err != nil {
		return nil, err
	}
	client := Client{CallOptions: defaultCallOptions()}

	c := &gRPCClient{
		connPool:         connPool,
		disableDeadlines: disableDeadlines,
		client:           managedidentitiespb.NewManagedIdentitiesServiceClient(connPool),
		CallOptions:      &client.CallOptions,
	}
	c.setGoogleClientInfo()

	client.internalClient = c

	client.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool))
	if err != nil {
		// This error "should not happen", since we are just reusing old connection pool
		// and never actually need to dial.
		// If this does happen, we could leak connp. However, we cannot close conn:
		// If the user invoked the constructor with option.WithGRPCConn,
		// we would close a connection that's still in use.
		// TODO: investigate error conditions.
		return nil, err
	}
	c.LROClient = &client.LROClient
	return &client, nil
}

// Connection returns a connection to the API service.
//
// Deprecated: Connections are now pooled so this method does not always
// return the same resource.
func (c *gRPCClient) Connection() *grpc.ClientConn {
	return c.connPool.Conn()
}

// setGoogleClientInfo sets the name and version of the application in
// the `x-goog-api-client` header passed on each request. Intended for
// use by Google-written clients.
func (c *gRPCClient) setGoogleClientInfo(keyval ...string) {
	kv := append([]string{"gl-go", versionGo()}, keyval...)
	kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "grpc", grpc.Version)
	c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...))
}

// Close closes the connection to the API service. The user should invoke this when
// the client is no longer required.
func (c *gRPCClient) Close() error {
	return c.connPool.Close()
}

func (c *gRPCClient) CreateMicrosoftAdDomain(ctx context.Context, req *managedidentitiespb.CreateMicrosoftAdDomainRequest, opts ...gax.CallOption) (*CreateMicrosoftAdDomainOperation, error) {
	if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines {
		cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond)
		defer cancel()
		ctx = cctx
	}
	md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent())))

	ctx = insertMetadata(ctx, c.xGoogMetadata, md)
	opts = append((*c.CallOptions).CreateMicrosoftAdDomain[0:len((*c.CallOptions).CreateMicrosoftAdDomain):len((*c.CallOptions).CreateMicrosoftAdDomain)], opts...)
	var resp *longrunningpb.Operation
	err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
		var err error
		resp, err = c.client.CreateMicrosoftAdDomain(ctx, req, settings.GRPC...)
		return err
	}, opts...)
	if err != nil {
		return nil, err
	}
	return &CreateMicrosoftAdDomainOperation{
		lro: longrunning.InternalNewOperation(*c.LROClient, resp),
	}, nil
}

func (c *gRPCClient) ResetAdminPassword(ctx context.Context, req *managedidentitiespb.ResetAdminPasswordRequest, opts ...gax.CallOption) (*managedidentitiespb.ResetAdminPasswordResponse, error) {
	if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines {
		cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond)
		defer cancel()
		ctx = cctx
	}
	md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName())))

	ctx = insertMetadata(ctx, c.xGoogMetadata, md)
	opts = append((*c.CallOptions).ResetAdminPassword[0:len((*c.CallOptions).ResetAdminPassword):len((*c.CallOptions).ResetAdminPassword)], opts...)
	var resp *managedidentitiespb.ResetAdminPasswordResponse
	err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
		var err error
		resp, err = c.client.ResetAdminPassword(ctx, req, settings.GRPC...)
		return err
	}, opts...)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (c *gRPCClient) ListDomains(ctx context.Context, req *managedidentitiespb.ListDomainsRequest, opts ...gax.CallOption) *DomainIterator {
	md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent())))

	ctx = insertMetadata(ctx, c.xGoogMetadata, md)
	opts = append((*c.CallOptions).ListDomains[0:len((*c.CallOptions).ListDomains):len((*c.CallOptions).ListDomains)], opts...)
	it := &DomainIterator{}
	req = proto.Clone(req).(*managedidentitiespb.ListDomainsRequest)
	it.InternalFetch = func(pageSize int, pageToken string) ([]*managedidentitiespb.Domain, string, error) {
		resp := &managedidentitiespb.ListDomainsResponse{}
		if pageToken != "" {
			req.PageToken = pageToken
		}
		if pageSize > math.MaxInt32 {
			req.PageSize = math.MaxInt32
		} else if pageSize != 0 {
			req.PageSize = int32(pageSize)
		}
		err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
			var err error
			resp, err = c.client.ListDomains(ctx, req, settings.GRPC...)
			return err
		}, opts...)
		if err != nil {
			return nil, "", err
		}

		it.Response = resp
		return resp.GetDomains(), resp.GetNextPageToken(), nil
	}
	fetch := func(pageSize int, pageToken string) (string, error) {
		items, nextPageToken, err := it.InternalFetch(pageSize, pageToken)
		if err != nil {
			return "", err
		}
		it.items = append(it.items, items...)
		return nextPageToken, nil
	}

	it.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf)
	it.pageInfo.MaxSize = int(req.GetPageSize())
	it.pageInfo.Token = req.GetPageToken()

	return it
}

func (c *gRPCClient) GetDomain(ctx context.Context, req *managedidentitiespb.GetDomainRequest, opts ...gax.CallOption) (*managedidentitiespb.Domain, error) {
	if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines {
		cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond)
		defer cancel()
		ctx = cctx
	}
	md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName())))

	ctx = insertMetadata(ctx, c.xGoogMetadata, md)
	opts = append((*c.CallOptions).GetDomain[0:len((*c.CallOptions).GetDomain):len((*c.CallOptions).GetDomain)], opts...)
	var resp *managedidentitiespb.Domain
	err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
		var err error
		resp, err = c.client.GetDomain(ctx, req, settings.GRPC...)
		return err
	}, opts...)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (c *gRPCClient) UpdateDomain(ctx context.Context, req *managedidentitiespb.UpdateDomainRequest, opts ...gax.CallOption) (*UpdateDomainOperation, error) {
	if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines {
		cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond)
		defer cancel()
		ctx = cctx
	}
	md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "domain.name", url.QueryEscape(req.GetDomain().GetName())))

	ctx = insertMetadata(ctx, c.xGoogMetadata, md)
	opts = append((*c.CallOptions).UpdateDomain[0:len((*c.CallOptions).UpdateDomain):len((*c.CallOptions).UpdateDomain)], opts...)
	var resp *longrunningpb.Operation
	err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
		var err error
		resp, err = c.client.UpdateDomain(ctx, req, settings.GRPC...)
		return err
	}, opts...)
	if err != nil {
		return nil, err
	}
	return &UpdateDomainOperation{
		lro: longrunning.InternalNewOperation(*c.LROClient, resp),
	}, nil
}

func (c *gRPCClient) DeleteDomain(ctx context.Context, req *managedidentitiespb.DeleteDomainRequest, opts ...gax.CallOption) (*DeleteDomainOperation, error) {
	if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines {
		cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond)
		defer cancel()
		ctx = cctx
	}
	md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName())))

	ctx = insertMetadata(ctx, c.xGoogMetadata, md)
	opts = append((*c.CallOptions).DeleteDomain[0:len((*c.CallOptions).DeleteDomain):len((*c.CallOptions).DeleteDomain)], opts...)
	var resp *longrunningpb.Operation
	err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
		var err error
		resp, err = c.client.DeleteDomain(ctx, req, settings.GRPC...)
		return err
	}, opts...)
	if err != nil {
		return nil, err
	}
	return &DeleteDomainOperation{
		lro: longrunning.InternalNewOperation(*c.LROClient, resp),
	}, nil
}

func (c *gRPCClient) AttachTrust(ctx context.Context, req *managedidentitiespb.AttachTrustRequest, opts ...gax.CallOption) (*AttachTrustOperation, error) {
	if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines {
		cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond)
		defer cancel()
		ctx = cctx
	}
	md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName())))

	ctx = insertMetadata(ctx, c.xGoogMetadata, md)
	opts = append((*c.CallOptions).AttachTrust[0:len((*c.CallOptions).AttachTrust):len((*c.CallOptions).AttachTrust)], opts...)
	var resp *longrunningpb.Operation
	err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
		var err error
		resp, err = c.client.AttachTrust(ctx, req, settings.GRPC...)
		return err
	}, opts...)
	if err != nil {
		return nil, err
	}
	return &AttachTrustOperation{
		lro: longrunning.InternalNewOperation(*c.LROClient, resp),
	}, nil
}

func (c *gRPCClient) ReconfigureTrust(ctx context.Context, req *managedidentitiespb.ReconfigureTrustRequest, opts ...gax.CallOption) (*ReconfigureTrustOperation, error) {
	if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines {
		cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond)
		defer cancel()
		ctx = cctx
	}
	md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName())))

	ctx = insertMetadata(ctx, c.xGoogMetadata, md)
	opts = append((*c.CallOptions).ReconfigureTrust[0:len((*c.CallOptions).ReconfigureTrust):len((*c.CallOptions).ReconfigureTrust)], opts...)
	var resp *longrunningpb.Operation
	err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
		var err error
		resp, err = c.client.ReconfigureTrust(ctx, req, settings.GRPC...)
		return err
	}, opts...)
	if err != nil {
		return nil, err
	}
	return &ReconfigureTrustOperation{
		lro: longrunning.InternalNewOperation(*c.LROClient, resp),
	}, nil
}

func (c *gRPCClient) DetachTrust(ctx context.Context, req *managedidentitiespb.DetachTrustRequest, opts ...gax.CallOption) (*DetachTrustOperation, error) {
	if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines {
		cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond)
		defer cancel()
		ctx = cctx
	}
	md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName())))

	ctx = insertMetadata(ctx, c.xGoogMetadata, md)
	opts = append((*c.CallOptions).DetachTrust[0:len((*c.CallOptions).DetachTrust):len((*c.CallOptions).DetachTrust)], opts...)
	var resp *longrunningpb.Operation
	err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
		var err error
		resp, err = c.client.DetachTrust(ctx, req, settings.GRPC...)
		return err
	}, opts...)
	if err != nil {
		return nil, err
	}
	return &DetachTrustOperation{
		lro: longrunning.InternalNewOperation(*c.LROClient, resp),
	}, nil
}

func (c *gRPCClient) ValidateTrust(ctx context.Context, req *managedidentitiespb.ValidateTrustRequest, opts ...gax.CallOption) (*ValidateTrustOperation, error) {
	if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines {
		cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond)
		defer cancel()
		ctx = cctx
	}
	md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName())))

	ctx = insertMetadata(ctx, c.xGoogMetadata, md)
	opts = append((*c.CallOptions).ValidateTrust[0:len((*c.CallOptions).ValidateTrust):len((*c.CallOptions).ValidateTrust)], opts...)
	var resp *longrunningpb.Operation
	err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
		var err error
		resp, err = c.client.ValidateTrust(ctx, req, settings.GRPC...)
		return err
	}, opts...)
	if err != nil {
		return nil, err
	}
	return &ValidateTrustOperation{
		lro: longrunning.InternalNewOperation(*c.LROClient, resp),
	}, nil
}

// AttachTrustOperation manages a long-running operation from AttachTrust.
type AttachTrustOperation struct {
	lro *longrunning.Operation
}

// AttachTrustOperation returns a new AttachTrustOperation from a given name.
// The name must be that of a previously created AttachTrustOperation, possibly from a different process.
func (c *gRPCClient) AttachTrustOperation(name string) *AttachTrustOperation {
	return &AttachTrustOperation{
		lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}),
	}
}

// Wait blocks until the long-running operation is completed, returning the response and any errors encountered.
//
// See documentation of Poll for error-handling information.
func (op *AttachTrustOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*managedidentitiespb.Domain, error) {
	var resp managedidentitiespb.Domain
	if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil {
		return nil, err
	}
	return &resp, nil
}

// Poll fetches the latest state of the long-running operation.
//
// Poll also fetches the latest metadata, which can be retrieved by Metadata.
//
// If Poll fails, the error is returned and op is unmodified. If Poll succeeds and
// the operation has completed with failure, the error is returned and op.Done will return true.
// If Poll succeeds and the operation has completed successfully,
// op.Done will return true, and the response of the operation is returned.
// If Poll succeeds and the operation has not completed, the returned response and error are both nil.
func (op *AttachTrustOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*managedidentitiespb.Domain, error) {
	var resp managedidentitiespb.Domain
	if err := op.lro.Poll(ctx, &resp, opts...); err != nil {
		return nil, err
	}
	if !op.Done() {
		return nil, nil
	}
	return &resp, nil
}

// Metadata returns metadata associated with the long-running operation.
// Metadata itself does not contact the server, but Poll does.
// To get the latest metadata, call this method after a successful call to Poll.
// If the metadata is not available, the returned metadata and error are both nil.
func (op *AttachTrustOperation) Metadata() (*managedidentitiespb.OpMetadata, error) {
	var meta managedidentitiespb.OpMetadata
	if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata {
		return nil, nil
	} else if err != nil {
		return nil, err
	}
	return &meta, nil
}

// Done reports whether the long-running operation has completed.
func (op *AttachTrustOperation) Done() bool {
	return op.lro.Done()
}

// Name returns the name of the long-running operation.
// The name is assigned by the server and is unique within the service from which the operation is created.
func (op *AttachTrustOperation) Name() string {
	return op.lro.Name()
}

// CreateMicrosoftAdDomainOperation manages a long-running operation from CreateMicrosoftAdDomain.
type CreateMicrosoftAdDomainOperation struct {
	lro *longrunning.Operation
}

// CreateMicrosoftAdDomainOperation returns a new CreateMicrosoftAdDomainOperation from a given name.
// The name must be that of a previously created CreateMicrosoftAdDomainOperation, possibly from a different process.
func (c *gRPCClient) CreateMicrosoftAdDomainOperation(name string) *CreateMicrosoftAdDomainOperation {
	return &CreateMicrosoftAdDomainOperation{
		lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}),
	}
}

// Wait blocks until the long-running operation is completed, returning the response and any errors encountered.
//
// See documentation of Poll for error-handling information.
func (op *CreateMicrosoftAdDomainOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*managedidentitiespb.Domain, error) {
	var resp managedidentitiespb.Domain
	if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil {
		return nil, err
	}
	return &resp, nil
}

// Poll fetches the latest state of the long-running operation.
//
// Poll also fetches the latest metadata, which can be retrieved by Metadata.
//
// If Poll fails, the error is returned and op is unmodified. If Poll succeeds and
// the operation has completed with failure, the error is returned and op.Done will return true.
// If Poll succeeds and the operation has completed successfully,
// op.Done will return true, and the response of the operation is returned.
// If Poll succeeds and the operation has not completed, the returned response and error are both nil.
func (op *CreateMicrosoftAdDomainOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*managedidentitiespb.Domain, error) {
	var resp managedidentitiespb.Domain
	if err := op.lro.Poll(ctx, &resp, opts...); err != nil {
		return nil, err
	}
	if !op.Done() {
		return nil, nil
	}
	return &resp, nil
}

// Metadata returns metadata associated with the long-running operation.
// Metadata itself does not contact the server, but Poll does.
// To get the latest metadata, call this method after a successful call to Poll.
// If the metadata is not available, the returned metadata and error are both nil.
func (op *CreateMicrosoftAdDomainOperation) Metadata() (*managedidentitiespb.OpMetadata, error) {
	var meta managedidentitiespb.OpMetadata
	if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata {
		return nil, nil
	} else if err != nil {
		return nil, err
	}
	return &meta, nil
}

// Done reports whether the long-running operation has completed.
func (op *CreateMicrosoftAdDomainOperation) Done() bool {
	return op.lro.Done()
}

// Name returns the name of the long-running operation.
// The name is assigned by the server and is unique within the service from which the operation is created.
func (op *CreateMicrosoftAdDomainOperation) Name() string {
	return op.lro.Name()
}

// DeleteDomainOperation manages a long-running operation from DeleteDomain.
type DeleteDomainOperation struct {
	lro *longrunning.Operation
}

// DeleteDomainOperation returns a new DeleteDomainOperation from a given name.
// The name must be that of a previously created DeleteDomainOperation, possibly from a different process.
func (c *gRPCClient) DeleteDomainOperation(name string) *DeleteDomainOperation {
	return &DeleteDomainOperation{
		lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}),
	}
}

// Wait blocks until the long-running operation is completed, returning the response and any errors encountered.
//
// See documentation of Poll for error-handling information.
func (op *DeleteDomainOperation) Wait(ctx context.Context, opts ...gax.CallOption) error {
	return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...)
}

// Poll fetches the latest state of the long-running operation.
//
// Poll also fetches the latest metadata, which can be retrieved by Metadata.
//
// If Poll fails, the error is returned and op is unmodified. If Poll succeeds and
// the operation has completed with failure, the error is returned and op.Done will return true.
// If Poll succeeds and the operation has completed successfully,
// op.Done will return true, and the response of the operation is returned.
// If Poll succeeds and the operation has not completed, the returned response and error are both nil.
func (op *DeleteDomainOperation) Poll(ctx context.Context, opts ...gax.CallOption) error {
	return op.lro.Poll(ctx, nil, opts...)
}

// Metadata returns metadata associated with the long-running operation.
// Metadata itself does not contact the server, but Poll does.
// To get the latest metadata, call this method after a successful call to Poll.
// If the metadata is not available, the returned metadata and error are both nil.
func (op *DeleteDomainOperation) Metadata() (*managedidentitiespb.OpMetadata, error) {
	var meta managedidentitiespb.OpMetadata
	if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata {
		return nil, nil
	} else if err != nil {
		return nil, err
	}
	return &meta, nil
}

// Done reports whether the long-running operation has completed.
func (op *DeleteDomainOperation) Done() bool {
	return op.lro.Done()
}

// Name returns the name of the long-running operation.
// The name is assigned by the server and is unique within the service from which the operation is created.
func (op *DeleteDomainOperation) Name() string {
	return op.lro.Name()
}

// DetachTrustOperation manages a long-running operation from DetachTrust.
type DetachTrustOperation struct {
	lro *longrunning.Operation
}

// DetachTrustOperation returns a new DetachTrustOperation from a given name.
// The name must be that of a previously created DetachTrustOperation, possibly from a different process.
func (c *gRPCClient) DetachTrustOperation(name string) *DetachTrustOperation {
	return &DetachTrustOperation{
		lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}),
	}
}

// Wait blocks until the long-running operation is completed, returning the response and any errors encountered.
//
// See documentation of Poll for error-handling information.
func (op *DetachTrustOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*managedidentitiespb.Domain, error) {
	var resp managedidentitiespb.Domain
	if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil {
		return nil, err
	}
	return &resp, nil
}

// Poll fetches the latest state of the long-running operation.
//
// Poll also fetches the latest metadata, which can be retrieved by Metadata.
//
// If Poll fails, the error is returned and op is unmodified. If Poll succeeds and
// the operation has completed with failure, the error is returned and op.Done will return true.
// If Poll succeeds and the operation has completed successfully,
// op.Done will return true, and the response of the operation is returned.
// If Poll succeeds and the operation has not completed, the returned response and error are both nil.
func (op *DetachTrustOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*managedidentitiespb.Domain, error) {
	var resp managedidentitiespb.Domain
	if err := op.lro.Poll(ctx, &resp, opts...); err != nil {
		return nil, err
	}
	if !op.Done() {
		return nil, nil
	}
	return &resp, nil
}

// Metadata returns metadata associated with the long-running operation.
// Metadata itself does not contact the server, but Poll does.
// To get the latest metadata, call this method after a successful call to Poll.
// If the metadata is not available, the returned metadata and error are both nil.
func (op *DetachTrustOperation) Metadata() (*managedidentitiespb.OpMetadata, error) {
	var meta managedidentitiespb.OpMetadata
	if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata {
		return nil, nil
	} else if err != nil {
		return nil, err
	}
	return &meta, nil
}

// Done reports whether the long-running operation has completed.
func (op *DetachTrustOperation) Done() bool {
	return op.lro.Done()
}

// Name returns the name of the long-running operation.
// The name is assigned by the server and is unique within the service from which the operation is created.
func (op *DetachTrustOperation) Name() string {
	return op.lro.Name()
}

// ReconfigureTrustOperation manages a long-running operation from ReconfigureTrust.
type ReconfigureTrustOperation struct {
	lro *longrunning.Operation
}

// ReconfigureTrustOperation returns a new ReconfigureTrustOperation from a given name.
// The name must be that of a previously created ReconfigureTrustOperation, possibly from a different process.
func (c *gRPCClient) ReconfigureTrustOperation(name string) *ReconfigureTrustOperation {
	return &ReconfigureTrustOperation{
		lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}),
	}
}

// Wait blocks until the long-running operation is completed, returning the response and any errors encountered.
//
// See documentation of Poll for error-handling information.
func (op *ReconfigureTrustOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*managedidentitiespb.Domain, error) {
	var resp managedidentitiespb.Domain
	if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil {
		return nil, err
	}
	return &resp, nil
}

// Poll fetches the latest state of the long-running operation.
//
// Poll also fetches the latest metadata, which can be retrieved by Metadata.
//
// If Poll fails, the error is returned and op is unmodified. If Poll succeeds and
// the operation has completed with failure, the error is returned and op.Done will return true.
// If Poll succeeds and the operation has completed successfully,
// op.Done will return true, and the response of the operation is returned.
// If Poll succeeds and the operation has not completed, the returned response and error are both nil.
func (op *ReconfigureTrustOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*managedidentitiespb.Domain, error) {
	var resp managedidentitiespb.Domain
	if err := op.lro.Poll(ctx, &resp, opts...); err != nil {
		return nil, err
	}
	if !op.Done() {
		return nil, nil
	}
	return &resp, nil
}

// Metadata returns metadata associated with the long-running operation.
// Metadata itself does not contact the server, but Poll does.
// To get the latest metadata, call this method after a successful call to Poll.
// If the metadata is not available, the returned metadata and error are both nil.
func (op *ReconfigureTrustOperation) Metadata() (*managedidentitiespb.OpMetadata, error) {
	var meta managedidentitiespb.OpMetadata
	if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata {
		return nil, nil
	} else if err != nil {
		return nil, err
	}
	return &meta, nil
}

// Done reports whether the long-running operation has completed.
func (op *ReconfigureTrustOperation) Done() bool {
	return op.lro.Done()
}

// Name returns the name of the long-running operation.
// The name is assigned by the server and is unique within the service from which the operation is created.
func (op *ReconfigureTrustOperation) Name() string {
	return op.lro.Name()
}

// UpdateDomainOperation manages a long-running operation from UpdateDomain.
type UpdateDomainOperation struct {
	lro *longrunning.Operation
}

// UpdateDomainOperation returns a new UpdateDomainOperation from a given name.
// The name must be that of a previously created UpdateDomainOperation, possibly from a different process.
func (c *gRPCClient) UpdateDomainOperation(name string) *UpdateDomainOperation {
	return &UpdateDomainOperation{
		lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}),
	}
}

// Wait blocks until the long-running operation is completed, returning the response and any errors encountered.
//
// See documentation of Poll for error-handling information.
func (op *UpdateDomainOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*managedidentitiespb.Domain, error) {
	var resp managedidentitiespb.Domain
	if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil {
		return nil, err
	}
	return &resp, nil
}

// Poll fetches the latest state of the long-running operation.
//
// Poll also fetches the latest metadata, which can be retrieved by Metadata.
//
// If Poll fails, the error is returned and op is unmodified. If Poll succeeds and
// the operation has completed with failure, the error is returned and op.Done will return true.
// If Poll succeeds and the operation has completed successfully,
// op.Done will return true, and the response of the operation is returned.
// If Poll succeeds and the operation has not completed, the returned response and error are both nil.
func (op *UpdateDomainOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*managedidentitiespb.Domain, error) {
	var resp managedidentitiespb.Domain
	if err := op.lro.Poll(ctx, &resp, opts...); err != nil {
		return nil, err
	}
	if !op.Done() {
		return nil, nil
	}
	return &resp, nil
}

// Metadata returns metadata associated with the long-running operation.
// Metadata itself does not contact the server, but Poll does.
// To get the latest metadata, call this method after a successful call to Poll.
// If the metadata is not available, the returned metadata and error are both nil.
func (op *UpdateDomainOperation) Metadata() (*managedidentitiespb.OpMetadata, error) {
	var meta managedidentitiespb.OpMetadata
	if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata {
		return nil, nil
	} else if err != nil {
		return nil, err
	}
	return &meta, nil
}

// Done reports whether the long-running operation has completed.
func (op *UpdateDomainOperation) Done() bool {
	return op.lro.Done()
}

// Name returns the name of the long-running operation.
// The name is assigned by the server and is unique within the service from which the operation is created.
func (op *UpdateDomainOperation) Name() string {
	return op.lro.Name()
}

// ValidateTrustOperation manages a long-running operation from ValidateTrust.
type ValidateTrustOperation struct {
	lro *longrunning.Operation
}

// ValidateTrustOperation returns a new ValidateTrustOperation from a given name.
// The name must be that of a previously created ValidateTrustOperation, possibly from a different process.
func (c *gRPCClient) ValidateTrustOperation(name string) *ValidateTrustOperation {
	return &ValidateTrustOperation{
		lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}),
	}
}

// Wait blocks until the long-running operation is completed, returning the response and any errors encountered.
//
// See documentation of Poll for error-handling information.
func (op *ValidateTrustOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*managedidentitiespb.Domain, error) {
	var resp managedidentitiespb.Domain
	if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil {
		return nil, err
	}
	return &resp, nil
}

// Poll fetches the latest state of the long-running operation.
//
// Poll also fetches the latest metadata, which can be retrieved by Metadata.
//
// If Poll fails, the error is returned and op is unmodified. If Poll succeeds and
// the operation has completed with failure, the error is returned and op.Done will return true.
// If Poll succeeds and the operation has completed successfully,
// op.Done will return true, and the response of the operation is returned.
// If Poll succeeds and the operation has not completed, the returned response and error are both nil.
func (op *ValidateTrustOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*managedidentitiespb.Domain, error) {
	var resp managedidentitiespb.Domain
	if err := op.lro.Poll(ctx, &resp, opts...); err != nil {
		return nil, err
	}
	if !op.Done() {
		return nil, nil
	}
	return &resp, nil
}

// Metadata returns metadata associated with the long-running operation.
// Metadata itself does not contact the server, but Poll does.
// To get the latest metadata, call this method after a successful call to Poll.
// If the metadata is not available, the returned metadata and error are both nil.
func (op *ValidateTrustOperation) Metadata() (*managedidentitiespb.OpMetadata, error) {
	var meta managedidentitiespb.OpMetadata
	if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata {
		return nil, nil
	} else if err != nil {
		return nil, err
	}
	return &meta, nil
}

// Done reports whether the long-running operation has completed.
func (op *ValidateTrustOperation) Done() bool {
	return op.lro.Done()
}

// Name returns the name of the long-running operation.
// The name is assigned by the server and is unique within the service from which the operation is created.
func (op *ValidateTrustOperation) Name() string {
	return op.lro.Name()
}

// DomainIterator manages a stream of *managedidentitiespb.Domain.
type DomainIterator struct {
	items    []*managedidentitiespb.Domain
	pageInfo *iterator.PageInfo
	nextFunc func() error

	// Response is the raw response for the current page.
	// It must be cast to the RPC response type.
	// Calling Next() or InternalFetch() updates this value.
	Response interface{}

	// InternalFetch is for use by the Google Cloud Libraries only.
	// It is not part of the stable interface of this package.
	//
	// InternalFetch returns results from a single call to the underlying RPC.
	// The number of results is no greater than pageSize.
	// If there are no more results, nextPageToken is empty and err is nil.
	InternalFetch func(pageSize int, pageToken string) (results []*managedidentitiespb.Domain, nextPageToken string, err error)
}

// PageInfo supports pagination. See the google.golang.org/api/iterator package for details.
func (it *DomainIterator) PageInfo() *iterator.PageInfo {
	return it.pageInfo
}

// Next returns the next result. Its second return value is iterator.Done if there are no more
// results. Once Next returns Done, all subsequent calls will return Done.
func (it *DomainIterator) Next() (*managedidentitiespb.Domain, error) {
	var item *managedidentitiespb.Domain
	if err := it.nextFunc(); err != nil {
		return item, err
	}
	item = it.items[0]
	it.items = it.items[1:]
	return item, nil
}

func (it *DomainIterator) bufLen() int {
	return len(it.items)
}

func (it *DomainIterator) takeBuf() interface{} {
	b := it.items
	it.items = nil
	return b
}


text:
 -- Table: material_to_operation_map

CREATE TABLE material_to_operation_map
(
    material_id numeric(18,0) NOT NULL,
    operation_id numeric(18,0) NOT NULL,
    CONSTRAINT material_to_operation_map_pk PRIMARY KEY (material_id, operation_id)
)
WITH(OIDS=FALSE);

ALTER TABLE material_to_operation_map OWNER TO "sobek";

ALTER TABLE material_to_operation_map ADD CONSTRAINT m_to_o_material_id_fk FOREIGN KEY (material_id) REFERENCES node (id) ON DELETE NO ACTION ON UPDATE NO ACTION;
ALTER TABLE material_to_operation_map ADD CONSTRAINT m_to_o_operation_id_fk FOREIGN KEY (operation_id) REFERENCES node (id) ON DELETE NO ACTION ON UPDATE NO ACTION;

redpajama_set_name: RedPajamaGithub


text:
class  PageMastercard1Form < DatashiftJourney::BaseCollectorForm

  def params_key
    :page_mastercard1
  end

  property :field_value
  # Example basic validation - has field been filled in :
  # validates :field_value, presence: true
end


text:
/**
 * JUnit v3.x examples.
 */
package junit.samples;


text:
/**
 * Created by ivar on 1.12.15.
 */

define([
    'angularAMD'
], function (angularAMD) {

    angularAMD.controller('admin/senseRelType/addCtrl', ['$scope', '$state', '$uibModal', '$uibModalInstance', 'wnwbApi', function ($scope, $state, $uibModal, $uibModalInstance, wnwbApi) {
        console.log('admin/senseRelType/SenseRelTypeCtrl');

        $scope.senseRelType = new wnwbApi.SenseRelType();
        $scope.senseRelType.other = 0;

        $scope.initCounterpartOptions = function () {
            $scope.counterpartOptions = [{id: 0, name: 'N/A'}];
            angular.forEach($scope.senseRelTypes, function(value, key) {
                if(value != $scope.senseRelType && (value.direction == $scope.senseRelType.direction || $scope.senseRelType.other == value.id)) {
                    $scope.counterpartOptions.push(value);
                }
            });
        };

        $scope.$watch('senseRelType.direction', function (newVal, oldVal) {
            if(oldVal != newVal) {
                $scope.senseRelType.other = 0;
            }

            $scope.initCounterpartOptions();
        });

        $scope.initCounterpartOptions();

        $scope.save = function (form) {
            form.submitted = true;
            if(!form.$valid){
                return;
            }

            $scope.senseRelType.$save(function() {
                $uibModalInstance.close($scope.senseRelType);
                $scope.loadData();
            });
        };
    }]);
});


text:
//
//  GTLMapsEngineGeoJsonLineString.m
//

// ----------------------------------------------------------------------------
// NOTE: This file is generated from Google APIs Discovery Service.
// Service:
//   Google Maps Engine API (mapsengine/v1)
// Description:
//   The Google Maps Engine API allows developers to store and query geospatial
//   vector and raster data.
// Documentation:
//   https://developers.google.com/maps-engine/
// Classes:
//   GTLMapsEngineGeoJsonLineString (0 custom class methods, 2 custom properties)

#import "GTLMapsEngineGeoJsonLineString.h"

// ----------------------------------------------------------------------------
//
//   GTLMapsEngineGeoJsonLineString
//

@implementation GTLMapsEngineGeoJsonLineString
@dynamic coordinates, type;

+ (NSDictionary *)arrayPropertyToClassMap {
  NSDictionary *map = @{
    @"coordinates" : [NSNumber class]
  };
  return map;
}

@end


text:
<?xml version="1.0" encoding="UTF-8"?>
 <!DOCTYPE html PUBLIC  "-//W3C//DTD XHTML 1.0 Transitional//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Tests if the cursor property and cursor element are supported</title>

SVG Image
Reference Image

<object data="../svggen/interact-cursor-01-f.svg" width="480" height="360" type="image/svg+xml"/>

Test passes if all the different cursor behaviour is correct according to the description.

Move the cursor to the top left corner, in the white area. This is the default cursor.

Move the cursor over the text at the top of the example. The cursor changes to the text cursor.

Move the cursor to the blue link text - the cursor changes to the pointer cursor.

Now, move the cursor in turn to each of the gray rectangles. From top to bottom in the first row, the cursor
should change to:

A crosshair or other 'accurate positioning'  cursor

The 'default' cursor, as noted above

The 'pointer' cursor, as noted above

A cursor indicating movement, such as panning

Now from top to bottom in the second row, the cursor should change to:

The 'text' cursor, as noted above

A 'wait' cursor

A 'help' cursor

A special cursor which looks like a small magnifying glass. This is a downloaded image cursor.

Moving to the bottom-rightmost of the eight red triangles, and moving around them clockwise, the
cursor should change to:

SouthEast-resize

South-resize

SouthWest resize

West-resize

NorthWest-resize

North-resize

NorthEast-resize

East-resize

Lastly, move the cursor to the target in the bottom-right of the test. The cursor must not
change to the 'pointer'  cursor, but instread to the special magnifying glass cursor.


text:
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

/*
The test runner should check that, after `rustpkg install external crate`
  with RUST_PATH undefined in the environment
  and with `rustpkg install deeply/nested/path/foo` already
     executed:
   * ./.rust/external_crate exists and is an executable
*/

extern mod foo; // refers to deeply/nested/path/foo

fn main() {}


text:
package hosts

import (
	"os"
	"path/filepath"
	"strconv"
	"strings"
	"time"

	"github.com/coredns/caddy"
	"github.com/coredns/coredns/core/dnsserver"
	"github.com/coredns/coredns/plugin"
	clog "github.com/coredns/coredns/plugin/pkg/log"
)

var log = clog.NewWithPlugin("hosts")

func init() { plugin.Register("hosts", setup) }

func periodicHostsUpdate(h *Hosts) chan bool {
	parseChan := make(chan bool)

	if h.options.reload == 0 {
		return parseChan
	}

	go func() {
		ticker := time.NewTicker(h.options.reload)
		for {
			select {
			case <-parseChan:
				return
			case <-ticker.C:
				h.readHosts()
			}
		}
	}()
	return parseChan
}

func setup(c *caddy.Controller) error {
	h, err := hostsParse(c)
	if err != nil {
		return plugin.Error("hosts", err)
	}

	parseChan := periodicHostsUpdate(&h)

	c.OnStartup(func() error {
		h.readHosts()
		return nil
	})

	c.OnShutdown(func() error {
		close(parseChan)
		return nil
	})

	dnsserver.GetConfig(c).AddPlugin(func(next plugin.Handler) plugin.Handler {
		h.Next = next
		return h
	})

	return nil
}

func hostsParse(c *caddy.Controller) (Hosts, error) {
	config := dnsserver.GetConfig(c)

	h := Hosts{
		Hostsfile: &Hostsfile{
			path:    "/etc/hosts",
			hmap:    newMap(),
			inline:  newMap(),
			options: newOptions(),
		},
	}

	inline := []string{}
	i := 0
	for c.Next() {
		if i > 0 {
			return h, plugin.ErrOnce
		}
		i++

		args := c.RemainingArgs()

		if len(args) >= 1 {
			h.path = args[0]
			args = args[1:]

			if !filepath.IsAbs(h.path) && config.Root != "" {
				h.path = filepath.Join(config.Root, h.path)
			}
			s, err := os.Stat(h.path)
			if err != nil {
				if os.IsNotExist(err) {
					log.Warningf("File does not exist: %s", h.path)
				} else {
					return h, c.Errf("unable to access hosts file '%s': %v", h.path, err)
				}
			}
			if s != nil && s.IsDir() {
				log.Warningf("Hosts file %q is a directory", h.path)
			}
		}

		origins := make([]string, len(c.ServerBlockKeys))
		copy(origins, c.ServerBlockKeys)
		if len(args) > 0 {
			origins = args
		}

		for i := range origins {
			origins[i] = plugin.Host(origins[i]).Normalize()
		}
		h.Origins = origins

		for c.NextBlock() {
			switch c.Val() {
			case "fallthrough":
				h.Fall.SetZonesFromArgs(c.RemainingArgs())
			case "no_reverse":
				h.options.autoReverse = false
			case "ttl":
				remaining := c.RemainingArgs()
				if len(remaining) < 1 {
					return h, c.Errf("ttl needs a time in second")
				}
				ttl, err := strconv.Atoi(remaining[0])
				if err != nil {
					return h, c.Errf("ttl needs a number of second")
				}
				if ttl <= 0 || ttl > 65535 {
					return h, c.Errf("ttl provided is invalid")
				}
				h.options.ttl = uint32(ttl)
			case "reload":
				remaining := c.RemainingArgs()
				if len(remaining) != 1 {
					return h, c.Errf("reload needs a duration (zero seconds to disable)")
				}
				reload, err := time.ParseDuration(remaining[0])
				if err != nil {
					return h, c.Errf("invalid duration for reload '%s'", remaining[0])
				}
				if reload < 0 {
					return h, c.Errf("invalid negative duration for reload '%s'", remaining[0])
				}
				h.options.reload = reload
			default:
				if len(h.Fall.Zones) == 0 {
					line := strings.Join(append([]string{c.Val()}, c.RemainingArgs()...), " ")
					inline = append(inline, line)
					continue
				}
				return h, c.Errf("unknown property '%s'", c.Val())
			}
		}
	}

	h.initInline(inline)

	return h, nil
}


text:
import {AbstractControl} from "@angular/forms";

export function PositionAddressValidator(control: AbstractControl) : {[key: string] : boolean} {

  let position: string = control.value;

  var REGEXP =  /^[a-zA-Z0-9.,?¿!¡_-ñÑçÇáàéèíìóòúùüï]+$/i;

  if (position != null && position != "" && position.length > 140) {
    return { "incorrectPositionLength": true };
  }
  if (position != null && position != "" && !REGEXP.test(position)) {
    return { "incorrectPositionFormat": true };
  }

  if (position != null && position != "" && position.length < 2 )  {
    return { "incorrectDescriptionMinLength": true };
  }

  return null;
}


text:
require "chef/resource/package"
require "chef/mixin/uris"

class Chef
  class Resource
    class CabPackage < Chef::Resource::Package
      include Chef::Mixin::Uris

      resource_name :cab_package
      provides :cab_package

      description "Use the cab_package resource to install or remove Microsoft Windows cabinet (.cab) packages."
      introduced "12.15"

      allowed_actions :install, :remove

      property  :source, String,
                description: "The local file path or URL for the CAB package.",
                coerce: (proc do |s|
                  unless s.nil?
                    uri_scheme?(s) ? s : Chef::Util::PathHelper.canonical_path(s, false)
                  end
                end),
                default: lazy { |r| r.package_name }, default_description: "The package name."
    end
  end
end


text:
#ifndef _mergeoptmerger_h_
#define _mergeoptmerger_h_

#include "listmerger.h"
#include <string.h>
#include <algorithm>

template <class InvList = vector<unsigned> >
class MergeOptMerger : public ListsMerger<MergeOptMerger<InvList>, InvList> {
private:

  unsigned short* sc;
  unsigned maxId;
  unsigned* queryId;
  unsigned currentQuery;

  // using list weights
  void mergeWithDupls(vector<InvList*> &invLists,
		      unsigned threshold,
		      vector<unsigned> &results);

  // no list weights
  void mergeWithoutDupls(vector<InvList*> &invLists,
			 unsigned threshold,
			 vector<unsigned> &results);

public:
  MergeOptMerger(unsigned maxId = 100000, bool hasDuplicateLists = false)
    : ListsMerger<MergeOptMerger<InvList>, InvList>(hasDuplicateLists) {
    sc = new unsigned short[maxId];
    memset(sc, 0, sizeof(unsigned short) * maxId);
    queryId = new unsigned [maxId];
    memset(queryId, 0, sizeof(unsigned) * maxId);
    this->maxId = maxId;
    currentQuery = 0;
  }

  void merge_Impl(vector<InvList*> &invLists,
		  unsigned threshold,
		  vector<unsigned> &results);

  string getName() {
   return "MergeOptMerger";
  }

  ~MergeOptMerger() {
    if(sc) delete[] sc;
    if(queryId) delete[] queryId;
  }
};

template <class InvList>
void
MergeOptMerger<InvList>::
merge_Impl(vector<InvList*> &invLists,
	   unsigned threshold,
	   vector<unsigned> &results) {

  if(threshold > invLists.size()) return;

  if(this->hasDuplicateLists) mergeWithDupls(invLists, threshold, results);
  else mergeWithoutDupls(invLists, threshold, results);
}

template <class InvList>
void
MergeOptMerger<InvList>::
mergeWithoutDupls(vector<InvList*> &invLists,
		  unsigned threshold,
		  vector<unsigned> &results) {

  sort(invLists.begin(), invLists.end(), MergeOptMerger<InvList>::cmpInvList);

  unsigned numShortLists = invLists.size() - threshold + 1;

  currentQuery++;

  vector<Candi> candis;
  for(unsigned i = 0; i < numShortLists; i++) {
    for(unsigned j = 0; j < invLists[i]->size(); j++) {
      unsigned id = invLists[i]->at(j);
      if(queryId[id] == currentQuery) {
	sc[id]++;
      }
      else {
	queryId[id] = currentQuery;
	sc[id] = 1;
      }
    }
  }

  // verify candidates on long lists
  unsigned stop = invLists.size();
  unsigned start = numShortLists;
  typename InvList::iterator longListsPointers[invLists.size() - numShortLists];
  for(unsigned j = start; j < stop; j++) longListsPointers[j - start] = invLists[j]->begin();

  for(unsigned i = 0; i < maxId; i++) {
    if(sc[i] > 0) {
      if(sc[i] >= threshold) {
	results.push_back(i);
	continue;
      }

      unsigned targetCount = threshold - sc[i];
      unsigned count = 0;
      for(unsigned j = start; j < stop; j++) {
	unsigned llindex = j - start;
	typename InvList::iterator start, end;
	expProbe(longListsPointers[llindex], invLists[j]->end(), start, end, i);

	typename InvList::iterator iter = lower_bound(start, end, i);
	longListsPointers[llindex] = iter;
	if(*iter == i) {
	  count++;
	  if(count >= targetCount) {
	    results.push_back(i);
	    break;
	  }
	}
	else {
	  if(count + stop - j - 1 < targetCount) break; // early termination
	}
      }
    }
  }
}

template <class InvList>
void
MergeOptMerger<InvList>::
mergeWithDupls(vector<InvList*> &invLists,
	       unsigned threshold,
	       vector<unsigned> &results) {

  vector<InvList*> newInvLists;
  vector<unsigned> newWeights;
  detectDuplicateLists(invLists, newInvLists, newWeights);

  // assume that newArray should be sorted according to the length increasing
  unsigned numShortLists = 0;
  unsigned weightCounter = 0;
  unsigned shortListsWeight = invLists.size() - threshold + 1;
  for(unsigned i = 0; i < newInvLists.size() && weightCounter < shortListsWeight; i++) {
    weightCounter += newWeights[i];
    numShortLists++;
  }

  // OLD Heap-Based merging of short lists
  /*
  const typename InvList::value_type maxUnsigned = (typename InvList::value_type)0xFFFFFFFF;

  // add maxUnsigned
  for(unsigned i = 0; i < numShortLists; i++)
    newInvLists[i]->push_back(maxUnsigned);

  vector<HeapElement<InvList> > heap;
  heap.reserve(numShortLists);

  // make initial heap
  make_heap(heap.begin(), heap.end());
  for(unsigned i = 0; i < numShortLists; i++) {
    heap.push_back(HeapElement<InvList>(newInvLists[i]->begin(), i));
    push_heap(heap.begin(), heap.end());
  }

  HeapElement<InvList> popped[numShortLists];
  vector<Candi> candis;

  // merge the short lists
  while(*(heap.front().iter) != maxUnsigned) {

    unsigned weight = 0;
    unsigned count = 0;
    unsigned currentId = *(heap.front().iter);

    while(currentId == *(heap.front().iter) && !heap.empty()) {
      popped[count++] = heap.front();
      weight += newWeights[heap.front().invListIndex];
      pop_heap(heap.begin(), heap.end());
      heap.pop_back();
    }

    candis.push_back(Candi(currentId, weight));

    // move to the next element and push
    for(unsigned i = 0; i < count; i++) {
      popped[i].iter++;
      heap.push_back(HeapElement<InvList>(popped[i].iter, popped[i].invListIndex));
      push_heap(heap.begin(), heap.end());
    }
  }

  // remove maxUnsigned
  for(unsigned i = 0; i < numShortLists; i++)
    newInvLists[i]->pop_back();
  */

  vector<Candi> candis;
  for(unsigned i = 0; i < numShortLists; i++) {
    vector<Candi> tmp;
    vector<Candi>::const_iterator candiIter = candis.begin();

    typename InvList::iterator invListIter = invLists[i]->begin();
    typename InvList::iterator invListEnd = invLists[i]->end();

    while(candiIter != candis.end() || invListIter != invListEnd) {
      if(candiIter == candis.end() || (invListIter != invListEnd && candiIter->id > *invListIter)) {
	tmp.push_back(Candi(*invListIter, newWeights[i]));
	invListIter++;
      } else if (invListIter == invListEnd || (candiIter != candis.end() && candiIter->id < *invListIter)) {
	tmp.push_back(Candi(candiIter->id, candiIter->count));
	candiIter++;
      } else {
	tmp.push_back(Candi(candiIter->id, candiIter->count + newWeights[i]));
	candiIter++;
	invListIter++;
      }
    }
    std::swap(candis, tmp);
  }

  // verify candidates on long lists
  unsigned stop = newInvLists.size();
  unsigned start = numShortLists;
  typename InvList::iterator longListsPointers[newInvLists.size() - numShortLists];

  unsigned totalLongListsWeight = invLists.size() - shortListsWeight;
  unsigned weightRemaining[newInvLists.size() - numShortLists]; // for early termination
  unsigned cumulWeight = 0;
  for(unsigned j = start; j < stop; j++) {
    longListsPointers[j - start] = newInvLists[j]->begin();
    cumulWeight += newWeights[j];
    weightRemaining[j - start] = totalLongListsWeight - cumulWeight;
  }

  // use exponential probe + binary search for long lists
  for(unsigned i = 0; i < candis.size(); i++) {

    if(candis[i].count >= threshold) {
      results.push_back(candis[i].id);
      continue;
    }

    unsigned targetCount = threshold - candis[i].count;
    unsigned count = 0;
    for(unsigned j = start; j < stop; j++) {
      unsigned llindex = j - start;
      typename InvList::iterator start, end;
      expProbe(longListsPointers[llindex], newInvLists[j]->end(), start, end, candis[i].id);

      typename InvList::iterator iter = lower_bound(start, end, candis[i].id);
      longListsPointers[llindex] = iter;
      if(*iter == candis[i].id) {
	count += newWeights[j];
	if(count >= targetCount) {
	  results.push_back(candis[i].id);
	  break;
	}
      }
      else {
	if(count + weightRemaining[llindex] < targetCount) break; // early termination
      }
    }
  }
}

#endif


text:
<!-- DO NOT EDIT THIS FILE! -->
<!-- Instead edit contrib/rocketchat.php -->
<!-- Then run bin/docgen -->

# Rocketchat Recipe

```php
require 'contrib/rocketchat.php';
```

[Source](/contrib/rocketchat.php)

## Installing

Create a RocketChat incoming webhook, through the administration panel.

Add hook on deploy:

```
before('deploy', 'rocketchat:notify');
```

## Configuration

 - `rocketchat_webhook` - incoming rocketchat webook **required**
   ```
   set('rocketchat_webhook', 'https://rocketchat.yourcompany.com/hooks/XXXXX');
   ```

 - `rocketchat_title` - the title of the application, defaults to `{{application}}`
 - `rocketchat_text` - notification message
   ```
   set('rocketchat_text', '_{{user}}_ deploying {{branch}} to {{target}}');
   ```

 - `rocketchat_success_text` – success template, default:
  ```
  set('rocketchat_success_text', 'Deploy to *{{target}}* successful');
  ```
 - `rocketchat_failure_text` – failure template, default:
  ```
  set('rocketchat_failure_text', 'Deploy to *{{target}}* failed');
  ```

 - `rocketchat_color` – color's attachment
 - `rocketchat_success_color` – success color's attachment
 - `rocketchat_failure_color` – failure color's attachment

## Usage

If you want to notify only about beginning of deployment add this line only:

```php
before('deploy', 'rocketchat:notify');
```

If you want to notify about successful end of deployment add this too:

```php
after('deploy:success', 'rocketchat:notify:success');
```

If you want to notify about failed deployment add this too:

```php
after('deploy:failed', 'rocketchat:notify:failure');
```

## Configuration
### rockchat_title
[Source](https://github.com/deployphp/deployer/blob/master/contrib/rocketchat.php#L64)

```php title="Default value"
return get('application', 'Project');
```

### rocketchat_icon_emoji
[Source](https://github.com/deployphp/deployer/blob/master/contrib/rocketchat.php#L68)

```php title="Default value"
':robot:'
```

### rocketchat_icon_url
[Source](https://github.com/deployphp/deployer/blob/master/contrib/rocketchat.php#L69)

```php title="Default value"
null
```

### rocketchat_channel
[Source](https://github.com/deployphp/deployer/blob/master/contrib/rocketchat.php#L71)

```php title="Default value"
null
```

### rocketchat_room_id
[Source](https://github.com/deployphp/deployer/blob/master/contrib/rocketchat.php#L72)

```php title="Default value"
null
```

### rocketchat_username
[Source](https://github.com/deployphp/deployer/blob/master/contrib/rocketchat.php#L73)

```php title="Default value"
null
```

### rocketchat_webhook
[Source](https://github.com/deployphp/deployer/blob/master/contrib/rocketchat.php#L74)

```php title="Default value"
null
```

### rocketchat_color
[Source](https://github.com/deployphp/deployer/blob/master/contrib/rocketchat.php#L76)

```php title="Default value"
'#000000'
```

### rocketchat_success_color
[Source](https://github.com/deployphp/deployer/blob/master/contrib/rocketchat.php#L77)

```php title="Default value"
'#00c100'
```

### rocketchat_failure_color
[Source](https://github.com/deployphp/deployer/blob/master/contrib/rocketchat.php#L78)

```php title="Default value"
'#ff0909'
```

### rocketchat_text
[Source](https://github.com/deployphp/deployer/blob/master/contrib/rocketchat.php#L80)

```php title="Default value"
'_{{user}}_ deploying `{{branch}}` to *{{target}}*'
```

### rocketchat_success_text
[Source](https://github.com/deployphp/deployer/blob/master/contrib/rocketchat.php#L81)

```php title="Default value"
'Deploy to *{{target}}* successful'
```

### rocketchat_failure_text
[Source](https://github.com/deployphp/deployer/blob/master/contrib/rocketchat.php#L82)

```php title="Default value"
'Deploy to *{{target}}* failed'
```

## Tasks

### rocketchat:notify
[Source](https://github.com/deployphp/deployer/blob/master/contrib/rocketchat.php#L85)

Notifies RocketChat.

### rocketchat:notify:success
[Source](https://github.com/deployphp/deployer/blob/master/contrib/rocketchat.php#L115)

Notifies RocketChat about deploy finish.

### rocketchat:notify:failure
[Source](https://github.com/deployphp/deployer/blob/master/contrib/rocketchat.php#L145)

Notifies RocketChat about deploy failure.


text:
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const ManifestPlugin = require('webpack-manifest-plugin');

module.exports = ({production = false, browser = false} = {}) => {
  const bannerOptions = {
    raw: true,
    banner: 'require("source-map-support").install();'
  };
  const compress = {
    warnings: false
  };
  const compileTimeConstantForMinification = {
    __PRODUCTION__: JSON.stringify(production)
  };

  if (!production && !browser) {
    return [
      new webpack.EnvironmentPlugin(['NODE_ENV']),
      new webpack.DefinePlugin(compileTimeConstantForMinification),
      new webpack.BannerPlugin(bannerOptions)
    ];
  }
  if (!production && browser) {
    return [
      new webpack.EnvironmentPlugin(['NODE_ENV']),
      new webpack.DefinePlugin(compileTimeConstantForMinification),
      new webpack.HotModuleReplacementPlugin(),
      new webpack.NoEmitOnErrorsPlugin(),
      new webpack.ProvidePlugin({
        $: 'jquery',
        jQuery: 'jquery',
        jquery: 'jquery'
      })
    ];
  }
  if (production && !browser) {
    return [
      new webpack.EnvironmentPlugin(['NODE_ENV']),
      new webpack.DefinePlugin(compileTimeConstantForMinification),
      new webpack.BannerPlugin(bannerOptions),
      new webpack.optimize.UglifyJsPlugin({
        compress
      }),
      new webpack.ProvidePlugin({
        $: 'jquery',
        jQuery: 'jquery',
        jquery: 'jquery'
      })
    ];
  }
  if (production && browser) {
    return [
      new webpack.EnvironmentPlugin(['NODE_ENV']),
      new webpack.DefinePlugin(compileTimeConstantForMinification),
      new ExtractTextPlugin({
        filename: '[contenthash].css',
        allChunks: true
      }),
      new webpack.optimize.UglifyJsPlugin({
        compress
      }),
      new ManifestPlugin({
        fileName: 'manifest.json'
      }),
      new webpack.ProvidePlugin({
        $: 'jquery',
        jQuery: 'jquery',
        jquery: 'jquery'
      })
    ];
  }
  return [];
};


text:
<?php

namespace Magento\Customer\Test\Unit\Model\Config\Backend\CreateAccount;

class DisableAutoGroupAssignDefaultTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var \Magento\Customer\Model\Config\Backend\CreateAccount\DisableAutoGroupAssignDefault
     */
    protected $model;

    /**
     * @var \Magento\Eav\Model\Config|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $eavConfigMock;

    protected function setUp()
    {
        $this->eavConfigMock = $this->getMockBuilder('Magento\Eav\Model\Config')
            ->disableOriginalConstructor()
            ->getMock();

        $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this);
        $this->model = $objectManager->getObject(
            'Magento\Customer\Model\Config\Backend\CreateAccount\DisableAutoGroupAssignDefault',
            [
                'eavConfig' => $this->eavConfigMock,
            ]
        );
    }

    public function testAfterSave()
    {
        $value = true;

        $attributeMock = $this->getMockBuilder('Magento\Eav\Model\Entity\Attribute\AbstractAttribute')
            ->setMethods(['save', 'setData'])
            ->disableOriginalConstructor()
            ->getMockForAbstractClass();

        $this->eavConfigMock->expects($this->once())
            ->method('getAttribute')
            ->with('customer', 'disable_auto_group_change')
            ->willReturn($attributeMock);

        $attributeMock->expects($this->once())
            ->method('setData')
            ->with('default_value', $value);
        $attributeMock->expects($this->once())
            ->method('save');

        $this->model->setValue($value);

        $this->assertEquals($this->model, $this->model->afterSave());
    }
}


text:
<meta charset="UTF-8">
<title>AdaptedPropertyCasMapping.setAnnotationClassName - biomedicus-uima</title>
<link rel="stylesheet" href="../../../style.css">

biomedicus-uima / edu.umn.biomedicus.uima.rtf / AdaptedPropertyCasMapping / setAnnotationClassName

setAnnotationClassName

open fun setAnnotationClassName(@Nullable annotationClassName: String?): Unit


text:
"""Run ES and PES to tune regularization hyperparameters (e.g., L2 coefficient)

for UCI regression tasks.

Run the UCI experiments:
------------------------
for INIT_THETA in 5 3 1 -1 -3 -5 ; do
    CUDA_VISIBLE_DEVICES=-1 python uci.py \
        --estimate=pes \
        --K=1 \
        --outer_lr=0.003 \
        --lr=0.001 \
        --init_theta=$INIT_THETA \
        --save_dir=saves_uci &
done

for INIT_THETA in 5 3 1 -1 -3 -5 ; do
    CUDA_VISIBLE_DEVICES=-1 python uci.py \
        --estimate=es \
        --K=1 \
        --outer_lr=0.003 \
        --lr=0.001 \
        --init_theta=$INIT_THETA \
        --save_dir=saves_uci &
done

for INIT_THETA in 5 3 1 -1 -3 -5 ; do
    CUDA_VISIBLE_DEVICES=-1 python uci.py \
        --estimate=pes-a \
        --K=1 \
        --outer_lr=0.003 \
        --lr=0.001 \
        --init_theta=$INIT_THETA \
        --save_dir=saves_uci &
done

Plot the results:
-----------------
python plot_uci.py
"""
import os
import sys
import pdb
import argparse
import numpy as np
import pandas as pd
import pickle as pkl
from functools import partial
from typing import NamedTuple, Optional, Any, Union

# YAML setup
from ruamel.yaml import YAML

yaml = YAML()
yaml.preserve_quotes = True
yaml.boolean_representation = ['False', 'True']

import jax
import jax.numpy as jnp
from jax import flatten_util

import optax

# Local imports
import inner_optim
import gradient_estimators
from logger import CSVLogger

parser = argparse.ArgumentParser(description='UCI Regression Task')
parser.add_argument('--data', type=str, default='yacht', help='Dataset')

parser.add_argument(
    '--outer_iterations',
    type=int,
    default=50000,
    help='Number of meta-optimization iterations')
parser.add_argument(
    '--outer_optimizer', type=str, default='adam', help='Outer optimizer')
parser.add_argument(
    '--outer_lr', type=float, default=1e-3, help='Outer learning rate')
parser.add_argument(
    '--outer_b1',
    type=float,
    default=0.99,
    help='Outer optimizer Adam b1 hyperparameter')
parser.add_argument(
    '--outer_b2',
    type=float,
    default=0.9999,
    help='Outer optimizer Adam b2 hyperparameter')
parser.add_argument(
    '--outer_eps',
    type=float,
    default=1e-8,
    help='Outer optimizer Adam epsilon hyperparameter')
parser.add_argument(
    '--outer_clip',
    type=float,
    default=-1,
    help='Outer gradient clipping (-1 means no clipping)')

parser.add_argument(
    '--regularizer_type',
    type=str,
    default='l2',
    choices=['l1', 'l2'],
    help='Regularizer type (l1 or l2)')
parser.add_argument(
    '--init_theta',
    type=float,
    default=-1.0,
    help='The initial regularization coefficient for L1 or L2')

parser.add_argument(
    '--inner_optimizer', type=str, default='sgd', help='Inner optimizer')
parser.add_argument('--lr', type=float, default=0.001, help='Learning rate')

parser.add_argument(
    '--estimate',
    type=str,
    default='pes',
    choices=['tbptt', 'es', 'pes', 'pes-a'],
    help='Type of gradient estimate (es or pes)')
# parser.add_argument('--T', type=int, default=10000,
parser.add_argument(
    '--T',
    type=int,
    default=1000000,
    help='Maximum number of iterations of the inner loop')
parser.add_argument(
    '--K',
    type=int,
    default=10,
    help='Number of steps to unroll (== truncation length)')
parser.add_argument(
    '--N', type=int, default=4, help='Number of ES/PES particles')
parser.add_argument(
    '--sigma',
    type=float,
    default=0.01,
    help='Variance for ES/PES perturbations')

parser.add_argument(
    '--log_every',
    type=int,
    default=10,
    help='Log the full training and val losses to the CSV log'
    'every N iterations')
parser.add_argument(
    '--prefix', type=str, default='', help='Optional experiment name prefix')
parser.add_argument(
    '--save_dir', type=str, default='saves', help='Save directory')
parser.add_argument('--seed', type=int, default=3, help='Random seed')
args = parser.parse_args()

# Set random seed
np.random.seed(args.seed)

if args.prefix:
  exp_name = '{}-{}-{}-theta:{}-lr:{}-olr:{}-K:{}-N:{}-sig:{}-s:{}'.format(
      args.prefix, args.data, args.estimate, args.init_theta, args.lr,
      args.outer_lr, args.K, args.N, args.sigma, args.seed)
else:
  exp_name = '{}-{}-theta:{}-lr:{}-olr:{}-K:{}-N:{}-sig:{}-s:{}'.format(
      args.data, args.estimate, args.init_theta, args.lr, args.outer_lr, args.K,
      args.N, args.sigma, args.seed)

save_dir = os.path.join(args.save_dir, exp_name)

# Create experiment save directory
if not os.path.exists(save_dir):
  os.makedirs(save_dir)

# Save command-line arguments
with open(os.path.join(save_dir, 'args.yaml'), 'w') as f:
  yaml.dump(vars(args), f)

iteration_logger = CSVLogger(
    fieldnames=[
        'outer_iteration', 'total_inner_iterations', 'val_loss', 'theta',
        'theta_grad'
    ],
    filename=os.path.join(save_dir, 'iteration.csv'))

# Based on https://github.com/stanfordmlgroup/ngboost/blob/master/examples/experiments/regression_exp.py
dataset_name_to_loader = {
    'housing':
        lambda: pd.read_csv(
            'https://archive.ics.uci.edu/ml/machine-learning-databases/housing/housing.data',
            header=None,
            delim_whitespace=True,
        ),
    'concrete':
        lambda: pd.read_excel(
            'https://archive.ics.uci.edu/ml/machine-learning-databases/concrete/compressive/Concrete_Data.xls'
        ),
    'wine':
        lambda: pd.read_csv(
            'https://archive.ics.uci.edu/ml/machine-learning-databases/wine-quality/winequality-red.csv',
            delimiter=';',
        ),
    'kin8nm':
        lambda: pd.read_csv('data/uci/kin8nm.csv'),
    'naval':
        lambda: pd.read_csv(
            'data/uci/naval-propulsion.txt', delim_whitespace=True, header=None)
        .iloc[:, :-1],
    'power':
        lambda: pd.read_excel('data/uci/power-plant.xlsx'),
    'energy':
        lambda: pd.read_excel(
            'https://archive.ics.uci.edu/ml/machine-learning-databases/00242/ENB2012_data.xlsx'
        ).iloc[:, :-1],
    'protein':
        lambda: pd.read_csv('data/uci/protein.csv')
        [['F1', 'F2', 'F3', 'F4', 'F5', 'F6', 'F7', 'F8', 'F9', 'RMSD']],
    'yacht':
        lambda: pd.read_csv(
            'http://archive.ics.uci.edu/ml/machine-learning-databases/00243/yacht_hydrodynamics.data',
            header=None,
            delim_whitespace=True,
        ),
    'msd':
        lambda: pd.read_csv('data/uci/YearPredictionMSD.txt').iloc[:, ::-1],
}

data = dataset_name_to_loader['yacht']()
X, y = data.iloc[:, :-1].values, data.iloc[:, -1].values

# If we want to normalize the data with mean and standard deviation computed
# over all the data (including both the training and val data)
# ------------------------------------------------------------
X_mean, X_std = np.mean(X, axis=0), np.std(X, axis=0)
y_mean, y_std = np.mean(y, axis=0), np.std(y, axis=0)
X = (X - X_mean) / X_std
y = (y - y_mean) / y_std
# ------------------------------------------------------------

# Dataloading based on:
#   https://github.com/yaringal/DropoutUncertaintyExps/blob/master/UCI_Datasets/concrete/data/split_data_train_test.py
n = X.shape[0]
np.random.seed(1)

permutation = np.random.choice(range(n), n, replace=False)
end_train = round(n * 80.0 / 100.0)  # Take 80% of the data as training data
end_vak = n
train_index = permutation[0:end_train]
val_index = permutation[end_train:n]

x_train, x_val = X[train_index], X[val_index]
y_train, y_val = y[train_index], y[val_index]

print(
    'x_train.shape: {} | y_train.shape: {} | x_val.shape: {} | y_val.shape: {}'
    .format(x_train.shape, y_train.shape, x_val.shape, y_val.shape))

N_train = x_train.shape[0]
N_val = x_val.shape[0]
print('N_train: {} | N_val: {}'.format(N_train, N_val))

def model_forward(w, x):
  return jnp.dot(x, w)

@jax.jit
def L_t_reg(w, theta):
  output = model_forward(w, x_train)
  mse_loss = 0.5 * jnp.sum(jnp.square(output.reshape(-1) - y_train.reshape(-1)))
  w_flat, _ = flatten_util.ravel_pytree(w)
  if args.regularizer_type == 'l2':
    regularizer = 0.5 * jnp.sum(jnp.exp(theta) * w_flat**2)
  elif args.regularizer_type == 'l1':
    regularizer = jnp.sum(jnp.exp(theta) * jnp.abs(w_flat))
  return mse_loss + regularizer

grad_L_t_reg = jax.jit(jax.grad(L_t_reg, argnums=0))

# ====================================

@jax.jit
def L_v(w):
  output = model_forward(w, x_val)
  mse_loss = 0.5 * jnp.sum(jnp.square(output.reshape(-1) - y_val.reshape(-1)))
  return mse_loss

@partial(jax.jit, static_argnames=('T', 'K'))
def unroll(rng, theta, state, T, K):

  def update(loop_state, i):
    state, L = loop_state
    g = grad_L_t_reg(state.inner_state, theta)
    inner_state_updated, opt_state = opt_step(state.inner_state, g,
                                              state.inner_opt_state)

    loss_value = L_v(inner_state_updated)
    L += loss_value

    state_updated = state._replace(
        inner_state=inner_state_updated,
        inner_opt_state=opt_state,
        t=state.t + 1,
    )
    return (state_updated, L), loss_value

  (state_updated, L), loss_values = jax.lax.scan(update, (state, 0.0),
                                                 jnp.array(list(range(K))))

  result = jnp.sum(loss_values)
  return result, state_updated

@partial(jax.jit, static_argnums=3)
def unroll_and_L_v(w, theta, inner_optim_params, K):
  w_unrolled, _ = unroll(w, theta, inner_optim_params, K)
  return L_v(w_unrolled)

grad_unroll_and_L_v = jax.jit(
    jax.grad(unroll_and_L_v, argnums=1), static_argnums=3)

opt_funcs = inner_optim.init_optimizer('sgd')
reset_opt_params = opt_funcs['reset_opt_params']
opt_step = opt_funcs['opt_step']

init_opt_params = {'lr': 0.001, 'wd': 0.0}

class InnerState(NamedTuple):
  inner_state: jnp.ndarray
  inner_opt_state: Any
  t: jnp.ndarray
  pert_accums: Optional[jnp.ndarray] = None

def init_state_fn(rng):
  """Initialize the inner parameters."""
  w = jax.random.normal(key, (x_train.shape[1],))
  inner_opt_state = reset_opt_params(w, init_opt_params)

  inner_state = InnerState(
      t=jnp.array(0).astype(jnp.int32),
      inner_state=w,
      inner_opt_state=inner_opt_state)
  return inner_state

theta = jnp.array([args.init_theta])
theta_opt = optax.adam(args.outer_lr)
theta_opt_state = theta_opt.init(theta)

key = jax.random.PRNGKey(args.seed)
estimator = gradient_estimators.MultiParticleEstimator(
    key=key,
    theta_shape=theta.shape,
    n_chunks=1,
    n_particles_per_chunk=args.N,
    K=args.K,
    T=args.T,
    sigma=args.sigma,
    method='lockstep',
    estimator_type=args.estimate,
    init_state_fn=init_state_fn,
    unroll_fn=unroll,
)

iterations = []
lam_trajectory = []
eps_trajectory = []
total_inner_iterations = 0

# A particle that will be evolved using the mean theta
state_mean = init_state_fn(key)

key = jax.random.PRNGKey(3)
for outer_iteration in range(args.outer_iterations):
  key, skey = jax.random.split(key)
  theta_grad = estimator.grad_estimate(theta)

  if args.outer_clip > 0:
    theta_grad = jnp.clip(theta_grad, -args.outer_clip, args.outer_clip)

  theta_update, theta_opt_state = theta_opt.update(theta_grad, theta_opt_state)
  theta = optax.apply_updates(theta, theta_update)

  _, state_mean = unroll(key, theta, state_mean, args.T, args.K)
  total_inner_iterations += 2 * args.K
  total_inner_iterations_including_N = args.N * total_inner_iterations

  if outer_iteration % args.log_every == 0:
    val_loss = L_v(state_mean.inner_state)
    print('Iter: {} | Total iter: {} | Val Loss: {:6.4f} | Theta: {} | Grad: {}'
          .format(outer_iteration, total_inner_iterations_including_N, val_loss,
                  theta, theta_grad))

    iteration_stat_dict = {
        'outer_iteration': outer_iteration,
        'total_inner_iterations': total_inner_iterations_including_N,
        'val_loss': val_loss,
        'theta': theta,
        'theta_grad': theta_grad
    }
    iteration_logger.writerow(iteration_stat_dict)


text:
package org.kaaproject.kaa.server.common.core.configuration;

import org.kaaproject.kaa.server.common.core.schema.DataSchema;

public class ProfileData extends AbstractKaaData<DataSchema> {

    private static final long serialVersionUID = -149116092748606760L;

    public ProfileData(DataSchema schema, String data) {
        super(schema, data);
    }

}


text:
import json
import time

from monasca_common.kafka import consumer
from monasca_common.kafka import producer
from oslo_config import cfg
from oslo_log import log as logging
from six import PY3

from monasca_notification.common.utils import construct_notification_object
from monasca_notification.common.utils import get_db_repo
from monasca_notification.common.utils import get_statsd_client
from monasca_notification.processors import notification_processor

log = logging.getLogger(__name__)
CONF = cfg.CONF

class RetryEngine(object):
    def __init__(self):
        self._statsd = get_statsd_client()

        self._consumer = consumer.KafkaConsumer(
            CONF.kafka.url,
            ','.join(CONF.zookeeper.url),
            CONF.zookeeper.notification_retry_path,
            CONF.kafka.group,
            CONF.kafka.notification_retry_topic
        )
        self._producer = producer.KafkaProducer(CONF.kafka.url)

        self._notifier = notification_processor.NotificationProcessor()
        self._db_repo = get_db_repo()

    def run(self):
        for raw_notification in self._consumer:
            message = raw_notification[1].message.value

            message = message.decode('UTF-8') if PY3 else message
            notification_data = json.loads(message)

            notification = construct_notification_object(self._db_repo, notification_data)

            if notification is None:
                self._consumer.commit()
                continue

            wait_duration = CONF.retry_engine.interval - (
                time.time() - notification_data['notification_timestamp'])

            if wait_duration > 0:
                time.sleep(wait_duration)

            sent, failed = self._notifier.send([notification])

            if sent:
                self._producer.publish(CONF.kafka.notification_topic,
                                       [notification.to_json()])

            if failed:
                notification.retry_count += 1
                notification.notification_timestamp = time.time()
                if notification.retry_count < CONF.retry_engine.max_attempts:
                    log.error(u"retry failed for {} with name {} "
                              u"at {}.  "
                              u"Saving for later retry.".format(notification.type,
                                                                notification.name,
                                                                notification.address))
                    self._producer.publish(CONF.kafka.notification_retry_topic,
                                           [notification.to_json()])
                else:
                    log.error(u"retry failed for {} with name {} "
                              u"at {} after {} retries.  "
                              u"Giving up on retry."
                              .format(notification.type,
                                      notification.name,
                                      notification.address,
                                      CONF.retry_engine.max_attempts))

            self._consumer.commit()


text:
cd

for i in /bsbm/data/benchmark/sql/*.sql
do
  echo "file=$i"
  mysql -u root -h base_mysql  benchmark < $i
done


text:
'use strict';

const models = require('./index');

/**
 * An Azure resource
 *
 * @extends models['BaseResource']
 */
class Resource extends models['BaseResource'] {
  /**
   * Create a Resource.
   * @member {string} [id] The fully qualified Maps Account resource
   * identifier.
   * @member {string} [name] The name of the Maps Account, which is unique
   * within a Resource Group.
   * @member {string} [type] Azure resource type.
   */
  constructor() {
    super();
  }

  /**
   * Defines the metadata of Resource
   *
   * @returns {object} metadata of Resource
   *
   */
  mapper() {
    return {
      required: false,
      serializedName: 'Resource',
      type: {
        name: 'Composite',
        className: 'Resource',
        modelProperties: {
          id: {
            required: false,
            readOnly: true,
            serializedName: 'id',
            type: {
              name: 'String'
            }
          },
          name: {
            required: false,
            readOnly: true,
            serializedName: 'name',
            type: {
              name: 'String'
            }
          },
          type: {
            required: false,
            readOnly: true,
            serializedName: 'type',
            type: {
              name: 'String'
            }
          }
        }
      }
    };
  }
}

module.exports = Resource;


text:
MTGSetCalculator
================

An html interface for number-crunching custom Magic the Gathering sets.

To use MTG Set Calculator, simply download the file and open index.html.


text:
using ModuleA.Views;
using Prism.Ioc;
using Prism.Modularity;
using Prism.Regions;

namespace ModuleA
{
    public class ModuleAModule : IModule
    {
        public void OnInitialized(IContainerProvider containerProvider)
        {
            var regionManager = containerProvider.Resolve<IRegionManager>();
            regionManager.RegisterViewWithRegion("ContentRegion", typeof(ViewA));
        }

        public void RegisterTypes(IContainerRegistry containerRegistry)
        {

        }
    }
}


text:
import os

from django.template.base import Node

from opbeat.utils.stacks import get_frame_info

try:
    from django.template.base import Template
except ImportError:
    class Template(object):
        pass

def linebreak_iter(template_source):
    yield 0
    p = template_source.find('\n')
    while p >= 0:
        yield p + 1
        p = template_source.find('\n', p + 1)
    yield len(template_source) + 1

def get_data_from_template_source(source):
    origin, (start, end) = source
    template_source = origin.reload()

    lineno = None
    upto = 0
    source_lines = []
    for num, next in enumerate(linebreak_iter(template_source)):
        if start >= upto and end <= next:
            lineno = num
        source_lines.append(template_source[upto:next])
        upto = next

    if not source_lines or lineno is None:
        return {}

    pre_context = source_lines[max(lineno - 3, 0):lineno]
    post_context = source_lines[(lineno + 1):(lineno + 4)]
    context_line = source_lines[lineno]

    return {
        'template': {
            'filename': origin.loadname,
            'abs_path': origin.name,
            'pre_context': pre_context,
            'context_line': context_line,
            'lineno': lineno,
            'post_context': post_context,
        },
        'culprit': origin.loadname,
    }

def get_data_from_template_debug(template_debug):
    pre_context = []
    post_context = []
    context_line = None
    for lineno, line in template_debug['source_lines']:
        if lineno < template_debug['line']:
            pre_context.append(line)
        elif lineno > template_debug['line']:
            post_context.append(line)
        else:
            context_line = line
    return {
        'template': {
            'filename': os.path.basename(template_debug['name']),
            'abs_path': template_debug['name'],
            'pre_context': pre_context,
            'context_line': context_line,
            'lineno': template_debug['line'],
            'post_context': post_context,
        },
        'culprit': os.path.basename(template_debug['name']),
    }

def iterate_with_template_sources(frames, extended=True):
    template = None
    for frame, lineno in frames:
        f_code = getattr(frame, 'f_code', None)
        if f_code:
            function = frame.f_code.co_name
            if function == 'render':
                renderer = getattr(frame, 'f_locals', {}).get('self')
                if renderer and isinstance(renderer, Node):
                    if getattr(renderer, "token", None) is not None:
                        if hasattr(renderer, "source"):
                            # up to Django 1.8
                            yield {
                                'lineno': renderer.token.lineno,
                                'filename': renderer.source[0].name
                            }
                        else:
                            template = {'lineno': renderer.token.lineno}
                # Django 1.9 doesn't have the origin on the Node instance,
                # so we have to get it a bit further down the stack from the
                # Template instance
                elif renderer and isinstance(renderer, Template):
                    if template and getattr(renderer, 'origin', None):
                        template['filename'] = renderer.origin.name
                        yield template
                        template = None

        yield get_frame_info(frame, lineno, extended)


text:
Yii2 Glide
==========
Yii2 Glide integration.
> Glide is a wonderfully easy on-demand image manipulation library written in PHP.

Before you start read [Glide documentation](http://glide.thephpleague.com/) to understand what we are doing

Demo
----
Since this package was created as a part of [yii2-starter-kit](https://github.com/trntv/yii2-starter-kit) it's demo can be found in starter kit demo.

Contibuting
-----------
You can contribute anything you found useful in any convenient way. Any help appreciated.

Installation
------------

The preferred way to install this extension is through [composer](http://getcomposer.org/download/).

Either run

```
php composer.phar require --prefer-dist trntv/yii2-glide "*"
```

or add

```
"trntv/yii2-glide": "*"
```

to the require section of your `composer.json` file.

Usage
-----

Add glide configuration:

```php
'components' => [
    ...
    'glide' => [
        'class' => 'trntv\glide\components\Glide',
        'sourcePath' => '@app/web/uploads',
        'cachePath' => '@runtime/glide',
        'signKey' => '<random-key>' // "false" if you do not want to use HTTP signatures
    ],
    ...
]
```

Then you can output modified image like so:
```php
Yii::$app->glide->outputImage('new-upload.jpg', ['w' => 100, 'fit' => 'crop'])
```

You can also use ``trntv\glide\actions\GlideAction`` to output images:
In any controller add (``SiteController`` for example):
```php
public function actions()
{
    return [
        'glide' => 'trntv\glide\actions\GlideAction'
    ]
}
```
Than use it:
``/index.php?r=site/glide?path=new-upload.jpg&w=100&h=75``

Example
-------
Complex Glide integration example can be found [here](https://github.com/trntv/yii2-starter-kit/tree/master/storage)

Secure Urls
-----------
TBD


text:
package pe.org.edustats.service.util;

public class ServiceConstants {

  // messages constants
  // MC_XXX = MESSAGE_CODE_XXX
  public static final String MC_EXISTE_PERIODO_ACADEMICO_APERTURADO = "periodo_academico.ya_aperturado";

  public static final String MC_ACCESS_DENIED = "acceso.permiso_denegado";

}


text:
/*jshint eqnull: true, browser: true */
/*global describe, it, expect, beforeEach, afterEach, SocketWrench, window*/

  // .isReady
describe('.isReady', function () {
  'use strict';

  beforeEach(function () {
    this.defaults = {
      url : 'ws://localhost:4014',
      autoConnect : false
    };
    this.wsValue = window.WebSocket;
  });

  afterEach(function () {
    window.WebSocket = this.wsValue;
  });

  it('should be a function', function () {
    var wrench = new SocketWrench(this.defaults);
    expect(typeof wrench.isReady).toBe('function');
  });

  it('returns false when the socket does not exist', function () {
    window.WebSocket = null;
    var wrench = new SocketWrench(this.defaults);
    expect(wrench.isReady()).toBe(false);
  });

  it('returns false when the socket is not ready', function () {
    var wrench = new SocketWrench(this.defaults);
    expect(wrench.isReady()).toBe(false);
  });

 it('returns true when the socket is ready', function (done) {
   var wrench = new SocketWrench(this.defaults);
   wrench.open();

   wrench.on('ready', function () {
     expect(wrench.isReady()).toBe(true);
     done();
   });
 });
});