text:
package typegraph

import (
	"fmt"
	"strconv"
	"strings"

	"github.com/serulian/compiler/compilercommon"
	"github.com/serulian/compiler/compilergraph"
	"github.com/serulian/compiler/graphs/typegraph/proto"
)

// MemberSignatureKind defines the various kinds of members, for calculating signatures
// for interface comparisons.
type MemberSignatureKind int

const (
	CustomMemberSignature MemberSignatureKind = iota

	ConstructorMemberSignature
	FunctionMemberSignature
	PropertyMemberSignature
	OperatorMemberSignature
	FieldMemberSignature

	NativeConstructorMemberSignature
	NativeFunctionMemberSignature
	NativeOperatorMemberSignature
	NativePropertyMemberSignature
)

// operatorMemberNamePrefix defines a unicode character for prefixing the "member name" of operators. Allows
// for easier comparison of all members under a type.
var operatorMemberNamePrefix = "•"

// TypeGraphConstructor defines an interface that is implemented by various source graphs (SRG, IRG)
// for translating their parsed form into type graph information.
type TypeGraphConstructor interface {
	// Defines the modules exported by the source graph.
	DefineModules(builder GetModuleBuilder)

	// Defines the types exported by the source graph (including generics).
	DefineTypes(builder GetTypeBuilder)

	// Defines the constraints on generics, inheritance, and other type-dependent info.
	DefineDependencies(annotator Annotator, graph *TypeGraph)

	// Defines the members under the modules and types.
	DefineMembers(builder GetMemberBuilder, reporter IssueReporter, graph *TypeGraph)

	// Decorates all members with their generics and other attributes. Occurs as a second step after
	// DefineMembers to ensure member-level generics are available for resolution.
	DecorateMembers(decorator GetMemberDecorator, reporter IssueReporter, graph *TypeGraph)

	// Performs final validation of the type graph after full definition.
	Validate(reporter IssueReporter, graph *TypeGraph)

	// GetRanges returns the range information for the given source node in the source graph,
	// if any.
	GetRanges(sourceNodeID compilergraph.GraphNodeId) []compilercommon.SourceRange
}

type GetModuleBuilder func() *moduleBuilder
type GetTypeBuilder func(moduleSourceNode compilergraph.GraphNode) *typeBuilder
type GetMemberBuilder func(moduleOrTypeSourceNode compilergraph.GraphNode, isOperator bool) *MemberBuilder
type GetMemberDecorator func(memberSourceNode compilergraph.GraphNode) *MemberDecorator

type getGenericBuilder func() *genericBuilder

// IssueReporter ////////////////////////////////////////////////////////////////////////////////

// IssueReporter defines a helper type for reporting issues on source nodes translated into the type graph.
type IssueReporter interface {
	ReportError(sourceNode compilergraph.GraphNode, message string, params ...interface{})
}

type issueReporterImpl struct {
	tdg      *TypeGraph                       // The underlying type graph.
	modifier compilergraph.GraphLayerModifier // The modifier being used.
}

// ReportError adds an error to the type graph, starting from the given source node.
func (ir issueReporterImpl) ReportError(sourceNode compilergraph.GraphNode, message string, params ...interface{}) {
	issueNode := ir.modifier.CreateNode(NodeTypeReportedIssue)
	issueNode.Connect(NodePredicateSource, sourceNode)
	ir.tdg.decorateWithError(issueNode, message, params...)
}

// Annotator ////////////////////////////////////////////////////////////////////////////////////

// Annotator defines a helper type for annotating various constraints in the type graph such as
// generic constraints, inheritance, etc.
type Annotator struct {
	issueReporterImpl
}

// DefineGenericConstraint defines the constraint on a type or type member generic to be that specified.
func (an Annotator) DefineGenericConstraint(genericSourceNode compilergraph.GraphNode, constraint TypeReference) {
	genericNode, ok := an.tdg.tryGetMatchingTypeGraphNode(genericSourceNode)
	if !ok {
		return
	}
	an.modifier.Modify(genericNode).DecorateWithTagged(NodePredicateGenericSubtype, constraint)
}

// DefinePrincipalType defines the principal type that this agent accepts.
func (an Annotator) DefinePrincipalType(typeSourceNode compilergraph.GraphNode, principal TypeReference) {
	typeNode, ok := an.tdg.tryGetMatchingTypeGraphNode(typeSourceNode)
	if !ok {
		return
	}
	if typeNode.Kind() != NodeTypeAgent {
		panic("Cannot set principal on non-agent type")
	}

	an.modifier.Modify(typeNode).DecorateWithTagged(NodePredicatePrincipalType, principal)
}

// DefineParentType defines that the given type inherits from the given parent type ref. For external interfaces, the
// parent is inherited and for nominal types, it describes conversion. Inheritance should only be used by legacy code
// and never for SRG-based types: Agency composition should be used instead.
func (an Annotator) DefineParentType(typeSourceNode compilergraph.GraphNode, inherits TypeReference) {
	typeNode, ok := an.tdg.tryGetMatchingTypeGraphNode(typeSourceNode)
	if !ok {
		return
	}
	typeKind := typeNode.Kind()

	if typeKind != NodeTypeExternalInterface && typeKind != NodeTypeNominalType {
		panic("Cannot set parent on non-nominal and non-external interface type")
	}

	an.modifier.Modify(typeNode).DecorateWithTagged(NodePredicateParentType, inherits)
}

// DefineAgencyComposition defines that the type being constructed composes an agent of the given type,
// with the given name. Agency composition is a type-safe form of composition with automatic back reference
// to the composing type within the agent.
func (an Annotator) DefineAgencyComposition(typeSourceNode compilergraph.GraphNode, agentType TypeReference, compositionName string) {
	typeNode, ok := an.tdg.tryGetMatchingTypeGraphNode(typeSourceNode)
	if !ok {
		return
	}

	typeKind := typeNode.Kind()

	if typeKind != NodeTypeClass && typeKind != NodeTypeAgent {
		panic("Cannot agency compose on non-class and non-agent type")
	}

	agentReference := an.modifier.CreateNode(NodeTypeAgentReference)
	agentReference.DecorateWithTagged(NodePredicateAgentType, agentType)
	agentReference.Decorate(NodePredicateAgentCompositionName, compositionName)
	an.modifier.Modify(typeNode).Connect(NodePredicateComposedAgent, agentReference)
}

// DefineAliasedType defines that the given type aliases the other type. Only applies to aliases.
func (an Annotator) DefineAliasedType(typeSourceNode compilergraph.GraphNode, aliased TGTypeDecl) {
	aliased.TypeKind() // Will panic if not a valid type.

	typeNode, ok := an.tdg.tryGetMatchingTypeGraphNode(typeSourceNode)
	if !ok {
		return
	}

	if typeNode.Kind() != NodeTypeAlias {
		panic("Cannot alias a non-alias type declaration")
	}

	an.modifier.Modify(typeNode).Connect(NodePredicateAliasedType, aliased.GraphNode)
}

// moduleBuilder ////////////////////////////////////////////////////////////////////////////////////

// moduleBuilder defines a helper type for easy construction of module definitions in the type graph.
type moduleBuilder struct {
	tdg        *TypeGraph                       // The underlying type graph.
	modifier   compilergraph.GraphLayerModifier // The modifier being used for the construction.
	name       string                           // The name of the module.
	path       string                           // The defined path for the module.
	sourceNode compilergraph.GraphNode          // The node for the module in the source graph.
}

// Name sets the name of the module.
func (mb *moduleBuilder) Name(name string) *moduleBuilder {
	mb.name = name
	return mb
}

// Path sets the global path of the module. Used for visibility resolution.
func (mb *moduleBuilder) Path(path string) *moduleBuilder {
	mb.path = path
	return mb
}

// SourceNode sets the source node for the module in the source graph.
func (mb *moduleBuilder) SourceNode(sourceNode compilergraph.GraphNode) *moduleBuilder {
	mb.sourceNode = sourceNode
	return mb
}

// Define defines the module in the type graph.
func (mb *moduleBuilder) Define() {
	if mb.name == "" {
		panic("Missing name on defined module")
	}

	if mb.path == "" {
		panic("Missing path on defined module")
	}

	if string(mb.sourceNode.NodeId) == "" {
		panic(fmt.Sprintf("Missing source node on defined module %v", mb.name))
	}

	moduleNode := mb.modifier.CreateNode(NodeTypeModule)
	moduleNode.Connect(NodePredicateSource, mb.sourceNode)
	moduleNode.Decorate(NodePredicateModuleName, mb.name)
	moduleNode.Decorate(NodePredicateModulePath, mb.path)
}

// typeBuilder ////////////////////////////////////////////////////////////////////////////////////

// typeBuilder defines a helper type for easy construction of type definitions in the type graph.
type typeBuilder struct {
	modifier      compilergraph.GraphLayerModifier // The modifier being used.
	module        TGModule                         // The parent module.
	name          string                           // The name of the type.
	exported      bool                             // Whether the type is exported publicly.
	globalId      string                           // The global ID of the type.
	globalAlias   string                           // The global alias of the type.
	sourceNode    compilergraph.GraphNode          // The node for the type in the source graph.
	typeKind      TypeKind                         // The kind of this type.
	attributes    []TypeAttribute                  // The custom attributes on the type, if any.
	documentation string                           // The documentation string for the type, if any.
}

// GlobalId sets the global ID of the type. This ID must be unique. For types that are
// engine-native, this must be the name found in the context when the code is running.
func (tb *typeBuilder) GlobalId(globalId string) *typeBuilder {
	tb.globalId = globalId
	return tb
}

// Exported sets whether the type is exported publicly.
func (tb *typeBuilder) Exported(exported bool) *typeBuilder {
	tb.exported = exported
	return tb
}

// Name sets the name of the type.
func (tb *typeBuilder) Name(name string) *typeBuilder {
	tb.name = name
	return tb
}

// Documentation sets the documentation of the type.
func (tb *typeBuilder) Documentation(documentation string) *typeBuilder {
	tb.documentation = documentation
	return tb
}

// WithAttribute adds the attribute with the given name to the type.
func (tb *typeBuilder) WithAttribute(name TypeAttribute) *typeBuilder {
	tb.attributes = append(tb.attributes, name)
	return tb
}

// GlobalAlias sets the global alias of the type.
func (tb *typeBuilder) GlobalAlias(globalAlias string) *typeBuilder {
	tb.globalAlias = globalAlias
	return tb
}

// TypeKind sets the kind of this type in the type graph.
func (tb *typeBuilder) TypeKind(typeKind TypeKind) *typeBuilder {
	tb.typeKind = typeKind
	return tb
}

// SourceNode sets the source node for the type in the source graph.
func (tb *typeBuilder) SourceNode(sourceNode compilergraph.GraphNode) *typeBuilder {
	tb.sourceNode = sourceNode
	return tb
}

