func callsetregid(rgid int, egid int) (r1 uintptr, e1 Errno) {
	r1, _, e1 = rawSyscall6(uintptr(unsafe.Pointer(&libc_setregid)), 2, uintptr(rgid), uintptr(egid), 0, 0, 0, 0)
	return
}


func yaml_emitter_emit_scalar(emitter *yaml_emitter_t, event *yaml_event_t) bool {
	if !yaml_emitter_select_scalar_style(emitter, event) {
		return false
	}
	if !yaml_emitter_process_anchor(emitter) {
		return false
	}
	if !yaml_emitter_process_tag(emitter) {
		return false
	}
	if !yaml_emitter_increase_indent(emitter, true, false) {
		return false
	}
	if !yaml_emitter_process_scalar(emitter) {
		return false
	}
	emitter.indent = emitter.indents[len(emitter.indents)-1]
	emitter.indents = emitter.indents[:len(emitter.indents)-1]
	emitter.state = emitter.states[len(emitter.states)-1]
	emitter.states = emitter.states[:len(emitter.states)-1]
	return true
}


func Convert_apiextensions_CustomResourceDefinitionCondition_To_v1_CustomResourceDefinitionCondition(in *apiextensions.CustomResourceDefinitionCondition, out *CustomResourceDefinitionCondition, s conversion.Scope) error {
	return autoConvert_apiextensions_CustomResourceDefinitionCondition_To_v1_CustomResourceDefinitionCondition(in, out, s)
}

// Convert_apiextensions_CustomResourceDefinitionCondition_To_v1_CustomResourceDefinitionCondition is an autogenerated conversion function.


func NewOptComputeSkipReason(v ComputeSkipReason) OptComputeSkipReason {
	return OptComputeSkipReason{
		Value: v,
		Set:   true,
	}
}

// NewOptComputeSkipReason returns new OptComputeSkipReason with value set to v.


func RecordID(ctx context.Context, id int64) (DomainFeedback, error) {
	e := DomainFeedback{ID: id}
	err := ReportsDB.Get(ctx, &e)
	return e, err
}

// RecordID returns the report for the ID.


func (r *elemRef) count() int {
	if r.node != nil {
		return len(r.node.inodes)
	}
	return int(r.page.count)
}

// count returns the number of inodes or page elements.


func ValidHostHeader(h string) bool {
	// The latest spec is actually this:
	//
	// http://tools.ietf.org/html/rfc7230#section-5.4
	//     Host = uri-host [ ":" port ]
	//
	// Where uri-host is:
	//     http://tools.ietf.org/html/rfc3986#section-3.2.2
	//
	// But we're going to be much more lenient for now and just
	// search for any byte that's not a valid byte in any of those
	// expressions.
	for i := 0; i < len(h); i++ {
		if !validHostByte[h[i]] {
			return false
		}
	}
	return true
}

// ValidHostHeader reports whether h is a valid host header.


func KeyctlGetKeyringID(id int, create bool) (ringid int, err error) {
	createInt := 0
	if create {
		createInt = 1
	}
	return KeyctlInt(KEYCTL_GET_KEYRING_ID, id, createInt, 0, 0)
}

// Keyctl commands with special signatures.
// KeyctlGetKeyringID implements the KEYCTL_GET_KEYRING_ID command.
// See the full documentation at:
// http://man7.org/linux/man-pages/man3/keyctl_get_keyring_ID.3.html


func Kill(pid int, sig Signal) (err error) {
	r0, er := C.kill(C.int(pid), C.int(sig))
	if r0 == -1 && er != nil {
		err = er
	}
	return
}

// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT


func read(fd int, p []byte) (n int, err error) {
	var _p0 *byte
	if len(p) > 0 {
		_p0 = &p[0]
	}
	r0, e1 := callread(fd, uintptr(unsafe.Pointer(_p0)), len(p))
	n = int(r0)
	if e1 != 0 {
		err = errnoErr(e1)
	}
	return
}


func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) {
	_, _, e1 := RawSyscall6(SYS_SOCKETPAIR, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0)
	if e1 != 0 {
		err = errnoErr(e1)
	}
	return
}


func Mount(fsType string, dir string, flags int, data unsafe.Pointer) (err error) {
	var _p0 *byte
	_p0, err = BytePtrFromString(fsType)
	if err != nil {
		return
	}
	var _p1 *byte
	_p1, err = BytePtrFromString(dir)
	if err != nil {
		return
	}
	_, _, e1 := syscall_syscall6(libc_mount_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(flags), uintptr(data), 0, 0)
	if e1 != 0 {
		err = errnoErr(e1)
	}
	return
}

//go:cgo_import_dynamic libc_mknodat mknodat "libc.so"
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT


func Getrtable() (rtable int, err error) {
	r0, _, e1 := syscall_rawSyscall(libc_getrtable_trampoline_addr, 0, 0, 0)
	rtable = int(r0)
	if e1 != 0 {
		err = errnoErr(e1)
	}
	return
}

//go:cgo_import_dynamic libc_getrlimit getrlimit "libc.so"
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT


func isTitle(c *context) bool {
	ct := c.caseType()
	if c.info&hasMappingMask == 0 || ct == cTitle {
		return true
	}
	if c.info&exceptionBit == 0 {
		if ct == cLower {
			c.err = transform.ErrEndOfSpan
			return false
		}
		return true
	}
	// Get the exception data.
	e := exceptions[c.info>>exceptionShift:]
	if nTitle := e[1] & lengthMask; nTitle != noChange {
		c.err = transform.ErrEndOfSpan
		return false
	}
	nFirst := (e[1] >> lengthBits) & lengthMask
	if ct == cLower && nFirst != noChange {
		c.err = transform.ErrEndOfSpan
		return false
	}
	return true
}

// isTitle reports whether the current rune is in title case.


func (t *nfcTrie) lookupValue(n uint32, b byte) uint16 {
	switch {
	case n < 46:
		return uint16(nfcValues[n<<6+uint32(b)])
	default:
		n -= 46
		return uint16(nfcSparse.lookup(n, b))
	}
}

// lookupValue determines the type of block n and looks up the value for b.


func brokerMessageToV2Issue49ChatSubscribeMessage(bMsg extensions.BrokerMessage) (V2Issue49ChatSubscribeMessage, error) {
	var msg V2Issue49ChatSubscribeMessage

	// Convert to string
	payload := string(bMsg.Payload)
	msg.Payload = payload // No need for type conversion to reference

	// TODO: run checks on msg type

	return msg, nil
}

// brokerMessageToV2Issue49ChatSubscribeMessage will fill a new V2Issue49ChatSubscribeMessage with data from generic broker message


func (s *State) CodePath() string {
	name := MainGo
	if s.CellIsTest {
		name = MainTestGo
	}
	return path.Join(s.TempDir, name)
}

// CodePath is the path to where the code is going to be saved. Either `main.go` or `main_test.go` file.


func DeclareVariable(decls *Declarations, name, value string) {
	decls.Variables[name] = &Variable{
		Cursor:          NoCursor,
		CellLines:       CellLines{},
		Key:             name,
		Name:            name,
		ValueDefinition: value,
	}
}

// DeclareVariable creates a variable definition in `decls`.
// `value` is copied verbatim, so any type of variable goes.


func (wscb *WorkflowStepCreateBulk) ExecE(ctx context.Context, cbs ...func(ctx context.Context, mc ClientSet, created *WorkflowStep) error) error {
	_, err := wscb.SaveE(ctx, cbs...)
	return err
}

// ExecE calls the given function after executed the query,
// which is always good for cascading create operations.


func (wss *WorkflowStageSelect) Scan(ctx context.Context, v any) error {
	ctx = setContextOp(ctx, wss.ctx, "Select")
	if err := wss.prepareQuery(ctx); err != nil {
		return err
	}
	return scanWithInterceptors[*WorkflowStageQuery, *WorkflowStageSelect](ctx, wss.WorkflowStageQuery, wss, wss.inters, v)
}

// Scan applies the selector query and scans the result into the given value.


func NameLT(v string) predicate.ResourceDefinitionMatchingRule {
	return predicate.ResourceDefinitionMatchingRule(sql.FieldLT(FieldName, v))
}

// NameLT applies the LT predicate on the "name" field.


func ProjectIDIn(vs ...object.ID) predicate.ResourceRun {
	return predicate.ResourceRun(sql.FieldIn(FieldProjectID, vs...))
}

// ProjectIDIn applies the In predicate on the "project_id" field.


func TemplateIDNotIn(vs ...object.ID) predicate.ResourceRun {
	return predicate.ResourceRun(sql.FieldNotIn(FieldTemplateID, vs...))
}

// TemplateIDNotIn applies the NotIn predicate on the "template_id" field.


func CreatedByNEQ(v string) predicate.ResourceRun {
	return predicate.ResourceRun(sql.FieldNEQ(FieldCreatedBy, v))
}

// CreatedByNEQ applies the NEQ predicate on the "created_by" field.


func TypeContainsFold(v string) predicate.WorkflowStep {
	return predicate.WorkflowStep(sql.FieldContainsFold(FieldType, v))
}

// TypeContainsFold applies the ContainsFold predicate on the "type" field.