// Define defines the type in the type graph.
func (tb *typeBuilder) Define() getGenericBuilder {
	if tb.name == "" {
		panic("Missing name on defined type")
	}

	if tb.globalId == "" {
		panic("Missing global ID on defined type")
	}

	if string(tb.sourceNode.NodeId) == "" {
		panic(fmt.Sprintf("Missing source node on defined type %v", tb.name))
	}

	// Create the type node.
	typeNode := tb.modifier.CreateNode(getTypeNodeType(tb.typeKind))
	typeNode.Connect(NodePredicateTypeModule, tb.module.GraphNode)
	typeNode.Connect(NodePredicateSource, tb.sourceNode)
	typeNode.Decorate(NodePredicateTypeName, tb.name)
	typeNode.Decorate(NodePredicateTypeGlobalId, tb.globalId)
	typeNode.Decorate(NodePredicateModulePath, tb.module.Get(NodePredicateModulePath))

	if tb.documentation != "" {
		typeNode.Decorate(NodePredicateDocumentation, tb.documentation)
	}

	if tb.exported {
		typeNode.Decorate(NodePredicateTypeExported, "true")
	}

	if tb.globalAlias != "" {
		typeNode.Decorate(NodePredicateTypeGlobalAlias, tb.globalAlias)

		if tb.typeKind == AliasType {
			panic("Aliases cannot themselves be aliased")
		}
	}

	for _, attribute := range tb.attributes {
		if tb.typeKind == AliasType {
			panic("Aliases cannot have attributes")
		}

		attrNode := tb.modifier.CreateNode(NodeTypeAttribute)
		attrNode.Decorate(NodePredicateAttributeName, string(attribute))
		typeNode.Connect(NodePredicateTypeAttribute, attrNode)
	}

	var genericIndex = -1

	return func() *genericBuilder {
		genericIndex = genericIndex + 1
		return &genericBuilder{
			modifier:        tb.modifier,
			tdg:             tb.module.tdg,
			parentNode:      typeNode,
			genericKind:     typeDeclGeneric,
			index:           genericIndex,
			parentPredicate: NodePredicateTypeGeneric,
		}
	}
}

// getTypeNodeType returns the NodeType for creating type graph nodes for an SRG type declaration.
func getTypeNodeType(kind TypeKind) NodeType {
	switch kind {
	case ClassType:
		return NodeTypeClass

	case ImplicitInterfaceType:
		return NodeTypeInterface

	case ExternalInternalType:
		return NodeTypeExternalInterface

	case NominalType:
		return NodeTypeNominalType

	case StructType:
		return NodeTypeStruct

	case AgentType:
		return NodeTypeAgent

	case AliasType:
		return NodeTypeAlias

	default:
		panic(fmt.Sprintf("Unknown kind of type declaration: %v", kind))
	}
}

// genericBuilder ////////////////////////////////////////////////////////////////////////////////////

type genericKind int

const (
	typeDeclGeneric genericKind = iota
	typeMemberGeneric
)

// genericBuilder defines a helper type for easy construction of generic definitions on types or type members.
type genericBuilder struct {
	modifier        compilergraph.GraphLayerModifier  // The parent modifier.
	tdg             *TypeGraph                        // The underlying type graph.
	parentNode      compilergraph.ModifiableGraphNode // The parent type or member node.
	genericKind     genericKind                       // The kind of generic being built.
	index           int                               // The 0-based index of the generic under the type or member.
	parentPredicate compilergraph.Predicate           // The predicate for connecting the type or member to the generic.

	name          string                  // The name of the generic.
	documentation string                  // The documentation for the generic.
	sourceNode    compilergraph.GraphNode // The node for the generic in the source graph.
	hasSourceNode bool                    // Whether this generic has a source node.
}

// Name sets the name of the generic.
func (gb *genericBuilder) Name(name string) *genericBuilder {
	gb.name = name
	return gb
}

// Documentation sets the documentation for the generic.
func (gb *genericBuilder) Documentation(documentation string) *genericBuilder {
	gb.documentation = documentation
	return gb
}

// SourceNode sets the source node for the generic in the source graph.
func (gb *genericBuilder) SourceNode(sourceNode compilergraph.GraphNode) *genericBuilder {
	gb.sourceNode = sourceNode
	gb.hasSourceNode = true
	return gb
}

// Define defines the generic in the type graph.
func (gb *genericBuilder) Define() {
	gb.defineGeneric()
}

func (gb *genericBuilder) defineGeneric() TGGeneric {
	if gb.name == "" {
		panic("Missing name on defined generic")
	}

	if gb.hasSourceNode && string(gb.sourceNode.NodeId) == "" {
		panic(fmt.Sprintf("Missing source node on defined generic %v", gb.name))
	}

	// Create the generic node.
	genericNode := gb.modifier.CreateNode(NodeTypeGeneric)
	genericNode.Decorate(NodePredicateGenericName, gb.name)
	genericNode.Decorate(NodePredicateGenericIndex, strconv.Itoa(gb.index))
	genericNode.Decorate(NodePredicateGenericKind, strconv.Itoa(int(gb.genericKind)))

	if gb.hasSourceNode {
		genericNode.Connect(NodePredicateSource, gb.sourceNode)
	}

	if len(gb.documentation) > 0 {
		genericNode.Decorate(NodePredicateDocumentation, gb.documentation)
	}

	// Add the generic to the parent node.
	gb.parentNode.Connect(gb.parentPredicate, genericNode)

	return TGGeneric{genericNode.AsNode(), gb.tdg}
}

// MemberBuilder ////////////////////////////////////////////////////////////////////////////////////

// MemberBuilder defines a helper type for easy construction of module and type members.
type MemberBuilder struct {
	modifier         compilergraph.GraphLayerModifier // The modifier being used.
	tdg              *TypeGraph                       // The underlying type graph.
	parent           TGTypeOrModule                   // The parent type or module node.
	isOperator       bool                             // Whether the member being defined is an operator.
	name             string                           // The name of the member.
	sourceNode       compilergraph.GraphNode          // The node for the member in the source graph.
	hasSourceNode    bool                             // Whether there is a source node.
	memberGenerics   []memberGeneric                  // The generics on the member.
	memberParameters []memberParameter                // The parameters on the member.
	documentation    string                           // The documentation string for the member, if any.
}

// memberGeneric holds information about a member's generic.
type memberGeneric struct {
	name          string
	documentation string
	sourceNode    compilergraph.GraphNode
	hasSourceNode bool
}

// memberParameter holds information about a member's parameter.
type memberParameter struct {
	name          string
	documentation string
	sourceNode    compilergraph.GraphNode
	hasSourceNode bool
}

// Name sets the name of the member.
func (mb *MemberBuilder) Name(name string) *MemberBuilder {
	mb.name = name
	return mb
}

// Documentation sets the documentation of the member.
func (mb *MemberBuilder) Documentation(documentation string) *MemberBuilder {
	mb.documentation = documentation
	return mb
}

// SourceNode sets the source node for the member in the source graph.
func (mb *MemberBuilder) SourceNode(sourceNode compilergraph.GraphNode) *MemberBuilder {
	mb.sourceNode = sourceNode
	mb.hasSourceNode = true
	return mb
}

// WithGeneric adds a generic to this member.
func (mb *MemberBuilder) WithGeneric(name string, documentation string, sourceNode compilergraph.GraphNode) *MemberBuilder {
	mb.memberGenerics = append(mb.memberGenerics, memberGeneric{
		name, documentation, sourceNode, true,
	})

	return mb
}

// withGeneric adds a generic to this member.
func (mb *MemberBuilder) withGeneric(name string) *MemberBuilder {
	mb.memberGenerics = append(mb.memberGenerics, memberGeneric{
		name, "", compilergraph.GraphNode{}, false,
	})

	return mb
}

// WithParameter adds a parameter to this member.
func (mb *MemberBuilder) WithParameter(name string, documentation string, sourceNode compilergraph.GraphNode) *MemberBuilder {
	mb.memberParameters = append(mb.memberParameters, memberParameter{
		name, documentation, sourceNode, true,
	})

	return mb
}

// Define defines the member under the type or module in the type graph.
func (mb *MemberBuilder) Define() TGMember {
	var name = mb.name
	if mb.isOperator {
		// Normalize the name by lowercasing it.
		name = strings.ToLower(mb.name)
	}

	// Create the member node.
	var memberNode compilergraph.ModifiableGraphNode
	if mb.isOperator {
		memberNode = mb.modifier.CreateNode(NodeTypeOperator)
		memberNode.Decorate(NodePredicateOperatorName, name)
		memberNode.Decorate(NodePredicateMemberName, operatorMemberNamePrefix+name)
	} else {
		memberNode = mb.modifier.CreateNode(NodeTypeMember)
		memberNode.Decorate(NodePredicateMemberName, name)
	}

	if mb.hasSourceNode {
		memberNode.Connect(NodePredicateSource, mb.sourceNode)
	}

	if mb.documentation != "" {
		memberNode.Decorate(NodePredicateDocumentation, mb.documentation)
	}

	memberNode.Decorate(NodePredicateModulePath, mb.parent.ParentModule().Get(NodePredicateModulePath))

	// Decorate the member with its generics.
	for index, genericInfo := range mb.memberGenerics {
		genericBuilder := genericBuilder{
			modifier:        mb.modifier,
			tdg:             mb.tdg,
			parentNode:      memberNode,
			genericKind:     typeMemberGeneric,
			index:           index,
			parentPredicate: NodePredicateMemberGeneric,
		}

		genericBuilder.Name(genericInfo.name)
		if genericInfo.hasSourceNode {
			genericBuilder.SourceNode(genericInfo.sourceNode)
		}
		genericBuilder.Documentation(genericInfo.documentation)
		genericBuilder.defineGeneric()
	}

	// Decorate the member with its parameters.
	for _, parameterInfo := range mb.memberParameters {
		// Create the parameter node.
		parameterNode := mb.modifier.CreateNode(NodeTypeParameter)
		parameterNode.Decorate(NodePredicateParameterName, parameterInfo.name)

		if parameterInfo.hasSourceNode {
			parameterNode.Connect(NodePredicateSource, parameterInfo.sourceNode)
		}

		if len(parameterInfo.documentation) > 0 {
			parameterNode.Decorate(NodePredicateParameterDocumentation, parameterInfo.documentation)
		}

		// Add the parameter to the member node.
		memberNode.Connect(NodePredicateMemberParameter, parameterNode)
	}

	// Add the member to the parent node.
	parentNode := mb.modifier.Modify(mb.parent.Node())

	if mb.isOperator {
		parentNode.Connect(NodePredicateTypeOperator, memberNode)
	} else {
		parentNode.Connect(NodePredicateMember, memberNode)
	}

	return TGMember{memberNode.AsNode(), mb.tdg}
}

// MemberDecorator ////////////////////////////////////////////////////////////////////////////////////

// MemberDecorator defines a helper type for easy annotation of module and type members's dependent
// information.
type MemberDecorator struct {
	modifier   compilergraph.GraphLayerModifier // The modifier being used.
	tdg        *TypeGraph                       // The parent type graph.
	sourceNode compilergraph.GraphNode          // The node for the generic in the source graph.
	member     TGMember                         // The member being decorated.
	memberName string                           // The name of the member.

	issueReporter IssueReporter // The underlying issue reporter.

	promising MemberPromisingOption // Whether the member is promising.

	exported     bool // Whether the member is exported publicly.
	readonly     bool // Whether the member is readonly.
	static       bool // Whether the member is static.
	implicit     bool // Whether the member is implicitly called.
	native       bool // Whether this operator is native to ES.
	hasdefault   bool // Whether the member has a default value.
	field        bool // Whether the member is a field holding data.
	invokesasync bool // Whether the member invokes an async worker.

	skipOperatorChecking bool // Whether to skip operator checking.

	memberType TypeReference // The defined type of the member.

	signatureType    TypeReference // The defined signature type.
	hasSignatureType bool          // Whether there is a custom signature type.

	memberKind MemberSignatureKind // The kind of the member.

	genericConstraints map[compilergraph.GraphNode]TypeReference // The defined generic constraints.
	memberIssues       []string                                  // Issues added on the member source node.
	returnables        []memberReturnable                        // The defined returnables.
	tags               map[string]string                         // The defined member tags.
}

// memberReturnable holds information about a returnable under a member.
type memberReturnable struct {
	sourceNode compilergraph.GraphNode
	returnType TypeReference
}

// isOperator returns whether the member being decorated is an operator.
func (mb *MemberDecorator) isOperator() bool {
	return mb.member.IsOperator()
}

// WithTag adds a tag onto the member.
func (mb *MemberDecorator) WithTag(name string, value string) *MemberDecorator {
	mb.tags[name] = value
	return mb
}

// SkipOperatorChecking sets whether to skip operator checking for native operators.
func (mb *MemberDecorator) SkipOperatorChecking(skip bool) *MemberDecorator {
	if !mb.isOperator() {
		panic("SkipOperatorChecking can only be called for operators")
	}

	if !mb.native {
		panic("SkipOperatorChecking can only be called for native operators")
	}

	mb.skipOperatorChecking = skip
	return mb
}

// Native sets whether the member is native.
func (mb *MemberDecorator) Native(native bool) *MemberDecorator {
	if !mb.isOperator() {
		panic("Native can only be called for operators")
	}

	mb.native = native
	return mb
}

// HasDefaultValue sets whether the member has a default value.
func (mb *MemberDecorator) HasDefaultValue(hasdefault bool) *MemberDecorator {
	mb.hasdefault = hasdefault
	return mb
}

// ImplicitlyCalled sets whether the member is implicitly called on access or assignment.
func (mb *MemberDecorator) ImplicitlyCalled(implicit bool) *MemberDecorator {
	mb.implicit = implicit
	return mb
}

// Exported sets whether the member is exported publicly.
func (mb *MemberDecorator) Exported(exported bool) *MemberDecorator {
	mb.exported = exported
	return mb
}

// ReadOnly sets whether the member is read only.
func (mb *MemberDecorator) ReadOnly(readonly bool) *MemberDecorator {
	mb.readonly = readonly
	return mb
}

// InvokesAsync sets whether the member invokes asynchronously.
func (mb *MemberDecorator) InvokesAsync(invokesasync bool) *MemberDecorator {
	mb.invokesasync = invokesasync
	return mb
}

// Field sets whether the member is a field.
func (mb *MemberDecorator) Field(field bool) *MemberDecorator {
	mb.field = field
	return mb
}

// Static sets whether the member is static.
func (mb *MemberDecorator) Static(static bool) *MemberDecorator {
	mb.static = static
	return mb
}

// Promising sets whether the member is promising.
func (mb *MemberDecorator) Promising(promising MemberPromisingOption) *MemberDecorator {
	mb.promising = promising
	return mb
}

// MemberType sets the type of the member, as well as the signature type. Call SignatureType
// to override.
func (mb *MemberDecorator) MemberType(memberType TypeReference) *MemberDecorator {
	mb.memberType = memberType

	if !mb.hasSignatureType {
		mb.signatureType = memberType
	}

	return mb
}

// SignatureType sets the type of the member for interface signature calculation.
func (mb *MemberDecorator) SignatureType(signatureType TypeReference) *MemberDecorator {
	mb.signatureType = signatureType
	mb.hasSignatureType = true
	return mb
}

// MemberKind sets the kind of the member. Used for signature calculation.
func (mb *MemberDecorator) MemberKind(memberKind MemberSignatureKind) *MemberDecorator {
	mb.memberKind = memberKind
	return mb
}

// CreateReturnable adds a returnable definition to the type graph, indicating that the given source node returns
// a value of the given type.
func (mb *MemberDecorator) CreateReturnable(sourceNode compilergraph.GraphNode, returnType TypeReference) *MemberDecorator {
	mb.returnables = append(mb.returnables, memberReturnable{
		sourceNode, returnType,
	})
	return mb
}

// DefineParameterType defines the type of the parameter specified.
func (mb *MemberDecorator) DefineParameterType(parameterSourceNode compilergraph.GraphNode, parameterType TypeReference) {
	parameterNode, ok := mb.tdg.tryGetMatchingTypeGraphNode(parameterSourceNode)
	if !ok {
		return
	}
	mb.modifier.Modify(parameterNode).DecorateWithTagged(NodePredicateParameterType, parameterType)
}

// DefineGenericConstraint defines the constraint on the type member generic to be that specified.
func (mb *MemberDecorator) DefineGenericConstraint(genericSourceNode compilergraph.GraphNode, constraint TypeReference) {
	genericNode, ok := mb.tdg.tryGetMatchingTypeGraphNode(genericSourceNode)
	if !ok {
		return
	}
	mb.defineGenericConstraint(genericNode, constraint)
}

// defineGenericConstraint defines the constraint on the type member generic to be that specified.
func (mb *MemberDecorator) defineGenericConstraint(genericNode compilergraph.GraphNode, constraint TypeReference) *MemberDecorator {
	mb.genericConstraints[genericNode] = constraint
	mb.modifier.Modify(genericNode).DecorateWithTagged(NodePredicateGenericSubtype, constraint)
	return mb
}

// Decorate completes the decoration of the member.
func (mb *MemberDecorator) Decorate() {
	memberNode := mb.modifier.Modify(mb.member.GraphNode)

	// If this is an operator, type check and compute member type.
	if mb.isOperator() {
		mb.checkAndComputeOperator(memberNode, mb.member.Name())
	} else {
		// Decorate the member with its type.
		memberNode.DecorateWithTagged(NodePredicateMemberType, mb.memberType)

		// Decorate the member with its signature.
		mb.decorateWithSig(mb.signatureType, mb.member.Generics()...)
	}

	if mb.promising != MemberNotPromising {
		memberNode.DecorateWith(NodePredicateMemberPromising, int(mb.promising))
	}

	if mb.exported {
		memberNode.Decorate(NodePredicateMemberExported, "true")
	}

	if mb.static {
		memberNode.Decorate(NodePredicateMemberStatic, "true")
	}

	if mb.readonly {
		memberNode.Decorate(NodePredicateMemberReadOnly, "true")
	}

	if mb.hasdefault {
		memberNode.Decorate(NodePredicateMemberHasDefaultValue, "true")
	}

	if mb.field {
		memberNode.Decorate(NodePredicateMemberField, "true")
	}

	if mb.implicit {
		memberNode.Decorate(NodePredicateMemberImplicitlyCalled, "true")
	}

	if mb.native {
		memberNode.Decorate(NodePredicateOperatorNative, "true")
	}

	if mb.invokesasync {
		memberNode.Decorate(NodePredicateMemberInvokesAsync, "true")
	}

	// Add the tags to the member (if any).
	for name, value := range mb.tags {
		tagNode := mb.modifier.CreateNode(NodeTypeMemberTag)
		tagNode.Decorate(NodePredicateMemberTagName, name)
		tagNode.Decorate(NodePredicateMemberTagValue, value)

		memberNode.Connect(NodePredicateMemberTag, tagNode)
	}

	// Add the returnables to the member (if any).
	for _, returnableInfo := range mb.returnables {
		returnNode := mb.modifier.CreateNode(NodeTypeReturnable)
		returnNode.Connect(NodePredicateSource, returnableInfo.sourceNode)
		returnNode.DecorateWithTagged(NodePredicateReturnType, returnableInfo.returnType)

		memberNode.Connect(NodePredicateReturnable, returnNode)
	}
}

// parent returns the parent type or module.
func (mb *MemberDecorator) parent() TGTypeOrModule {
	return mb.member.Parent()
}

// checkAndComputeOperator handles specialized logic for operator members.
func (mb *MemberDecorator) checkAndComputeOperator(memberNode compilergraph.ModifiableGraphNode, name string) {
	name = strings.ToLower(name)

	// Verify that the operator matches a known operator.
	definition, ok := mb.tdg.operators[name]
	if !ok {
		mb.tdg.decorateWithError(memberNode, "Unknown operator '%s' defined on type '%s'", name, mb.parent().Name())
		return
	}

	// Some operators are static and some are assignable.
	mb.static = definition.IsStatic
	mb.readonly = !definition.IsAssignable

	// Ensure that the declared return type is equal to that expected.
	asType, _ := mb.parent().AsType()

	declaredReturnType := mb.memberType.Generics()[0]
	containingType := asType.GetTypeReference()
	expectedReturnType := definition.ExpectedReturnType(containingType)

	if !mb.skipOperatorChecking {
		if !expectedReturnType.IsAny() && !declaredReturnType.IsAny() && declaredReturnType != expectedReturnType {
			mb.tdg.decorateWithError(memberNode, "Operator '%s' defined on type '%s' expects a return type of '%v'; found %v",
				name, mb.parent().Name(), expectedReturnType, declaredReturnType)
			return
		}
	}

	// Decorate the operator with its return type.
	var actualReturnType = expectedReturnType
	if expectedReturnType.IsAny() {
		actualReturnType = declaredReturnType
	}

	mb.CreateReturnable(mb.sourceNode, actualReturnType)

	// Ensure we have the expected number of parameters.
	parametersExpected := definition.Parameters
	if !mb.skipOperatorChecking {
		if mb.memberType.ParameterCount() != len(parametersExpected) {
			mb.tdg.decorateWithError(memberNode, "Operator '%s' defined on type '%s' expects %v parameters; found %v",
				name, mb.parent().Name(), len(parametersExpected), mb.memberType.ParameterCount())
			return
		}
	}

	var memberType = mb.tdg.NewTypeReference(mb.tdg.FunctionType(), actualReturnType)

	// Ensure the parameters expected on the operator match those specified.
	parameterTypes := mb.memberType.Parameters()
	for index, parameterType := range parameterTypes {
		if !mb.skipOperatorChecking {
			expectedType := parametersExpected[index].ExpectedType(containingType)
			if !expectedType.IsAny() && expectedType != parameterType {
				mb.tdg.decorateWithError(memberNode, "Parameter '%s' (#%v) for operator '%s' defined on type '%s' expects type %v; found %v",
					parametersExpected[index].Name, index, name, mb.parent().Name(),
					expectedType, parameterType)
			}
		}

		memberType = memberType.WithParameter(parameterType)
	}

	// Decorate the member with its type.
	memberNode.DecorateWithTagged(NodePredicateMemberType, memberType)

	// Decorate the member with its signature.
	if definition.IsStatic {
		mb.decorateWithSig(mb.tdg.AnyTypeReference())
	} else {
		mb.decorateWithSig(memberType)
	}
}