func (i Values) ValidateWith(schema *openapi3.Schema) error {
	if schema == nil {
		return nil
	}

	// Check required and undefined.
	l := sets.StringKeySet(i)
	r := sets.NewString(schema.Required...)
	a := sets.StringKeySet(schema.Properties)

	if diff := r.Difference(l).UnsortedList(); len(diff) != 0 {
		return fmt.Errorf("not found required values %v", diff)
	}

	if diff := l.Difference(a).UnsortedList(); len(diff) != 0 {
		return fmt.Errorf("found undefiend values %v", diff)
	}

	// Validate.
	for n, v := range i {
		if schema.Properties[n] == nil || schema.Properties[n].Value == nil {
			continue
		}

		var (
			s           = schema.Properties[n].Value
			errTypeFunc = func(name string, ok bool, err error, expectedType string, actualValue any) error {
				if !ok {
					return fmt.Errorf("%s is not type %s, actual value: %v", name, expectedType, actualValue)
				}

				if err != nil {
					return fmt.Errorf("failed to convert %s to %s: %w", name, expectedType, err)
				}
				return nil
			}
			validateSchemaFunc = func(name string, val any) error {
				err := s.VisitJSON(val)
				if err != nil {
					var e *openapi3.SchemaError
					if errors.As(err, &e) {
						return errorx.Errorf("invalid %s: %v", name, e.Reason)
					}
					return err
				}
				return nil
			}
		)

		var (
			val any
			ok  bool
			err error
		)

		switch {
		default:
			_, ok, err := GetAny[any](v)
			if !ok || err != nil {
				return errTypeFunc(n, ok, err, s.Type, v)
			}

			continue
		case s.Type == openapi3.TypeString:
			val, ok, err = GetString(v)
			if !ok || err != nil {
				return errTypeFunc(n, ok, err, s.Type, v)
			}
		case s.Type == openapi3.TypeBoolean:
			val, ok, err = GetBool(v)
			if !ok || err != nil {
				return errTypeFunc(n, ok, err, s.Type, v)
			}
		case s.Type == openapi3.TypeInteger:
			val, ok, err = GetInt(v)
			if !ok || err != nil {
				return errTypeFunc(n, ok, err, s.Type, v)
			}
		case s.Type == openapi3.TypeNumber:
			val, ok, err = GetNumber(v)
			if !ok || err != nil {
				return errTypeFunc(n, ok, err, s.Type, v)
			}
		case HasAnyTypes(s):
			// Skip validate for any type.
			continue
		case s.Type == openapi3.TypeArray:
			val, ok, err = GetSlice[any](v)
			if !ok || err != nil {
				return errTypeFunc(n, ok, err, s.Type, v)
			}
		case s.Type == openapi3.TypeObject:
			val, ok, err = GetMap[any](v)
			if !ok || err != nil {
				return errTypeFunc(n, ok, err, s.Type, v)
			}
		}

		err = validateSchemaFunc(n, val)
		if err != nil {
			return err
		}
	}

	return nil
}

// ValidateWith validates the property value with the given schemas.


func NewBinaryLiteralFromUint(value uint64, byteSize int) BinaryLiteral {
	if byteSize != -1 && (byteSize < 1 || byteSize > 8) {
		panic("Invalid byteSize")
	}
	buf := make([]byte, 8)
	binary.BigEndian.PutUint64(buf, value)
	if byteSize == -1 {
		buf = trimLeadingZeroBytes(buf)
	} else {
		buf = buf[8-byteSize:]
	}
	return buf
}

// NewBinaryLiteralFromUint creates a new BinaryLiteral instance by the given uint value in BitEndian.
// byteSize will be used as the length of the new BinaryLiteral, with leading bytes filled to zero.
// If byteSize is -1, the leading zeros in new BinaryLiteral will be trimmed.


func ParseDatetimeFromNum(sc *stmtctx.StatementContext, num int64) (Time, error) {
	return ParseTimeFromNum(sc, num, mysql.TypeDatetime, DefaultFsp)
}

// ParseDatetimeFromNum is a helper function wrapping ParseTimeFromNum with datetime type and default fsp.


func MatchesPodSpec(rules []types.ResourceRule) bool {
	for _, r := range rules {
		gr := r.ToGVR().GroupResource()
		if defaultPodSpecResources[gr] {
			return true
		}
	}
	return false
}

// MatchesPodSpec returns true if any rule matches a Pod spec


func WithVectorDimensions(size int) Option {
	return func(p *Store) {
		p.vectorDimensions = size
	}
}

// WithVectorDimensions is an option for specifying the vector size.


func MappedBits[T comparable](values []T, maps map[T]Bits, opts ...BuilderOpt[T]) Bits {
	bo := builderOpts[T]{}
	for _, opt := range opts {
		opt(&bo)
	}

	b := Bits(0)
	for _, value := range values {
		for _, t := range bo.transform {
			value = t(value)
		}
		if val, ok := maps[value]; ok {
			b |= val
		}
	}
	return b
}

// MappedBits builds a Bits map from a set of values (e.g. strings) that are mapped in the form
// value --> corresponding Bits value
// in the "maps" constructor argument


func MarshalText(w io.Writer, m Message) error { return defaultTextMarshaler.Marshal(w, m) }

// MarshalText writes the proto text format of m to w.


func xorInGeneric(d *state, buf []byte) {
	n := len(buf) / 8

	for i := 0; i < n; i++ {
		a := binary.LittleEndian.Uint64(buf)
		d.a[i] ^= a
		buf = buf[8:]
	}
}

// xorInGeneric xors the bytes in buf into the state; it
// makes no non-portable assumptions about memory layout
// or alignment.


func Symlink(path string, link string) (err error) {
	var _p0 *byte
	_p0, err = BytePtrFromString(path)
	if err != nil {
		return
	}
	var _p1 *byte
	_p1, err = BytePtrFromString(link)
	if err != nil {
		return
	}
	_, _, e1 := Syscall(SYS_SYMLINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0)
	if e1 != 0 {
		err = errnoErr(e1)
	}
	return
}

// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT


func Time(t *Time_t) (tt Time_t, err error) {
	r0, _, e1 := RawSyscall(SYS_TIME, uintptr(unsafe.Pointer(t)), 0, 0)
	tt = Time_t(r0)
	if e1 != 0 {
		err = errnoErr(e1)
	}
	return
}


func socket(domain int, typ int, proto int) (fd int, err error) {
	r0, _, e1 := RawSyscall(SYS_SOCKET, uintptr(domain), uintptr(typ), uintptr(proto))
	fd = int(r0)
	if e1 != 0 {
		err = errnoErr(e1)
	}
	return
}


func munmap(addr uintptr, length uintptr) (err error) {
	_, _, e1 := syscall_syscall(SYS_MUNMAP, uintptr(addr), uintptr(length), 0)
	if e1 != 0 {
		err = errnoErr(e1)
	}
	return
}


func Renameat(olddirfd int, oldpath string, newdirfd int, newpath string) (err error) {
	var _p0 *byte
	_p0, err = BytePtrFromString(oldpath)
	if err != nil {
		return
	}
	var _p1 *byte
	_p1, err = BytePtrFromString(newpath)
	if err != nil {
		return
	}
	_, _, e1 := Syscall6(SYS_RENAMEAT, uintptr(olddirfd), uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1)), 0, 0)
	if e1 != 0 {
		err = errnoErr(e1)
	}
	return
}


func NewClientTLSFromCert(cp *x509.CertPool, serverNameOverride string) TransportCredentials {
	return NewTLS(&tls.Config{ServerName: serverNameOverride, RootCAs: cp})
}

// NewClientTLSFromCert constructs TLS credentials from the provided root
// certificate authority certificate(s) to validate server connections. If
// certificates to establish the identity of the client need to be included in
// the credentials (eg: for mTLS), use NewTLS instead, where a complete
// tls.Config can be specified.
// serverNameOverride is for testing only. If set to a non empty string,
// it will override the virtual host name of authority (e.g. :authority header
// field) in requests.


func Close(fd int) (err error) {
	_, _, e1 := syscall_syscall(libc_close_trampoline_addr, uintptr(fd), 0, 0)
	if e1 != 0 {
		err = errnoErr(e1)
	}
	return
}

//go:cgo_import_dynamic libc_clock_gettime clock_gettime "libc.so"
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT


func (l *HandlerList) Swap(name string, replace NamedHandler) bool {
	var swapped bool

	for i := 0; i < len(l.list); i++ {
		if l.list[i].Name == name {
			l.list[i] = replace
			swapped = true
		}
	}

	return swapped
}

// Swap will swap out all handlers matching the name passed in. The matched
// handlers will be swapped in. True is returned if the handlers were swapped.


func mapassign_faststr(t *rt.GoType, h unsafe.Pointer, s string) unsafe.Pointer

//go:linkname mapassign_faststr runtime.mapassign_faststr
//goland:noinspection GoUnusedParameter


func (r Response) AddHeader(header string, value string) Response {
	r.Header().Add(header, value)
	return r
}

// AddHeader is a shortcut for .Header().Add(header,value)


func (group *RouterGroup) Any(relativePath string, handlers ...HandlerFunc) IRoutes {
	for _, method := range anyMethods {
		group.handle(method, relativePath, handlers)
	}

	return group.returnObj()
}

// Any registers a route that matches all the HTTP methods.
// GET, POST, PUT, PATCH, HEAD, OPTIONS, DELETE, CONNECT, TRACE.


func Float64Value(v *float64) float64 {
	if v != nil {
		return *v
	}
	return 0
}

// Float64Value returns the value of the float64 pointer passed in or
// 0 if the pointer is nil.


func isTIGER128(fl FieldLevel) bool {
	return tiger128Regex.MatchString(fl.Field().String())
}

// isTIGER128 is the validation function for validating if the field's value is a valid TIGER128.


func appendMerge(target, sub []int) []int {
	lt, ls := len(target), len(sub)
	out := make([]int, 0, lt+ls)

	for x, y := 0, 0; x < lt || y < ls; {
		if x >= lt {
			out = append(out, sub[y:]...)
			break
		}

		if y >= ls {
			out = append(out, target[x:]...)
			break
		}

		xValue := target[x]
		yValue := sub[y]

		switch {

		case xValue == yValue:
			out = append(out, xValue)
			x++
			y++

		case xValue < yValue:
			out = append(out, xValue)
			x++

		case yValue < xValue:
			out = append(out, yValue)
			y++

		}
	}

	target = append(target[:0], out...)

	return target
}

// appendMerge merges and sorts given already SORTED and UNIQUE segments.