// decorateWithSig decorates the given member node with a unique signature for fast subtype checking.
func (mb *MemberDecorator) decorateWithSig(sigMemberType TypeReference, generics ...TGGeneric) {
	// Build type reference value strings for the member type and any generic constraints (which
	// handles generic count as well). The call to Localize replaces the type node IDs in the
	// type references with a local ID (#1, #2, etc), to allow for positional comparison between
	// different member signatures.
	memberTypeStr := sigMemberType.Localize(generics...).Value()
	constraintStr := make([]string, len(generics))
	for index, generic := range generics {
		genericConstraint := mb.genericConstraints[generic.GraphNode]
		constraintStr[index] = genericConstraint.Localize(generics...).Value()
	}

	isWritable := !mb.readonly
	name := strings.ToLower(mb.memberName)
	memberKind := uint64(mb.memberKind)

	signature := &proto.MemberSig{
		MemberName:         name,
		MemberKind:         memberKind,
		IsExported:         mb.exported,
		IsWritable:         isWritable,
		MemberType:         memberTypeStr,
		GenericConstraints: constraintStr,
	}

	mb.modifier.Modify(mb.member.GraphNode).DecorateWithTagged(NodePredicateMemberSignature, signature)
}

// Other stuff ////////////////////////////////////////////////////////////////////////////////////

// decorateWithError decorates the given node with an associated error node.
func (t *TypeGraph) decorateWithError(node compilergraph.ModifiableGraphNode, message string, args ...interface{}) {
	errorNode := node.Modifier().CreateNode(NodeTypeError)
	errorNode.Decorate(NodePredicateErrorMessage, fmt.Sprintf(message, args...))
	node.Connect(NodePredicateError, errorNode)
}


text:
int
main(int argc, char* argv[])
{
    // Read it back in.
    spec_info* info1 = read_spec_info("spec.info");

    // Print the roundtripped object
    printf("\n\n\tinfo1\n\n");
    print_spec_info(info1);

    // Write it out again.
    //write_spec_info(info1, "spec2.info");

    return 0;
}

redpajama_set_name: RedPajamaGithub


text:
#ifndef BTEN_BOX_MORE_ANCHORS_H
#define BTEN_BOX_MORE_ANCHORS_H

/**
 * @file tgBoxMoreAnchorsInfo.h
 * @brief Class that interfaces with Bullet to build the boxes, specifically for boxes that support more than 2 anchor points.
 * @author Drew Sabelhaus
 * @date September 2016
 * $Id$
 */

// This library
#include "tgPairs.h"
//#include "tgRigidInfo.h"
#include "tgBoxInfo.h"
// The NTRT Core Library
#include "tgUtil.h"
//#include "core/tgBox.h"
#include "core/tgBoxMoreAnchors.h"

// The Bullet Physics library
#include "btBulletDynamicsCommon.h"

class btVector3;

// @todo: Need to take tags into account...

/**
 * Implementation of a box shape as defined by a 'from' point and a 'to'
 * point. It also has length, width and density.
 * This 'info' class will also detect and add nodes that are along the outside
 * edge of the box (as of 2016-08-31, actually adds nodes on or INSIDE the box,
 * which is not the behavior we want, but is good enough for the ForcePlateModel
 *
 * NOTE THAT THIS CLASS DOES NOT WORK WELL AT THE MOMENT.
 *     A discussion on the limitations of NTRT's creation of boxes
 *     is present in tgBoxMoreAnchors.cpp, but briefly: since NTRTsim does not
 *     specify an orientation for a box, the width and height directions currently
 *     are chosen ARBITRARILY by the underlying Bullet Physics methods. As a result,
 *     this class will sometimes break for no reason. That would occur if Bullet
 *     chooses which parameter is width and which is height in a different way
 *     than is assumed here. To fix this, we'd want to change how boxes are
 *     specified, but that means changing tgBox, which may affect other code...
 */
class tgBoxMoreAnchorsInfo : public tgBoxInfo {
public:

    /**
     * Construct a tgBoxMoreAnchorsInfo with just a config.
     * The pair must be filled in
     * later, or factory methods can be used to create instances with
     * pairs.
     * note that this class is using the config from tgBox since that's easier.
     * A bit messy, but works for now.
     */
    tgBoxMoreAnchorsInfo(const tgBox::Config& config);

    /**
     * Construct a tgBoxMoreAnchorsInfo with just a config and tags. The pair must
     * be filled in later, or factory methods can be used to create instances
     * with pairs.
     */
    tgBoxMoreAnchorsInfo(const tgBox::Config& config, tgTags tags);

    /**
     * Construct a tgBoxMoreAnchorsInfo from its endpoints, radius and density.
     * @param[in] from one endpoint
     * @param[in] to the other endpoint
     * @param[in] config contains the radius and density
     * @todo: make sure that tgPairs returns references to the vectors...
     */
    tgBoxMoreAnchorsInfo(const tgBox::Config& config, const tgPair& pair);

    /**
     * Construct a tgBoxInfo from its endpoints, radius and density.
     * @param[in] from one endpoint
     * @param[in] to the other endpoint
     * @param[in] config contains the radius and density
     * @todo: make sure that tgPairs returns references to the vectors...
     */
    tgBoxMoreAnchorsInfo(const tgBox::Config& config, tgTags tags,
			 const tgPair& pair);

    /**
     * World will destroy the rigid body
     */
    virtual ~tgBoxMoreAnchorsInfo() {}

    /**
     * Create a tgRigidInfo* from a tgPair.
     * Needs to be re-declared and re-defined in this class so that
     * a tgBoxMoreAnchorsInfo will be returned, not a tgBoxInfo.
     */
    tgRigidInfo* createRigidInfo(const tgPair& pair);

    /**
     * This method needs to be re-defined to create a tgBoxMoreAnchors instead
     * of just a tgBox.
     */
    virtual tgModel* createModel(tgWorld& world);

    /**
     * The following three functions are part of tgBoxInfo.
     * This just makes it so that tgBoxMoreAnchorsInfo does not own the pair.
     * But that's fine. In the implementation of tgBoxMoreAnchorsInfo, we'll just
     * call these functions instead of addressing m_pair directly.
     * So, these are listed here for your reference, do not re-implement them.
     *const tgBox::Config& getConfig() const { return m_config; }
     *const btVector3& getFrom() const { return m_pair.getFrom(); }
     *const btVector3& getTo() const { return m_pair.getTo(); }
     **/

    /**
     * This class uses the parent's getCollisionShape method, since the underlying
     * Bullet Physics object for a box is still the same.
     * For reference, here's the line that does that creation:
     *new btBoxShape(btVector3(width, length / 2.0, height));
     */

    /**
     * Return a set containing only a pointer to this Box.
     * @retval a set containing only a pointer to this Box
     * @todo This function can't be const unless the return value is
     * std::set<const tgRigidInfo*>.
     * Note that this is re-defined so that a tgBoxMoreAnchorsInfo is returned
     * instead of a tgBoxInfo.
     */
    virtual std::set<tgRigidInfo*> getLeafRigids();

     /**
     * This function determines if a node is on the surface (*ON THE INSIDE*)
     * of this box. This is the big difference from tgBoxInfo! In that class,
     * this function just checked if the nodeVector was either of the two endpoints.
     */
    virtual bool containsNode(const btVector3& nodeVector) const;

    /**
     * Return a set containing all the nodes in this box. Note that
     * tgBoxInfo has this same function, and we're redefining it here
     * so that the returned set will include the additional nodes after they're
     * added to additionalNodes by the containsNode method.
     * @TODO: actually implement this. right now, just use the parent's function.
     */
    //    virtual std::set<btVector3> getContainedNodes() const;

protected:

    /**
     * This function checks if a node is on the surface of the tgBox that will be
     * created with this tgBoxInfo.
     * NOTE that it does NOT work for boxes that start off rotated:
     * unless a box is orthogonal to the axes of the world,
     * this function will always return false.
     * It is protected so that only children of this class could call or re-define.
     * @param[in] nodeVector a btVector3 that is to be checked against this box.
     * @retval result, true if the node is on or inside the box, false else.
     */
    bool isNodeOnBoxSurface(const btVector3& nodeVector) const;

    /**
     * This function is a helper to isNodeOnBoxSurface.
     * It returns the correct geometry of the box around which to check for nodes.
     * This is needed because it's unclear what direction is width and which
     * is height for a box. We fix this by testing and hard-coding the width/height
     * ordering for different orientations of the box.
     * This is done because the Bullet Physics object is not created yet:
     * containsNode is called before the methods that create the Bullet object.
     * @TODO: can this program determine what orientation and rotations will
     * be used by Bullet, and do that instead of hard-coding?
     * @retval a btVector3 of half extents, just like Bullet uses for btBoxShape.
     */
    btVector3 getHalfExtents() const;

    /**
     * This function is a helper inside getHalfExtents.
     * It returns the orientation of the box.
     * @retval a string with the axis along which this box exists.
     * This should be enough to determine how to orient the half extents.
     */
    std::string getBoxOrientation() const;

    /**
     * The following three functions are helpers to getHalfExtents.
     * They each assign the half extents according to the specific orientation
     * of the box.
     */
    btVector3 getHalfExtentsOrientedX() const;
    btVector3 getHalfExtentsOrientedY() const;
    btVector3 getHalfExtentsOrientedZ() const;

private:

    /** Disable the copy constructor. */
    tgBoxMoreAnchorsInfo(const tgBoxMoreAnchorsInfo&);

    /** Disable the assignment operator. */
    tgBoxMoreAnchorsInfo& operator=(const tgBoxMoreAnchorsInfo&);

    // The following variable is used in the half extents checking.
    // This "SIMD_EPSILON" is what btVector3 uses in its fuzzyZero method,
    // which motivates its use here.
    // @TODO: will this not work sometimes??
    double tgEpsilon = SIMD_EPSILON * 10;

    // note that tgBoxInfo has the following two private variables:
    //const tgPair m_pair;
    //const tgBox::Config m_config;

};

/**
 * Overload operator<<() to handle a tgBoxMoreAnchorsInfo.
 * @param[in,out] os an ostream
 * @param[in] q a tgBoxMoreAnchorsInfo
 * @return os
 */
inline std::ostream& operator<<(std::ostream& os, const tgBoxMoreAnchorsInfo& box)
{
    os << "tgBoxMoreAnchorsInfo(" << box.getFrom() << ", " << box.getTo() <<")";
    return os;
}

#endif


text:
package com.hazelcast.concurrent.lock;

import com.hazelcast.concurrent.lock.operations.AwaitBackupOperation;
import com.hazelcast.concurrent.lock.operations.AwaitOperation;
import com.hazelcast.concurrent.lock.operations.BeforeAwaitBackupOperation;
import com.hazelcast.concurrent.lock.operations.BeforeAwaitOperation;
import com.hazelcast.concurrent.lock.operations.GetLockCountOperation;
import com.hazelcast.concurrent.lock.operations.GetRemainingLeaseTimeOperation;
import com.hazelcast.concurrent.lock.operations.IsLockedOperation;
import com.hazelcast.concurrent.lock.operations.LockBackupOperation;
import com.hazelcast.concurrent.lock.operations.LockOperation;
import com.hazelcast.concurrent.lock.operations.LockReplicationOperation;
import com.hazelcast.concurrent.lock.operations.SignalBackupOperation;
import com.hazelcast.concurrent.lock.operations.SignalOperation;
import com.hazelcast.concurrent.lock.operations.UnlockBackupOperation;
import com.hazelcast.concurrent.lock.operations.UnlockOperation;
import com.hazelcast.internal.serialization.DataSerializerHook;
import com.hazelcast.internal.serialization.impl.FactoryIdHelper;
import com.hazelcast.nio.serialization.DataSerializableFactory;
import com.hazelcast.nio.serialization.IdentifiedDataSerializable;

import static com.hazelcast.internal.serialization.impl.FactoryIdHelper.LOCK_DS_FACTORY;
import static com.hazelcast.internal.serialization.impl.FactoryIdHelper.LOCK_DS_FACTORY_ID;

public final class LockDataSerializerHook implements DataSerializerHook {

    public static final int F_ID = FactoryIdHelper.getFactoryId(LOCK_DS_FACTORY, LOCK_DS_FACTORY_ID);

    public static final int LOCK_RESOURCE = 0;
    public static final int LOCK_STORE = 1;
    public static final int WAITERS_INFO = 2;
    public static final int AWAIT_BACKUP = 3;
    public static final int AWAIT = 4;
    public static final int BEFORE_AWAIT_BACKUP = 5;
    public static final int BEFORE_AWAIT = 6;
    public static final int GET_LOCK_COUNT = 7;
    public static final int GET_REMAINING_LEASETIME = 8;
    public static final int IS_LOCKED = 9;
    public static final int LOCK_BACKUP = 10;
    public static final int LOCK = 11;
    public static final int LOCK_REPLICATION = 12;
    public static final int SIGNAL_BACKUP = 13;
    public static final int SIGNAL = 14;
    public static final int UNLOCK_BACKUP = 15;
    public static final int UNLOCK = 16;

    @Override
    public int getFactoryId() {
        return F_ID;
    }

    @Override
    public DataSerializableFactory createFactory() {
        return new DataSerializableFactory() {
            @Override
            public IdentifiedDataSerializable create(int typeId) {
                switch (typeId) {
                    case AWAIT_BACKUP:
                        return new AwaitBackupOperation();
                    case AWAIT:
                        return new AwaitOperation();
                    case BEFORE_AWAIT_BACKUP:
                        return new BeforeAwaitBackupOperation();
                    case BEFORE_AWAIT:
                        return new BeforeAwaitOperation();
                    case GET_LOCK_COUNT:
                        return new GetLockCountOperation();
                    case GET_REMAINING_LEASETIME:
                        return new GetRemainingLeaseTimeOperation();
                    case IS_LOCKED:
                        return new IsLockedOperation();
                    case LOCK:
                        return new LockOperation();
                    case LOCK_BACKUP:
                        return new LockBackupOperation();
                    case LOCK_REPLICATION:
                        return new LockReplicationOperation();
                    case SIGNAL_BACKUP:
                        return new SignalBackupOperation();
                    case SIGNAL:
                        return new SignalOperation();
                    case UNLOCK_BACKUP:
                        return new UnlockBackupOperation();
                    case UNLOCK:
                        return new UnlockOperation();
                    case LOCK_STORE:
                        return new LockStoreImpl();
                    case WAITERS_INFO:
                        return new WaitersInfo();
                    case LOCK_RESOURCE:
                        return new LockResourceImpl();
                    default:
                        return null;
                }
            }
        };
    }
}


text:
package st.redline.compiler;

import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import st.redline.core.PrimObject;
import st.redline.core.RedlineException;

import java.util.HashMap;
import java.util.Map;

public class BlockReturnTypeCreator implements Opcodes {

    private final static Map<String, String> registry = new HashMap<String, String>();

    private final String fullyQualifiedClassName;

    public BlockReturnTypeCreator(String fullyQualifedClassName) {
        this.fullyQualifiedClassName = fullyQualifedClassName;
    }

    void create() {
        if (registry.containsKey(fullyQualifiedClassName))
            return;
        registry.put(fullyQualifiedClassName, fullyQualifiedClassName);
        loadClass(createClass());
    }

    private void loadClass(byte[] aClass) {
        try {
            PrimObject.exposedClassLoader().defineClass(aClass);
        } catch (Exception e) {
            throw new RedlineException(e);
        }
    }

    private byte[] createClass() {
        ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_FRAMES);
        writer.visit(V1_5, ACC_PUBLIC + ACC_SUPER, fullyQualifiedClassName, null, "st/redline/core/BlockReturn", null);
        createAnswerArgumentConstructor(writer);
        writer.visitEnd();
        return writer.toByteArray();
    }

    void createAnswerArgumentConstructor(ClassWriter writer) {
        MethodVisitor mv = writer.visitMethod(ACC_PUBLIC, "<init>", "(Lst/redline/core/PrimObject;)V", null, null);
        mv.visitCode();
        mv.visitVarInsn(ALOAD, 0);
        mv.visitVarInsn(ALOAD, 1);
        mv.visitMethodInsn(INVOKESPECIAL, "st/redline/core/BlockReturn", "<init>", "(Lst/redline/core/PrimObject;)V");
        mv.visitInsn(RETURN);
        mv.visitMaxs(2, 3);
        mv.visitEnd();
    }
}


text:
package com.dak.duty.repository;

import java.time.LocalDate;
import java.util.List;
import java.util.Set;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.RepositoryDefinition;
import org.springframework.stereotype.Repository;

import com.dak.duty.model.Event;
import com.dak.duty.model.EventType;
import com.dak.duty.model.Person;

@Repository
@RepositoryDefinition(domainClass = Event.class, idClass = Long.class)
public interface EventRepository extends JpaRepository<Event, Long>, JpaSpecificationExecutor<Event> {

	// commenting out because this *only* returns rows of the same event type.
	// @Query("select e from Event e where e.eventType = ?1 and e.dateEvent = (select max(e.dateEvent) from Event e where
	// e.eventType = ?1)")
	// instead, we want to show ALL rows from the date this event type last occurred
	// example: we're creating roster for Sunday AM - we want to pull last Sunday PM and last Sunday AM
	@Query("select e from Event e where e.organisation = ?#{principal.person.organisation} and e.eventType = ?1 and e.dateEvent = (select max(e.dateEvent) from Event e where e.eventType = ?1)")
	List<Event> findMostRecentEventsByEventType(final EventType et);

	@Query("select max(e.dateEvent) from Event e where e.organisation = ?#{principal.person.organisation}")
	LocalDate findMaxEventDate();

	@Modifying
	@Query("update Event e set e.approved = ?1 where e.approved != ?1 and e.organisation = ?#{principal.person.organisation}")
	Integer setApprovedStatusOnAllEvents(boolean approved);

	@Query("select e from Event e where e.approved = ?1 and e.organisation = ?#{principal.person.organisation}")
	List<Event> findByApproved(Boolean approved);

	@Query("select e from Event e where e.organisation = ?#{principal.person.organisation} order by e.dateEvent desc")
	List<Event> findAllByOrderByDateEventDesc();

	@Query("select e from Event e where e.organisation = ?#{principal.person.organisation} and e.dateEvent >= ?1 and e.dateEvent <= ?2")
	List<Event> findEventsByDateBetween(final LocalDate startDate, final LocalDate endDate);

	@Query("select e from Event e where e.organisation = ?#{principal.person.organisation} and e.dateEvent >= ?1")
	List<Event> findAllByDateEventGreaterThanEqual(final LocalDate d);

	// @Query("select e from Event e where e.organisation = ?#{principal.person.organisation} and e.roster.person = ?1
	// and e.dateEvent >= ?2")
	List<Event> findAllByRoster_PersonAndDateEventGreaterThanEqual(Person person, LocalDate d);

	// @Query("select e from Event e where e.organisation = ?#{principal.person.organisation} and e.roster.person = ?1
	// and e.dateEvent >= ?2 "
	// + "order by e.dateEvent asc")
	Set<Event> findAllByRoster_PersonAndDateEventGreaterThanEqualOrderByDateEventAsc(Person person, LocalDate d);

	@Override
	@Query("select e from Event e where e.organisation = ?#{principal.person.organisation}")
	List<Event> findAll();
}


text:
namespace bpt = boost::property_tree;