func cleanupSurroundingIdentical(groups []diffStats, eq func(i, j int) bool) []diffStats {
	var ix, iy int // indexes into sequence x and y
	for i, ds := range groups {
		// Handle equal group.
		if ds.NumDiff() == 0 {
			ix += ds.NumIdentical
			iy += ds.NumIdentical
			continue
		}

		// Handle unequal group.
		nx := ds.NumIdentical + ds.NumRemoved + ds.NumModified
		ny := ds.NumIdentical + ds.NumInserted + ds.NumModified
		var numLeadingIdentical, numTrailingIdentical int
		for j := 0; j < nx && j < ny && eq(ix+j, iy+j); j++ {
			numLeadingIdentical++
		}
		for j := 0; j < nx && j < ny && eq(ix+nx-1-j, iy+ny-1-j); j++ {
			numTrailingIdentical++
		}
		if numIdentical := numLeadingIdentical + numTrailingIdentical; numIdentical > 0 {
			if numLeadingIdentical > 0 {
				// Remove leading identical span from this group and
				// insert it into the preceding group.
				if i-1 >= 0 {
					groups[i-1].NumIdentical += numLeadingIdentical
				} else {
					// No preceding group exists, so prepend a new group,
					// but do so after we finish iterating over all groups.
					defer func() {
						groups = append([]diffStats{{Name: groups[0].Name, NumIdentical: numLeadingIdentical}}, groups...)
					}()
				}
				// Increment indexes since the preceding group would have handled this.
				ix += numLeadingIdentical
				iy += numLeadingIdentical
			}
			if numTrailingIdentical > 0 {
				// Remove trailing identical span from this group and
				// insert it into the succeeding group.
				if i+1 < len(groups) {
					groups[i+1].NumIdentical += numTrailingIdentical
				} else {
					// No succeeding group exists, so append a new group,
					// but do so after we finish iterating over all groups.
					defer func() {
						groups = append(groups, diffStats{Name: groups[len(groups)-1].Name, NumIdentical: numTrailingIdentical})
					}()
				}
				// Do not increment indexes since the succeeding group will handle this.
			}

			// Update this group since some identical elements were removed.
			nx -= numIdentical
			ny -= numIdentical
			groups[i] = diffStats{Name: ds.Name, NumRemoved: nx, NumInserted: ny}
		}
		ix += nx
		iy += ny
	}
	return groups
}

// cleanupSurroundingIdentical scans through all unequal groups, and
// moves any leading sequence of equal elements to the preceding equal group and
// moves and trailing sequence of equal elements to the succeeding equal group.
//
// This is necessary since coalesceInterveningIdentical may coalesce edit groups
// together such that leading/trailing spans of equal elements becomes possible.
// Note that this can occur even with an optimal diffing algorithm.
//
// Example:
//
//	Input: [
//		{NumIdentical: 61},
//		{NumIdentical: 1 , NumRemoved: 11, NumInserted: 2}, // assume 3 leading identical elements
//		{NumIdentical: 67},
//		{NumIdentical: 7, NumRemoved: 12, NumInserted: 3},  // assume 10 trailing identical elements
//		{NumIdentical: 54},
//	]
//	Output: [
//		{NumIdentical: 64}, // incremented by 3
//		{NumRemoved: 9},
//		{NumIdentical: 67},
//		{NumRemoved: 9},
//		{NumIdentical: 64}, // incremented by 10
//	]


func Setns(ns NsHandle, nstype int) (err error) {
	return ErrNotImplemented
}

// Setns sets namespace using golang.org/x/sys/unix.Setns on Linux. It
// is not implemented on other platforms.
//
// Deprecated: Use golang.org/x/sys/unix.Setns instead.


func MessagingServicebusMessageEnqueuedTime(val int) attribute.KeyValue {
	return MessagingServicebusMessageEnqueuedTimeKey.Int(val)
}

// MessagingServicebusMessageEnqueuedTime returns an attribute KeyValue
// conforming to the "messaging.servicebus.message.enqueued_time" semantic
// conventions. It represents the UTC epoch seconds at which the message has
// been accepted and stored in the entity.


func (t TraceID) IsValid() bool {
	return !bytes.Equal(t[:], nilTraceID[:])
}

// IsValid checks whether the trace TraceID is valid. A valid trace ID does
// not consist of zeros only.


func LowercaseLevelEncoder(l Level, enc PrimitiveArrayEncoder) {
	enc.AppendString(l.String())
}

// LowercaseLevelEncoder serializes a Level to a lowercase string. For example,
// InfoLevel is serialized to "info".


func ToUnicode(s string) (string, error) {
	return Punycode.process(s, false)
}

// ToUnicode is a wrapper for Punycode.ToUnicode.


func Setegid(egid int) (err error) {
	_, _, e1 := RawSyscall(SYS_SETEGID, uintptr(egid), 0, 0)
	if e1 != 0 {
		err = errnoErr(e1)
	}
	return
}


func Seek(fd int, offset int64, whence int) (newoffset int64, err error) {
	r0, _, e1 := Syscall(SYS_LSEEK, uintptr(fd), uintptr(offset), uintptr(whence))
	newoffset = int64(r0)
	if e1 != 0 {
		err = errnoErr(e1)
	}
	return
}


func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) {
	var _p0 unsafe.Pointer
	if len(buf) > 0 {
		_p0 = unsafe.Pointer(&buf[0])
	} else {
		_p0 = unsafe.Pointer(&_zero)
	}
	_, _, e1 := Syscall6(SYS_SENDTO, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen))
	if e1 != 0 {
		err = errnoErr(e1)
	}
	return
}


func ForceCodec(codec encoding.Codec) CallOption {
	return ForceCodecCallOption{Codec: codec}
}

// ForceCodec returns a CallOption that will set codec to be used for all
// request and response messages for a call. The result of calling Name() will
// be used as the content-subtype after converting to lowercase, unless
// CallContentSubtype is also used.
//
// See Content-Type on
// https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#requests for
// more details. Also see the documentation on RegisterCodec and
// CallContentSubtype for more details on the interaction between Codec and
// content-subtype.
//
// This function is provided for advanced users; prefer to use only
// CallContentSubtype to select a registered codec instead.
//
// # Experimental
//
// Notice: This API is EXPERIMENTAL and may be changed or removed in a
// later release.


func (v Value) IsValid() bool {
	return v.typ != nilType
}

// IsValid reports whether v is populated with a value.


func addKnownTypes(scheme *runtime.Scheme) error {
	scheme.AddKnownTypes(SchemeGroupVersion,
		&Ingress{},
		&IngressList{},
		&IngressClass{},
		&IngressClassList{},
	)
	// Add the watch version that applies
	metav1.AddToGroupVersion(scheme, SchemeGroupVersion)
	return nil
}

// Adds the list of known types to the given scheme.


func diffMaps(original, modified map[string]interface{}, schema LookupPatchMeta, diffOptions DiffOptions) (map[string]interface{}, error) {
	patch := map[string]interface{}{}

	// This will be used to build the $retainKeys directive sent in the patch
	retainKeysList := make([]interface{}, 0, len(modified))

	// Compare each value in the modified map against the value in the original map
	for key, modifiedValue := range modified {
		// Get the underlying type for pointers
		if diffOptions.BuildRetainKeysDirective && modifiedValue != nil {
			retainKeysList = append(retainKeysList, key)
		}

		originalValue, ok := original[key]
		if !ok {
			// Key was added, so add to patch
			if !diffOptions.IgnoreChangesAndAdditions {
				patch[key] = modifiedValue
			}
			continue
		}

		// The patch may have a patch directive
		// TODO: figure out if we need this. This shouldn't be needed by apply. When would the original map have patch directives in it?
		foundDirectiveMarker, err := handleDirectiveMarker(key, originalValue, modifiedValue, patch)
		if err != nil {
			return nil, err
		}
		if foundDirectiveMarker {
			continue
		}

		if reflect.TypeOf(originalValue) != reflect.TypeOf(modifiedValue) {
			// Types have changed, so add to patch
			if !diffOptions.IgnoreChangesAndAdditions {
				patch[key] = modifiedValue
			}
			continue
		}

		// Types are the same, so compare values
		switch originalValueTyped := originalValue.(type) {
		case map[string]interface{}:
			modifiedValueTyped := modifiedValue.(map[string]interface{})
			err = handleMapDiff(key, originalValueTyped, modifiedValueTyped, patch, schema, diffOptions)
		case []interface{}:
			modifiedValueTyped := modifiedValue.([]interface{})
			err = handleSliceDiff(key, originalValueTyped, modifiedValueTyped, patch, schema, diffOptions)
		default:
			replacePatchFieldIfNotEqual(key, originalValue, modifiedValue, patch, diffOptions)
		}
		if err != nil {
			return nil, err
		}
	}

	updatePatchIfMissing(original, modified, patch, diffOptions)
	// Insert the retainKeysList iff there are values present in the retainKeysList and
	// either of the following is true:
	// - the patch is not empty
	// - there are additional field in original that need to be cleared
	if len(retainKeysList) > 0 &&
		(len(patch) > 0 || hasAdditionalNewField(original, modified)) {
		patch[retainKeysDirective] = sortScalars(retainKeysList)
	}
	return patch, nil
}

// Returns a (recursive) strategic merge patch that yields modified when applied to original.
// Including:
// - Adding fields to the patch present in modified, missing from original
// - Setting fields to the patch present in modified and original with different values
// - Delete fields present in original, missing from modified through
// - IFF map field - set to nil in patch
// - IFF list of maps && merge strategy - use deleteDirective for the elements
// - IFF list of primitives && merge strategy - use parallel deletion list
// - IFF list of maps or primitives with replace strategy (default) - set patch value to the value in modified
// - Build $retainKeys directive for fields with retainKeys patch strategy


func ExtractReplicaSet(replicaSet *extensionsv1beta1.ReplicaSet, fieldManager string) (*ReplicaSetApplyConfiguration, error) {
	return extractReplicaSet(replicaSet, fieldManager, "")
}

// ExtractReplicaSet extracts the applied configuration owned by fieldManager from
// replicaSet. If no managedFields are found in replicaSet for fieldManager, a
// ReplicaSetApplyConfiguration is returned with only the Name, Namespace (if applicable),
// APIVersion and Kind populated. It is possible that no managed fields were found for because other
// field managers have taken ownership of all the fields previously owned by fieldManager, or because
// the fieldManager never owned fields any fields.
// replicaSet must be a unmodified ReplicaSet API object that was retrieved from the Kubernetes API.
// ExtractReplicaSet provides a way to perform a extract/modify-in-place/apply workflow.
// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously
// applied if another fieldManager has updated or force applied any of the previously applied fields.
// Experimental!


func (r *Ref) IsValidURI(basepaths ...string) bool {
	if r.String() == "" {
		return true
	}

	v := r.RemoteURI()
	if v == "" {
		return true
	}

	if r.HasFullURL {
		rr, err := http.Get(v)
		if err != nil {
			return false
		}

		return rr.StatusCode/100 == 2
	}

	if !(r.HasFileScheme || r.HasFullFilePath || r.HasURLPathOnly) {
		return false
	}

	// check for local file
	pth := v
	if r.HasURLPathOnly {
		base := "."
		if len(basepaths) > 0 {
			base = filepath.Dir(filepath.Join(basepaths...))
		}
		p, e := filepath.Abs(filepath.ToSlash(filepath.Join(base, pth)))
		if e != nil {
			return false
		}
		pth = p
	}

	fi, err := os.Stat(filepath.ToSlash(pth))
	if err != nil {
		return false
	}

	return !fi.IsDir()
}

// IsValidURI returns true when the url the ref points to can be found


func MultiMutatingHandler(handlers ...Handler) Handler {
	return multiMutating(handlers)
}

// MultiMutatingHandler combines multiple mutating webhook handlers into a single
// mutating webhook handler.  Handlers are called in sequential order, and the first
// `allowed: false`	response may short-circuit the rest.  Users must take care to
// ensure patches are disjoint.


func fileExists(filePath string) bool {
	if _, err := os.Stat(filePath); err != nil {
		if os.IsNotExist(err) {
			return false
		}
	}

	return true
}

// fileExists reports whether the named file or directory exists.


func (u userPrivateInfoDo) Save(values ...*model.UserPrivateInfo) error {
	if len(values) == 0 {
		return nil
	}
	return u.DO.Save(values)
}

// Save : !!! underlying implementation is different with GORM
// The method is equivalent to executing the statement: db.Clauses(clause.OnConflict{UpdateAll: true}).Create(values)


func NewDBPathsFromData(paths []string, target_sizes []uint64) []*DBPath {
	dbpaths := make([]*DBPath, len(paths))
	for i, path := range paths {
		targetSize := target_sizes[i]
		dbpaths[i] = NewDBPath(path, targetSize)
	}

	return dbpaths
}

// NewDBPathsFromData creates a slice with allocated DBPath objects
// from paths and target_sizes.


func isNewline(lg lineGroup) bool {
	return len(lg.comment) == 0 && len(lg.lines) == 1 && strings.TrimSpace(lg.lines[0]) == ""
}

// isNewline determines if lg is just an empty line.


func (m *Fixed32NotIn) Validate() error {
	return m.validate(false)
}

// Validate checks the field values on Fixed32NotIn with the rules defined in
// the proto definition for this message. If any rules are violated, the first
// error encountered is returned, or nil if there are no violations.


func TimeValueMap(src map[string]*time.Time) map[string]time.Time {
	dst := make(map[string]time.Time)
	for k, val := range src {
		if val != nil {
			dst[k] = *val
		}
	}
	return dst
}

// TimeValueMap converts a string map of time.Time pointers into a string
// map of time.Time values


func RegisterFieldEncoder(typ string, field string, encoder ValEncoder) {
	fieldEncoders[fmt.Sprintf("%s/%s", typ, field)] = encoder
}

// RegisterFieldEncoder register TypeEncoder for a struct field


func (b *Buffer) Size() int {
	size := len(b.Buf)
	for _, buf := range b.bufs {
		size += len(buf)
	}
	return size
}

// Size computes the size of a buffer by adding sizes of every chunk.


func socket(domain int, typ int, proto int) (fd int, err error) {
	r0, er := C.socket(C.int(domain), C.int(typ), C.int(proto))
	fd = int(r0)
	if r0 == -1 && er != nil {
		err = er
	}
	return
}

// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT


func Fadvise(fd int, offset int64, length int64, advice int) (err error) {
	_, _, e1 := Syscall6(SYS_FADVISE64, uintptr(fd), uintptr(offset), uintptr(length), uintptr(advice), 0, 0)
	if e1 != 0 {
		err = errnoErr(e1)
	}
	return
}


func Utime(path string, buf *Utimbuf) (err error) {
	var _p0 *byte
	_p0, err = BytePtrFromString(path)
	if err != nil {
		return
	}
	_, _, e1 := Syscall(SYS_UTIME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(buf)), 0)
	if e1 != 0 {
		err = errnoErr(e1)
	}
	return
}


func IoctlGetPtmget(fd int, req uint) (*Ptmget, error) {
	var value Ptmget
	err := ioctlPtr(fd, req, unsafe.Pointer(&value))
	return &value, err
}

//sys	ioctl(fd int, req uint, arg uintptr) (err error)
//sys	ioctlPtr(fd int, req uint, arg unsafe.Pointer) (err error) = SYS_IOCTL
//sys	sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) = SYS___SYSCTL


func getgroups(ngid int, gid *_Gid_t) (n int, err error) {
	r0, _, e1 := syscall_rawSyscall(libc_getgroups_trampoline_addr, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0)
	n = int(r0)
	if e1 != 0 {
		err = errnoErr(e1)
	}
	return
}


func Fadvise(fd int, offset int64, length int64, advice int) (err error) {
	_, _, e1 := Syscall9(SYS_POSIX_FADVISE, uintptr(fd), 0, uintptr(offset), uintptr(offset>>32), uintptr(length), uintptr(length>>32), uintptr(advice), 0, 0)
	if e1 != 0 {
		err = errnoErr(e1)
	}
	return
}


func (t *bidiTrie) lookupValue(n uint32, b byte) uint8 {
	switch {
	default:
		return uint8(bidiValues[n<<6+uint32(b)])
	}
}

// lookupValue determines the type of block n and looks up the value for b.


func (e *Encoder) Snapshot() encoderState {
	return e.encoderState
}

// Snapshot returns the current snapshot for use in Reset.


func MustParse(str string) Quantity {
	q, err := ParseQuantity(str)
	if err != nil {
		panic(fmt.Errorf("cannot parse '%v': %v", str, err))
	}
	return q
}

// MustParse turns the given string into a quantity or panics; for tests
// or other cases where you know the string is valid.


func RollingUpdateDeployment() *RollingUpdateDeploymentApplyConfiguration {
	return &RollingUpdateDeploymentApplyConfiguration{}
}

// RollingUpdateDeploymentApplyConfiguration constructs a declarative configuration of the RollingUpdateDeployment type for use with
// apply.


func IngressTLS() *IngressTLSApplyConfiguration {
	return &IngressTLSApplyConfiguration{}
}

// IngressTLSApplyConfiguration constructs a declarative configuration of the IngressTLS type for use with
// apply.


func ExtractResourceSliceStatus(resourceSlice *resourcev1alpha3.ResourceSlice, fieldManager string) (*ResourceSliceApplyConfiguration, error) {
	return extractResourceSlice(resourceSlice, fieldManager, "status")
}

// ExtractResourceSliceStatus is the same as ExtractResourceSlice except
// that it extracts the status subresource applied configuration.
// Experimental!


func CreatedAtIn(vs ...time.Time) predicate.Integration {
	return predicate.Integration(sql.FieldIn(FieldCreatedAt, vs...))
}

// CreatedAtIn applies the In predicate on the "created_at" field.


func AnyToInt(i any) (int, error) {
	v, err := AnyToInt64(i)
	if err != nil {
		return 0, err
	}

	// int 兼容32位和64位系统
	//if int64(int(v)) != v {
	//	return 0, ErrValOut
	//}

	return int(v), nil
}


func ChallengeBlocks(domain, keyAuth string) ([]byte, []byte, error) {
	// Compute the SHA-256 digest of the key authorization.
	zBytes := sha256.Sum256([]byte(keyAuth))

	value, err := asn1.Marshal(zBytes[:sha256.Size])
	if err != nil {
		return nil, nil, err
	}

	// Add the keyAuth digest as the acmeValidation-v1 extension
	// (marked as critical such that it won't be used by non-ACME software).
	// Reference: https://tools.ietf.org/html/draft-ietf-acme-tls-alpn-05#section-3
	extensions := []pkix.Extension{
		{
			Id:       idPeAcmeIdentifierV1,
			Critical: true,
			Value:    value,
		},
	}

	// Generate a new RSA key for the certificates.
	tempPrivateKey, err := certcrypto.GeneratePrivateKey(certcrypto.RSA2048)
	if err != nil {
		return nil, nil, err
	}

	rsaPrivateKey := tempPrivateKey.(*rsa.PrivateKey)

	// Generate the PEM certificate using the provided private key, domain, and extra extensions.
	tempCertPEM, err := certcrypto.GeneratePemCert(rsaPrivateKey, domain, extensions)
	if err != nil {
		return nil, nil, err
	}

	// Encode the private key into a PEM format. We'll need to use it to generate the x509 keypair.
	rsaPrivatePEM := certcrypto.PEMEncode(rsaPrivateKey)

	return tempCertPEM, rsaPrivatePEM, nil
}

// ChallengeBlocks returns PEM blocks (certPEMBlock, keyPEMBlock) with the acmeValidation-v1 extension
// and domain name for the `tls-alpn-01` challenge.