namespace {

void test_tilejson_fetch() {
  char cwd[PATH_MAX];
  if (getcwd(&cwd[0], PATH_MAX) == NULL) { throw std::runtime_error("getcwd failed"); }
  bpt::ptree conf = avecado::tilejson((boost::format("file://%1%/test/tilejson.json") % cwd).str());

  test::assert_equal<int>(conf.get<int>("maskLevel"), 8, "maskLevel");
  test::assert_equal<int>(conf.get<int>("maxzoom"), 15, "maxzoom");
  test::assert_equal<int>(conf.get<int>("minzoom"), 0, "minzoom");
}

// TODO: this is a pretty awful test, and isn't able to dig any deeper than
// the overzoom, not even to inspect it. might need an upgrade to how the
// built-in HTTP server works so that we can do more with these tests...
void test_tilejson_parse() {
  using namespace avecado;

  char cwd[PATH_MAX];
  if (getcwd(&cwd[0], PATH_MAX) == NULL) { throw std::runtime_error("getcwd failed"); }
  bpt::ptree conf = tilejson((boost::format("file://%1%/test/tilejson.json") % cwd).str());

  std::unique_ptr<fetcher> f = make_tilejson_fetcher(conf);
  fetch::overzoom *o = dynamic_cast<fetch::overzoom *>(f.get());
  test::assert_equal<bool>(o != nullptr, true, "is overzoom");
}

// utility function to create TileJSON from Mapnik XML.
std::string tile_json_for_xml(const std::string xml) {
  using test::make_map;
  using avecado::make_tilejson;

  char cwd[PATH_MAX];
  if (getcwd(&cwd[0], PATH_MAX) == NULL) { throw std::runtime_error("getcwd failed"); }

  mapnik::Map map = make_map(xml, 256, 0, 0, 0);
  std::string json = make_tilejson(map, (boost::format("file://%1%/") % cwd).str());

  return json;
}

// https://github.com/MapQuest/avecado/issues/54
//
// maxzoom, minzoom & metatile (masklevel, presumably, too) are all
// supposed to be numeric, but are being generated as strings.
//
// the 2.1.0 tilejson spec doesn't specify metatile or masklevel,
// but we'll just assume they're supposed to be integers too.
void test_tilejson_generate_numeric() {
  using namespace boost::xpressive;

  for (auto &xml : {"test/empty_map_file.xml", "test/tilejson_params.xml"}) {
    try {
      // this test is kinda half-assed, what with the regex and all...
      // but it should work to detect the difference between a JSON
      // string and a number.
      const std::string json = tile_json_for_xml(xml);

      for (auto &param : {"metatile", "maskLevel", "minzoom", "maxzoom"}) {
        // first, need to check if the key is present at all. if not,
        // then it doesn't make sense to check that it's a number.
        // NOTE: this is /"${param}" *:/
        sregex is_present = as_xpr('"') >> param >> '"' >> *space >> as_xpr(':');

        if (regex_search(json.begin(), json.end(), is_present)) {
          // if present, we check if the value begins with a valid number
          // prefix: an optional minus sign and then digits. this might
          // match invalid JSON, but the validity of generated JSON is a
          // test we'll have to do elsewhere.
          sregex is_number = as_xpr('"') >> param >> '"' >> *space >> as_xpr(':')
                                         >> *space >> !as_xpr('-') >> +digit;

          if (!regex_search(json.begin(), json.end(), is_number)) {
            throw std::runtime_error(
              (boost::format("Parameter \"%1%\" should be a number, but is not "
                             "in TileJSON: %2%") % param % json).str());
          }
        }
      }

      // Some params need to be arrays of integers
      for (auto &param : {"center", "bounds"}) {
        // The same check as above for presense
        sregex is_present = as_xpr('"') >> param >> '"' >> *space >> as_xpr(':');
        if (regex_search(json.begin(), json.end(), is_present)) {
          sregex is_array = as_xpr('"') >> param >> '"' >> *space >> as_xpr(':')
                                        >> *space >> as_xpr('[');

          if (!regex_search(json.begin(), json.end(), is_array)) {
            throw std::runtime_error(
              (boost::format("Parameter \"%1%\" should be an array of numbers, but is not "
                             "in TileJSON: %2%") % param % json).str());
          }
        }
      }

    } catch (const std::exception &e) {
      std::throw_with_nested(
        std::runtime_error(
          (boost::format("while processing XML file \"%1%\"") % xml).str()));
    }
  }
}

// same as the above test, but we force Mapnik to store strings
// in its parameter list so that we have to convert to numeric
// before outputting to JSON.
void test_tilejson_generate_numeric_force() {
  using namespace boost::xpressive;
  using test::make_map;
  using avecado::make_tilejson;

  char cwd[PATH_MAX];
  if (getcwd(&cwd[0], PATH_MAX) == NULL) { throw std::runtime_error("getcwd failed"); }

  mapnik::Map map = make_map("test/empty_map_file.xml", 256, 0, 0, 0);
  map.get_extra_parameters().emplace("maxzoom", mapnik::value_holder(std::string("0")));

  std::string json = make_tilejson(map, (boost::format("file://%1%/") % cwd).str());

  sregex is_present = as_xpr("\"maxzoom\"") >> *space >> as_xpr(':');
  if (!regex_search(json.begin(), json.end(), is_present)) {
    throw std::runtime_error(
      (boost::format("maxzoom key not in generated JSON: %1%") % json).str());
  }

  sregex is_number = as_xpr("\"maxzoom\"") >> *space >> as_xpr(':')
                                           >> *space >> !as_xpr('-') >> +digit;
  if (!regex_search(json.begin(), json.end(), is_number)) {
    throw std::runtime_error(
      (boost::format("Parameter \"maxzoom\" should be a number, but is not "
                     "in TileJSON: %1%") % json).str());
  }
}

void test_tilejson_generate_masklevel() {
  using test::make_map;
  using avecado::make_tilejson;

  test::temp_dir tmp;
  std::string base_url = (boost::format("file://%1%/") % tmp.path().native()).str();

  mapnik::Map map = make_map("test/empty_map_file.xml", 256, 0, 0, 0);
  for (int maxzoom = 0; maxzoom < 23; ++maxzoom) {
    map.get_extra_parameters().erase("maxzoom");
    map.get_extra_parameters().emplace("maxzoom", mapnik::value_integer(maxzoom));

    const std::string json = make_tilejson(map, base_url);
    const std::string json_file = (tmp.path() / "tile.json").native();
    std::ofstream out(json_file);
    out.write(json.data(), json.size());
    out.close();

    bpt::ptree conf = avecado::tilejson((boost::format("%1%tile.json") % base_url).str());

    test::assert_equal<mapnik::value_integer>(
      map.get_extra_parameters().find("maxzoom")->second.get<mapnik::value_integer>(),
      mapnik::value_integer(maxzoom), "maxzoom parameter");
    test::assert_equal<size_t>(map.get_extra_parameters().count("maskLevel"), 0,
                               "maskLevel presence in original parameters");
    test::assert_equal<int>(conf.get<int>("maxzoom"), maxzoom, "maxzoom");
    test::assert_equal<int>(conf.get<int>("maskLevel"), maxzoom, "maskLevel");
  }
}

} // anonymous namespace

int main() {
  int tests_failed = 0;

  std::cout << "== Testing TileJSON parsing ==" << std::endl << std::endl;

#define RUN_TEST(x) { tests_failed += test::run(#x, &(x)); }
  RUN_TEST(test_tilejson_fetch);
  RUN_TEST(test_tilejson_parse);
  RUN_TEST(test_tilejson_generate_numeric);
  RUN_TEST(test_tilejson_generate_numeric_force);
  RUN_TEST(test_tilejson_generate_masklevel);

  std::cout << " >> Tests failed: " << tests_failed << std::endl << std::endl;

  return (tests_failed > 0) ? 1 : 0;
}


text:
<?php

namespace Application\Model;

use Zend\InputFilter\Factory as InputFactory;
use Zend\InputFilter\InputFilter;
use Zend\InputFilter\InputFilterAwareInterface;
use Zend\InputFilter\InputFilterInterface;

class screenshots

{
    public $id;
    public $tempId;
    public $screenshot_image;
    public $screenshot_desc;
    public $screenshot_header;
  // protected $inputFilter;

public function exchangeArray($data)
{
    $this->id                = (isset($data['id']))                 ? $data['id']                    : null;
    $this->tempId            = (isset($data['tempId']))             ? $data['tempId']                : null;
    $this->screenshot_image  = (isset($data['screenshot_image']))   ? $data['screenshot_image']      : null;
    $this->screenshot_desc   = (isset($data['screenshot_desc']))    ? $data['screenshot_desc']       : null;
    $this->screenshot_header = (isset($data['screenshot_header']))  ? $data['screenshot_header']     : null;
}

public function getArrayCopy()
{
     return get_object_vars($this);

}

}

?>


text:
package retrofit;

import akha.yakhont.Core.Utils.TypeHelper;
import akha.yakhont.CoreReflection;

import android.support.annotation.NonNull;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.lang.reflect.Type;
import java.util.Map;

/** @exclude */ @SuppressWarnings("JavaDoc")
public class YakhontRestAdapter<T> {

    private T                               mHandler;
    private Class<T>                        mService;
    private Map<Method, RestMethodInfo>     mMethodInfoCache;

    /** @exclude */ @SuppressWarnings("JavaDoc")
    public interface YakhontCallback<D> extends Callback<D> {
        boolean setType(Type type);
    }

    @SuppressWarnings("unchecked")
    public T create(@NonNull final Class<T> service, @NonNull final RestAdapter restAdapter) {
        mHandler            = restAdapter.create(service);
        mService            = service;
        mMethodInfoCache    = restAdapter.getMethodInfoCache(service);

        return (T) Proxy.newProxyInstance(service.getClassLoader(), new Class<?>[] {service}, new YakhontHandler());
    }

    private class YakhontHandler implements InvocationHandler {
        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            final boolean notInvoke = (!method.getDeclaringClass().equals(Object.class)
                    && args != null && args.length > 0 && args[args.length - 1] instanceof YakhontCallback)
                    && ((YakhontCallback) args[args.length - 1]).setType(getType(method));
            return notInvoke ? null: CoreReflection.invoke(mHandler, method, args);
        }
    }

    private Type getType(@NonNull final Method method) {
        return RestAdapter.getMethodInfo(mMethodInfoCache, method).responseObjectType;
    }

    public Method findMethod(@NonNull final Type typeResponse) {
        for (final Method method: mService.getMethods())
            if (TypeHelper.checkType(typeResponse, getType(method)))
                return method;
        return null;
    }

    public T getHandler() {
        return mHandler;
    }
}


text:
package com.sun.jmx.remote.opt.internal;

import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.lang.reflect.Method;
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.rmi.server.Operation;
import java.rmi.server.RemoteCall;
import java.rmi.server.RemoteObject;
import java.rmi.server.RemoteRef;

public class ProxyRef implements RemoteRef {
    public ProxyRef(RemoteRef ref) {
	this.ref = ref;
    }

    public void readExternal(ObjectInput in)
	    throws IOException, ClassNotFoundException {
	ref.readExternal(in);
    }

    public void writeExternal(ObjectOutput out) throws IOException {
	ref.writeExternal(out);
    }

    public void invoke(RemoteCall call) throws Exception {
	ref.invoke(call);
    }

    public Object invoke(Remote obj, Method method, Object[] params,
			 long opnum) throws Exception {
	return ref.invoke(obj, method, params, opnum);
    }

    public void done(RemoteCall call) throws RemoteException {
	ref.done(call);
    }

    public String getRefClass(ObjectOutput out) {
	return ref.getRefClass(out);
    }

    public RemoteCall newCall(RemoteObject obj, Operation[] op, int opnum,
			      long hash) throws RemoteException {
	return ref.newCall(obj, op, opnum, hash);
    }

    public boolean remoteEquals(RemoteRef obj) {
        return ref.remoteEquals(obj);
    }

    public int remoteHashCode() {
        return ref.remoteHashCode();
    }

    public String remoteToString() {
        return ref.remoteToString();
    }

    protected RemoteRef ref;
}


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-2.0.xsd">
    <changeSet author="fx (generated)" id="1371136508309-1">
        <addColumn tableName="abstractaccount_permissions">
            <column name="inducedpermission" type="VARCHAR(255)"/>
        </addColumn>
		<addColumn tableName="role_permissions">
            <column name="inducedpermission" type="VARCHAR(255)"/>
        </addColumn>
    </changeSet>
</databaseChangeLog>


text:
pub enum Visibility {
	Enter = 0,
	Retain,
	Leave,
}

#[repr(C)]
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum ConnectStatus {
	/// There is no activity to the server, this is the default value
	Disconnected = 0,
	/// We are trying to connect, we haven't got a clientID yet, we haven't been accepted by the server
	Connecting,
	/// The server has accepted us, we can talk and hear and we got a clientID, but we don't have the channels and clients yet, we can get server infos (welcome msg etc.)
	Connected,
	/// We are connected and we are visible
	ConnectionEstablishing,
	/// We are connected and we have the client and channels available
	ConnectionEstablished,
}