func callgetsystemcfg(label int) (r1 uintptr, e1 Errno) {
	r1 = uintptr(C.getsystemcfg(C.int(label)))
	e1 = syscall.GetErrno()
	return
}


func ExtattrListFile(file string, attrnamespace int, data uintptr, nbytes int) (ret int, err error) {
	var _p0 *byte
	_p0, err = BytePtrFromString(file)
	if err != nil {
		return
	}
	r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0)
	ret = int(r0)
	if e1 != 0 {
		err = errnoErr(e1)
	}
	return
}


func Setrlimit(resource int, rlim *Rlimit) (err error) {
	_, e1 := callsetrlimit(resource, uintptr(unsafe.Pointer(rlim)))
	if e1 != 0 {
		err = errnoErr(e1)
	}
	return
}


func ExtattrGetFd(fd int, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) {
	var _p0 *byte
	_p0, err = BytePtrFromString(attrname)
	if err != nil {
		return
	}
	r0, _, e1 := Syscall6(SYS_EXTATTR_GET_FD, uintptr(fd), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p0)), uintptr(data), uintptr(nbytes), 0)
	ret = int(r0)
	if e1 != 0 {
		err = errnoErr(e1)
	}
	return
}


func Access(path string, mode uint32) (err error) {
	var _p0 *byte
	_p0, err = BytePtrFromString(path)
	if err != nil {
		return
	}
	_, _, e1 := Syscall(SYS_ACCESS, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0)
	if e1 != 0 {
		err = errnoErr(e1)
	}
	return
}


func Kill(pid int, signum syscall.Signal) (err error) {
	_, _, e1 := Syscall(SYS_KILL, uintptr(pid), uintptr(signum), 0)
	if e1 != 0 {
		err = errnoErr(e1)
	}
	return
}


func ExtattrListFd(fd int, attrnamespace int, data uintptr, nbytes int) (ret int, err error) {
	r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_FD, uintptr(fd), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0)
	ret = int(r0)
	if e1 != 0 {
		err = errnoErr(e1)
	}
	return
}


func callfchown(fd int, uid int, gid int) (r1 uintptr, e1 Errno) {
	r1, _, e1 = syscall6(uintptr(unsafe.Pointer(&libc_fchown)), 3, uintptr(fd), uintptr(uid), uintptr(gid), 0, 0, 0)
	return
}


func KeyctlString(cmd int, id int) (string, error) {
	// We must loop as the string data may change in between the syscalls.
	// We could allocate a large buffer here to reduce the chance that the
	// syscall needs to be called twice; however, this is unnecessary as
	// the performance loss is negligible.
	var buffer []byte
	for {
		// Try to fill the buffer with data
		length, err := KeyctlBuffer(cmd, id, buffer, 0)
		if err != nil {
			return "", err
		}

		// Check if the data was written
		if length <= len(buffer) {
			// Exclude the null terminator
			return string(buffer[:length-1]), nil
		}

		// Make a bigger buffer if needed
		buffer = make([]byte, length)
	}
}

// Keyctl Commands (http://man7.org/linux/man-pages/man2/keyctl.2.html)
// KeyctlInt calls keyctl commands in which each argument is an int.
// These commands are KEYCTL_REVOKE, KEYCTL_CHOWN, KEYCTL_CLEAR, KEYCTL_LINK,
// KEYCTL_UNLINK, KEYCTL_NEGATE, KEYCTL_SET_REQKEY_KEYRING, KEYCTL_SET_TIMEOUT,
// KEYCTL_ASSUME_AUTHORITY, KEYCTL_SESSION_TO_PARENT, KEYCTL_REJECT,
// KEYCTL_INVALIDATE, and KEYCTL_GET_PERSISTENT.
//sys	KeyctlInt(cmd int, arg2 int, arg3 int, arg4 int, arg5 int) (ret int, err error) = SYS_KEYCTL
// KeyctlBuffer calls keyctl commands in which the third and fourth
// arguments are a buffer and its length, respectively.
// These commands are KEYCTL_UPDATE, KEYCTL_READ, and KEYCTL_INSTANTIATE.
//sys	KeyctlBuffer(cmd int, arg2 int, buf []byte, arg5 int) (ret int, err error) = SYS_KEYCTL
// KeyctlString calls keyctl commands which return a string.
// These commands are KEYCTL_DESCRIBE and KEYCTL_GET_SECURITY.


func NewError(reason string) *Error {
	return &Error{reason: reason}
}


func (f *FlagSet) Changed(name string) bool {
	flag := f.Lookup(name)
	// If a flag doesn't exist, it wasn't changed....
	if flag == nil {
		return false
	}
	return flag.Changed
}

// Changed returns true if the flag was explicitly set during Parse() and false
// otherwise


func Fstat(fd int, stat *Stat_t) (err error) {
	_, _, e1 := Syscall(SYS_FSTAT, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0)
	if e1 != 0 {
		err = errnoErr(e1)
	}
	return
}


func pread(fd int, p []byte, offset int64) (n int, err error) {
	var _p0 unsafe.Pointer
	if len(p) > 0 {
		_p0 = unsafe.Pointer(&p[0])
	} else {
		_p0 = unsafe.Pointer(&_zero)
	}
	r0, _, e1 := syscall_syscall6(libc_pread_trampoline_addr, uintptr(fd), uintptr(_p0), uintptr(len(p)), 0, uintptr(offset), uintptr(offset>>32))
	n = int(r0)
	if e1 != 0 {
		err = errnoErr(e1)
	}
	return
}

//go:cgo_import_dynamic libc_pathconf pathconf "libc.so"
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT


func Access(path string, mode uint32) (err error) {
	return Faccessat(AT_FDCWD, path, mode, 0)
}


func Sync() {
	SyscallNoError(SYS_SYNC, 0, 0, 0)
	return
}


func (m *FeedbackSummarizationsReactionsMutation) FieldCleared(name string) bool {
	_, ok := m.clearedFields[name]
	return ok
}

// FieldCleared returns a boolean indicating if a field with the given name was
// cleared in this mutation.


func Linkat(pathfd int, path string, linkfd int, link string, flags int) (err error) {
	var _p0 *byte
	_p0, err = BytePtrFromString(path)
	if err != nil {
		return
	}
	var _p1 *byte
	_p1, err = BytePtrFromString(link)
	if err != nil {
		return
	}
	_, _, e1 := Syscall6(SYS_LINKAT, uintptr(pathfd), uintptr(unsafe.Pointer(_p0)), uintptr(linkfd), uintptr(unsafe.Pointer(_p1)), uintptr(flags), 0)
	if e1 != 0 {
		err = errnoErr(e1)
	}
	return
}


func mknodat(fd int, path string, mode uint32, dev int) (err error) {
	var _p0 *byte
	_p0, err = BytePtrFromString(path)
	if err != nil {
		return
	}
	_, _, e1 := Syscall6(SYS_MKNODAT, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev), 0, 0)
	if e1 != 0 {
		err = errnoErr(e1)
	}
	return
}


func Tee(rfd int, wfd int, len int, flags int) (n int64, err error) {
	r0, _, e1 := Syscall6(SYS_TEE, uintptr(rfd), uintptr(wfd), uintptr(len), uintptr(flags), 0, 0)
	n = int64(r0)
	if e1 != 0 {
		err = errnoErr(e1)
	}
	return
}


func Fclonefileat(srcDirfd int, dstDirfd int, dst string, flags int) (err error) {
	var _p0 *byte
	_p0, err = BytePtrFromString(dst)
	if err != nil {
		return
	}
	_, _, e1 := syscall_syscall6(libc_fclonefileat_trampoline_addr, uintptr(srcDirfd), uintptr(dstDirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0, 0)
	if e1 != 0 {
		err = errnoErr(e1)
	}
	return
}

//go:cgo_import_dynamic libc_fchownat fchownat "/usr/lib/libSystem.B.dylib"
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT


func Setresgid(rgid int, egid int, sgid int) (err error) {
	_, _, e1 := RawSyscall(SYS_SETRESGID, uintptr(rgid), uintptr(egid), uintptr(sgid))
	if e1 != 0 {
		err = errnoErr(e1)
	}
	return
}


func (r *Types) RegisterExtension(xt protoreflect.ExtensionType) error {
	// Under rare circumstances getting the descriptor might recursively
	// examine the registry, so fetch it before locking.
	//
	// A known case where this can happen: Fetching the TypeDescriptor for a
	// legacy ExtensionDesc can consult the global registry.
	xd := xt.TypeDescriptor()

	if r == GlobalTypes {
		globalMutex.Lock()
		defer globalMutex.Unlock()
	}

	field := xd.Number()
	message := xd.ContainingMessage().FullName()
	if prev := r.extensionsByMessage[message][field]; prev != nil {
		err := errors.New("extension number %d is already registered on message %v", field, message)
		err = amendErrorWithCaller(err, prev, xt)
		if !(r == GlobalTypes && ignoreConflict(xd, err)) {
			return err
		}
	}

	if err := r.register("extension", xd, xt); err != nil {
		return err
	}
	if r.extensionsByMessage == nil {
		r.extensionsByMessage = make(extensionsByMessage)
	}
	if r.extensionsByMessage[message] == nil {
		r.extensionsByMessage[message] = make(extensionsByNumber)
	}
	r.extensionsByMessage[message][field] = xt
	r.numExtensions++
	return nil
}

// RegisterExtension registers the provided extension type.
//
// If a naming conflict occurs, the type is not registered and an error is returned.


func (ev binlogEvent) NextPosition() uint32 {
	return binary.LittleEndian.Uint32(ev.Bytes()[13 : 13+4])
}

// NextPosition returns the nextPosition field from the header


func ConvertStateToMySQLErrorCode(state vterrors.State) string {
	s := getStateToMySQLState(state)
	return strconv.Itoa(s.num)
}

// ConvertStateToMySQLErrorCode returns MySQL error code for the given vterrors.State
// If the state is == 0, an empty string is returned


func checkTablesCount(t *testing.T, tablet *cluster.Vttablet, showTableName string, expectCount int) {
	query := fmt.Sprintf(`show tables like '%%%s%%';`, showTableName)
	queryResult, err := tablet.VttabletProcess.QueryTablet(query, keyspaceName, true)
	require.Nil(t, err)
	assert.Equal(t, expectCount, len(queryResult.Rows))
}

// checkTablesCount checks the number of tables in the given tablet


func (node *TruncateTable) GetToTables() TableNames {
	return nil
}

// GetToTables implements the DDLStatement interface


func (bs Bitset) AndNot(b2 Bitset) Bitset {
	if len(b2) == 0 {
		return bs
	}

	merged := make([]byte, len(bs))
	m := 0

	for m = 0; m < len(bs); m++ {
		if m < len(b2) {
			merged[m] = bs[m] & ^b2[m]
		} else {
			merged[m] = bs[m]
		}
	}
	for ; m > 0; m-- {
		if merged[m-1] != 0 {
			break
		}
	}
	return toBitset(merged[:m])
}

// AndNot returns the logical AND NOT of the two Bitsets as a new Bitset


func GenerateInsertStatement(qr *rules.Rule, ifNotExist bool) (string, error) {
	insertTemplate := getInsertSQLTemplate(ifNotExist)
	parsed := sqlparser.BuildParsedQuery(insertTemplate,
		":name",
		":description",
		":priority",
		":status",
		":plans",
		":fully_qualified_table_names",
		":query_regex",
		":query_template",
		":request_ip_regex",
		":user_regex",
		":leading_comment_regex",
		":trailing_comment_regex",
		":bind_var_conds",
		":action",
		":action_args",
	)
	bindVars, err := qr.ToBindVariable()
	if err != nil {
		return "", err
	}
	bound, err := parsed.GenerateQuery(bindVars, nil)
	return bound, err
}

// GenerateInsertStatement returns the SQL statement to insert the rule into the database.


func buildSelectColumnList(t *schema.Table) string {
	buf := sqlparser.NewTrackedBuffer(nil)
	for i, c := range t.MessageInfo.Fields {
		// Column names may have to be escaped.
		if i == 0 {
			buf.Myprintf("%v", sqlparser.NewIdentifierCI(c.Name))
		} else {
			buf.Myprintf(", %v", sqlparser.NewIdentifierCI(c.Name))
		}
	}
	return buf.String()
}

// buildSelectColumnList is a convenience function that
// builds a 'select' list for the user-defined columns.


func NewCollectedStatusLister(indexer cache.Indexer) CollectedStatusLister {
	return &collectedStatusLister{indexer: indexer}
}

// NewCollectedStatusLister returns a new CollectedStatusLister.


func Lstat(name string) (os.FileInfo, error) {
	defer updateOSMetrics(osMetricLstat, name)()
	return os.Lstat(name)
}

// Lstat captures time taken to call os.Lstat


func (sses3) ParseHTTP(h http.Header) error {
	if h.Get(xhttp.AmzServerSideEncryption) != xhttp.AmzEncryptionAES {
		return ErrInvalidEncryptionMethod
	}
	return nil
}

// ParseHTTP parses the SSE-S3 related HTTP headers and checks
// whether they contain valid values.


func (o *ClientFindSubEntry) GetFilteringEnabled() bool {
	if o == nil || o.FilteringEnabled == nil {
		var ret bool
		return ret
	}
	return *o.FilteringEnabled
}

// GetFilteringEnabled returns the FilteringEnabled field value if set, zero value otherwise.


func IsCRC32(str string) bool {
	return IsHash(str, "crc32")
}

// IsCRC32 checks is a string is a CRC32 hash. Alias for `IsHash(str, "crc32")`


func NewSignalChannel() (<-chan os.Signal, func()) {
	signalC := make(chan os.Signal, 1)
	signal.Notify(signalC, signals...)
	return signalC, func() {
		signal.Stop(signalC)
		close(signalC)
	}
}

// NewSignalChannel returns a new channel for interrupt signals.
//
// Call the returned function to cancel sending to this channel.


func (p *PortOpt) Set(value string) error {
	longSyntax, err := regexp.MatchString(`\w+=\w+(,\w+=\w+)*`, value)
	if err != nil {
		return err
	}
	if longSyntax {
		csvReader := csv.NewReader(strings.NewReader(value))
		fields, err := csvReader.Read()
		if err != nil {
			return err
		}

		pConfig := swarm.PortConfig{}
		for _, field := range fields {
			parts := strings.SplitN(field, "=", 2)
			if len(parts) != 2 {
				return fmt.Errorf("invalid field %s", field)
			}

			key := strings.ToLower(parts[0])
			value := strings.ToLower(parts[1])

			switch key {
			case portOptProtocol:
				if value != string(swarm.PortConfigProtocolTCP) && value != string(swarm.PortConfigProtocolUDP) && value != string(swarm.PortConfigProtocolSCTP) {
					return fmt.Errorf("invalid protocol value %s", value)
				}

				pConfig.Protocol = swarm.PortConfigProtocol(value)
			case portOptMode:
				if value != string(swarm.PortConfigPublishModeIngress) && value != string(swarm.PortConfigPublishModeHost) {
					return fmt.Errorf("invalid publish mode value %s", value)
				}

				pConfig.PublishMode = swarm.PortConfigPublishMode(value)
			case portOptTargetPort:
				tPort, err := strconv.ParseUint(value, 10, 16)
				if err != nil {
					return err
				}

				pConfig.TargetPort = uint32(tPort)
			case portOptPublishedPort:
				pPort, err := strconv.ParseUint(value, 10, 16)
				if err != nil {
					return err
				}

				pConfig.PublishedPort = uint32(pPort)
			default:
				return fmt.Errorf("invalid field key %s", key)
			}
		}

		if pConfig.TargetPort == 0 {
			return fmt.Errorf("missing mandatory field %q", portOptTargetPort)
		}

		if pConfig.PublishMode == "" {
			pConfig.PublishMode = swarm.PortConfigPublishModeIngress
		}

		if pConfig.Protocol == "" {
			pConfig.Protocol = swarm.PortConfigProtocolTCP
		}

		p.ports = append(p.ports, pConfig)
	} else {
		// short syntax
		portConfigs := []swarm.PortConfig{}
		ports, portBindingMap, err := nat.ParsePortSpecs([]string{value})
		if err != nil {
			return err
		}
		for _, portBindings := range portBindingMap {
			for _, portBinding := range portBindings {
				if portBinding.HostIP != "" {
					return fmt.Errorf("hostip is not supported")
				}
			}
		}

		for port := range ports {
			portConfig, err := ConvertPortToPortConfig(port, portBindingMap)
			if err != nil {
				return err
			}
			portConfigs = append(portConfigs, portConfig...)
		}
		p.ports = append(p.ports, portConfigs...)
	}
	return nil
}

// Set a new port value
// nolint: gocyclo


func IsDataLoss(err error) bool {
	_, ok := getImplementer(err).(ErrDataLoss)
	return ok
}

// IsDataLoss returns if the passed in error is an ErrDataLoss


func Marshal(v interface{}) ([]byte, error) {
	return marshal(v, false)
}

// Marshal returns the JSON encoding of v.
//
// Marshal traverses the value v recursively.
// If an encountered value implements the Marshaler interface
// and is not a nil pointer, Marshal calls its MarshalJSON method
// to produce JSON. If no MarshalJSON method is present but the
// value implements encoding.TextMarshaler instead, Marshal calls
// its MarshalText method.
// The nil pointer exception is not strictly necessary
// but mimics a similar, necessary exception in the behavior of
// UnmarshalJSON.
//
// Otherwise, Marshal uses the following type-dependent default encodings:
//
// Boolean values encode as JSON booleans.
//
// Floating point, integer, and Number values encode as JSON numbers.
//
// String values encode as JSON strings coerced to valid UTF-8,
// replacing invalid bytes with the Unicode replacement rune.
// The angle brackets "<" and ">" are escaped to "\u003c" and "\u003e"
// to keep some browsers from misinterpreting JSON output as HTML.
// Ampersand "&" is also escaped to "\u0026" for the same reason.
//
// Array and slice values encode as JSON arrays, except that
// []byte encodes as a base64-encoded string, and a nil slice
// encodes as the null JSON object.
//
// Struct values encode as JSON objects. Each exported struct field
// becomes a member of the object unless
//   - the field's tag is "-", or
//   - the field is empty and its tag specifies the "omitempty" option.
// The empty values are false, 0, any
// nil pointer or interface value, and any array, slice, map, or string of
// length zero. The object's default key string is the struct field name
// but can be specified in the struct field's tag value. The "json" key in
// the struct field's tag value is the key name, followed by an optional comma
// and options. Examples:
//
//   // Field is ignored by this package.
//   Field int `json:"-"`
//
//   // Field appears in JSON as key "myName".
//   Field int `json:"myName"`
//
//   // Field appears in JSON as key "myName" and
//   // the field is omitted from the object if its value is empty,
//   // as defined above.
//   Field int `json:"myName,omitempty"`
//
//   // Field appears in JSON as key "Field" (the default), but
//   // the field is skipped if empty.
//   // Note the leading comma.
//   Field int `json:",omitempty"`
//
// The "string" option signals that a field is stored as JSON inside a
// JSON-encoded string. It applies only to fields of string, floating point,
// integer, or boolean types. This extra level of encoding is sometimes used
// when communicating with JavaScript programs:
//
//    Int64String int64 `json:",string"`
//
// The key name will be used if it's a non-empty string consisting of
// only Unicode letters, digits, dollar signs, percent signs, hyphens,
// underscores and slashes.
//
// Anonymous struct fields are usually marshaled as if their inner exported fields
// were fields in the outer struct, subject to the usual Go visibility rules amended
// as described in the next paragraph.
// An anonymous struct field with a name given in its JSON tag is treated as
// having that name, rather than being anonymous.
// An anonymous struct field of interface type is treated the same as having
// that type as its name, rather than being anonymous.
//
// The Go visibility rules for struct fields are amended for JSON when
// deciding which field to marshal or unmarshal. If there are
// multiple fields at the same level, and that level is the least
// nested (and would therefore be the nesting level selected by the
// usual Go rules), the following extra rules apply:
//
// 1) Of those fields, if any are JSON-tagged, only tagged fields are considered,
// even if there are multiple untagged fields that would otherwise conflict.
// 2) If there is exactly one field (tagged or not according to the first rule), that is selected.
// 3) Otherwise there are multiple fields, and all are ignored; no error occurs.
//
// Handling of anonymous struct fields is new in Go 1.1.
// Prior to Go 1.1, anonymous struct fields were ignored. To force ignoring of
// an anonymous struct field in both current and earlier versions, give the field
// a JSON tag of "-".
//
// Map values encode as JSON objects.
// The map's key type must be string; the map keys are used as JSON object
// keys, subject to the UTF-8 coercion described for string values above.
//
// Pointer values encode as the value pointed to.
// A nil pointer encodes as the null JSON object.
//
// Interface values encode as the value contained in the interface.
// A nil interface value encodes as the null JSON object.
//
// Channel, complex, and function values cannot be encoded in JSON.
// Attempting to encode such a value causes Marshal to return
// an UnsupportedTypeError.
//
// JSON cannot represent cyclic data structures and Marshal does not
// handle them.  Passing cyclic structures to Marshal will result in
// an infinite recursion.
//


func (c Continue) RandString() string {
	return randString(c.Rand)
}

// RandString makes a random string up to 20 characters long. The returned string
// may include a variety of (valid) UTF-8 encodings.


func FieldMaskFromRequestBody(r io.Reader, msg proto.Message) (*field_mask.FieldMask, error) {
	fm := &field_mask.FieldMask{}
	var root interface{}

	if err := json.NewDecoder(r).Decode(&root); err != nil {
		if err == io.EOF {
			return fm, nil
		}
		return nil, err
	}

	queue := []fieldMaskPathItem{{node: root, msg: msg.ProtoReflect()}}
	for len(queue) > 0 {
		// dequeue an item
		item := queue[0]
		queue = queue[1:]

		m, ok := item.node.(map[string]interface{})
		switch {
		case ok:
			// if the item is an object, then enqueue all of its children
			for k, v := range m {
				if item.msg == nil {
					return nil, errors.New("JSON structure did not match request type")
				}

				fd := getFieldByName(item.msg.Descriptor().Fields(), k)
				if fd == nil {
					return nil, fmt.Errorf("could not find field %q in %q", k, item.msg.Descriptor().FullName())
				}

				if isDynamicProtoMessage(fd.Message()) {
					for _, p := range buildPathsBlindly(string(fd.FullName().Name()), v) {
						newPath := p
						if item.path != "" {
							newPath = item.path + "." + newPath
						}
						queue = append(queue, fieldMaskPathItem{path: newPath})
					}
					continue
				}

				if isProtobufAnyMessage(fd.Message()) && !fd.IsList() {
					_, hasTypeField := v.(map[string]interface{})["@type"]
					if hasTypeField {
						queue = append(queue, fieldMaskPathItem{path: k})
						continue
					} else {
						return nil, fmt.Errorf("could not find field @type in %q in message %q", k, item.msg.Descriptor().FullName())
					}

				}

				child := fieldMaskPathItem{
					node: v,
				}
				if item.path == "" {
					child.path = string(fd.FullName().Name())
				} else {
					child.path = item.path + "." + string(fd.FullName().Name())
				}

				switch {
				case fd.IsList(), fd.IsMap():
					// As per: https://github.com/protocolbuffers/protobuf/blob/master/src/google/protobuf/field_mask.proto#L85-L86
					// Do not recurse into repeated fields. The repeated field goes on the end of the path and we stop.
					fm.Paths = append(fm.Paths, child.path)
				case fd.Message() != nil:
					child.msg = item.msg.Get(fd).Message()
					fallthrough
				default:
					queue = append(queue, child)
				}
			}
		case len(item.path) > 0:
			// otherwise, it's a leaf node so print its path
			fm.Paths = append(fm.Paths, item.path)
		}
	}

	// Sort for deterministic output in the presence
	// of repeated fields.
	sort.Strings(fm.Paths)

	return fm, nil
}

// FieldMaskFromRequestBody creates a FieldMask printing all complete paths from the JSON body.


func (s *set) indexNL(key Key) int {
	for i, k := range s.keys {
		if k == key {
			return i
		}
	}
	return -1
}

// indexNL is Index(), but without the locking


func BiDirectional() InitOption {
	return func(g *Generator) { g.workflow = &onceWorkflow{workflow: &standardWorkflow{BiDi: true}} }
}

// BiDirectional instructs the Generator to build the AST graph in both
// directions (ie, accessing dependents of an entity, not just dependencies).


func DebugFn(fn LogFunction) {
	std.DebugFn(fn)
}

// DebugFn logs a message from a func at level Debug on the standard logger.


func Float64SliceVarP(p *[]float64, name, shorthand string, value []float64, usage string) {
	CommandLine.VarP(newFloat64SliceValue(value, p), name, shorthand, usage)
}

// Float64SliceVarP is like Float64SliceVar, but accepts a shorthand letter that can be used after a single dash.


func IPMaskVar(p *net.IPMask, name string, value net.IPMask, usage string) {
	CommandLine.VarP(newIPMaskValue(value, p), name, "", usage)
}

// IPMaskVar defines an net.IPMask flag with specified name, default value, and usage string.
// The argument p points to an net.IPMask variable in which to store the value of the flag.


func filterSet(kvs []KeyValue, filter Filter) (Set, []KeyValue) {
	var excluded []KeyValue

	// Move attributes that do not match the filter so they're adjacent before
	// calling computeDistinct().
	distinctPosition := len(kvs)

	// Swap indistinct keys forward and distinct keys toward the
	// end of the slice.
	offset := len(kvs) - 1
	for ; offset >= 0; offset-- {
		if filter(kvs[offset]) {
			distinctPosition--
			kvs[offset], kvs[distinctPosition] = kvs[distinctPosition], kvs[offset]
			continue
		}
	}
	excluded = kvs[:distinctPosition]

	return Set{
		equivalent: computeDistinct(kvs[distinctPosition:]),
	}, excluded
}

// filterSet reorders kvs so that included keys are contiguous at the end of
// the slice, while excluded keys precede the included keys.


func ptracePtr(request int, pid int, addr unsafe.Pointer, data int) (err error) {
	_, _, e1 := Syscall6(SYS_PTRACE, uintptr(request), uintptr(pid), uintptr(addr), uintptr(data), 0, 0)
	if e1 != 0 {
		err = errnoErr(e1)
	}
	return
}

// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT


func pread(fd int, p []byte, offset int64) (n int, err error) {
	var _p0 unsafe.Pointer
	if len(p) > 0 {
		_p0 = unsafe.Pointer(&p[0])
	} else {
		_p0 = unsafe.Pointer(&_zero)
	}
	r0, _, e1 := Syscall6(SYS_PREAD, uintptr(fd), uintptr(_p0), uintptr(len(p)), 0, uintptr(offset), 0)
	n = int(r0)
	if e1 != 0 {
		err = errnoErr(e1)
	}
	return
}


func Getrlimit(resource int, rlim *Rlimit) (err error) {
	_, _, e1 := RawSyscall(SYS_GETRLIMIT, uintptr(resource), uintptr(unsafe.Pointer(rlim)), 0)
	if e1 != 0 {
		err = errnoErr(e1)
	}
	return
}


func pread(fd int, p []byte, offset int64) (n int, err error) {
	var _p0 *byte
	if len(p) > 0 {
		_p0 = &p[0]
	}
	r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procpread)), 4, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(len(p)), uintptr(offset), 0, 0)
	n = int(r0)
	if e1 != 0 {
		err = errnoErr(e1)
	}
	return
}