#[repr(C)]
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum LocalTestMode {
	Off                 = 0,
	VoiceLocalOnly      = 1,
	VoiceLocalAndRemote = 2,
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.wutiarn</groupId>
    <artifactId>flibusta-bot</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>flibusta-bot</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.1.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>10</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-freemarker</artifactId>
            <version>2.0.1.RELEASE</version>
        </dependency>
        <!--<dependency>-->
            <!--<groupId>org.springframework.boot</groupId>-->
            <!--<artifactId>spring-boot-starter-data-jpa</artifactId>-->
        <!--</dependency>-->
        <!--<dependency>-->
            <!--<groupId>org.postgresql</groupId>-->
            <!--<artifactId>postgresql</artifactId>-->
            <!--<version>42.2.2</version>-->
        <!--</dependency>-->
        <dependency>
            <groupId>javax.xml.bind</groupId>
            <artifactId>jaxb-api</artifactId>
            <version>2.3.0</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.dataformat</groupId>
            <artifactId>jackson-dataformat-xml</artifactId>
            <version>2.9.5</version>
        </dependency>
        <dependency>
            <groupId>com.github.pengrad</groupId>
            <artifactId>java-telegram-bot-api</artifactId>
            <version>3.6.0</version>
        </dependency>
        <dependency>
            <groupId>com.squareup.okhttp3</groupId>
            <artifactId>okhttp</artifactId>
            <version>3.10.0</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                        <configuration>
                            <finalName>flibusta-bot</finalName>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>


text:
#ifndef PageScriptDebugServer_h
#define PageScriptDebugServer_h

#include "bindings/core/v8/ScriptDebugServer.h"
#include "bindings/core/v8/ScriptPreprocessor.h"
#include "wtf/Forward.h"
#include "wtf/RefCounted.h"
#include <v8.h>

namespace blink {

class Page;
class ScriptController;
class ScriptPreprocessor;
class ScriptSourceCode;
class Frame;

class PageScriptDebugServer FINAL : public ScriptDebugServer {
    WTF_MAKE_NONCOPYABLE(PageScriptDebugServer);
public:
    static PageScriptDebugServer& shared();

    static void setMainThreadIsolate(v8::Isolate*);

    void addListener(ScriptDebugListener*, Page*);
    void removeListener(ScriptDebugListener*, Page*);

    static void interruptAndRun(PassOwnPtr<Task>);

    class ClientMessageLoop {
    public:
        virtual ~ClientMessageLoop() { }
        virtual void run(Page*) = 0;
        virtual void quitNow() = 0;
    };
    void setClientMessageLoop(PassOwnPtr<ClientMessageLoop>);

    virtual void compileScript(ScriptState*, const String& expression, const String& sourceURL, String* scriptId, String* exceptionDetailsText, int* lineNumber, int* columnNumber, RefPtrWillBeRawPtr<ScriptCallStack>* stackTrace) OVERRIDE;
    virtual void clearCompiledScripts() OVERRIDE;
    virtual void runScript(ScriptState*, const String& scriptId, ScriptValue* result, bool* wasThrown, String* exceptionDetailsText, int* lineNumber, int* columnNumber, RefPtrWillBeRawPtr<ScriptCallStack>* stackTrace) OVERRIDE;
    virtual void setPreprocessorSource(const String&) OVERRIDE;
    virtual void preprocessBeforeCompile(const v8::Debug::EventDetails&) OVERRIDE;
    virtual PassOwnPtr<ScriptSourceCode> preprocess(LocalFrame*, const ScriptSourceCode&) OVERRIDE;
    virtual String preprocessEventListener(LocalFrame*, const String& source, const String& url, const String& functionName) OVERRIDE;
    virtual void clearPreprocessor() OVERRIDE;

    virtual void muteWarningsAndDeprecations() OVERRIDE;
    virtual void unmuteWarningsAndDeprecations() OVERRIDE;
    void rescanScripts(LocalFrame *frame);

private:
    PageScriptDebugServer();
    virtual ~PageScriptDebugServer();

    virtual ScriptDebugListener* getDebugListenerForContext(v8::Handle<v8::Context>) OVERRIDE;
    virtual void runMessageLoopOnPause(v8::Handle<v8::Context>) OVERRIDE;
    virtual void quitMessageLoopOnPause() OVERRIDE;

    typedef HashMap<Page*, ScriptDebugListener*> ListenersMap;
    ListenersMap m_listenersMap;
    OwnPtr<ClientMessageLoop> m_clientMessageLoop;
    Page* m_pausedPage;
    HashMap<String, String> m_compiledScriptURLs;

    OwnPtr<ScriptSourceCode> m_preprocessorSourceCode;
    OwnPtr<ScriptPreprocessor> m_scriptPreprocessor;
    bool canPreprocess(LocalFrame*);
    static v8::Isolate* s_mainThreadIsolate;
};

} // namespace blink

#endif // PageScriptDebugServer_h


text:
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.

using System;
using Microsoft.AspNetCore.Authentication;

namespace IdentityServer.UnitTests.Common
{
    internal class StubClock : ISystemClock
    {
        public Func<DateTime> UtcNowFunc = () => DateTime.UtcNow;
        public DateTimeOffset UtcNow => new DateTimeOffset(UtcNowFunc());
    }
}


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

                «

    <p class="styleSans12.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">
The Middle Bakken dolomite throughout the entire horizontal section was typically light bluish gray to medium bluish gray to gray, spotted very light brown, dark gray in part, microcrystalline, argillaceous, and minimally carbonaceous. The dolomite was also generally moderately firm, with fair to good intergranular porosity and light green to dark yellow to dark green fluorescence, with fast streaming cuts. ROP in the horizontal ranged from 0.10 to 13.90 minutes per foot while rotating and sliding, and gas
measurements ranged from 20 to 4,696 units, with max gas value within range observed at 15,088' MD.
Conclusion
EOG Resources Parshall 97-3332H reached a total depth of 15,656' MD at 2:00 PM CST on December 22, 2014 in the Middle Bakken, and is now awaiting completion
Mitch Olson Wellsite Geologist Neset Consulting Service


text:
order: 5
zh-CN:
	title: 内联样式
	loading: 加载中
en-US:
	title: Inline style
	loading: Loading
---

```js
import { InlineLoading } from 'zent';

ReactDOM.render(
	<div className="zent-loading-demo-inline-container">
		<InlineLoading loading />
		<InlineLoading
			loading
			icon="circle"
			iconText="{i18n.loading}"
			textPosition="right"
		/>
		<InlineLoading loading iconText="{i18n.loading}" />
	</div>,
	mountNode
);
```

<style>
	.zent-loading-demo-inline-container {
		display: flex;
		align-items: center;
		justify-content: space-around;
	}
</style>


text:
package org.openqa.selenium.server;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestName;
import org.openqa.selenium.server.log.LoggingManager;
import org.openqa.selenium.server.log.StdOutHandler;
import org.openqa.selenium.server.log.TerseFormatter;
import org.openqa.selenium.testworker.TrackableRunnable;
import org.openqa.selenium.testworker.TrackableThread;

import java.util.logging.Handler;
import java.util.logging.Logger;

public class CommandQueueUnitTest {

  private static final String sessionId = "1";
  private static final String testCommand = "testCommand";
  private static final String waitCommand = "waitForSomethingCommand";
  private static final String testResult = "OK";
  private static final int defaultTimeout = 7;
  private static final int retryTimeout = 5;

  private static final Logger log = Logger.getLogger(CommandQueueUnitTest.class.getName());

  @Rule public TestName name = new TestName();

  private CommandQueue cq;
  private RemoteControlConfiguration configuration;

  @Before
  public void setUp() throws Exception {
    configureLogging();
    configuration = new RemoteControlConfiguration();
    configuration.setTimeoutInSeconds(defaultTimeout);
    configuration.setProxyInjectionModeArg(false);
    cq = new CommandQueue(sessionId, name.getMethodName(), configuration);
    log.info("Start test: " + name.getMethodName());
  }

  private void configureLogging() throws Exception {
    LoggingManager.configureLogging(new RemoteControlConfiguration(), true);
    Logger logger = Logger.getLogger("");
    for (Handler handler : logger.getHandlers()) {
      if (handler instanceof StdOutHandler) {
        handler.setFormatter(new TerseFormatter(true));
        break;
      }
    }
  }

  @After
  public void tearDown() throws Exception {
    LoggingManager.configureLogging(new RemoteControlConfiguration(), false);
  }

  @Test
  public void testQueueDelayInitializedAtDefault() {
    assertEquals(CommandQueue.getSpeed(), cq.getQueueDelay());
  }

  @Test
  public void testQueueDelayChangedAsSetNoCrosstalk() {
    int defaultSpeed = CommandQueue.getSpeed();
    int newSpeed = cq.getQueueDelay() + 42;
    int newGlobalSpeed = defaultSpeed + 21;
    cq.setQueueDelay(newSpeed);
    CommandQueue.setSpeed(newGlobalSpeed);
    assertEquals(newSpeed, cq.getQueueDelay());
    assertEquals(newGlobalSpeed, CommandQueue.getSpeed());

    CommandQueue cq2 =
        new CommandQueue(sessionId, name.getMethodName() + "2", new RemoteControlConfiguration());
    assertEquals(newGlobalSpeed, cq2.getQueueDelay());

    CommandQueue cq3 =
        new CommandQueue(sessionId, name.getMethodName() + "3", newSpeed, new RemoteControlConfiguration());
    assertEquals(newSpeed, cq3.getQueueDelay());

    CommandQueue.setSpeed(defaultSpeed);
  }

  @Test
  public void testAssertStartingState() {
    assertNull(cq.peekAtCommand());
    assertNull(cq.peekAtResult());
  }

  @Test
  public void testBasicDoCommandWithoutWaiting() throws WindowClosedException {
    cq.doCommandWithoutWaitingForAResponse(testCommand, "", "");
    RemoteCommand rc = cq.peekAtCommand();
    assertNotNull(rc);
    assertEquals(testCommand, rc.getCommand());
    assertNull(cq.peekAtResult());
  }

  @Test
  public void testDoCommandWithoutWaitingWithResultAlreadyThereWithNoPI()
      throws WindowClosedException {
    cq.putResult(testResult);
    try {
      cq.doCommandWithoutWaitingForAResponse(testCommand, "", "");
      fail();
    } catch (IllegalStateException ise) {
      assertNotNull(cq.peekAtResult());
    }
  }

  @Test
  public void testDoCommandWithoutWaitingWithResultAlreadyThereWithPI()
      throws WindowClosedException {
    configuration = new RemoteControlConfiguration();
    configuration.setTimeoutInSeconds(defaultTimeout);
    configuration.setProxyInjectionModeArg(true);
    cq = new CommandQueue(sessionId, name.getMethodName(), configuration);
    cq.putResult(testResult);
    cq.doCommandWithoutWaitingForAResponse(testCommand, "", "");
    assertEquals(testResult, cq.peekAtResult());
  }

  @Test
  public void testDoCommandWithoutWaitingWithBadResultAlreadyThereWithPI()
      throws WindowClosedException {
    configuration = new RemoteControlConfiguration();
    configuration.setTimeoutInSeconds(defaultTimeout);
    configuration.setProxyInjectionModeArg(true);
    cq = new CommandQueue(sessionId, name.getMethodName(), configuration);
    cq.putResult(testResult);
    cq.doCommandWithoutWaitingForAResponse(waitCommand, "", "");
    assertEquals(testResult, cq.peekAtResult());
  }

  @Test
  public void testGetsTimeoutExceptionOnGetResult() {
    expectResult(CommandResultHolder.CMD_TIMED_OUT_MSG);
    assertNull(cq.peekAtResult());
  }

  @Test
  public void testDoCommandTimesOut() {
    long now = System.currentTimeMillis();
    String result = cq.doCommand(testCommand, "", "");
    long after = System.currentTimeMillis();
    assertEquals(CommandResultHolder.CMD_TIMED_OUT_MSG, result);
    assertTrue((after - now) > defaultTimeout);
  }

  @Test
  public void testGetsPrevCommandFromHandleNullResult() throws WindowClosedException {
    cq.doCommandWithoutWaitingForAResponse(testCommand, "", "");
    RemoteCommand rc = cq.handleCommandResult(null);
    assertEquals(testCommand, rc.getCommand());
  }

  @Test
  public void testSendsRetryCommandIfNoneAfterRetryPeriod() {
    long now = System.currentTimeMillis();
    RemoteCommand rc = cq.handleCommandResult(null);
    long after = System.currentTimeMillis();
    assertTrue((after - now) > retryTimeout);
    assertEquals(CommandHolder.RETRY_CMD_STRING, rc.getCommand());
  }

  @Test
  public void testHandleResultNoWaitingWithOKResultWithResExpectedNoPI() {
    cq.setResultExpected(true);
    cq.handleCommandResultWithoutWaitingForACommand(testResult);
    assertEquals(testResult, cq.peekAtResult());
  }

  @Test
  public void testHandleResultWithOKResultWithNoResExpectedWithPI() {
    configuration = new RemoteControlConfiguration();
    configuration.setTimeoutInSeconds(defaultTimeout);
    configuration.setProxyInjectionModeArg(true);
    cq = new CommandQueue(sessionId, name.getMethodName(), configuration);
    cq.handleCommandResultWithoutWaitingForACommand(testResult);
    assertEquals(testResult, cq.peekAtResult());
  }

  @Test
  public void testGetNextCommandWhenAlreadyWaiting() throws Throwable {
    cq.setResultExpected(true);
    TrackableRunnable internalRunner = new TrackableRunnable() {
      @Override
      public Object go() throws Throwable {
        cq.doCommandWithoutWaitingForAResponse(testCommand, "", "");
        return null;
      }
    };
    String name = "launching runner";
    TrackableThread t = new TrackableThread(internalRunner, name);
    t.start();
    t.getResult();
    assertsForCommandState(cq.getNextCommand());
  }

  private void assertsForCommandState(RemoteCommand cmd) {
    assertNotNull(cmd);
    assertEquals(testCommand, cmd.getCommand());
  }

  @Test
  public void testSimpleSingleThreaded() throws Exception {
    injectCommandAsIfWaiting("something", "arg1", "arg2");
    expectCommand("something", "arg1", "arg2");
    cq.handleCommandResultWithoutWaitingForACommand("OK");
    expectResult("OK");
  }

  @Test
  public void testRealSimple() throws Throwable {
    TrackableThread commandRunner = launchCommandRunner("something", "arg1", "arg2");
    expectCommand("something", "arg1", "arg2");
    cq.handleCommandResultWithoutWaitingForACommand("OK");
    assertEquals("OK", commandRunner.getResult());
  }

  @Test
  public void testTwoRoundsSingleThreaded() throws Exception {
    testSimpleSingleThreaded();
    cq.doCommandWithoutWaitingForAResponse("testComplete", "", "");
    expectCommand("testComplete", "", "");
    cq.handleCommandResultWithoutWaitingForACommand("OK");
    expectResult("OK");
  }

  @Test
  public void testRealTwoRounds() throws Throwable {
    // do "something"
    TrackableThread commandRunner = launchCommandRunner("something", "arg1", "arg2");
    // browser receives "something"
    TrackableThread browserRequestRunner = launchBrowserResultRunner(null);
    expectCommand(browserRequestRunner, "something", "arg1", "arg2");
    // browser replies "OK"
    browserRequestRunner = launchBrowserResultRunner("OK");
    // commandRunner receives "OK"
    assertEquals("OK", commandRunner.getResult());
    // send a final "testComplete" in the current foreground thread
    cq.doCommandWithoutWaitingForAResponse("testComplete", "", "");
    expectCommand(browserRequestRunner, "testComplete", "", "");
  }

  // TODO test JsVar stuff

  /**
   * In PI Mode, open replies "OK", but then we asynchronously receive "closed!"
   */
  @Test
  public void testPIOpenSingleThreaded() throws Exception {
    injectCommandAsIfWaiting("open", "blah.html", "");
    expectCommand("open", "blah.html", "");
    cq.handleCommandResultWithoutWaitingForACommand("OK");
    cq.declareClosed();
    assertEquals("OK", cq.peekAtResult());
  }

  private void injectCommandAsIfWaiting(String cmd, String field, String value)
      throws WindowClosedException {
    cq.setResultExpected(true);
    cq.doCommandWithoutWaitingForAResponse(cmd, field, value);
  }

  private void expectCommand(TrackableThread browserRequestRunner, String cmd, String arg1,
      String arg2) throws Throwable {
    RemoteCommand actual = (RemoteCommand) browserRequestRunner.getResult();
    RemoteCommand expected = new DefaultRemoteCommand(cmd, arg1, arg2);
    assertEquals(cmd + " command got mangled", expected, actual);
  }

  private void expectCommand(String cmd, String arg1, String arg2) {
    RemoteCommand actual = cq.getNextCommand();
    RemoteCommand expected = new DefaultRemoteCommand(cmd, arg1, arg2);
    assertEquals(cmd + " command got mangled", expected, actual);
  }

  private void expectResult(String expected) {
    String actual = cq.getResult();
    assertEquals(expected + " result got mangled", expected, actual);
  }

  /**
   * Fire off a command in the background, so we can wait for the result
   */
  private TrackableThread launchCommandRunner(String cmd, String arg1, String arg2) {
    TrackableThread t = new TrackableThread(new AsyncCommandRunner(cmd, arg1, arg2), cmd);
    t.start();
    return t;
  }

  /**
   * Send back a browser result in the background, so we can wait for the next command
   */
  private TrackableThread launchBrowserResultRunner(String browserResult) {
    String name = browserResult;
    if (name == null) {
      name = "NULL STARTING";
    }
    TrackableThread t = new TrackableThread(new AsyncBrowserResultRunner(browserResult), name);
    t.start();
    return t;
  }

  /**
   * Passes the specified command to command queue
   */
  private class AsyncCommandRunner extends TrackableRunnable {
    private final String cmd, arg1, arg2;

    AsyncCommandRunner(String cmd, String arg1, String arg2) {
      this.cmd = cmd;
      this.arg1 = arg1;
      this.arg2 = arg2;
    }

    @Override
    public Object go() throws Throwable {
      Object result = cq.doCommand(cmd, arg1, arg2);
      log.info(Thread.currentThread().getName() + " got result: " + result);
      return result;
    }
  }

  /**
   * Passes the specified browserResult to command queue
   */
  private class AsyncBrowserResultRunner extends TrackableRunnable {
    private final String browserResult;

    public AsyncBrowserResultRunner(String browserResult) {
      this.browserResult = browserResult;
    }

    @Override
    public Object go() throws Throwable {
      Object result = cq.handleCommandResult(browserResult);
      log.info(Thread.currentThread().getName() + " got result: " + result);
      return result;
    }
  }

}


text:
#ifndef LOGTAPE_H
#define LOGTAPE_H

#include "storage/sharedfileset.h"

/* LogicalTapeSet is an opaque type whose details are not known outside logtape.c. */

typedef struct LogicalTapeSet LogicalTapeSet;

/*
 * The approach tuplesort.c takes to parallel external sorts is that workers,
 * whose state is almost the same as independent serial sorts, are made to
 * produce a final materialized tape of sorted output in all cases.  This is
 * frozen, just like any case requiring a final materialized tape.  However,
 * there is one difference, which is that freezing will also export an
 * underlying shared fileset BufFile for sharing.  Freezing produces TapeShare
 * metadata for the worker when this happens, which is passed along through
 * shared memory to leader.
 *
 * The leader process can then pass an array of TapeShare metadata (one per
 * worker participant) to LogicalTapeSetCreate(), alongside a handle to a
 * shared fileset, which is sufficient to construct a new logical tapeset that
 * consists of each of the tapes materialized by workers.
 *
 * Note that while logtape.c does create an empty leader tape at the end of the
 * tapeset in the leader case, it can never be written to due to a restriction
 * in the shared buffile infrastructure.
 */
typedef struct TapeShare
{
	/*
	 * Currently, all the leader process needs is the location of the
	 * materialized tape's first block.
	 */
	long		firstblocknumber;
} TapeShare;

/*
 * prototypes for functions in logtape.c
 */

extern char * LogicalTapeGetBufFilename(const LogicalTapeSet *lts);
extern LogicalTapeSet *LogicalTapeSetCreate(int ntapes, TapeShare *shared,
											SharedFileSet *fileset, int worker);
extern void LogicalTapeSetClose(LogicalTapeSet *lts);
extern void LogicalTapeSetForgetFreeSpace(LogicalTapeSet *lts);
extern size_t LogicalTapeRead(LogicalTapeSet *lts, int tapenum,
							  void *ptr, size_t size);
extern void LogicalTapeWrite(LogicalTapeSet *lts, int tapenum,
							 void *ptr, size_t size);
extern void LogicalTapeRewindForRead(LogicalTapeSet *lts, int tapenum,
									 size_t buffer_size);
extern void LogicalTapeRewindForWrite(LogicalTapeSet *lts, int tapenum);
extern void LogicalTapeFreeze(LogicalTapeSet *lts, int tapenum,
							  TapeShare *share);
extern void LogicalTapeSetExtend(LogicalTapeSet *lts, int nAdditional);
extern size_t LogicalTapeBackspace(LogicalTapeSet *lts, int tapenum,
								   size_t size);
extern void LogicalTapeSeek(LogicalTapeSet *lts, int tapenum,
							long blocknum, int offset);
extern void LogicalTapeTell(LogicalTapeSet *lts, int tapenum,
							long *blocknum, int *offset);
extern long LogicalTapeSetBlocks(LogicalTapeSet *lts);

#endif							/* LOGTAPE_H */