func (s *EnvSettings) Namespace() string {
	if ns, _, err := s.config.ToRawKubeConfigLoader().Namespace(); err == nil {
		return ns
	}
	return "default"
}

// Namespace gets the namespace from the configuration


func Resource(resource string) schema.GroupResource {
	return SchemeGroupVersion.WithResource(resource).GroupResource()
}

// Resource takes an unqualified resource and returns a Group qualified GroupResource


func RegisterDefaults(scheme *runtime.Scheme) error {
	scheme.AddTypeDefaultingFunc(&CustomResourceDefinition{}, func(obj interface{}) { SetObjectDefaults_CustomResourceDefinition(obj.(*CustomResourceDefinition)) })
	scheme.AddTypeDefaultingFunc(&CustomResourceDefinitionList{}, func(obj interface{}) {
		SetObjectDefaults_CustomResourceDefinitionList(obj.(*CustomResourceDefinitionList))
	})
	return nil
}

// RegisterDefaults adds defaulters functions to the given scheme.
// Public to allow building arbitrary schemes.
// All generated defaulters are covering - they call all nested defaulters.


func (r *Refable) UnmarshalJSON(d []byte) error {
	return json.Unmarshal(d, &r.Ref)
}

// UnmarshalJSON unmarshalss the ref from json


func (c *paramVerifyingSchema) ValidateBytes(data []byte) error {
	obj, err := schemavalidation.Parse(data)
	if err != nil {
		return err
	}

	gvk, errs := schemavalidation.GetObjectKind(obj)
	if errs != nil {
		return utilerrors.NewAggregate(errs)
	}

	err = c.verifier.HasSupport(gvk)
	if resource.IsParamUnsupportedError(err) {
		switch c.directive {
		case metav1.FieldValidationStrict:
			return c.schema.ValidateBytes(data)
		case metav1.FieldValidationWarn:
			klog.Warningf("cannot perform warn validation if server-side field validation is unsupported, skipping validation")
		default:
			// can't be reached
			klog.Warningf("unexpected field validation directive: %s, skipping validation", c.directive)
		}
		return nil
	}
	return err
}

// ValidateBytes validates bytes per a ParamVerifyingSchema


func GetNode(root *yaml.Node, path ...string) (*yaml.Node, bool, error) {
	resNode, restPath, err := asCloseAsPossible(root, path...)
	if err != nil {
		return nil, false, err
	}
	// more path means the node didn't exist
	if len(restPath) != 0 {
		return nil, false, nil
	}
	return resNode, true, nil
}

// GetNode gets the node at the given path in the given sequence of mapping
// nodes, or, if it doesn't exist, returning false.


func main() {
	x := Xenia{
		Host:    "localhost:8000",
		Timeout: time.Second,
	}

	p := Pillar{
		Host:    "localhost:9000",
		Timeout: time.Second,
	}

	if err := Copy(&x, &p, 3); err != io.EOF {
		fmt.Println(err)
	}
}


func (s *Server) Wait() error {

	// ΠΡΟΣΠΟΙΗΘΕΙΤΕ ΟΤΙ ΥΠΑΡΧΕΙ ΣΥΓΚΕΚΡΙΜΕΝΗ ΥΛΟΠΟΙΗΣΗ.
	return nil
}

// Η Wait αποτρέπει τον server να δεχτεί νέες συνδέσεις.


func sendNotification(n notifier) {
	n.notify()
}

// sendNotification accepts values that implement the notifier
// interface and sends notifications.


func (v PreciseVector) SmallestComponent() Axis {
	t := v.Abs()

	if t.X.Cmp(t.Y) < 0 {
		if t.X.Cmp(t.Z) < 0 {
			return XAxis
		}
		return ZAxis
	}
	if t.Y.Cmp(t.Z) < 0 {
		return YAxis
	}
	return ZAxis
}

// SmallestComponent returns the axis that represents the smallest component in this vector.


func CheckPath(path string) (err error) {
	defer func() {
		if err != nil {
			err = &InvalidPathError{Kind: "module", Path: path, Err: err}
		}
	}()

	if err := checkPath(path, modulePath); err != nil {
		return err
	}
	i := strings.Index(path, "/")
	if i < 0 {
		i = len(path)
	}
	if i == 0 {
		return fmt.Errorf("leading slash")
	}
	if !strings.Contains(path[:i], ".") {
		return fmt.Errorf("missing dot in first path element")
	}
	if path[0] == '-' {
		return fmt.Errorf("leading dash in first path element")
	}
	for _, r := range path[:i] {
		if !firstPathOK(r) {
			return fmt.Errorf("invalid char %q in first path element", r)
		}
	}
	if _, _, ok := SplitPathVersion(path); !ok {
		return fmt.Errorf("invalid version")
	}
	return nil
}

// CheckPath checks that a module path is valid.
// A valid module path is a valid import path, as checked by [CheckImportPath],
// with three additional constraints.
// First, the leading path element (up to the first slash, if any),
// by convention a domain name, must contain only lower-case ASCII letters,
// ASCII digits, dots (U+002E), and dashes (U+002D);
// it must contain at least one dot and cannot start with a dash.
// Second, for a final path element of the form /vN, where N looks numeric
// (ASCII digits and dots) must not begin with a leading zero, must not be /v1,
// and must not contain any dots. For paths beginning with "gopkg.in/",
// this second requirement is replaced by a requirement that the path
// follow the gopkg.in server's conventions.
// Third, no path element may begin with a dot.


func accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) {
	r0, _, e1 := Syscall(SYS_ACCEPT, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)))
	fd = int(r0)
	if e1 != 0 {
		err = errnoErr(e1)
	}
	return
}


func Adjtime(delta *Timeval, olddelta *Timeval) (err error) {
	_, _, e1 := Syscall(SYS_ADJTIME, uintptr(unsafe.Pointer(delta)), uintptr(unsafe.Pointer(olddelta)), 0)
	if e1 != 0 {
		err = errnoErr(e1)
	}
	return
}


func Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) {
	var _p0 *byte
	_p0, err = BytePtrFromString(path)
	if err != nil {
		return
	}
	_, _, e1 := Syscall6(SYS_FCHMODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0)
	if e1 != 0 {
		err = errnoErr(e1)
	}
	return
}


func Setrtable(rtable int) (err error) {
	_, _, e1 := syscall_rawSyscall(libc_setrtable_trampoline_addr, uintptr(rtable), 0, 0)
	if e1 != 0 {
		err = errnoErr(e1)
	}
	return
}

//go:cgo_import_dynamic libc_setresuid setresuid "libc.so"
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT


func Faccessat(dirfd int, path string, mode uint32, flags int) (err error) {
	var _p0 *byte
	_p0, err = BytePtrFromString(path)
	if err != nil {
		return
	}
	_, _, e1 := syscall_syscall6(libc_faccessat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0)
	if e1 != 0 {
		err = errnoErr(e1)
	}
	return
}

//go:cgo_import_dynamic libc_exit exit "/usr/lib/libSystem.B.dylib"
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT


func consumeFixed32Ptr(b []byte, p pointer, wtyp protowire.Type, f *coderFieldInfo, opts unmarshalOptions) (out unmarshalOutput, err error) {
	if wtyp != protowire.Fixed32Type {
		return out, errUnknown
	}
	v, n := protowire.ConsumeFixed32(b)
	if n < 0 {
		return out, errDecode
	}
	vp := p.Uint32Ptr()
	if *vp == nil {
		*vp = new(uint32)
	}
	**vp = v
	out.n = n
	return out, nil
}

// consumeFixed32Ptr wire decodes a *uint32 pointer as a Fixed32.


func (_ *RESTProvider) ReregisterEntity(
	_ context.Context, _ minderv1.Entity, _ *properties.Properties,
) error {
	// TODO: implement
	return nil
}

// ReregisterEntity implements the Provider interface


func GetNiceStatus(code codes.Code) *NiceStatus {
	s := &NiceStatus{}
	return s.SetCode(code)
}

// GetNiceStatus get a nice status from the code.


func (p *PPU) nameTableIdx(addr uint16) uint {
	var (
		idx  = (addr - 0x2000) / 0x0400
		mode = p.cart.MirrorMode()
	)

	switch mode {
	case ines.MirrorHorizontal:
		switch idx {
		case 0, 1:
			return 0
		default:
			return 1
		}
	case ines.MirrorVertical:
		switch idx {
		case 0, 2:
			return 0
		default:
			return 1
		}
	case ines.MirrorSingle0:
		return 0
	case ines.MirrorSingle1:
		return 1
	default:
		panic(fmt.Sprintf("invalid mirroring mode: %d", mode))
	}
}

// nameTableIdx returns the index of the nametable (0 or 1) for the given vram
// address, based on the cartridge’s mirroring mode.


func TestSystem(t *testing.T, makeSystem MakeSystem) {
	t.Run("file", file.runFunc(makeSystem))
	t.Run("proc", proc.runFunc(makeSystem))
	t.Run("poll", poll.runFunc(makeSystem))
	t.Run("socket", socket.runFunc(makeSystem))
}

// TestSystem is a test suite which validates the behavior of wasi.System
// implementations.


func (c *constraints) AddReservation(p peer.ID, a ma.Multiaddr) error {
	c.mutex.Lock()

	now := time.Now()
	c.cleanup(now)

	if len(c.total) >= c.rc.MaxReservations {
		c.mutex.Unlock()
		return errTooManyReservations
	}

	ip, err := manet.ToIP(a)
	if err != nil {
		c.mutex.Unlock()
		return errors.New("no IP address associated with peer")
	}

	peerReservations := c.peers[p]
	if len(peerReservations) >= c.rc.MaxReservationsPerPeer {
		c.mutex.Unlock()
		return errTooManyReservationsForPeer
	}

	ipReservations := c.ips[ip.String()]
	if len(ipReservations) >= c.rc.MaxReservationsPerIP {
		c.mutex.Unlock()
		return errTooManyReservationsForIP
	}

	var asnReservations []time.Time
	var asn uint32
	if ip.To4() == nil {
		asn = asnutil.AsnForIPv6(ip)
		if asn != 0 {
			asnReservations = c.asns[asn]
			if len(asnReservations) >= c.rc.MaxReservationsPerASN {
				c.mutex.Unlock()
				return errTooManyReservationsForASN
			}
		}
	}

	expiry := now.Add(validity)
	c.total = append(c.total, expiry)

	peerReservations = append(peerReservations, expiry)
	c.peers[p] = peerReservations

	ipReservations = append(ipReservations, expiry)
	c.ips[ip.String()] = ipReservations

	if asn != 0 {
		asnReservations = append(asnReservations, expiry)
		c.asns[asn] = asnReservations
	}
	c.mutex.Unlock()
	return nil
}

// AddReservation adds a reservation for a given peer with a given multiaddr.
// If adding this reservation violates IP constraints, an error is returned.


func (set *IdSet) Delete(atom Atom) bool {
	switch a := atom.(type) {
	case *Vertex:
		if _, exists := set.atoms[a.GetID()]; exists {
			delete(set.atoms, a.GetID())
			return true
		}
	case *Hyperedge:
		if _, exists := set.atoms[a.GetID()]; exists {
			delete(set.atoms, a.GetID())
			return true
		}
	}
	return false
}

// Delete removes an atom from the IdSet and returns true if the atom was
// present.


func WithReason(ctx context.Context, reason Reason) context.Context {
	info := infoFromCtx(ctx)
	info.reason = reason
	return withInfo(ctx, info)
}

// WithReason creates a context that has an associated Reason (which ends up in
// traces created under that context).